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
|
|---|---|---|---|---|---|---|---|---|---|
bcf0a9923c8480ef57bbc83e6357c6ca1b3d912c
|
frontend/device/screen.lua
|
frontend/device/screen.lua
|
local Blitbuffer = require("ffi/blitbuffer")
local einkfb = require("ffi/framebuffer")
local Geom = require("ui/geometry")
local util = require("ffi/util")
local DEBUG = require("dbg")
--[[
Codes for rotation modes:
1 for no rotation,
2 for landscape with bottom on the right side of screen, etc.
2
+--------------+
| +----------+ |
| | | |
| | Freedom! | |
| | | |
| | | |
3 | | | | 1
| | | |
| | | |
| +----------+ |
| |
| |
+--------------+
0
--]]
local Screen = {
cur_rotation_mode = 0,
native_rotation_mode = nil,
blitbuffer_rotation_mode = 0,
bb = nil,
saved_bb = nil,
screen_size = Geom:new(),
viewport = nil,
fb = einkfb.open("/dev/fb0"),
-- will be set upon loading by Device class:
device = nil,
}
function Screen:new(o)
local o = o or {}
setmetatable(o, self)
self.__index = self
if o.init then o:init() end
return o
end
function Screen:init()
self.bb = self.fb.bb
self.blitbuffer_rotation_mode = self.bb:getRotation()
-- asking the framebuffer for orientation is error prone,
-- so we do this simple heuristic (for now)
self.screen_size.w = self.bb:getWidth()
self.screen_size.h = self.bb:getHeight()
if self.screen_size.w > self.screen_size.h then
self.native_rotation_mode = 1
self.screen_size.w, self.screen_size.h = self.screen_size.h, self.screen_size.w
else
self.native_rotation_mode = 0
end
self.cur_rotation_mode = self.native_rotation_mode
end
--[[
set a rectangle that represents the area of the screen we are working on
--]]
function Screen:setViewport(viewport)
self.viewport = self.screen_size:intersect(viewport)
self.bb = self.fb.bb:viewport(
self.viewport.x, self.viewport.y,
self.viewport.w, self.viewport.h)
end
function Screen:refresh(refresh_type, waveform_mode, wait_for_marker, x, y, w, h)
if self.viewport and x and y then
-- adapt to viewport, depending on rotation
if self.cur_rotation_mode == 0 then
-- (0,0) is at top left of screen
x = x + self.viewport.x
y = y + self.viewport.y
elseif self.cur_rotation_mode == 1 then
-- (0,0) is at bottom left of screen
x = x + (self.fb.bb:getWidth()-self.viewport.h)
y = y + self.viewport.x
elseif self.cur_rotation_mode == 2 then
-- (0,0) is at bottom right of screen
x = x + (self.fb.bb:getWidth()-self.viewport.w)
y = y + (self.fb.bb:getHeight()-self.viewport.h)
else
-- (0,0) is at top right of screen
x = x + self.viewport.y
y = y + (self.fb.bb:getHeight()-self.viewport.w)
end
end
self.fb:refresh(refresh_type, waveform_mode, wait_for_marker, x, y, w, h)
end
function Screen:getSize()
return Geom:new{w = self.bb:getWidth(), h = self.bb:getHeight()}
end
function Screen:getWidth()
return self.bb:getWidth()
end
function Screen:getScreenWidth()
return self.screen_size.w
end
function Screen:getScreenHeight()
return self.screen_size.h
end
function Screen:getHeight()
return self.bb:getHeight()
end
function Screen:getDPI()
if self.dpi == nil then
self.dpi = G_reader_settings:readSetting("screen_dpi")
end
if self.dpi == nil then
self.dpi = self.device.display_dpi
end
if self.dpi == nil then
self.dpi = 160
end
return self.dpi
end
function Screen:setDPI(dpi)
G_reader_settings:saveSetting("screen_dpi", dpi)
end
function Screen:scaleByDPI(px)
-- scaled positive px should also be positive
return math.ceil(px * self:getDPI()/167)
end
function Screen:getRotationMode()
return self.cur_rotation_mode
end
function Screen:getScreenMode()
if self:getWidth() > self:getHeight() then
return "landscape"
else
return "portrait"
end
end
function Screen:setRotationMode(mode)
self.bb:rotateAbsolute(-90 * (mode - self.native_rotation_mode - self.blitbuffer_rotation_mode))
if self.viewport then
self.fb.bb:setRotation(self.bb:getRotation())
end
self.cur_rotation_mode = mode
end
function Screen:setScreenMode(mode)
if mode == "portrait" then
if self.cur_rotation_mode ~= 0 then
self:setRotationMode(0)
end
elseif mode == "landscape" then
if self.cur_rotation_mode == 0 or self.cur_rotation_mode == 2 then
self:setRotationMode(DLANDSCAPE_CLOCKWISE_ROTATION and 1 or 3)
elseif self.cur_rotation_mode == 1 or self.cur_rotation_mode == 3 then
self:setRotationMode((self.cur_rotation_mode + 2) % 4)
end
end
end
function Screen:toggleNightMode()
self.bb:invert()
if self.viewport then
-- invert and blank out the full framebuffer when we are working on a viewport
self.fb.bb:invert()
self.fb.bb:fill(Blitbuffer.COLOR_WHITE)
end
end
function Screen:saveCurrentBB()
if self.saved_bb then self.saved_bb:free() end
self.saved_bb = self.bb:copy()
end
function Screen:restoreFromSavedBB()
if self.saved_bb then
self.bb:blitFullFrom(self.saved_bb)
-- free data
self.saved_bb:free()
self.saved_bb = nil
end
end
function Screen:shot(filename)
DEBUG("write PNG file", filename)
self.bb:writePNG(filename)
end
function Screen:close()
DEBUG("close screen framebuffer")
self.fb:close()
end
return Screen
|
local Blitbuffer = require("ffi/blitbuffer")
local einkfb = require("ffi/framebuffer")
local Geom = require("ui/geometry")
local util = require("ffi/util")
local DEBUG = require("dbg")
--[[
Codes for rotation modes:
1 for no rotation,
2 for landscape with bottom on the right side of screen, etc.
2
+--------------+
| +----------+ |
| | | |
| | Freedom! | |
| | | |
| | | |
3 | | | | 1
| | | |
| | | |
| +----------+ |
| |
| |
+--------------+
0
--]]
local Screen = {
cur_rotation_mode = 0,
native_rotation_mode = nil,
blitbuffer_rotation_mode = 0,
bb = nil,
saved_bb = nil,
screen_size = Geom:new(),
viewport = nil,
fb = einkfb.open("/dev/fb0"),
-- will be set upon loading by Device class:
device = nil,
}
function Screen:new(o)
local o = o or {}
setmetatable(o, self)
self.__index = self
if o.init then o:init() end
return o
end
function Screen:init()
self.bb = self.fb.bb
self.blitbuffer_rotation_mode = self.bb:getRotation()
-- asking the framebuffer for orientation is error prone,
-- so we do this simple heuristic (for now)
self.screen_size.w = self.bb:getWidth()
self.screen_size.h = self.bb:getHeight()
if self.screen_size.w > self.screen_size.h then
self.native_rotation_mode = 1
self.screen_size.w, self.screen_size.h = self.screen_size.h, self.screen_size.w
else
self.native_rotation_mode = 0
end
self.cur_rotation_mode = self.native_rotation_mode
end
--[[
set a rectangle that represents the area of the screen we are working on
--]]
function Screen:setViewport(viewport)
self.viewport = self.screen_size:intersect(viewport)
self.bb = self.fb.bb:viewport(
self.viewport.x, self.viewport.y,
self.viewport.w, self.viewport.h)
end
function Screen:refresh(refresh_type, waveform_mode, wait_for_marker, x, y, w, h)
if self.viewport and x and y then
--[[
we need to adapt the coordinates when we have a viewport.
this adaptation depends on the rotation:
0,0 fb.w
+---+---------------------------+---+
| |v.y v.y| |
|v.x| |vx2|
+---+---------------------------+---+
| | v.w | |
| | | |
| | | |
| |v.h (viewport) | |
| | | | fb.h
| | | |
| | | |
| | | |
+---+---------------------------+---+
|v.x| |vx2|
| |vy2 vy2| |
+---+---------------------------+---+
The viewport offset v.y/v.x only applies when rotation is 0 degrees.
For other rotations (0,0 is in one of the other edges), we need to
recalculate the offsets.
--]]
local vx2 = self.screen_size.w - (self.viewport.x + self.viewport.w)
local vy2 = self.screen_size.h - (self.viewport.y + self.viewport.h)
if self.cur_rotation_mode == 0 then
-- (0,0) is at top left of screen
x = x + self.viewport.x
y = y + self.viewport.y
elseif self.cur_rotation_mode == 1 then
-- (0,0) is at bottom left of screen
x = x + vy2
y = y + self.viewport.x
elseif self.cur_rotation_mode == 2 then
-- (0,0) is at bottom right of screen
x = x + vx2
y = y + vy2
else
-- (0,0) is at top right of screen
x = x + self.viewport.y
y = y + vx2
end
end
self.fb:refresh(refresh_type, waveform_mode, wait_for_marker, x, y, w, h)
end
function Screen:getSize()
return Geom:new{w = self.bb:getWidth(), h = self.bb:getHeight()}
end
function Screen:getWidth()
return self.bb:getWidth()
end
function Screen:getScreenWidth()
return self.screen_size.w
end
function Screen:getScreenHeight()
return self.screen_size.h
end
function Screen:getHeight()
return self.bb:getHeight()
end
function Screen:getDPI()
if self.dpi == nil then
self.dpi = G_reader_settings:readSetting("screen_dpi")
end
if self.dpi == nil then
self.dpi = self.device.display_dpi
end
if self.dpi == nil then
self.dpi = 160
end
return self.dpi
end
function Screen:setDPI(dpi)
G_reader_settings:saveSetting("screen_dpi", dpi)
end
function Screen:scaleByDPI(px)
-- scaled positive px should also be positive
return math.ceil(px * self:getDPI()/167)
end
function Screen:getRotationMode()
return self.cur_rotation_mode
end
function Screen:getScreenMode()
if self:getWidth() > self:getHeight() then
return "landscape"
else
return "portrait"
end
end
function Screen:setRotationMode(mode)
self.bb:rotateAbsolute(-90 * (mode - self.native_rotation_mode - self.blitbuffer_rotation_mode))
if self.viewport then
self.fb.bb:setRotation(self.bb:getRotation())
end
self.cur_rotation_mode = mode
end
function Screen:setScreenMode(mode)
if mode == "portrait" then
if self.cur_rotation_mode ~= 0 then
self:setRotationMode(0)
end
elseif mode == "landscape" then
if self.cur_rotation_mode == 0 or self.cur_rotation_mode == 2 then
self:setRotationMode(DLANDSCAPE_CLOCKWISE_ROTATION and 1 or 3)
elseif self.cur_rotation_mode == 1 or self.cur_rotation_mode == 3 then
self:setRotationMode((self.cur_rotation_mode + 2) % 4)
end
end
end
function Screen:toggleNightMode()
self.bb:invert()
if self.viewport then
-- invert and blank out the full framebuffer when we are working on a viewport
self.fb.bb:invert()
self.fb.bb:fill(Blitbuffer.COLOR_WHITE)
end
end
function Screen:saveCurrentBB()
if self.saved_bb then self.saved_bb:free() end
self.saved_bb = self.bb:copy()
end
function Screen:restoreFromSavedBB()
if self.saved_bb then
self.bb:blitFullFrom(self.saved_bb)
-- free data
self.saved_bb:free()
self.saved_bb = nil
end
end
function Screen:shot(filename)
DEBUG("write PNG file", filename)
self.bb:writePNG(filename)
end
function Screen:close()
DEBUG("close screen framebuffer")
self.fb:close()
end
return Screen
|
(really?) fix refresh viewport calculations
|
(really?) fix refresh viewport calculations
This adds more documentation about the viewport offset calculations
for refreshing rotated viewports.
The old behaviour also was (still) buggy, even after the latest round
of fixes. Now, the offsets when rotated are hopefully calculated correct.
|
Lua
|
agpl-3.0
|
ashang/koreader,Markismus/koreader,NiLuJe/koreader,poire-z/koreader,NickSavage/koreader,Hzj-jie/koreader,Frenzie/koreader,houqp/koreader,robert00s/koreader,mwoz123/koreader,koreader/koreader,apletnev/koreader,lgeek/koreader,pazos/koreader,mihailim/koreader,Frenzie/koreader,koreader/koreader,chrox/koreader,frankyifei/koreader,poire-z/koreader,ashhher3/koreader,NiLuJe/koreader,chihyang/koreader,noname007/koreader
|
15ce30b1c9536d522bcda35eed4b6ee0dbbdb2b2
|
lib/switchboard_modules/lua_script_debugger/premade_scripts/11b_user_ram_fifo.lua
|
lib/switchboard_modules/lua_script_debugger/premade_scripts/11b_user_ram_fifo.lua
|
--[[
Name: 11b_user_ram_fifo.lua
Desc: Example showing how to use USER RAM FIFO buffers to transfer an array
of data to/from an external computer
Note: This system is considered an advanced topic. Simple data transfer
to/from Lua is easiest with USER_RAM, not a FIFO. These FIFO buffers
are good for users who want to send an array of information in
sequence to/from a Lua script. Usually 2 buffers are used for each
endpoint, one buffer dedicated for each communication direction (read
and write). A host may write new data for the Lua script into FIFO0,
then once the script reads the data out of that buffer, it responds
by writing data into FIFO1, and then the host may read the data out
of FIFO1
See the datasheet for more on USER RAM FIFO buffers:
http://labjack.com/support/datasheets/t7/scripting
This example requires firmware 1.0282 (T7) or 1.0023 (T4)
--]]
print("Transfer an array of ordered information to/from an external computer using a FIFO buffer.")
-- To get started, simply run the script.
-- Once the script is running, open up the Register Matrix, and search USER_RAM_FIFO1_DATA_F32
-- add this USER_RAM_FIFO1_DATA_F32 register to the active watch area, and
-- view each element coming out in sequence at the update rate of the software.
local f32out= {}
f32out[1] = 10.0
f32out[2] = 20.1
f32out[3] = 30.2
f32out[4] = 40.3
f32out[5] = 50.4
local f32in = {}
local numvalsfio0 = 5
local numvalsfio1 = 5
local bytesperval = 4
local fifo0bytes = numvalsfio0*bytesperval
local fifo1bytes = numvalsfio1*bytesperval
-- Allocate 20 bytes for FIFO0 by writing to USER_RAM_FIFO0_NUM_BYTES_IN_FIFO
MB.writeName("USER_RAM_FIFO0_NUM_BYTES_IN_FIFO", fifo0bytes)
-- Allocate 20 bytes for FIFO1 by writing to USER_RAM_FIFO1_NUM_BYTES_IN_FIFO
MB.writeName("USER_RAM_FIFO1_NUM_BYTES_IN_FIFO", fifo1bytes)
-- Configure an interval of 2000ms
LJ.IntervalConfig(0, 2000)
-- Run the program in an infinite loop
while true do
-- If an interval is done
if LJ.CheckInterval(0) then
-- Write to FIFO0 for the host computer to access
for i=1, numvalsfio0 do
local outval = f32out[i]
currentbytesfifo0 = MB.readName("USER_RAM_FIFO0_ALLOCATE_NUM_BYTES")
-- If there are less bytes in FIFO0 than we allocated for, send a new
-- array of size numvalsfio0 to the host
if (currentbytesfifo0 < fifo0bytes) then
MB.writeName("USER_RAM_FIFO0_DATA_F32", outval)
print ("Next Value FIFO0: ", outval)
else
print ("FIFO0 buffer is full.")
end
end
--read in new data from the host with FIFO1
--Note that an external computer must have previously written to FIFO1
currentbytesfifo1 = MB.readName("USER_RAM_FIFO1_ALLOCATE_NUM_BYTES")
if (currentbytesfifo1 == 0) then
print ("FIFO1 buffer is empty.")
end
for i=1, ((currentbytesfifo1+1)/bytesperval) do
inval = MB.readName("USER_RAM_FIFO1_DATA_F32")
f32in[i] = inval
print ("Next Value FIFO1: ", inval)
end
print ("\n")
end
end
|
--[[
Name: 11b_user_ram_fifo.lua
Desc: Example showing how to use USER RAM FIFO buffers to transfer an array
of data to/from an external computer
Note: This system is considered an advanced topic. Simple data transfer
to/from Lua is easiest with USER_RAM, not a FIFO. These FIFO buffers
are good for users who want to send an array of information in
sequence to/from a Lua script. Usually 2 buffers are used for each
endpoint, one buffer dedicated for each communication direction (read
and write). A host may write new data for the Lua script into FIFO0,
then once the script reads the data out of that buffer, it responds
by writing data into FIFO1, and then the host may read the data out
of FIFO1
See the datasheet for more on USER RAM FIFO buffers:
http://labjack.com/support/datasheets/t7/scripting
This example requires firmware 1.0282 (T7) or 1.0023 (T4)
--]]
print("Transfer an array of ordered information to/from an external computer using a FIFO buffer.")
-- To get started, simply run the script.
-- Once the script is running, open up the Register Matrix, and search USER_RAM_FIFO1_DATA_F32
-- add this USER_RAM_FIFO1_DATA_F32 register to the active watch area, and
-- view each element coming out in sequence at the update rate of the software.
local f32out= {}
f32out[1] = 10.0
f32out[2] = 20.1
f32out[3] = 30.2
f32out[4] = 40.3
f32out[5] = 50.4
local f32in = {}
local numvalsfio0 = 5
local numvalsfio1 = 5
local bytesperval = 4
local fifo0bytes = numvalsfio0*bytesperval
local fifo1bytes = numvalsfio1*bytesperval
-- Allocate 20 bytes for FIFO0 by writing to USER_RAM_FIFO0_NUM_BYTES_IN_FIFO
MB.writeName("USER_RAM_FIFO0_ALLOCATE_NUM_BYTES", fifo0bytes)
-- Allocate 20 bytes for FIFO1 by writing to USER_RAM_FIFO1_NUM_BYTES_IN_FIFO
MB.writeName("USER_RAM_FIFO1_ALLOCATE_NUM_BYTES", fifo1bytes)
-- Configure an interval of 2000ms
LJ.IntervalConfig(0, 2000)
-- Run the program in an infinite loop
while true do
-- If an interval is done
if LJ.CheckInterval(0) then
-- Write to FIFO0 for the host computer to access
for i=1, numvalsfio0 do
local outval = f32out[i]
local currentbytesfifo0 = MB.readName("USER_RAM_FIFO0_NUM_BYTES_IN_FIFO")
-- If there are less bytes in FIFO0 than we allocated for, send a new
-- array of size numvalsfio0 to the host
if (currentbytesfifo0 < fifo0bytes) then
MB.writeName("USER_RAM_FIFO0_DATA_F32", outval)
print ("Next Value FIFO0: ", outval)
else
print ("FIFO0 buffer is full.")
end
end
--read in new data from the host with FIFO1
--Note that an external computer must have previously written to FIFO1
currentbytesfifo1 = MB.readName("USER_RAM_FIFO1_NUM_BYTES_IN_FIFO")
if (currentbytesfifo1 == 0) then
print ("FIFO1 buffer is empty.")
end
for i=1, ((currentbytesfifo1+1)/bytesperval) do
inval = MB.readName("USER_RAM_FIFO1_DATA_F32")
f32in[i] = inval
print ("Next Value FIFO1: ", inval)
end
print ("\n")
end
end
|
Fixed the USER_RAM FIFO example
|
Fixed the USER_RAM FIFO example
|
Lua
|
mit
|
chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager
|
7c72d241faf37ae3fdfe3cb997ad75ef8d230a2c
|
protocols/core/luasrc/model/cbi/admin_network/proto_dhcp.lua
|
protocols/core/luasrc/model/cbi/admin_network/proto_dhcp.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2011-2012 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
]]--
local map, section, net = ...
local ifc = net:get_interface()
local hostname, accept_ra, send_rs
local bcast, no_gw, peerdns, dns, metric, clientid, vendorclass
hostname = section:taboption("general", Value, "hostname",
translate("Hostname to send when requesting DHCP"))
hostname.placeholder = luci.sys.hostname()
hostname.datatype = "hostname"
if luci.model.network:has_ipv6() then
accept_ra = s:taboption("general", Flag, "accept_ra", translate("Accept router advertisements"))
accept_ra.default = accept_ra.enabled
send_rs = s:taboption("general", Flag, "send_rs", translate("Send router solicitations"))
send_rs.default = send_rs.disabled
send_rs:depends("accept_ra", "")
end
bcast = section:taboption("advanced", Flag, "broadcast",
translate("Use broadcast flag"),
translate("Required for certain ISPs, e.g. Charter with DOCSIS 3"))
bcast.default = bcast.disabled
no_gw = section:taboption("advanced", Flag, "gateway",
translate("Use default gateway"),
translate("If unchecked, no default route is configured"))
no_gw.default = no_gw.enabled
function no_gw.cfgvalue(...)
return Flag.cfgvalue(...) == "0.0.0.0" and "0" or "1"
end
function no_gw.write(self, section, value)
if value == "1" then
m:set(section, "gateway", nil)
else
m:set(section, "gateway", "0.0.0.0")
end
end
peerdns = section:taboption("advanced", Flag, "peerdns",
translate("Use DNS servers advertised by peer"),
translate("If unchecked, the advertised DNS server addresses are ignored"))
peerdns.default = peerdns.enabled
dns = section:taboption("advanced", DynamicList, "dns",
translate("Use custom DNS servers"))
dns:depends("peerdns", "")
dns.datatype = "ipaddr"
dns.cast = "string"
metric = section:taboption("advanced", Value, "metric",
translate("Use gateway metric"))
metric.placeholder = "0"
metric.datatype = "uinteger"
metric:depends("gateway", "1")
clientid = section:taboption("advanced", Value, "clientid",
translate("Client ID to send when requesting DHCP"))
vendorclass = section:taboption("advanced", Value, "vendorid",
translate("Vendor Class to send when requesting DHCP"))
macaddr = section:taboption("advanced", Value, "macaddr", translate("Override MAC address"))
macaddr.placeholder = ifc and ifc:mac() or "00:00:00:00:00:00"
macaddr.datatype = "macaddr"
mtu = section:taboption("advanced", Value, "mtu", translate("Override MTU"))
mtu.placeholder = "1500"
mtu.datatype = "max(1500)"
|
--[[
LuCI - Lua Configuration Interface
Copyright 2011-2012 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
]]--
local map, section, net = ...
local ifc = net:get_interface()
local hostname, accept_ra, send_rs
local bcast, defaultroute, peerdns, dns, metric, clientid, vendorclass
hostname = section:taboption("general", Value, "hostname",
translate("Hostname to send when requesting DHCP"))
hostname.placeholder = luci.sys.hostname()
hostname.datatype = "hostname"
if luci.model.network:has_ipv6() then
accept_ra = s:taboption("general", Flag, "accept_ra", translate("Accept router advertisements"))
accept_ra.default = accept_ra.enabled
send_rs = s:taboption("general", Flag, "send_rs", translate("Send router solicitations"))
send_rs.default = send_rs.disabled
send_rs:depends("accept_ra", "")
end
bcast = section:taboption("advanced", Flag, "broadcast",
translate("Use broadcast flag"),
translate("Required for certain ISPs, e.g. Charter with DOCSIS 3"))
bcast.default = bcast.disabled
defaultroute = section:taboption("advanced", Flag, "gateway",
translate("Use default gateway"),
translate("If unchecked, no default route is configured"))
defaultroute.default = defaultroute.enabled
peerdns = section:taboption("advanced", Flag, "peerdns",
translate("Use DNS servers advertised by peer"),
translate("If unchecked, the advertised DNS server addresses are ignored"))
peerdns.default = peerdns.enabled
dns = section:taboption("advanced", DynamicList, "dns",
translate("Use custom DNS servers"))
dns:depends("peerdns", "")
dns.datatype = "ipaddr"
dns.cast = "string"
metric = section:taboption("advanced", Value, "metric",
translate("Use gateway metric"))
metric.placeholder = "0"
metric.datatype = "uinteger"
metric:depends("gateway", "1")
clientid = section:taboption("advanced", Value, "clientid",
translate("Client ID to send when requesting DHCP"))
vendorclass = section:taboption("advanced", Value, "vendorid",
translate("Vendor Class to send when requesting DHCP"))
macaddr = section:taboption("advanced", Value, "macaddr", translate("Override MAC address"))
macaddr.placeholder = ifc and ifc:mac() or "00:00:00:00:00:00"
macaddr.datatype = "macaddr"
mtu = section:taboption("advanced", Value, "mtu", translate("Override MTU"))
mtu.placeholder = "1500"
mtu.datatype = "max(1500)"
|
protocols/core: fix defaultroute setting for DHCP interfaces
|
protocols/core: fix defaultroute setting for DHCP interfaces
|
Lua
|
apache-2.0
|
thesabbir/luci,ReclaimYourPrivacy/cloak-luci,Hostle/openwrt-luci-multi-user,male-puppies/luci,cshore-firmware/openwrt-luci,tobiaswaldvogel/luci,ReclaimYourPrivacy/cloak-luci,chris5560/openwrt-luci,openwrt-es/openwrt-luci,MinFu/luci,lbthomsen/openwrt-luci,kuoruan/luci,thesabbir/luci,zhaoxx063/luci,dwmw2/luci,jorgifumi/luci,david-xiao/luci,Hostle/openwrt-luci-multi-user,kuoruan/luci,slayerrensky/luci,nwf/openwrt-luci,artynet/luci,Noltari/luci,db260179/openwrt-bpi-r1-luci,NeoRaider/luci,Kyklas/luci-proto-hso,Noltari/luci,ff94315/luci-1,palmettos/cnLuCI,nwf/openwrt-luci,tobiaswaldvogel/luci,openwrt/luci,forward619/luci,ollie27/openwrt_luci,florian-shellfire/luci,nmav/luci,palmettos/test,RedSnake64/openwrt-luci-packages,LazyZhu/openwrt-luci-trunk-mod,Kyklas/luci-proto-hso,jorgifumi/luci,david-xiao/luci,tcatm/luci,wongsyrone/luci-1,thess/OpenWrt-luci,cappiewu/luci,jlopenwrtluci/luci,bright-things/ionic-luci,oneru/luci,chris5560/openwrt-luci,RuiChen1113/luci,opentechinstitute/luci,taiha/luci,lcf258/openwrtcn,mumuqz/luci,urueedi/luci,ReclaimYourPrivacy/cloak-luci,dwmw2/luci,male-puppies/luci,opentechinstitute/luci,ff94315/luci-1,Wedmer/luci,joaofvieira/luci,981213/luci-1,aa65535/luci,Noltari/luci,palmettos/cnLuCI,rogerpueyo/luci,shangjiyu/luci-with-extra,fkooman/luci,RuiChen1113/luci,wongsyrone/luci-1,tcatm/luci,obsy/luci,schidler/ionic-luci,hnyman/luci,schidler/ionic-luci,RuiChen1113/luci,Hostle/luci,thesabbir/luci,remakeelectric/luci,Wedmer/luci,oyido/luci,teslamint/luci,nwf/openwrt-luci,palmettos/test,schidler/ionic-luci,tobiaswaldvogel/luci,slayerrensky/luci,marcel-sch/luci,cshore/luci,oyido/luci,bittorf/luci,jorgifumi/luci,ff94315/luci-1,lbthomsen/openwrt-luci,LuttyYang/luci,palmettos/cnLuCI,lcf258/openwrtcn,Hostle/luci,aircross/OpenWrt-Firefly-LuCI,tobiaswaldvogel/luci,male-puppies/luci,taiha/luci,tobiaswaldvogel/luci,Sakura-Winkey/LuCI,jlopenwrtluci/luci,male-puppies/luci,Kyklas/luci-proto-hso,schidler/ionic-luci,forward619/luci,shangjiyu/luci-with-extra,nwf/openwrt-luci,rogerpueyo/luci,joaofvieira/luci,aa65535/luci,Wedmer/luci,joaofvieira/luci,shangjiyu/luci-with-extra,RuiChen1113/luci,db260179/openwrt-bpi-r1-luci,tcatm/luci,wongsyrone/luci-1,nmav/luci,mumuqz/luci,joaofvieira/luci,Hostle/luci,981213/luci-1,Kyklas/luci-proto-hso,daofeng2015/luci,ReclaimYourPrivacy/cloak-luci,teslamint/luci,obsy/luci,MinFu/luci,male-puppies/luci,bright-things/ionic-luci,ollie27/openwrt_luci,NeoRaider/luci,Kyklas/luci-proto-hso,cappiewu/luci,sujeet14108/luci,dismantl/luci-0.12,taiha/luci,urueedi/luci,openwrt/luci,keyidadi/luci,jlopenwrtluci/luci,opentechinstitute/luci,taiha/luci,sujeet14108/luci,maxrio/luci981213,thess/OpenWrt-luci,Sakura-Winkey/LuCI,oneru/luci,aa65535/luci,dismantl/luci-0.12,oyido/luci,daofeng2015/luci,Noltari/luci,openwrt/luci,bittorf/luci,lbthomsen/openwrt-luci,Hostle/luci,LuttyYang/luci,male-puppies/luci,tcatm/luci,daofeng2015/luci,lbthomsen/openwrt-luci,jorgifumi/luci,rogerpueyo/luci,LazyZhu/openwrt-luci-trunk-mod,florian-shellfire/luci,zhaoxx063/luci,rogerpueyo/luci,jorgifumi/luci,openwrt/luci,schidler/ionic-luci,cappiewu/luci,opentechinstitute/luci,MinFu/luci,Noltari/luci,remakeelectric/luci,florian-shellfire/luci,obsy/luci,wongsyrone/luci-1,thesabbir/luci,kuoruan/luci,keyidadi/luci,oneru/luci,Kyklas/luci-proto-hso,maxrio/luci981213,opentechinstitute/luci,tobiaswaldvogel/luci,palmettos/cnLuCI,kuoruan/luci,bittorf/luci,urueedi/luci,dismantl/luci-0.12,Wedmer/luci,artynet/luci,kuoruan/luci,bright-things/ionic-luci,oneru/luci,db260179/openwrt-bpi-r1-luci,deepak78/new-luci,joaofvieira/luci,LazyZhu/openwrt-luci-trunk-mod,oyido/luci,thesabbir/luci,Noltari/luci,openwrt-es/openwrt-luci,hnyman/luci,harveyhu2012/luci,joaofvieira/luci,rogerpueyo/luci,lcf258/openwrtcn,jchuang1977/luci-1,opentechinstitute/luci,Wedmer/luci,db260179/openwrt-bpi-r1-luci,harveyhu2012/luci,sujeet14108/luci,taiha/luci,slayerrensky/luci,urueedi/luci,MinFu/luci,schidler/ionic-luci,RedSnake64/openwrt-luci-packages,dismantl/luci-0.12,nmav/luci,tobiaswaldvogel/luci,palmettos/test,thess/OpenWrt-luci,RuiChen1113/luci,deepak78/new-luci,oyido/luci,keyidadi/luci,david-xiao/luci,taiha/luci,florian-shellfire/luci,dwmw2/luci,remakeelectric/luci,tcatm/luci,bittorf/luci,palmettos/test,Sakura-Winkey/LuCI,db260179/openwrt-bpi-r1-luci,maxrio/luci981213,ReclaimYourPrivacy/cloak-luci,lbthomsen/openwrt-luci,shangjiyu/luci-with-extra,keyidadi/luci,schidler/ionic-luci,florian-shellfire/luci,jlopenwrtluci/luci,artynet/luci,florian-shellfire/luci,slayerrensky/luci,deepak78/new-luci,nwf/openwrt-luci,981213/luci-1,zhaoxx063/luci,remakeelectric/luci,cshore-firmware/openwrt-luci,marcel-sch/luci,slayerrensky/luci,artynet/luci,harveyhu2012/luci,keyidadi/luci,chris5560/openwrt-luci,Sakura-Winkey/LuCI,ff94315/luci-1,fkooman/luci,chris5560/openwrt-luci,dismantl/luci-0.12,aircross/OpenWrt-Firefly-LuCI,aircross/OpenWrt-Firefly-LuCI,LuttyYang/luci,mumuqz/luci,cshore/luci,palmettos/test,981213/luci-1,kuoruan/luci,Sakura-Winkey/LuCI,aa65535/luci,hnyman/luci,shangjiyu/luci-with-extra,nwf/openwrt-luci,jorgifumi/luci,hnyman/luci,nwf/openwrt-luci,teslamint/luci,palmettos/cnLuCI,palmettos/test,thess/OpenWrt-luci,deepak78/new-luci,aa65535/luci,shangjiyu/luci-with-extra,Noltari/luci,kuoruan/lede-luci,mumuqz/luci,openwrt-es/openwrt-luci,mumuqz/luci,LuttyYang/luci,mumuqz/luci,kuoruan/lede-luci,bright-things/ionic-luci,david-xiao/luci,Hostle/luci,aa65535/luci,Wedmer/luci,aircross/OpenWrt-Firefly-LuCI,slayerrensky/luci,bittorf/luci,teslamint/luci,taiha/luci,Wedmer/luci,ollie27/openwrt_luci,harveyhu2012/luci,tcatm/luci,artynet/luci,artynet/luci,MinFu/luci,fkooman/luci,david-xiao/luci,sujeet14108/luci,bright-things/ionic-luci,forward619/luci,tcatm/luci,hnyman/luci,harveyhu2012/luci,cappiewu/luci,hnyman/luci,cshore/luci,palmettos/cnLuCI,daofeng2015/luci,ReclaimYourPrivacy/cloak-luci,cshore/luci,teslamint/luci,RuiChen1113/luci,Hostle/luci,jlopenwrtluci/luci,nmav/luci,ReclaimYourPrivacy/cloak-luci,oneru/luci,kuoruan/lede-luci,openwrt-es/openwrt-luci,male-puppies/luci,kuoruan/lede-luci,openwrt-es/openwrt-luci,oneru/luci,zhaoxx063/luci,lbthomsen/openwrt-luci,sujeet14108/luci,artynet/luci,obsy/luci,openwrt-es/openwrt-luci,fkooman/luci,openwrt/luci,kuoruan/lede-luci,db260179/openwrt-bpi-r1-luci,mumuqz/luci,LazyZhu/openwrt-luci-trunk-mod,aa65535/luci,daofeng2015/luci,marcel-sch/luci,dwmw2/luci,nmav/luci,marcel-sch/luci,marcel-sch/luci,dwmw2/luci,sujeet14108/luci,cshore-firmware/openwrt-luci,RedSnake64/openwrt-luci-packages,aircross/OpenWrt-Firefly-LuCI,dismantl/luci-0.12,slayerrensky/luci,Hostle/luci,remakeelectric/luci,NeoRaider/luci,lcf258/openwrtcn,keyidadi/luci,lcf258/openwrtcn,slayerrensky/luci,openwrt/luci,remakeelectric/luci,fkooman/luci,cshore/luci,cshore-firmware/openwrt-luci,lbthomsen/openwrt-luci,Sakura-Winkey/LuCI,jchuang1977/luci-1,kuoruan/lede-luci,maxrio/luci981213,bittorf/luci,joaofvieira/luci,openwrt-es/openwrt-luci,palmettos/test,Noltari/luci,forward619/luci,Hostle/luci,hnyman/luci,nwf/openwrt-luci,deepak78/new-luci,thess/OpenWrt-luci,ollie27/openwrt_luci,lcf258/openwrtcn,jorgifumi/luci,tcatm/luci,cshore-firmware/openwrt-luci,shangjiyu/luci-with-extra,LazyZhu/openwrt-luci-trunk-mod,NeoRaider/luci,palmettos/test,marcel-sch/luci,lbthomsen/openwrt-luci,dwmw2/luci,palmettos/cnLuCI,forward619/luci,fkooman/luci,bright-things/ionic-luci,lcf258/openwrtcn,zhaoxx063/luci,NeoRaider/luci,Hostle/openwrt-luci-multi-user,sujeet14108/luci,ollie27/openwrt_luci,nmav/luci,male-puppies/luci,RedSnake64/openwrt-luci-packages,chris5560/openwrt-luci,Wedmer/luci,981213/luci-1,urueedi/luci,ff94315/luci-1,palmettos/cnLuCI,dwmw2/luci,bittorf/luci,deepak78/new-luci,Hostle/openwrt-luci-multi-user,teslamint/luci,oneru/luci,Noltari/luci,remakeelectric/luci,ff94315/luci-1,kuoruan/lede-luci,obsy/luci,daofeng2015/luci,jchuang1977/luci-1,LazyZhu/openwrt-luci-trunk-mod,openwrt-es/openwrt-luci,obsy/luci,dismantl/luci-0.12,Hostle/openwrt-luci-multi-user,maxrio/luci981213,taiha/luci,jlopenwrtluci/luci,aa65535/luci,nmav/luci,forward619/luci,chris5560/openwrt-luci,fkooman/luci,zhaoxx063/luci,cappiewu/luci,aircross/OpenWrt-Firefly-LuCI,sujeet14108/luci,lcf258/openwrtcn,NeoRaider/luci,cappiewu/luci,oyido/luci,lcf258/openwrtcn,bright-things/ionic-luci,forward619/luci,chris5560/openwrt-luci,cappiewu/luci,RedSnake64/openwrt-luci-packages,MinFu/luci,NeoRaider/luci,LuttyYang/luci,jlopenwrtluci/luci,thess/OpenWrt-luci,chris5560/openwrt-luci,opentechinstitute/luci,ff94315/luci-1,bright-things/ionic-luci,harveyhu2012/luci,LuttyYang/luci,deepak78/new-luci,Hostle/openwrt-luci-multi-user,jorgifumi/luci,daofeng2015/luci,keyidadi/luci,forward619/luci,cshore/luci,david-xiao/luci,schidler/ionic-luci,bittorf/luci,ollie27/openwrt_luci,nmav/luci,marcel-sch/luci,deepak78/new-luci,kuoruan/luci,obsy/luci,urueedi/luci,db260179/openwrt-bpi-r1-luci,Hostle/openwrt-luci-multi-user,RedSnake64/openwrt-luci-packages,florian-shellfire/luci,MinFu/luci,ollie27/openwrt_luci,teslamint/luci,shangjiyu/luci-with-extra,wongsyrone/luci-1,joaofvieira/luci,fkooman/luci,nmav/luci,obsy/luci,maxrio/luci981213,marcel-sch/luci,openwrt/luci,thesabbir/luci,Sakura-Winkey/LuCI,wongsyrone/luci-1,florian-shellfire/luci,openwrt/luci,thesabbir/luci,oneru/luci,harveyhu2012/luci,artynet/luci,aircross/OpenWrt-Firefly-LuCI,keyidadi/luci,rogerpueyo/luci,jchuang1977/luci-1,981213/luci-1,NeoRaider/luci,Kyklas/luci-proto-hso,ff94315/luci-1,jchuang1977/luci-1,jchuang1977/luci-1,981213/luci-1,LazyZhu/openwrt-luci-trunk-mod,kuoruan/luci,LuttyYang/luci,hnyman/luci,wongsyrone/luci-1,cshore-firmware/openwrt-luci,opentechinstitute/luci,urueedi/luci,remakeelectric/luci,RuiChen1113/luci,kuoruan/lede-luci,ollie27/openwrt_luci,db260179/openwrt-bpi-r1-luci,jlopenwrtluci/luci,lcf258/openwrtcn,thess/OpenWrt-luci,tobiaswaldvogel/luci,Sakura-Winkey/LuCI,MinFu/luci,mumuqz/luci,artynet/luci,cshore/luci,cappiewu/luci,RedSnake64/openwrt-luci-packages,LuttyYang/luci,Hostle/openwrt-luci-multi-user,LazyZhu/openwrt-luci-trunk-mod,cshore/luci,rogerpueyo/luci,thess/OpenWrt-luci,RuiChen1113/luci,zhaoxx063/luci,oyido/luci,maxrio/luci981213,ReclaimYourPrivacy/cloak-luci,urueedi/luci,cshore-firmware/openwrt-luci,wongsyrone/luci-1,dwmw2/luci,thesabbir/luci,maxrio/luci981213,teslamint/luci,david-xiao/luci,jchuang1977/luci-1,daofeng2015/luci,jchuang1977/luci-1,zhaoxx063/luci,oyido/luci,cshore-firmware/openwrt-luci,rogerpueyo/luci,david-xiao/luci
|
1010955910c8440423a11dfeb49853e0a40e9074
|
statistics.lua
|
statistics.lua
|
local dkim_space = 0
local from_space = 1
local envfrom_space = 2
local sender_ip_space = 3
local dkim_msgtype_ts_space = 4
local dkim_senderip_space = 5
field_count = 10
timeout = 0.006
max_attempts = 5
-- BEG deprecated interface
function increment_or_insert(space, key, field)
retry = true
count = 0
while retry do
status, result = pcall(box.update, space, key, '+p', field, 1)
if status then
--success update or tuple is not exist
retry = false
if result == nil then
--insert new tuple
tuple = {}
for i = 2, field_count do tuple[i] = 0 end
tuple[1] = string.sub(key, -8)
tuple[tonumber(field)] = 1
box.insert(space, key, unpack(tuple))
end
else
--exception
count = count + 1
if count == max_attempts then
print("max attempts reached for space="..space.." key="..key.." field="..field)
break
end
box.fiber.sleep(timeout)
end
end
end
function increment_or_insert_2(space, key, field, element1, element2)
retry = true
count = 0
while retry do
status, result = pcall(box.update, space, key, '+p', field, 1)
if status then
--success update or tuple is not exist
retry = false
if result == nil then
--insert new tuple
tuple = {}
for i = 2, field_count + 2 do tuple[i] = 0 end
tuple[1] = string.sub(key, -8)
tuple[tonumber(field)] = 1
tuple[field_count + 1] = element1
tuple[field_count + 2] = element2
box.insert(space, key, unpack(tuple))
end
else
--exception
count = count + 1
if count == max_attempts then
print("max attempts reached for space="..space.." key="..key.." field="..field)
break
end
box.fiber.sleep(timeout)
end
end
end
function update_or_insert(space, key, subject, timestamp)
increment_stat3(space, key, subject, timestamp)
end
-- END deprecated interface
local function increment_stat(space, key, users, spam_users, prob_spam_users, inv_users)
retry = true
count = 0
while retry do
status, result = pcall(box.update, space, key, '+p+p+p+p', 2, users, 3, spam_users, 4, prob_spam_users, 5, inv_users)
if status then
--success update or tuple is not exist
retry = false
if result == nil then
--insert new tuple
tuple = {}
for i = 2, field_count do tuple[i] = 0 end
tuple[1] = string.sub(key, -8)
tuple[2] = users
tuple[3] = spam_users
tuple[4] = prob_spam_users
tuple[5] = inv_users
box.insert(space, key, unpack(tuple))
end
else
--exception
count = count + 1
if count == max_attempts then
print("max attempts reached for space="..space.." key="..key)
break
end
box.fiber.sleep(timeout)
end
end
end
local function increment_stat2(space, key, element1, element2, users, spam_users, prob_spam, inv_users)
retry = true
count = 0
while retry do
status, result = pcall(box.update, space, key, '+p+p+p+p', 2, users, 3, spam_users, 4, prob_spam_users, 5, inv_users)
if status then
--success update or tuple is not exist
retry = false
if result == nil then
--insert new tuple
tuple = {}
for i = 2, field_count + 2 do tuple[i] = 0 end
tuple[1] = string.sub(key, -8)
tuple[2] = users
tuple[3] = spam_users
tuple[4] = prob_spam_users
tuple[5] = inv_users
tuple[field_count + 1] = element1
tuple[field_count + 2] = element2
box.insert(space, key, unpack(tuple))
end
else
--exception
count = count + 1
if count == max_attempts then
print("max attempts reached for space="..space.." key="..key)
break
end
box.fiber.sleep(timeout)
end
end
end
field_subject = 2
field_first = 3
field_last = 4
local function increment_stat3(space, key, subject, timestamp)
retry = true
count = 0
while retry do
status, result = pcall(box.update, space, key, '=p', field_last, timestamp)
if status then
--success update or tuple is not exist
retry = false
if result == nil then
--insert new tuple
tuple = {}
for i = 2, field_last do tuple[i] = 0 end
tuple[1] = string.sub(key, -8)
tuple[field_subject] = subject
tuple[field_first] = timestamp
tuple[field_last] = timestamp
box.insert(space, key, unpack(tuple))
end
else
--exception
count = count + 1
if count == max_attempts then
print("max attempts reached for space="..space.." key="..key)
break
end
box.fiber.sleep(timeout)
end
end
end
function mstat_add(
msgtype, sender_ip, from_domain, envfrom_domain, dkim_domain, subject,
users, spam_users, prob_spam_users, inv_users,
timestamp)
users = box.unpack('i', users)
spam_users = box.unpack('i', spam_users)
prob_spam_users = box.unpack('i', prob_spam_users)
inv_users = box.unpack('i', inv_users)
timestamp = box.unpack('i', timestamp)
local time_str = os.date("_%d_%m_%y", timestamp)
if envfrom_domain ~= "" then
increment_stat(envfrom_space, envfrom_domain..time_str, users, spam_users, prob_spam_users, inv_users)
end
if from_domain ~= "" then
increment_stat(from_space, from_domain..time_str, users, spam_users, prob_spam_users, inv_users)
end
if dkim_domain ~= "" then
increment_stat(dkim_space, dkim_domain..time_str, users, spam_users, prob_spam_users, inv_users)
end
if sender_ip ~= "" then
increment_stat(sender_ip_space, sender_ip..time_str, users, spam_users, prob_spam, inv_users)
end
if dkim_domain ~= "" and sender_ip ~= "" then
increment_stat2(dkim_senderip_space, dkim_domain.."|"..sender_ip..time_str, dkim_domain, sender_ip, users, spam_users, prob_spam_users, inv_users)
end
if dkim_domain ~= "" and msgtype ~= "" then
local element = dkim_domain..":"..msgtype..time_str
increment_stat(dkim_space, element, user, spam_users, prob_spam_users, inv_users)
if subject == "" then subject = " " end
increment_stat3(dkim_msgtype_ts_space, element, subject, timestamp)
end
end
|
local dkim_space = 0
local from_space = 1
local envfrom_space = 2
local sender_ip_space = 3
local dkim_msgtype_ts_space = 4
local dkim_senderip_space = 5
local field_count = 10
local timeout = 0.006
local max_attempts = 5
local function increment_stat3(space, key, subject, timestamp)
retry = true
count = 0
while retry do
status, result = pcall(box.update, space, key, '=p', field_last, timestamp)
if status then
--success update or tuple is not exist
retry = false
if result == nil then
--insert new tuple
tuple = {}
for i = 2, field_last do tuple[i] = 0 end
tuple[1] = string.sub(key, -8)
tuple[2] = subject
tuple[3] = timestamp
tuple[4] = timestamp
box.insert(space, key, unpack(tuple))
end
else
--exception
count = count + 1
if count == max_attempts then
print("max attempts reached for space="..space.." key="..key)
break
end
box.fiber.sleep(timeout)
end
end
end
-- BEG deprecated interface
function increment_or_insert(space, key, field)
retry = true
count = 0
while retry do
status, result = pcall(box.update, space, key, '+p', field, 1)
if status then
--success update or tuple is not exist
retry = false
if result == nil then
--insert new tuple
tuple = {}
for i = 2, field_count do tuple[i] = 0 end
tuple[1] = string.sub(key, -8)
tuple[tonumber(field)] = 1
box.insert(space, key, unpack(tuple))
end
else
--exception
count = count + 1
if count == max_attempts then
print("max attempts reached for space="..space.." key="..key.." field="..field)
break
end
box.fiber.sleep(timeout)
end
end
end
function increment_or_insert_2(space, key, field, element1, element2)
retry = true
count = 0
while retry do
status, result = pcall(box.update, space, key, '+p', field, 1)
if status then
--success update or tuple is not exist
retry = false
if result == nil then
--insert new tuple
tuple = {}
for i = 2, field_count + 2 do tuple[i] = 0 end
tuple[1] = string.sub(key, -8)
tuple[tonumber(field)] = 1
tuple[field_count + 1] = element1
tuple[field_count + 2] = element2
box.insert(space, key, unpack(tuple))
end
else
--exception
count = count + 1
if count == max_attempts then
print("max attempts reached for space="..space.." key="..key.." field="..field)
break
end
box.fiber.sleep(timeout)
end
end
end
function update_or_insert(space, key, subject, timestamp)
increment_stat3(space, key, subject, timestamp)
end
-- END deprecated interface
local function increment_stat(space, key, users, spam_users, prob_spam_users, inv_users)
retry = true
count = 0
while retry do
status, result = pcall(box.update, space, key, '+p+p+p+p', 2, users, 3, spam_users, 4, prob_spam_users, 5, inv_users)
if status then
--success update or tuple is not exist
retry = false
if result == nil then
--insert new tuple
tuple = {}
for i = 2, field_count do tuple[i] = 0 end
tuple[1] = string.sub(key, -8)
tuple[2] = users
tuple[3] = spam_users
tuple[4] = prob_spam_users
tuple[5] = inv_users
box.insert(space, key, unpack(tuple))
end
else
--exception
count = count + 1
if count == max_attempts then
print("max attempts reached for space="..space.." key="..key)
break
end
box.fiber.sleep(timeout)
end
end
end
local function increment_stat2(space, key, element1, element2, users, spam_users, prob_spam, inv_users)
retry = true
count = 0
while retry do
status, result = pcall(box.update, space, key, '+p+p+p+p', 2, users, 3, spam_users, 4, prob_spam_users, 5, inv_users)
if status then
--success update or tuple is not exist
retry = false
if result == nil then
--insert new tuple
tuple = {}
for i = 2, field_count + 2 do tuple[i] = 0 end
tuple[1] = string.sub(key, -8)
tuple[2] = users
tuple[3] = spam_users
tuple[4] = prob_spam_users
tuple[5] = inv_users
tuple[field_count + 1] = element1
tuple[field_count + 2] = element2
box.insert(space, key, unpack(tuple))
end
else
--exception
count = count + 1
if count == max_attempts then
print("max attempts reached for space="..space.." key="..key)
break
end
box.fiber.sleep(timeout)
end
end
end
function mstat_add(
msgtype, sender_ip, from_domain, envfrom_domain, dkim_domain, subject,
users, spam_users, prob_spam_users, inv_users,
timestamp)
users = box.unpack('i', users)
spam_users = box.unpack('i', spam_users)
prob_spam_users = box.unpack('i', prob_spam_users)
inv_users = box.unpack('i', inv_users)
timestamp = box.unpack('i', timestamp)
local time_str = os.date("_%d_%m_%y", timestamp)
if envfrom_domain ~= "" then
increment_stat(envfrom_space, envfrom_domain..time_str, users, spam_users, prob_spam_users, inv_users)
end
if from_domain ~= "" then
increment_stat(from_space, from_domain..time_str, users, spam_users, prob_spam_users, inv_users)
end
if dkim_domain ~= "" then
increment_stat(dkim_space, dkim_domain..time_str, users, spam_users, prob_spam_users, inv_users)
end
if sender_ip ~= "" then
increment_stat(sender_ip_space, sender_ip..time_str, users, spam_users, prob_spam, inv_users)
end
if dkim_domain ~= "" and sender_ip ~= "" then
increment_stat2(dkim_senderip_space, dkim_domain.."|"..sender_ip..time_str, dkim_domain, sender_ip, users, spam_users, prob_spam_users, inv_users)
end
if dkim_domain ~= "" and msgtype ~= "" then
local element = dkim_domain..":"..msgtype..time_str
increment_stat(dkim_space, element, user, spam_users, prob_spam_users, inv_users)
if subject == "" then subject = " " end
increment_stat3(dkim_msgtype_ts_space, element, subject, timestamp)
end
end
|
statistics.lua: fix bug with call of local function from global function
|
statistics.lua: fix bug with call of local function from global function
|
Lua
|
bsd-2-clause
|
spectrec/tntlua,BHYCHIK/tntlua,derElektrobesen/tntlua,grechkin-pogrebnyakov/tntlua,mailru/tntlua
|
a735d467bfe2070756f98f48a8a31e44a3c10e4e
|
profile.lua
|
profile.lua
|
-- Begin of globals
bollards_whitelist = { [""] = true, ["cattle_grid"] = true, ["border_control"] = true, ["toll_booth"] = true, ["no"] = true, ["sally_port"] = true, ["gate"] = true}
access_tag_whitelist = { ["yes"] = true, ["motorcar"] = true, ["motor_vehicle"] = true, ["vehicle"] = true, ["permissive"] = true, ["designated"] = true }
access_tag_blacklist = { ["no"] = true, ["private"] = true, ["agricultural"] = true, ["forestery"] = true }
access_tag_restricted = { ["destination"] = true, ["delivery"] = true }
access_tags = { "motorcar", "motor_vehicle", "vehicle" }
service_tag_restricted = { ["parking_aisle"] = true }
ignore_in_grid = { ["ferry"] = true, ["pier"] = true }
speed_profile = {
["motorway"] = 90,
["motorway_link"] = 75,
["trunk"] = 85,
["trunk_link"] = 70,
["primary"] = 65,
["primary_link"] = 60,
["secondary"] = 55,
["secondary_link"] = 50,
["tertiary"] = 40,
["tertiary_link"] = 30,
["unclassified"] = 25,
["residential"] = 25,
["living_street"] = 10,
["service"] = 15,
-- ["track"] = 5,
["ferry"] = 5,
["pier"] = 5,
["default"] = 50
}
take_minimum_of_speeds = true
obey_oneway = true
obey_bollards = true
use_restrictions = true
ignore_areas = true -- future feature
traffic_signal_penalty = 2
u_turn_penalty = 20
-- End of globals
function node_function (node)
local barrier = node.tags:Find ("barrier")
local access = node.tags:Find ("access")
local traffic_signal = node.tags:Find("highway")
--flag node if it carries a traffic light
if traffic_signal == "traffic_signals" then
node.traffic_light = true;
end
if access_tag_blacklist[barrier] then
node.bollard = true;
end
if "" ~= barrier then
if obey_bollards then
--flag node as unpassable if it black listed as unpassable
print(barrier)
node.bollard = true;
end
--reverse the previous flag if there is an access tag specifying entrance
if node.bollard and bollards_whitelist[barrier] and access_tag_whitelist[barrier] then
node.bollard = false;
return 1
end
-- Check if our vehicle types are allowd to pass the barrier
for i,v in ipairs(access_tags) do
local mode_value = node.tags:Find(v)
if nil ~= mode_value and "yes" == mode_value then
return 1
node.bollard = false
return
end
end
else
-- Check if our vehicle types are forbidden to pass the node
for i,v in ipairs(access_tags) do
local mode_value = node.tags:Find(v)
if nil ~= mode_value and "no" == mode_value then
node.bollard = true
return 1
end
end
end
return 1
end
function way_function (way, numberOfNodesInWay)
-- A way must have two nodes or more
if(numberOfNodesInWay < 2) then
return 0;
end
-- First, get the properties of each way that we come across
local highway = way.tags:Find("highway")
local name = way.tags:Find("name")
local ref = way.tags:Find("ref")
local junction = way.tags:Find("junction")
local route = way.tags:Find("route")
local maxspeed = parseMaxspeed(way.tags:Find ( "maxspeed") )
local man_made = way.tags:Find("man_made")
local barrier = way.tags:Find("barrier")
local oneway = way.tags:Find("oneway")
local cycleway = way.tags:Find("cycleway")
local duration = way.tags:Find("duration")
local service = way.tags:Find("service")
local area = way.tags:Find("area")
local access = way.tags:Find("access")
-- Second parse the way according to these properties
if ignore_areas and ("yes" == area) then
return 0
end
-- Check if we are allowed to access the way
if access_tag_blacklist[access] ~=nil and access_tag_blacklist[access] then
return 0;
end
-- Check if our vehicle types are forbidden
for i,v in ipairs(access_tags) do
local mode_value = way.tags:Find(v)
if nil ~= mode_value and "no" == mode_value then
return 0;
end
end
-- Set the name that will be used for instructions
if "" ~= ref then
way.name = ref
elseif "" ~= name then
way.name = name
end
if "roundabout" == junction then
way.roundabout = true;
end
-- Handling ferries and piers
if (speed_profile[route] ~= nil and speed_profile[route] > 0) or
(speed_profile[man_made] ~= nil and speed_profile[man_made] > 0)
then
if durationIsValid(duration) then
way.speed = math.max( duration / math.max(1, numberOfNodesInWay-1) );
way.is_duration_set = true;
end
way.direction = Way.bidirectional;
if speed_profile[route] ~= nil then
highway = route;
elseif speed_profile[man_made] ~= nil then
highway = man_made;
end
if not way.is_duration_set then
way.speed = speed_profile[highway]
end
end
-- Set the avg speed on the way if it is accessible by road class
if (speed_profile[highway] ~= nil and way.speed == -1 ) then
if (0 < maxspeed and not take_minimum_of_speeds) or (maxspeed == 0) then
maxspeed = math.huge
end
way.speed = math.min(speed_profile[highway], maxspeed)
end
-- Set the avg speed on ways that are marked accessible
if access_tag_whitelist[access] and way.speed == -1 then
if (0 < maxspeed and not take_minimum_of_speeds) or maxspeed == 0 then
maxspeed = math.huge
end
way.speed = math.min(speed_profile["default"], maxspeed)
end
-- Set access restriction flag if access is allowed under certain restrictions only
if access ~= "" and access_tag_restricted[access] then
way.is_access_restricted = true
end
-- Set access restriction flag if service is allowed under certain restrictions only
if service ~= "" and service_tag_restricted[service] then
way.is_access_restricted = true
end
-- Set direction according to tags on way
if obey_oneway then
if oneway == "no" or oneway == "0" or oneway == "false" then
way.direction = Way.bidirectional
elseif oneway == "-1" then
way.direction = Way.opposite
elseif oneway == "yes" or oneway == "1" or oneway == "true" or junction == "roundabout" or highway == "motorway_link" or highway == "motorway" then
way.direction = Way.oneway
else
way.direction = Way.bidirectional
end
else
way.direction = Way.bidirectional
end
-- Override general direction settings of there is a specific one for our mode of travel
if ignore_in_grid[highway] ~= nil and ignore_in_grid[highway] then
way.ignore_in_grid = true
end
way.type = 1
return 1
end
|
-- Begin of globals
bollards_whitelist = { [""] = true, ["cattle_grid"] = true, ["border_control"] = true, ["toll_booth"] = true, ["no"] = true, ["sally_port"] = true, ["gate"] = true}
access_tag_whitelist = { ["yes"] = true, ["motorcar"] = true, ["motor_vehicle"] = true, ["vehicle"] = true, ["permissive"] = true, ["designated"] = true }
access_tag_blacklist = { ["no"] = true, ["private"] = true, ["agricultural"] = true, ["forestery"] = true }
access_tag_restricted = { ["destination"] = true, ["delivery"] = true }
access_tags = { "motorcar", "motor_vehicle", "vehicle" }
service_tag_restricted = { ["parking_aisle"] = true }
ignore_in_grid = { ["ferry"] = true, ["pier"] = true }
speed_profile = {
["motorway"] = 90,
["motorway_link"] = 75,
["trunk"] = 85,
["trunk_link"] = 70,
["primary"] = 65,
["primary_link"] = 60,
["secondary"] = 55,
["secondary_link"] = 50,
["tertiary"] = 40,
["tertiary_link"] = 30,
["unclassified"] = 25,
["residential"] = 25,
["living_street"] = 10,
["service"] = 15,
-- ["track"] = 5,
["ferry"] = 5,
["pier"] = 5,
["default"] = 50
}
take_minimum_of_speeds = true
obey_oneway = true
obey_bollards = true
use_restrictions = true
ignore_areas = true -- future feature
traffic_signal_penalty = 2
u_turn_penalty = 20
-- End of globals
function node_function (node)
local barrier = node.tags:Find ("barrier")
local access = node.tags:Find ("access")
local traffic_signal = node.tags:Find("highway")
--flag node if it carries a traffic light
if traffic_signal == "traffic_signals" then
node.traffic_light = true;
end
if access_tag_blacklist[barrier] then
node.bollard = true;
end
if "" ~= barrier then
if obey_bollards then
--flag node as unpassable if it black listed as unpassable
node.bollard = true;
end
--reverse the previous flag if there is an access tag specifying entrance
if node.bollard and bollards_whitelist[barrier] and access_tag_whitelist[barrier] then
node.bollard = false;
return 1
end
-- Check if our vehicle types are allowd to pass the barrier
for i,v in ipairs(access_tags) do
local mode_value = node.tags:Find(v)
if nil ~= mode_value and "yes" == mode_value then
node.bollard = false
return
end
end
else
-- Check if our vehicle types are forbidden to pass the node
for i,v in ipairs(access_tags) do
local mode_value = node.tags:Find(v)
if nil ~= mode_value and "no" == mode_value then
node.bollard = true
return 1
end
end
end
return 1
end
function way_function (way, numberOfNodesInWay)
-- A way must have two nodes or more
if(numberOfNodesInWay < 2) then
return 0;
end
-- First, get the properties of each way that we come across
local highway = way.tags:Find("highway")
local name = way.tags:Find("name")
local ref = way.tags:Find("ref")
local junction = way.tags:Find("junction")
local route = way.tags:Find("route")
local maxspeed = parseMaxspeed(way.tags:Find ( "maxspeed") )
local man_made = way.tags:Find("man_made")
local barrier = way.tags:Find("barrier")
local oneway = way.tags:Find("oneway")
local cycleway = way.tags:Find("cycleway")
local duration = way.tags:Find("duration")
local service = way.tags:Find("service")
local area = way.tags:Find("area")
local access = way.tags:Find("access")
-- Second parse the way according to these properties
if ignore_areas and ("yes" == area) then
return 0
end
-- Check if we are allowed to access the way
if access_tag_blacklist[access] ~=nil and access_tag_blacklist[access] then
return 0;
end
-- Check if our vehicle types are forbidden
for i,v in ipairs(access_tags) do
local mode_value = way.tags:Find(v)
if nil ~= mode_value and "no" == mode_value then
return 0;
end
end
-- Set the name that will be used for instructions
if "" ~= ref then
way.name = ref
elseif "" ~= name then
way.name = name
end
if "roundabout" == junction then
way.roundabout = true;
end
-- Handling ferries and piers
if (speed_profile[route] ~= nil and speed_profile[route] > 0) or
(speed_profile[man_made] ~= nil and speed_profile[man_made] > 0)
then
if durationIsValid(duration) then
way.speed = math.max( duration / math.max(1, numberOfNodesInWay-1) );
way.is_duration_set = true;
end
way.direction = Way.bidirectional;
if speed_profile[route] ~= nil then
highway = route;
elseif speed_profile[man_made] ~= nil then
highway = man_made;
end
if not way.is_duration_set then
way.speed = speed_profile[highway]
end
end
-- Set the avg speed on the way if it is accessible by road class
if (speed_profile[highway] ~= nil and way.speed == -1 ) then
if (0 < maxspeed and not take_minimum_of_speeds) or (maxspeed == 0) then
maxspeed = math.huge
end
way.speed = math.min(speed_profile[highway], maxspeed)
end
-- Set the avg speed on ways that are marked accessible
if access_tag_whitelist[access] and way.speed == -1 then
if (0 < maxspeed and not take_minimum_of_speeds) or maxspeed == 0 then
maxspeed = math.huge
end
way.speed = math.min(speed_profile["default"], maxspeed)
end
-- Set access restriction flag if access is allowed under certain restrictions only
if access ~= "" and access_tag_restricted[access] then
way.is_access_restricted = true
end
-- Set access restriction flag if service is allowed under certain restrictions only
if service ~= "" and service_tag_restricted[service] then
way.is_access_restricted = true
end
-- Set direction according to tags on way
if obey_oneway then
if oneway == "no" or oneway == "0" or oneway == "false" then
way.direction = Way.bidirectional
elseif oneway == "-1" then
way.direction = Way.opposite
elseif oneway == "yes" or oneway == "1" or oneway == "true" or junction == "roundabout" or highway == "motorway_link" or highway == "motorway" then
way.direction = Way.oneway
else
way.direction = Way.bidirectional
end
else
way.direction = Way.bidirectional
end
-- Override general direction settings of there is a specific one for our mode of travel
if ignore_in_grid[highway] ~= nil and ignore_in_grid[highway] then
way.ignore_in_grid = true
end
way.type = 1
return 1
end
|
Fixes issue #430
|
Fixes issue #430
|
Lua
|
bsd-2-clause
|
hydrays/osrm-backend,neilbu/osrm-backend,chaupow/osrm-backend,frodrigo/osrm-backend,felixguendling/osrm-backend,Tristramg/osrm-backend,KnockSoftware/osrm-backend,ibikecph/osrm-backend,felixguendling/osrm-backend,Carsten64/OSRM-aux-git,deniskoronchik/osrm-backend,ibikecph/osrm-backend,KnockSoftware/osrm-backend,bjtaylor1/osrm-backend,yuryleb/osrm-backend,hydrays/osrm-backend,nagyistoce/osrm-backend,prembasumatary/osrm-backend,alex85k/Project-OSRM,ammeurer/osrm-backend,Project-OSRM/osrm-backend,raymond0/osrm-backend,arnekaiser/osrm-backend,ammeurer/osrm-backend,yuryleb/osrm-backend,stevevance/Project-OSRM,tkhaxton/osrm-backend,jpizarrom/osrm-backend,bjtaylor1/Project-OSRM-Old,arnekaiser/osrm-backend,duizendnegen/osrm-backend,antoinegiret/osrm-geovelo,KnockSoftware/osrm-backend,skyborla/osrm-backend,oxidase/osrm-backend,agruss/osrm-backend,oxidase/osrm-backend,beemogmbh/osrm-backend,bjtaylor1/Project-OSRM-Old,bjtaylor1/osrm-backend,keesklopt/matrix,ramyaragupathy/osrm-backend,yuryleb/osrm-backend,antoinegiret/osrm-backend,chaupow/osrm-backend,Conggge/osrm-backend,atsuyim/osrm-backend,yuryleb/osrm-backend,ramyaragupathy/osrm-backend,bjtaylor1/Project-OSRM-Old,tkhaxton/osrm-backend,antoinegiret/osrm-geovelo,Project-OSRM/osrm-backend,Conggge/osrm-backend,keesklopt/matrix,stevevance/Project-OSRM,atsuyim/osrm-backend,bitsteller/osrm-backend,agruss/osrm-backend,deniskoronchik/osrm-backend,Project-OSRM/osrm-backend,neilbu/osrm-backend,deniskoronchik/osrm-backend,hydrays/osrm-backend,tkhaxton/osrm-backend,Carsten64/OSRM-aux-git,frodrigo/osrm-backend,atsuyim/osrm-backend,raymond0/osrm-backend,frodrigo/osrm-backend,frodrigo/osrm-backend,duizendnegen/osrm-backend,antoinegiret/osrm-backend,nagyistoce/osrm-backend,beemogmbh/osrm-backend,agruss/osrm-backend,ammeurer/osrm-backend,antoinegiret/osrm-backend,bjtaylor1/osrm-backend,hydrays/osrm-backend,ammeurer/osrm-backend,jpizarrom/osrm-backend,ammeurer/osrm-backend,skyborla/osrm-backend,Carsten64/OSRM-aux-git,duizendnegen/osrm-backend,nagyistoce/osrm-backend,ramyaragupathy/osrm-backend,bitsteller/osrm-backend,stevevance/Project-OSRM,Tristramg/osrm-backend,Conggge/osrm-backend,beemogmbh/osrm-backend,bjtaylor1/Project-OSRM-Old,arnekaiser/osrm-backend,felixguendling/osrm-backend,duizendnegen/osrm-backend,ammeurer/osrm-backend,keesklopt/matrix,neilbu/osrm-backend,Tristramg/osrm-backend,prembasumatary/osrm-backend,bjtaylor1/osrm-backend,skyborla/osrm-backend,antoinegiret/osrm-geovelo,alex85k/Project-OSRM,raymond0/osrm-backend,jpizarrom/osrm-backend,prembasumatary/osrm-backend,stevevance/Project-OSRM,ammeurer/osrm-backend,Carsten64/OSRM-aux-git,deniskoronchik/osrm-backend,oxidase/osrm-backend,chaupow/osrm-backend,Conggge/osrm-backend,alex85k/Project-OSRM,neilbu/osrm-backend,beemogmbh/osrm-backend,Project-OSRM/osrm-backend,bitsteller/osrm-backend,raymond0/osrm-backend,ibikecph/osrm-backend,KnockSoftware/osrm-backend,arnekaiser/osrm-backend,oxidase/osrm-backend,keesklopt/matrix
|
f0782f31c129fcfb8963bc774d95d67e9b2e2c9f
|
BIOS/setup.lua
|
BIOS/setup.lua
|
--BIOS Setup Screen
local Handled, Devkits = ... --It has been passed by the BIOS POST Screen :)
local BIOS = Handled.BIOS
local GPU = Handled.GPU
local CPU = Handled.CPU
local fs = Handled.HDD
local KB = Handled.Keyboard
local coreg = require("Engine.coreg")
local stopWhile = false
GPU.clear(0)
GPU.color(7)
KB.textinput(true)
local function drawInfo()
GPU.clear(0)
GPU.printCursor(0,0,0)
GPU.print("LIKO-12 Setup ------ Press R to reboot")
GPU.print("Press O to reflash DiskOS")
GPU.print("Press B to boot from D:")
GPU.print("Press W then C or D to wipe a disk")
end
local function attemptBootFromD()
fs.drive("D")
if not fs.exists("/boot.lua") then
GPU.print("Could not find boot.lua")
CPU.sleep(1)
drawInfo()
return
end
local bootchunk, err = fs.load("/boot.lua")
if not bootchunk then error(err or "") end
local coglob = coreg:sandbox(bootchunk)
local co = coroutine.create(bootchunk)
local HandledAPIS = BIOS.HandledAPIS()
coroutine.yield("echo",HandledAPIS)
coreg:setCoroutine(co,coglob) --Switch to boot.lua coroutine
end
drawInfo()
while not stopWhile do
for event, a, b, c, d, e, f in CPU.pullEvent do
if event == "keypressed" and c == false then
if a == "o" then
GPU.print("Flashing in 5 seconds...")
CPU.sleep(5)
love.filesystem.load("BIOS/installer.lua")(Handled,"DiskOS",false)
CPU.reboot()
end
if a == "r" then
CPU.reboot()
end
if a == "w" then
wipingMode = true
GPU.print("Wiping mode enabled")
GPU.flip()
end
if a == "b" then
stopWhile = true
break
end
if wipingMode then
if a == "c" then
GPU.print("Wiping C: in 15 seconds!")
CPU.sleep(15)
GPU.print("Please wait, wiping...")
fs.drive("C")
fs.delete("/")
GPU.print("Wipe done.")
GPU.flip()
CPU.sleep(1)
drawInfo()
end
if a == "d" and c == false then
GPU.print("Wiping D: in 15 seconds!")
CPU.sleep(15)
GPU.print("Please wait, wiping...")
fs.drive("D")
fs.delete("/")
GPU.print("Wipe done.")
CPU.sleep(1)
drawInfo()
end
end
end
if event == "touchpressed" then
KB.textinput(true)
end
end
end
attemptBootFromD()
|
--BIOS Setup Screen
local Handled, love = ... --Handled is passed by BIOS POST, love is available too.
local BIOS = Handled.BIOS
local GPU = Handled.GPU
local CPU = Handled.CPU
local fs = Handled.HDD
local KB = Handled.Keyboard
local coreg = require("Engine.coreg")
local stopWhile = false
local wipingMode = false
GPU.clear(0)
GPU.color(7)
KB.textinput(true)
local function drawInfo()
GPU.clear(0)
GPU.printCursor(0,0,0)
GPU.print("LIKO-12 Setup ------ Press R to reboot")
GPU.print("Press O to reflash DiskOS")
GPU.print("Press B to boot from D:")
GPU.print("Press W then C or D to wipe a disk")
end
local function attemptBootFromD()
fs.drive("D")
local bootchunk, err = fs.load("/boot.lua")
if not bootchunk then error(err or "") end
local coglob = coreg:sandbox(bootchunk)
local co = coroutine.create(bootchunk)
local HandledAPIS = BIOS.HandledAPIS()
coroutine.yield("echo",HandledAPIS)
coreg:setCoroutine(co,coglob) --Switch to boot.lua coroutine
end
drawInfo()
while not stopWhile do
for event, a, _, c, _, _, _ in CPU.pullEvent do
if event == "keypressed" and c == false then
if a == "o" then
GPU.print("Flashing in 5 seconds...")
CPU.sleep(5)
love.filesystem.load("BIOS/installer.lua")(Handled,"DiskOS",false)
CPU.reboot()
end
if a == "r" then
CPU.reboot()
end
if a == "w" then
wipingMode = true
GPU.print("Wiping mode enabled")
GPU.flip()
end
if a == "b" then
if not fs.exists("/boot.lua") then
GPU.print("Could not find boot.lua")
CPU.sleep(1)
drawInfo()
else
stopWhile = true
break
end
end
if wipingMode then
if a == "c" then
GPU.print("Wiping C: in 15 seconds!")
CPU.sleep(15)
GPU.print("Please wait, wiping...")
fs.drive("C")
fs.delete("/")
GPU.print("Wipe done.")
GPU.flip()
CPU.sleep(1)
drawInfo()
end
if a == "d" and c == false then
GPU.print("Wiping D: in 15 seconds!")
CPU.sleep(15)
GPU.print("Please wait, wiping...")
fs.drive("D")
fs.delete("/")
GPU.print("Wipe done.")
CPU.sleep(1)
drawInfo()
end
end
end
if event == "touchpressed" then
KB.textinput(true)
end
end
end
attemptBootFromD()
|
Fix to pass luacheck
|
Fix to pass luacheck
Fixed 10 warnings
Former-commit-id: 7da00e328d806d97669734075ea0c2056dd61b52
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
aa64dfbc8e2dd7e48c0e472fac2ebb58f99e1713
|
runners/hostinfo_runner.lua
|
runners/hostinfo_runner.lua
|
--[[
Copyright 2015 Rackspace
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local HostInfo = require('../hostinfo')
local json = require('json')
local function run(...)
local argv, typeName, klass
argv = require("options")
.usage('Usage: -x [Host Info Type]')
.describe("x", "host info type to run")
.argv("x:")
if not argv.args.x then
print(argv._usage)
process:exit(0)
end
typeName = argv.args.x
klass = HostInfo.create(typeName)
klass:run(function(err, callback)
if err then
print(json.stringify({error = err}))
else
print(json.stringify(klass:serialize()))
end
end)
end
return { run = run }
|
--[[
Copyright 2015 Rackspace
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local HostInfo = require('../hostinfo')
local json = require('json')
local upper = require('string').upper
local function run(...)
local argv, typeName, klass
argv = require("options")
.usage('Usage: -x [Host Info Type]')
.describe("x", "host info type to run")
.argv("x:")
if not argv.args.x then
print(argv._usage)
process:exit(0)
end
typeName = upper(argv.args.x)
klass = HostInfo.create(typeName)
klass:run(function(err, callback)
if err then
print(json.stringify({error = err}))
else
print(json.stringify(klass:serialize()))
end
end)
end
return { run = run }
|
fix(runners/hostinfo_runner): Make hostinfo runner types case insensitive;closes #806
|
fix(runners/hostinfo_runner): Make hostinfo runner types case insensitive;closes #806
|
Lua
|
apache-2.0
|
kaustavha/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent
|
b5768add077703a644f8c4d1e2a7f052bd7e870a
|
src/base/os.lua
|
src/base/os.lua
|
--
-- os.lua
-- Additions to the OS namespace.
-- Copyright (c) 2002-2011 Jason Perkins and the Premake project
--
--
-- Same as os.execute(), but accepts string formatting arguments.
--
function os.executef(cmd, ...)
cmd = string.format(cmd, unpack(arg))
return os.execute(cmd)
end
--
-- Scan the well-known system locations for a particular library.
--
function os.findlib(libname)
local path, formats
-- assemble a search path, depending on the platform
if os.is("windows") then
formats = { "%s.dll", "%s" }
path = os.getenv("PATH")
elseif os.is("haiku") then
formats = { "lib%s.so", "%s.so" }
path = os.getenv("LIBRARY_PATH")
else
if os.is("macosx") then
formats = { "lib%s.dylib", "%s.dylib" }
path = os.getenv("DYLD_LIBRARY_PATH")
else
formats = { "lib%s.so", "%s.so" }
path = os.getenv("LD_LIBRARY_PATH") or ""
io.input("/etc/ld.so.conf")
if io.input() then
for line in io.lines() do
path = path .. ":" .. line
end
io.input():close()
end
end
table.insert(formats, "%s")
path = path or ""
if os.is64bit() then
path = path .. ":/lib64:/usr/lib64/:usr/local/lib64"
end
path = ":/lib:/usr/lib:/usr/local/lib"
end
for _, fmt in ipairs(formats) do
local name = string.format(fmt, libname)
local result = os.pathsearch(name, path)
if result then return result end
end
end
--
-- Retrieve the current operating system ID string.
--
function os.get()
return _OPTIONS.os or _OS
end
--
-- Check the current operating system; may be set with the /os command line flag.
--
function os.is(id)
return (os.get():lower() == id:lower())
end
--
-- Determine if the current system is running a 64-bit architecture
--
local _64BitHostTypes = {
"x86_64",
"ia64",
"amd64",
"ppc64",
"powerpc64",
"sparc64"
}
function os.is64bit()
-- Call the native code implementation. If this returns true then
-- we're 64-bit, otherwise do more checking locally
if (os._is64bit()) then
return true
end
-- Identify the system
local arch
if _OS == "windows" then
arch = os.getenv("PROCESSOR_ARCHITECTURE")
elseif _OS == "macosx" then
arch = os.outputof("echo $HOSTTYPE")
else
arch = os.outputof("uname -m")
end
-- Check our known 64-bit identifiers
arch = arch:lower()
for _, hosttype in ipairs(_64BitHostTypes) do
if arch:find(hosttype) then
return true
end
end
return false
end
--
-- The os.matchdirs() and os.matchfiles() functions
--
local function domatch(result, mask, wantfiles)
-- need to remove extraneous path info from the mask to ensure a match
-- against the paths returned by the OS. Haven't come up with a good
-- way to do it yet, so will handle cases as they come up
if mask:startswith("./") then
mask = mask:sub(3)
end
-- strip off any leading directory information to find out
-- where the search should take place
local basedir = mask
local starpos = mask:find("%*")
if starpos then
basedir = basedir:sub(1, starpos - 1)
end
basedir = path.getdirectory(basedir)
if (basedir == ".") then basedir = "" end
-- recurse into subdirectories?
local recurse = mask:find("**", nil, true)
-- convert mask to a Lua pattern
mask = path.wildcards(mask)
local function matchwalker(basedir)
local wildcard = path.join(basedir, "*")
-- retrieve files from OS and test against mask
local m = os.matchstart(wildcard)
while (os.matchnext(m)) do
local isfile = os.matchisfile(m)
if ((wantfiles and isfile) or (not wantfiles and not isfile)) then
local fname = path.join(basedir, os.matchname(m))
if fname:match(mask) == fname then
table.insert(result, fname)
end
end
end
os.matchdone(m)
-- check subdirectories
if recurse then
m = os.matchstart(wildcard)
while (os.matchnext(m)) do
if not os.matchisfile(m) then
local dirname = os.matchname(m)
matchwalker(path.join(basedir, dirname))
end
end
os.matchdone(m)
end
end
matchwalker(basedir)
end
function os.matchdirs(...)
local result = { }
for _, mask in ipairs(arg) do
domatch(result, mask, false)
end
return result
end
function os.matchfiles(...)
local result = { }
for _, mask in ipairs(arg) do
domatch(result, mask, true)
end
return result
end
--
-- An overload of the os.mkdir() function, which will create any missing
-- subdirectories along the path.
--
local builtin_mkdir = os.mkdir
function os.mkdir(p)
local dir = iif(p:startswith("/"), "/", "")
for part in p:gmatch("[^/]+") do
dir = dir .. part
if (part ~= "" and not path.isabsolute(part) and not os.isdir(dir)) then
local ok, err = builtin_mkdir(dir)
if (not ok) then
return nil, err
end
end
dir = dir .. "/"
end
return true
end
--
-- Run a shell command and return the output.
--
function os.outputof(cmd)
local pipe = io.popen(cmd)
local result = pipe:read('*a')
pipe:close()
return result
end
--
-- Remove a directory, along with any contained files or subdirectories.
--
local builtin_rmdir = os.rmdir
function os.rmdir(p)
-- recursively remove subdirectories
local dirs = os.matchdirs(p .. "/*")
for _, dname in ipairs(dirs) do
os.rmdir(dname)
end
-- remove any files
local files = os.matchfiles(p .. "/*")
for _, fname in ipairs(files) do
os.remove(fname)
end
-- remove this directory
builtin_rmdir(p)
end
|
--
-- os.lua
-- Additions to the OS namespace.
-- Copyright (c) 2002-2011 Jason Perkins and the Premake project
--
--
-- Same as os.execute(), but accepts string formatting arguments.
--
function os.executef(cmd, ...)
cmd = string.format(cmd, unpack(arg))
return os.execute(cmd)
end
--
-- Scan the well-known system locations for a particular library.
--
function os.findlib(libname)
local path, formats
-- assemble a search path, depending on the platform
if os.is("windows") then
formats = { "%s.dll", "%s" }
path = os.getenv("PATH")
elseif os.is("haiku") then
formats = { "lib%s.so", "%s.so" }
path = os.getenv("LIBRARY_PATH")
else
if os.is("macosx") then
formats = { "lib%s.dylib", "%s.dylib" }
path = os.getenv("DYLD_LIBRARY_PATH")
else
formats = { "lib%s.so", "%s.so" }
path = os.getenv("LD_LIBRARY_PATH") or ""
io.input("/etc/ld.so.conf")
if io.input() then
for line in io.lines() do
path = path .. ":" .. line
end
io.input():close()
end
end
table.insert(formats, "%s")
path = path or ""
if os.is64bit() then
path = path .. ":/lib64:/usr/lib64/:usr/local/lib64"
end
path = path .. ":/lib:/usr/lib:/usr/local/lib"
end
for _, fmt in ipairs(formats) do
local name = string.format(fmt, libname)
local result = os.pathsearch(name, path)
if result then return result end
end
end
--
-- Retrieve the current operating system ID string.
--
function os.get()
return _OPTIONS.os or _OS
end
--
-- Check the current operating system; may be set with the /os command line flag.
--
function os.is(id)
return (os.get():lower() == id:lower())
end
--
-- Determine if the current system is running a 64-bit architecture
--
local _64BitHostTypes = {
"x86_64",
"ia64",
"amd64",
"ppc64",
"powerpc64",
"sparc64"
}
function os.is64bit()
-- Call the native code implementation. If this returns true then
-- we're 64-bit, otherwise do more checking locally
if (os._is64bit()) then
return true
end
-- Identify the system
local arch
if _OS == "windows" then
arch = os.getenv("PROCESSOR_ARCHITECTURE")
elseif _OS == "macosx" then
arch = os.outputof("echo $HOSTTYPE")
else
arch = os.outputof("uname -m")
end
-- Check our known 64-bit identifiers
arch = arch:lower()
for _, hosttype in ipairs(_64BitHostTypes) do
if arch:find(hosttype) then
return true
end
end
return false
end
--
-- The os.matchdirs() and os.matchfiles() functions
--
local function domatch(result, mask, wantfiles)
-- need to remove extraneous path info from the mask to ensure a match
-- against the paths returned by the OS. Haven't come up with a good
-- way to do it yet, so will handle cases as they come up
if mask:startswith("./") then
mask = mask:sub(3)
end
-- strip off any leading directory information to find out
-- where the search should take place
local basedir = mask
local starpos = mask:find("%*")
if starpos then
basedir = basedir:sub(1, starpos - 1)
end
basedir = path.getdirectory(basedir)
if (basedir == ".") then basedir = "" end
-- recurse into subdirectories?
local recurse = mask:find("**", nil, true)
-- convert mask to a Lua pattern
mask = path.wildcards(mask)
local function matchwalker(basedir)
local wildcard = path.join(basedir, "*")
-- retrieve files from OS and test against mask
local m = os.matchstart(wildcard)
while (os.matchnext(m)) do
local isfile = os.matchisfile(m)
if ((wantfiles and isfile) or (not wantfiles and not isfile)) then
local fname = path.join(basedir, os.matchname(m))
if fname:match(mask) == fname then
table.insert(result, fname)
end
end
end
os.matchdone(m)
-- check subdirectories
if recurse then
m = os.matchstart(wildcard)
while (os.matchnext(m)) do
if not os.matchisfile(m) then
local dirname = os.matchname(m)
matchwalker(path.join(basedir, dirname))
end
end
os.matchdone(m)
end
end
matchwalker(basedir)
end
function os.matchdirs(...)
local result = { }
for _, mask in ipairs(arg) do
domatch(result, mask, false)
end
return result
end
function os.matchfiles(...)
local result = { }
for _, mask in ipairs(arg) do
domatch(result, mask, true)
end
return result
end
--
-- An overload of the os.mkdir() function, which will create any missing
-- subdirectories along the path.
--
local builtin_mkdir = os.mkdir
function os.mkdir(p)
local dir = iif(p:startswith("/"), "/", "")
for part in p:gmatch("[^/]+") do
dir = dir .. part
if (part ~= "" and not path.isabsolute(part) and not os.isdir(dir)) then
local ok, err = builtin_mkdir(dir)
if (not ok) then
return nil, err
end
end
dir = dir .. "/"
end
return true
end
--
-- Run a shell command and return the output.
--
function os.outputof(cmd)
local pipe = io.popen(cmd)
local result = pipe:read('*a')
pipe:close()
return result
end
--
-- Remove a directory, along with any contained files or subdirectories.
--
local builtin_rmdir = os.rmdir
function os.rmdir(p)
-- recursively remove subdirectories
local dirs = os.matchdirs(p .. "/*")
for _, dname in ipairs(dirs) do
os.rmdir(dname)
end
-- remove any files
local files = os.matchfiles(p .. "/*")
for _, fname in ipairs(files) do
os.remove(fname)
end
-- remove this directory
builtin_rmdir(p)
end
|
Fixed broken lib search path from last commit (h/t coh)
|
Fixed broken lib search path from last commit (h/t coh)
|
Lua
|
bsd-3-clause
|
dimitarcl/premake-dev,dimitarcl/premake-dev,dimitarcl/premake-dev
|
00b21d845d18a0e6dd9df1665bd5c3037147e264
|
deps/semver.lua
|
deps/semver.lua
|
exports.name = "creationix/semver"
exports.version = "1.0.2"
local parse, normalize, match
-- Make the module itself callable
setmetatable(exports, {
__call = function (_, ...)
return match(...)
end
})
function parse(version)
if not version then return end
return
assert(tonumber(string.match(version, "^v?(%d+)")), "Not a semver"),
tonumber(string.match(version, "^v?%d+%.(%d+)") or 0),
tonumber(string.match(version, "^v?%d+%.%d+%.(%d+)") or 0),
tonumber(string.match(version, "^v?%d+%.%d+%.%d+-(%d+)") or 0)
end
exports.parse = parse
function normalize(version)
if not version then return "*" end
local a, b, c, d = parse(version)
return a .. '.' .. b .. '.' .. c .. (d > 0 and ('-' .. d) or (''))
end
exports.normalize = normalize
-- Return true is first is greater than ot equal to the second
-- nil counts as lowest value in this case
function exports.gte(first, second)
if not second or first == second then return true end
if not first then return false end
local a, b, c, x = parse(second)
local d, e, f, y = parse(first)
return (d > a) or (d == a and (e > b or (e == b and (f > c or (f == c and y > x)))))
end
-- Sanity check for gte code
assert(exports.gte(nil, nil))
assert(exports.gte("0.0.0", nil))
assert(exports.gte("9.9.9", "9.9.9"))
assert(exports.gte("9.9.10", "9.9.9"))
assert(exports.gte("9.10.0", "9.9.99"))
assert(exports.gte("10.0.0", "9.99.99"))
assert(exports.gte("10.0.0-1", "10.0.0-0"))
assert(exports.gte("10.0.1-0", "10.0.0-0"))
assert(exports.gte("10.0.1", "10.0.0-10"))
assert(not exports.gte(nil, "0.0.0"))
assert(not exports.gte("9.9.9", "9.9.10"))
assert(not exports.gte("9.9.99", "9.10.0"))
assert(not exports.gte("9.99.99", "10.0.0"))
assert(not exports.gte("10.0.0-0", "10.0.0-1"))
-- Given a semver string in the format a.b.c, and a list of versions in the
-- same format, return the newest version that is compatable.
-- For all versions, don't match anything older than minumum.
-- For 0.0.z-b, only match build updates
-- For 0.y.z-b, match patch and build updates
-- For x.y.z-b, match minor, patch, and build updates
-- If there is no minumum, grab the absolute maximum.
function match(version, iterator)
-- Major Minor Patch Build
-- found a b c x
-- possible d e f y
-- minimum g h i z
local a, b, c, x
if not version then
-- With an empty match, simply grab the newest version
for possible in iterator do
local d, e, f, y = parse(possible)
if (not a) or (d > a) or (d == a and (e > b or (e == b and (f > c or (f == c and y >= x))))) then
a, b, c, x = d, e, f, y
end
end
else
local g, h, i, z = parse(version)
if g > 0 then
-- From 1.0.0 and onward, minor updates are allowed since they mean non-
-- breaking changes or additons.
for possible in iterator do
local d, e, f, y = parse(possible)
-- Must be gte the minimum, but match major version. If this is the
-- first match, keep it, otherwise, make sure it's better than the last
-- match.
if d == g and (e > h or (e == h and (f > i or (f == i and y >= z)))) and
((not a) or e > b or (e == b and (f > c or (f == c and y > x)))) then
a, b, c, x = d, e, f, y
end
end
elseif h > 0 then
-- Before 1.0.0 we only allow patch updates assuming less stability at
-- this period.
for possible in iterator do
local d, e, f, y = parse(possible)
-- Must be gte the minumum, but match major and minor versions.
if d == g and e == h and (f > i or (f == i and y >= z)) and
((not a) or f > c or (f == c and y > x)) then
a, b, c, x = d, e, f, y
end
end
else
-- Before 0.1.0 we assume even less stability and only update new builds
for possible in iterator do
local d, e, f, y = parse(possible)
-- Must match major, minor, and patch, only allow build updates
if d == g and e == h and f == i and y >= z and
((not a) or y > x) then
a, b, c, x = d, e, f, y
end
end
end
end
return a and (a .. '.' .. b .. '.' .. c .. (x > 0 and ('-' .. x) or ('')))
end
exports.match = match
local function iterator()
local versions = {
"0.0.1",
"0.0.2",
"0.0.3", "0.0.3-1", "0.0.3-2",
"0.0.4",
"0.1.0", "0.1.1",
"0.2.0", "0.2.1",
"0.3.0", "0.3.0-1", "0.3.0-2", "0.3.1",
"0.4.0", "0.4.0-1", "0.4.0-2",
"1.0.0", "1.1.0", "1.1.3",
"2.0.0", "2.1.2",
"3.1.4",
"4.0.0", "4.0.0-1", "4.0.0-2", "4.0.1",
"5.0.0", "5.0.0-1", "5.0.0-2",
"6.0.0", "6.0.0-1", "6.1.0",
}
local i = 0
return function ()
i = i + 1
return versions[i]
end
end
-- Sanity check for match code
assert(match("0.0.1", iterator()) == "0.0.1")
assert(match("0.0.3", iterator()) == "0.0.3-2")
assert(match("0.1.0", iterator()) == "0.1.1")
assert(match("0.1.0-1", iterator()) == "0.1.1")
assert(match("0.2.0", iterator()) == "0.2.1")
assert(not match("0.5.0", iterator()))
assert(match("1.0.0", iterator()) == "1.1.3")
assert(match("1.0.0-1", iterator()) == "1.1.3")
assert(not match("1.1.4", iterator()))
assert(not match("1.2.0", iterator()))
assert(match("2.0.0", iterator()) == "2.1.2")
assert(not match("2.1.3", iterator()))
assert(not match("2.2.0", iterator()))
assert(match("3.0.0", iterator()) == "3.1.4")
assert(not match("3.1.5", iterator()))
assert(match(nil, iterator()) == "6.1.0")
|
exports.name = "creationix/semver"
exports.version = "1.0.2"
local parse, normalize, match
-- Make the module itself callable
setmetatable(exports, {
__call = function (_, ...)
return match(...)
end
})
function parse(version)
if not version then return end
return
assert(tonumber(string.match(version, "^v?(%d+)")), "Not a semver"),
tonumber(string.match(version, "^v?%d+%.(%d+)") or 0),
tonumber(string.match(version, "^v?%d+%.%d+%.(%d+)") or 0),
tonumber(string.match(version, "^v?%d+%.%d+%.%d+-(%d+)") or 0)
end
exports.parse = parse
function normalize(version)
if not version then return "*" end
local a, b, c, d = parse(version)
return a .. '.' .. b .. '.' .. c .. (d > 0 and ('-' .. d) or (''))
end
exports.normalize = normalize
-- Return true is first is greater than ot equal to the second
-- nil counts as lowest value in this case
function exports.gte(first, second)
if not second or first == second then return true end
if not first then return false end
local a, b, c, x = parse(second)
local d, e, f, y = parse(first)
return (d > a) or (d == a and (e > b or (e == b and (f > c or (f == c and y >= x)))))
end
-- Sanity check for gte code
assert(exports.gte(nil, nil))
assert(exports.gte("0.0.0", nil))
assert(exports.gte("9.9.9", "9.9.9"))
assert(exports.gte("1.2.3", "1.2.3-0"))
assert(exports.gte("1.2.3-4", "1.2.3-4"))
assert(exports.gte("9.9.10", "9.9.9"))
assert(exports.gte("9.10.0", "9.9.99"))
assert(exports.gte("10.0.0", "9.99.99"))
assert(exports.gte("10.0.0-1", "10.0.0-0"))
assert(exports.gte("10.0.1-0", "10.0.0-0"))
assert(exports.gte("10.0.1", "10.0.0-10"))
assert(not exports.gte(nil, "0.0.0"))
assert(not exports.gte("9.9.9", "9.9.10"))
assert(not exports.gte("9.9.99", "9.10.0"))
assert(not exports.gte("9.99.99", "10.0.0"))
assert(not exports.gte("10.0.0-0", "10.0.0-1"))
-- Given a semver string in the format a.b.c, and a list of versions in the
-- same format, return the newest version that is compatable.
-- For all versions, don't match anything older than minumum.
-- For 0.0.z-b, only match build updates
-- For 0.y.z-b, match patch and build updates
-- For x.y.z-b, match minor, patch, and build updates
-- If there is no minumum, grab the absolute maximum.
function match(version, iterator)
-- Major Minor Patch Build
-- found a b c x
-- possible d e f y
-- minimum g h i z
local a, b, c, x
if not version then
-- With an empty match, simply grab the newest version
for possible in iterator do
local d, e, f, y = parse(possible)
if (not a) or (d > a) or (d == a and (e > b or (e == b and (f > c or (f == c and y >= x))))) then
a, b, c, x = d, e, f, y
end
end
else
local g, h, i, z = parse(version)
if g > 0 then
-- From 1.0.0 and onward, minor updates are allowed since they mean non-
-- breaking changes or additons.
for possible in iterator do
local d, e, f, y = parse(possible)
-- Must be gte the minimum, but match major version. If this is the
-- first match, keep it, otherwise, make sure it's better than the last
-- match.
if d == g and (e > h or (e == h and (f > i or (f == i and y >= z)))) and
((not a) or e > b or (e == b and (f > c or (f == c and y > x)))) then
a, b, c, x = d, e, f, y
end
end
elseif h > 0 then
-- Before 1.0.0 we only allow patch updates assuming less stability at
-- this period.
for possible in iterator do
local d, e, f, y = parse(possible)
-- Must be gte the minumum, but match major and minor versions.
if d == g and e == h and (f > i or (f == i and y >= z)) and
((not a) or f > c or (f == c and y > x)) then
a, b, c, x = d, e, f, y
end
end
else
-- Before 0.1.0 we assume even less stability and only update new builds
for possible in iterator do
local d, e, f, y = parse(possible)
-- Must match major, minor, and patch, only allow build updates
if d == g and e == h and f == i and y >= z and
((not a) or y > x) then
a, b, c, x = d, e, f, y
end
end
end
end
return a and (a .. '.' .. b .. '.' .. c .. (x > 0 and ('-' .. x) or ('')))
end
exports.match = match
local function iterator()
local versions = {
"0.0.1",
"0.0.2",
"0.0.3", "0.0.3-1", "0.0.3-2",
"0.0.4",
"0.1.0", "0.1.1",
"0.2.0", "0.2.1",
"0.3.0", "0.3.0-1", "0.3.0-2", "0.3.1",
"0.4.0", "0.4.0-1", "0.4.0-2",
"1.0.0", "1.1.0", "1.1.3",
"2.0.0", "2.1.2",
"3.1.4",
"4.0.0", "4.0.0-1", "4.0.0-2", "4.0.1",
"5.0.0", "5.0.0-1", "5.0.0-2",
"6.0.0", "6.0.0-1", "6.1.0",
}
local i = 0
return function ()
i = i + 1
return versions[i]
end
end
-- Sanity check for match code
assert(match("0.0.1", iterator()) == "0.0.1")
assert(match("0.0.3", iterator()) == "0.0.3-2")
assert(match("0.1.0", iterator()) == "0.1.1")
assert(match("0.1.0-1", iterator()) == "0.1.1")
assert(match("0.2.0", iterator()) == "0.2.1")
assert(not match("0.5.0", iterator()))
assert(match("1.0.0", iterator()) == "1.1.3")
assert(match("1.0.0-1", iterator()) == "1.1.3")
assert(not match("1.1.4", iterator()))
assert(not match("1.2.0", iterator()))
assert(match("2.0.0", iterator()) == "2.1.2")
assert(not match("2.1.3", iterator()))
assert(not match("2.2.0", iterator()))
assert(match("3.0.0", iterator()) == "3.1.4")
assert(not match("3.1.5", iterator()))
assert(match(nil, iterator()) == "6.1.0")
|
Fix edge equality test
|
Fix edge equality test
|
Lua
|
apache-2.0
|
squeek502/lit,DBarney/lit,zhaozg/lit,kaustavha/lit,lduboeuf/lit,kidaa/lit,james2doyle/lit,1yvT0s/lit,luvit/lit
|
8ec945b0c04f5dabdd7aecf46eefadcdde3b9133
|
src/romdisk/samples/main.lua
|
src/romdisk/samples/main.lua
|
local button = require("button")
local scene1 = require("scene1")
local scene2 = require("scene2")
local scene_manager = require("scene_manager")
require("easing")
----------------------------------------------------------------------------------
local runtime = display_object:new("runtime")
local background = display_image:new("/romdisk/samples/images/background.png")
runtime:add_child(background)
local s1 = scene1:new()
local s2 = scene2:new()
s1:setanchor(800 / 2, 480 / 2)
s2:setanchor(800 / 2, 480 / 2)
local sm = scene_manager:new({
["s1"] = s1,
["s2"] = s2,
})
runtime:add_child(sm)
local scenes = {"s1", "s2"}
local currentScene = 1
local function nextScene()
local next = scenes[currentScene]
currentScene = currentScene + 1
if currentScene > #scenes then
currentScene = 1
end
return next
end
-- create the up and down sprites for the button
local normal = display_image:new("/romdisk/samples/images/button_normal.png")
local active = display_image:new("/romdisk/samples/images/button_active.png")
local btn = button:new(normal, active)
btn:add_event_listener("click", function(d, e)
sm:changeScene(nextScene(), 1, scene_manager.moveFromLeft, easing.outBounce)
-- d:scale(1.1, 1.1)
-- d:setalpha(0.2)
end, btn)
btn:setxy(40, 200)
btn:setanchor(btn.x + btn.width / 2, btn.y + btn.height / 2)
runtime:add_child(btn)
local cursor = display_image:new("/romdisk/samples/images/cursor.png", 0, 0)
cursor:add_event_listener(event.MOUSE_DOWN, function(d, e) d:setxy(e.info.x, e.info.y) end, cursor)
cursor:add_event_listener(event.MOUSE_MOVE, function(d, e) d:setxy(e.info.x, e.info.y) end, cursor)
cursor:add_event_listener(event.MOUSE_UP, function(d, e) d:setxy(e.info.x, e.info.y) end, cursor)
cursor:add_event_listener(event.TOUCHES_BEGIN, function(d, e) d:setxy(e.info.x, e.info.y) end, cursor)
cursor:add_event_listener(event.TOUCHES_MOVE, function(d, e) d:setxy(e.info.x, e.info.y) end, cursor)
cursor:add_event_listener(event.TOUCHES_END, function(d, e) d:setxy(e.info.x, e.info.y) end, cursor)
cursor:add_event_listener(event.TOUCHES_CANCEL, function(d, e) d:setxy(e.info.x, e.info.y) end, cursor)
runtime:add_child(cursor)
------------------- main --------------------------------
local stopwatch = buildin_stopwatch.new()
local cs1 = buildin_cairo.xboot_surface_create()
local cs2 = buildin_cairo.xboot_surface_create()
local cr1 = buildin_cairo.create(cs1)
local cr2 = buildin_cairo.create(cs2)
local index = false;
timer:new(1 / 60, 0, function(t, e)
local cr
index = not index
if index then
cr = cr2
else
cr = cr1
end
runtime:render(cr, event:new(event.ENTER_FRAME))
if index then
cs2:present()
else
cs1:present()
end
end)
while true do
stopwatch:reset()
local info = buildin_event.pump()
if info ~= nil then
local e = event:new(info.type, info)
runtime:dispatch(e)
end
timer:schedule(stopwatch:elapsed())
end
|
local button = require("button")
local scene1 = require("scene1")
local scene2 = require("scene2")
local scene_manager = require("scene_manager")
require("easing")
----------------------------------------------------------------------------------
local runtime = display_object:new("runtime")
local background = display_image:new("/romdisk/samples/images/background.png")
runtime:add_child(background)
local s1 = scene1:new()
local s2 = scene2:new()
s1:setanchor(800 / 2, 480 / 2)
s2:setanchor(800 / 2, 480 / 2)
local sm = scene_manager:new({
["s1"] = s1,
["s2"] = s2,
})
runtime:add_child(sm)
local scenes = {"s1", "s2"}
local currentScene = 1
local function nextScene()
local next = scenes[currentScene]
currentScene = currentScene + 1
if currentScene > #scenes then
currentScene = 1
end
return next
end
-- create the up and down sprites for the button
local normal = display_image:new("/romdisk/samples/images/button_normal.png")
local active = display_image:new("/romdisk/samples/images/button_active.png")
local btn = button:new(normal, active)
btn:add_event_listener("click", function(d, e)
sm:changeScene(nextScene(), 1, scene_manager.moveFromLeft, easing.outBounce)
-- d:scale(1.1, 1.1)
-- d:setalpha(0.2)
end, btn)
btn:setxy(40, 200)
btn:setanchor(btn.x + btn.width / 2, btn.y + btn.height / 2)
runtime:add_child(btn)
local cursor = display_image:new("/romdisk/samples/images/cursor.png", 0, 0)
cursor:add_event_listener(event.MOUSE_DOWN, function(d, e) d:setxy(e.info.x, e.info.y) end, cursor)
cursor:add_event_listener(event.MOUSE_MOVE, function(d, e) d:setxy(e.info.x, e.info.y) end, cursor)
cursor:add_event_listener(event.MOUSE_UP, function(d, e) d:setxy(e.info.x, e.info.y) end, cursor)
cursor:add_event_listener(event.TOUCHES_BEGIN, function(d, e) d:setxy(e.info.x, e.info.y) end, cursor)
cursor:add_event_listener(event.TOUCHES_MOVE, function(d, e) d:setxy(e.info.x, e.info.y) end, cursor)
cursor:add_event_listener(event.TOUCHES_END, function(d, e) d:setxy(e.info.x, e.info.y) end, cursor)
cursor:add_event_listener(event.TOUCHES_CANCEL, function(d, e) d:setxy(e.info.x, e.info.y) end, cursor)
runtime:add_child(cursor)
------------------- main --------------------------------
local cs1 = buildin_cairo.xboot_surface_create()
local cs2 = buildin_cairo.xboot_surface_create()
local cr1 = buildin_cairo.create(cs1)
local cr2 = buildin_cairo.create(cs2)
local index = false;
timer:new(1 / 60, 0, function(t, e)
local cr
index = not index
if index then
cr = cr2
else
cr = cr1
end
runtime:render(cr, event:new(event.ENTER_FRAME))
if index then
cs2:present()
else
cs1:present()
end
end)
local sw = buildin_stopwatch.new()
while true do
local info = buildin_event.pump()
if info ~= nil then
local e = event:new(info.type, info)
runtime:dispatch(e)
end
local elapsed = sw:elapsed()
if elapsed ~= 0 then
sw:reset()
timer:schedule(elapsed)
end
end
|
fix main.lua
|
fix main.lua
|
Lua
|
mit
|
xboot/xboot,xboot/xboot
|
14cbc2c6690ec6e6ac1c79afc0f1ce167969ac0d
|
luci-access-control/luasrc/model/cbi/access_control.lua
|
luci-access-control/luasrc/model/cbi/access_control.lua
|
--[[
LuCI - Lua Configuration Interface - Internet access control
Copyright 2015 Krzysztof Szuster.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local CONFIG_FILE_RULES = "firewall"
local CONFIG_FILE_AC = "access_control"
local ma, mr, s, o
ma = Map(CONFIG_FILE_AC, translate("Internet Access Control"),
translate("Access Control allows you to manage internet access for specific local hosts."))
if CONFIG_FILE_AC==CONFIG_FILE_RULES then
mr = ma
else
mr = Map(CONFIG_FILE_RULES)
end
---------------------------------------------------------------------------------------------
-- General switch
--s = ma:section(TypedSection, "access_control", "General settings")
-- s.anonymous = true
s = ma:section(NamedSection, "general", "access_control", "General settings")
o = s:option(Flag, "enabled", translate("Enabled"))
o.rmempty = false
---------------------------------------------------------------------------------------------
-- Rule table
s = mr:section(TypedSection, "rule", translate("Client Rules"))
s.addremove = true
s.anonymous = true
-- s.sortable = true
s.template = "cbi/tblsection"
-- hidden, constant options
s.defaults.enabled = "0"
s.defaults.src = "*" --"lan", "guest" or enything on local side
s.defaults.dest = "wan"
s.defaults.target = "REJECT"
s.defaults.proto = "0"
s.defaults.extra = "--kerneltz"
-- only AC-related rules
s.filter = function(self, section)
return self.map:get (section, "ac_enabled") ~= nil
end
o = s:option(Flag, "ac_enabled", translate("Enabled"))
o.default = '1'
o.rmempty = false
-- ammend "enabled" option
function o.write(self, section, value)
local s = "cbid.access_control.general.enabled"
local global_enable = luci.http.formvalue(s)
if global_enable == "1" then
self.map:set(section, "enabled", value)
io.stderr:write("set "..value.."\n")
else
self.map:set(section, "enabled", "0")
io.stderr:write("reset\n")
-- if global_enable == nil then
-- ma.uci:section(CONFIG_FILE_AC, "access_control", "general",
-- { enabled = "0" })
-- ma.uci:commit(CONFIG_FILE_AC)
-- end
end
-- self.map:set(section, "src", "*")
-- self.map:set(section, "dest", "wan")
-- self.map:set(section, "target", "REJECT")
-- self.map:set(section, "proto", "0")
-- self.map:set(section, "extra", "--kerneltz")
return Flag.write(self, section, value)
end
o = s:option(Value, "name", "Description")
o.rmempty = false -- force validate
-- better validate, then: o.datatype = "minlength(1)"
o.validate = function(self, val, sid)
if type(val) ~= "string" or #val == 0 then
return nil, translate("Name must be specified!")
end
return val
end
o = s:option(Value, "src_mac", "MAC address")
o.rmempty = false
o.datatype = "macaddr"
luci.sys.net.mac_hints(function(mac, name)
o:value(mac, "%s (%s)" %{ mac, name })
end)
function validate_time(self, value, section)
local hh, mm
hh,mm = string.match (value, "^(%d?%d):(%d%d)$")
hh = tonumber (hh)
mm = tonumber (mm)
if hh and mm and hh <= 23 and mm <= 60 then
return value
else
return nil, "Time value must be HH:MM or empty"
end
end
o = s:option(Value, "start_time", "Start time")
o.rmempty = true -- do not validae blank
o.validate = validate_time
o = s:option(Value, "stop_time", "End time")
o.rmempty = true -- do not validae blank
o.validate = validate_time
if CONFIG_FILE_AC==CONFIG_FILE_RULES then
return ma
else
return ma, mr
end
|
--[[
LuCI - Lua Configuration Interface - Internet access control
Copyright 2015 Krzysztof Szuster <@openwrt.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local CONFIG_FILE_RULES = "firewall"
local CONFIG_FILE_AC = "access_control"
local ma, mr, s, o
ma = Map(CONFIG_FILE_AC, translate("Internet Access Control"),
translate("Access Control allows you to manage internet access for specific local hosts."))
if CONFIG_FILE_AC==CONFIG_FILE_RULES then
mr = ma
else
mr = Map(CONFIG_FILE_RULES)
end
---------------------------------------------------------------------------------------------
-- General switch
--s = ma:section(TypedSection, "access_control", "General settings")
-- s.anonymous = true
s = ma:section(NamedSection, "general", "access_control", "General settings")
o = s:option(Flag, "enabled", translate("Enabled"))
o.rmempty = false
---------------------------------------------------------------------------------------------
-- Rule table
s = mr:section(TypedSection, "rule", translate("Client Rules"))
s.addremove = true
s.anonymous = true
-- s.sortable = true
s.template = "cbi/tblsection"
-- hidden, constant options
s.defaults.enabled = "0"
s.defaults.src = "*" --"lan", "guest" or enything on local side
s.defaults.dest = "wan"
s.defaults.target = "REJECT"
s.defaults.proto = "0"
s.defaults.extra = "--kerneltz"
-- only AC-related rules
s.filter = function(self, section)
return self.map:get (section, "ac_enabled") ~= nil
end
o = s:option(Flag, "ac_enabled", translate("Enabled"))
o.default = '1'
o.rmempty = false
-- ammend "enabled" option
function o.write(self, section, value)
local s = "cbid.access_control.general.enabled"
local global_enable = luci.http.formvalue(s)
if global_enable == "1" then
self.map:set(section, "enabled", value)
io.stderr:write("set "..value.."\n")
else
self.map:set(section, "enabled", "0")
io.stderr:write("reset\n")
-- if global_enable == nil then
-- ma.uci:section(CONFIG_FILE_AC, "access_control", "general",
-- { enabled = "0" })
-- ma.uci:commit(CONFIG_FILE_AC)
-- end
end
-- self.map:set(section, "src", "*")
-- self.map:set(section, "dest", "wan")
-- self.map:set(section, "target", "REJECT")
-- self.map:set(section, "proto", "0")
-- self.map:set(section, "extra", "--kerneltz")
return Flag.write(self, section, value)
end
o = s:option(Value, "name", "Description")
o.rmempty = false -- force validate
-- better validate, then: o.datatype = "minlength(1)"
o.validate = function(self, val, sid)
if type(val) ~= "string" or #val == 0 then
return nil, translate("Name must be specified!")
end
return val
end
o = s:option(Value, "src_mac", "MAC address")
o.rmempty = false
o.datatype = "macaddr"
luci.sys.net.mac_hints(function(mac, name)
o:value(mac, "%s (%s)" %{ mac, name })
end)
function validate_time(self, value, section)
local hh, mm
hh,mm = string.match (value, "^(%d?%d):(%d%d)$")
hh = tonumber (hh)
mm = tonumber (mm)
if hh and mm and hh <= 23 and mm <= 60 then
return value
else
return nil, "Time value must be HH:MM or empty"
end
end
o = s:option(Value, "start_time", "Start time")
o.rmempty = true -- do not validae blank
o.validate = validate_time
o.size = 5
o = s:option(Value, "stop_time", "End time")
o.rmempty = true -- do not validae blank
o.validate = validate_time
o.size = 5
if CONFIG_FILE_AC==CONFIG_FILE_RULES then
return ma
else
return ma, mr
end
|
minor fix in screen layout
|
minor fix in screen layout
|
Lua
|
apache-2.0
|
k-szuster/luci-access-control
|
73376d66c1a76a8d39faa7d24884b60ab6976b88
|
check/plugin.lua
|
check/plugin.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.
--]]
--[[
Module for running custom agent plugins written in an arbitrary programing
/ scripting language. This module is backward compatibile with Cloudkick agent
plugins (https://support.cloudkick.com/Creating_a_plugin).
All the plugins must output information to the standard output in the
format defined bellow:
status <status string>
metric <name 1> <type> <value> [<unit>]
metric <name 2> <type> <value> [<unit>]
metric <name 3> <type> <value> [<unit>]
* <status string> - A status string which includes a summary of the results.
* <name> Name of the metric. No spaces are allowed. If a name contains a dot,
string before the dot is considered to be a metric dimension.
* <type> - Metric type which can be one of:
* string
* gauge
* float
* int
* [<unit>] - Metric unit, optional. A string representing the units of the metric
measurement. Units may only be provided on non-string metrics, and may not
contain any spaces. Examples: 'bytes', 'milliseconds', 'percent'.
--]]
local table = require('table')
local childprocess = require('childprocess')
local timer = require('timer')
local path = require('path')
local string = require('string')
local fmt = string.format
local logging = require('logging')
local LineEmitter = require('line-emitter').LineEmitter
local ChildCheck = require('./base').ChildCheck
local CheckResult = require('./base').CheckResult
local Metric = require('./base').Metric
local split = require('/base/util/misc').split
local tableContains = require('/base/util/misc').tableContains
local lastIndexOf = require('/base/util/misc').lastIndexOf
local constants = require('/constants')
local loggingUtil = require('/base/util/logging')
local toString = require('/base/util/misc').toString
local PluginCheck = ChildCheck:extend()
--[[
Constructor.
params.details - Table with the following keys:
- file (string) - Name of the plugin file.
- args (table) - Command-line arguments which get passed to the plugin.
- timeout (number) - Plugin execution timeout in milliseconds.
--]]
function PluginCheck:initialize(params)
ChildCheck.initialize(self, params)
if params.details.file == nil then
params.details.file = ''
end
local file = path.basename(params.details.file)
local args = params.details.args and params.details.args or {}
local timeout = params.details.timeout and params.details.timeout or constants:get('DEFAULT_PLUGIN_TIMEOUT')
self._file = file
self._pluginPath = path.join(constants:get('DEFAULT_CUSTOM_PLUGINS_PATH'), file)
self._pluginArgs = args
self._timeout = timeout
self._log = loggingUtil.makeLogger(fmt('(plugin=%s, id=%s, iid=%s)', file, self.id, self._iid))
end
function PluginCheck:toString()
if not self._pluginArgs then
self._pluginArgs = {}
end
local argString = table.concat(self._pluginArgs, ',')
if argString == '' then
argString = '(none)'
end
return fmt('%s (id=%s, period=%ss, file=%s, args=%s)', self.getType(), self.id, self.period, self._file, argString)
end
function PluginCheck:getType()
return 'agent.plugin'
end
function PluginCheck:run(callback)
local exePath = self._pluginPath
local exeArgs = self._pluginArgs
local ext = path.extname(exePath)
if virgo.win32_get_associated_exe ~= nil and ext ~= "" then
-- If we are on windows, we want to suport custom plugins like "foo.py",
-- but this means we need to map the .py file ending to the Python Executable,
-- and mutate our run path to be like: C:/Python27/python.exe custom_plugins_path/foo.py
local assocExe, err = virgo.win32_get_associated_exe(ext)
if assocExe ~= nil then
table.insert(exeArgs, 1, self._pluginPath)
exePath = assocExe
else
self._log(logging.WARNING, fmt('error getting associated executable for "%s": %s', ext, err))
end
end
local cenv = self:_childEnv()
local child = self:_runChild(exePath, exeArgs, cenv, callback)
if child.stdin._closed ~= true then
child.stdin:close()
end
end
local exports = {}
exports.PluginCheck = PluginCheck
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.
--]]
--[[
Module for running custom agent plugins written in an arbitrary programing
/ scripting language. This module is backward compatibile with Cloudkick agent
plugins (https://support.cloudkick.com/Creating_a_plugin).
All the plugins must output information to the standard output in the
format defined bellow:
status <status string>
metric <name 1> <type> <value> [<unit>]
metric <name 2> <type> <value> [<unit>]
metric <name 3> <type> <value> [<unit>]
* <status string> - A status string which includes a summary of the results.
* <name> Name of the metric. No spaces are allowed. If a name contains a dot,
string before the dot is considered to be a metric dimension.
* <type> - Metric type which can be one of:
* string
* gauge
* float
* int
* [<unit>] - Metric unit, optional. A string representing the units of the metric
measurement. Units may only be provided on non-string metrics, and may not
contain any spaces. Examples: 'bytes', 'milliseconds', 'percent'.
--]]
local table = require('table')
local childprocess = require('childprocess')
local timer = require('timer')
local path = require('path')
local string = require('string')
local fmt = string.format
local logging = require('logging')
local LineEmitter = require('line-emitter').LineEmitter
local ChildCheck = require('./base').ChildCheck
local CheckResult = require('./base').CheckResult
local Metric = require('./base').Metric
local split = require('/base/util/misc').split
local tableContains = require('/base/util/misc').tableContains
local lastIndexOf = require('/base/util/misc').lastIndexOf
local constants = require('/constants')
local loggingUtil = require('/base/util/logging')
local toString = require('/base/util/misc').toString
local PluginCheck = ChildCheck:extend()
--[[
Constructor.
params.details - Table with the following keys:
- file (string) - Name of the plugin file.
- args (table) - Command-line arguments which get passed to the plugin.
- timeout (number) - Plugin execution timeout in milliseconds.
--]]
function PluginCheck:initialize(params)
ChildCheck.initialize(self, params)
if params.details.file == nil then
params.details.file = ''
end
local file = path.basename(params.details.file)
local args = params.details.args and params.details.args or {}
local timeout = params.details.timeout and params.details.timeout or constants:get('DEFAULT_PLUGIN_TIMEOUT')
self._file = file
self._pluginPath = path.join(constants:get('DEFAULT_CUSTOM_PLUGINS_PATH'), file)
self._pluginArgs = args
self._timeout = timeout
self._log = loggingUtil.makeLogger(fmt('(plugin=%s, id=%s, iid=%s)', file, self.id, self._iid))
end
function PluginCheck:toString()
if not self._pluginArgs then
self._pluginArgs = {}
end
local argString = table.concat(self._pluginArgs, ',')
if argString == '' then
argString = '(none)'
end
return fmt('%s (id=%s, period=%ss, timeout=%ss, file=%s, args=%s)',
self.getType(),
self.id,
self.period,
self._timeout,
self._file,
argString)
end
function PluginCheck:getType()
return 'agent.plugin'
end
function PluginCheck:run(callback)
local exePath = self._pluginPath
local exeArgs = self._pluginArgs
local ext = path.extname(exePath)
if virgo.win32_get_associated_exe ~= nil and ext ~= "" then
-- If we are on windows, we want to suport custom plugins like "foo.py",
-- but this means we need to map the .py file ending to the Python Executable,
-- and mutate our run path to be like: C:/Python27/python.exe custom_plugins_path/foo.py
local assocExe, err = virgo.win32_get_associated_exe(ext)
if assocExe ~= nil then
table.insert(exeArgs, 1, self._pluginPath)
exePath = assocExe
else
self._log(logging.WARNING, fmt('error getting associated executable for "%s": %s', ext, err))
end
end
local cenv = self:_childEnv()
local child = self:_runChild(exePath, exeArgs, cenv, callback)
if child.stdin._closed ~= true then
child.stdin:close()
end
end
local exports = {}
exports.PluginCheck = PluginCheck
return exports
|
fix(update-check): Plugin Timeouts
|
fix(update-check): Plugin Timeouts
|
Lua
|
apache-2.0
|
christopherjwang/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent
|
a006fa2047df5b6157334087d40ed2c2b316f3be
|
states/game.lua
|
states/game.lua
|
local Scene = require 'entities.scene'
local Dynamo = require 'entities.scenes.dynamo'
local Sprite = require 'entities.sprite'
local Bit = require 'bit'
local game = {}
function game:init()
self.dynamo = Dynamo:new()
self.scene = Scene:new()
self.catalogs = {
art = require 'catalogs.art',
}
self.isoSprite = love.graphics.newImage(self.catalogs.art.iso_tile)
self.shipBitmask = love.image.newImageData(self.catalogs.art.ship_bitmask)
-- Map (r, g, b) -> unique int
local function getColorHash(r, g, b)
return Bit.bor(Bit.lshift(r, 32), Bit.lshift(g, 16), b)
end
self.grid = {}
self.rooms = {}
self.enemies = {}
for x = 1, self.shipBitmask:getWidth() do
self.grid[x] = {}
self.rooms[x] = {}
self.enemies[x] = {}
for y = 1, self.shipBitmask:getHeight() do
local r, g, b, a = self.shipBitmask:getPixel(x - 1, y - 1)
self.grid[x][y] = 0
self.rooms[x][y] = 0
self.enemies[x][y] = 0
if not (r == 0 and g == 0 and b == 0 and a == 0) then
self.grid[x][y] = 1
self.rooms[x][y] = getColorHash(r, g, b)
end
end
end
self.gridX = love.graphics.getWidth()/2
self.gridY = love.graphics.getHeight()/2
self.gridWidth = #self.grid[1] -- tiles
self.gridHeight = #self.grid -- tiles
self.tileWidth = self.isoSprite:getWidth() -- pixels
self.tileHeight = self.isoSprite:getHeight() -- pixels
self.tileDepth = self.tileHeight / 2
self.scene:add{
hoverX = nil,
hoverY = nil,
update = function(self, dt)
local mx, my = love.mouse.getPosition()
local gx, gy, gw, gh = game:getGridBoundingBox()
local translatedX = gx - game.gridX + gw/2
local translatedY = gy - game.gridY + gh/2
mx = -translatedX - mx
my = -translatedY - my
mx = mx + game.tileWidth / 2
my = my + game.tileHeight
self.hoverX, self.hoverY = game:screenToGrid(-mx, -my)
end,
mousepressed = function(self, mx, my)
game.enemies[self.hoverX][self.hoverY] = 0
end,
draw = function(self)
love.graphics.print(self.hoverX .. ', ' .. self.hoverY, 10, 10)
love.graphics.push()
local gx, gy, gw, gh = game:getGridBoundingBox()
local translatedX = gx - game.gridX + gw/2
local translatedY = gy - game.gridY + gh/2
love.graphics.translate(-translatedX, -translatedY)
for x = 1, game.gridWidth do
for y = 1, game.gridHeight do
local roomNumber = game.rooms[x][y]
if x == self.hoverX and y == self.hoverY then
love.graphics.setColor(255, 0, 0)
elseif game.enemies[x][y] > 0 then
love.graphics.setColor(0, 255, 0)
elseif roomNumber > 0 then
love.graphics.setColor(255, 128, 255)
else
love.graphics.setColor(255, 255, 255)
end
tx, ty = game:gridToScreen(x, y)
local cellValue = game.grid[x][y]
if cellValue == 1 then
love.graphics.draw(game.isoSprite, tx, ty)
end
end
end
-- Grid bounding box
love.graphics.rectangle('line', gx, gy, gw, gh)
love.graphics.pop()
end,
}
-- Every so often add a new enemy
Timer.every(1, function()
local ex, ey
local enemy
local notAnEmptySpace
-- Locate empty square
repeat
ex = love.math.random(self.gridWidth)
ey = love.math.random(self.gridHeight)
enemy = self.enemies[ex][ey]
notAnEmptySpace = self.grid[ex][ey] > 0
until (enemy == 0 and notAnEmptySpace)
self.enemies[ex][ey] = 1
end)
end
function game:enter()
end
function game:update(dt)
self.scene:update(dt)
self.dynamo:update(dt)
end
function game:keypressed(key, code)
self.scene:keypressed(key, code)
self.dynamo:keypressed(key, code)
end
function game:keyreleased(key, code)
self.scene:keyreleased(key, code)
self.dynamo:keyreleased(key, code)
end
function game:mousepressed(x, y, mbutton)
self.scene:mousepressed(x, y, mbutton)
self.dynamo:mousepressed(x, y, mbutton)
end
function game:mousereleased(x, y, mbutton)
self.scene:mousereleased(x, y, mbutton)
self.dynamo:mousereleased(x, y, mbutton)
end
function game:mousemoved(x, y, dx, dy, istouch)
self.scene:mousemoved(x, y, dx, dy, istouch)
self.dynamo:mousemoved(x, y, dx, dy, istouch)
end
function game:draw()
self.scene:draw()
self.dynamo:draw()
end
function game:screenToGrid(sx, sy)
local gx = ((sx / (self.tileWidth / 2)) + (sy / (self.tileDepth / 2))) / 2 + 1
local gy = ((sy / (self.tileDepth / 2)) - (sx / (self.tileWidth / 2))) / 2 + 1
return Lume.round(gx), Lume.round(gy)
end
function game:gridToScreen(gx, gy)
local x = (gx - gy) * game.tileWidth / 2
local y = (gx + gy) * game.tileDepth / 2
return x, y
end
function game:getGridBoundingBox()
local xFudge = 0
local yFudge = 4
local w = self.gridWidth * self.tileWidth + xFudge
local h = self.gridHeight * self.tileDepth + yFudge
local x = -w/2 + self.tileWidth/2 - xFudge * 2
local y = self.tileHeight - yFudge * 2
return x, y, w, h
end
return game
|
local Scene = require 'entities.scene'
local Dynamo = require 'entities.scenes.dynamo'
local Sprite = require 'entities.sprite'
local Bit = require 'bit'
local game = {}
function game:init()
self.dynamo = Dynamo:new()
self.scene = Scene:new()
self.catalogs = {
art = require 'catalogs.art',
}
self.isoSprite = love.graphics.newImage(self.catalogs.art.iso_tile)
self.shipBitmask = love.image.newImageData(self.catalogs.art.ship_bitmask)
-- Map (r, g, b) -> unique int
local function getColorHash(r, g, b)
return Bit.bor(Bit.lshift(r, 32), Bit.lshift(g, 16), b)
end
self.grid = {}
self.rooms = {}
self.enemies = {}
for x = 1, self.shipBitmask:getWidth() do
self.grid[x] = {}
self.rooms[x] = {}
self.enemies[x] = {}
for y = 1, self.shipBitmask:getHeight() do
local r, g, b, a = self.shipBitmask:getPixel(x - 1, y - 1)
self.grid[x][y] = 0
self.rooms[x][y] = 0
self.enemies[x][y] = 0
if not (r == 0 and g == 0 and b == 0 and a == 0) then
self.grid[x][y] = 1
self.rooms[x][y] = getColorHash(r, g, b)
end
end
end
self.gridX = love.graphics.getWidth()/2
self.gridY = love.graphics.getHeight()/2
self.gridWidth = #self.grid[1] -- tiles
self.gridHeight = #self.grid -- tiles
self.tileWidth = self.isoSprite:getWidth() -- pixels
self.tileHeight = self.isoSprite:getHeight() -- pixels
self.tileDepth = self.tileHeight / 2
self.scene:add{
hoverX = nil,
hoverY = nil,
update = function(self, dt)
local mx, my = love.mouse.getPosition()
local gx, gy, gw, gh = game:getGridBoundingBox()
local translatedX = gx - game.gridX + gw/2
local translatedY = gy - game.gridY + gh/2
mx = -translatedX - mx
my = -translatedY - my
mx = mx + game.tileWidth / 2
my = my + game.tileHeight
self.hoverX, self.hoverY = game:screenToGrid(-mx, -my)
end,
mousepressed = function(self, mx, my)
if game.enemies[self.hoverX] and game.enemies[self.hoverX][self.hoverY] then
game.enemies[self.hoverX][self.hoverY] = 0
end
end,
draw = function(self)
love.graphics.print(self.hoverX .. ', ' .. self.hoverY, 10, 10)
love.graphics.push()
local gx, gy, gw, gh = game:getGridBoundingBox()
local translatedX = gx - game.gridX + gw/2
local translatedY = gy - game.gridY + gh/2
love.graphics.translate(-translatedX, -translatedY)
for x = 1, game.gridWidth do
for y = 1, game.gridHeight do
local roomNumber = game.rooms[x][y]
if x == self.hoverX and y == self.hoverY then
love.graphics.setColor(255, 0, 0)
elseif game.enemies[x][y] > 0 then
love.graphics.setColor(0, 255, 0)
elseif roomNumber > 0 then
love.graphics.setColor(255, 128, 255)
else
love.graphics.setColor(255, 255, 255)
end
tx, ty = game:gridToScreen(x, y)
local cellValue = game.grid[x][y]
if cellValue == 1 then
love.graphics.draw(game.isoSprite, tx, ty)
end
end
end
-- Grid bounding box
love.graphics.rectangle('line', gx, gy, gw, gh)
love.graphics.pop()
end,
}
-- Every so often add a new enemy
Timer.every(1, function()
local ex, ey
local enemy
local notAnEmptySpace
-- Locate empty square
repeat
ex = love.math.random(self.gridWidth)
ey = love.math.random(self.gridHeight)
enemy = self.enemies[ex][ey]
notAnEmptySpace = self.grid[ex][ey] > 0
until (enemy == 0 and notAnEmptySpace)
self.enemies[ex][ey] = 1
end)
end
function game:enter()
end
function game:update(dt)
self.scene:update(dt)
self.dynamo:update(dt)
end
function game:keypressed(key, code)
self.scene:keypressed(key, code)
self.dynamo:keypressed(key, code)
end
function game:keyreleased(key, code)
self.scene:keyreleased(key, code)
self.dynamo:keyreleased(key, code)
end
function game:mousepressed(x, y, mbutton)
self.scene:mousepressed(x, y, mbutton)
self.dynamo:mousepressed(x, y, mbutton)
end
function game:mousereleased(x, y, mbutton)
self.scene:mousereleased(x, y, mbutton)
self.dynamo:mousereleased(x, y, mbutton)
end
function game:mousemoved(x, y, dx, dy, istouch)
self.scene:mousemoved(x, y, dx, dy, istouch)
self.dynamo:mousemoved(x, y, dx, dy, istouch)
end
function game:draw()
self.scene:draw()
self.dynamo:draw()
end
function game:screenToGrid(sx, sy)
local gx = ((sx / (self.tileWidth / 2)) + (sy / (self.tileDepth / 2))) / 2 + 1
local gy = ((sy / (self.tileDepth / 2)) - (sx / (self.tileWidth / 2))) / 2 + 1
return Lume.round(gx), Lume.round(gy)
end
function game:gridToScreen(gx, gy)
local x = (gx - gy) * game.tileWidth / 2
local y = (gx + gy) * game.tileDepth / 2
return x, y
end
function game:getGridBoundingBox()
local xFudge = 0
local yFudge = 4
local w = self.gridWidth * self.tileWidth + xFudge
local h = self.gridHeight * self.tileDepth + yFudge
local x = -w/2 + self.tileWidth/2 - xFudge * 2
local y = self.tileHeight - yFudge * 2
return x, y, w, h
end
return game
|
Fix crash
|
Fix crash
|
Lua
|
mit
|
Nuthen/ludum-dare-39
|
3461ef584f91e17fd17d3ad36e408d64361aeb4b
|
yahoo-stobo.lua
|
yahoo-stobo.lua
|
#!./bin/lua
local inspect = require 'inspect'
local http = require 'socket.http'
local https = require 'ssl.https'
local cjson = require 'cjson'
local api_url = 'https://finance-yql.media.yahoo.com/v7/finance/chart/%s?period1=%s&period2=%s&interval=%s'
-- Quote
Quote = {} do
local numberOrNil = function(number)
if type(number) == 'number' then
return number
else
return 0
end
end
local floatToInt = function(number)
if type(number) == 'number' then
return math.floor(number)
end
end
function Quote.new(timestamp, open, low, high, close, volume)
local self = setmetatable({}, { __index = Quote })
local datetable = os.date('*t', timestamp)
self.datetime = ('%04d%02d%02d%02d%02d'):format(datetable.year,
datetable.month, datetable.day,
datetable.hour, datetable.min)
self.open = numberOrNil(open)
self.low = numberOrNil(low)
self.high = numberOrNil(high)
self.close = numberOrNil(close)
self.volume = floatToInt(numberOrNil(volume))
return self
end
end
-- Stock
Stock = {} do
function Stock.new(symbol)
local self = setmetatable({}, { __index = Stock })
self.symbol = symbol
self.quotes = {}
return self
end
function Stock:get(options)
local period_start = options and options.period_start or
os.time{year=2015, month=6, day=22, hour=10}
local period_stop = options and options.period_stop or
os.time()
local interval = options and options.interval or
'1m'
local url = (api_url):format(self.symbol, period_start, period_stop, interval)
local json = https.request(url)
local table = cjson.decode(json)
local result = table.chart.result[1]
local data = result.indicators.quote[1]
for i,timestamp in ipairs(result.timestamp) do
local quote = Quote.new(timestamp,
data.open[i],
data.low[i],
data.high[i],
data.close[i],
data.volume[i])
self.quotes[quote.datetime] = quote
end
return self
end
end
-- Main
do
local stock = Stock.new('TIMP3.SA'):get{ interval = '2m' }
for i,quote in pairs(stock.quotes) do
local result = ('%s - O: %.2f H: %.2f L: %.2f C: %.2f V: %s'):format(
quote.datetime, quote.open,
quote.high, quote.low,
quote.close, quote.volume)
print(result)
end
end
|
#!./bin/lua
local inspect = require 'inspect'
local http = require 'socket.http'
local https = require 'ssl.https'
local cjson = require 'cjson'
local api_url = 'https://finance-yql.media.yahoo.com/v7/finance/chart/%s?period1=%s&period2=%s&interval=%s'
-- Quote
Quote = {} do
local numberOrNil = function(number)
if type(number) == 'number' then
return number
else
return 0
end
end
local floatToInt = function(number)
if type(number) == 'number' then
return math.floor(number)
end
end
function Quote.new(timestamp, open, low, high, close, volume)
local self = setmetatable({}, { __index = Quote })
local datetable = os.date('*t', timestamp)
self.datetime = ('%04d%02d%02d%02d%02d'):format(datetable.year,
datetable.month, datetable.day,
datetable.hour, datetable.min)
self.open = numberOrNil(open)
self.low = numberOrNil(low)
self.high = numberOrNil(high)
self.close = numberOrNil(close)
self.volume = floatToInt(numberOrNil(volume))
return self
end
end
-- Stock
Stock = {} do
function Stock.new(symbol)
local self = setmetatable({}, { __index = Stock })
self.symbol = symbol
self.quotes = {}
return self
end
function Stock:get(options)
local period_start = options and options.period_start or
os.time{year=2015, month=6, day=22, hour=10}
local period_stop = options and options.period_stop or
os.time()
local interval = options and options.interval or
'1m'
local url = (api_url):format(self.symbol, period_start, period_stop, interval)
local json = https.request(url)
local jsontable = cjson.decode(json)
local result = jsontable.chart.result[1]
local data = result.indicators.quote[1]
for i,timestamp in ipairs(result.timestamp) do
local quote = Quote.new(timestamp,
data.open[i],
data.low[i],
data.high[i],
data.close[i],
data.volume[i])
table.insert(self.quotes, quote)
end
return self
end
end
-- Main
do
local stock = Stock.new('TIMP3.SA'):get{ interval = '2m' }
print(stock.symbol)
for i,quote in ipairs(stock.quotes) do
local result = ('%s - O: %.2f H: %.2f L: %.2f C: %.2f V: %s'):format(
quote.datetime, quote.open,
quote.high, quote.low,
quote.close, quote.volume)
print(result)
end
end
|
Fixing from yahoo order
|
Fixing from yahoo order
|
Lua
|
mit
|
henriquegogo/stobo,henriquegogo/stobo,henriquegogo/stobo,henriquegogo/stobo
|
c75df7121e12ecfd183c278cafba09ebddba13e9
|
assets/objects/enemy.lua
|
assets/objects/enemy.lua
|
local class = require 'libs.middleclass'
local Enemy = class('Enemy')
function Enemy:initialize(speed, width, height, x, y, spacing, enemy_table)
self.speed = speed
self.width = width
self.height = height
self.x = x
self.y = y
self.spacing = spacing
self.enemy_table = enemy_table
end
function Enemy:create()
if #self.enemy_table == 0 then
table.insert(self.enemy_table, {x = self.x, alive = true})
else
table.insert(self.enemy_table, {x = self.enemy_table[#self.enemy_table].x + self.spacing, alive = true})
end
end
function Enemy:checkCollision()
for i, enemy in ipairs(self.enemy_table) do
if enemy.x + self.width >= love.graphics.getWidth() then
self.y = self.y + self.spacing
enemy.x = self.x
end
end
end
function Enemy:update(dt)
for i, enemy in ipairs(self.enemy_table) do
prevX = enemy.x
if i ~= 1 then
enemy.x = prevX + self.spacing + self.speed * dt
enemy.y = self.y
end
end
end
function Enemy:draw()
for i, enemy in ipairs(self.enemy_table) do
if enemy.alive then
love.graphics.setColor(0, 255, 0)
love.graphics.rectangle("fill", enemy.x, self.y, self.width, self.height)
end
end
end
return Enemy
--Enemy:update(), Enemy:destroy() --> Compensate for spacing Enemy:draw()
|
local class = require 'libs.middleclass'
local Enemy = class('Enemy')
function Enemy:initialize(speed, width, height, x, y, spacing, enemy_table)
self.speed = speed
self.width = width
self.height = height
self.x = x
self.y = y
self.spacing = spacing
self.enemy_table = enemy_table
end
function Enemy:create()
if #self.enemy_table == 0 then
table.insert(self.enemy_table, {x = self.x, y = self.y, alive = true})
else
table.insert(self.enemy_table, {x = self.enemy_table[#self.enemy_table].x + self.spacing, y = self.y, alive = true})
end
end
function Enemy:checkCollision()
for i, enemy in ipairs(self.enemy_table) do
if enemy.x + self.width >= love.graphics.getWidth() then
enemy.y = enemy.y + self.spacing
enemy.x = self.x
end
end
end
function Enemy:update(dt)
for i, enemy in ipairs(self.enemy_table) do
enemy.x = enemy.x + self.speed * dt
--enemy.y = self.y
end
end
function Enemy:draw()
for i, enemy in ipairs(self.enemy_table) do
if enemy.alive then
love.graphics.setColor(0, 255, 0)
love.graphics.rectangle("fill", enemy.x, enemy.y, self.width, self.height)
end
end
end
return Enemy
--fix y axis
|
fixed some glitches, but it still doesn't as intended
|
fixed some glitches, but it still doesn't as intended
|
Lua
|
mit
|
MeArio/Space_Invaders
|
9154e1468de436f4805c63704bbe49a1e98eed46
|
toribio.lua
|
toribio.lua
|
--- Embedded Robotics Library.
-- Toribio is a library for developing robotics applications. It is based on Lumen cooperative
-- scheduler, and allows to write coroutine, signal and callback based applications.
-- Toribio provides a mechanism for easily accesing hardware, and is geared towards
-- low end hardware, such as Single-Board Computers.
-- @module toribio
-- @usage local toribio = require 'toribio'
-- @alias M
local M ={}
local sched = require 'sched'
local log= require 'log'
local mutex = require 'mutex'
--require "log".setlevel('ALL')
--- Available devices.
-- This is a table containing the name and associated object for all available devices
-- in the system.
-- When toribio adds or removes a device, @{events} are emitted. For easily
-- accesing this table, use @{wait_for_device}
-- @usage for name, _ in pairs(toribio.devices) do
-- print(name)
--end
M.devices = {}
local devices=M.devices
local function get_device_name(n)
if not devices[n] then
--print('NAME', n, n)
return n
end
local i=2
local nn=n.."#"..i
while devices[nn] do
i=i+1
nn=n.."#"..i
end
--print('NAME', n, nn)
return nn
end
--- Signals that toribio can emit.
-- @usage local sched = require 'sched'
--sched.sigrun_task(
-- {toribio.events.new_device},
-- print
--)
-- @field new_device A new device was added. The first parameter is the device object.
-- @field removed_device A device was removed. The first parameter is the device.
-- @table events
local events = {
new_device = {},
removed_device = {},
}
M.events = events
--- Return a device with a given name or matching a filter.
-- If the parameter provided is a string, will look for a
-- device with it as a name. Alternativelly, it can be a table
-- specifying a criterion a device must match.
-- If no such device exists, will block until it appears.
-- @param devdesc The name of the device or a filter.
-- @param timeout How much time wait for the device.
-- @return The requested device. On timeout, returns _nil,'timeout'_.
-- @usage local mice = toribio.wait_for_device('mice')
--local some_button = toribio.wait_for_device({module='bb-button'})
M.wait_for_device = function(devdesc, timeout)
assert(sched.running_task, 'Must run in a task')
local wait_until
if timeout then wait_until=sched.get_time() + timeout end
local device_in_devices, device_matches --matching function
if type (devdesc) == 'string' then
device_matches = function (device, dd)
return device.name == dd
end
device_in_devices = function (dd)
return devices[dd]
end
else
device_matches = function (device, dd)
local matches = true
for key, value in pairs(dd) do
if device[key]~=value then
matches=false
break
end
end
return matches
end
device_in_devices = function (dd)
for _, device in pairs(devices) do
if device_matches(device, dd) then return device end
end
end
end
local in_devices=device_in_devices(devdesc)
if in_devices then
return in_devices
else
local tortask = M.task
local waitd = {M.events.new_device}
if wait_until then waitd.timeout=wait_until-sched.get_time() end
while true do
local ev, device = sched.wait(waitd)
if not ev then --timeout
return nil, 'timeout'
end
if device_matches (device, devdesc) then
return device
end
if wait_until then waitd.timeout=wait_until-sched.get_time() end
end
end
end
--- Register a callback for a device's signal.
-- Only one instance of the callback function will be executed at a time. This means
-- that if a event happens again while a callback is running, the new callback will
-- be fired only when the first finishes. Can be invoked also as
-- device:register_callback(event, f)
-- @param device The device to watch.
-- @param event the name of the event to watch.
-- @param f the callback function. It will be passed the signal's parameters.
-- @param timeout Timeout on wait. On expiration, f will be invoked with
-- nil, 'timeout' as parameters.
-- @return The callback task, or _nil, error_ on failure
M.register_callback = function(device, event, f, timeout)
assert(sched.running_task, 'Must run in a task')
if not device.events or not device.events[event] then return nil, "Device has no such event" end
local waitd = {
device.events[event],
timeout=timeout,
}
local mx = mutex.new()
local fsynched = mx:synchronize(f)
local wrapper = function(_, ...)
return fsynched(...)
end
return sched.sigrun(waitd, wrapper)
end
--- Provide a new Device object.
-- Registers the Device object with Toribio. Warning: if the object's name is
-- already taken, Toribio will rename the object.
-- @param device a Device object.
M.add_device = function (device)
local devicename=get_device_name(device.name)
log ('TORIBIO', 'INFO', 'Adding device "%s" (module "%s")', device.name, device.module)
if device.name~=devicename then
log ('TORIBIO', 'WARN', 'device renamed from "%s" to "%s" (module "%s")', device.name, devicename, device.module)
device.name=devicename
end
devices[devicename] = device
-- for device:register_callback() notation
device.register_callback = M.register_callback
device.remove = M.remove_device
sched.schedule_signal(events.new_device, device )
end
M.remove_devices = function(devdesc)
if type(devdesc) == 'string' then
devdesc={name=devdesc}
end
for _, device in pairs(devices) do
local matches = true
for key, value in pairs(devdesc) do
if device[key]~=value then
matches=false
break
end
end
if matches then M.remove_device(device) end
end
end
M.remove_device = function(device)
log ('TORIBIO', 'INFO', 'Removing device %s', device.name)
if device.task then sched.kill(device.task) end
devices[device.name]=nil
sched.schedule_signal(events.removed_device, device )
end
--- Start a task.
-- @param section The section to which the task belongs
-- (possible values are 'deviceloaders' and 'tasks')
-- @param taskname The name of the task
-- @return true on success.
M.start = function(section, taskname)
local packagename = section..'/'..taskname
if package.loaded[packagename]
then return package.loaded[packagename] end
local sect = M.configuration[section] or {}
local conf = sect[taskname] or {}
local taskmodule = require (packagename)
log('TORIBIO', 'INFO', 'module %s loaded: %s', packagename, tostring(taskmodule))
if taskmodule==true then
log('TORIBIO', 'WARN', 'Task module "%s" did not return a table!', packagename)
error('Task module "'..packagename..'" did not return a table!')
end
if taskmodule and taskmodule.init then
sched.run(function()
taskmodule.init(conf)
log('TORIBIO', 'INFO', 'module %s started', packagename)
end)
end
return taskmodule
end
--- The configuration table.
-- This table contains the configurations specified in toribio-go.conf file.
M.configuration = {}
return M
|
--- Embedded Robotics Library.
-- Toribio is a library for developing robotics applications. It is based on Lumen cooperative
-- scheduler, and allows to write coroutine, signal and callback based applications.
-- Toribio provides a mechanism for easily accesing hardware, and is geared towards
-- low end hardware, such as Single-Board Computers.
-- @module toribio
-- @usage local toribio = require 'toribio'
-- @alias M
local M ={}
local sched = require 'sched'
local log= require 'log'
local mutex = require 'mutex'
--require "log".setlevel('ALL')
--- Available devices.
-- This is a table containing the name and associated object for all available devices
-- in the system.
-- When toribio adds or removes a device, @{events} are emitted. For easily
-- accesing this table, use @{wait_for_device}
-- @usage for name, _ in pairs(toribio.devices) do
-- print(name)
--end
M.devices = {}
local devices=M.devices
local function get_device_name(n)
if not devices[n] then
--print('NAME', n, n)
return n
end
local i=2
local nn=n.."#"..i
while devices[nn] do
i=i+1
nn=n.."#"..i
end
--print('NAME', n, nn)
return nn
end
--- Signals that toribio can emit.
-- @usage local sched = require 'sched'
--sched.sigrun_task(
-- {toribio.events.new_device},
-- print
--)
-- @field new_device A new device was added. The first parameter is the device object.
-- @field removed_device A device was removed. The first parameter is the device.
-- @table events
local events = {
new_device = {},
removed_device = {},
}
M.events = events
--- Return a device with a given name or matching a filter.
-- If the parameter provided is a string, will look for a
-- device with it as a name. Alternativelly, it can be a table
-- specifying a criterion a device must match.
-- If no such device exists, will block until it appears.
-- @param devdesc The name of the device or a filter.
-- @param timeout How much time wait for the device.
-- @return The requested device. On timeout, returns _nil,'timeout'_.
-- @usage local mice = toribio.wait_for_device('mice')
--local some_button = toribio.wait_for_device({module='bb-button'})
M.wait_for_device = function(devdesc, timeout)
assert(sched.running_task, 'Must run in a task')
local wait_until
if timeout then wait_until=sched.get_time() + timeout end
local device_in_devices, device_matches --matching function
if type (devdesc) == 'string' then
device_matches = function (device, dd)
return device.name == dd
end
device_in_devices = function (dd)
return devices[dd]
end
else
device_matches = function (device, dd)
local matches = true
for key, value in pairs(dd) do
if device[key]~=value then
matches=false
break
end
end
return matches
end
device_in_devices = function (dd)
for _, device in pairs(devices) do
if device_matches(device, dd) then return device end
end
end
end
local in_devices=device_in_devices(devdesc)
if in_devices then
return in_devices
else
local tortask = M.task
local waitd = {M.events.new_device}
if wait_until then waitd.timeout=wait_until-sched.get_time() end
while true do
local ev, device = sched.wait(waitd)
if not ev then --timeout
return nil, 'timeout'
end
if device_matches (device, devdesc) then
return device
end
if wait_until then waitd.timeout=wait_until-sched.get_time() end
end
end
end
--- Register a callback for a device's signal.
-- Only one instance of the callback function will be executed at a time. This means
-- that if a event happens again while a callback is running, the new callback will
-- be fired only when the first finishes. Can be invoked also as
-- device:register_callback(event, f)
-- @param device The device to watch.
-- @param event the name of the event to watch.
-- @param f the callback function. It will be passed the signal's parameters.
-- @param timeout Timeout on wait. On expiration, f will be invoked with
-- nil, 'timeout' as parameters.
-- @return The callback task, or _nil, error_ on failure
M.register_callback = function(device, event, f, timeout)
assert(sched.running_task, 'Must run in a task')
if not device.events or not device.events[event] then
log ('TORIBIO', 'WARN', 'Event not found for device %s: "%s"', tostring(device), tostring(event))
return nil, "Device has no such event"
end
log ('TORIBIO', 'INFO', 'Registering callback on device %s: "%s"', tostring(device), tostring(event))
local waitd = {
device.events[event],
timeout=timeout,
}
local mx = mutex.new()
local fsynched = mx:synchronize(f)
local wrapper = function(_, ...)
return fsynched(...)
end
return sched.sigrun(waitd, wrapper)
end
--- Provide a new Device object.
-- Registers the Device object with Toribio. Warning: if the object's name is
-- already taken, Toribio will rename the object.
-- @param device a Device object.
M.add_device = function (device)
local devicename=get_device_name(device.name)
log ('TORIBIO', 'INFO', 'Adding device "%s" (module "%s")', device.name, device.module)
if device.name~=devicename then
log ('TORIBIO', 'WARN', 'device renamed from "%s" to "%s" (module "%s")',
device.name, devicename, device.module)
device.name=devicename
end
devices[devicename] = device
-- for device:register_callback() notation
device.register_callback = M.register_callback
device.remove = M.remove_device
sched.schedule_signal(events.new_device, device )
end
M.remove_devices = function(devdesc)
if type(devdesc) == 'string' then
devdesc={name=devdesc}
end
for _, device in pairs(devices) do
local matches = true
for key, value in pairs(devdesc) do
if device[key]~=value then
matches=false
break
end
end
if matches then M.remove_device(device) end
end
end
M.remove_device = function(device)
log ('TORIBIO', 'INFO', 'Removing device %s', device.name)
if device.task then sched.kill(device.task) end
devices[device.name]=nil
sched.schedule_signal(events.removed_device, device )
end
--- Start a task.
-- @param section The section to which the task belongs
-- (possible values are 'deviceloaders' and 'tasks')
-- @param taskname The name of the task
-- @return true on success.
M.start = function(section, taskname)
local packagename = section..'/'..taskname
if package.loaded[packagename]
then return package.loaded[packagename] end
local sect = M.configuration[section] or {}
local conf = sect[taskname] or {}
local taskmodule = require (packagename)
log('TORIBIO', 'INFO', 'module %s loaded: %s', packagename, tostring(taskmodule))
if taskmodule==true then
log('TORIBIO', 'WARN', 'Task module "%s" did not return a table!', packagename)
error('Task module "'..packagename..'" did not return a table!')
end
if taskmodule and taskmodule.init then
sched.run(function()
taskmodule.init(conf)
log('TORIBIO', 'INFO', 'module %s started', packagename)
end)
end
return taskmodule
end
--- The configuration table.
-- This table contains the configurations specified in toribio-go.conf file.
M.configuration = {}
return M
|
fix typo
|
fix typo
|
Lua
|
mit
|
xopxe/Toribio,xopxe/Toribio,xopxe/Toribio
|
c5c234422f1bd5be46c9b51a5b38b45800b1fe05
|
test/LanguageModel_test.lua
|
test/LanguageModel_test.lua
|
require 'torch'
require 'nn'
require 'LanguageModel'
local tests = {}
local tester = torch.Tester()
local function check_dims(x, dims)
tester:assert(x:dim() == #dims)
for i, d in ipairs(dims) do
tester:assert(x:size(i) == d)
end
end
-- Just a smoke test to make sure model can run forward / backward
function tests.simpleTest()
local N, T, D, H, V = 2, 3, 4, 5, 6
local idx_to_token = {[1]='a', [2]='b', [3]='c', [4]='d', [5]='e', [6]='f'}
local LM = nn.LanguageModel{
idx_to_token=idx_to_token,
model_type='rnn',
wordvec_size=D,
rnn_size=H,
num_layers=6,
dropout=0,
}
local crit = nn.CrossEntropyCriterion()
local params, grad_params = LM:getParameters()
local x = torch.Tensor(N, T):random(V)
local y = torch.Tensor(N, T):random(V)
local scores = LM:forward(x)
check_dims(scores, {N, T, V})
local scores_view = scores:view(N * T, V)
local y_view = y:view(N * T)
local loss = crit:forward(scores_view, y_view)
local dscores = crit:backward(scores_view, y_view):view(N, T, V)
LM:backward(x, dscores)
end
function tests.sampleTest()
local N, T, D, H, V = 2, 3, 4, 5, 6
local idx_to_token = {[1]='a', [2]='b', [3]='c', [4]='d', [5]='e', [6]='f'}
local LM = nn.LanguageModel{
idx_to_token=idx_to_token,
model_type='rnn',
wordvec_size=D,
rnn_size=H,
num_layers=6,
dropout=0,
}
local TT = 100
local start_text = 'bad'
local sampled = LM:sample{start_text=start_text, length=TT}
tester:assert(torch.type(sampled) == 'string')
tester:assert(string.len(sampled) == TT)
end
function tests.encodeDecodeTest()
local idx_to_token = {
[1]='a', [2]='b', [3]='c', [4]='d',
[5]='e', [6]='f', [7]='g', [8]=' ',
}
local N, T, D, H, V = 2, 3, 4, 5, 7
local LM = nn.LanguageModel{
idx_to_token=idx_to_token,
model_type='rnn',
wordvec_size=D,
rnn_size=H,
num_layers=6,
dropout=0,
}
local s = 'a bad feed'
local encoded = LM:encode_string(s)
local expected_encoded = torch.LongTensor{1, 8, 2, 1, 4, 8, 6, 5, 5, 4}
tester:assert(torch.all(torch.eq(encoded, expected_encoded)))
local s2 = LM:decode_string(encoded)
tester:assert(s == s2)
end
tester:add(tests)
tester:run()
|
require 'torch'
require 'nn'
require 'LanguageModel'
local tests = {}
local tester = torch.Tester()
local function check_dims(x, dims)
tester:assert(x:dim() == #dims)
for i, d in ipairs(dims) do
tester:assert(x:size(i) == d)
end
end
-- Just a smoke test to make sure model can run forward / backward
function tests.simpleTest()
local N, T, D, H, V = 2, 3, 4, 5, 6
local idx_to_token = {[1]='a', [2]='b', [3]='c', [4]='d', [5]='e', [6]='f'}
local LM = nn.LanguageModel{
idx_to_token=idx_to_token,
model_type='rnn',
wordvec_size=D,
rnn_size=H,
num_layers=6,
dropout=0,
batchnorm=0,
}
local crit = nn.CrossEntropyCriterion()
local params, grad_params = LM:getParameters()
local x = torch.Tensor(N, T):random(V)
local y = torch.Tensor(N, T):random(V)
local scores = LM:forward(x)
check_dims(scores, {N, T, V})
local scores_view = scores:view(N * T, V)
local y_view = y:view(N * T)
local loss = crit:forward(scores_view, y_view)
local dscores = crit:backward(scores_view, y_view):view(N, T, V)
LM:backward(x, dscores)
end
function tests.sampleTest()
local N, T, D, H, V = 2, 3, 4, 5, 6
local idx_to_token = {[1]='a', [2]='b', [3]='c', [4]='d', [5]='e', [6]='f'}
local LM = nn.LanguageModel{
idx_to_token=idx_to_token,
model_type='rnn',
wordvec_size=D,
rnn_size=H,
num_layers=6,
dropout=0,
batchnorm=0,
}
local TT = 100
local start_text = 'bad'
local sampled = LM:sample{start_text=start_text, length=TT}
tester:assert(torch.type(sampled) == 'string')
tester:assert(string.len(sampled) == TT)
end
function tests.encodeDecodeTest()
local idx_to_token = {
[1]='a', [2]='b', [3]='c', [4]='d',
[5]='e', [6]='f', [7]='g', [8]=' ',
}
local N, T, D, H, V = 2, 3, 4, 5, 7
local LM = nn.LanguageModel{
idx_to_token=idx_to_token,
model_type='rnn',
wordvec_size=D,
rnn_size=H,
num_layers=6,
dropout=0,
batchnorm=0,
}
local s = 'a bad feed'
local encoded = LM:encode_string(s)
local expected_encoded = torch.LongTensor{1, 8, 2, 1, 4, 8, 6, 5, 5, 4}
tester:assert(torch.all(torch.eq(encoded, expected_encoded)))
local s2 = LM:decode_string(encoded)
tester:assert(s == s2)
end
tester:add(tests)
tester:run()
|
fix broken test
|
fix broken test
|
Lua
|
mit
|
phanhuy1502/FYP,antihutka/torch-rnn,billzorn/torch-rnn,guillitte/torch-rnn,phanhuy1502/FYP,JackHopkins/torch-rnn,jcjohnson/torch-rnn,JackHopkins/torch-rnn,JackHopkins/torch-rnn,tmp6154/torch-rnn,oneyanshi/transcend-exe,gabrielegiannini/torch-rnn-repo,spaceraccoon/bilabot,JackHopkins/torch-rnn,JackHopkins/torch-rnn,JackHopkins/torch-rnn,dgcrouse/torch-rnn,JackHopkins/torch-rnn
|
6b2e492eb058f4feb3b1e29994e6d97493276543
|
test/compat_luaunit_v2x.lua
|
test/compat_luaunit_v2x.lua
|
lu = require('luaunit')
--[[
Use Luaunit in the v2.1 fashion and check that it still works.
Exercise every luaunit v2.1 function and have it executed successfully.
Coverage:
x Made LuaUnit:run() method able to be called with 'run' or 'Run'.
x Made LuaUnit.wrapFunctions() function able to be called with 'wrapFunctions' or 'WrapFunctions' or 'wrap_functions'.
x Moved wrapFunctions to the LuaUnit module table (e.g. local LuaUnit = require( "luaunit" ); LuaUnit.wrapFunctions( ... ) )
x Added LuaUnit.is<Type> and LuaUnit.is_<type> helper functions. (e.g. assert( LuaUnit.isString( getString() ) )
x Added assert<Type> and assert_<type>
x Added assertNot<Type> and assert_not_<type>
x Added _VERSION variable to hold the LuaUnit version
x Added LuaUnit:setVerbosity(lvl) method to the LuaUnit. Alias: LuaUnit:SetVerbosity() and LuaUnit:set_verbosity().
x Added table deep compare
x check that wrapFunctions works
x Made "testable" classes able to start with 'test' or 'Test' for their name.
x Made "testable" methods able to start with 'test' or 'Test' for their name.
x Made testClass:setUp() methods able to be named with 'setUp' or 'Setup' or 'setup'.
x Made testClass:tearDown() methods able to be named with 'tearDown' or 'TearDown' or 'teardown'.
]]
TestLuaUnitV2Compat = {}
function TestLuaUnitV2Compat:testRunAliases()
-- some old function
assertFunction( lu.run )
assertEquals( lu.run, lu.Run )
end
function TestLuaUnitV2Compat:testWrapFunctionsAliases()
assertFunction( lu.wrapFunctions )
assertEquals( lu.wrapFunctions, lu.WrapFunctions )
assertEquals( lu.wrapFunctions, lu.wrap_functions )
end
function TestLuaUnitV2Compat:testIsXXX()
local goodType, badType
-- isBoolean
goodType = true
badType = "toto"
assertEquals( lu.is_boolean( goodType), true )
assertEquals( lu.is_boolean( badType), false )
assertEquals( lu.is_boolean, lu.isBoolean )
-- isNumber
goodType = true
goodType = 1
badType = "toto"
assertEquals( lu.is_number( goodType ), true )
assertEquals( lu.is_number( badType ), false )
assertEquals( is_number, isNumber )
-- isString
goodType = "toto"
badType = 1.0
assertEquals( lu.is_string( goodType ), true )
assertEquals( lu.is_string( badType ), false )
assertEquals( is_string, isString )
-- isNil
goodType = nil
badType = "toto"
assertEquals( lu.is_nil( goodType ), true )
assertEquals( lu.is_nil( badType ), false )
assertEquals( isNil, is_nil )
-- isTable
goodType = {1,2,3}
badType = "toto"
assertEquals( lu.is_table( goodType ), true )
assertEquals( lu.is_table( badType ), false )
assertEquals( is_table, isTable )
-- isFunction
goodType = function (v) return v*2 end
badType = "toto"
assertEquals( lu.is_function( goodType ), true )
assertEquals( lu.is_function( badType ), false )
assertEquals( is_function, isFunction )
-- isUserData
badType = "toto"
assertEquals( lu.is_userdata( badType ), false )
assertEquals( is_userdata, isUserdata )
-- isThread
goodType = coroutine.create( function(v) local y=v+1 end )
badType = "toto"
assertEquals( lu.is_thread( goodType ), true )
assertEquals( lu.is_thread( badType ), false )
assertEquals( isThread, is_thread )
end
function typeAsserter( goodType, badType, goodAsserter, badAsserter )
goodAsserter( goodType )
badAsserter( badType )
end
function TestLuaUnitV2Compat:testAssertType()
f = function (v) return v+1 end
t = coroutine.create( function(v) local y=v+1 end )
typesToVerify = {
-- list of: { goodType, badType, goodAsserter, badAsserter }
{ true, "toto", assertBoolean, assertNotBoolean },
{ 1 , "toto", assertNumber, assertNotNumber },
{ "q" , 1 , assertString, assertNotString },
{ nil , 1 , assertNil, assertNotNil },
{ {1,2}, "toto", assertTable, assertNotTable },
{ f , "toto", assertFunction, assertNotFunction },
{ t , "toto", assertThread, assertNotThread },
}
for _,v in ipairs( typesToVerify ) do
goodType, badType, goodAsserter, badAsserter = table.unpack( v )
typeAsserter( goodType, badType, goodAsserter, badAsserter )
end
assertNotUserdata( "toto" )
end
function TestLuaUnitV2Compat:testHasVersionKey()
assertNotNil( lu._VERSION )
assertString( lu._VERSION )
end
function TestLuaUnitV2Compat:testTableEquality()
t1 = {1,2}
t2 = t1
t3 = {1,2}
t4 = {1,2,3}
assertEquals( t1, t1 )
assertEquals( t1, t2 )
-- new in LuaUnit v2.0 , deep table compare
assertEquals( t1, t3 )
assertError( assertEquals, t1, t4 )
end
-- Setup
called = {}
function test_w1() called.w1 = true end
function test_w2() called.w2 = true end
function test_w3() called.w3 = true end
TestSomeFuncs = lu.wrapFunctions( 'test_w1', 'test_w2', 'test_w3' )
TestWithCap = {}
function TestWithCap:setup() called.setup = true end
function TestWithCap:Test1() called.t1 = true end
function TestWithCap:test2() called.t2 = true end
function TestWithCap:teardown() called.teardown = true end
testWithoutCap = {}
function testWithoutCap:Setup() called.Setup = true end
function testWithoutCap:Test3() called.t3 = true end
function testWithoutCap:test4() called.t4 = true end
function testWithoutCap:tearDown() called.tearDown = true end
TestWithUnderscore = {}
function TestWithUnderscore:setUp() called.setUp = true end
function TestWithUnderscore:Test1() called.t1 = true end
function TestWithUnderscore:test2() called.t2 = true end
function TestWithUnderscore:TearDown() called.TearDown = true end
-- Run
lu:setVerbosity( 1 )
lu:set_verbosity( 1 )
lu:SetVerbosity( 1 )
local results = lu.run()
-- Verif
assert( called.w1 == true )
assert( called.w2 == true )
assert( called.w3 == true )
assert( called.t1 == true )
assert( called.t2 == true )
assert( called.t3 == true )
assert( called.t4 == true )
assert( called.setup == true )
assert( called.setUp == true )
assert( called.Setup == true )
assert( called.teardown == true )
assert( called.tearDown == true )
assert( called.TearDown == true )
os.exit( results )
|
EXPORT_ASSERT_TO_GLOBALS = true
lu = require('luaunit')
--[[
Use Luaunit in the v2.1 fashion and check that it still works.
Exercise every luaunit v2.1 function and have it executed successfully.
Coverage:
x Made LuaUnit:run() method able to be called with 'run' or 'Run'.
x Made LuaUnit.wrapFunctions() function able to be called with 'wrapFunctions' or 'WrapFunctions' or 'wrap_functions'.
x Moved wrapFunctions to the LuaUnit module table (e.g. local LuaUnit = require( "luaunit" ); LuaUnit.wrapFunctions( ... ) )
x Added LuaUnit.is<Type> and LuaUnit.is_<type> helper functions. (e.g. assert( LuaUnit.isString( getString() ) )
x Added assert<Type> and assert_<type>
x Added assertNot<Type> and assert_not_<type>
x Added _VERSION variable to hold the LuaUnit version
x Added LuaUnit:setVerbosity(lvl) method to the LuaUnit. Alias: LuaUnit:SetVerbosity() and LuaUnit:set_verbosity().
x Added table deep compare
x check that wrapFunctions works
x Made "testable" classes able to start with 'test' or 'Test' for their name.
x Made "testable" methods able to start with 'test' or 'Test' for their name.
x Made testClass:setUp() methods able to be named with 'setUp' or 'Setup' or 'setup'.
x Made testClass:tearDown() methods able to be named with 'tearDown' or 'TearDown' or 'teardown'.
]]
TestLuaUnitV2Compat = {}
function TestLuaUnitV2Compat:testRunAliases()
-- some old function
assertFunction( lu.run )
assertEquals( lu.Run, lu.run )
end
function TestLuaUnitV2Compat:testWrapFunctionsAliases()
assertFunction( lu.wrapFunctions )
assertEquals( lu.wrapFunctions, lu.WrapFunctions )
assertEquals( lu.wrapFunctions, lu.wrap_functions )
end
function typeAsserter( goodType, badType, goodAsserter, badAsserter )
goodAsserter( goodType )
badAsserter( badType )
end
function TestLuaUnitV2Compat:testAssertType()
f = function (v) return v+1 end
t = coroutine.create( function(v) local y=v+1 end )
typesToVerify = {
-- list of: { goodType, badType, goodAsserter, badAsserter }
{ true, "toto", assertBoolean, assertNotBoolean },
{ 1 , "toto", assertNumber, assertNotNumber },
{ "q" , 1 , assertString, assertNotString },
{ nil , 1 , assertNil, assertNotNil },
{ {1,2}, "toto", assertTable, assertNotTable },
{ f , "toto", assertFunction, assertNotFunction },
{ t , "toto", assertThread, assertNotThread },
}
for _,v in ipairs( typesToVerify ) do
goodType, badType, goodAsserter, badAsserter = table.unpack( v )
typeAsserter( goodType, badType, goodAsserter, badAsserter )
end
assertNotUserdata( "toto" )
end
function TestLuaUnitV2Compat:testHasVersionKey()
assertNotNil( lu._VERSION )
assertString( lu._VERSION )
end
function TestLuaUnitV2Compat:testTableEquality()
t1 = {1,2}
t2 = t1
t3 = {1,2}
t4 = {1,2,3}
assertEquals( t1, t1 )
assertEquals( t1, t2 )
-- new in LuaUnit v2.0 , deep table compare
assertEquals( t1, t3 )
assertError( assertEquals, t1, t4 )
end
-- Setup
called = {}
function test_w1() called.w1 = true end
function test_w2() called.w2 = true end
function test_w3() called.w3 = true end
TestSomeFuncs = lu.wrapFunctions( 'test_w1', 'test_w2', 'test_w3' )
TestWithCap = {}
function TestWithCap:setup() called.setup = true end
function TestWithCap:Test1() called.t1 = true end
function TestWithCap:test2() called.t2 = true end
function TestWithCap:teardown() called.teardown = true end
testWithoutCap = {}
function testWithoutCap:Setup() called.Setup = true end
function testWithoutCap:Test3() called.t3 = true end
function testWithoutCap:test4() called.t4 = true end
function testWithoutCap:tearDown() called.tearDown = true end
TestWithUnderscore = {}
function TestWithUnderscore:setUp() called.setUp = true end
function TestWithUnderscore:Test1() called.t1 = true end
function TestWithUnderscore:test2() called.t2 = true end
function TestWithUnderscore:TearDown() called.TearDown = true end
-- Run
lu:setVerbosity( 1 )
lu:set_verbosity( 1 )
lu:SetVerbosity( 1 )
local results = lu.run()
-- Verif
assert( called.w1 == true )
assert( called.w2 == true )
assert( called.w3 == true )
assert( called.t1 == true )
assert( called.t2 == true )
assert( called.t3 == true )
assert( called.t4 == true )
assert( called.setup == true )
assert( called.setUp == true )
assert( called.Setup == true )
assert( called.teardown == true )
assert( called.tearDown == true )
assert( called.TearDown == true )
os.exit( results )
|
Compatibility with luaunit v2x needs global variable export + small fixes. luaunit.isXXX is discarded, it does not add any value.
|
Compatibility with luaunit v2x needs global variable export + small fixes. luaunit.isXXX is discarded, it does not add any value.
|
Lua
|
bsd-2-clause
|
GuntherStruyf/luaunit,GuntherStruyf/luaunit
|
d161475ba5a74e36356aa9bfd2ac404b38011ffc
|
premake5.lua
|
premake5.lua
|
workspace "pwre"
language "C++"
flags { "C++11" }
location ( "build" )
configurations { "Debug", "Release" }
platforms {"native", "x64", "x32"}
objdir("build/obj/%{cfg.system}")
includedirs { "include" }
project "pwre"
kind "StaticLib"
targetdir("lib/%{cfg.system}/%{cfg.platform}")
files {
"include/*.hpp", "include/*.h",
"src/*.cpp", "src/*.hpp", "src/*.h",
"src/win32/*.cpp", "src/win32/*.hpp",
"src/x11/*.cpp", "src/x11/*.hpp",
"src/cocoa/*.cpp", "src/cocoa/*.hpp", "src/cocoa/*.mm"
}
includedirs { "deps" }
configuration { "windows", "gmake" }
targetprefix "lib"
targetextension ".a"
configuration "macosx"
files { "src/*.mm" }
configuration "Debug"
defines { "DEBUG" }
symbols "On"
warnings "Extra"
targetsuffix ("_d")
configuration "Release"
defines { "NDEBUG" }
optimize "Speed"
project "demo_blank"
kind "ConsoleApp"
targetdir("bin/%{cfg.system}/%{cfg.platform}")
files { "demo/blank.cpp" }
libdirs { "lib/%{cfg.system}/%{cfg.platform}" }
configuration "Debug"
defines { "DEBUG" }
symbols "On"
warnings "Extra"
targetsuffix ("_d")
links { "pwre_d" }
configuration "Release"
defines { "NDEBUG" }
optimize "Speed"
links { "pwre" }
configuration "windows"
links { "user32" }
configuration "macosx"
linkoptions { "-framework Cocoa" }
configuration "linux"
links { "X11", "pthread" }
project "demo_gl"
kind "ConsoleApp"
targetdir("bin/%{cfg.system}/%{cfg.platform}")
files { "demo/gl.cpp" }
libdirs { "lib/%{cfg.system}/%{cfg.platform}" }
configuration "Debug"
defines { "DEBUG" }
symbols "On"
warnings "Extra"
targetsuffix ("_d")
links { "pwre_d" }
configuration "Release"
defines { "NDEBUG" }
optimize "Speed"
links { "pwre" }
configuration "windows"
links { "user32", "gdi32", "opengl32" }
configuration "macosx"
linkoptions { "-framework Cocoa", "-framework OpenGL" }
configuration "linux"
links { "X11", "pthread", "GL", "Xrender" }
project "demo_gl_alpha"
kind "ConsoleApp"
targetdir("bin/%{cfg.system}/%{cfg.platform}")
files { "demo/gl_alpha.cpp" }
libdirs { "lib/%{cfg.system}/%{cfg.platform}" }
configuration "Debug"
defines { "DEBUG" }
symbols "On"
warnings "Extra"
targetsuffix ("_d")
links { "pwre_d" }
configuration "Release"
defines { "NDEBUG" }
optimize "Speed"
links { "pwre" }
configuration "windows"
links { "user32", "gdi32", "opengl32" }
configuration "macosx"
linkoptions { "-framework Cocoa", "-framework OpenGL" }
configuration "linux"
links { "X11", "pthread", "GL", "Xrender" }
|
workspace "pwre"
language "C++"
flags { "C++11" }
location ( "build" )
configurations { "Debug", "Release" }
platforms {"native", "x64", "x32"}
objdir("build/obj/%{cfg.system}")
includedirs { "include" }
project "pwre"
kind "StaticLib"
targetdir("lib/%{cfg.system}/%{cfg.platform}")
files {
"include/*.hpp", "include/*.h",
"src/*.cpp", "src/*.hpp", "src/*.h",
"src/win32/*.cpp", "src/win32/*.hpp",
"src/x11/*.cpp", "src/x11/*.hpp"
}
includedirs { "deps" }
configuration { "windows", "gmake" }
targetprefix "lib"
targetextension ".a"
configuration "macosx"
files { "src/cocoa/*.mm", "src/cocoa/*.hpp" }
configuration "Debug"
defines { "DEBUG" }
symbols "On"
warnings "Extra"
targetsuffix ("_d")
configuration "Release"
defines { "NDEBUG" }
optimize "Speed"
project "demo_blank"
kind "ConsoleApp"
targetdir("bin/%{cfg.system}/%{cfg.platform}")
files { "demo/blank.cpp" }
libdirs { "lib/%{cfg.system}/%{cfg.platform}" }
configuration "Debug"
defines { "DEBUG" }
symbols "On"
warnings "Extra"
targetsuffix ("_d")
links { "pwre_d" }
configuration "Release"
defines { "NDEBUG" }
optimize "Speed"
links { "pwre" }
configuration "windows"
links { "user32" }
configuration "macosx"
linkoptions { "-framework Cocoa" }
configuration "linux"
links { "X11", "pthread" }
project "demo_gl"
kind "ConsoleApp"
targetdir("bin/%{cfg.system}/%{cfg.platform}")
files { "demo/gl.cpp" }
libdirs { "lib/%{cfg.system}/%{cfg.platform}" }
configuration "Debug"
defines { "DEBUG" }
symbols "On"
warnings "Extra"
targetsuffix ("_d")
links { "pwre_d" }
configuration "Release"
defines { "NDEBUG" }
optimize "Speed"
links { "pwre" }
configuration "windows"
links { "user32", "gdi32", "opengl32" }
configuration "macosx"
linkoptions { "-framework Cocoa", "-framework OpenGL" }
configuration "linux"
links { "X11", "pthread", "GL", "Xrender" }
project "demo_gl_alpha"
kind "ConsoleApp"
targetdir("bin/%{cfg.system}/%{cfg.platform}")
files { "demo/gl_alpha.cpp" }
libdirs { "lib/%{cfg.system}/%{cfg.platform}" }
configuration "Debug"
defines { "DEBUG" }
symbols "On"
warnings "Extra"
targetsuffix ("_d")
links { "pwre_d" }
configuration "Release"
defines { "NDEBUG" }
optimize "Speed"
links { "pwre" }
configuration "windows"
links { "user32", "gdi32", "opengl32" }
configuration "macosx"
linkoptions { "-framework Cocoa", "-framework OpenGL" }
configuration "linux"
links { "X11", "pthread", "GL", "Xrender" }
|
Fixed files
|
Fixed files
|
Lua
|
mit
|
yulon/pwre
|
a13d522d992ceb6ef989b8a50816c2f912e80f39
|
otherplatforms/raspberry-pi/premake4.lua
|
otherplatforms/raspberry-pi/premake4.lua
|
------------------------------------------------------------------
-- premake 4 Pyros3D solution
------------------------------------------------------------------
solution "Pyros3D"
newoption {
trigger = "shared",
description = "Ouput Shared Library"
}
newoption {
trigger = "static",
description = "Ouput Static Library - Default Option"
}
newoption {
trigger = "examples",
description = "Build Demos Examples"
}
newoption {
trigger = "log",
value = "OUTPUT",
description = "Log Output",
allowed = {
{ "none", "No log - Default" },
{ "console", "Log to Console"},
{ "file", "Log to File"}
}
}
framework = "_SDL2";
libsToLink = { "SDL2", "SDL2_mixer" }
excludes { "**/SFML/**", "**/SDL/**" }
buildArch = "native"
libsToLinkGL = { "GLESv2" }
------------------------------------------------------------------
-- setup common settings
------------------------------------------------------------------
configurations { "Debug", "Release" }
platforms { buildArch }
location "build"
rootdir = "../../"
libName = "PyrosEngine"
project "PyrosEngine"
targetdir "../../libs"
if _OPTIONS["shared"] then
kind "SharedLib"
else
kind "StaticLib"
end
language "C++"
files { "../../src/**.h", "../../src/**.cpp", "../../include/Pyros3D/**.h" }
includedirs { "../../include/", "/usr/local/include/SDL2", "/opt/vc/include/", "/usr/include/freetype2", "/usr/include/bullet" }
defines({"GLES2", "UNICODE", "LODEPNG", framework })
if _OPTIONS["log"]=="console" then
defines({"LOG_TO_CONSOLE"})
else
if _OPTIONS["log"]=="file" then
defines({"LOG_TO_FILE"})
else
defines({"LOG_DISABLE"})
end
end
configuration "Debug"
targetname(libName.."d")
defines({"_DEBUG"})
flags { "Symbols" }
configuration "Release"
flags { "Optimize" }
targetname(libName)
project "AssimpImporter"
targetdir "../../bin/tools"
kind "ConsoleApp"
language "C++"
files { "../../tools/AssimpImporter/src/**.h", "../../tools/AssimpImporter/src/**.cpp" }
includedirs { "../../include/", "/usr/local/include/SDL2", "/opt/vc/include/", "/usr/include/freetype2", "/usr/include/bullet" }
defines({"UNICODE"})
defines({"LOG_DISABLE"})
configuration "Debug"
defines({"_DEBUG"})
targetdir ("../../bin/tools/")
links { libName.."d", libsToLinkGL, libsToLink, "assimp", "BulletDynamics", "BulletCollision", "LinearMath", "freetype", "z" }
linkoptions { "-L../libs -L/usr/local/lib -Wl,-rpath,../../../../libs" }
flags { "Symbols" }
configuration "Release"
targetdir ("../../bin/tools/")
links { libName, libsToLinkGL, libsToLink, "assimp", "BulletDynamics", "BulletCollision", "LinearMath", "freetype", "pthread", "z" }
linkoptions { "-L../libs -L/usr/local/lib -Wl,-rpath,../../../../libs" }
flags { "Optimize" }
function BuildDemo(demoPath, demoName)
project (demoName)
kind "ConsoleApp"
language "C++"
files { "../../"..demoPath.."/**.h", "../../"..demoPath.."/**.cpp", "../../"..demoPath.."/../WindowManagers/SDL2/**.cpp", "../../"..demoPath.."/../WindowManagers/**.h", "../../"..demoPath.."/../MainProgram.cpp" }
includedirs { "../../include/", "/usr/local/include/SDL2", "/opt/vc/include/", "/usr/include/freetype2", "/usr/include/bullet" }
defines({framework, "GLES2", "DEMO_NAME="..demoName, "_"..demoName, "UNICODE"})
configuration "Debug"
defines({"_DEBUG"})
targetdir ("bin/")
links { libName.."d", libsToLinkGL, libsToLink, "BulletDynamics", "BulletCollision", "LinearMath", "freetype", "z" }
linkoptions { "-L../libs -L/usr/local/lib -Wl,-rpath,../../../../libs" }
flags { "Symbols" }
configuration "Release"
targetdir ("bin/")
links { libName, libsToLinkGL, libsToLink, "BulletDynamics", "BulletCollision", "LinearMath", "freetype", "pthread", "z" }
linkoptions { "-L../libs -L/usr/local/lib -Wl,-rpath,../../../../libs" }
flags { "Optimize" }
end;
if _OPTIONS["examples"] then
BuildDemo("examples/RotatingCube", "RotatingCube");
BuildDemo("examples/RotatingTexturedCube", "RotatingTexturedCube");
BuildDemo("examples/RotatingTextureAnimatedCube", "RotatingTextureAnimatedCube");
BuildDemo("examples/RotatingCubeWithLighting", "RotatingCubeWithLighting");
BuildDemo("examples/RotatingCubeWithLightingAndShadow", "RotatingCubeWithLightingAndShadow");
BuildDemo("examples/SimplePhysics", "SimplePhysics");
BuildDemo("examples/TextRendering", "TextRendering");
BuildDemo("examples/CustomMaterial", "CustomMaterial");
BuildDemo("examples/PickingPainterMethod", "PickingPainterMethod");
BuildDemo("examples/SkeletonAnimationExample", "SkeletonAnimationExample");
BuildDemo("examples/DeferredRendering", "DeferredRendering");
BuildDemo("examples/LOD_example", "LOD_example");
BuildDemo("examples/IslandDemo", "IslandDemo");
BuildDemo("examples/RacingGame", "RacingGame");
-- ImGui Example only works with SFML for now
if framework ~= "SDL" or not "SDL2" then
BuildDemo("examples/ImGuiExample", "ImGuiExample");
end
end
|
------------------------------------------------------------------
-- premake 4 Pyros3D solution
------------------------------------------------------------------
solution "Pyros3D"
newoption {
trigger = "shared",
description = "Ouput Shared Library"
}
newoption {
trigger = "static",
description = "Ouput Static Library - Default Option"
}
newoption {
trigger = "examples",
description = "Build Demos Examples"
}
newoption {
trigger = "log",
value = "OUTPUT",
description = "Log Output",
allowed = {
{ "none", "No log - Default" },
{ "console", "Log to Console"},
{ "file", "Log to File"}
}
}
framework = "_SDL2";
libsToLink = { "SDL2", "SDL2_mixer" }
excludes { "**/SFML/**", "**/SDL/**" }
buildArch = "native"
libsToLinkGL = { "GLESv2" }
------------------------------------------------------------------
-- setup common settings
------------------------------------------------------------------
configurations { "Debug", "Release" }
platforms { buildArch }
location "build"
rootdir = "../../"
libName = "PyrosEngine"
project "PyrosEngine"
targetdir "../../libs"
if _OPTIONS["shared"] then
kind "SharedLib"
else
kind "StaticLib"
end
language "C++"
files { "../../src/**.h", "../../src/**.cpp", "../../include/Pyros3D/**.h" }
includedirs { "../../include/", "/usr/local/include/SDL2", "/opt/vc/include/", "/usr/include/freetype2", "/usr/include/bullet" }
defines({"GLES2", "UNICODE", "LODEPNG", framework })
if _OPTIONS["log"]=="console" then
defines({"LOG_TO_CONSOLE"})
else
if _OPTIONS["log"]=="file" then
defines({"LOG_TO_FILE"})
else
defines({"LOG_DISABLE"})
end
end
configuration "Debug"
targetname(libName.."d")
defines({"_DEBUG"})
flags { "Symbols" }
configuration "Release"
flags { "Optimize" }
targetname(libName)
project "AssimpImporter"
targetdir "../../bin/tools"
kind "ConsoleApp"
language "C++"
files { "../../tools/AssimpImporter/src/**.h", "../../tools/AssimpImporter/src/**.cpp" }
includedirs { "../../include/", "/usr/local/include/SDL2", "/opt/vc/include/", "/usr/include/freetype2", "/usr/include/bullet" }
defines({"UNICODE"})
defines({"LOG_DISABLE"})
configuration "Debug"
defines({"_DEBUG"})
targetdir ("../../bin/tools/")
links { libName.."d", libsToLinkGL, libsToLink, "assimp", "BulletDynamics", "BulletCollision", "LinearMath", "freetype", "z" }
linkoptions { "-L../libs -L/opt/vc/lib -L/usr/local/lib -Wl,-rpath,../../../../libs" }
flags { "Symbols" }
configuration "Release"
targetdir ("../../bin/tools/")
links { libName, libsToLinkGL, libsToLink, "assimp", "BulletDynamics", "BulletCollision", "LinearMath", "freetype", "pthread", "z" }
linkoptions { "-L../libs -L/opt/vc/lib -L/usr/local/lib -Wl,-rpath,../../../../libs" }
flags { "Optimize" }
function BuildDemo(demoPath, demoName)
project (demoName)
kind "ConsoleApp"
language "C++"
files { "../../"..demoPath.."/**.h", "../../"..demoPath.."/**.cpp", "../../"..demoPath.."/../WindowManagers/SDL2/**.cpp", "../../"..demoPath.."/../WindowManagers/**.h", "../../"..demoPath.."/../MainProgram.cpp" }
includedirs { "../../include/", "/usr/local/include/SDL2", "/opt/vc/include/", "/usr/include/freetype2", "/usr/include/bullet" }
defines({framework, "GLES2", "DEMO_NAME="..demoName, "_"..demoName, "UNICODE"})
configuration "Debug"
defines({"_DEBUG"})
targetdir ("../../bin/")
links { libName.."d", libsToLinkGL, libsToLink, "BulletDynamics", "BulletCollision", "LinearMath", "freetype", "z" }
linkoptions { "-L../../libs -L/opt/vc/lib -L/usr/local/lib -Wl,-rpath,../../../../libs" }
flags { "Symbols" }
configuration "Release"
targetdir ("../../bin/")
links { libName, libsToLinkGL, libsToLink, "BulletDynamics", "BulletCollision", "LinearMath", "freetype", "pthread", "z" }
linkoptions { "-L../../libs -L/opt/vc/lib -L/usr/local/lib -Wl,-rpath,../../../../libs" }
flags { "Optimize" }
end;
if _OPTIONS["examples"] then
BuildDemo("examples/RotatingCube", "RotatingCube");
BuildDemo("examples/RotatingTexturedCube", "RotatingTexturedCube");
BuildDemo("examples/RotatingTextureAnimatedCube", "RotatingTextureAnimatedCube");
BuildDemo("examples/RotatingCubeWithLighting", "RotatingCubeWithLighting");
BuildDemo("examples/RotatingCubeWithLightingAndShadow", "RotatingCubeWithLightingAndShadow");
BuildDemo("examples/SimplePhysics", "SimplePhysics");
BuildDemo("examples/TextRendering", "TextRendering");
BuildDemo("examples/CustomMaterial", "CustomMaterial");
BuildDemo("examples/PickingPainterMethod", "PickingPainterMethod");
BuildDemo("examples/SkeletonAnimationExample", "SkeletonAnimationExample");
BuildDemo("examples/DeferredRendering", "DeferredRendering");
BuildDemo("examples/LOD_example", "LOD_example");
BuildDemo("examples/IslandDemo", "IslandDemo");
BuildDemo("examples/RacingGame", "RacingGame");
-- ImGui Example only works with SFML for now
if framework ~= "SDL" or not "SDL2" then
BuildDemo("examples/ImGuiExample", "ImGuiExample");
end
end
|
Fixed raspberry premake file
|
Fixed raspberry premake file
|
Lua
|
mit
|
Peixinho/Pyros3D,Peixinho/Pyros3D,Peixinho/Pyros3D
|
481c3841369695fdfe913fcdd4f7c816660ad2b0
|
keybindings.lua
|
keybindings.lua
|
local module = {}
local utils = require "utils"
-- ------------------
-- simple vi-mode
-- ------------------
local arrows = {
h = 'left',
j = 'down',
k = 'up',
l = 'right'
}
local enableSimpleViMode = function()
for k, v in pairs(arrows) do
utils.keymap(k, 'alt', v, nil)
utils.keymap(k, 'alt+shift', v, 'alt')
utils.keymap(k, 'alt+shift+ctrl', v, 'shift')
end
end
local disableSimpleViMode = function()
for k,v in pairs (arrows) do
hs.hotkey.disableAll({'alt'}, k);
end
end
-- ----------------------------
-- App switcher with Cmd++j/k
-- ----------------------------
switcher = hs.window.switcher.new(utils.globalfilter(),
{textSize = 12,
showTitles = false,
showThumbnails = false,
showSelectedTitle = false,
selectedThumbnailSize = 640,
backgroundColor = {0, 0, 0, 0}})
hs.hotkey.bind({'cmd'},'j', function() switcher:next() end)
hs.hotkey.bind({'cmd'},'k', function() switcher:previous() end)
-- ----------------------------
-- tab switching with Cmd++h/l
-- ----------------------------
local left_right = { h = "[", l = "]"}
local simpleTabSwitching = {}
for dir, key in pairs(left_right) do
local tapFn = function() hs.eventtap.keyStroke({"shift", "cmd"}, key) end
simpleTabSwitching[dir] = hs.hotkey.new({"cmd"}, dir, tapFn, nil, tapFn)
end
-- ------------------
-- App specific keybindings
-- ------------------
appSpecificKeys = {}
-- Given an app name and hs.hotkey, binds that hotkey when app activates
module.activateAppKey = function(app, hotkey)
if not appSpecificKeys[app] then
appSpecificKeys[app] = {}
end
for a, keys in pairs(appSpecificKeys) do
if not keys[hotkey.idx] then
keys[hotkey.idx] = hotkey
end
for idx, hk in pairs(keys) do
if idx == hotkey.idx then
hk:enable()
end
end
end
end
-- Disables specific hotkeys for a given app name
module.deactivateAppKeys = function(app)
for a, keys in pairs(appSpecificKeys) do
if a == app then
for _,hk in pairs(keys) do
hk:disable()
end
end
end
end
module.appSpecific = {
["*"] = {
activated = function() enableSimpleViMode() end
},
["Emacs"] = {
activated = function() disableSimpleViMode() end
},
["Google Chrome"] = {
activated = function()
--- setting conflicting Cmd+L (jump to address bar) keybinding to Cmd+Shift+L
local hk = hs.hotkey.new({'cmd', 'shift'}, 'l', function()
local app = hs.window.focusedWindow():application()
app:selectMenuItem({'File', 'Open Location…'})
end)
module.activateAppKey("Google Chrome", hk)
for k, hk in pairs(simpleTabSwitching) do
module.activateAppKey("Google Chrome", hk)
end
end,
deactivated = function() module.deactivateAppKeys("Google Chrome") end
},
["iTerm2"] = {
activated = function()
for k, hk in pairs(simpleTabSwitching) do
module.activateAppKey("iTerm2", hk)
end
end,
deactivated = function() module.deactivateAppKeys("iTerm2") end
}
}
-- Creates a new watcher and runs all the functions for specific `appName` and `events`
-- listed in the module in `module.appSpecific`
hs.application.watcher.new(
function(appName, event, appObj)
for app, modes in pairs(module.appSpecific) do
if app == appName or app == "*" then
for mode, fn in pairs(modes) do
if event == hs.application.watcher[mode] then fn() end
end
end
end
end
):start()
return module
|
local module = {}
local utils = require "utils"
-- ------------------
-- simple vi-mode
-- ------------------
local arrows = {
h = 'left',
j = 'down',
k = 'up',
l = 'right'
}
local enableSimpleViMode = function()
for k, v in pairs(arrows) do
utils.keymap(k, 'alt', v, nil)
utils.keymap(k, 'alt+shift', v, 'alt')
utils.keymap(k, 'alt+shift+ctrl', v, 'shift')
end
end
local disableSimpleViMode = function()
for k,v in pairs (arrows) do
hs.hotkey.disableAll({'alt'}, k);
end
end
-- ----------------------------
-- App switcher with Cmd++j/k
-- ----------------------------
switcher = hs.window.switcher.new(utils.globalfilter(),
{textSize = 12,
showTitles = false,
showThumbnails = false,
showSelectedTitle = false,
selectedThumbnailSize = 640,
backgroundColor = {0, 0, 0, 0}})
hs.hotkey.bind({'cmd'},'j', function() switcher:next() end)
hs.hotkey.bind({'cmd'},'k', function() switcher:previous() end)
-- ----------------------------
-- tab switching with Cmd++h/l
-- ----------------------------
local simpleTabSwitching = {}
for dir, key in pairs({ h = "[", l = "]"}) do
local tf = function()
hs.eventtap.keyStroke({"shift", "cmd"}, key)
end
simpleTabSwitching[dir] = hs.hotkey.new({"cmd"}, dir, tf, nil, tf)
end
-- ------------------
-- App specific keybindings
-- ------------------
appSpecificKeys = {}
-- Given an app name and hs.hotkey, binds that hotkey when app activates
module.activateAppKey = function(app, hotkey)
if not appSpecificKeys[app] then
appSpecificKeys[app] = {}
end
for a, keys in pairs(appSpecificKeys) do
if (a == app or app == "*") and not keys[hotkey.idx] then
keys[hotkey.idx] = hotkey
end
for idx, hk in pairs(keys) do
if idx == hotkey.idx then
hk:enable()
end
end
end
end
-- Disables specific hotkeys for a given app name
module.deactivateAppKeys = function(app)
for a, keys in pairs(appSpecificKeys) do
if a == app then
for _,hk in pairs(keys) do
hk:disable()
end
end
end
end
module.appSpecific = {
["*"] = {
activated = function() enableSimpleViMode() end
},
["Emacs"] = {
activated = function() disableSimpleViMode() end
},
["Google Chrome"] = {
activated = function()
--- setting conflicting Cmd+L (jump to address bar) keybinding to Cmd+Shift+L
local cmdSL = hs.hotkey.new({'cmd', 'shift'}, 'l', function()
local app = hs.window.focusedWindow():application()
app:selectMenuItem({'File', 'Open Location…'})
end)
module.activateAppKey("Google Chrome", cmdSL)
for k, hk in pairs(simpleTabSwitching) do
module.activateAppKey("Google Chrome", hs.fnutils.copy(hk))
end
end,
deactivated = function() module.deactivateAppKeys("Google Chrome") end
},
["iTerm2"] = {
activated = function()
for k, hk in pairs(simpleTabSwitching) do
module.activateAppKey("iTerm2", hs.fnutils.copy(hk))
end
end,
deactivated = function() module.deactivateAppKeys("iTerm2") end
}
}
-- Creates a new watcher and runs all the functions for specific `appName` and `events`
-- listed in the module in `module.appSpecific`
hs.application.watcher.new(
function(appName, event, appObj)
-- first executing all fns in `appSpecific["*"]`
for k,v in pairs (hs.application.watcher) do
if v == event and module.appSpecific["*"][k] then
module.appSpecific["*"][k]()
end
end
for app, modes in pairs(module.appSpecific) do
if app == appName then
for mode, fn in pairs(modes) do
if event == hs.application.watcher[mode] then fn() end
end
end
end
end
):start()
return module
|
Bugfixing
|
Bugfixing
- Simple tab switching wouldn't work (because hotkeys between iTerm and Chrome
were shared vars) - immutability matters!
- appSpecific["*"] functions wouldn't execute
|
Lua
|
mit
|
agzam/spacehammer
|
67c815d0419a2f9f9f6b1817bc7a849b073dae0c
|
lib/envconf.lua
|
lib/envconf.lua
|
local focusSetting = {
submitCmd = 'sbatch',
submitIDRow = 4,
delCmd = 'scancel',
statCmd = 'fjstat',
statStateColumn = 5,
statStateRow = 4,
jobEndFunc = function (t)
if (t[1][1] == 'Invalid' and t[1][2] == 'job' and t[1][3] == 'ID') then return true
else return false end
end,
bootsh = [[
#!/bin/bash
#SBATCH -p ye001uta3m
#SBATCH -N JOB.NODE
#SBATCH -n JOB.CORE
#SBATCH -J JOB.NAME
#SBATCH -o stdout.%J.log
#SBATCH -e stderr.%J.log
JOB.OPTION
sh JOB.JOB
]]
}
local focusTunnelSetting = {
submitCmd = 'sbatch',
submitIDRow = 4,
delCmd = 'scancel',
statCmd = 'fjstat',
statStateColumn = 5,
statStateRow = 4,
--portForwardingInfo = [[
--{
-- "host" : "ff01",
-- "user": "userid",
-- "password": "*****"
--}
--]],
jobEndFunc = function (t)
if (t[1][1] == 'Invalid' and t[1][2] == 'job' and t[1][3] == 'ID') then return true
else return false end
end,
bootsh = [[
#!/bin/bash
#SBATCH -p ye001uta3m
#SBATCH -N JOB.NODE
#SBATCH -n JOB.CORE
#SBATCH -J JOB.NAME
#SBATCH -o stdout.%J.log
#SBATCH -e stderr.%J.log
JOB.OPTION
sh JOB.JOB
]]
}
local focusSettingFFV = {
submitCmd = 'fjsub',
submitIDRow = 4,
delCmd = 'fjdel',
statCmd = 'fjstat',
statStateColumn = 5,
statStateRow = 4,
jobEndFunc = function (t)
if (t[1][1] == 'Invalid' and t[1][2] == 'job' and t[1][3] == 'ID') then return true
else return false end
end,
bootsh = [[
#!/bin/bash
#SBATCH -p ye016uta72h
#SBATCH -N JOB.NODE
#SBATCH -n JOB.CORE
#SBATCH -J JOB.NAME
#SBATCH -o stdout.%J.log
#SBATCH -e stderr.%J.log
module load PrgEnv-intel
module load intel/openmpi165
JOB.OPTION
sh JOB.JOB
]]
}
local kSetting = {
submitCmd = 'pjsub',
submitIDRow = 6,
delCmd = 'pjdel',
statCmd = 'pjstat',
statStateColumn = 6,
statStateRow = 4,
jobEndFunc = function(t)
-- TODO: 'END'
return false
end,
bootsh = [[echo "TODO:"]]
}
local localhostSetting = {
submitCmd = 'sh',
submitIDRow = 2,
delCmd = 'kill',
-- portForwardingInfo = [[
--{
-- "host" : "192.168.1.25"
--}
-- ]],
--statCmd = 'fjstat',
--statStateColumn = 5,
--statStateRow = 4,
--jobEndFunc = function (t)
-- if (t[1][1] == 'Invalid' and t[1][2] == 'job' and t[1][3] == 'ID') then return true
-- else return false end
--end,
bootsh = [[
#!/bin/bash
JOB.OPTION
sh JOB.JOB
]]
}
local function getServerInfo(server)
local info = {
["localhost"] = localhostSetting,
["k.aics.riken.jp"] = kSetting,
["ssh.j-focus.jp"] = focusTunnelSetting,
["ff01.j-focus.jp"] = focusSetting,
["ff02.j-focus.jp"] = focusSetting,
["ff01"] = focusSetting,
["ff02"] = focusSetting,
["ff01ffv"] = focusSettingFFV,
}
info["ff01ffv"].server = "ff01"
if info[server] ~= nil then
return info[server]
else
return localhostSetting
end
end
return {getServerInfo=getServerInfo}
|
local focusSetting = {
submitCmd = 'sbatch',
submitIDRow = 4,
delCmd = 'scancel',
statCmd = 'fjstat',
statStateColumn = 5,
statStateRow = 4,
jobEndFunc = function (t)
if (t[1][1] == 'Invalid' and t[1][2] == 'job' and t[1][3] == 'ID') then return true
else return false end
end,
bootsh = [[
#!/bin/bash
#SBATCH -p ye001uta3m
#SBATCH -N JOB.NODE
#SBATCH -n JOB.CORE
#SBATCH -J JOB.NAME
#SBATCH -o stdout.%J.log
#SBATCH -e stderr.%J.log
JOB.OPTION
sh JOB.JOB
]]
}
local focusTunnelSetting = {
submitCmd = 'sbatch',
submitIDRow = 4,
delCmd = 'scancel',
statCmd = 'fjstat',
statStateColumn = 5,
statStateRow = 4,
--portForwardingInfo = [[{"host" : "ff01","user": "userid","password": "*****"}]],
jobEndFunc = function (t)
if (t[1][1] == 'Invalid' and t[1][2] == 'job' and t[1][3] == 'ID') then return true
else return false end
end,
bootsh = [[
#!/bin/bash
#SBATCH -p ye001uta3m
#SBATCH -N JOB.NODE
#SBATCH -n JOB.CORE
#SBATCH -J JOB.NAME
#SBATCH -o stdout.%J.log
#SBATCH -e stderr.%J.log
JOB.OPTION
sh JOB.JOB
]]
}
local focusSettingFFV = {
submitCmd = 'fjsub',
submitIDRow = 4,
delCmd = 'fjdel',
statCmd = 'fjstat',
statStateColumn = 5,
statStateRow = 4,
jobEndFunc = function (t)
if (t[1][1] == 'Invalid' and t[1][2] == 'job' and t[1][3] == 'ID') then return true
else return false end
end,
bootsh = [[
#!/bin/bash
#SBATCH -p ye016uta72h
#SBATCH -N JOB.NODE
#SBATCH -n JOB.CORE
#SBATCH -J JOB.NAME
#SBATCH -o stdout.%J.log
#SBATCH -e stderr.%J.log
module load PrgEnv-intel
module load intel/openmpi165
JOB.OPTION
sh JOB.JOB
]]
}
local kSetting = {
submitCmd = 'pjsub',
submitIDRow = 6,
delCmd = 'pjdel',
statCmd = 'pjstat',
statStateColumn = 6,
statStateRow = 4,
jobEndFunc = function(t)
-- TODO: 'END'
return false
end,
bootsh = [[echo "TODO:"]]
}
local localhostSetting = {
submitCmd = 'sh',
submitIDRow = 2,
delCmd = 'kill',
-- portForwardingInfo = [[
--{
-- "host" : "192.168.1.25"
--}
-- ]],
--statCmd = 'fjstat',
--statStateColumn = 5,
--statStateRow = 4,
--jobEndFunc = function (t)
-- if (t[1][1] == 'Invalid' and t[1][2] == 'job' and t[1][3] == 'ID') then return true
-- else return false end
--end,
bootsh = [[
#!/bin/bash
JOB.OPTION
sh JOB.JOB
]]
}
local function getServerInfo(server)
local info = {
["localhost"] = localhostSetting,
["k.aics.riken.jp"] = kSetting,
["ssh.j-focus.jp"] = focusTunnelSetting,
["ff01.j-focus.jp"] = focusSetting,
["ff02.j-focus.jp"] = focusSetting,
["ff01"] = focusSetting,
["ff02"] = focusSetting,
["ff01ffv"] = focusSettingFFV,
}
info["ff01ffv"].server = "ff01"
if info[server] ~= nil then
return info[server]
else
return localhostSetting
end
end
return {getServerInfo=getServerInfo}
|
fixed for windows
|
fixed for windows
|
Lua
|
bsd-2-clause
|
avr-aics-riken/hpcpfGUI,digirea/hpcpfGUI,digirea/hpcpfGUI,digirea/hpcpfGUI,avr-aics-riken/hpcpfGUI,avr-aics-riken/hpcpfGUI
|
3b92157dfc3c3a69308157562018a541e3c3b633
|
mod_ircd/mod_ircd.lua
|
mod_ircd/mod_ircd.lua
|
local irc_listener = { default_port = 6667, default_mode = "*l" };
local sessions = {};
local commands = {};
local nicks = {};
local st = require "util.stanza";
local conference_server = module:get_option("conference_server") or "conference.jabber.org";
local function irc_close_session(session)
session.conn:close();
end
function irc_listener.onincoming(conn, data)
local session = sessions[conn];
if not session then
session = { conn = conn, host = module.host, reset_stream = function () end,
close = irc_close_session, log = logger.init("irc"..(conn.id or "1")),
roster = {} };
sessions[conn] = session;
function session.data(data)
module:log("debug", "Received: %s", data);
local command, args = data:match("^%s*([^ ]+) *(.*)%s*$");
if not command then
module:log("warn", "Invalid command: %s", data);
return;
end
command = command:upper();
module:log("debug", "Received command: %s", command);
if commands[command] then
local ret = commands[command](session, args);
if ret then
session.send(ret.."\r\n");
end
end
end
function session.send(data)
module:log("debug", "sending: %s", data);
return conn:write(data.."\r\n");
end
end
if data then
session.data(data);
end
end
function irc_listener.ondisconnect(conn, error)
module:log("debug", "Client disconnected");
sessions[conn] = nil;
end
function commands.NICK(session, nick)
nick = nick:match("^[%w_]+");
if nicks[nick] then
session.send(":"..session.host.." 433 * The nickname "..nick.." is already in use");
return;
end
nicks[nick] = session;
session.nick = nick;
session.full_jid = nick.."@"..module.host.."/ircd";
session.type = "c2s";
module:log("debug", "Client bound to %s", session.full_jid);
session.send(":"..session.host.." 001 "..session.nick.." :Welcome to XMPP via the "..session.host.." gateway "..session.nick);
end
local joined_mucs = {};
function commands.JOIN(session, channel)
if not joined_mucs[channel] then
joined_mucs[channel] = { occupants = {}, sessions = {} };
end
joined_mucs[channel].sessions[session] = true;
local join_stanza = st.presence({ from = session.full_jid, to = channel:gsub("^#", "").."@"..conference_server.."/"..session.nick });
core_process_stanza(session, join_stanza);
session.send(":"..session.nick.." JOIN :"..channel);
session.send(":"..session.host.." 332 "..session.nick.." "..channel.." :Connection in progress...");
session.send(":"..session.host.." 353 "..session.nick.." = "..channel.." :"..session.nick);
session.send(":"..session.host.." 366 "..session.nick.." "..channel.." :End of /NAMES list.");
end
function commands.PART(session, channel)
local channel, part_message = channel:match("^([^:]+):?(.*)$");
channel = channel:match("^([%S]*)");
core_process_stanza(session, st.presence{ type = "unavailable", from = session.full_jid,
to = channel:gsub("^#", "").."@"..conference_server.."/"..session.nick }:tag("status"):text(part_message));
session.send(":"..session.nick.." PART :"..channel);
end
function commands.PRIVMSG(session, message)
local who, message = message:match("^(%S+) :(.+)$");
if joined_mucs[who] then
core_process_stanza(session, st.message{to=who:gsub("^#", "").."@"..conference_server, type="groupchat"}:tag("body"):text(message));
end
end
function commands.PING(session, server)
session.send(":"..session.host..": PONG "..server);
end
function commands.WHO(session, channel)
if joined_mucs[channel] then
for nick in pairs(joined_mucs[channel].occupants) do
--n=MattJ 91.85.191.50 irc.freenode.net MattJ H :0 Matthew Wild
session.send(":"..session.host.." 352 "..session.nick.." "..channel.." "..nick.." "..nick.." "..session.host.." "..nick.." H :0 "..nick);
end
session.send(":"..session.host.." 315 "..session.nick.." "..channel.. " :End of /WHO list");
end
end
function commands.MODE(session, channel)
session.send(":"..session.host.." 324 "..session.nick.." "..channel.." +J");
end
--- Component (handle stanzas from the server for IRC clients)
function irc_component(origin, stanza)
local from, from_bare = stanza.attr.from, jid.bare(stanza.attr.from);
local from_node = "#"..jid.split(stanza.attr.from);
if joined_mucs[from_node] and from_bare == from then
-- From room itself
local joined_muc = joined_mucs[from_node];
if stanza.name == "message" then
local subject = stanza:get_child("subject");
if subject then
local subject_text = subject:get_text();
for session in pairs(joined_muc.sessions) do
session.send(":"..session.host.." 332 "..session.nick.." "..from_node.." :"..subject_text);
end
end
end
elseif joined_mucs[from_node] then
-- From room occupant
local joined_muc = joined_mucs[from_node];
local nick = select(3, jid.split(from)):gsub(" ", "_");
if stanza.name == "presence" then
local what;
if not stanza.attr.type then
if joined_muc.occupants[nick] then
return;
end
joined_muc.occupants[nick] = true;
what = "JOIN";
else
joined_muc.occupants[nick] = nil;
what = "PART";
end
for session in pairs(joined_muc.sessions) do
if nick ~= session.nick then
session.send(":"..nick.."!"..nick.." "..what.." :"..from_node);
end
end
elseif stanza.name == "message" then
local body = stanza:get_child("body");
body = body and body:get_text() or "";
local hasdelay = stanza:get_child("delay", "urn:xmpp:delay");
if body ~= "" then
for session in pairs(joined_muc.sessions) do
if nick ~= session.nick or hasdelay then
session.send(":"..nick.." PRIVMSG "..from_node.." :"..body);
end
end
end
end
end
end
require "core.componentmanager".register_component(module.host, irc_component);
prosody.events.add_handler("server-stopping", function (shutdown)
module:log("debug", "Closing IRC connections prior to shutdown");
for channel, joined_muc in pairs(joined_mucs) do
for session in pairs(joined_muc.sessions) do
core_process_stanza(session,
st.presence{ type = "unavailable", from = session.full_jid,
to = channel:gsub("^#", "").."@"..conference_server.."/"..session.nick }
:tag("status")
:text("Connection closed: Server is shutting down"..(shutdown.reason and (": "..shutdown.reason) or "")));
session:close();
end
end
end);
require "net.connlisteners".register("irc", irc_listener);
require "net.connlisteners".start("irc", { port = module:get_option("port") });
|
local irc_listener = { default_port = 6667, default_mode = "*l" };
local sessions = {};
local commands = {};
local nicks = {};
local st = require "util.stanza";
local conference_server = module:get_option("conference_server") or "conference.jabber.org";
local function irc_close_session(session)
session.conn:close();
end
function irc_listener.onincoming(conn, data)
local session = sessions[conn];
if not session then
session = { conn = conn, host = module.host, reset_stream = function () end,
close = irc_close_session, log = logger.init("irc"..(conn.id or "1")),
roster = {} };
sessions[conn] = session;
function session.data(data)
module:log("debug", "Received: %s", data);
local command, args = data:match("^%s*([^ ]+) *(.*)%s*$");
if not command then
module:log("warn", "Invalid command: %s", data);
return;
end
command = command:upper();
module:log("debug", "Received command: %s", command);
if commands[command] then
local ret = commands[command](session, args);
if ret then
session.send(ret.."\r\n");
end
end
end
function session.send(data)
module:log("debug", "sending: %s", data);
return conn:write(data.."\r\n");
end
end
if data then
session.data(data);
end
end
function irc_listener.ondisconnect(conn, error)
module:log("debug", "Client disconnected");
sessions[conn] = nil;
end
function commands.NICK(session, nick)
nick = nick:match("^[%w_]+");
if nicks[nick] then
session.send(":"..session.host.." 433 * The nickname "..nick.." is already in use");
return;
end
nicks[nick] = session;
session.nick = nick;
session.full_jid = nick.."@"..module.host.."/ircd";
session.type = "c2s";
module:log("debug", "Client bound to %s", session.full_jid);
session.send(":"..session.host.." 001 "..session.nick.." :Welcome to XMPP via the "..session.host.." gateway "..session.nick);
end
local joined_mucs = {};
function commands.JOIN(session, channel)
if not joined_mucs[channel] then
joined_mucs[channel] = { occupants = {}, sessions = {} };
end
joined_mucs[channel].sessions[session] = true;
local join_stanza = st.presence({ from = session.full_jid, to = channel:gsub("^#", "").."@"..conference_server.."/"..session.nick });
core_process_stanza(session, join_stanza);
session.send(":"..session.nick.." JOIN :"..channel);
session.send(":"..session.host.." 332 "..session.nick.." "..channel.." :Connection in progress...");
session.send(":"..session.host.." 353 "..session.nick.." = "..channel.." :"..session.nick);
session.send(":"..session.host.." 366 "..session.nick.." "..channel.." :End of /NAMES list.");
end
function commands.PART(session, channel)
local channel, part_message = channel:match("^([^:]+):?(.*)$");
channel = channel:match("^([%S]*)");
core_process_stanza(session, st.presence{ type = "unavailable", from = session.full_jid,
to = channel:gsub("^#", "").."@"..conference_server.."/"..session.nick }:tag("status"):text(part_message));
session.send(":"..session.nick.." PART :"..channel);
end
function commands.PRIVMSG(session, message)
local who, message = message:match("^(%S+) :(.+)$");
if joined_mucs[who] then
core_process_stanza(session, st.message{to=who:gsub("^#", "").."@"..conference_server, type="groupchat"}:tag("body"):text(message));
end
end
function commands.PING(session, server)
session.send(":"..session.host..": PONG "..server);
end
function commands.WHO(session, channel)
if joined_mucs[channel] then
for nick in pairs(joined_mucs[channel].occupants) do
--n=MattJ 91.85.191.50 irc.freenode.net MattJ H :0 Matthew Wild
session.send(":"..session.host.." 352 "..session.nick.." "..channel.." "..nick.." "..nick.." "..session.host.." "..nick.." H :0 "..nick);
end
session.send(":"..session.host.." 315 "..session.nick.." "..channel.. " :End of /WHO list");
end
end
function commands.MODE(session, channel)
session.send(":"..session.host.." 324 "..session.nick.." "..channel.." +J");
end
--- Component (handle stanzas from the server for IRC clients)
function irc_component(origin, stanza)
local from, from_bare = stanza.attr.from, jid.bare(stanza.attr.from);
local from_node = "#"..jid.split(stanza.attr.from);
if joined_mucs[from_node] and from_bare == from then
-- From room itself
local joined_muc = joined_mucs[from_node];
if stanza.name == "message" then
local subject = stanza:get_child("subject");
subject = subject and (subject:get_text() or "");
if subject then
for session in pairs(joined_muc.sessions) do
session.send(":"..session.host.." 332 "..session.nick.." "..from_node.." :"..subject);
end
end
end
elseif joined_mucs[from_node] then
-- From room occupant
local joined_muc = joined_mucs[from_node];
local nick = select(3, jid.split(from)):gsub(" ", "_");
if stanza.name == "presence" then
local what;
if not stanza.attr.type then
if joined_muc.occupants[nick] then
return;
end
joined_muc.occupants[nick] = true;
what = "JOIN";
else
joined_muc.occupants[nick] = nil;
what = "PART";
end
for session in pairs(joined_muc.sessions) do
if nick ~= session.nick then
session.send(":"..nick.."!"..nick.." "..what.." :"..from_node);
end
end
elseif stanza.name == "message" then
local body = stanza:get_child("body");
body = body and body:get_text() or "";
local hasdelay = stanza:get_child("delay", "urn:xmpp:delay");
if body ~= "" then
for session in pairs(joined_muc.sessions) do
if nick ~= session.nick or hasdelay then
session.send(":"..nick.." PRIVMSG "..from_node.." :"..body);
end
end
end
end
end
end
require "core.componentmanager".register_component(module.host, irc_component);
prosody.events.add_handler("server-stopping", function (shutdown)
module:log("debug", "Closing IRC connections prior to shutdown");
for channel, joined_muc in pairs(joined_mucs) do
for session in pairs(joined_muc.sessions) do
core_process_stanza(session,
st.presence{ type = "unavailable", from = session.full_jid,
to = channel:gsub("^#", "").."@"..conference_server.."/"..session.nick }
:tag("status")
:text("Connection closed: Server is shutting down"..(shutdown.reason and (": "..shutdown.reason) or "")));
session:close();
end
end
end);
require "net.connlisteners".register("irc", irc_listener);
require "net.connlisteners".start("irc", { port = module:get_option("port") });
|
mod_ircd: Fixed handling of empty <subject/> elements.
|
mod_ircd: Fixed handling of empty <subject/> elements.
|
Lua
|
mit
|
dhotson/prosody-modules,asdofindia/prosody-modules,BurmistrovJ/prosody-modules,olax/prosody-modules,1st8/prosody-modules,dhotson/prosody-modules,crunchuser/prosody-modules,mardraze/prosody-modules,joewalker/prosody-modules,guilhem/prosody-modules,either1/prosody-modules,drdownload/prosody-modules,amenophis1er/prosody-modules,mmusial/prosody-modules,prosody-modules/import,LanceJenkinZA/prosody-modules,obelisk21/prosody-modules,brahmi2/prosody-modules,Craige/prosody-modules,mmusial/prosody-modules,joewalker/prosody-modules,dhotson/prosody-modules,guilhem/prosody-modules,syntafin/prosody-modules,jkprg/prosody-modules,jkprg/prosody-modules,NSAKEY/prosody-modules,1st8/prosody-modules,amenophis1er/prosody-modules,mardraze/prosody-modules,vfedoroff/prosody-modules,iamliqiang/prosody-modules,jkprg/prosody-modules,guilhem/prosody-modules,heysion/prosody-modules,vfedoroff/prosody-modules,apung/prosody-modules,mmusial/prosody-modules,BurmistrovJ/prosody-modules,softer/prosody-modules,cryptotoad/prosody-modules,crunchuser/prosody-modules,olax/prosody-modules,joewalker/prosody-modules,NSAKEY/prosody-modules,BurmistrovJ/prosody-modules,syntafin/prosody-modules,heysion/prosody-modules,obelisk21/prosody-modules,softer/prosody-modules,either1/prosody-modules,cryptotoad/prosody-modules,LanceJenkinZA/prosody-modules,1st8/prosody-modules,jkprg/prosody-modules,apung/prosody-modules,heysion/prosody-modules,cryptotoad/prosody-modules,1st8/prosody-modules,Craige/prosody-modules,syntafin/prosody-modules,heysion/prosody-modules,softer/prosody-modules,brahmi2/prosody-modules,drdownload/prosody-modules,apung/prosody-modules,drdownload/prosody-modules,LanceJenkinZA/prosody-modules,either1/prosody-modules,LanceJenkinZA/prosody-modules,amenophis1er/prosody-modules,mardraze/prosody-modules,crunchuser/prosody-modules,asdofindia/prosody-modules,drdownload/prosody-modules,joewalker/prosody-modules,stephen322/prosody-modules,dhotson/prosody-modules,syntafin/prosody-modules,dhotson/prosody-modules,cryptotoad/prosody-modules,prosody-modules/import,crunchuser/prosody-modules,vfedoroff/prosody-modules,mardraze/prosody-modules,apung/prosody-modules,amenophis1er/prosody-modules,brahmi2/prosody-modules,stephen322/prosody-modules,either1/prosody-modules,drdownload/prosody-modules,Craige/prosody-modules,iamliqiang/prosody-modules,prosody-modules/import,apung/prosody-modules,crunchuser/prosody-modules,guilhem/prosody-modules,softer/prosody-modules,olax/prosody-modules,vince06fr/prosody-modules,olax/prosody-modules,mardraze/prosody-modules,jkprg/prosody-modules,1st8/prosody-modules,Craige/prosody-modules,iamliqiang/prosody-modules,brahmi2/prosody-modules,mmusial/prosody-modules,asdofindia/prosody-modules,vince06fr/prosody-modules,guilhem/prosody-modules,BurmistrovJ/prosody-modules,BurmistrovJ/prosody-modules,obelisk21/prosody-modules,olax/prosody-modules,obelisk21/prosody-modules,LanceJenkinZA/prosody-modules,asdofindia/prosody-modules,stephen322/prosody-modules,iamliqiang/prosody-modules,amenophis1er/prosody-modules,prosody-modules/import,stephen322/prosody-modules,vfedoroff/prosody-modules,vfedoroff/prosody-modules,stephen322/prosody-modules,brahmi2/prosody-modules,vince06fr/prosody-modules,iamliqiang/prosody-modules,obelisk21/prosody-modules,vince06fr/prosody-modules,NSAKEY/prosody-modules,syntafin/prosody-modules,prosody-modules/import,NSAKEY/prosody-modules,NSAKEY/prosody-modules,either1/prosody-modules,heysion/prosody-modules,softer/prosody-modules,asdofindia/prosody-modules,Craige/prosody-modules,mmusial/prosody-modules,vince06fr/prosody-modules,cryptotoad/prosody-modules,joewalker/prosody-modules
|
b075060a944f46400d38c52757513c40f66f0698
|
MMOCoreORB/bin/scripts/mobile/faction/imperial/stormtrooper_medic.lua
|
MMOCoreORB/bin/scripts/mobile/faction/imperial/stormtrooper_medic.lua
|
stormtrooper_medic = Creature:new {
objectName = "@mob/creature_names:stormtrooper_medic",
socialGroup = "imperial",
pvpFaction = "imperial",
faction = "imperial",
level = 25,
chanceHit = 0.36,
damageMin = 240,
damageMax = 250,
baseXp = 2637,
baseHAM = 7200,
baseHAMmax = 8800,
armor = 0,
resists = {15,15,40,15,15,15,15,-1,-1},
meatType = "",
meatAmount = 0,
hideType = "",
hideAmount = 0,
boneType = "",
boneAmount = 0,
milk = 0,
tamingChance = 0,
ferocity = 0,
pvpBitmask = ATTACKABLE,
creatureBitmask = PACK + KILLER + HEALER,
optionsBitmask = 136,
diet = HERBIVORE,
templates = {"object/mobile/dressed_stormtrooper_medic_m.iff"},
lootGroups = {
{
groups = {
{group = "color_crystals", chance = 100000},
{group = "junk", chance = 5500000},
{group = "rifles", chance = 550000},
{group = "pistols", chance = 550000},
{group = "melee_weapons", chance = 550000},
{group = "carbines", chance = 550000},
{group = "clothing_attachments", chance = 250000},
{group = "armor_attachments", chance = 250000},
{group = "stormtrooper_common", chance = 700000},
{group = "wearables_common", chance = 1000000}
},
lootChance = 2800000
}
},
weapons = {"stormtrooper_weapons"},
conversationTemplate = "imperial_recruiter_convotemplate",
attacks = merge(riflemanmaster,carbineermaster)
}
CreatureTemplates:addCreatureTemplate(stormtrooper_medic, "stormtrooper_medic")
|
stormtrooper_medic = Creature:new {
objectName = "@mob/creature_names:stormtrooper_medic",
socialGroup = "imperial",
pvpFaction = "imperial",
faction = "imperial",
level = 25,
chanceHit = 0.36,
damageMin = 240,
damageMax = 250,
baseXp = 2637,
baseHAM = 7200,
baseHAMmax = 8800,
armor = 0,
resists = {15,15,40,15,15,15,15,-1,-1},
meatType = "",
meatAmount = 0,
hideType = "",
hideAmount = 0,
boneType = "",
boneAmount = 0,
milk = 0,
tamingChance = 0,
ferocity = 0,
pvpBitmask = ATTACKABLE,
creatureBitmask = PACK + KILLER + HEALER,
optionsBitmask = 136,
diet = HERBIVORE,
templates = {"object/mobile/dressed_stormtrooper_medic_m.iff"},
lootGroups = {
{
groups = {
{group = "color_crystals", chance = 100000},
{group = "junk", chance = 5500000},
{group = "rifles", chance = 550000},
{group = "pistols", chance = 550000},
{group = "melee_weapons", chance = 550000},
{group = "carbines", chance = 550000},
{group = "clothing_attachments", chance = 250000},
{group = "armor_attachments", chance = 250000},
{group = "stormtrooper_common", chance = 700000},
{group = "wearables_common", chance = 1000000}
},
lootChance = 2800000
}
},
weapons = {"stormtrooper_weapons"},
conversationTemplate = "",
attacks = merge(riflemanmaster,carbineermaster)
}
CreatureTemplates:addCreatureTemplate(stormtrooper_medic, "stormtrooper_medic")
|
[Fixed] stormtrooper medics are no longer recruiters
|
[Fixed] stormtrooper medics are no longer recruiters
Change-Id: I3f0ce80cae39054b48300a384fe1142e50d129f4
|
Lua
|
agpl-3.0
|
Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo
|
6617f526a2a6d3f201df8180f9d01a6124074ff6
|
Bilinear.lua
|
Bilinear.lua
|
local Bilinear, parent = torch.class('nn.Bilinear', 'nn.Module')
local function isint(x) return type(x) == 'number' and x == math.floor(x) end
function Bilinear:__assertInput(input)
assert(input and type(input) == 'table' and #input == 2,
'input should be a table containing two data Tensors')
assert(input[1]:nDimension() == 2 and input[2]:nDimension() == 2,
'input Tensors should be two-dimensional')
assert(input[1]:size(1) == input[2]:size(1),
'input Tensors should have the same number of rows (instances)')
assert(input[1]:size(2) == self.weight:size(2),
'dimensionality of first input is erroneous')
assert(input[2]:size(2) == self.weight:size(3),
'dimensionality of second input is erroneous')
end
function Bilinear:__assertInputGradOutput(input, gradOutput)
assert(input[1]:size(1) == gradOutput:size(1),
'number of rows in gradOutput does not match input')
assert(gradOutput:size(2) == self.weight:size(1),
'number of columns in gradOutput does not output size of layer')
end
function Bilinear:__init(inputSize1, inputSize2, outputSize, bias)
-- assertions:
assert(self and inputSize1 and inputSize2 and outputSize,
'should specify inputSize1 and inputSize2 and outputSize')
assert(isint(inputSize1) and isint(inputSize2) and isint(outputSize),
'inputSize1 and inputSize2 and outputSize should be integer numbers')
assert(inputSize1 > 0 and inputSize2 > 0 and outputSize > 0,
'inputSize1 and inputSize2 and outputSize should be positive numbers')
-- set up model:
parent.__init(self)
local bias = ((bias == nil) and true) or bias
self.weight = torch.Tensor(outputSize, inputSize1, inputSize2)
self.gradWeight = torch.Tensor(outputSize, inputSize1, inputSize2)
if bias then
self.bias = torch.Tensor(outputSize)
self.gradBias = torch.Tensor(outputSize)
end
self.gradInput = {torch.Tensor(), torch.Tensor()}
self:reset()
end
function Bilinear:reset(stdv)
assert(self)
if stdv then
assert(stdv and type(stdv) == 'number' and stdv > 0,
'standard deviation should be a positive number')
stdv = stdv * math.sqrt(3)
else
stdv = 1 / math.sqrt(self.weight:size(2))
end
self.weight:uniform(-stdv, stdv)
if self.bias then self.bias:uniform(-stdv, stdv) end
return self
end
function Bilinear:updateOutput(input)
assert(self)
self:__assertInput(input)
-- set up buffer:
self.buff = self.buff or input[1].new()
self.buff:resizeAs(input[2])
-- compute output scores:
self.output:resize(input[1]:size(1), self.weight:size(1))
for k = 1,self.weight:size(1) do
torch.mm(self.buff, input[1], self.weight[k])
self.buff:cmul(input[2])
torch.sum(self.output:narrow(2, k, 1), self.buff, 2)
end
self.output:add(
self.bias:reshape(1, self.bias:nElement()):expandAs(self.output)
)
return self.output
end
function Bilinear:updateGradInput(input, gradOutput)
assert(self)
if self.gradInput then
self:__assertInputGradOutput(input, gradOutput)
-- compute d output / d input:
self.gradInput[1]:resizeAs(input[1]):fill(0)
self.gradInput[2]:resizeAs(input[2]):fill(0)
if torch.type(self.weight, 'torch.CudaTensor') then
for k = 1,self.weight:size(1) do
torch.addmm(self.gradInput[1], input[2], self.weight[k]:t())
torch.addmm(self.gradInput[2], input[1], self.weight[k])
end -- TODO: Remove this once cutorch gets addbmm() function
else
self.gradInput[1]:addbmm(
input[2]:view(1, input[2]:size(1), input[2]:size(2)):expand(
self.weight:size(1), input[2]:size(1), input[2]:size(2)
),
self.weight:transpose(2, 3)
)
self.gradInput[2]:addbmm(
input[1]:view(1, input[1]:size(1), input[1]:size(2)):expand(
self.weight:size(1), input[1]:size(1), input[1]:size(2)
), self.weight
)
end
return self.gradInput
end
end
function Bilinear:accGradParameters(input, gradOutput, scale)
local scale = scale or 1
self:__assertInputGradOutput(input, gradOutput)
assert(scale and type(scale) == 'number' and scale >= 0)
-- make sure we have buffer:
self.buff = self.buff or input[1].new()
self.buff:resizeAs(input[2])
-- accumulate parameter gradients:
for k = 1,self.weight:size(1) do
torch.cmul(
self.buff, input[1], gradOutput:narrow(2, k, 1):expandAs(input[1])
)
self.gradWeight[k]:addmm(self.buff:t(), input[2])
end
if self.bias then self.gradBias:add(scale, gradOutput:sum(1)) end
end
-- we do not need to accumulate parameters when sharing:
Bilinear.sharedAccUpdateGradParameters = Bilinear.accUpdateGradParameters
function Bilinear:__tostring__()
return torch.type(self) ..
string.format(
'(%dx%d -> %d) %s',
self.weight:size(2), self.weight:size(3), self.weight:size(1),
(self.bias == nil and ' without bias' or '')
)
end
|
local Bilinear, parent = torch.class('nn.Bilinear', 'nn.Module')
local function isint(x) return type(x) == 'number' and x == math.floor(x) end
function Bilinear:__assertInput(input)
assert(input and type(input) == 'table' and #input == 2,
'input should be a table containing two data Tensors')
assert(input[1]:nDimension() == 2 and input[2]:nDimension() == 2,
'input Tensors should be two-dimensional')
assert(input[1]:size(1) == input[2]:size(1),
'input Tensors should have the same number of rows (instances)')
assert(input[1]:size(2) == self.weight:size(2),
'dimensionality of first input is erroneous')
assert(input[2]:size(2) == self.weight:size(3),
'dimensionality of second input is erroneous')
end
function Bilinear:__assertInputGradOutput(input, gradOutput)
assert(input[1]:size(1) == gradOutput:size(1),
'number of rows in gradOutput does not match input')
assert(gradOutput:size(2) == self.weight:size(1),
'number of columns in gradOutput does not output size of layer')
end
function Bilinear:__init(inputSize1, inputSize2, outputSize, bias)
-- assertions:
assert(self and inputSize1 and inputSize2 and outputSize,
'should specify inputSize1 and inputSize2 and outputSize')
assert(isint(inputSize1) and isint(inputSize2) and isint(outputSize),
'inputSize1 and inputSize2 and outputSize should be integer numbers')
assert(inputSize1 > 0 and inputSize2 > 0 and outputSize > 0,
'inputSize1 and inputSize2 and outputSize should be positive numbers')
-- set up model:
parent.__init(self)
local bias = ((bias == nil) and true) or bias
self.weight = torch.Tensor(outputSize, inputSize1, inputSize2)
self.gradWeight = torch.Tensor(outputSize, inputSize1, inputSize2)
if bias then
self.bias = torch.Tensor(outputSize)
self.gradBias = torch.Tensor(outputSize)
end
self.gradInput = {torch.Tensor(), torch.Tensor()}
self:reset()
end
function Bilinear:reset(stdv)
assert(self)
if stdv then
assert(stdv and type(stdv) == 'number' and stdv > 0,
'standard deviation should be a positive number')
stdv = stdv * math.sqrt(3)
else
stdv = 1 / math.sqrt(self.weight:size(2))
end
self.weight:uniform(-stdv, stdv)
if self.bias then self.bias:uniform(-stdv, stdv) end
return self
end
function Bilinear:updateOutput(input)
assert(self)
self:__assertInput(input)
-- set up buffer:
self.buff = self.buff or input[1].new()
self.buff:resizeAs(input[2])
-- compute output scores:
self.output:resize(input[1]:size(1), self.weight:size(1))
for k = 1,self.weight:size(1) do
torch.mm(self.buff, input[1], self.weight[k])
self.buff:cmul(input[2])
torch.sum(self.output:narrow(2, k, 1), self.buff, 2)
end
if self.bias then
self.output:add(
self.bias:reshape(1, self.bias:nElement()):expandAs(self.output)
)
end
return self.output
end
function Bilinear:updateGradInput(input, gradOutput)
assert(self)
if self.gradInput then
self:__assertInputGradOutput(input, gradOutput)
-- compute d output / d input:
self.gradInput[1]:resizeAs(input[1]):fill(0)
self.gradInput[2]:resizeAs(input[2]):fill(0)
if torch.type(self.weight, 'torch.CudaTensor') then
for k = 1,self.weight:size(1) do
torch.addmm(self.gradInput[1], input[2], self.weight[k]:t())
torch.addmm(self.gradInput[2], input[1], self.weight[k])
end -- TODO: Remove this once cutorch gets addbmm() function
else
self.gradInput[1]:addbmm(
input[2]:view(1, input[2]:size(1), input[2]:size(2)):expand(
self.weight:size(1), input[2]:size(1), input[2]:size(2)
),
self.weight:transpose(2, 3)
)
self.gradInput[2]:addbmm(
input[1]:view(1, input[1]:size(1), input[1]:size(2)):expand(
self.weight:size(1), input[1]:size(1), input[1]:size(2)
), self.weight
)
end
return self.gradInput
end
end
function Bilinear:accGradParameters(input, gradOutput, scale)
local scale = scale or 1
self:__assertInputGradOutput(input, gradOutput)
assert(scale and type(scale) == 'number' and scale >= 0)
-- make sure we have buffer:
self.buff = self.buff or input[1].new()
self.buff:resizeAs(input[2])
-- accumulate parameter gradients:
for k = 1,self.weight:size(1) do
torch.cmul(
self.buff, input[1], gradOutput:narrow(2, k, 1):expandAs(input[1])
)
self.gradWeight[k]:addmm(self.buff:t(), input[2])
end
if self.bias then self.gradBias:add(scale, gradOutput:sum(1)) end
end
-- we do not need to accumulate parameters when sharing:
Bilinear.sharedAccUpdateGradParameters = Bilinear.accUpdateGradParameters
function Bilinear:__tostring__()
return torch.type(self) ..
string.format(
'(%dx%d -> %d) %s',
self.weight:size(2), self.weight:size(3), self.weight:size(1),
(self.bias == nil and ' without bias' or '')
)
end
|
fixing bilinear bias-free path
|
fixing bilinear bias-free path
|
Lua
|
bsd-3-clause
|
joeyhng/nn,xianjiec/nn,apaszke/nn,diz-vara/nn,jonathantompson/nn,PraveerSINGH/nn,kmul00/nn,andreaskoepf/nn,nicholas-leonard/nn,eriche2016/nn,sagarwaghmare69/nn,jhjin/nn,colesbury/nn,caldweln/nn,elbamos/nn
|
95fad443fd00d02d42746235e06bc8ede28564b3
|
LocalSpatialConvolution.lua
|
LocalSpatialConvolution.lua
|
local C = ccn2.C
local SpatialConvolution, parent = torch.class('ccn2.SpatialConvolution', 'nn.Module')
function SpatialConvolution:__init(nInputPlane, nOutputPlane, kH, dH, padding)
parent.__init(self)
dH = dH or 1 -- stride
padding = padding or 0
if not (nInputPlane >= 1 and (nInputPlane <= 3 or math.fmod(nInputPlane, 4) == 0)) then
error('Assertion failed: [(nInputPlane >= 1 and (nInputPlane <= 3 or math.fmod(nInputPlane, 4)))]. Number of input channels has to be 1, 2, 3 or a multiple of 4')
end
if math.fmod(nOutputPlane, 16) ~= 0 then
error('Assertion failed: [math.fmod(nOutputPlane, 16) == 0]. Number of output planes has to be a multiple of 16.')
end
self.nInputPlane = nInputPlane
self.nOutputPlane = nOutputPlane
self.kH = kH
self.dH = dH
self.padding = padding
local oH = math.floor((self.padding * 2 + input:size(2) - self.kH) / self.dH + 1);
local outputSize = oH*oH
local filterSize = self.kH*self.kH
self.weight = torch.Tensor(outputSize*nInputPlane*filterSize, nOutputPlane)
self.bias = torch.Tensor(outputSize*nOutputPlane)
self.gradWeight = torch.Tensor(outputSize*nInputPlane*filterSize, nOutputPlane)
self.gradBias = torch.Tensor(outputSize*nOutputPlane)
self.gradInput = torch.Tensor()
self.output = torch.Tensor()
self:reset()
self:cuda()
end
function SpatialConvolution:reset(stdv)
if stdv then
stdv = stdv * math.sqrt(3)
else
stdv = 1/math.sqrt(self.kH*self.kH*self.nInputPlane)
end
self.weight:uniform(-stdv, stdv)
self.bias:uniform(-stdv, stdv)
end
function SpatialConvolution:updateOutput(input)
ccn2.typecheck(input)
ccn2.inputcheck(input)
local nBatch = input:size(4)
local oH = math.floor((self.padding * 2 + input:size(2) - self.kH) / self.dH + 1);
local inputC = input:view(input:size(1) * input:size(2) * input:size(3),
input:size(4))
-- do convolution
C['localFilterActs'](inputC:cdata(), self.weight:cdata(), self.output:cdata(),
input:size(2), oH, oH, -self.padding, self.dH, self.nInputPlane, 1);
-- add bias
self.output = self.output:view(self.nOutputPlane, oH*oH*nBatch)
C['addBias'](self.output:cdata(), self.bias:cdata());
self.output = self.output:view(self.nOutputPlane, oH, oH, nBatch)
return self.output
end
function SpatialConvolution:updateGradInput(input, gradOutput)
ccn2.typecheck(input); ccn2.typecheck(gradOutput);
ccn2.inputcheck(input); ccn2.inputcheck(gradOutput);
local oH = gradOutput:size(2);
local iH = input:size(2)
local nBatch = input:size(4)
self.gradInput:resize(self.nInputPlane*iH*iH, nBatch);
local gradOutputC = gradOutput:view(
gradOutput:size(1) * gradOutput:size(2) * gradOutput:size(3), gradOutput:size(4)
)
C['localImgActs'](gradOutputC:cdata(), self.weight:cdata(), self.gradInput:cdata(),
iH, iH, oH, -self.padding, self.dH, self.nInputPlane, 1);
self.gradInput = self.gradInput:view(self.nInputPlane, iH, iH, nBatch)
return self.gradInput
end
function SpatialConvolution:accGradParameters(input, gradOutput, scale)
scale = scale or 1
ccn2.typecheck(input); ccn2.typecheck(gradOutput);
ccn2.inputcheck(input); ccn2.inputcheck(gradOutput);
local oH = gradOutput:size(2);
local iH = input:size(2)
local nBatch = input:size(4)
local inputC = input:view(input:size(1) * input:size(2) * input:size(3), input:size(4))
local gradOutputC = gradOutput:view(gradOutput:size(1) * gradOutput:size(2) * gradOutput:size(3), gradOutput:size(4))
C['localWeightActsSt'](inputC:cdata(), gradOutputC:cdata(), self.gradWeight:cdata(),
iH, oH, oH, self.kH,
-self.padding, self.dH, self.nInputPlane, 1, 0, scale);
gradOutputC = gradOutput:view(self.nOutputPlane, oH * oH * nBatch)
C['gradBias'](gradOutputC:cdata(), self.gradBias:cdata(), scale);
end
|
local C = ccn2.C
local LocalSpatialConvolution, parent = torch.class('ccn2.LocalSpatialConvolution', 'nn.Module')
function LocalSpatialConvolution:__init(nInputPlane, nOutputPlane, ini, kH, dH, padding)
parent.__init(self)
dH = dH or 1 -- stride
padding = padding or 0
if not (nInputPlane >= 1 and (nInputPlane <= 3 or math.fmod(nInputPlane, 4) == 0)) then
error('Assertion failed: [(nInputPlane >= 1 and (nInputPlane <= 3 or math.fmod(nInputPlane, 4)))]. Number of input channels has to be 1, 2, 3 or a multiple of 4')
end
if math.fmod(nOutputPlane, 16) ~= 0 then
error('Assertion failed: [math.fmod(nOutputPlane, 16) == 0]. Number of output planes has to be a multiple of 16.')
end
self.nInputPlane = nInputPlane
self.nOutputPlane = nOutputPlane
self.kH = kH
self.dH = dH
self.padding = padding
self.oH = math.floor((self.padding * 2 + ini - self.kH) / self.dH + 1)
local outputSize = self.oH*self.oH
local filterSize = self.kH*self.kH
self.weight = torch.Tensor(outputSize*nInputPlane*filterSize, nOutputPlane)
self.bias = torch.Tensor(outputSize*nOutputPlane)
self.gradWeight = torch.Tensor(outputSize*nInputPlane*filterSize, nOutputPlane)
self.gradBias = torch.Tensor(outputSize*nOutputPlane)
self.gradInput = torch.Tensor()
self.output = torch.Tensor()
self:reset()
self:cuda()
end
function LocalSpatialConvolution:reset(stdv)
if stdv then
stdv = stdv * math.sqrt(3)
else
stdv = 1/math.sqrt(self.kH*self.kH*self.nInputPlane)
end
self.weight:uniform(-stdv, stdv)
self.bias:uniform(-stdv, stdv)
end
function LocalSpatialConvolution:updateOutput(input)
ccn2.typecheck(input)
ccn2.inputcheck(input)
local nBatch = input:size(4)
local oH = math.floor((self.padding * 2 + input:size(2) - self.kH) / self.dH + 1);
local inputC = input:view(input:size(1) * input:size(2) * input:size(3),
input:size(4))
-- do convolution
C['localFilterActs'](inputC:cdata(), self.weight:cdata(), self.output:cdata(),
input:size(2), oH, oH, -self.padding, self.dH, self.nInputPlane, 1);
-- add bias
self.output = self.output:view(self.nOutputPlane, oH*oH*nBatch)
C['addBias'](self.output:cdata(), self.bias:cdata());
self.output = self.output:view(self.nOutputPlane, oH, oH, nBatch)
return self.output
end
function LocalSpatialConvolution:updateGradInput(input, gradOutput)
ccn2.typecheck(input); ccn2.typecheck(gradOutput);
ccn2.inputcheck(input); ccn2.inputcheck(gradOutput);
local oH = gradOutput:size(2);
local iH = input:size(2)
local nBatch = input:size(4)
self.gradInput:resize(self.nInputPlane*iH*iH, nBatch);
local gradOutputC = gradOutput:view(
gradOutput:size(1) * gradOutput:size(2) * gradOutput:size(3), gradOutput:size(4)
)
C['localImgActs'](gradOutputC:cdata(), self.weight:cdata(), self.gradInput:cdata(),
iH, iH, oH, -self.padding, self.dH, self.nInputPlane, 1);
self.gradInput = self.gradInput:view(self.nInputPlane, iH, iH, nBatch)
return self.gradInput
end
function LocalSpatialConvolution:accGradParameters(input, gradOutput, scale)
scale = scale or 1
ccn2.typecheck(input); ccn2.typecheck(gradOutput);
ccn2.inputcheck(input); ccn2.inputcheck(gradOutput);
local oH = gradOutput:size(2);
local iH = input:size(2)
local nBatch = input:size(4)
local inputC = input:view(input:size(1) * input:size(2) * input:size(3), input:size(4))
local gradOutputC = gradOutput:view(gradOutput:size(1) * gradOutput:size(2) * gradOutput:size(3), gradOutput:size(4))
C['localWeightActsSt'](inputC:cdata(), gradOutputC:cdata(), self.gradWeight:cdata(),
iH, oH, oH, self.kH,
-self.padding, self.dH, self.nInputPlane, 1, 0, scale);
gradOutputC = gradOutput:view(self.nOutputPlane, oH * oH * nBatch)
C['gradBias'](gradOutputC:cdata(), self.gradBias:cdata(), scale);
end
|
fixed class name issue
|
fixed class name issue
|
Lua
|
apache-2.0
|
monikajhuria/cuda-convnet2.torch-master_update,ajtao/my_ccn2_t,szagoruyko/cuda-convnet2.torch,szagoruyko/cuda-convnet2.torch,ajtao/my_ccn2_t,soumith/cuda-convnet2.torch,szagoruyko/cuda-convnet2.torch,ajtao/my_ccn2_t,soumith/cuda-convnet2.torch,soumith/cuda-convnet2.torch,monikajhuria/cuda-convnet2.torch-master_update,monikajhuria/cuda-convnet2.torch-master_update,szagoruyko/cuda-convnet2.torch
|
141b85dbe72535082563f7642b5085e89dde6a24
|
MapTable.lua
|
MapTable.lua
|
local MapTable, parent = torch.class('nn.MapTable', 'nn.Container')
function MapTable:__init(module, shared)
parent.__init(self)
self.shared = shared or {'weight', 'bias', 'gradWeight', 'gradBias'}
self.output = {}
self.gradInput = {}
self:add(module)
end
function MapTable:_extend(n)
self.modules[1] = self.module
for i = 2, n do
if not self.modules[i] then
self.modules[i] = self.module:clone(table.unpack(self.shared))
end
end
end
function MapTable:resize(n)
self:_extend(n)
for i = n + 1, #self.modules do
self.modules[i] = nil
end
end
function MapTable:add(module)
assert(not self.module, 'Single module required')
self.module = module
self.modules[1] = self.module
return self
end
function MapTable:updateOutput(input)
self.output = {}
self:_extend(#input)
for i = 1, #input do
self.output[i] = self:rethrowErrors(self.modules[i], i, 'updateOutput', input[i])
end
return self.output
end
function MapTable:updateGradInput(input, gradOutput)
self.gradInput = {}
self:_extend(#input)
for i = 1, #input do
self.gradInput[i] = self:rethrowErrors(self.modules[i], i, 'updateGradInput', input[i], gradOutput[i])
end
return self.gradInput
end
function MapTable:accGradParameters(input, gradOutput, scale)
scale = scale or 1
self:_extend(#input)
for i = 1, #input do
self:rethrowErrors(self.modules[i], i, 'accGradParameters', input[i], gradOutput[i], scale)
end
end
function MapTable:accUpdateGradParameters(input, gradOutput, lr)
lr = lr or 1
self:_extend(#input)
for i = 1, #input do
self:rethrowErrors(self.modules[i], i, 'accUpdateGradParameters', input[i], gradOutput[i], lr)
end
end
function MapTable:zeroGradParameters()
if self.module then
self.module:zeroGradParameters()
end
end
function MapTable:updateParameters(learningRate)
if self.module then
self.module:updateParameters(learningRate)
end
end
function MapTable:clearState()
for i = 2, #self.modules do
self.modules[i] = nil
end
parent.clearState(self)
end
function MapTable:__tostring__()
local tab = ' '
local line = '\n'
local extlast = ' '
local str = torch.type(self)
if self.module then
str = str .. ' {' .. line .. tab
str = str .. tostring(self.module):gsub(line, line .. tab .. extlast) .. line .. '}'
else
str = str .. ' { }'
end
return str
end
|
local MapTable, parent = torch.class('nn.MapTable', 'nn.Container')
function MapTable:__init(module, shared)
parent.__init(self)
self.shared = shared or {'weight', 'bias', 'gradWeight', 'gradBias'}
self.output = {}
self.gradInput = {}
self:add(module)
end
function MapTable:_extend(n)
self.modules[1] = self.module
for i = 2, n do
if not self.modules[i] then
self.modules[i] = self.module:clone(table.unpack(self.shared))
end
end
end
function MapTable:resize(n)
self:_extend(n)
for i = n + 1, #self.modules do
-- It's not clear why this clearState call is necessary, but it fixes
-- https://github.com/torch/nn/issues/1141 .
self.modules[i]:clearState()
self.modules[i] = nil
end
end
function MapTable:add(module)
assert(not self.module, 'Single module required')
self.module = module
self.modules[1] = self.module
return self
end
function MapTable:updateOutput(input)
self.output = {}
self:_extend(#input)
for i = 1, #input do
self.output[i] = self:rethrowErrors(self.modules[i], i, 'updateOutput', input[i])
end
return self.output
end
function MapTable:updateGradInput(input, gradOutput)
self.gradInput = {}
self:_extend(#input)
for i = 1, #input do
self.gradInput[i] = self:rethrowErrors(self.modules[i], i, 'updateGradInput', input[i], gradOutput[i])
end
return self.gradInput
end
function MapTable:accGradParameters(input, gradOutput, scale)
scale = scale or 1
self:_extend(#input)
for i = 1, #input do
self:rethrowErrors(self.modules[i], i, 'accGradParameters', input[i], gradOutput[i], scale)
end
end
function MapTable:accUpdateGradParameters(input, gradOutput, lr)
lr = lr or 1
self:_extend(#input)
for i = 1, #input do
self:rethrowErrors(self.modules[i], i, 'accUpdateGradParameters', input[i], gradOutput[i], lr)
end
end
function MapTable:zeroGradParameters()
if self.module then
self.module:zeroGradParameters()
end
end
function MapTable:updateParameters(learningRate)
if self.module then
self.module:updateParameters(learningRate)
end
end
function MapTable:clearState()
for i = 2, #self.modules do
-- It's not clear why this clearState call is necessary, but it fixes
-- https://github.com/torch/nn/issues/1141 .
self.modules[i]:clearState()
self.modules[i] = nil
end
parent.clearState(self)
end
function MapTable:__tostring__()
local tab = ' '
local line = '\n'
local extlast = ' '
local str = torch.type(self)
if self.module then
str = str .. ' {' .. line .. tab
str = str .. tostring(self.module):gsub(line, line .. tab .. extlast) .. line .. '}'
else
str = str .. ' { }'
end
return str
end
|
Fix memory issue with MapTable module removal
|
Fix memory issue with MapTable module removal
Fixes Issue #1141: https://github.com/torch/nn/issues/1141
|
Lua
|
bsd-3-clause
|
joeyhng/nn,apaszke/nn,nicholas-leonard/nn
|
16fa2856c18f7de34b2fc0b49c9fbb7bd1f7b998
|
libs/uvl/luasrc/uvl/errors.lua
|
libs/uvl/luasrc/uvl/errors.lua
|
--[[
UCI Validation Layer - Error handling
(c) 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
(c) 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local uci = require "luci.model.uci"
local uvl = require "luci.uvl"
local util = require "luci.util"
local string = require "string"
local ipairs, error, type = ipairs, error, type
local tonumber, unpack = tonumber, unpack
local luci = luci
module "luci.uvl.errors"
ERRCODES = {
{ 'UCILOAD', 'Unable to load config "%p": %1' },
{ 'SCHEME', 'Error in scheme "%p":\n%c' },
{ 'CONFIG', 'Error in config "%p":\n%c' },
{ 'SECTION', 'Error in section "%i" (%I):\n%c' },
{ 'OPTION', 'Error in option "%i" (%I):\n%c' },
{ 'REFERENCE', 'Option "%i" has invalid reference specification %1:\n%c' },
{ 'DEPENDENCY', 'In dependency check for %t "%i":\n%c' },
{ 'SME_FIND', 'Can not find scheme "%p" in "%1"' },
{ 'SME_READ', 'Can not access file "%1"' },
{ 'SME_REQFLD', 'Missing required scheme field "%1" in "%i"' },
{ 'SME_INVREF', 'Illegal reference "%1" to an anonymous section' },
{ 'SME_BADREF', 'Malformed reference in "%1"' },
{ 'SME_BADDEP', 'Malformed dependency specification "%1" in "%i"' },
{ 'SME_BADVAL', 'Malformed validator specification "%1" in "%i"' },
{ 'SME_ERRVAL', 'External validator "%1" failed: %2' },
{ 'SME_VBADPACK', 'Variable "%o" in scheme "%p" references unknown package "%1"' },
{ 'SME_VBADSECT', 'Variable "%o" in scheme "%p" references unknown section "%1"' },
{ 'SME_EBADPACK', 'Enum "%v" in scheme "%p" references unknown package "%1"' },
{ 'SME_EBADSECT', 'Enum "%v" in scheme "%p" references unknown section "%1"' },
{ 'SME_EBADOPT', 'Enum "%v" in scheme "%p" references unknown option "%1"' },
{ 'SME_EBADTYPE', 'Enum "%v" in scheme "%p" references non-enum option "%I"' },
{ 'SME_EBADDEF', 'Enum "%v" in scheme "%p" redeclares the default value of "%I"' },
{ 'SECT_UNKNOWN', 'Section "%i" (%I) not found in scheme' },
{ 'SECT_REQUIRED', 'Required section "%p.%S" not found in config' },
{ 'SECT_UNIQUE', 'Unique section "%p.%S" occurs multiple times in config' },
{ 'SECT_NAMED', 'The section of type "%p.%S" is stored anonymously in config but must be named' },
{ 'SECT_NOTFOUND', 'Section "%p.%s" not found in config' },
{ 'OPT_UNKNOWN', 'Option "%i" (%I) not found in scheme' },
{ 'OPT_REQUIRED', 'Required option "%i" has no value' },
{ 'OPT_BADVALUE', 'Value "%1" of option "%i" is not defined in enum %2' },
{ 'OPT_INVVALUE', 'Value "%1" of option "%i" does not validate as datatype "%2"' },
{ 'OPT_NOTLIST', 'Option "%i" is defined as list but stored as plain value' },
{ 'OPT_DATATYPE', 'Option "%i" has unknown datatype "%1"' },
{ 'OPT_NOTFOUND', 'Option "%p.%s.%o" not found in config' },
{ 'OPT_RANGE', 'Option "%p.%s.%o" is not within the specified range' },
{ 'DEP_NOTEQUAL', 'Dependency (%1) failed:\nOption "%i" is not eqal "%2"' },
{ 'DEP_NOVALUE', 'Dependency (%1) failed:\nOption "%i" has no value' },
{ 'DEP_NOTVALID', 'Dependency (%1) failed:\n%c' },
{ 'DEP_RECURSIVE', 'Recursive dependency for option "%i" detected' },
{ 'DEP_BADENUM', 'In dependency check for enum value "%i":\n%c' }
}
-- build error constants and instance constructors
for i, v in ipairs(ERRCODES) do
_M[v[1]] = function(...)
return error(i, ...)
end
_M['ERR_'..v[1]] = i
end
function i18n(key, def)
if luci.i18n then
return luci.i18n.translate(key,def)
else
return def
end
end
error = util.class()
function error.__init__(self, code, pso, args)
self.code = code
self.args = ( type(args) == "table" and args or { args } )
if util.instanceof( pso, uvl.uvlitem ) then
self.stype = pso.sref[2]
self.package, self.section, self.option, self.value = unpack(pso.cref)
self.object = pso
self.value = self.value or ( pso.value and pso:value() )
else
pso = ( type(pso) == "table" and pso or { pso } )
if pso[2] then
local uci = uci.cursor()
self.stype = uci:get(pso[1], pso[2]) or pso[2]
end
self.package, self.section, self.option, self.value = unpack(pso)
end
end
function error.child(self, err)
if not self.childs then
self.childs = { err }
else
self.childs[#self.childs+1] = err
end
return self
end
function error.string(self,pad)
pad = pad or " "
local str = i18n(
'uvl_err_%s' % string.lower(ERRCODES[self.code][1]),
ERRCODES[self.code][2]
)
:gsub("\n", "\n"..pad)
:gsub("%%i", self:cid())
:gsub("%%I", self:sid())
:gsub("%%p", self.package or '(nil)')
:gsub("%%s", self.section or '(nil)')
:gsub("%%S", self.stype or '(nil)')
:gsub("%%o", self.option or '(nil)')
:gsub("%%v", self.value or '(nil)')
:gsub("%%t", self.object and self.object:type() or '(nil)' )
:gsub("%%T", self.object and self.object:title() or '(nil)' )
:gsub("%%([1-9])", function(n) return self.args[tonumber(n)] or '(nil)' end)
:gsub("%%c",
function()
local s = ""
for _, err in ipairs(self.childs or {}) do
s = s .. err:string(pad.." ") .. "\n" .. pad
end
return s
end
)
return (str:gsub("%s+$",""))
end
function error.cid(self)
return self.object and self.object:cid() or self.package ..
( self.section and '.' .. self.section or '' ) ..
( self.option and '.' .. self.option or '' ) ..
( self.value and '.' .. self.value or '' )
end
function error.sid(self)
return self.object and self.object:sid() or self.package ..
( self.stype and '.' .. self.stype or '' ) ..
( self.option and '.' .. self.option or '' ) ..
( self.value and '.' .. self.value or '' )
end
function error.is(self, code)
if self.code == code then
return true
elseif self.childs then
for _, c in ipairs(self.childs) do
if c:is(code) then
return true
end
end
end
return false
end
function error.is_all(self, ...)
local codes = { ... }
if util.contains(codes, self.code) then
return true
else
local equal = false
for _, c in ipairs(self.childs) do
if c.childs then
equal = c:is_all(...)
else
equal = util.contains(codes, c.code)
end
end
return equal
end
end
|
--[[
UCI Validation Layer - Error handling
(c) 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
(c) 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local uci = require "luci.model.uci"
local uvl = require "luci.uvl"
local util = require "luci.util"
local string = require "string"
local ipairs, error, type = ipairs, error, type
local tonumber, unpack = tonumber, unpack
local luci = luci
module "luci.uvl.errors"
ERRCODES = {
{ 'UCILOAD', 'Unable to load config "%p": %1' },
{ 'SCHEME', 'Error in scheme "%p":\n%c' },
{ 'CONFIG', 'Error in config "%p":\n%c' },
{ 'SECTION', 'Error in section "%i" (%I):\n%c' },
{ 'OPTION', 'Error in option "%i" (%I):\n%c' },
{ 'REFERENCE', 'Option "%i" has invalid reference specification %1:\n%c' },
{ 'DEPENDENCY', 'In dependency check for %t "%i":\n%c' },
{ 'SME_FIND', 'Can not find scheme "%p" in "%1"' },
{ 'SME_READ', 'Can not access file "%1"' },
{ 'SME_REQFLD', 'Missing required scheme field "%1" in "%i"' },
{ 'SME_INVREF', 'Illegal reference "%1" to an anonymous section' },
{ 'SME_BADREF', 'Malformed reference in "%1"' },
{ 'SME_BADDEP', 'Malformed dependency specification "%1" in "%i"' },
{ 'SME_BADVAL', 'Malformed validator specification "%1" in "%i"' },
{ 'SME_ERRVAL', 'External validator "%1" failed: %2' },
{ 'SME_VBADPACK', 'Variable "%o" in scheme "%p" references unknown package "%1"' },
{ 'SME_VBADSECT', 'Variable "%o" in scheme "%p" references unknown section "%1"' },
{ 'SME_EBADPACK', 'Enum "%v" in scheme "%p" references unknown package "%1"' },
{ 'SME_EBADSECT', 'Enum "%v" in scheme "%p" references unknown section "%1"' },
{ 'SME_EBADOPT', 'Enum "%v" in scheme "%p" references unknown option "%1"' },
{ 'SME_EBADTYPE', 'Enum "%v" in scheme "%p" references non-enum option "%I"' },
{ 'SME_EBADDEF', 'Enum "%v" in scheme "%p" redeclares the default value of "%I"' },
{ 'SECT_UNKNOWN', 'Section "%i" (%I) not found in scheme' },
{ 'SECT_REQUIRED', 'Required section "%p.%S" not found in config' },
{ 'SECT_UNIQUE', 'Unique section "%p.%S" occurs multiple times in config' },
{ 'SECT_NAMED', 'The section of type "%p.%S" is stored anonymously in config but must be named' },
{ 'SECT_NOTFOUND', 'Section "%p.%s" not found in config' },
{ 'OPT_UNKNOWN', 'Option "%i" (%I) not found in scheme' },
{ 'OPT_REQUIRED', 'Required option "%i" has no value' },
{ 'OPT_BADVALUE', 'Value "%1" of option "%i" is not defined in enum %2' },
{ 'OPT_INVVALUE', 'Value "%1" of option "%i" does not validate as datatype "%2"' },
{ 'OPT_NOTLIST', 'Option "%i" is defined as list but stored as plain value' },
{ 'OPT_DATATYPE', 'Option "%i" has unknown datatype "%1"' },
{ 'OPT_NOTFOUND', 'Option "%p.%s.%o" not found in config' },
{ 'OPT_RANGE', 'Option "%p.%s.%o" is not within the specified range' },
{ 'DEP_NOTEQUAL', 'Dependency (%1) failed:\nOption "%i" is not eqal "%2"' },
{ 'DEP_NOVALUE', 'Dependency (%1) failed:\nOption "%i" has no value' },
{ 'DEP_NOTVALID', 'Dependency (%1) failed:\n%c' },
{ 'DEP_RECURSIVE', 'Recursive dependency for option "%i" detected' },
{ 'DEP_BADENUM', 'In dependency check for enum value "%i":\n%c' }
}
-- build error constants and instance constructors
for i, v in ipairs(ERRCODES) do
_M[v[1]] = function(...)
return error(i, ...)
end
_M['ERR_'..v[1]] = i
end
function i18n(key)
if luci.i18n then
return luci.i18n.translate(key)
else
return key
end
end
error = util.class()
function error.__init__(self, code, pso, args)
self.code = code
self.args = ( type(args) == "table" and args or { args } )
if util.instanceof( pso, uvl.uvlitem ) then
self.stype = pso.sref[2]
self.package, self.section, self.option, self.value = unpack(pso.cref)
self.object = pso
self.value = self.value or ( pso.value and pso:value() )
else
pso = ( type(pso) == "table" and pso or { pso } )
if pso[2] then
local uci = uci.cursor()
self.stype = uci:get(pso[1], pso[2]) or pso[2]
end
self.package, self.section, self.option, self.value = unpack(pso)
end
end
function error.child(self, err)
if not self.childs then
self.childs = { err }
else
self.childs[#self.childs+1] = err
end
return self
end
function error.string(self,pad)
pad = pad or " "
local str = i18n(ERRCODES[self.code][2])
:gsub("\n", "\n"..pad)
:gsub("%%i", self:cid())
:gsub("%%I", self:sid())
:gsub("%%p", self.package or '(nil)')
:gsub("%%s", self.section or '(nil)')
:gsub("%%S", self.stype or '(nil)')
:gsub("%%o", self.option or '(nil)')
:gsub("%%v", self.value or '(nil)')
:gsub("%%t", self.object and self.object:type() or '(nil)' )
:gsub("%%T", self.object and self.object:title() or '(nil)' )
:gsub("%%([1-9])", function(n) return self.args[tonumber(n)] or '(nil)' end)
:gsub("%%c",
function()
local s = ""
for _, err in ipairs(self.childs or {}) do
s = s .. err:string(pad.." ") .. "\n" .. pad
end
return s
end
)
return (str:gsub("%s+$",""))
end
function error.cid(self)
return self.object and self.object:cid() or self.package ..
( self.section and '.' .. self.section or '' ) ..
( self.option and '.' .. self.option or '' ) ..
( self.value and '.' .. self.value or '' )
end
function error.sid(self)
return self.object and self.object:sid() or self.package ..
( self.stype and '.' .. self.stype or '' ) ..
( self.option and '.' .. self.option or '' ) ..
( self.value and '.' .. self.value or '' )
end
function error.is(self, code)
if self.code == code then
return true
elseif self.childs then
for _, c in ipairs(self.childs) do
if c:is(code) then
return true
end
end
end
return false
end
function error.is_all(self, ...)
local codes = { ... }
if util.contains(codes, self.code) then
return true
else
local equal = false
for _, c in ipairs(self.childs) do
if c.childs then
equal = c:is_all(...)
else
equal = util.contains(codes, c.code)
end
end
return equal
end
end
|
libs/uvl: fix i18n handling for errors
|
libs/uvl: fix i18n handling for errors
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@5475 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci
|
6aa4f7be48d0152046972f2e419209971e2dfe18
|
src/lua/Parallel.lua
|
src/lua/Parallel.lua
|
local zmq = require "lzmq"
local zloop = require "lzmq.loop"
local zthreads = require "lzmq.threads"
local mp = require "cmsgpack"
local zassert = zmq.assert
local ENDPOINT = "inproc://main"
local THREAD_STARTER = [[
local ENDPOINT = ]] .. ("%q"):format(ENDPOINT) .. [[
local zmq = require "lzmq"
local zthreads = require "lzmq.threads"
local mp = require "cmsgpack"
local zassert = zmq.assert
function FOR(do_work)
local ctx = zthreads.get_parent_ctx()
local s, err = ctx:socket{zmq.DEALER, connect = ENDPOINT}
if not s then return end
s:sendx(0, 'READY')
while not s:closed() do
local tid, cmd, args = s:recvx()
if not tid then
if cmd and (cmd:no() == zmq.errors.ETERM) then break end
zassert(nil, cmd)
end
assert(tid and cmd)
if cmd == 'END' then break end
assert(cmd == 'TASK', "invalid command " .. tostring(cmd))
assert(args, "invalid args in command")
local res, err = mp.pack( do_work(mp.unpack(args)) )
s:sendx(tid, 'RESP', res)
end
ctx:destroy()
end
]]
local function pcall_ret_pack(ok, ...)
if ok then return mp.pack(ok, ...) end
return nil, ...
end
local function pcall_ret(ok, ...)
if ok then return pcall_ret_pack(...) end
return nil, ...
end
local function ppcall(...)
return pcall_ret(pcall(...))
end
local function thread_alive(self)
local ok, err = self:join(0)
if ok then return false end
if err == 'timeout' then return true end
return nil, err
end
local function parallel_for_impl(code, src, snk, N, cache_size)
N = N or 4
-- @fixme do not change global state in zthreads library
zthreads.set_bootstrap_prelude(THREAD_STARTER)
local src_err, snk_err
local cache = {} -- заранее рассчитанные данные для заданий
local threads = {} -- рабочие потоки
local MAX_CACHE = cache_size or N
local function call_src()
if src and not src_err then
local args, err = ppcall(src)
if args then return args end
if err then
src_err = err
return nil, err
end
src = nil
end
end
local function next_src()
local args = table.remove(cache, 1)
if args then return args end
return call_src()
end
local function cache_src()
if #cache >= MAX_CACHE then return end
for i = #cache, MAX_CACHE do
local args = call_src()
if args then cache[#cache + 1] = args else break end
end
end
local loop = zloop.new()
local skt, err = loop:create_socket{zmq.ROUTER, bind = ENDPOINT}
zassert(skt, err)
loop:add_socket(skt, function(skt)
local identity, tid, cmd, args = skt:recvx()
zassert(tid, cmd)
if cmd ~= 'READY' then
assert(cmd == 'RESP')
if not snk_err then
if snk then
local ok, err = ppcall(snk, mp.unpack(args))
if not ok and err then snk_err = err end
end
else
skt:sendx(identity, tid, 'END')
return
end
end
if #cache == 0 then cache_src() end
local args, err = next_src()
if args ~= nil then
skt:sendx(identity, tid, 'TASK', args)
return
end
skt:sendx(identity, tid, 'END')
end)
-- watchdog
loop:add_interval(1000, function()
local alive = 0
for _, thread in ipairs(threads) do
if thread_alive(thread) then alive = alive + 1 end
end
if alive == 0 then loop:interrupt() end
end)
loop:add_interval(100, function(ev) cache_src() end)
local err
for i = 1, N do
local thread
thread, err = zthreads.run(loop:context(), code, i)
if thread and thread:start(true, true) then
threads[#threads + 1] = thread
end
end
if #threads == 0 then return nil, err end
loop:start()
loop:destroy()
for _, t in ipairs(threads) do t:join() end
if src_err or snk_err then
return nil, src_err or snk_err
end
return true
end
---
-- @tparam[number] be begin index
-- @tparam[number] en end index
-- @tparam[number?] step step
-- @tparam[string] code
-- @tparam[callable?] snk sink
-- @tparam[number?] N thread count
-- @tparam[number?] C cache size
local function For(be, en, step, code, snk, N, C)
if type(step) ~= 'number' then -- no step
step, code, snk, N, C = 1, step, code, snk, N
end
if type(snk) == 'number' then -- no sink
N, C = snk, N
end
assert(type(be) == "number")
assert(type(en) == "number")
assert(type(step) == "number")
assert(type(code) == "string")
local src = function()
if be > en then return end
local n = be
be = be + step
return n
end
return parallel_for_impl(code, src, snk, N, C)
end
---
-- @tparam[string] code
-- @tparam[callable?] snk sink
-- @tparam[number?] N thread count
-- @tparam[number?] C cache size
local function ForEach(it, code, snk, N, C)
local src = it
if type(it) == 'table' then
local k, v
src = function()
k, v = next(it, k)
return k, v
end
end
if type(snk) == 'number' then -- no sink
snk, N, C = nil, snk, N
end
assert(type(src) == "function")
assert(type(code) == "string")
return parallel_for_impl(code, src, snk, N, C)
end
local function Invoke(N, ...)
local code = string.dump(function() FOR(function(_,src)
if src:sub(1,1) == '@' then dofile(src:sub(2))
else assert((loadstring or load)(src))() end
end) end)
if type(N) == 'number' then
return ForEach({...}, code, N)
end
return ForEach({N, ...}, code)
end
local Parallel = {} do
Parallel.__index = Parallel
function Parallel:new(N)
local o = setmetatable({
thread_count = N or 4;
}, self)
o.cache_size = o.thread_count * 2
return o
end
function Parallel:For(be, en, step, code, snk)
return For(be, en, step, code, snk, self.thread_count, self.cache_size)
end
function Parallel:ForEach(src, code, snk)
return ForEach(src, code, snk, self.thread_count, self.cache_size)
end
function Parallel:Invoke(...)
return Invoke(self.thread_count, ...)
end
end
return {
For = For;
ForEach = ForEach;
Invoke = Invoke;
New = function(...) return Parallel:new(...) end
}
|
local zmq = require "lzmq"
local zloop = require "lzmq.loop"
local zthreads = require "lzmq.threads"
local mp = require "cmsgpack"
local zassert = zmq.assert
local ENDPOINT = "inproc://main"
local THREAD_STARTER = [[
local ENDPOINT = ]] .. ("%q"):format(ENDPOINT) .. [[
local zmq = require "lzmq"
local zthreads = require "lzmq.threads"
local mp = require "cmsgpack"
local zassert = zmq.assert
function FOR(do_work)
local ctx = zthreads.get_parent_ctx()
local s, err = ctx:socket{zmq.DEALER, connect = ENDPOINT}
if not s then return end
s:sendx(0, 'READY')
while not s:closed() do
local tid, cmd, args = s:recvx()
if not tid then
if cmd and (cmd:no() == zmq.errors.ETERM) then break end
zassert(nil, cmd)
end
assert(tid and cmd)
if cmd == 'END' then break end
assert(cmd == 'TASK', "invalid command " .. tostring(cmd))
assert(args, "invalid args in command")
local res, err = mp.pack( do_work(mp.unpack(args)) )
s:sendx(tid, 'RESP', res)
end
ctx:destroy()
end
]]
local function pcall_ret_pack(ok, ...)
if ok then return mp.pack(ok, ...) end
return nil, ...
end
local function pcall_ret(ok, ...)
if ok then return pcall_ret_pack(...) end
return nil, ...
end
local function ppcall(...)
return pcall_ret(pcall(...))
end
local function thread_alive(self)
local ok, err = self:join(0)
if ok then return false end
if err == 'timeout' then return true end
return nil, err
end
local function parallel_for_impl(code, src, snk, N, cache_size)
N = N or 4
-- @fixme do not change global state in zthreads library
zthreads.set_bootstrap_prelude(THREAD_STARTER)
local src_err, snk_err
local cache = {} -- заранее рассчитанные данные для заданий
local threads = {} -- рабочие потоки
local MAX_CACHE = cache_size or N
local function call_src()
if src and not src_err then
local args, err = ppcall(src)
if args then return args end
if err then
src_err = err
return nil, err
end
src = nil
end
end
local function next_src()
local args = table.remove(cache, 1)
if args then return args end
return call_src()
end
local function cache_src()
if #cache >= MAX_CACHE then return end
for i = #cache, MAX_CACHE do
local args = call_src()
if args then cache[#cache + 1] = args else break end
end
end
local loop = zloop.new()
local skt, err = loop:create_socket{zmq.ROUTER, bind = ENDPOINT}
zassert(skt, err)
loop:add_socket(skt, function(skt)
local identity, tid, cmd, args = skt:recvx()
zassert(tid, cmd)
if cmd ~= 'READY' then
assert(cmd == 'RESP')
if not snk_err then
if snk then
local ok, err = ppcall(snk, mp.unpack(args))
if not ok and err then snk_err = err end
end
else
skt:sendx(identity, tid, 'END')
return
end
end
if #cache == 0 then cache_src() end
local args, err = next_src()
if args ~= nil then
skt:sendx(identity, tid, 'TASK', args)
return
end
skt:sendx(identity, tid, 'END')
end)
-- watchdog
loop:add_interval(1000, function()
for _, thread in ipairs(threads) do
if thread_alive(thread) then return end
end
loop:interrupt()
end)
loop:add_interval(100, function(ev) cache_src() end)
local err
for i = 1, N do
local thread
thread, err = zthreads.run(loop:context(), code, i)
if thread and thread:start(true, true) then
threads[#threads + 1] = thread
end
end
if #threads == 0 then return nil, err end
loop:start()
loop:destroy()
for _, t in ipairs(threads) do t:join() end
if src_err or snk_err then
return nil, src_err or snk_err
end
return true
end
---
-- @tparam[number] be begin index
-- @tparam[number] en end index
-- @tparam[number?] step step
-- @tparam[string] code
-- @tparam[callable?] snk sink
-- @tparam[number?] N thread count
-- @tparam[number?] C cache size
local function For(be, en, step, code, snk, N, C)
if type(step) ~= 'number' then -- no step
step, code, snk, N, C = 1, step, code, snk, N
end
if type(snk) == 'number' then -- no sink
N, C = snk, N
end
assert(type(be) == "number")
assert(type(en) == "number")
assert(type(step) == "number")
assert(type(code) == "string")
local src = function()
if be > en then return end
local n = be
be = be + step
return n
end
return parallel_for_impl(code, src, snk, N, C)
end
---
-- @tparam[string] code
-- @tparam[callable?] snk sink
-- @tparam[number?] N thread count
-- @tparam[number?] C cache size
local function ForEach(it, code, snk, N, C)
local src = it
if type(it) == 'table' then
local k, v
src = function()
k, v = next(it, k)
return k, v
end
end
if type(snk) == 'number' then -- no sink
snk, N, C = nil, snk, N
end
assert(type(src) == "function")
assert(type(code) == "string")
return parallel_for_impl(code, src, snk, N, C)
end
local function Invoke(N, ...)
local code = string.dump(function() FOR(function(_,src)
if src:sub(1,1) == '@' then dofile(src:sub(2))
else assert((loadstring or load)(src))() end
end) end)
if type(N) == 'number' then
return ForEach({...}, code, N)
end
return ForEach({N, ...}, code)
end
local Parallel = {} do
Parallel.__index = Parallel
function Parallel:new(N)
local o = setmetatable({
thread_count = N or 4;
}, self)
o.cache_size = o.thread_count * 2
return o
end
function Parallel:For(be, en, step, code, snk)
return For(be, en, step, code, snk, self.thread_count, self.cache_size)
end
function Parallel:ForEach(src, code, snk)
return ForEach(src, code, snk, self.thread_count, self.cache_size)
end
function Parallel:Invoke(...)
return Invoke(self.thread_count, ...)
end
end
return {
For = For;
ForEach = ForEach;
Invoke = Invoke;
New = function(...) return Parallel:new(...) end
}
|
Fix. Watchdog test threads only until first alive thread.
|
Fix. Watchdog test threads only until first alive thread.
|
Lua
|
mit
|
moteus/lua-Parallel,kidaa/lua-Parallel
|
df32e586a3ad1a6c53639424986f96735082d3d8
|
modules/admin-full/luasrc/model/cbi/admin_system/fstab/mount.lua
|
modules/admin-full/luasrc/model/cbi/admin_system/fstab/mount.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2010 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local fs = require "nixio.fs"
local util = require "nixio.util"
local has_extroot = fs.access("/lib/preinit/00_extroot.conf")
local has_fscheck = fs.access("/lib/functions/fsck.sh")
local devices = {}
util.consume((fs.glob("/dev/sd*")), devices)
util.consume((fs.glob("/dev/hd*")), devices)
util.consume((fs.glob("/dev/scd*")), devices)
util.consume((fs.glob("/dev/mmc*")), devices)
local size = {}
for i, dev in ipairs(devices) do
local s = tonumber((fs.readfile("/sys/class/block/%s/size" % dev:sub(6))))
size[dev] = s and math.floor(s / 2048)
end
m = Map("fstab", translate("Mount Points - Mount Entry"))
m.redirect = luci.dispatcher.build_url("admin/system/fstab")
if not arg[1] or m.uci:get("fstab", arg[1]) ~= "mount" then
luci.http.redirect(m.redirect)
return
end
mount = m:section(NamedSection, arg[1], "mount", translate("Mount Entry"))
mount.anonymous = true
mount.addremove = false
mount:tab("general", translate("General Settings"))
mount:tab("advanced", translate("Advanced Settings"))
mount:taboption("general", Flag, "enabled", translate("Enable this mount")).rmempty = false
o = mount:taboption("general", Value, "device", translate("Device"),
translate("The device file of the memory or partition (<abbr title=\"for example\">e.g.</abbr> <code>/dev/sda1</code>)"))
for i, d in ipairs(devices) do
o:value(d, size[d] and "%s (%s MB)" % {d, size[d]})
end
o = mount:taboption("advanced", Value, "uuid", translate("UUID"),
translate("If specified, mount the device by its UUID instead of a fixed device node"))
o = mount:taboption("advanced", Value, "label", translate("Label"),
translate("If specified, mount the device by the partition label instead of a fixed device node"))
o = mount:taboption("general", Value, "target", translate("Mount point"),
translate("Specifies the directory the device is attached to"))
o:depends("is_rootfs", "")
o = mount:taboption("general", Value, "fstype", translate("Filesystem"),
translate("The filesystem that was used to format the memory (<abbr title=\"for example\">e.g.</abbr> <samp><abbr title=\"Third Extended Filesystem\">ext3</abbr></samp>)"))
local fs
for fs in io.lines("/proc/filesystems") do
fs = fs:match("%S+")
if fs ~= "nodev" then
o:value(fs)
end
end
o = mount:taboption("advanced", Value, "options", translate("Mount options"),
translate("See \"mount\" manpage for details"))
o.placeholder = "defaults"
if has_extroot then
o = mount:taboption("general", Flag, "is_rootfs", translate("Use as root filesystem"),
translate("Configures this mount as overlay storage for block-extroot"))
o:depends("fstype", "jffs")
o:depends("fstype", "ext2")
o:depends("fstype", "ext3")
o:depends("fstype", "ext4")
end
if has_fscheck then
o = mount:taboption("general", Flag, "enabled_fsck", translate("Run filesystem check"),
translate("Run a filesystem check before mounting the device"))
end
return m
|
--[[
LuCI - Lua Configuration Interface
Copyright 2010 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local fs = require "nixio.fs"
local util = require "nixio.util"
local has_extroot = fs.access("/sbin/block")
local has_fscheck = fs.access("/usr/sbin/e2fsck")
local devices = {}
util.consume((fs.glob("/dev/sd*")), devices)
util.consume((fs.glob("/dev/hd*")), devices)
util.consume((fs.glob("/dev/scd*")), devices)
util.consume((fs.glob("/dev/mmc*")), devices)
local size = {}
for i, dev in ipairs(devices) do
local s = tonumber((fs.readfile("/sys/class/block/%s/size" % dev:sub(6))))
size[dev] = s and math.floor(s / 2048)
end
m = Map("fstab", translate("Mount Points - Mount Entry"))
m.redirect = luci.dispatcher.build_url("admin/system/fstab")
if not arg[1] or m.uci:get("fstab", arg[1]) ~= "mount" then
luci.http.redirect(m.redirect)
return
end
mount = m:section(NamedSection, arg[1], "mount", translate("Mount Entry"))
mount.anonymous = true
mount.addremove = false
mount:tab("general", translate("General Settings"))
mount:tab("advanced", translate("Advanced Settings"))
mount:taboption("general", Flag, "enabled", translate("Enable this mount")).rmempty = false
o = mount:taboption("general", Value, "device", translate("Device"),
translate("The device file of the memory or partition (<abbr title=\"for example\">e.g.</abbr> <code>/dev/sda1</code>)"))
for i, d in ipairs(devices) do
o:value(d, size[d] and "%s (%s MB)" % {d, size[d]})
end
o = mount:taboption("advanced", Value, "uuid", translate("UUID"),
translate("If specified, mount the device by its UUID instead of a fixed device node"))
o = mount:taboption("advanced", Value, "label", translate("Label"),
translate("If specified, mount the device by the partition label instead of a fixed device node"))
o = mount:taboption("general", Value, "target", translate("Mount point"),
translate("Specifies the directory the device is attached to"))
o:depends("is_rootfs", "")
o = mount:taboption("general", Value, "fstype", translate("Filesystem"),
translate("The filesystem that was used to format the memory (<abbr title=\"for example\">e.g.</abbr> <samp><abbr title=\"Third Extended Filesystem\">ext3</abbr></samp>)"))
local fs
for fs in io.lines("/proc/filesystems") do
fs = fs:match("%S+")
if fs ~= "nodev" then
o:value(fs)
end
end
o = mount:taboption("advanced", Value, "options", translate("Mount options"),
translate("See \"mount\" manpage for details"))
o.placeholder = "defaults"
if has_extroot then
o = mount:taboption("general", Flag, "is_rootfs", translate("Use as root filesystem"),
translate("Configures this mount as overlay storage for block-extroot"))
o:depends("fstype", "jffs")
o:depends("fstype", "ext2")
o:depends("fstype", "ext3")
o:depends("fstype", "ext4")
end
if has_fscheck then
o = mount:taboption("general", Flag, "enabled_fsck", translate("Run filesystem check"),
translate("Run a filesystem check before mounting the device"))
end
return m
|
modules/admin-full: fix extroot and fsck availability check (https://dev.openwrt.org/ticket/13837)
|
modules/admin-full: fix extroot and fsck availability check (https://dev.openwrt.org/ticket/13837)
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@9866 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
ReclaimYourPrivacy/cloak-luci,gwlim/luci,ReclaimYourPrivacy/cloak-luci,vhpham80/luci,ReclaimYourPrivacy/cloak-luci,yeewang/openwrt-luci,yeewang/openwrt-luci,phi-psi/luci,gwlim/luci,zwhfly/openwrt-luci,zwhfly/openwrt-luci,phi-psi/luci,ReclaimYourPrivacy/cloak-luci,ch3n2k/luci,ReclaimYourPrivacy/cloak-luci,phi-psi/luci,zwhfly/openwrt-luci,phi-psi/luci,ReclaimYourPrivacy/cloak-luci,vhpham80/luci,zwhfly/openwrt-luci,Canaan-Creative/luci,ThingMesh/openwrt-luci,Canaan-Creative/luci,gwlim/luci,vhpham80/luci,zwhfly/openwrt-luci,8devices/carambola2-luci,ch3n2k/luci,vhpham80/luci,zwhfly/openwrt-luci,eugenesan/openwrt-luci,gwlim/luci,Canaan-Creative/luci,phi-psi/luci,ch3n2k/luci,Canaan-Creative/luci,ch3n2k/luci,8devices/carambola2-luci,ch3n2k/luci,ThingMesh/openwrt-luci,Canaan-Creative/luci,ReclaimYourPrivacy/cloak-luci,zwhfly/openwrt-luci,Canaan-Creative/luci,8devices/carambola2-luci,vhpham80/luci,ThingMesh/openwrt-luci,yeewang/openwrt-luci,eugenesan/openwrt-luci,eugenesan/openwrt-luci,8devices/carambola2-luci,phi-psi/luci,phi-psi/luci,yeewang/openwrt-luci,ThingMesh/openwrt-luci,eugenesan/openwrt-luci,8devices/carambola2-luci,yeewang/openwrt-luci,ch3n2k/luci,ThingMesh/openwrt-luci,Canaan-Creative/luci,gwlim/luci,ThingMesh/openwrt-luci,gwlim/luci,yeewang/openwrt-luci,ThingMesh/openwrt-luci,ReclaimYourPrivacy/cloak-luci,eugenesan/openwrt-luci,eugenesan/openwrt-luci,yeewang/openwrt-luci,zwhfly/openwrt-luci,zwhfly/openwrt-luci,gwlim/luci,8devices/carambola2-luci,vhpham80/luci,Canaan-Creative/luci,8devices/carambola2-luci,eugenesan/openwrt-luci,ch3n2k/luci
|
3795de92647086762d1cdd8db5548f009fb5a8c2
|
extensions/milight/init.lua
|
extensions/milight/init.lua
|
--- === hs.milight ===
---
--- Simple controls for the MiLight LED WiFi bridge (also known as LimitlessLED and EasyBulb)
local milight = require "hs.milight.internal"
milight.cmd = milight._cacheCommands()
local milightObject = hs.getObjectMetatable("hs.milight")
--- hs.milight.minBrightness
--- Constant
--- Specifies the minimum brightness value that can be used. Defaults to 0
milight.minBrightness = 0
--
--- hs.milight.maxBrightness
--- Constant
--- Specifies the maximum brightness value that can be used. Defaults to 25
milight.maxBrightness = 25
-- Internal helper to set brightness
function brightnessHelper(bridge, zonecmd, value)
if (milight.send(bridge, milight.cmd[zonecmd])) then
if (value < milight.minBrightness) then
value = milight.minBrightness
elseif (value > milight.maxBrightness) then
value = milight.maxBrightness
end
value = value + 2 -- bridge accepts values between 2 and 27
result = milight.send(bridge, milight.cmd["brightness"], value)
if (result) then
return value - 2
else
return -1
end
else
return -1
end
end
-- Internal helper to set color
function colorHelper(bridge, zonecmd, value)
if (milight.send(bridge, milight.cmd[zonecmd])) then
if (value < 0) then
value = 0
elseif (value > 255) then
value = 255
end
return milight.send(bridge, milight.cmd["rgbw"], value)
else
return false
end
end
-- Internal helper to map an integer and a string to a zone command key
function zone2cmdkey(zone, cmdType)
local zoneString
if (zone == 0) then
zoneString = "all_"
else
zoneString = "zone"..zone.."_"
end
return zoneString..cmdType
end
--- hs.milight:zoneOff(zone) -> bool
--- Method
--- Turns off the specified zone
---
--- Parameters:
--- * zone - A number specifying which zone to operate on. 0 for all zones, 1-4 for zones one through four
---
--- Returns:
--- * True if the command was sent correctly, otherwise false
function milightObject:zoneOff(zone)
return milight.send(self, milight.cmd[zone2cmdkey(zone, "off")])
end
--- hs.milight:zoneOn(zone) -> bool
--- Method
--- Turns on the specified zone
---
--- Parameters:
--- * zone - A number specifying which zone to operate on. 0 for all zones, 1-4 for zones one through four
---
--- Returns:
--- * True if the command was sent correctly, otherwise false
function milightObject:zoneOn(zone)
return milight.send(self, milight.cmd[zone2cmdkey(zone, "on")])
end
--- hs.milight:disco() -> bool
--- Method
--- Cycles through the disco modes
---
--- Parameters:
--- * None
---
--- Returns:
--- * True if the command was sent correctly, otherwise false
function milightObject:discoCycle(zone)
if (self:zoneOn(zone)) then
return milight.send(self, milight.cmd["disco"])
else
return false
end
end
--- hs.milight:zoneBrightness(zone, value) -> integer
--- Method
--- Sets brightness for the specified zone
---
--- Parameters:
--- * zone - A number specifying which zone to operate on. 0 for all zones, 1-4 for zones one through four
--- * value - A number containing the brightness level to set, between `hs.milight.minBrightness` and `hs.milight.maxBrightness`
---
--- Returns:
--- * A number containing the value that was sent to the WiFi bridge, or -1 if an error occurred
function milightObject:zoneBrightness(zone, value)
return brightnessHelper(self, zone2cmdkey(zone, "on"), value)
end
--- hs.milight:zoneColor(zone, value) -> bool
--- Method
--- Sets RGB color for the specified zone
---
--- Parameters:
--- * zone - A number specifying which zone to operate on. 0 for all zones, 1-4 for zones one through four
--- * value - A number containing an RGB color value between 0 and 255
---
--- Returns:
--- * True if the command was sent correctly, otherwise false
function milightObject:zoneColor(zone, value)
return colorHelper(self, zone2cmdkey(zone, "on"), value)
end
--- hs.milight:zoneWhite(zone) -> bool
--- Method
--- Sets the specified zone to white
---
--- Parameters:
--- * zone - A number specifying which zone to operate on. 0 for all zones, 1-4 for zones one through four
---
--- Returns:
--- * True if the command was sent correctly, otherwise false
function milightObject:zoneWhite(zone)
if (self:zoneOn(zone)) then
return milight.send(self, milight.cmd[zone2cmdkey(zone, "white")])
else
return false
end
end
return milight
|
--- === hs.milight ===
---
--- Simple controls for the MiLight LED WiFi bridge (also known as LimitlessLED and EasyBulb)
local milight = require "hs.milight.internal"
milight.cmd = milight._cacheCommands()
local milightObject = hs.getObjectMetatable("hs.milight")
--- hs.milight.minBrightness
--- Constant
--- Specifies the minimum brightness value that can be used. Defaults to 0
milight.minBrightness = 0
--
--- hs.milight.maxBrightness
--- Constant
--- Specifies the maximum brightness value that can be used. Defaults to 25
milight.maxBrightness = 25
-- Internal helper to set brightness
function brightnessHelper(bridge, zonecmd, value)
if (bridge:send(milight.cmd[zonecmd])) then
if (value < milight.minBrightness) then
value = milight.minBrightness
elseif (value > milight.maxBrightness) then
value = milight.maxBrightness
end
value = value + 2 -- bridge accepts values between 2 and 27
result = bridge:send(milight.cmd["brightness"], value)
if (result) then
return value - 2
else
return -1
end
else
return -1
end
end
-- Internal helper to set color
function colorHelper(bridge, zonecmd, value)
if (bridge:send(milight.cmd[zonecmd])) then
if (value < 0) then
value = 0
elseif (value > 255) then
value = 255
end
return bridge:send(milight.cmd["rgbw"], value)
else
return false
end
end
-- Internal helper to map an integer and a string to a zone command key
function zone2cmdkey(zone, cmdType)
local zoneString
if (zone == 0) then
zoneString = "all_"
else
zoneString = "zone"..zone.."_"
end
return zoneString..cmdType
end
--- hs.milight:zoneOff(zone) -> bool
--- Method
--- Turns off the specified zone
---
--- Parameters:
--- * zone - A number specifying which zone to operate on. 0 for all zones, 1-4 for zones one through four
---
--- Returns:
--- * True if the command was sent correctly, otherwise false
function milightObject:zoneOff(zone)
return self:send(milight.cmd[zone2cmdkey(zone, "off")])
end
--- hs.milight:zoneOn(zone) -> bool
--- Method
--- Turns on the specified zone
---
--- Parameters:
--- * zone - A number specifying which zone to operate on. 0 for all zones, 1-4 for zones one through four
---
--- Returns:
--- * True if the command was sent correctly, otherwise false
function milightObject:zoneOn(zone)
return self:send(milight.cmd[zone2cmdkey(zone, "on")])
end
--- hs.milight:disco() -> bool
--- Method
--- Cycles through the disco modes
---
--- Parameters:
--- * None
---
--- Returns:
--- * True if the command was sent correctly, otherwise false
function milightObject:discoCycle(zone)
if (self:zoneOn(zone)) then
return self:send(milight.cmd["disco"])
else
return false
end
end
--- hs.milight:zoneBrightness(zone, value) -> integer
--- Method
--- Sets brightness for the specified zone
---
--- Parameters:
--- * zone - A number specifying which zone to operate on. 0 for all zones, 1-4 for zones one through four
--- * value - A number containing the brightness level to set, between `hs.milight.minBrightness` and `hs.milight.maxBrightness`
---
--- Returns:
--- * A number containing the value that was sent to the WiFi bridge, or -1 if an error occurred
function milightObject:zoneBrightness(zone, value)
return brightnessHelper(self, zone2cmdkey(zone, "on"), value)
end
--- hs.milight:zoneColor(zone, value) -> bool
--- Method
--- Sets RGB color for the specified zone
---
--- Parameters:
--- * zone - A number specifying which zone to operate on. 0 for all zones, 1-4 for zones one through four
--- * value - A number containing an RGB color value between 0 and 255
---
--- Returns:
--- * True if the command was sent correctly, otherwise false
function milightObject:zoneColor(zone, value)
return colorHelper(self, zone2cmdkey(zone, "on"), value)
end
--- hs.milight:zoneWhite(zone) -> bool
--- Method
--- Sets the specified zone to white
---
--- Parameters:
--- * zone - A number specifying which zone to operate on. 0 for all zones, 1-4 for zones one through four
---
--- Returns:
--- * True if the command was sent correctly, otherwise false
function milightObject:zoneWhite(zone)
if (self:zoneOn(zone)) then
return self:send(milight.cmd[zone2cmdkey(zone, "white")])
else
return false
end
end
return milight
|
Fix hs.milight to work post-LuaSkin transition
|
Fix hs.milight to work post-LuaSkin transition
|
Lua
|
mit
|
Habbie/hammerspoon,kkamdooong/hammerspoon,chrisjbray/hammerspoon,zzamboni/hammerspoon,Habbie/hammerspoon,cmsj/hammerspoon,heptal/hammerspoon,kkamdooong/hammerspoon,wsmith323/hammerspoon,TimVonsee/hammerspoon,latenitefilms/hammerspoon,TimVonsee/hammerspoon,zzamboni/hammerspoon,cmsj/hammerspoon,TimVonsee/hammerspoon,Habbie/hammerspoon,junkblocker/hammerspoon,Hammerspoon/hammerspoon,ocurr/hammerspoon,asmagill/hammerspoon,latenitefilms/hammerspoon,wvierber/hammerspoon,CommandPost/CommandPost-App,lowne/hammerspoon,latenitefilms/hammerspoon,CommandPost/CommandPost-App,Stimim/hammerspoon,latenitefilms/hammerspoon,lowne/hammerspoon,heptal/hammerspoon,kkamdooong/hammerspoon,junkblocker/hammerspoon,joehanchoi/hammerspoon,latenitefilms/hammerspoon,ocurr/hammerspoon,wsmith323/hammerspoon,ocurr/hammerspoon,CommandPost/CommandPost-App,Habbie/hammerspoon,nkgm/hammerspoon,Habbie/hammerspoon,zzamboni/hammerspoon,nkgm/hammerspoon,nkgm/hammerspoon,cmsj/hammerspoon,CommandPost/CommandPost-App,wsmith323/hammerspoon,wvierber/hammerspoon,bradparks/hammerspoon,cmsj/hammerspoon,chrisjbray/hammerspoon,wvierber/hammerspoon,Hammerspoon/hammerspoon,emoses/hammerspoon,asmagill/hammerspoon,lowne/hammerspoon,CommandPost/CommandPost-App,dopcn/hammerspoon,emoses/hammerspoon,dopcn/hammerspoon,bradparks/hammerspoon,joehanchoi/hammerspoon,knl/hammerspoon,bradparks/hammerspoon,dopcn/hammerspoon,junkblocker/hammerspoon,knu/hammerspoon,Hammerspoon/hammerspoon,knl/hammerspoon,chrisjbray/hammerspoon,junkblocker/hammerspoon,TimVonsee/hammerspoon,junkblocker/hammerspoon,wvierber/hammerspoon,cmsj/hammerspoon,knl/hammerspoon,Stimim/hammerspoon,heptal/hammerspoon,emoses/hammerspoon,joehanchoi/hammerspoon,ocurr/hammerspoon,joehanchoi/hammerspoon,heptal/hammerspoon,lowne/hammerspoon,knl/hammerspoon,wsmith323/hammerspoon,zzamboni/hammerspoon,wsmith323/hammerspoon,latenitefilms/hammerspoon,chrisjbray/hammerspoon,bradparks/hammerspoon,cmsj/hammerspoon,nkgm/hammerspoon,lowne/hammerspoon,zzamboni/hammerspoon,knu/hammerspoon,dopcn/hammerspoon,Stimim/hammerspoon,chrisjbray/hammerspoon,joehanchoi/hammerspoon,knl/hammerspoon,nkgm/hammerspoon,emoses/hammerspoon,knu/hammerspoon,asmagill/hammerspoon,Hammerspoon/hammerspoon,asmagill/hammerspoon,zzamboni/hammerspoon,heptal/hammerspoon,Stimim/hammerspoon,asmagill/hammerspoon,knu/hammerspoon,Habbie/hammerspoon,asmagill/hammerspoon,bradparks/hammerspoon,kkamdooong/hammerspoon,TimVonsee/hammerspoon,knu/hammerspoon,kkamdooong/hammerspoon,emoses/hammerspoon,CommandPost/CommandPost-App,ocurr/hammerspoon,chrisjbray/hammerspoon,Hammerspoon/hammerspoon,Stimim/hammerspoon,wvierber/hammerspoon,Hammerspoon/hammerspoon,dopcn/hammerspoon,knu/hammerspoon
|
ccf9fc99ac9abd44630b899276fbb36ac8e216f8
|
photos/node.lua
|
photos/node.lua
|
local COUNTDOWN = 3
gl.setup(NATIVE_WIDTH, NATIVE_HEIGHT)
pictures = util.generator(function()
local out = {}
for name, _ in pairs(CONTENTS) do
if name:match(".*jpg") then
out[#out + 1] = name
end
end
return out
end)
node.event("content_remove", function(filename)
pictures:remove(filename)
end)
local out_effect = math.random() * 3
local in_effect = math.random() * 3
local current_image = resource.load_image(pictures.next())
local next_image
local next_image_time = sys.now() + COUNTDOWN
function node.render()
gl.clear(0,0,0,1)
gl.perspective(60,
WIDTH/2, HEIGHT/2, -WIDTH/1.6,
-- WIDTH/2, HEIGHT/2, -WIDTH/1.4,
WIDTH/2, HEIGHT/2, 0
)
-- gl.perspective(60,
-- WIDTH/2+math.cos(sys.now()) * 100, HEIGHT/2+math.sin(sys.now()) * 100, -WIDTH/1.9,
-- -- WIDTH/2, HEIGHT/2, -WIDTH/1.4,
-- WIDTH/2, HEIGHT/2, 0
-- )
local time_to_next = next_image_time - sys.now()
if time_to_next < 0 then
if next_image then
current_image = next_image
next_image = nil
next_image_time = sys.now() + COUNTDOWN
util.draw_correct(current_image, 0,0,WIDTH,HEIGHT)
in_effect = math.random() * 3
out_effect = math.random() * 3
else
next_image_time = sys.now() + COUNTDOWN
end
util.draw_correct(current_image, 0,0,WIDTH,HEIGHT)
elseif time_to_next < 1 then
if not next_image then
next_image = resource.load_image(pictures.next())
end
local xoff = (1 - time_to_next) * WIDTH
gl.pushMatrix()
if out_effect < 1 then
gl.rotate(200 * (1-time_to_next), 0,1,0)
util.draw_correct(current_image, 0 + xoff, 0, WIDTH + xoff, HEIGHT, time_to_next)
elseif out_effect < 2 then
gl.rotate(60 * (1-time_to_next), 0,0,1)
util.draw_correct(current_image, 0 + xoff, 0, WIDTH + xoff, HEIGHT, time_to_next)
else
gl.rotate(300 * (1-time_to_next), -1,0.2,0.4)
util.draw_correct(current_image, 0 + xoff, 0, WIDTH + xoff, HEIGHT, time_to_next)
end
gl.popMatrix()
gl.pushMatrix()
xoff = time_to_next * -WIDTH
if in_effect < 1 then
gl.rotate(100 * (time_to_next), 1,-1,0)
util.draw_correct(next_image, 0 + xoff, 0,WIDTH + xoff, HEIGHT, 1-time_to_next)
elseif in_effect < 2 then
gl.rotate(100 * (time_to_next), 0,0,-1)
util.draw_correct(next_image, 0 + xoff, 0,WIDTH + xoff, HEIGHT, 1-time_to_next)
else
local half_width = WIDTH/2
local half_height = HEIGHT/2
local percent = 1 - time_to_next
gl.translate(half_width, half_height)
gl.rotate(100 * time_to_next, 0,0,-1)
gl.translate(-half_width, -half_height)
util.draw_correct(next_image,
half_width - half_width*percent, half_height - half_height*percent,
half_width + half_width*percent, half_height + half_height*percent,
1-time_to_next
)
end
gl.popMatrix()
else
util.draw_correct(current_image, 0,0,WIDTH,HEIGHT)
end
end
|
local COUNTDOWN = 3
gl.setup(NATIVE_WIDTH, NATIVE_HEIGHT)
pictures = util.generator(function()
local out = {}
for name, _ in pairs(CONTENTS) do
if name:match(".*jpg") then
out[#out + 1] = name
end
end
return out
end)
node.event("content_remove", function(filename)
pictures:remove(filename)
end)
local out_effect = math.random() * 3
local in_effect = math.random() * 3
local current_image = resource.load_image(pictures.next())
local next_image
local next_image_time = sys.now() + COUNTDOWN
function node.render()
gl.clear(0,0,0,1)
gl.perspective(60,
WIDTH/2, HEIGHT/2, -WIDTH/1.6,
-- WIDTH/2, HEIGHT/2, -WIDTH/1.4,
WIDTH/2, HEIGHT/2, 0
)
-- gl.perspective(60,
-- WIDTH/2+math.cos(sys.now()) * 100, HEIGHT/2+math.sin(sys.now()) * 100, -WIDTH/1.9,
-- -- WIDTH/2, HEIGHT/2, -WIDTH/1.4,
-- WIDTH/2, HEIGHT/2, 0
-- )
local time_to_next = next_image_time - sys.now()
if time_to_next < 0 then
if next_image then
current_image:dispose()
current_image = next_image
next_image = nil
next_image_time = sys.now() + COUNTDOWN
util.draw_correct(current_image, 0,0,WIDTH,HEIGHT)
in_effect = math.random() * 3
out_effect = math.random() * 3
else
next_image_time = sys.now() + COUNTDOWN
end
util.draw_correct(current_image, 0,0,WIDTH,HEIGHT)
elseif time_to_next < 1 then
if not next_image then
next_image = resource.load_image(pictures.next())
end
local xoff = (1 - time_to_next) * WIDTH
gl.pushMatrix()
if out_effect < 1 then
gl.rotate(200 * (1-time_to_next), 0,1,0)
util.draw_correct(current_image, 0 + xoff, 0, WIDTH + xoff, HEIGHT, time_to_next)
elseif out_effect < 2 then
gl.rotate(60 * (1-time_to_next), 0,0,1)
util.draw_correct(current_image, 0 + xoff, 0, WIDTH + xoff, HEIGHT, time_to_next)
else
gl.rotate(300 * (1-time_to_next), -1,0.2,0.4)
util.draw_correct(current_image, 0 + xoff, 0, WIDTH + xoff, HEIGHT, time_to_next)
end
gl.popMatrix()
gl.pushMatrix()
xoff = time_to_next * -WIDTH
if in_effect < 1 then
gl.rotate(100 * (time_to_next), 1,-1,0)
util.draw_correct(next_image, 0 + xoff, 0,WIDTH + xoff, HEIGHT, 1-time_to_next)
elseif in_effect < 2 then
gl.rotate(100 * (time_to_next), 0,0,-1)
util.draw_correct(next_image, 0 + xoff, 0,WIDTH + xoff, HEIGHT, 1-time_to_next)
else
local half_width = WIDTH/2
local half_height = HEIGHT/2
local percent = 1 - time_to_next
gl.translate(half_width, half_height)
gl.rotate(100 * time_to_next, 0,0,-1)
gl.translate(-half_width, -half_height)
util.draw_correct(next_image,
half_width - half_width*percent, half_height - half_height*percent,
half_width + half_width*percent, half_height + half_height*percent,
1-time_to_next
)
end
gl.popMatrix()
else
util.draw_correct(current_image, 0,0,WIDTH,HEIGHT)
end
end
|
fix gc problem
|
fix gc problem
|
Lua
|
bsd-2-clause
|
dividuum/info-beamer-nodes,dividuum/info-beamer-nodes
|
f003c83218b6d3dde6c432b4cb256529a93eaa81
|
check/plugin.lua
|
check/plugin.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.
--]]
--[[
Module for running custom agent plugins written in an arbitrary programing
/ scripting language. This module is backward compatibile with Cloudkick agent
plugins (https://support.cloudkick.com/Creating_a_plugin).
All the plugins must output information to the standard output in the
format defined bellow:
status <status string>
metric <name 1> <type> <value> [<unit>]
metric <name 2> <type> <value> [<unit>]
metric <name 3> <type> <value> [<unit>]
* <status string> - A status string which includes a summary of the results.
* <name> Name of the metric. No spaces are allowed. If a name contains a dot,
string before the dot is considered to be a metric dimension.
* <type> - Metric type which can be one of:
* string
* gauge
* float
* int
* [<unit>] - Metric unit, optional. A string representing the units of the metric
measurement. Units may only be provided on non-string metrics, and may not
contain any spaces. Examples: 'bytes', 'milliseconds', 'percent'.
--]]
local table = require('table')
local childprocess = require('childprocess')
local timer = require('timer')
local path = require('path')
local string = require('string')
local fmt = string.format
local logging = require('logging')
local LineEmitter = require('line-emitter').LineEmitter
local ChildCheck = require('./base').ChildCheck
local CheckResult = require('./base').CheckResult
local Metric = require('./base').Metric
local split = require('/base/util/misc').split
local tableContains = require('/base/util/misc').tableContains
local lastIndexOf = require('/base/util/misc').lastIndexOf
local constants = require('/constants')
local loggingUtil = require('/base/util/logging')
local toString = require('/base/util/misc').toString
local PluginCheck = ChildCheck:extend()
--[[
Constructor.
params.details - Table with the following keys:
- file (string) - Name of the plugin file.
- args (table) - Command-line arguments which get passed to the plugin.
- timeout (number) - Plugin execution timeout in milliseconds.
--]]
function PluginCheck:initialize(params)
ChildCheck.initialize(self, params)
if params.details.file == nil then
params.details.file = ''
end
local file = path.basename(params.details.file)
local args = params.details.args and params.details.args or {}
local timeout = params.details.timeout and params.details.timeout or constants:get('DEFAULT_PLUGIN_TIMEOUT')
self._full_path = params.details.file or ''
self._file = file
self._pluginPath = path.join(constants:get('DEFAULT_CUSTOM_PLUGINS_PATH'), file)
self._pluginArgs = args
self._timeout = timeout
self._log = loggingUtil.makeLogger(fmt('(plugin=%s, id=%s, iid=%s)', file, self.id, self._iid))
end
function PluginCheck:getType()
return 'agent.plugin'
end
function PluginCheck:run(callback)
local exePath = self._pluginPath
local exeArgs = self._pluginArgs
local ext = path.extname(exePath)
local closeStdin = false
if virgo.win32_get_associated_exe ~= nil and ext ~= "" then
-- If we are on windows, we want to suport custom plugins like "foo.py",
-- but this means we need to map the .py file ending to the Python Executable,
-- and mutate our run path to be like: C:/Python27/python.exe custom_plugins_path/foo.py
local assocExe, err = virgo.win32_get_associated_exe(ext, '0') -- Try the 0 verb first for Powershell
if assocExe == nil then
assocExe, err = virgo.win32_get_associated_exe(ext, 'open')
end
if assocExe ~= nil then
-- If Powershell is the EXE then add a parameter for the exec policy
local justExe = path.basename(assocExe)
-- On windows if the associated exe is %1 it references itself
if assocExe ~= "%1" then
table.insert(exeArgs, 1, self._pluginPath)
exePath = assocExe
-- Force Bypass for this child powershell
if justExe == "powershell.exe" then
table.insert(exeArgs, 1, 'Bypass')
table.insert(exeArgs, 1, '-ExecutionPolicy')
closeStdin = true -- NEEDED for Powershell 2.0 to exit
end
end
else
self._log(logging.WARNING, fmt('error getting associated executable for "%s": %s', ext, err))
end
end
local cenv = self:_childEnv()
-- Ruby 1.9.1p0 crashes when stdin is closed, so we let luvit take care of
-- closing the pipe after the process runs.
local child = self:_runChild(exePath, exeArgs, cenv, callback)
if closeStdin then
child.stdin:close()
end
end
local exports = {}
exports.PluginCheck = PluginCheck
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.
--]]
--[[
Module for running custom agent plugins written in an arbitrary programing
/ scripting language. This module is backward compatibile with Cloudkick agent
plugins (https://support.cloudkick.com/Creating_a_plugin).
All the plugins must output information to the standard output in the
format defined bellow:
status <status string>
metric <name 1> <type> <value> [<unit>]
metric <name 2> <type> <value> [<unit>]
metric <name 3> <type> <value> [<unit>]
* <status string> - A status string which includes a summary of the results.
* <name> Name of the metric. No spaces are allowed. If a name contains a dot,
string before the dot is considered to be a metric dimension.
* <type> - Metric type which can be one of:
* string
* gauge
* float
* int
* [<unit>] - Metric unit, optional. A string representing the units of the metric
measurement. Units may only be provided on non-string metrics, and may not
contain any spaces. Examples: 'bytes', 'milliseconds', 'percent'.
--]]
local table = require('table')
local childprocess = require('childprocess')
local timer = require('timer')
local path = require('path')
local string = require('string')
local fmt = string.format
local logging = require('logging')
local LineEmitter = require('line-emitter').LineEmitter
local ChildCheck = require('./base').ChildCheck
local CheckResult = require('./base').CheckResult
local Metric = require('./base').Metric
local split = require('/base/util/misc').split
local tableContains = require('/base/util/misc').tableContains
local lastIndexOf = require('/base/util/misc').lastIndexOf
local constants = require('/constants')
local loggingUtil = require('/base/util/logging')
local toString = require('/base/util/misc').toString
local PluginCheck = ChildCheck:extend()
--[[
Constructor.
params.details - Table with the following keys:
- file (string) - Name of the plugin file.
- args (table) - Command-line arguments which get passed to the plugin.
- timeout (number) - Plugin execution timeout in milliseconds.
--]]
function PluginCheck:initialize(params)
ChildCheck.initialize(self, params)
if params.details.file == nil then
params.details.file = ''
end
local file = path.basename(params.details.file)
local args = params.details.args and params.details.args or {}
local timeout = params.details.timeout and params.details.timeout or constants:get('DEFAULT_PLUGIN_TIMEOUT')
self._full_path = params.details.file or ''
self._file = file
self._pluginPath = path.join(constants:get('DEFAULT_CUSTOM_PLUGINS_PATH'), file)
self._pluginArgs = args
self._timeout = timeout
self._log = loggingUtil.makeLogger(fmt('(plugin=%s, id=%s, iid=%s)', file, self.id, self._iid))
end
function PluginCheck:getType()
return 'agent.plugin'
end
function PluginCheck:run(callback)
local exePath = self._pluginPath
local exeArgs = self._pluginArgs
local ext = path.extname(exePath)
local closeStdin = false
if virgo.win32_get_associated_exe ~= nil and ext ~= "" then
-- If we are on windows, we want to suport custom plugins like "foo.py",
-- but this means we need to map the .py file ending to the Python Executable,
-- and mutate our run path to be like: C:/Python27/python.exe custom_plugins_path/foo.py
local assocExe, err = virgo.win32_get_associated_exe(ext, '0') -- Try the 0 verb first for Powershell
if assocExe == nil then
assocExe, err = virgo.win32_get_associated_exe(ext, 'open')
end
if assocExe ~= nil then
-- If Powershell is the EXE then add a parameter for the exec policy
local justExe = path.basename(assocExe)
-- On windows if the associated exe is %1 it references itself
if assocExe ~= "%1" then
table.insert(exeArgs, 1, self._pluginPath)
exePath = assocExe
-- Force Bypass for this child powershell
if justExe == "powershell.exe" then
table.insert(exeArgs, 1, '-File')
table.insert(exeArgs, 1, 'Bypass')
table.insert(exeArgs, 1, '-ExecutionPolicy')
closeStdin = true -- NEEDED for Powershell 2.0 to exit
end
end
else
self._log(logging.WARNING, fmt('error getting associated executable for "%s": %s', ext, err))
end
end
local cenv = self:_childEnv()
-- Ruby 1.9.1p0 crashes when stdin is closed, so we let luvit take care of
-- closing the pipe after the process runs.
local child = self:_runChild(exePath, exeArgs, cenv, callback)
if closeStdin then
child.stdin:close()
end
end
local exports = {}
exports.PluginCheck = PluginCheck
return exports
|
Fix a plugin error on windows 2012 using spaces in the plugin path
|
Fix a plugin error on windows 2012 using spaces in the plugin path
|
Lua
|
apache-2.0
|
AlphaStaxLLC/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent
|
d00e228f77189ed3253e2ad75a686c9dae1f3915
|
src/moonhowl/img_store.lua
|
src/moonhowl/img_store.lua
|
local lgi = require "lgi"
local GdkPixbuf = lgi.GdkPixbuf
local img_store = {}
local cache = {}
local requests = {}
function img_store.get_cached(url)
return cache[url]
end
function img_store.join_request(url, obj)
local req = requests[url]
req[#req + 1] = obj
end
local function pixbuf_from_image_data(data)
local loader = GdkPixbuf.PixbufLoader()
loader:write(data)
loader:close()
return loader:get_pixbuf()
end
local function dispatch(url, data)
if data then
data = pixbuf_from_image_data(data)
cache[url] = data
else
data = "image-missing"
cache[url] = nil
end
for _, obj in ipairs(requests[url]) do
obj:set_image(data)
end
end
function img_store.new_request(url, obj)
cache[url] = false
requests[url] = { obj }
return {
url = url,
_callback = function(data, code)
if code == 200 then
dispatch(url, data)
else
dispatch(url)
end
requests[url] = nil
end,
}
end
return img_store
|
local lgi = require "lgi"
local GdkPixbuf = lgi.GdkPixbuf
local img_store = {}
local cache = {}
local requests = {}
function img_store.get_cached(url)
return cache[url]
end
function img_store.join_request(url, obj)
local req = requests[url]
req[#req + 1] = obj
end
local function pixbuf_from_image_data(data)
local loader = GdkPixbuf.PixbufLoader()
loader:write(data)
loader:close()
return loader:get_pixbuf()
end
local function dispatch(url, data)
if data then
data = pixbuf_from_image_data(data)
cache[url] = data
else
data = "image-missing"
cache[url] = nil
end
for _, obj in ipairs(requests[url]) do
obj:set_image(data)
end
requests[url] = nil
end
function img_store.new_request(url, obj)
cache[url] = false
requests[url] = { obj }
local cb = function(data, code)
return dispatch(url, code == 200 and data)
end
return {
url = url,
_callback = {
ok = cb,
error = cb,
},
}
end
return img_store
|
fix callback handler for img_store
|
fix callback handler for img_store
|
Lua
|
mpl-2.0
|
darkstalker/moonhowl
|
7c0d516da1cc5527182281a3688945e35ae7ce82
|
share/media/break.lua
|
share/media/break.lua
|
-- libquvi-scripts
-- Copyright (C) 2010-2012 Toni Gundogdu <legatvs@gmail.com>
--
-- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>.
--
-- This program is free software: you can redistribute it and/or
-- modify it under the terms of the GNU Affero General Public
-- License as published by the Free Software Foundation, either
-- version 3 of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU Affero General Public License for more details.
--
-- You should have received a copy of the GNU Affero General
-- Public License along with this program. If not, see
-- <http://www.gnu.org/licenses/>.
--
local Break = {} -- Utility functions unique to this script
-- Identify the media script.
function ident(qargs)
return {
can_parse_url = Break.can_parse_url(qargs),
domains = table.concat({'break.com'}, ',')
}
end
-- Parse media properties.
function parse(qargs)
local p = quvi.fetch(qargs.input_url)
qargs.thumb_url = p:match('"og:image" content="(.-)"') or ''
qargs.title = p:match('id="vid_title" content="(.-)"') or ''
qargs.id = p:match("ContentID='(.-)'") or ''
local n = p:match("FileName='(.-)'") or error("no match: file name")
local h = p:match('flashVars.icon = "(.-)"') or error("no match: file hash")
qargs.streams = Break.iter_streams(n, h)
return qargs
end
--
-- Utility functions.
--
function Break.can_parse_url(qargs)
local U = require 'socket.url'
local t = U.parse(qargs.input_url)
if t and t.scheme and t.scheme:lower():match('^http$')
and t.host and t.host:lower():match('break%.com$')
and t.path and t.path:lower():match('^/index/')
then
return true
else
return false
end
end
function Break.iter_streams(n, h)
local u = string.format("%s.flv?%s", n, h)
local S = require 'quvi/stream'
return {S.stream_new(u)}
end
-- vim: set ts=2 sw=2 tw=72 expandtab:
|
-- libquvi-scripts
-- Copyright (C) 2010-2012 Toni Gundogdu <legatvs@gmail.com>
--
-- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>.
--
-- This program is free software: you can redistribute it and/or
-- modify it under the terms of the GNU Affero General Public
-- License as published by the Free Software Foundation, either
-- version 3 of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU Affero General Public License for more details.
--
-- You should have received a copy of the GNU Affero General
-- Public License along with this program. If not, see
-- <http://www.gnu.org/licenses/>.
--
local Break = {} -- Utility functions unique to this script
-- Identify the media script.
function ident(qargs)
return {
can_parse_url = Break.can_parse_url(qargs),
domains = table.concat({'break.com'}, ',')
}
end
-- Parse media properties.
function parse(qargs)
local p = quvi.fetch(qargs.input_url)
qargs.thumb_url = p:match('"og:image" content="(.-)"') or ''
qargs.title = p:match("sVidTitle:%s+['\"](.-)['\"]") or ''
qargs.id = p:match("iContentID:%s+'(.-)'") or ''
local n = p:match("videoPath:%s+['\"](.-)['\"]")
or error("no match: file path")
local h = p:match("icon:%s+['\"](.-)['\"]")
or error("no match: file hash")
qargs.streams = Break.iter_streams(n, h)
return qargs
end
--
-- Utility functions.
--
function Break.can_parse_url(qargs)
local U = require 'socket.url'
local t = U.parse(qargs.input_url)
if t and t.scheme and t.scheme:lower():match('^http$')
and t.host and t.host:lower():match('break%.com$')
and t.path and t.path:lower():match('^/index/')
then
return true
else
return false
end
end
function Break.iter_streams(n, h)
local u = string.format("%s.flv?%s", n, h)
local S = require 'quvi/stream'
return {S.stream_new(u)}
end
-- vim: set ts=2 sw=2 tw=72 expandtab:
|
FIX: media/break.lua
|
FIX: media/break.lua
Fix patterns {title,id,filepath,filehash}.
Signed-off-by: Toni Gundogdu <eac2284b3c43676907b96f08de9d3d52d5df0361@gmail.com>
|
Lua
|
agpl-3.0
|
legatvs/libquvi-scripts,alech/libquvi-scripts,legatvs/libquvi-scripts,alech/libquvi-scripts
|
3f2d8f432d160b20670b5c817b8a5d5648220f51
|
lualib/http/internal.lua
|
lualib/http/internal.lua
|
local table = table
local type = type
local sockethelper = require "http.sockethelper"
local M = {}
local LIMIT = 8192
local function chunksize(readbytes, body)
while true do
local f,e = body:find("\r\n",1,true)
if f then
return tonumber(body:sub(1,f-1),16), body:sub(e+1)
end
if #body > 128 then
-- pervent the attacker send very long stream without \r\n
return
end
body = body .. readbytes()
end
end
local function readcrln(readbytes, body)
if #body >= 2 then
if body:sub(1,2) ~= "\r\n" then
return
end
return body:sub(3)
else
body = body .. readbytes(2-#body)
if body ~= "\r\n" then
return
end
return ""
end
end
function M.recvheader(readbytes, lines, header)
if #header >= 2 then
if header:find "^\r\n" then
return header:sub(3)
end
end
local result
local e = header:find("\r\n\r\n", 1, true)
if e then
result = header:sub(e+4)
else
while true do
local bytes = readbytes()
header = header .. bytes
e = header:find("\r\n\r\n", -#bytes-3, true)
if e then
result = header:sub(e+4)
break
end
if header:find "^\r\n" then
return header:sub(3)
end
if #header > LIMIT then
return
end
end
end
for v in header:gmatch("(.-)\r\n") do
if v == "" then
break
end
table.insert(lines, v)
end
return result
end
function M.parseheader(lines, from, header)
local name, value
for i=from,#lines do
local line = lines[i]
if line:byte(1) == 9 then -- tab, append last line
if name == nil then
return
end
header[name] = header[name] .. line:sub(2)
else
name, value = line:match "^(.-):%s*(.*)"
if name == nil or value == nil then
return
end
name = name:lower()
if header[name] then
local v = header[name]
if type(v) == "table" then
table.insert(v, value)
else
header[name] = { v , value }
end
else
header[name] = value
end
end
end
return header
end
function M.recvchunkedbody(readbytes, bodylimit, header, body)
local result = ""
local size = 0
while true do
local sz
sz , body = chunksize(readbytes, body)
if not sz then
return
end
if sz == 0 then
break
end
size = size + sz
if bodylimit and size > bodylimit then
return
end
if #body >= sz then
result = result .. body:sub(1,sz)
body = body:sub(sz+1)
else
result = result .. body .. readbytes(sz - #body)
body = ""
end
body = readcrln(readbytes, body)
if not body then
return
end
end
local tmpline = {}
body = M.recvheader(readbytes, tmpline, body)
if not body then
return
end
header = M.parseheader(tmpline,1,header)
return result, header
end
function M.request(interface, method, host, url, recvheader, header, content)
local is_ws = interface.websocket
local read = interface.read
local write = interface.write
local header_content = ""
if header then
if not header.host then
header.host = host
end
for k,v in pairs(header) do
header_content = string.format("%s%s:%s\r\n", header_content, k, v)
end
else
header_content = string.format("host:%s\r\n",host)
end
if content then
local data = string.format("%s %s HTTP/1.1\r\n%sContent-length:%d\r\n\r\n", method, url, header_content, #content)
write(data)
write(content)
else
local request_header = string.format("%s %s HTTP/1.1\r\n%sContent-length:0\r\n\r\n", method, url, header_content)
write(request_header)
end
local tmpline = {}
local body = M.recvheader(read, tmpline, "")
if not body then
error(sockethelper.socket_error)
end
local statusline = tmpline[1]
local code, info = statusline:match "HTTP/[%d%.]+%s+([%d]+)%s+(.*)$"
code = assert(tonumber(code))
local header = M.parseheader(tmpline,2,recvheader or {})
if not header then
error("Invalid HTTP response header")
end
local length = header["content-length"]
if length then
length = tonumber(length)
end
local mode = header["transfer-encoding"]
if mode then
if mode ~= "identity" and mode ~= "chunked" then
error ("Unsupport transfer-encoding")
end
end
if mode == "chunked" then
body, header = M.recvchunkedbody(read, nil, header, body)
if not body then
error("Invalid response body")
end
else
-- identity mode
if length then
if #body >= length then
body = body:sub(1,length)
else
local padding = read(length - #body)
body = body .. padding
end
elseif code == 204 or code == 304 or code < 200 then
body = ""
-- See https://stackoverflow.com/questions/15991173/is-the-content-length-header-required-for-a-http-1-0-response
elseif is_ws and code == 101 then
-- if websocket handshake success
return code, body
else
-- no content-length, read all
body = body .. interface.readall()
end
end
return code, body
end
return M
|
local table = table
local type = type
local M = {}
local LIMIT = 8192
local function chunksize(readbytes, body)
while true do
local f,e = body:find("\r\n",1,true)
if f then
return tonumber(body:sub(1,f-1),16), body:sub(e+1)
end
if #body > 128 then
-- pervent the attacker send very long stream without \r\n
return
end
body = body .. readbytes()
end
end
local function readcrln(readbytes, body)
if #body >= 2 then
if body:sub(1,2) ~= "\r\n" then
return
end
return body:sub(3)
else
body = body .. readbytes(2-#body)
if body ~= "\r\n" then
return
end
return ""
end
end
function M.recvheader(readbytes, lines, header)
if #header >= 2 then
if header:find "^\r\n" then
return header:sub(3)
end
end
local result
local e = header:find("\r\n\r\n", 1, true)
if e then
result = header:sub(e+4)
else
while true do
local bytes = readbytes()
header = header .. bytes
e = header:find("\r\n\r\n", -#bytes-3, true)
if e then
result = header:sub(e+4)
break
end
if header:find "^\r\n" then
return header:sub(3)
end
if #header > LIMIT then
return
end
end
end
for v in header:gmatch("(.-)\r\n") do
if v == "" then
break
end
table.insert(lines, v)
end
return result
end
function M.parseheader(lines, from, header)
local name, value
for i=from,#lines do
local line = lines[i]
if line:byte(1) == 9 then -- tab, append last line
if name == nil then
return
end
header[name] = header[name] .. line:sub(2)
else
name, value = line:match "^(.-):%s*(.*)"
if name == nil or value == nil then
return
end
name = name:lower()
if header[name] then
local v = header[name]
if type(v) == "table" then
table.insert(v, value)
else
header[name] = { v , value }
end
else
header[name] = value
end
end
end
return header
end
function M.recvchunkedbody(readbytes, bodylimit, header, body)
local result = ""
local size = 0
while true do
local sz
sz , body = chunksize(readbytes, body)
if not sz then
return
end
if sz == 0 then
break
end
size = size + sz
if bodylimit and size > bodylimit then
return
end
if #body >= sz then
result = result .. body:sub(1,sz)
body = body:sub(sz+1)
else
result = result .. body .. readbytes(sz - #body)
body = ""
end
body = readcrln(readbytes, body)
if not body then
return
end
end
local tmpline = {}
body = M.recvheader(readbytes, tmpline, body)
if not body then
return
end
header = M.parseheader(tmpline,1,header)
return result, header
end
function M.request(interface, method, host, url, recvheader, header, content)
local is_ws = interface.websocket
local read = interface.read
local write = interface.write
local header_content = ""
if header then
if not header.host then
header.host = host
end
for k,v in pairs(header) do
header_content = string.format("%s%s:%s\r\n", header_content, k, v)
end
else
header_content = string.format("host:%s\r\n",host)
end
if content then
local data = string.format("%s %s HTTP/1.1\r\n%sContent-length:%d\r\n\r\n", method, url, header_content, #content)
write(data)
write(content)
else
local request_header = string.format("%s %s HTTP/1.1\r\n%sContent-length:0\r\n\r\n", method, url, header_content)
write(request_header)
end
local tmpline = {}
local body = M.recvheader(read, tmpline, "")
if not body then
error("Recv header failed")
end
local statusline = tmpline[1]
local code, info = statusline:match "HTTP/[%d%.]+%s+([%d]+)%s+(.*)$"
code = assert(tonumber(code))
local header = M.parseheader(tmpline,2,recvheader or {})
if not header then
error("Invalid HTTP response header")
end
local length = header["content-length"]
if length then
length = tonumber(length)
end
local mode = header["transfer-encoding"]
if mode then
if mode ~= "identity" and mode ~= "chunked" then
error ("Unsupport transfer-encoding")
end
end
if mode == "chunked" then
body, header = M.recvchunkedbody(read, nil, header, body)
if not body then
error("Invalid response body")
end
else
-- identity mode
if length then
if #body >= length then
body = body:sub(1,length)
else
local padding = read(length - #body)
body = body .. padding
end
elseif code == 204 or code == 304 or code < 200 then
body = ""
-- See https://stackoverflow.com/questions/15991173/is-the-content-length-header-required-for-a-http-1-0-response
elseif is_ws and code == 101 then
-- if websocket handshake success
return code, body
else
-- no content-length, read all
body = body .. interface.readall()
end
end
return code, body
end
return M
|
Fix #1452
|
Fix #1452
|
Lua
|
mit
|
icetoggle/skynet,icetoggle/skynet,icetoggle/skynet
|
5513841940e29f4eb6050e461b88451d97487d38
|
NaoTHSoccer/Make/premake4.lua
|
NaoTHSoccer/Make/premake4.lua
|
-- set the default global platform
PLATFORM = _OPTIONS["platform"]
if PLATFORM == nil then
PLATFORM = "Native"
end
-- load the global default settings
dofile "projectconfig.lua"
-- load some helpers
dofile (FRAMEWORK_PATH .. "/BuildTools/info.lua")
dofile (FRAMEWORK_PATH .. "/BuildTools/protoc.lua")
--dofile (FRAMEWORK_PATH .. "/BuildTools/ilpath.lua")
dofile (FRAMEWORK_PATH .. "/BuildTools/qtcreator.lua")
dofile (FRAMEWORK_PATH .. "/BuildTools/qtcreator_2.7+.lua")
--dofile (FRAMEWORK_PATH .. "/BuildTools/extract_todos.lua")
-- include the Nao platform
if COMPILER_PATH_NAO ~= nil then
include (COMPILER_PATH_NAO)
end
-- test
-- print("INFO:" .. (os.findlib("Controller") or "couldn't fined the lib Controller"))
newoption {
trigger = "Wno-conversion",
description = "Disable te -Wconversion warnin for gCC"
}
newoption {
trigger = "Wno-misleading-indentation",
description = "Disable the -Wmisleading-indentation warning/error for gcc (6.0+)"
}
newoption {
trigger = "Wno-ignored-attributes",
description = "Disable the -Wignored-attributes warning/error for gcc (6.0+)"
}
-- definition of the solution
solution "NaoTHSoccer"
platforms {"Native", "Nao"}
configurations {"OptDebug", "Debug", "Release"}
location "../build"
print("generating solution NaoTHSoccer for platform " .. PLATFORM)
-- global lib path for all configurations
-- additional includes
libdirs (PATH["libs"])
-- global include path for all projects and configurations
includedirs (PATH["includes"])
-- global links ( needed by NaoTHSoccer )
links {
"opencv_core",
"opencv_ml",
"opencv_imgproc",
"opencv_objdetect"
}
-- set the repository information
defines {
"REVISION=\"" .. REVISION .. "\"",
"USER_NAME=\"" .. USER_NAME .. "\"",
"BRANCH_PATH=\"" .. BRANCH_PATH .. "\""
}
-- TODO: howto compile the framework representations properly *inside* the project?
local COMMONS_MESSAGES = FRAMEWORK_PATH .. "/Commons/Messages/"
invokeprotoc(
{ COMMONS_MESSAGES .. "CommonTypes.proto",
COMMONS_MESSAGES .. "Framework-Representations.proto",
COMMONS_MESSAGES .. "Messages.proto"
},
FRAMEWORK_PATH .. "/Commons/Source/Messages/",
"../../RobotControl/RobotConnector/src/",
"../../Utils/pyLogEvaluator",
{COMMONS_MESSAGES}
)
invokeprotoc(
{"../Messages/Representations.proto"},
"../Source/Messages/",
"../../RobotControl/RobotConnector/src/",
"../../Utils/pyLogEvaluator",
{COMMONS_MESSAGES, "../Messages/"}
)
print ("operation system: " .. os.get())
configuration { "Debug" }
defines { "DEBUG" }
flags { "Symbols", "FatalWarnings" }
configuration { "OptDebug" }
defines { "DEBUG" }
flags { "Optimize", "FatalWarnings" }
configuration{"Native"}
targetdir "../dist/Native"
-- special defines for the Nao robot
configuration {"Nao"}
defines { "NAO" }
targetdir "../dist/Nao"
flags { "ExtraWarnings" }
-- disable warning "comparison always true due to limited range of data type"
-- this warning is caused by protobuf 2.4.1
buildoptions {"-Wno-type-limits"}
-- some of the protobuf messages are marked as deprecated but are still in use for legacy reasons
buildoptions {"-Wno-deprecated-declarations"}
buildoptions {"-std=c++11"}
if _OPTIONS["Wno-conversion"] == nil then
-- enable the conversion warning by default
buildoptions {"-Wconversion"}
defines { "_NAOTH_CHECK_CONVERSION_" }
end
-- additional defines for visual studio
configuration {"windows", "vs*"}
defines {"WIN32", "NOMINMAX", "EIGEN_DONT_ALIGN"}
buildoptions {"/wd4351"} -- disable warning: "...new behavior: elements of array..."
buildoptions {"/wd4996"} -- disable warning: "...deprecated..."
buildoptions {"/wd4290"} -- exception specification ignored (typed stecifications are ignored)
links {"ws2_32"}
debugdir "$(SolutionDir).."
configuration {"linux", "gmake"}
-- "position-independent code" needed to compile shared libraries.
-- In our case it's only the NaoSMAL. So, we probably don't need this one.
-- Premake4 automatically includes -fPIC if a project is declared as a SharedLib.
-- http://www.akkadia.org/drepper/dsohowto.pdf
buildoptions {"-fPIC"}
-- may be needed for newer glib2 versions, remove if not needed
buildoptions {"-Wno-deprecated-declarations"}
buildoptions {"-Wno-deprecated"}
buildoptions {"-std=c++11"}
--flags { "ExtraWarnings" }
links {"pthread"}
if _OPTIONS["Wno-conversion"] == nil then
buildoptions {"-Wconversion"}
defines { "_NAOTH_CHECK_CONVERSION_" }
end
if _OPTIONS["Wno-misleading-indentation"] ~= nil then
buildoptions {"-Wno-misleading-indentation"}
end
if _OPTIONS["Wno-ignored-attributes"] ~= nil then
buildoptions {"-Wno-ignored-attributes"}
end
-- Why? OpenCV is always dynamically linked and we can only garantuee that there is one version in Extern (Thomas)
linkoptions {"-Wl,-rpath \"" .. path.getabsolute(EXTERN_PATH .. "/lib/") .. "\""}
configuration {"macosx", "gmake"}
defines { "BOOST_SIGNALS_NO_DEPRECATION_WARNING" }
buildoptions {"-std=c++11"}
-- disable some warnings
buildoptions {"-Wno-deprecated-declarations"}
buildoptions {"-Wno-deprecated-register"}
buildoptions {"-Wno-logical-op-parentheses"}
buildoptions {"CXX=clang++"}
-- commons
dofile (FRAMEWORK_PATH .. "/Commons/Make/Commons.lua")
-- core
dofile "NaoTHSoccer.lua"
-- set up platforms
if _OPTIONS["platform"] == "Nao" then
dofile (FRAMEWORK_PATH .. "/Platforms/Make/NaoSMAL.lua")
-- HACK: boost from NaoQI SDK makes problems
buildoptions {"-Wno-conversion"}
defines { "BOOST_SIGNALS_NO_DEPRECATION_WARNING" }
-- ACHTUNG: NaoSMAL doesn't build with the flag -std=c++11 (because of Boost)
buildoptions {"-std=gnu++11"}
dofile (FRAMEWORK_PATH .. "/Platforms/Make/NaoRobot.lua")
kind "ConsoleApp"
links { "NaoTHSoccer", "Commons" }
else
dofile (FRAMEWORK_PATH .. "/Platforms/Make/SimSpark.lua")
kind "ConsoleApp"
links { "NaoTHSoccer", "Commons" }
debugargs { "--sync" }
dofile (FRAMEWORK_PATH .. "/Platforms/Make/LogSimulator.lua")
kind "ConsoleApp"
links { "NaoTHSoccer", "Commons" }
dofile (FRAMEWORK_PATH .. "/Platforms/Make/LogSimulatorJNI.lua")
kind "SharedLib"
links { "NaoTHSoccer", "Commons" }
end
|
-- set the default global platform
PLATFORM = _OPTIONS["platform"]
if PLATFORM == nil then
PLATFORM = "Native"
end
-- load the global default settings
dofile "projectconfig.lua"
-- load some helpers
dofile (FRAMEWORK_PATH .. "/BuildTools/info.lua")
dofile (FRAMEWORK_PATH .. "/BuildTools/protoc.lua")
--dofile (FRAMEWORK_PATH .. "/BuildTools/ilpath.lua")
dofile (FRAMEWORK_PATH .. "/BuildTools/qtcreator.lua")
dofile (FRAMEWORK_PATH .. "/BuildTools/qtcreator_2.7+.lua")
--dofile (FRAMEWORK_PATH .. "/BuildTools/extract_todos.lua")
-- include the Nao platform
if COMPILER_PATH_NAO ~= nil then
include (COMPILER_PATH_NAO)
end
-- test
-- print("INFO:" .. (os.findlib("Controller") or "couldn't fined the lib Controller"))
newoption {
trigger = "Wno-conversion",
description = "Disable te -Wconversion warnin for gCC"
}
newoption {
trigger = "Wno-misleading-indentation",
description = "Disable the -Wmisleading-indentation warning/error for gcc (6.0+)"
}
newoption {
trigger = "Wno-ignored-attributes",
description = "Disable the -Wignored-attributes warning/error for gcc (6.0+)"
}
-- definition of the solution
solution "NaoTHSoccer"
platforms {"Native", "Nao"}
configurations {"OptDebug", "Debug", "Release"}
location "../build"
print("generating solution NaoTHSoccer for platform " .. PLATFORM)
-- global lib path for all configurations
-- additional includes
libdirs (PATH["libs"])
-- global include path for all projects and configurations
includedirs (PATH["includes"])
-- global links ( needed by NaoTHSoccer )
links {
"opencv_core",
"opencv_ml",
"opencv_imgproc",
"opencv_objdetect"
}
-- set the repository information
defines {
"REVISION=\"" .. REVISION .. "\"",
"USER_NAME=\"" .. USER_NAME .. "\"",
"BRANCH_PATH=\"" .. BRANCH_PATH .. "\""
}
-- TODO: howto compile the framework representations properly *inside* the project?
local COMMONS_MESSAGES = FRAMEWORK_PATH .. "/Commons/Messages/"
invokeprotoc(
{ COMMONS_MESSAGES .. "CommonTypes.proto",
COMMONS_MESSAGES .. "Framework-Representations.proto",
COMMONS_MESSAGES .. "Messages.proto"
},
FRAMEWORK_PATH .. "/Commons/Source/Messages/",
"../../RobotControl/RobotConnector/src/",
"../../Utils/pyLogEvaluator",
{COMMONS_MESSAGES}
)
invokeprotoc(
{"../Messages/Representations.proto"},
"../Source/Messages/",
"../../RobotControl/RobotConnector/src/",
"../../Utils/pyLogEvaluator",
{COMMONS_MESSAGES, "../Messages/"}
)
print ("operation system: " .. os.get())
configuration { "Debug" }
defines { "DEBUG" }
flags { "Symbols", "FatalWarnings" }
configuration { "OptDebug" }
defines { "DEBUG" }
flags { "Optimize", "FatalWarnings" }
configuration{"Native"}
targetdir "../dist/Native"
-- special defines for the Nao robot
configuration {"Nao"}
defines { "NAO" }
targetdir "../dist/Nao"
flags { "ExtraWarnings" }
-- disable warning "comparison always true due to limited range of data type"
-- this warning is caused by protobuf 2.4.1
buildoptions {"-Wno-type-limits"}
-- some of the protobuf messages are marked as deprecated but are still in use for legacy reasons
buildoptions {"-Wno-deprecated-declarations"}
buildoptions {"-std=c++11"}
if _OPTIONS["Wno-conversion"] == nil then
-- enable the conversion warning by default
buildoptions {"-Wconversion"}
defines { "_NAOTH_CHECK_CONVERSION_" }
end
-- additional defines for visual studio
configuration {"windows", "vs*"}
defines {"WIN32", "NOMINMAX", "EIGEN_DONT_ALIGN"}
buildoptions {"/wd4351"} -- disable warning: "...new behavior: elements of array..."
buildoptions {"/wd4996"} -- disable warning: "...deprecated..."
buildoptions {"/wd4290"} -- exception specification ignored (typed stecifications are ignored)
links {"ws2_32"}
debugdir "$(SolutionDir).."
configuration {"linux", "gmake"}
-- "position-independent code" needed to compile shared libraries.
-- In our case it's only the NaoSMAL. So, we probably don't need this one.
-- Premake4 automatically includes -fPIC if a project is declared as a SharedLib.
-- http://www.akkadia.org/drepper/dsohowto.pdf
buildoptions {"-fPIC"}
-- may be needed for newer glib2 versions, remove if not needed
buildoptions {"-Wno-deprecated-declarations"}
buildoptions {"-Wno-deprecated"}
buildoptions {"-std=c++11"}
--flags { "ExtraWarnings" }
links {"pthread"}
if _OPTIONS["Wno-conversion"] == nil then
buildoptions {"-Wconversion"}
defines { "_NAOTH_CHECK_CONVERSION_" }
end
if _OPTIONS["Wno-misleading-indentation"] ~= nil then
buildoptions {"-Wno-misleading-indentation"}
end
if _OPTIONS["Wno-ignored-attributes"] ~= nil then
buildoptions {"-Wno-ignored-attributes"}
end
-- Why? OpenCV is always dynamically linked and we can only garantuee that there is one version in Extern (Thomas)
linkoptions {"-Wl,-rpath \"" .. path.getabsolute(EXTERN_PATH .. "/lib/") .. "\""}
configuration {"macosx", "gmake"}
defines { "BOOST_SIGNALS_NO_DEPRECATION_WARNING" }
buildoptions {"-std=c++11"}
-- disable some warnings
buildoptions {"-Wno-deprecated-declarations"}
buildoptions {"-Wno-deprecated-register"}
buildoptions {"-Wno-logical-op-parentheses"}
-- use clang on macOS
premake.gcc.cc = 'clang'
premake.gcc.cxx = 'clang++'
-- commons
dofile (FRAMEWORK_PATH .. "/Commons/Make/Commons.lua")
-- core
dofile "NaoTHSoccer.lua"
-- set up platforms
if _OPTIONS["platform"] == "Nao" then
dofile (FRAMEWORK_PATH .. "/Platforms/Make/NaoSMAL.lua")
-- HACK: boost from NaoQI SDK makes problems
buildoptions {"-Wno-conversion"}
defines { "BOOST_SIGNALS_NO_DEPRECATION_WARNING" }
-- ACHTUNG: NaoSMAL doesn't build with the flag -std=c++11 (because of Boost)
buildoptions {"-std=gnu++11"}
dofile (FRAMEWORK_PATH .. "/Platforms/Make/NaoRobot.lua")
kind "ConsoleApp"
links { "NaoTHSoccer", "Commons" }
else
dofile (FRAMEWORK_PATH .. "/Platforms/Make/SimSpark.lua")
kind "ConsoleApp"
links { "NaoTHSoccer", "Commons" }
debugargs { "--sync" }
dofile (FRAMEWORK_PATH .. "/Platforms/Make/LogSimulator.lua")
kind "ConsoleApp"
links { "NaoTHSoccer", "Commons" }
dofile (FRAMEWORK_PATH .. "/Platforms/Make/LogSimulatorJNI.lua")
kind "SharedLib"
links { "NaoTHSoccer", "Commons" }
end
|
Fix for using clang on macOS.
|
Fix for using clang on macOS.
|
Lua
|
apache-2.0
|
BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH
|
4a43d51426073b31c5cb6240fa75d6b60ec887e3
|
src/_premake_main.lua
|
src/_premake_main.lua
|
--
-- _premake_main.lua
-- Script-side entry point for the main program logic.
-- Copyright (c) 2002-2014 Jason Perkins and the Premake project
--
local shorthelp = "Type 'premake5 --help' for help"
local versionhelp = "premake5 (Premake Build Script Generator) %s"
_WORKING_DIR = os.getcwd()
--
-- Script-side program entry point.
--
function _premake_main()
-- Clear out any configuration scoping left over from initialization
filter {}
-- Seed the random number generator so actions don't have to do it themselves
math.randomseed(os.time())
-- Look for and run the system-wide configuration script; make sure any
-- configuration scoping gets cleared before continuing
dofileopt(_OPTIONS["systemscript"] or { "premake5-system.lua", "premake-system.lua" })
filter {}
-- The "next-gen" actions have now replaced their deprecated counterparts.
-- Provide a warning for a little while before I remove them entirely.
if _ACTION and _ACTION:endswith("ng") then
premake.warnOnce(_ACTION, "'%s' has been deprecated; use '%s' instead", _ACTION, _ACTION:sub(1, -3))
end
-- Set up the environment for the chosen action early, so side-effects
-- can be picked up by the scripts.
premake.action.set(_ACTION)
local action = premake.action.current()
-- If there is a project script available, run it to get the
-- project information, available options and actions, etc.
local hasScript = dofileopt(_OPTIONS["file"] or { "premake5.lua", "premake4.lua" })
-- Process special options
if (_OPTIONS["version"]) then
printf(versionhelp, _PREMAKE_VERSION)
return 1
end
if (_OPTIONS["help"]) then
premake.showhelp()
return 1
end
-- Validate the command-line arguments. This has to happen after the
-- script has run to allow for project-specific options
ok, err = premake.option.validate(_OPTIONS)
if not ok then
print("Error: " .. err)
return 1
end
-- If no further action is possible, show a short help message
if not _OPTIONS.interactive then
if not _ACTION then
print(shorthelp)
return 1
end
if not action then
print("Error: no such action '" .. _ACTION .. "'")
return 1
end
if not hasScript then
print("No Premake script (premake5.lua) found!")
return 1
end
end
-- "Bake" the project information, preparing it for use by the action
if action then
print("Building configurations...")
premake.oven.bake()
end
-- Run the interactive prompt, if requested
if _OPTIONS.interactive then
debug.prompt()
end
-- Sanity check the current project setup
premake.validate()
-- Hand over control to the action
printf("Running action '%s'...", action.trigger)
premake.action.call(action.trigger)
print("Done.")
return 0
end
|
--
-- _premake_main.lua
-- Script-side entry point for the main program logic.
-- Copyright (c) 2002-2014 Jason Perkins and the Premake project
--
local shorthelp = "Type 'premake5 --help' for help"
local versionhelp = "premake5 (Premake Build Script Generator) %s"
_WORKING_DIR = os.getcwd()
--
-- Script-side program entry point.
--
function _premake_main()
-- Clear out any configuration scoping left over from initialization
filter {}
-- Seed the random number generator so actions don't have to do it themselves
math.randomseed(os.time())
-- Look for and run the system-wide configuration script; make sure any
-- configuration scoping gets cleared before continuing
dofileopt(_OPTIONS["systemscript"] or { "premake5-system.lua", "premake-system.lua" })
filter {}
-- The "next-gen" actions have now replaced their deprecated counterparts.
-- Provide a warning for a little while before I remove them entirely.
if _ACTION and _ACTION:endswith("ng") then
premake.warnOnce(_ACTION, "'%s' has been deprecated; use '%s' instead", _ACTION, _ACTION:sub(1, -3))
end
-- Set up the environment for the chosen action early, so side-effects
-- can be picked up by the scripts.
premake.action.set(_ACTION)
-- If there is a project script available, run it to get the
-- project information, available options and actions, etc.
local hasScript = dofileopt(_OPTIONS["file"] or { "premake5.lua", "premake4.lua" })
-- Process special options
local action = premake.action.current()
if (_OPTIONS["version"]) then
printf(versionhelp, _PREMAKE_VERSION)
return 1
end
if (_OPTIONS["help"]) then
premake.showhelp()
return 1
end
-- Validate the command-line arguments. This has to happen after the
-- script has run to allow for project-specific options
ok, err = premake.option.validate(_OPTIONS)
if not ok then
print("Error: " .. err)
return 1
end
-- If no further action is possible, show a short help message
if not _OPTIONS.interactive then
if not _ACTION then
print(shorthelp)
return 1
end
if not action then
print("Error: no such action '" .. _ACTION .. "'")
return 1
end
if not hasScript then
print("No Premake script (premake5.lua) found!")
return 1
end
end
-- "Bake" the project information, preparing it for use by the action
if action then
print("Building configurations...")
premake.oven.bake()
end
-- Run the interactive prompt, if requested
if _OPTIONS.interactive then
debug.prompt()
end
-- Sanity check the current project setup
premake.validate()
-- Hand over control to the action
printf("Running action '%s'...", action.trigger)
premake.action.call(action.trigger)
print("Done.")
return 0
end
|
Fix action check to work with new interactive prompt
|
Fix action check to work with new interactive prompt
|
Lua
|
bsd-3-clause
|
annulen/premake,annulen/premake,annulen/premake,annulen/premake
|
379437b21fcceafaafd02bd399511db5cba6533a
|
src/lua/csv.lua
|
src/lua/csv.lua
|
-- csv.lua (internal file)
do
local ffi = require 'ffi'
ffi.cdef[[
typedef void (*csv_emit_row_t)(void *ctx);
typedef void (*csv_emit_field_t)(void *ctx, const char *field, const char *end);
struct csv
{
void *emit_ctx;
csv_emit_row_t emit_row;
csv_emit_field_t emit_field;
char csv_delim;
char csv_quote;
int csv_invalid;
int csv_ending_spaces;
void *(*csv_realloc)(void*, size_t);
int state;
char *buf;
char *bufp;
size_t buf_len;
};
void csv_create(struct csv *csv);
void csv_destroy(struct csv *csv);
void csv_setopt(struct csv *csv, int opt, ...);
struct csv_iterator {
struct csv *csv;
const char *buf_begin;
const char *buf_end;
const char *field;
size_t field_len;
};
typedef struct csv csv_t;
typedef struct csv_iterator csv_iterator_t;
void csv_iter_create(struct csv_iterator *it, struct csv *csv);
int csv_next(struct csv_iterator *);
void csv_feed(struct csv_iterator *, const char *);
int csv_escape_field(struct csv *, const char *, char *);
enum {
CSV_IT_OK,
CSV_IT_EOL,
CSV_IT_NEEDMORE,
CSV_IT_EOF,
CSV_IT_ERROR
};
]]
iter = function(csvstate)
local readable = csvstate[1]
local csv_chunk_size = csvstate[2]
local csv = csvstate[3]
local it = csvstate[4]
local errlog = csvstate[5]
local tup = {}
local st = ffi.C.csv_next(it)
while st ~= ffi.C.CSV_IT_EOF do
if st == ffi.C.CSV_IT_NEEDMORE then
ffi.C.csv_feed(it, readable:read(csv_chunk_size))
elseif st == ffi.C.CSV_IT_EOL then
return tup
elseif st == ffi.C.CSV_IT_OK then
table.insert(tup, ffi.string(it[0].field, it[0].field_len))
elseif st == ffi.C.CSV_IT_ERROR then
errlog.warn("CSV file has errors")
break
elseif st == ffi.C.CSV_IT_EOF then
break
end
st = ffi.C.csv_next(it)
end
end
csv = {
iterate = function(readable, csv_chunk_size)
csv_chunk_size = csv_chunk_size or 4096
if type(readable.read) ~= "function" then
error("Usage: load(object with read method)")
end
local errlog = require('log')
local it = ffi.new('csv_iterator_t[1]')
local csv = ffi.new('csv_t[1]')
ffi.C.csv_create(csv)
ffi.C.csv_iter_create(it, csv)
return iter, {readable, csv_chunk_size, csv, it, errlog}
end
,
load = function(readable, csv_chunk_size)
csv_chunk_size = csv_chunk_size or 4096
if type(readable.read) ~= "function" then
error("Usage: load(object with read method)")
end
result = {}
for tup in csv.iterate(readable, csv_chunk_size) do table.insert(result, tup) end
return result
end
,
dump = function(writable, t)
if type(writable.write) ~= "function" or type(t) ~= "table" then
error("Usage: dump(writable, table)")
end
local csv = ffi.new('csv_t[1]')
ffi.C.csv_create(csv)
local bufsz = 256
--local buf = ffi.new('char[?]', bufsz)
local buf = csv[0].csv_realloc(ffi.cast(ffi.typeof('void *'), 0), bufsz)
local it
if type(t[1]) ~= 'table' then
t = {t}
end
for k, line in pairs(t) do
local first = true
for k2, field in pairs(line) do
strf = tostring(field)
if (strf:len() + 1) * 2 > bufsz then
bufsz = (strf:len() + 1) * 2
buf = csv[0].csv_realloc(buf, bufsz)
end
local len = ffi.C.csv_escape_field(csv, strf, buf)
if first then
first = false
else
writable:write(',')
end
writable:write(ffi.string(buf, len))
end
writable:write('\n')
end
csv[0].csv_realloc(buf, 0)
end
}
return csv
end
|
-- csv.lua (internal file)
local ffi = require('ffi')
local log = require('log')
ffi.cdef[[
typedef void (*csv_emit_row_t)(void *ctx);
typedef void (*csv_emit_field_t)(void *ctx, const char *field, const char *end);
struct csv
{
void *emit_ctx;
csv_emit_row_t emit_row;
csv_emit_field_t emit_field;
char csv_delim;
char csv_quote;
int csv_invalid;
int csv_ending_spaces;
void *(*csv_realloc)(void*, size_t);
int state;
char *buf;
char *bufp;
size_t buf_len;
};
void csv_create(struct csv *csv);
void csv_destroy(struct csv *csv);
void csv_setopt(struct csv *csv, int opt, ...);
struct csv_iterator {
struct csv *csv;
const char *buf_begin;
const char *buf_end;
const char *field;
size_t field_len;
};
typedef struct csv csv_t;
typedef struct csv_iterator csv_iterator_t;
void csv_iter_create(struct csv_iterator *it, struct csv *csv);
int csv_next(struct csv_iterator *);
void csv_feed(struct csv_iterator *, const char *);
int csv_escape_field(struct csv *, const char *, char *);
enum {
CSV_IT_OK,
CSV_IT_EOL,
CSV_IT_NEEDMORE,
CSV_IT_EOF,
CSV_IT_ERROR
};
]]
local iter = function(csvstate)
local readable = csvstate[1]
local csv_chunk_size = csvstate[2]
local csv = csvstate[3]
local it = csvstate[4]
local tup = {}
local st = ffi.C.csv_next(it)
while st ~= ffi.C.CSV_IT_EOF do
if st == ffi.C.CSV_IT_NEEDMORE then
ffi.C.csv_feed(it, readable:read(csv_chunk_size))
elseif st == ffi.C.CSV_IT_EOL then
return tup
elseif st == ffi.C.CSV_IT_OK then
table.insert(tup, ffi.string(it[0].field, it[0].field_len))
elseif st == ffi.C.CSV_IT_ERROR then
log.warn("CSV file has errors")
break
elseif st == ffi.C.CSV_IT_EOF then
break
end
st = ffi.C.csv_next(it)
end
end
local csv = {
iterate = function(readable, csv_chunk_size)
csv_chunk_size = csv_chunk_size or 4096
if type(readable.read) ~= "function" then
error("Usage: load(object with read method)")
end
local it = ffi.new('csv_iterator_t[1]')
local csv = ffi.new('csv_t[1]')
ffi.C.csv_create(csv)
ffi.C.csv_iter_create(it, csv)
return iter, {readable, csv_chunk_size, csv, it}
end,
load = function(readable, csv_chunk_size)
csv_chunk_size = csv_chunk_size or 4096
if type(readable.read) ~= "function" then
error("Usage: load(object with read method)")
end
result = {}
for tup in csv.iterate(readable, csv_chunk_size) do
table.insert(result, tup)
end
return result
end,
dump = function(writable, t)
if type(writable.write) ~= "function" or type(t) ~= "table" then
error("Usage: dump(writable, table)")
end
local csv = ffi.new('csv_t[1]')
ffi.C.csv_create(csv)
local bufsz = 256
--local buf = ffi.new('char[?]', bufsz)
local buf = csv[0].csv_realloc(ffi.cast(ffi.typeof('void *'), 0), bufsz)
if type(t[1]) ~= 'table' then
t = {t}
end
for k, line in pairs(t) do
local first = true
for k2, field in pairs(line) do
strf = tostring(field)
if (strf:len() + 1) * 2 > bufsz then
bufsz = (strf:len() + 1) * 2
buf = csv[0].csv_realloc(buf, bufsz)
end
local len = ffi.C.csv_escape_field(csv, strf, buf)
if first then
first = false
else
writable:write(',')
end
writable:write(ffi.string(buf, len))
end
writable:write('\n')
end
csv[0].csv_realloc(buf, 0)
end
}
return csv
|
Style fixes
|
Style fixes
|
Lua
|
bsd-2-clause
|
guard163/tarantool,KlonD90/tarantool,ocelot-inc/tarantool,guard163/tarantool,mejedi/tarantool,KlonD90/tarantool,Sannis/tarantool,rtsisyk/tarantool,condor-the-bird/tarantool,ocelot-inc/tarantool,guard163/tarantool,KlonD90/tarantool,KlonD90/tarantool,vasilenkomike/tarantool,Sannis/tarantool,vasilenkomike/tarantool,mejedi/tarantool,mejedi/tarantool,condor-the-bird/tarantool,rtsisyk/tarantool,KlonD90/tarantool,vasilenkomike/tarantool,condor-the-bird/tarantool,rtsisyk/tarantool,vasilenkomike/tarantool,Sannis/tarantool,vasilenkomike/tarantool,guard163/tarantool,ocelot-inc/tarantool,mejedi/tarantool,rtsisyk/tarantool,guard163/tarantool,Sannis/tarantool,condor-the-bird/tarantool,ocelot-inc/tarantool,condor-the-bird/tarantool,Sannis/tarantool
|
6e1d2eed2c2a65ad60d0895dbbc52d405c56564c
|
share/lua/website/tube8.lua
|
share/lua/website/tube8.lua
|
-- libquvi-scripts
-- Copyright (C) 2010 quvi project
--
-- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>.
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-- 02110-1301 USA
--
-- Identify the script.
function ident (self)
package.path = self.script_dir .. '/?.lua'
local C = require 'quvi/const'
local r = {}
r.domain = "tube8%.com"
r.formats = "default"
r.categories = C.proto_http
local U = require 'quvi/util'
r.handles = U.handles(self.page_url, {r.domain}, {"/%w+/[%w-_]+/%d+"})
return r
end
-- Query available formats.
function query_formats(self)
self.formats = 'default'
return self
end
-- Parse media URL.
function parse (self)
self.host_id = "tube8"
local page = quvi.fetch(self.page_url .. "?processdisclaimer")
local _,_,s = page:find("<title>(.-)%s+-")
self.title = s or error ("no match: media title")
local _,_,s = page:find('name="vidId" value="(%d+)"')
self.id = s or error ("no match: media id")
local _,_,s = page:find('videourl="(.-)"')
self.url = {s or error ("no match: file")}
return self
end
-- vim: set ts=4 sw=4 tw=72 expandtab:
|
-- libquvi-scripts
-- Copyright (C) 2010 quvi project
--
-- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>.
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-- 02110-1301 USA
--
-- Identify the script.
function ident (self)
package.path = self.script_dir .. '/?.lua'
local C = require 'quvi/const'
local r = {}
r.domain = "tube8%.com"
r.formats = "default"
r.categories = C.proto_http
local U = require 'quvi/util'
r.handles = U.handles(self.page_url, {r.domain}, {"/%w+/[%w-_]+/%d+"})
return r
end
-- Query available formats.
function query_formats(self)
self.formats = 'default'
return self
end
-- Parse media URL.
function parse (self)
self.host_id = "tube8"
local page = quvi.fetch(self.page_url .. "?processdisclaimer")
local _,_,s = page:find("<title>(.-)%s+-")
self.title = s or error ("no match: media title")
local _,_,s = page:find('name="vidId" value="(%d+)"')
self.id = s or error ("no match: media id")
local U = require 'quvi/util'
local _,_,s = page:find('"video_url":"(.-)"')
self.url = { U.unescape( s or error ("no match: file") ) }
return self
end
-- vim: set ts=4 sw=4 tw=72 expandtab:
|
Fix tube8.lua url parsing
|
Fix tube8.lua url parsing
|
Lua
|
agpl-3.0
|
alech/libquvi-scripts,legatvs/libquvi-scripts,legatvs/libquvi-scripts,hadess/libquvi-scripts-iplayer,DangerCove/libquvi-scripts,DangerCove/libquvi-scripts,alech/libquvi-scripts,hadess/libquvi-scripts-iplayer
|
5ba6fb47c3e0b36a0bafacda0bd2c86ba7db646d
|
mods/base/req/hooks.lua
|
mods/base/req/hooks.lua
|
_G.Hooks = Hooks or {}
Hooks._registered_hooks = Hooks._registered_hooks or {}
Hooks._prehooks = Hooks._prehooks or {}
Hooks._posthooks = Hooks._posthooks or {}
--[[
Hooks:Register( key )
Registers a hook so that functions can be added to it, and later called
key, Unique identifier for the hook, so that hooked functions can be added to it
]]
function Hooks:RegisterHook( key )
self._registered_hooks[key] = self._registered_hooks[key] or {}
end
--[[
Hooks:Register( key )
Functionaly the same as Hooks:RegisterHook
]]
function Hooks:Register( key )
self:RegisterHook( key )
end
--[[
Hooks:AddHook( key, id, func )
Adds a function call to a hook, so that it will be called when the hook is
key, The unique identifier of the hook to be called on
id, A unique identifier for this specific function call
func, The function to call with the hook
]]
function Hooks:AddHook( key, id, func )
self._registered_hooks[key] = self._registered_hooks[key] or {}
local tbl = {
id = id,
func = func
}
table.insert( self._registered_hooks[key], tbl )
end
--[[
Hooks:Add( key, id, func )
Functionaly the same as Hooks:AddHook
]]
function Hooks:Add( key, id, func )
self:AddHook( key, id, func )
end
--[[
Hooks:UnregisterHook( key )
Removes a hook, so that it will not call any functions
key, The unique identifier of the hook to unregister
]]
function Hooks:UnregisterHook( key )
self._registered_hooks[key] = nil
end
--[[
Hooks:Unregister( key )
Functionaly the same as Hooks:UnregisterHook
]]
function Hooks:Unregister( key )
self:UnregisterHook( key )
end
--[[
Hooks:Remove( id )
Removes a hooked function call with the specified id to prevent it from being called
id, Removes the function call and prevents it from being called
]]
function Hooks:Remove( id )
for k, v in pairs(self._registered_hooks) do
if type(v) == "table" then
for x, y in pairs( v ) do
if y.id == id then
y = nil
end
end
end
end
end
--[[
Hooks:Call( key, ... )
Calls a specified hook, and all of its hooked functions
key, The unique identifier of the hook to call its hooked functions
args, The arguments to pass to the hooked functions
]]
function Hooks:Call( key, ... )
if not self._registered_hooks[key] then
return
end
for k, v in pairs(self._registered_hooks[key]) do
if v then
if type(v.func) == "function" then
v.func( ... )
end
end
end
end
--[[
Hooks:ReturnCall( key, ... )
Calls a specified hook, and returns the first non-nil value returned by a hooked function
key, The unique identifier of the hook to call its hooked functions
args, The arguments to pass to the hooked functions
returns, The first non-nil value returned by a hooked function
]]
function Hooks:ReturnCall( key, ... )
if not self._registered_hooks[key] then
return
end
for k, v in pairs(self._registered_hooks[key]) do
if v then
if type(v.func) == "function" then
local r = v.func( ... )
if r ~= nil then
return r
end
end
end
end
end
--[[
Hooks:PreHook( object, func, id, pre_call )
Automatically hooks a function to be called before the specified function on a specified object
object, The object for the hooked function to be called on
func, The name of the function (as a string) on the object for the hooked call to be ran before
id, The unique identifier for this prehook
pre_call, The function to be called before the func on object
]]
function Hooks:PreHook( object, func, id, pre_call )
if not object then
self:_PrePostHookError(func)
return
end
if object and self._prehooks[object] == nil then
self._prehooks[object] = {}
end
if object and self._prehooks[object][func] == nil then
self._prehooks[object][func] = {
original = object[func],
overrides = {}
}
object[func] = function(...)
local hooked_func = self._prehooks[object][func]
local r, _r
for k, v in ipairs(hooked_func.overrides) do
if v.func then
_r = v.func(...)
end
if _r then
r = _r
end
end
_r = hooked_func.original(...)
if _r then
r = _r
end
return r
end
end
for k, v in pairs( self._prehooks[object][func].overrides ) do
if v.id == id then
return
end
end
local func_tbl = {
id = id,
func = pre_call,
}
table.insert( self._prehooks[object][func].overrides, func_tbl )
end
--[[
Hooks:RemovePreHook( id )
Removes the prehook with id, and prevents it from being run
id, The unique identifier of the prehook to remove
]]
function Hooks:RemovePreHook( id )
for object_i, object in pairs( self._prehooks ) do
for func_i, func in pairs( object ) do
for override_i, override in ipairs( func.overrides ) do
if override and override.id == id then
table.remove( func.overrides, override_i )
end
end
end
end
end
--[[
Hooks:PostHook( object, func, id, post_call )
Automatically hooks a function to be called after the specified function on a specified object
object, The object for the hooked function to be called on
func, The name of the function (as a string) on the object for the hooked call to be ran after
id, The unique identifier for this posthook
post_call, The function to be called after the func on object
]]
function Hooks:PostHook( object, func, id, post_call )
if not object then
self:_PrePostHookError(func)
return
end
if object and self._posthooks[object] == nil then
self._posthooks[object] = {}
end
if object and self._posthooks[object][func] == nil then
self._posthooks[object][func] = {
original = object[func],
overrides = {}
}
object[func] = function(...)
local hooked_func = self._posthooks[object][func]
local r, _r
_r = hooked_func.original(...)
if _r then
r = _r
end
for k, v in ipairs(hooked_func.overrides) do
if v.func then
_r = v.func(...)
end
if _r then
r = _r
end
end
return r
end
end
for k, v in pairs( self._posthooks[object][func].overrides ) do
if v.id == id then
return
end
end
local func_tbl = {
id = id,
func = post_call,
}
table.insert( self._posthooks[object][func].overrides, func_tbl )
end
--[[
Hooks:RemovePostHook( id )
Removes the posthook with id, and prevents it from being run
id, The unique identifier of the posthook to remove
]]
function Hooks:RemovePostHook( id )
for object_i, object in pairs( self._posthooks ) do
for func_i, func in pairs( object ) do
for override_i, override in ipairs( func.overrides ) do
if override and override.id == id then
table.remove( func.overrides, override_i )
end
end
end
end
end
function Hooks:_PrePostHookError( func )
log("[Hooks] Error: Could not hook function '", tostring(func), "'!")
end
|
_G.Hooks = Hooks or {}
Hooks._registered_hooks = Hooks._registered_hooks or {}
Hooks._prehooks = Hooks._prehooks or {}
Hooks._posthooks = Hooks._posthooks or {}
--[[
Hooks:Register( key )
Registers a hook so that functions can be added to it, and later called
key, Unique identifier for the hook, so that hooked functions can be added to it
]]
function Hooks:RegisterHook( key )
self._registered_hooks[key] = self._registered_hooks[key] or {}
end
--[[
Hooks:Register( key )
Functionaly the same as Hooks:RegisterHook
]]
function Hooks:Register( key )
self:RegisterHook( key )
end
--[[
Hooks:AddHook( key, id, func )
Adds a function call to a hook, so that it will be called when the hook is
key, The unique identifier of the hook to be called on
id, A unique identifier for this specific function call
func, The function to call with the hook
]]
function Hooks:AddHook( key, id, func )
self._registered_hooks[key] = self._registered_hooks[key] or {}
-- Update existing hook
for k, v in pairs( self._registered_hooks[key] ) do
if v.id == id then
v.func = func
return
end
end
-- Add new hook, if id doesn't exist
local tbl = {
id = id,
func = func
}
table.insert( self._registered_hooks[key], tbl )
end
--[[
Hooks:Add( key, id, func )
Functionaly the same as Hooks:AddHook
]]
function Hooks:Add( key, id, func )
self:AddHook( key, id, func )
end
--[[
Hooks:UnregisterHook( key )
Removes a hook, so that it will not call any functions
key, The unique identifier of the hook to unregister
]]
function Hooks:UnregisterHook( key )
self._registered_hooks[key] = nil
end
--[[
Hooks:Unregister( key )
Functionaly the same as Hooks:UnregisterHook
]]
function Hooks:Unregister( key )
self:UnregisterHook( key )
end
--[[
Hooks:Remove( id )
Removes a hooked function call with the specified id to prevent it from being called
id, Removes the function call and prevents it from being called
]]
function Hooks:Remove( id )
for k, v in pairs(self._registered_hooks) do
if type(v) == "table" then
for x, y in pairs( v ) do
if y.id == id then
y = nil
end
end
end
end
end
--[[
Hooks:Call( key, ... )
Calls a specified hook, and all of its hooked functions
key, The unique identifier of the hook to call its hooked functions
args, The arguments to pass to the hooked functions
]]
function Hooks:Call( key, ... )
if not self._registered_hooks[key] then
return
end
for k, v in pairs(self._registered_hooks[key]) do
if v then
if type(v.func) == "function" then
v.func( ... )
end
end
end
end
--[[
Hooks:ReturnCall( key, ... )
Calls a specified hook, and returns the first non-nil value returned by a hooked function
key, The unique identifier of the hook to call its hooked functions
args, The arguments to pass to the hooked functions
returns, The first non-nil value returned by a hooked function
]]
function Hooks:ReturnCall( key, ... )
if not self._registered_hooks[key] then
return
end
for k, v in pairs(self._registered_hooks[key]) do
if v then
if type(v.func) == "function" then
local r = v.func( ... )
if r ~= nil then
return r
end
end
end
end
end
--[[
Hooks:PreHook( object, func, id, pre_call )
Automatically hooks a function to be called before the specified function on a specified object
object, The object for the hooked function to be called on
func, The name of the function (as a string) on the object for the hooked call to be ran before
id, The unique identifier for this prehook
pre_call, The function to be called before the func on object
]]
function Hooks:PreHook( object, func, id, pre_call )
if not object then
self:_PrePostHookError(func)
return
end
if object and self._prehooks[object] == nil then
self._prehooks[object] = {}
end
if object and self._prehooks[object][func] == nil then
self._prehooks[object][func] = {
original = object[func],
overrides = {}
}
object[func] = function(...)
local hooked_func = self._prehooks[object][func]
local r, _r
for k, v in ipairs(hooked_func.overrides) do
if v.func then
_r = v.func(...)
end
if _r then
r = _r
end
end
_r = hooked_func.original(...)
if _r then
r = _r
end
return r
end
end
for k, v in pairs( self._prehooks[object][func].overrides ) do
if v.id == id then
return
end
end
local func_tbl = {
id = id,
func = pre_call,
}
table.insert( self._prehooks[object][func].overrides, func_tbl )
end
--[[
Hooks:RemovePreHook( id )
Removes the prehook with id, and prevents it from being run
id, The unique identifier of the prehook to remove
]]
function Hooks:RemovePreHook( id )
for object_i, object in pairs( self._prehooks ) do
for func_i, func in pairs( object ) do
for override_i, override in ipairs( func.overrides ) do
if override and override.id == id then
table.remove( func.overrides, override_i )
end
end
end
end
end
--[[
Hooks:PostHook( object, func, id, post_call )
Automatically hooks a function to be called after the specified function on a specified object
object, The object for the hooked function to be called on
func, The name of the function (as a string) on the object for the hooked call to be ran after
id, The unique identifier for this posthook
post_call, The function to be called after the func on object
]]
function Hooks:PostHook( object, func, id, post_call )
if not object then
self:_PrePostHookError(func)
return
end
if object and self._posthooks[object] == nil then
self._posthooks[object] = {}
end
if object and self._posthooks[object][func] == nil then
self._posthooks[object][func] = {
original = object[func],
overrides = {}
}
object[func] = function(...)
local hooked_func = self._posthooks[object][func]
local r, _r
_r = hooked_func.original(...)
if _r then
r = _r
end
for k, v in ipairs(hooked_func.overrides) do
if v.func then
_r = v.func(...)
end
if _r then
r = _r
end
end
return r
end
end
for k, v in pairs( self._posthooks[object][func].overrides ) do
if v.id == id then
return
end
end
local func_tbl = {
id = id,
func = post_call,
}
table.insert( self._posthooks[object][func].overrides, func_tbl )
end
--[[
Hooks:RemovePostHook( id )
Removes the posthook with id, and prevents it from being run
id, The unique identifier of the posthook to remove
]]
function Hooks:RemovePostHook( id )
for object_i, object in pairs( self._posthooks ) do
for func_i, func in pairs( object ) do
for override_i, override in ipairs( func.overrides ) do
if override and override.id == id then
table.remove( func.overrides, override_i )
end
end
end
end
end
function Hooks:_PrePostHookError( func )
log("[Hooks] Error: Could not hook function '", tostring(func), "'!")
end
|
Fixed hooks with duplicate id's being added twice
|
Fixed hooks with duplicate id's being added twice
|
Lua
|
mit
|
Olipro/Payday-2-BLT_Club-Sandwich-Edition,antonpup/Payday-2-BLT,SirWaddles/Payday-2-BLT,JamesWilko/Payday-2-BLT,SirWaddles/Payday-2-BLT,JamesWilko/Payday-2-BLT,antonpup/Payday-2-BLT,Olipro/Payday-2-BLT_Club-Sandwich-Edition
|
0c220601207265cb4dfc520d4d35cbf244c5c4b5
|
share/lua/website/guardian.lua
|
share/lua/website/guardian.lua
|
-- libquvi-scripts
-- Copyright (C) 2011 Toni Gundogdu <legatvs@gmail.com>
--
-- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>.
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-- 02110-1301 USA
--
--
-- NOTE: Ignores the m3u8 format. Patches welcome.
--
-- libquvi allows specifying multiple media stream URLs in
-- "self.url" (referred sometimes as "media or video segments"),
-- e.g.
-- self.url = {"http://foo", "http://bar"}
--
-- Whether the applications using libquvi make any use of this,
-- is a whole different matter.
--
local Guardian = {} -- Utility functions unique to this script
-- Identify the script.
function ident (self)
package.path = self.script_dir .. '/?.lua'
local C = require 'quvi/const'
local r = {}
r.domain = "guardian%.co%.uk"
r.formats = "default"
r.categories = C.proto_http
local U = require 'quvi/util'
r.handles = U.handles(self.page_url,
{r.domain}, {"/video/","/audio"})
return r
end
-- Query available formats.
function query_formats(self)
local c = Guardian.get_config(self)
local fmts = Guardian.iter_formats(c)
local t = {}
for _,v in pairs(fmts) do
table.insert(t, Guardian.to_s(v))
end
table.sort(t)
self.formats = table.concat(t, "|")
return self
end
-- Parse media URL.
function parse(self)
self.host_id = "guardian"
local c = Guardian.get_config(self)
local formats = Guardian.iter_formats(c)
local U = require 'quvi/util'
local format = U.choose_format(self, formats,
Guardian.choose_best,
Guardian.choose_default,
Guardian.to_s)
or error("unable to choose format")
self.url = {format.url or error("no match: media url")}
self.title = c:match('"headline":%s+"(.-)%s+-%s+video"')
or error("no match: media title")
self.id = c:match('"video%-id":%s+"(.-)"')
or error ("no match: media id")
self.thumbnail_url = c:match('"thumbnail%-image%-url":%s+"(.-)"') or ''
local d = c:match('"duration":%s+(%d+)') or 0
self.duration = tonumber(d)*1000 -- to msec
return self
end
--
-- Utility functions
--
function Guardian.get_config(self)
return quvi.fetch(self.page_url .. "/json", {fetch_type='config'})
end
function Guardian.iter_formats(config)
local p = '"format":%s+"(.-)".-"video%-file%-url":%s+"(.-)"'
local t = {}
for c,u in config:gmatch(p) do
-- print(f,u)
c = c:gsub("video/", "")
c = c:gsub(":", "_")
if c ~= "m3u8" then -- http://en.wikipedia.org/wiki/M3U
table.insert(t, {container=c, url=u})
end
end
return t
end
function Guardian.choose_best(t) -- Expect the first to be the 'best'
return t[1]
end
function Guardian.choose_default(t) -- Use the first
return t[1]
end
function Guardian.to_s(t)
return t.container
end
-- vim: set ts=4 sw=4 tw=72 expandtab:
|
-- libquvi-scripts
-- Copyright (C) 2011,2013 Toni Gundogdu <legatvs@gmail.com>
--
-- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>.
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-- 02110-1301 USA
--
local Guardian = {} -- Utility functions unique to this script
-- Identify the script.
function ident(self)
package.path = self.script_dir .. '/?.lua'
local C = require 'quvi/const'
local r = {}
r.domain = "guardian%.co%.uk"
r.formats = "default"
r.categories = C.proto_http
local U = require 'quvi/util'
r.handles = U.handles(self.page_url, {r.domain}, {"/video/","/audio/"})
return r
end
-- Query available formats.
function query_formats(self)
self.formats = 'default'
return self
end
-- Parse media URL.
function parse(self)
self.host_id = "guardian"
local p = quvi.fetch(self.page_url)
self.title = p:match('"og:title" content="(.-)"')
or error('no match: media title')
self.id = p:match('containerID%s+=%s+["\'](.-)["\']')
or p:match('audioID%s+=%s+["\'](.-)["\']')
or ''
self.id = self.id:match('(%d+)') or error('no match: media ID')
self.duration = tonumber(p:match('duration%:%s+"?(%d+)"?') or 0) * 1000
self.thumbnail_url = p:match('"thumbnail" content="(.-)"')
or p:match('"og:image" content="(.-)"') or ''
self.url = {p:match('file:%s+"(.-)"')
or error('no match: media stream URL')}
return self
end
-- vim: set ts=4 sw=4 tw=72 expandtab:
|
FIX: website/guardian.lua: all patterns
|
FIX: website/guardian.lua: all patterns
* Remove stream interation (only one appears to be available now)
* Parse all media properties from the media page
* Remove unused Guardian.* functions
* Improve thumbnail URL parsing
Signed-off-by: Toni Gundogdu <eac2284b3c43676907b96f08de9d3d52d5df0361@gmail.com>
|
Lua
|
agpl-3.0
|
alech/libquvi-scripts,legatvs/libquvi-scripts,legatvs/libquvi-scripts,alech/libquvi-scripts
|
c23c49630414156c15635f77e03d3c51a268f723
|
themes/term.lua
|
themes/term.lua
|
-- Copyright 2007-2020 Mitchell mitchell.att.foicica.com. See LICENSE.
-- Terminal theme for Textadept.
-- Contributions by Ana Balan.
local view, colors, styles = view, lexer.colors, lexer.styles
-- Normal colors.
colors.black = 0x000000
colors.red = 0x000080
colors.green = 0x008000
colors.yellow = 0x008080
colors.blue = 0x800000
colors.magenta = 0x800080
colors.cyan = 0x808000
colors.white = 0xC0C0C0
-- Light colors. (16 color terminals only.)
-- These only apply to 16 color terminals. For other terminals, set the
-- style's `bold` attribute to use the light color variant.
colors.light_black = 0x404040
colors.light_red = 0x0000FF
colors.light_green = 0x00FF00
colors.light_yellow = 0x00FFFF
colors.light_blue = 0xFF0000
colors.light_magenta = 0xFF00FF
colors.light_cyan = 0xFFFF00
colors.light_white = 0xFFFFFF
-- Predefined styles.
styles.default = {fore = colors.white, back = colors.black}
styles.line_number = {fore = colors.black, bold = true}
styles.brace_light = {fore = colors.black, back = colors.white}
--styles.control_char =
--styles.indent_guide =
--styles.call_tip =
styles.fold_display_text = {fore = colors.black, bold = true}
-- Token styles.
styles.class = {fore = colors.yellow}
styles.comment = {fore = colors.black, bold = true}
styles.constant = {fore = colors.red}
styles.embedded = {fore = colors.white, bold = true, back = colors.black}
styles.error = {fore = colors.red, bold = true}
styles['function'] = {fore = colors.blue}
styles.identifier = {}
styles.keyword = {fore = colors.white, bold = true}
styles.label = {fore = colors.red, bold = true}
styles.number = {fore = colors.cyan}
styles.operator = {fore = colors.yellow}
styles.preprocessor = {fore = colors.magenta}
styles.regex = {fore = colors.green, bold = true}
styles.string = {fore = colors.green}
styles.type = {fore = colors.magenta, bold = true}
styles.variable = {fore = colors.blue, bold = true}
styles.whitespace = {}
-- Multiple Selection and Virtual Space
--view.additional_sel_fore =
--view.additional_sel_back =
--view.additional_caret_fore =
-- Caret and Selection Styles.
--view:set_sel_fore(true, colors.white)
--view:set_sel_back(true, colors.black)
--view.caret_fore = colors.black
--view.caret_line_back =
-- Fold Margin.
--view:set_fold_margin_color(true, colors.white)
--view:set_fold_margin_hi_color(true, colors.white)
-- Markers.
view.marker_back[textadept.bookmarks.MARK_BOOKMARK] = colors.blue
view.marker_back[textadept.run.MARK_WARNING] = colors.yellow
view.marker_back[textadept.run.MARK_ERROR] = colors.red
-- Indicators.
view.indic_fore[ui.find.INDIC_FIND] = colors.yellow
view.indic_fore[textadept.editing.INDIC_HIGHLIGHT] = colors.yellow
view.indic_fore[textadept.snippets.INDIC_PLACEHOLDER] = colors.magenta
-- Call tips.
view.call_tip_fore_hlt = colors.blue
-- Long Lines.
view.edge_color = colors.red
|
-- Copyright 2007-2020 Mitchell mitchell.att.foicica.com. See LICENSE.
-- Terminal theme for Textadept.
-- Contributions by Ana Balan.
local view, colors, styles = view, lexer.colors, lexer.styles
-- Normal colors.
colors.black = 0x000000
colors.red = 0x000080
colors.green = 0x008000
colors.yellow = 0x008080
colors.blue = 0x800000
colors.magenta = 0x800080
colors.cyan = 0x808000
colors.white = 0xC0C0C0
-- Light colors. (16 color terminals only.)
-- These only apply to 16 color terminals. For other terminals, set the
-- style's `bold` attribute to use the light color variant.
colors.light_black = 0x404040
colors.light_red = 0x0000FF
colors.light_green = 0x00FF00
colors.light_yellow = 0x00FFFF
colors.light_blue = 0xFF0000
colors.light_magenta = 0xFF00FF
colors.light_cyan = 0xFFFF00
colors.light_white = 0xFFFFFF
-- Predefined styles.
styles.default = {fore = colors.white, back = colors.black}
styles.line_number = {fore = colors.black, bold = true}
styles.brace_light = {fore = colors.black, back = colors.white}
--styles.control_char =
--styles.indent_guide =
styles.call_tip = {fore = colors.white, back = colors.black}
styles.fold_display_text = {fore = colors.black, bold = true}
-- Token styles.
styles.class = {fore = colors.yellow}
styles.comment = {fore = colors.black, bold = true}
styles.constant = {fore = colors.red}
styles.embedded = {fore = colors.white, bold = true, back = colors.black}
styles.error = {fore = colors.red, bold = true}
styles['function'] = {fore = colors.blue}
styles.identifier = {}
styles.keyword = {fore = colors.white, bold = true}
styles.label = {fore = colors.red, bold = true}
styles.number = {fore = colors.cyan}
styles.operator = {fore = colors.yellow}
styles.preprocessor = {fore = colors.magenta}
styles.regex = {fore = colors.green, bold = true}
styles.string = {fore = colors.green}
styles.type = {fore = colors.magenta, bold = true}
styles.variable = {fore = colors.blue, bold = true}
styles.whitespace = {}
-- Multiple Selection and Virtual Space
--view.additional_sel_fore =
--view.additional_sel_back =
--view.additional_caret_fore =
-- Caret and Selection Styles.
--view:set_sel_fore(true, colors.white)
--view:set_sel_back(true, colors.black)
--view.caret_fore = colors.black
--view.caret_line_back =
-- Fold Margin.
--view:set_fold_margin_color(true, colors.white)
--view:set_fold_margin_hi_color(true, colors.white)
-- Markers.
view.marker_back[textadept.bookmarks.MARK_BOOKMARK] = colors.blue
view.marker_back[textadept.run.MARK_WARNING] = colors.yellow
view.marker_back[textadept.run.MARK_ERROR] = colors.red
-- Indicators.
view.indic_fore[ui.find.INDIC_FIND] = colors.yellow
view.indic_fore[textadept.editing.INDIC_HIGHLIGHT] = colors.yellow
view.indic_fore[textadept.snippets.INDIC_PLACEHOLDER] = colors.magenta
-- Call tips.
view.call_tip_fore_hlt = colors.blue
-- Long Lines.
view.edge_color = colors.red
|
Fixed call tip style display in the terminal version. It does not appear to inherit from STYLE_DEFAULT. The bug was introduced in r2817.
|
Fixed call tip style display in the terminal version.
It does not appear to inherit from STYLE_DEFAULT.
The bug was introduced in r2817.
|
Lua
|
mit
|
rgieseke/textadept,rgieseke/textadept
|
f81d529e36399feeb9d674f40013d469d43178af
|
modulefiles/Core/eemt/0.1.lua
|
modulefiles/Core/eemt/0.1.lua
|
help(
[[
This module loads the EEMT stack which includes a bunch of GIS tools
]])
whatis("Loads the EEMT GIS system")
local version = "0.1"
local base = "/cvmfs/oasis.opensciencegrid.org/osg/modules/eemt/"..version
prepend_path("PATH", base.."/grass-6.4.4/bin")
prepend_path("PATH", base.."/grass-6.4.4/scripts")
prepend_path("PATH", base.."/bin")
prepend_path("LD_LIBRARY_PATH", base.."/grass-6.4.4/lib")
prepend_path("LD_LIBRARY_PATH", base.."/lib")
prepend_path("PYTHONPATH", base.."/grass-6.4.4/lib/python2.7/site-packages")
family('eemt')
|
help(
[[
This module loads the EEMT stack which includes a bunch of GIS tools
]])
whatis("Loads the EEMT GIS system")
local version = "0.1"
local base = "/cvmfs/oasis.opensciencegrid.org/osg/modules/eemt/"..version
setenv("GISBASE", base.."/grass-6.4.4")
prepend_path("PATH", base.."/grass-6.4.4/bin")
prepend_path("PATH", base.."/grass-6.4.4/scripts")
prepend_path("PATH", base.."/bin")
prepend_path("LD_LIBRARY_PATH", base.."/grass-6.4.4/lib")
prepend_path("LD_LIBRARY_PATH", base.."/lib")
prepend_path("PYTHONPATH", base.."/grass-6.4.4/lib/python2.7/site-packages")
family('eemt')
|
EEMT fix
|
EEMT fix
|
Lua
|
apache-2.0
|
OSGConnect/modulefiles,OSGConnect/modulefiles,OSGConnect/modulefiles
|
f33051f68fb931a66026e228719a194e09e4f2b7
|
packages/lime-proto-anygw/files/usr/lib/lua/lime/proto/anygw.lua
|
packages/lime-proto-anygw/files/usr/lib/lua/lime/proto/anygw.lua
|
#!/usr/bin/lua
local fs = require("nixio.fs")
local network = require("lime.network")
local config = require("lime.config")
anygw = {}
anygw.configured = false
anygw.SAFE_CLIENT_MTU = 1350
function anygw.configure(args)
if anygw.configured then return end
anygw.configured = true
local ipv4, ipv6 = network.primary_address()
local anygw_mac = config.get("network", "anygw_mac")
anygw_mac = utils.applyNetTemplate16(anygw_mac)
--! bytes 4 & 5 vary depending on %N1 and %N2 by default
local anygw_mac_mask = "ff:ff:ff:00:00:00"
local anygw_ipv6 = ipv6:minhost()
local anygw_ipv4 = ipv4:minhost()
anygw_ipv6:prefix(64) -- SLAAC only works with a /64, per RFC
anygw_ipv4:prefix(ipv4:prefix())
local baseIfname = "br-lan"
local argsDev = { macaddr = anygw_mac }
local argsIf = { proto = "static" }
argsIf.ip6addr = anygw_ipv6:string()
argsIf.ipaddr = anygw_ipv4:host():string()
argsIf.netmask = anygw_ipv4:mask():string()
local owrtInterfaceName, _, _ = network.createMacvlanIface( baseIfname,
"anygw", argsDev, argsIf )
local uci = config.get_uci_cursor()
local pfr = network.limeIfNamePrefix.."anygw_"
uci:set("network", pfr.."rule6", "rule6")
uci:set("network", pfr.."rule6", "src", anygw_ipv6:host():string().."/128")
uci:set("network", pfr.."rule6", "lookup", "170") -- 0xaa in decimal
uci:set("network", pfr.."route6", "route6")
uci:set("network", pfr.."route6", "interface", owrtInterfaceName)
uci:set("network", pfr.."route6", "target", anygw_ipv6:network():string().."/"..anygw_ipv6:prefix())
uci:set("network", pfr.."route6", "table", "170")
uci:set("network", pfr.."rule4", "rule")
uci:set("network", pfr.."rule4", "src", anygw_ipv4:host():string().."/32")
uci:set("network", pfr.."rule4", "lookup", "170")
uci:set("network", pfr.."route4", "route")
uci:set("network", pfr.."route4", "interface", owrtInterfaceName)
uci:set("network", pfr.."route4", "target", anygw_ipv4:network():string())
uci:set("network", pfr.."route4", "netmask", anygw_ipv4:mask():string())
uci:set("network", pfr.."route4", "table", "170")
uci:save("network")
fs.mkdir("/etc/firewall.lime.d")
fs.writefile(
"/etc/firewall.lime.d/20-anygw-ebtables",
"\n" ..
"ebtables -D FORWARD -j DROP -d " .. anygw_mac .. "/" .. anygw_mac_mask .. "\n" ..
"ebtables -A FORWARD -j DROP -d " .. anygw_mac .. "/" .. anygw_mac_mask .. "\n" ..
"ebtables -t nat -D POSTROUTING -o bat0 -j DROP -s " .. anygw_mac .. "/" .. anygw_mac_mask .. "\n" ..
"ebtables -t nat -A POSTROUTING -o bat0 -j DROP -s " .. anygw_mac .. "/" .. anygw_mac_mask .. "\n" ..
"# Filter IPv6 Router Solicitation\n" ..
"ebtables -t nat -D POSTROUTING -o bat0 --protocol ipv6 --ip6-protocol ipv6-icmp --ip6-icmp-type router-solicitation -j DROP\n" ..
"ebtables -t nat -A POSTROUTING -o bat0 --protocol ipv6 --ip6-protocol ipv6-icmp --ip6-icmp-type router-solicitation -j DROP\n" ..
"# Filter rogue IPv6 Router advertisement\n" ..
"ebtables -t nat -D POSTROUTING -o bat0 --protocol ipv6 --ip6-protocol ipv6-icmp --ip6-icmp-type router-advertisement -j DROP\n" ..
"ebtables -t nat -A POSTROUTING -o bat0 --protocol ipv6 --ip6-protocol ipv6-icmp --ip6-icmp-type router-advertisement -j DROP\n"
)
uci:set("dhcp", "lan", "ignore", "1")
uci:set("dhcp", owrtInterfaceName.."_dhcp", "dhcp")
uci:set("dhcp", owrtInterfaceName.."_dhcp", "interface", owrtInterfaceName)
anygw_dhcp_start = config.get("network", "anygw_dhcp_start")
uci:set("dhcp", owrtInterfaceName.."_dhcp", "start", anygw_dhcp_start)
anygw_dhcp_limit = config.get("network", "anygw_dhcp_limit")
if tonumber(anygw_dhcp_limit) > 0 then
uci:set("dhcp", owrtInterfaceName.."_dhcp", "limit", anygw_dhcp_limit)
else
uci:set("dhcp", owrtInterfaceName.."_dhcp", "limit", (2 ^ (32 - anygw_ipv4:prefix())) - anygw_dhcp_start - 1)
end
uci:set("dhcp", owrtInterfaceName.."_dhcp", "leasetime", "1h")
uci:set("dhcp", owrtInterfaceName.."_dhcp", "force", "1")
uci:set("dhcp", owrtInterfaceName, "tag")
uci:set("dhcp", owrtInterfaceName, "dhcp_option", { "option:mtu,"..anygw.SAFE_CLIENT_MTU } )
uci:set("dhcp", owrtInterfaceName, "force", "1")
uci:foreach("dhcp", "dnsmasq",
function(s)
uci:set("dhcp", s[".name"], "address", {
"/anygw/"..anygw_ipv4:host():string(),
"/anygw/"..anygw_ipv6:host():string(),
"/thisnode.info/"..anygw_ipv4:host():string(),
"/thisnode.info/"..anygw_ipv6:host():string(),
"/minodo.info/"..anygw_ipv4:host():string(),
"/minodo.info/"..anygw_ipv6:host():string()
})
end
)
uci:save("dhcp")
local cloudDomain = config.get("system", "domain")
local content = { }
table.insert(content, "enable-ra")
table.insert(content, "ra-param=anygw,mtu:"..anygw.SAFE_CLIENT_MTU..",120")
table.insert(content, "dhcp-range=tag:anygw,"..ipv6:network():string()..",ra-names,24h")
table.insert(content, "dhcp-option=tag:anygw,option6:domain-search,"..cloudDomain)
fs.writefile("/etc/dnsmasq.d/lime-proto-anygw-20-ipv6.conf", table.concat(content, "\n").."\n")
io.popen("/etc/init.d/dnsmasq enable || true"):close()
end
function anygw.setup_interface(ifname, args) end
function anygw.bgp_conf(templateVarsIPv4, templateVarsIPv6)
local base_conf = [[
protocol direct {
interface "anygw";
}
]]
return base_conf
end
return anygw
|
#!/usr/bin/lua
local fs = require("nixio.fs")
local network = require("lime.network")
local config = require("lime.config")
anygw = {}
anygw.configured = false
anygw.SAFE_CLIENT_MTU = 1350
function anygw.configure(args)
if anygw.configured then return end
anygw.configured = true
local ipv4, ipv6 = network.primary_address()
local anygw_mac = config.get("network", "anygw_mac")
anygw_mac = utils.applyNetTemplate16(anygw_mac)
--! bytes 4 & 5 vary depending on %N1 and %N2 by default
local anygw_mac_mask = "ff:ff:ff:00:00:00"
local anygw_ipv6 = ipv6:minhost()
local anygw_ipv4 = ipv4:minhost()
anygw_ipv6:prefix(64) -- SLAAC only works with a /64, per RFC
anygw_ipv4:prefix(ipv4:prefix())
local baseIfname = "br-lan"
local argsDev = { macaddr = anygw_mac }
local argsIf = { proto = "static" }
argsIf.ip6addr = anygw_ipv6:string()
argsIf.ipaddr = anygw_ipv4:host():string()
argsIf.netmask = anygw_ipv4:mask():string()
local owrtInterfaceName, _, _ = network.createMacvlanIface( baseIfname,
"anygw", argsDev, argsIf )
local uci = config.get_uci_cursor()
local pfr = network.limeIfNamePrefix.."anygw_"
uci:set("network", pfr.."rule6", "rule6")
uci:set("network", pfr.."rule6", "src", anygw_ipv6:host():string().."/128")
uci:set("network", pfr.."rule6", "lookup", "170") -- 0xaa in decimal
uci:set("network", pfr.."route6", "route6")
uci:set("network", pfr.."route6", "interface", owrtInterfaceName)
uci:set("network", pfr.."route6", "target", anygw_ipv6:network():string().."/"..anygw_ipv6:prefix())
uci:set("network", pfr.."route6", "table", "170")
uci:set("network", pfr.."rule4", "rule")
uci:set("network", pfr.."rule4", "src", anygw_ipv4:host():string().."/32")
uci:set("network", pfr.."rule4", "lookup", "170")
uci:set("network", pfr.."route4", "route")
uci:set("network", pfr.."route4", "interface", owrtInterfaceName)
uci:set("network", pfr.."route4", "target", anygw_ipv4:network():string())
uci:set("network", pfr.."route4", "netmask", anygw_ipv4:mask():string())
uci:set("network", pfr.."route4", "table", "170")
uci:save("network")
fs.mkdir("/etc/firewall.lime.d")
fs.writefile(
"/etc/firewall.lime.d/20-anygw-ebtables",
"\n" ..
"ebtables -D FORWARD -j DROP -d " .. anygw_mac .. "/" .. anygw_mac_mask .. "\n" ..
"ebtables -A FORWARD -j DROP -d " .. anygw_mac .. "/" .. anygw_mac_mask .. "\n" ..
"ebtables -t nat -D POSTROUTING -o bat0 -j DROP -s " .. anygw_mac .. "/" .. anygw_mac_mask .. "\n" ..
"ebtables -t nat -A POSTROUTING -o bat0 -j DROP -s " .. anygw_mac .. "/" .. anygw_mac_mask .. "\n" ..
"# Filter IPv6 Router Solicitation\n" ..
"ebtables -t nat -D POSTROUTING -o bat0 --protocol ipv6 --ip6-protocol ipv6-icmp --ip6-icmp-type router-solicitation -j DROP\n" ..
"ebtables -t nat -A POSTROUTING -o bat0 --protocol ipv6 --ip6-protocol ipv6-icmp --ip6-icmp-type router-solicitation -j DROP\n" ..
"# Filter rogue IPv6 Router advertisement\n" ..
"ebtables -t nat -D POSTROUTING -o bat0 --protocol ipv6 --ip6-protocol ipv6-icmp --ip6-icmp-type router-advertisement -j DROP\n" ..
"ebtables -t nat -A POSTROUTING -o bat0 --protocol ipv6 --ip6-protocol ipv6-icmp --ip6-icmp-type router-advertisement -j DROP\n"
)
uci:set("dhcp", "lan", "ignore", "1")
uci:set("dhcp", owrtInterfaceName.."_dhcp", "dhcp")
uci:set("dhcp", owrtInterfaceName.."_dhcp", "interface", owrtInterfaceName)
anygw_dhcp_start = config.get("network", "anygw_dhcp_start")
uci:set("dhcp", owrtInterfaceName.."_dhcp", "start", anygw_dhcp_start)
anygw_dhcp_limit = config.get("network", "anygw_dhcp_limit")
if tonumber(anygw_dhcp_limit) > 0 then
uci:set("dhcp", owrtInterfaceName.."_dhcp", "limit", anygw_dhcp_limit)
else
uci:set("dhcp", owrtInterfaceName.."_dhcp", "limit", (2 ^ (32 - anygw_ipv4:prefix())) - anygw_dhcp_start - 1)
end
uci:set("dhcp", owrtInterfaceName.."_dhcp", "leasetime", "1h")
uci:set("dhcp", owrtInterfaceName.."_dhcp", "force", "1")
uci:set("dhcp", owrtInterfaceName, "tag")
uci:set("dhcp", owrtInterfaceName, "dhcp_option", { "option:mtu,"..anygw.SAFE_CLIENT_MTU } )
uci:set("dhcp", owrtInterfaceName, "force", "1")
--! useing host-record to declare own DNS entries (and not dnsmasq address as it wildcards subdomains)
uci:set("dhcp", "anygw_dns", "hostrecord")
uci:set("dhcp", "anygw_dns", "name", {"anygw", "thisnode.info", "minodo.info"})
uci:set("dhcp", "anygw_dns", "ip", anygw_ipv4:host():string() .. "," .. anygw_ipv6:host():string())
uci:save("dhcp")
local cloudDomain = config.get("system", "domain")
local content = { }
table.insert(content, "enable-ra")
table.insert(content, "ra-param=anygw,mtu:"..anygw.SAFE_CLIENT_MTU..",120")
table.insert(content, "dhcp-range=tag:anygw,"..ipv6:network():string()..",ra-names,24h")
table.insert(content, "dhcp-option=tag:anygw,option6:domain-search,"..cloudDomain)
fs.writefile("/etc/dnsmasq.d/lime-proto-anygw-20-ipv6.conf", table.concat(content, "\n").."\n")
io.popen("/etc/init.d/dnsmasq enable || true"):close()
end
function anygw.setup_interface(ifname, args) end
function anygw.bgp_conf(templateVarsIPv4, templateVarsIPv6)
local base_conf = [[
protocol direct {
interface "anygw";
}
]]
return base_conf
end
return anygw
|
anygw: use dnsmasq host-record instead of address
|
anygw: use dnsmasq host-record instead of address
This fixes dnsmasq returning the anycast address when the dns query
is for a host if dnsmasq does not know about it. For example
pepe.thisnode.info was returning the anycast address if pepe was not
known by dnsmasq (or only the ipv4 was known and the ipv6 was
requested).
This is related to openwrt's:
dfea3bae11dd5c207182371ce1fdca763fb5bbe0
Author: Jo-Philipp Wich <jow@openwrt.org>
Date: Mon Jun 17 11:55:30 2013 +0000
dnsmasq: use host-record instead of address
Using "--address" for individual host A records is broken, use
"--host-record" instead.
|
Lua
|
agpl-3.0
|
libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages
|
94a383fb17871bc5842fa0893e771491cd162f79
|
libs/httpd/luasrc/httpd.lua
|
libs/httpd/luasrc/httpd.lua
|
--[[
HTTP server implementation for LuCI - core
(c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net>
(c) 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
module("luci.httpd", package.seeall)
require("socket")
THREAD_IDLEWAIT = 0.01
THREAD_TIMEOUT = 90
THREAD_LIMIT = nil
local reading = {}
local clhandler = {}
local erhandler = {}
local threadc = 0
local threads = {}
local threadm = {}
local threadi = {}
function Socket(ip, port)
local sock, err = socket.bind( ip, port )
if sock then
sock:settimeout( 0, "t" )
end
return sock, err
end
function corecv(socket, ...)
threadi[socket] = true
while true do
local chunk, err, part = socket:receive(...)
if err ~= "timeout" then
threadi[socket] = false
return chunk, err, part
end
coroutine.yield()
end
end
function cosend(socket, chunk, i, ...)
threadi[socket] = true
i = i or 1
while true do
local stat, err, sent = socket:send(chunk, i, ...)
if err ~= "timeout" then
threadi[socket] = false
return stat, err, sent
else
i = sent and (sent + 1) or i
end
coroutine.yield()
end
end
function register(socket, s_clhandler, s_errhandler)
table.insert(reading, socket)
clhandler[socket] = s_clhandler
erhandler[socket] = s_errhandler
end
function run()
while true do
step()
end
end
function step()
local idle = true
if not THREAD_LIMIT or threadc < THREAD_LIMIT then
local now = os.time()
for i, server in ipairs(reading) do
local client = server:accept()
if client then
threadm[client] = now
threadc = threadc + 1
threads[client] = coroutine.create(clhandler[server])
end
end
end
for client, thread in pairs(threads) do
coroutine.resume(thread, client)
local now = os.time()
if coroutine.status(thread) == "dead" then
threads[client] = nil
threadc = threadc - 1
elseif threadm[client] and threadm[client] + THREAD_TIMEOUT < now then
threads[client] = nil
threadc = threadc - 1
client:close()
elseif not threadi[client] then
threadm[client] = now
idle = false
end
end
if idle then
socket.sleep(THREAD_IDLEWAIT)
end
end
|
--[[
HTTP server implementation for LuCI - core
(c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net>
(c) 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
module("luci.httpd", package.seeall)
require("socket")
THREAD_IDLEWAIT = 0.01
THREAD_TIMEOUT = 90
THREAD_LIMIT = nil
local reading = {}
local clhandler = {}
local erhandler = {}
local threadc = 0
local threads = {}
local threadm = {}
local threadi = {}
function Socket(ip, port)
local sock, err = socket.bind( ip, port )
if sock then
sock:settimeout( 0, "t" )
end
return sock, err
end
function corecv(socket, ...)
threadi[socket] = true
while true do
local chunk, err, part = socket:receive(...)
if err ~= "timeout" then
threadi[socket] = false
return chunk, err, part
end
coroutine.yield()
end
end
function cosend(socket, chunk, i, ...)
threadi[socket] = true
i = i or 1
while true do
local stat, err, sent = socket:send(chunk, i, ...)
if err ~= "timeout" then
threadi[socket] = false
return stat, err, sent
else
i = sent and (sent + 1) or i
end
coroutine.yield()
end
end
function register(socket, s_clhandler, s_errhandler)
table.insert(reading, socket)
clhandler[socket] = s_clhandler
erhandler[socket] = s_errhandler
end
function run()
while true do
step()
end
end
function step()
local idle = true
if not THREAD_LIMIT or threadc < THREAD_LIMIT then
local now = os.time()
for i, server in ipairs(reading) do
local client = server:accept()
if client then
threadm[client] = now
threadc = threadc + 1
threads[client] = coroutine.create(clhandler[server])
end
end
end
for client, thread in pairs(threads) do
coroutine.resume(thread, client)
local now = os.time()
if coroutine.status(thread) == "dead" then
threads[client] = nil
threadc = threadc - 1
threadm[client] = nil
threadi[client] = nil
elseif threadm[client] and threadm[client] + THREAD_TIMEOUT < now then
threads[client] = nil
threadc = threadc - 1
client:close()
elseif not threadi[client] then
threadm[client] = now
idle = false
end
end
if idle then
socket.sleep(THREAD_IDLEWAIT)
end
end
|
* libs/httpd: Fixed a memleak
|
* libs/httpd: Fixed a memleak
git-svn-id: edf5ee79c2c7d29460bbb5b398f55862cc26620d@2488 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
dtaht/cerowrt-luci-3.3,Canaan-Creative/luci,ThingMesh/openwrt-luci,yeewang/openwrt-luci,projectbismark/luci-bismark,alxhh/piratenluci,ReclaimYourPrivacy/cloak-luci,ReclaimYourPrivacy/cloak-luci,8devices/carambola2-luci,Flexibity/luci,gwlim/luci,Canaan-Creative/luci,alxhh/piratenluci,Canaan-Creative/luci,Flexibity/luci,zwhfly/openwrt-luci,alxhh/piratenluci,stephank/luci,ThingMesh/openwrt-luci,Flexibity/luci,saraedum/luci-packages-old,phi-psi/luci,dtaht/cerowrt-luci-3.3,ch3n2k/luci,freifunk-gluon/luci,projectbismark/luci-bismark,jschmidlapp/luci,projectbismark/luci-bismark,eugenesan/openwrt-luci,gwlim/luci,zwhfly/openwrt-luci,alxhh/piratenluci,jschmidlapp/luci,ch3n2k/luci,vhpham80/luci,Canaan-Creative/luci,Canaan-Creative/luci,zwhfly/openwrt-luci,eugenesan/openwrt-luci,dtaht/cerowrt-luci-3.3,saraedum/luci-packages-old,zwhfly/openwrt-luci,stephank/luci,saraedum/luci-packages-old,yeewang/openwrt-luci,yeewang/openwrt-luci,freifunk-gluon/luci,saraedum/luci-packages-old,Flexibity/luci,Flexibity/luci,vhpham80/luci,saraedum/luci-packages-old,jschmidlapp/luci,phi-psi/luci,yeewang/openwrt-luci,8devices/carambola2-luci,freifunk-gluon/luci,ReclaimYourPrivacy/cloak-luci,8devices/carambola2-luci,ReclaimYourPrivacy/cloak-luci,gwlim/luci,phi-psi/luci,ThingMesh/openwrt-luci,yeewang/openwrt-luci,projectbismark/luci-bismark,zwhfly/openwrt-luci,gwlim/luci,vhpham80/luci,stephank/luci,projectbismark/luci-bismark,vhpham80/luci,ThingMesh/openwrt-luci,zwhfly/openwrt-luci,ch3n2k/luci,freifunk-gluon/luci,ReclaimYourPrivacy/cloak-luci,jschmidlapp/luci,8devices/carambola2-luci,vhpham80/luci,jschmidlapp/luci,alxhh/piratenluci,ch3n2k/luci,ThingMesh/openwrt-luci,vhpham80/luci,eugenesan/openwrt-luci,ch3n2k/luci,eugenesan/openwrt-luci,ReclaimYourPrivacy/cloak-luci,Canaan-Creative/luci,Flexibity/luci,gwlim/luci,saraedum/luci-packages-old,alxhh/piratenluci,projectbismark/luci-bismark,stephank/luci,dtaht/cerowrt-luci-3.3,gwlim/luci,zwhfly/openwrt-luci,ReclaimYourPrivacy/cloak-luci,jschmidlapp/luci,freifunk-gluon/luci,alxhh/piratenluci,jschmidlapp/luci,Canaan-Creative/luci,8devices/carambola2-luci,gwlim/luci,phi-psi/luci,dtaht/cerowrt-luci-3.3,saraedum/luci-packages-old,ThingMesh/openwrt-luci,ThingMesh/openwrt-luci,jschmidlapp/luci,ch3n2k/luci,8devices/carambola2-luci,phi-psi/luci,phi-psi/luci,zwhfly/openwrt-luci,Flexibity/luci,eugenesan/openwrt-luci,yeewang/openwrt-luci,freifunk-gluon/luci,eugenesan/openwrt-luci,freifunk-gluon/luci,Flexibity/luci,ch3n2k/luci,eugenesan/openwrt-luci,dtaht/cerowrt-luci-3.3,freifunk-gluon/luci,yeewang/openwrt-luci,projectbismark/luci-bismark,projectbismark/luci-bismark,ReclaimYourPrivacy/cloak-luci,8devices/carambola2-luci,stephank/luci,stephank/luci,phi-psi/luci,zwhfly/openwrt-luci,Canaan-Creative/luci
|
02e2b3bd478013bab88ca9c197fd6f981ce2f85e
|
profiles/car.lua
|
profiles/car.lua
|
-- Begin of globals
require("lib/access")
barrier_whitelist = { ["cattle_grid"] = true, ["border_control"] = true, ["toll_booth"] = true, ["sally_port"] = true, ["gate"] = true, ["no"] = true, ["entrance"] = true}
access_tag_whitelist = { ["yes"] = true, ["motorcar"] = true, ["motor_vehicle"] = true, ["vehicle"] = true, ["permissive"] = true, ["designated"] = true }
access_tag_blacklist = { ["no"] = true, ["private"] = true, ["agricultural"] = true, ["forestry"] = true, ["emergency"] = true }
access_tag_restricted = { ["destination"] = true, ["delivery"] = true }
access_tags = { "motorcar", "motor_vehicle", "vehicle" }
access_tags_hierachy = { "motorcar", "motor_vehicle", "vehicle", "access" }
service_tag_restricted = { ["parking_aisle"] = true }
ignore_in_grid = { ["ferry"] = true }
restriction_exception_tags = { "motorcar", "motor_vehicle", "vehicle" }
speed_profile = {
["motorway"] = 90,
["motorway_link"] = 75,
["trunk"] = 85,
["trunk_link"] = 70,
["primary"] = 65,
["primary_link"] = 60,
["secondary"] = 55,
["secondary_link"] = 50,
["tertiary"] = 40,
["tertiary_link"] = 30,
["unclassified"] = 25,
["residential"] = 25,
["living_street"] = 10,
["service"] = 15,
-- ["track"] = 5,
["ferry"] = 5,
["shuttle_train"] = 10,
["default"] = 10
}
take_minimum_of_speeds = false
obey_oneway = true
obey_bollards = true
use_restrictions = true
ignore_areas = true -- future feature
traffic_signal_penalty = 2
u_turn_penalty = 20
-- End of globals
function get_exceptions(vector)
for i,v in ipairs(restriction_exception_tags) do
vector:Add(v)
end
end
local function parse_maxspeed(source)
if source == nil then
return 0
end
local n = tonumber(source:match("%d*"))
if n == nil then
n = 0
end
if string.match(source, "mph") or string.match(source, "mp/h") then
n = (n*1609)/1000;
end
return math.abs(n)
end
function node_function (node)
local barrier = node.tags:Find("barrier")
local access = Access.find_access_tag(node, access_tags_hierachy)
local traffic_signal = node.tags:Find("highway")
--flag node if it carries a traffic light
if traffic_signal == "traffic_signals" then
node.traffic_light = true;
end
-- parse access and barrier tags
if access and access ~= "" then
if access_tag_blacklist[access] then
node.bollard = true
end
elseif barrier and barrier ~= "" then
if barrier_whitelist[barrier] then
return
else
node.bollard = true
end
end
end
function way_function (way)
-- we dont route over areas
local area = way.tags:Find("area")
if ignore_areas and ("yes" == area) then
return
end
-- check if oneway tag is unsupported
local oneway = way.tags:Find("oneway")
if "reversible" == oneway then
return
end
local impassable = way.tags:Find("impassable")
if "yes" == impassable then
return
end
local status = way.tags:Find("status")
if "impassable" == status then
return
end
-- Check if we are allowed to access the way
local access = Access.find_access_tag(way, access_tags_hierachy)
if access_tag_blacklist[access] then
return
end
-- Second, parse the way according to these properties
local highway = way.tags:Find("highway")
local name = way.tags:Find("name")
local ref = way.tags:Find("ref")
local junction = way.tags:Find("junction")
local route = way.tags:Find("route")
local maxspeed = parse_maxspeed(way.tags:Find ( "maxspeed") )
local maxspeed_forward = parse_maxspeed(way.tags:Find( "maxspeed:forward"))
local maxspeed_backward = parse_maxspeed(way.tags:Find( "maxspeed:backward"))
local barrier = way.tags:Find("barrier")
local cycleway = way.tags:Find("cycleway")
local duration = way.tags:Find("duration")
local service = way.tags:Find("service")
-- Set the name that will be used for instructions
if "" ~= ref then
way.name = ref
elseif "" ~= name then
way.name = name
-- else
-- way.name = highway -- if no name exists, use way type
end
if "roundabout" == junction then
way.roundabout = true;
end
-- Handling ferries and piers
if (speed_profile[route] ~= nil and speed_profile[route] > 0) then
if durationIsValid(duration) then
way.duration = math.max( parseDuration(duration), 1 );
end
way.direction = Way.bidirectional
if speed_profile[route] ~= nil then
highway = route;
end
if tonumber(way.duration) < 0 then
way.speed = speed_profile[highway]
end
end
-- Set the avg speed on the way if it is accessible by road class
if (speed_profile[highway] ~= nil and way.speed == -1 ) then
if maxspeed > speed_profile[highway] then
way.speed = maxspeed
else
if 0 == maxspeed then
maxspeed = math.huge
end
way.speed = math.min(speed_profile[highway], maxspeed)
end
end
-- Set the avg speed on ways that are marked accessible
if "" ~= highway and access_tag_whitelist[access] and way.speed == -1 then
if 0 == maxspeed then
maxspeed = math.huge
end
way.speed = math.min(speed_profile["default"], maxspeed)
end
-- Set access restriction flag if access is allowed under certain restrictions only
if access ~= "" and access_tag_restricted[access] then
way.is_access_restricted = true
end
-- Set access restriction flag if service is allowed under certain restrictions only
if service ~= "" and service_tag_restricted[service] then
way.is_access_restricted = true
end
-- Set direction according to tags on way
way.direction = Way.bidirectional
if obey_oneway then
if oneway == "-1" then
way.direction = Way.opposite
elseif oneway == "yes" or
oneway == "1" or
oneway == "true" or
junction == "roundabout" or
(highway == "motorway_link" and oneway ~="no") or
(highway == "motorway" and oneway ~= "no")
then
way.direction = Way.oneway
end
end
-- Override speed settings if explicit forward/backward maxspeeds are given
if way.speed > 0 and maxspeed_forward ~= nil and maxspeed_forward > 0 then
if Way.bidirectional == way.direction then
way.backward_speed = way.speed
end
way.speed = maxspeed_forward
end
if maxspeed_backward ~= nil and maxspeed_backward > 0 then
way.backward_speed = maxspeed_backward
end
-- Override general direction settings of there is a specific one for our mode of travel
if ignore_in_grid[highway] ~= nil and ignore_in_grid[highway] then
way.ignore_in_grid = true
end
way.type = 1
return
end
-- These are wrappers to parse vectors of nodes and ways and thus to speed up any tracing JIT
function node_vector_function(vector)
for v in vector.nodes do
node_function(v)
end
end
|
-- Begin of globals
--require("lib/access") --function temporarily inlined
barrier_whitelist = { ["cattle_grid"] = true, ["border_control"] = true, ["toll_booth"] = true, ["sally_port"] = true, ["gate"] = true, ["no"] = true, ["entrance"] = true}
access_tag_whitelist = { ["yes"] = true, ["motorcar"] = true, ["motor_vehicle"] = true, ["vehicle"] = true, ["permissive"] = true, ["designated"] = true }
access_tag_blacklist = { ["no"] = true, ["private"] = true, ["agricultural"] = true, ["forestry"] = true, ["emergency"] = true }
access_tag_restricted = { ["destination"] = true, ["delivery"] = true }
access_tags = { "motorcar", "motor_vehicle", "vehicle" }
access_tags_hierachy = { "motorcar", "motor_vehicle", "vehicle", "access" }
service_tag_restricted = { ["parking_aisle"] = true }
ignore_in_grid = { ["ferry"] = true }
restriction_exception_tags = { "motorcar", "motor_vehicle", "vehicle" }
speed_profile = {
["motorway"] = 90,
["motorway_link"] = 75,
["trunk"] = 85,
["trunk_link"] = 70,
["primary"] = 65,
["primary_link"] = 60,
["secondary"] = 55,
["secondary_link"] = 50,
["tertiary"] = 40,
["tertiary_link"] = 30,
["unclassified"] = 25,
["residential"] = 25,
["living_street"] = 10,
["service"] = 15,
-- ["track"] = 5,
["ferry"] = 5,
["shuttle_train"] = 10,
["default"] = 10
}
take_minimum_of_speeds = false
obey_oneway = true
obey_bollards = true
use_restrictions = true
ignore_areas = true -- future feature
traffic_signal_penalty = 2
u_turn_penalty = 20
-- End of globals
function find_access_tag(source,access_tags_hierachy)
for i,v in ipairs(access_tags_hierachy) do
local tag = source.tags:Find(v)
if tag ~= '' then
return tag
end
end
return nil
end
function get_exceptions(vector)
for i,v in ipairs(restriction_exception_tags) do
vector:Add(v)
end
end
local function parse_maxspeed(source)
if source == nil then
return 0
end
local n = tonumber(source:match("%d*"))
if n == nil then
n = 0
end
if string.match(source, "mph") or string.match(source, "mp/h") then
n = (n*1609)/1000;
end
return math.abs(n)
end
function node_function (node)
local barrier = node.tags:Find("barrier")
local access = find_access_tag(node, access_tags_hierachy)
local traffic_signal = node.tags:Find("highway")
--flag node if it carries a traffic light
if traffic_signal == "traffic_signals" then
node.traffic_light = true;
end
-- parse access and barrier tags
if access and access ~= "" then
if access_tag_blacklist[access] then
node.bollard = true
end
elseif barrier and barrier ~= "" then
if barrier_whitelist[barrier] then
return
else
node.bollard = true
end
end
end
function way_function (way)
-- we dont route over areas
local area = way.tags:Find("area")
if ignore_areas and ("yes" == area) then
return
end
-- check if oneway tag is unsupported
local oneway = way.tags:Find("oneway")
if "reversible" == oneway then
return
end
local impassable = way.tags:Find("impassable")
if "yes" == impassable then
return
end
local status = way.tags:Find("status")
if "impassable" == status then
return
end
-- Check if we are allowed to access the way
local access = find_access_tag(way, access_tags_hierachy)
if access_tag_blacklist[access] then
return
end
-- Second, parse the way according to these properties
local highway = way.tags:Find("highway")
local name = way.tags:Find("name")
local ref = way.tags:Find("ref")
local junction = way.tags:Find("junction")
local route = way.tags:Find("route")
local maxspeed = parse_maxspeed(way.tags:Find ( "maxspeed") )
local maxspeed_forward = parse_maxspeed(way.tags:Find( "maxspeed:forward"))
local maxspeed_backward = parse_maxspeed(way.tags:Find( "maxspeed:backward"))
local barrier = way.tags:Find("barrier")
local cycleway = way.tags:Find("cycleway")
local duration = way.tags:Find("duration")
local service = way.tags:Find("service")
-- Set the name that will be used for instructions
if "" ~= ref then
way.name = ref
elseif "" ~= name then
way.name = name
-- else
-- way.name = highway -- if no name exists, use way type
end
if "roundabout" == junction then
way.roundabout = true;
end
-- Handling ferries and piers
if (speed_profile[route] ~= nil and speed_profile[route] > 0) then
if durationIsValid(duration) then
way.duration = math.max( parseDuration(duration), 1 );
end
way.direction = Way.bidirectional
if speed_profile[route] ~= nil then
highway = route;
end
if tonumber(way.duration) < 0 then
way.speed = speed_profile[highway]
end
end
-- Set the avg speed on the way if it is accessible by road class
if (speed_profile[highway] ~= nil and way.speed == -1 ) then
if maxspeed > speed_profile[highway] then
way.speed = maxspeed
else
if 0 == maxspeed then
maxspeed = math.huge
end
way.speed = math.min(speed_profile[highway], maxspeed)
end
end
-- Set the avg speed on ways that are marked accessible
if "" ~= highway and access_tag_whitelist[access] and way.speed == -1 then
if 0 == maxspeed then
maxspeed = math.huge
end
way.speed = math.min(speed_profile["default"], maxspeed)
end
-- Set access restriction flag if access is allowed under certain restrictions only
if access ~= "" and access_tag_restricted[access] then
way.is_access_restricted = true
end
-- Set access restriction flag if service is allowed under certain restrictions only
if service ~= "" and service_tag_restricted[service] then
way.is_access_restricted = true
end
-- Set direction according to tags on way
way.direction = Way.bidirectional
if obey_oneway then
if oneway == "-1" then
way.direction = Way.opposite
elseif oneway == "yes" or
oneway == "1" or
oneway == "true" or
junction == "roundabout" or
(highway == "motorway_link" and oneway ~="no") or
(highway == "motorway" and oneway ~= "no")
then
way.direction = Way.oneway
end
end
-- Override speed settings if explicit forward/backward maxspeeds are given
if way.speed > 0 and maxspeed_forward ~= nil and maxspeed_forward > 0 then
if Way.bidirectional == way.direction then
way.backward_speed = way.speed
end
way.speed = maxspeed_forward
end
if maxspeed_backward ~= nil and maxspeed_backward > 0 then
way.backward_speed = maxspeed_backward
end
-- Override general direction settings of there is a specific one for our mode of travel
if ignore_in_grid[highway] ~= nil and ignore_in_grid[highway] then
way.ignore_in_grid = true
end
way.type = 1
return
end
-- These are wrappers to parse vectors of nodes and ways and thus to speed up any tracing JIT
function node_vector_function(vector)
for v in vector.nodes do
node_function(v)
end
end
|
temporarily fixes #811 plus 16 others
|
temporarily fixes #811 plus 16 others
|
Lua
|
bsd-2-clause
|
frodrigo/osrm-backend,atsuyim/osrm-backend,neilbu/osrm-backend,ammeurer/osrm-backend,prembasumatary/osrm-backend,oxidase/osrm-backend,atsuyim/osrm-backend,bjtaylor1/Project-OSRM-Old,stevevance/Project-OSRM,felixguendling/osrm-backend,Project-OSRM/osrm-backend,tkhaxton/osrm-backend,bjtaylor1/Project-OSRM-Old,ammeurer/osrm-backend,hydrays/osrm-backend,bjtaylor1/osrm-backend,alex85k/Project-OSRM,antoinegiret/osrm-geovelo,yuryleb/osrm-backend,agruss/osrm-backend,atsuyim/osrm-backend,bjtaylor1/osrm-backend,antoinegiret/osrm-geovelo,ramyaragupathy/osrm-backend,arnekaiser/osrm-backend,chaupow/osrm-backend,raymond0/osrm-backend,Project-OSRM/osrm-backend,bjtaylor1/osrm-backend,ammeurer/osrm-backend,yuryleb/osrm-backend,bitsteller/osrm-backend,bitsteller/osrm-backend,skyborla/osrm-backend,oxidase/osrm-backend,frodrigo/osrm-backend,ammeurer/osrm-backend,Carsten64/OSRM-aux-git,Tristramg/osrm-backend,chaupow/osrm-backend,Carsten64/OSRM-aux-git,ramyaragupathy/osrm-backend,jpizarrom/osrm-backend,stevevance/Project-OSRM,raymond0/osrm-backend,nagyistoce/osrm-backend,yuryleb/osrm-backend,beemogmbh/osrm-backend,Tristramg/osrm-backend,KnockSoftware/osrm-backend,arnekaiser/osrm-backend,jpizarrom/osrm-backend,raymond0/osrm-backend,felixguendling/osrm-backend,arnekaiser/osrm-backend,antoinegiret/osrm-backend,frodrigo/osrm-backend,Conggge/osrm-backend,Project-OSRM/osrm-backend,beemogmbh/osrm-backend,beemogmbh/osrm-backend,tkhaxton/osrm-backend,Carsten64/OSRM-aux-git,yuryleb/osrm-backend,hydrays/osrm-backend,agruss/osrm-backend,Project-OSRM/osrm-backend,tkhaxton/osrm-backend,oxidase/osrm-backend,deniskoronchik/osrm-backend,deniskoronchik/osrm-backend,KnockSoftware/osrm-backend,neilbu/osrm-backend,duizendnegen/osrm-backend,neilbu/osrm-backend,beemogmbh/osrm-backend,agruss/osrm-backend,ammeurer/osrm-backend,oxidase/osrm-backend,nagyistoce/osrm-backend,skyborla/osrm-backend,Carsten64/OSRM-aux-git,hydrays/osrm-backend,ammeurer/osrm-backend,prembasumatary/osrm-backend,alex85k/Project-OSRM,Conggge/osrm-backend,Conggge/osrm-backend,jpizarrom/osrm-backend,Conggge/osrm-backend,antoinegiret/osrm-backend,antoinegiret/osrm-backend,stevevance/Project-OSRM,neilbu/osrm-backend,arnekaiser/osrm-backend,Tristramg/osrm-backend,duizendnegen/osrm-backend,bitsteller/osrm-backend,bjtaylor1/Project-OSRM-Old,bjtaylor1/osrm-backend,raymond0/osrm-backend,antoinegiret/osrm-geovelo,deniskoronchik/osrm-backend,duizendnegen/osrm-backend,stevevance/Project-OSRM,deniskoronchik/osrm-backend,chaupow/osrm-backend,nagyistoce/osrm-backend,skyborla/osrm-backend,bjtaylor1/Project-OSRM-Old,alex85k/Project-OSRM,KnockSoftware/osrm-backend,KnockSoftware/osrm-backend,duizendnegen/osrm-backend,ramyaragupathy/osrm-backend,felixguendling/osrm-backend,ammeurer/osrm-backend,hydrays/osrm-backend,prembasumatary/osrm-backend,frodrigo/osrm-backend
|
f08e8c9f3caf50d6553bd7224407c629374d04aa
|
src/socket.lua
|
src/socket.lua
|
-- defined below
local close
-- metatable to allow garbage-collecting file descriptors
local fd_mt = {
__gc = function(wrapper)
close(wrapper.fd)
--print("GC: closed "..wrapper.fd)
end
}
local function wrapFd(fd)
return setmetatable({fd = fd}, fd_mt)
end
-- Functions to establish sockets
local socketPath = nil
function socket.getSocketPath()
if socketPath then
return socketPath
end
--TODO: base default off $HOME? or?
-- $HOME/.sema/control.socket ?
--error("No control socket path available; try setting either $SEMA_SOCKET or $HOME.")
socketPath = os.getenv("SEMA_SOCKET") or "./sema.socket"
socketPath = aux.absPath(socketPath)
return socketPath
end
local clientFd = nil
function socket.grabClientSocket()
if clientFd then
return clientFd
end
clientFd = wrapFd(socket.cGrabClientSocket(socket.getSocketPath()))
if clientFd then
poll.addFd(clientFd.fd, "read")
socket.buffers[clientFd.fd] = ""
end
return clientFd
end
local serverFd = nil
function socket.grabServerSocket()
if serverFd then
return serverFd
end
serverFd = wrapFd(socket.cGrabServerSocket(socket.getSocketPath()))
if serverFd then
poll.addFd(serverFd.fd, "read")
socket.buffers[serverFd.fd] = ""
aux.addExitHook(socket.serverShutdown)
end
return serverFd
end
--incompletely-received data
socket.buffers = {}
--to only be run from a blockable coroutine!
function socket.accept(wrappedServerFd)
local serverFd = wrappedServerFd.fd
queue.fdBlocked:waitOn(serverFd)
-- get connection fd
local clientFd = socket.cAccept(serverFd)
-- prepare to receive data from it
poll.addFd(clientFd, "read")
socket.buffers[clientFd] = ""
return wrapFd(clientFd)
end
function close(fd)
-- if type(fd) == "table" then
-- fd, fd.fd = fd.fd, nil
-- end
poll.dropFd(fd)
socket.buffers[fd] = nil
socket.cClose(fd)
end
-- message = list of strings, {"like", "this", "..."}
--[[ format for message encoding :
(lengths are unsigned 32-bit
big-endian integers)
=============================
content #bytes
------- -----
"sema" 4
version byte (0x00) 1
payload length 4
<end of 9-byte header>
first string length 4
first string ????
second string length 4
second string ????
...
last string length 4
last string ????
--]]
function socket.sendMessage(wrappedFd, message)
local fd = wrappedFd.fd
--format message body
local body = ""
for i=1,#message do
local arg = tostring(message[i])
body = body .. socket.formatNetworkInt(#arg) .. arg
end
--format message header
local header = "sema\x00" .. socket.formatNetworkInt(#body)
socket.cWrite(fd, header .. body);
end
local function readBlock(fd)
queue.fdBlocked:waitOn(fd)
local block = socket.cRead(fd)
if #block == 0 then
error "Connection closed before whole message received."
end
return block
end
--to only be run from a blockable coroutine!
--assumption: only one coroutine is reading at a time
--- (later fix: "buffer" -> "buffers[fd]" w/ bookkeeping in accept/close?
--- & then extract appropriate chunks)
function socket.receiveMessage(wrappedFd)
local fd = wrappedFd.fd
local buffers = socket.buffers
local readBytes = #buffers[fd]
--read message header
while readBytes < 9 do
local block = readBlock(fd)
buffers[fd] = buffers[fd] .. block
readBytes = readBytes + #block
end
if buffers[fd]:sub(1,5) ~= "sema\x00" then
error "Message was not a sema packet."
end
local messageLength = socket.readNetworkInt(buffers[fd]:sub(6,9))
--discard header and read message body
buffers[fd] = buffers[fd]:sub(10)
readBytes = #buffers[fd]
while readBytes < messageLength do
local block = readBlock(fd)
buffers[fd] = buffers[fd] .. block
readBytes = readBytes + #block
end
--split out the current message while keeping any spare data in the buffer
local messageBytes = buffers[fd]:sub(1,messageLength)
buffers[fd] = buffers[fd]:sub(messageLength + 1)
--parse message body
local message = {}
while #messageBytes >= 4 do
local argLength = socket.readNetworkInt(messageBytes:sub(1,4))
message[#message + 1] = messageBytes:sub(5, 4 + argLength)
messageBytes = messageBytes:sub(5 + argLength)
end
return message
end
-- prevent client from deleting a socket it created when spawning a server
function socket.detachServer()
serverFd = nil --triggers GC
end
-- on exit, clean up socket
function socket.serverShutdown()
if serverFd then
socket.cUnlink(socket.getSocketPath())
end
end
|
-- defined below
local close
-- metatable to allow garbage-collecting file descriptors
local fd_mt = {
__gc = function(wrapper)
close(wrapper.fd)
--print("GC: closed "..wrapper.fd)
end
}
local function wrapFd(fd)
-- propagate nil
if fd == nil then return nil end
return setmetatable({fd = fd}, fd_mt)
end
-- Functions to establish sockets
local socketPath = nil
function socket.getSocketPath()
if socketPath then
return socketPath
end
--TODO: base default off $HOME? or?
-- $HOME/.sema/control.socket ?
--error("No control socket path available; try setting either $SEMA_SOCKET or $HOME.")
socketPath = os.getenv("SEMA_SOCKET") or "./sema.socket"
socketPath = aux.absPath(socketPath)
return socketPath
end
local clientFd = nil
function socket.grabClientSocket()
if clientFd then
return clientFd
end
clientFd = wrapFd(socket.cGrabClientSocket(socket.getSocketPath()))
if clientFd then
poll.addFd(clientFd.fd, "read")
socket.buffers[clientFd.fd] = ""
end
return clientFd
end
local serverFd = nil
function socket.grabServerSocket()
if serverFd then
return serverFd
end
serverFd = wrapFd(socket.cGrabServerSocket(socket.getSocketPath()))
if serverFd then
poll.addFd(serverFd.fd, "read")
socket.buffers[serverFd.fd] = ""
aux.addExitHook(socket.serverShutdown)
end
return serverFd
end
--incompletely-received data
socket.buffers = {}
--to only be run from a blockable coroutine!
function socket.accept(wrappedServerFd)
local serverFd = wrappedServerFd.fd
queue.fdBlocked:waitOn(serverFd)
-- get connection fd
local clientFd = socket.cAccept(serverFd)
-- prepare to receive data from it
poll.addFd(clientFd, "read")
socket.buffers[clientFd] = ""
return wrapFd(clientFd)
end
function close(fd)
-- if type(fd) == "table" then
-- fd, fd.fd = fd.fd, nil
-- end
poll.dropFd(fd)
socket.buffers[fd] = nil
socket.cClose(fd)
end
-- message = list of strings, {"like", "this", "..."}
--[[ format for message encoding :
(lengths are unsigned 32-bit
big-endian integers)
=============================
content #bytes
------- -----
"sema" 4
version byte (0x00) 1
payload length 4
<end of 9-byte header>
first string length 4
first string ????
second string length 4
second string ????
...
last string length 4
last string ????
--]]
function socket.sendMessage(wrappedFd, message)
local fd = wrappedFd.fd
--format message body
local body = ""
for i=1,#message do
local arg = tostring(message[i])
body = body .. socket.formatNetworkInt(#arg) .. arg
end
--format message header
local header = "sema\x00" .. socket.formatNetworkInt(#body)
socket.cWrite(fd, header .. body);
end
local function readBlock(fd)
queue.fdBlocked:waitOn(fd)
local block = socket.cRead(fd)
if #block == 0 then
error "Connection closed before whole message received."
end
return block
end
--to only be run from a blockable coroutine!
--assumption: only one coroutine is reading at a time
--- (later fix: "buffer" -> "buffers[fd]" w/ bookkeeping in accept/close?
--- & then extract appropriate chunks)
function socket.receiveMessage(wrappedFd)
local fd = wrappedFd.fd
local buffers = socket.buffers
local readBytes = #buffers[fd]
--read message header
while readBytes < 9 do
local block = readBlock(fd)
buffers[fd] = buffers[fd] .. block
readBytes = readBytes + #block
end
if buffers[fd]:sub(1,5) ~= "sema\x00" then
error "Message was not a sema packet."
end
local messageLength = socket.readNetworkInt(buffers[fd]:sub(6,9))
--discard header and read message body
buffers[fd] = buffers[fd]:sub(10)
readBytes = #buffers[fd]
while readBytes < messageLength do
local block = readBlock(fd)
buffers[fd] = buffers[fd] .. block
readBytes = readBytes + #block
end
--split out the current message while keeping any spare data in the buffer
local messageBytes = buffers[fd]:sub(1,messageLength)
buffers[fd] = buffers[fd]:sub(messageLength + 1)
--parse message body
local message = {}
while #messageBytes >= 4 do
local argLength = socket.readNetworkInt(messageBytes:sub(1,4))
message[#message + 1] = messageBytes:sub(5, 4 + argLength)
messageBytes = messageBytes:sub(5 + argLength)
end
return message
end
-- prevent client from deleting a socket it created when spawning a server
function socket.detachServer()
serverFd = nil --triggers GC
end
-- on exit, clean up socket
function socket.serverShutdown()
if serverFd then
socket.cUnlink(socket.getSocketPath())
end
end
|
Fix regression where error-signaling nil fds got wrapped, masking their error status.
|
Fix regression where error-signaling nil fds got wrapped, masking
their error status.
|
Lua
|
mit
|
Tangent128/sema,Tangent128/sema,Tangent128/sema
|
14a22809ccfe733859808d1e0dc9cc08c59cac97
|
lexers/yaml.lua
|
lexers/yaml.lua
|
-- Copyright 2006-2015 Mitchell mitchell.att.foicica.com. See LICENSE.
-- YAML LPeg lexer.
-- It does not keep track of indentation perfectly.
local l = require('lexer')
local token, word_match = l.token, l.word_match
local P, R, S = lpeg.P, lpeg.R, lpeg.S
local M = {_NAME = 'yaml'}
-- Whitespace.
local indent = #l.starts_line(S(' \t')) *
(token(l.WHITESPACE, ' ') + token('indent_error', '\t'))^1
local ws = token(l.WHITESPACE, S(' \t')^1 + l.newline^1)
-- Comments.
local comment = token(l.COMMENT, '#' * l.nonnewline^0)
-- Strings.
local string = token(l.STRING, l.delimited_range("'") + l.delimited_range('"'))
-- Numbers.
local integer = l.dec_num + l.hex_num + '0' * S('oO') * R('07')^1
local special_num = '.' * word_match({'inf', 'nan'}, nil, true)
local number = token(l.NUMBER, special_num + l.float + integer)
-- Timestamps.
local ts = token('timestamp', l.digit * l.digit * l.digit * l.digit * -- year
'-' * l.digit * l.digit^-1 * -- month
'-' * l.digit * l.digit^-1 * -- day
((S(' \t')^1 + S('tT'))^-1 * -- separator
l.digit * l.digit^-1 * -- hour
':' * l.digit * l.digit * -- minute
':' * l.digit * l.digit * -- second
('.' * l.digit^0)^-1 * -- fraction
('Z' + -- timezone
S(' \t')^0 * S('-+') * l.digit * l.digit^-1 *
(':' * l.digit * l.digit)^-1)^-1)^-1)
-- Constants.
local constant = token(l.CONSTANT,
word_match({'null', 'true', 'false'}, nil, true))
-- Types.
local type = token(l.TYPE, '!!' * word_match({
-- Collection types.
'map', 'omap', 'pairs', 'set', 'seq',
-- Scalar types.
'binary', 'bool', 'float', 'int', 'merge', 'null', 'str', 'timestamp',
'value', 'yaml'
}, nil, true) + '!' * l.delimited_range('<>'))
-- Document boundaries.
local doc_bounds = token('document', l.starts_line(P('---') + '...'))
-- Directives
local directive = token('directive', l.starts_line('%') * l.nonnewline^1)
local word = (l.alpha + '-' * -l.space) * (l.alnum + '-')^0
-- Keys and literals.
local colon = S(' \t')^0 * ':' * (l.space + -1)
local key = token(l.KEYWORD, #word * (l.nonnewline - colon)^1 * #colon)
local value = #word * (l.nonnewline - l.space^0 * S(',]}'))^1
local block = S('|>') * S('+-')^-1 * (l.newline + -1) * function(input, index)
local rest = input:sub(index)
local level = #rest:match('^( *)')
for pos, indent, line in rest:gmatch('() *()([^\r\n]+)') do
if indent - pos < level and line ~= ' ' or level == 0 and pos > 1 then
return index + pos - 1
end
end
return #input + 1
end
local literal = token('literal', value + block)
-- Indicators.
local anchor = token(l.LABEL, '&' * word)
local alias = token(l.VARIABLE, '*' * word)
local tag = token('tag', '!' * word * P('!')^-1)
local reserved = token(l.ERROR, S('@`') * word)
local indicator_chars = token(l.OPERATOR, S('-?:,[]{}!'))
M._rules = {
{'indent', indent},
{'whitespace', ws},
{'comment', comment},
{'doc_bounds', doc_bounds},
{'key', key},
{'literal', literal},
{'timestamp', ts},
{'number', number},
{'constant', constant},
{'type', type},
{'indicator', tag + indicator_chars + alias + anchor + reserved},
{'directive', directive},
}
M._tokenstyles = {
indent_error = 'back:%(color.red)',
document = l.STYLE_CONSTANT,
literal = l.STYLE_DEFAULT,
timestamp = l.STYLE_NUMBER,
tag = l.STYLE_CLASS,
directive = l.STYLE_PREPROCESSOR,
}
M._FOLDBYINDENTATION = true
return M
|
-- Copyright 2006-2015 Mitchell mitchell.att.foicica.com. See LICENSE.
-- YAML LPeg lexer.
-- It does not keep track of indentation perfectly.
local l = require('lexer')
local token, word_match = l.token, l.word_match
local P, R, S = lpeg.P, lpeg.R, lpeg.S
local M = {_NAME = 'yaml'}
-- Whitespace.
local indent = #l.starts_line(S(' \t')) *
(token(l.WHITESPACE, ' ') + token('indent_error', '\t'))^1
local ws = token(l.WHITESPACE, S(' \t')^1 + l.newline^1)
-- Comments.
local comment = token(l.COMMENT, '#' * l.nonnewline^0)
-- Strings.
local string = token(l.STRING, l.delimited_range("'") + l.delimited_range('"'))
-- Numbers.
local integer = l.dec_num + l.hex_num + '0' * S('oO') * R('07')^1
local special_num = '.' * word_match({'inf', 'nan'}, nil, true)
local number = token(l.NUMBER, special_num + l.float + integer)
-- Timestamps.
local ts = token('timestamp', l.digit * l.digit * l.digit * l.digit * -- year
'-' * l.digit * l.digit^-1 * -- month
'-' * l.digit * l.digit^-1 * -- day
((S(' \t')^1 + S('tT'))^-1 * -- separator
l.digit * l.digit^-1 * -- hour
':' * l.digit * l.digit * -- minute
':' * l.digit * l.digit * -- second
('.' * l.digit^0)^-1 * -- fraction
('Z' + -- timezone
S(' \t')^0 * S('-+') * l.digit * l.digit^-1 *
(':' * l.digit * l.digit)^-1)^-1)^-1)
-- Constants.
local constant = token(l.CONSTANT,
word_match({'null', 'true', 'false'}, nil, true))
-- Types.
local type = token(l.TYPE, '!!' * word_match({
-- Collection types.
'map', 'omap', 'pairs', 'set', 'seq',
-- Scalar types.
'binary', 'bool', 'float', 'int', 'merge', 'null', 'str', 'timestamp',
'value', 'yaml'
}, nil, true) + '!' * l.delimited_range('<>'))
-- Document boundaries.
local doc_bounds = token('document', l.starts_line(P('---') + '...'))
-- Directives
local directive = token('directive', l.starts_line('%') * l.nonnewline^1)
local word = (l.alpha + '-' * -l.space) * (l.alnum + '-')^0
-- Keys and literals.
local colon = S(' \t')^0 * ':' * (l.space + -1)
local key = token(l.KEYWORD,
#word * (l.nonnewline - colon)^1 * #colon *
P(function(input, index)
local line = input:sub(1, index - 1):match('[^\r\n]+$')
return not line:find('[%w-]+:') and index
end))
local value = #word * (l.nonnewline - l.space^0 * S(',]}'))^1
local block = S('|>') * S('+-')^-1 * (l.newline + -1) * function(input, index)
local rest = input:sub(index)
local level = #rest:match('^( *)')
for pos, indent, line in rest:gmatch('() *()([^\r\n]+)') do
if indent - pos < level and line ~= ' ' or level == 0 and pos > 1 then
return index + pos - 1
end
end
return #input + 1
end
local literal = token('literal', value + block)
-- Indicators.
local anchor = token(l.LABEL, '&' * word)
local alias = token(l.VARIABLE, '*' * word)
local tag = token('tag', '!' * word * P('!')^-1)
local reserved = token(l.ERROR, S('@`') * word)
local indicator_chars = token(l.OPERATOR, S('-?:,[]{}!'))
M._rules = {
{'indent', indent},
{'whitespace', ws},
{'comment', comment},
{'doc_bounds', doc_bounds},
{'key', key},
{'literal', literal},
{'timestamp', ts},
{'number', number},
{'constant', constant},
{'type', type},
{'indicator', tag + indicator_chars + alias + anchor + reserved},
{'directive', directive},
}
M._tokenstyles = {
indent_error = 'back:%(color.red)',
document = l.STYLE_CONSTANT,
literal = l.STYLE_DEFAULT,
timestamp = l.STYLE_NUMBER,
tag = l.STYLE_CLASS,
directive = l.STYLE_PREPROCESSOR,
}
M._FOLDBYINDENTATION = true
return M
|
Fix multiple key highlighting on a single line; lexers/yaml.lua
|
Fix multiple key highlighting on a single line; lexers/yaml.lua
|
Lua
|
mit
|
rgieseke/scintillua
|
bd704da395775081b23f1dc79e213b3b69bfcec2
|
src/jet/daemon/radix.lua
|
src/jet/daemon/radix.lua
|
-- Implements a radix tree for the jet-daemon
local pairs = pairs
local next = next
local type = type
local tinsert = table.insert
local tremove = table.remove
local new = function()
local j = {}
-- the table that holds the radix_tree
local radix_tree = {}
-- elments that can be filled by several functions
-- and be returned as set of possible hits
local radix_elements = {}
-- internal tree instance or table of tree instances
-- used to hold parts of the tree that may be interesting afterwards
local return_tree = {}
-- this FSM is used for string comparison
-- can evaluate if the radix tree contains or ends with a specific string
local lookup_fsm = function (wordpart,next_state,next_letter)
if wordpart:sub(next_state,next_state) ~= next_letter then
if wordpart:sub(1,1) ~= next_letter then
return false,0
else
return false,1
end
end
if #wordpart == next_state then
return true,next_state
else
return false,next_state
end
end
-- evaluate if the radix tree starts with a specific string
-- returns pointer to subtree
local root_lookup
root_lookup = function(tree_instance,part)
if #part == 0 then
return_tree = tree_instance
else
local s = part:sub(1, 1)
if type(tree_instance[s]) == 'table' then
root_lookup(tree_instance[s], part:sub(2))
end
end
end
-- evaluate if the radix tree contains or ends with a specific string
-- returns list of pointers to subtrees
local leaf_lookup
leaf_lookup = function(tree_instance,word,state)
local next_state = state+1
for k,v in pairs(tree_instance) do
if type(v) == 'table' then
local hit,next_state = lookup_fsm(word,next_state,k)
if hit == true then
tinsert(return_tree,v)
else
leaf_lookup(v,word,next_state)
end
end
end
end
-- takes a single tree or a list of trees
-- traverses the trees and adds all elements to radix_elements
local radix_traverse
radix_traverse = function(tree_instance)
for k,v in pairs(tree_instance) do
if type(v) == 'boolean' then
radix_elements[k] = true
elseif type(v) == 'table' then
radix_traverse(v)
end
end
end
-- adds a new element to the tree
local add_to_tree
add_to_tree = function(tree_instance,fullword,part)
part = part or fullword
if #part == 0 then
tree_instance[fullword] = true
else
local s = part:sub(1,1)
if type(tree_instance[s]) ~= 'table' then
tree_instance[s] = {}
end
add_to_tree(tree_instance[s],fullword,part:sub(2))
end
end
-- removes an element from the tree
local remove_from_tree
remove_from_tree = function(tree_instance,fullword,part)
part = part or fullword
if #part == 0 then
tree_instance[fullword] = nil
else
local s = part:sub( 1, 1 )
if type(tree_instance[s]) ~= 'table' then
return
end
remove_from_tree(tree_instance[s],fullword,part:sub(2))
end
end
-- performs the respective actions for the parts of a fetcher
-- that can be handled by a radix tree
-- fills radix_elements with all hits that were found
local match_parts = function(tree_instance,parts)
radix_elements = {}
if parts['equals'] then
return_tree = {}
root_lookup(tree_instance,parts['equals'])
if type(return_tree[next(return_tree)]) == 'boolean' then
radix_elements[next(return_tree)] = true
end
else
local temp_tree = tree_instance
if parts['startsWith'] then
return_tree = {}
root_lookup(temp_tree,parts['startsWith'])
temp_tree = return_tree
end
if parts['contains'] then
return_tree = {}
leaf_lookup(temp_tree,parts['contains'],0)
temp_tree = return_tree
end
if parts['endsWith'] then
return_tree = {}
leaf_lookup(temp_tree,parts['endsWith'],0)
for k,t in pairs(return_tree) do
if type(t[next(t)]) ~= 'boolean' then
tremove(return_tree,k)
end
end
temp_tree = return_tree
end
if temp_tree then
radix_traverse(temp_tree)
end
end
end
-- evaluates if the fetch operation can be handled
-- completely or partially by the radix tree
-- returns elements from the radix_tree if it can be handled
-- and nil otherwise
local get_possible_matches = function(peer,params,fetch_id,is_case_insensitive)
local involves_path_match = params.path
local involves_value_match = params.value or params.valueField
local level = 'impossible'
local radix_expressions = {}
if involves_path_match and not is_case_insensitive then
for name,value in pairs(params.path) do
if name == 'equals' or name == 'startsWith' or name == 'endsWith' or name == 'contains' then
if radix_expressions[name] then
level = 'impossible'
break
end
radix_expressions[name] = value
if level == 'partial_pending' or involves_value_match then
level = 'partial'
elseif level ~= 'partial' then
level = 'all'
end
else
if level == 'easy' or level == 'partial' then
level = 'partial'
else
level = 'partial_pending'
end
end
end
if level == 'partial_pending' then
level = 'impossible'
end
end
if level ~= 'impossible' then
match_parts(radix_tree,radix_expressions)
return radix_elements
else
return nil
end
end
j.add = function(word)
add_to_tree(radix_tree,word)
end
j.remove = function(word)
remove_from_tree(radix_tree,word)
end
j.get_possible_matches = get_possible_matches
-- for unit testing
j.match_parts = function(parts)
match_parts(radix_tree,parts)
end
j.found_elements = function()
return radix_elements
end
return j
end
return {
new = new
}
|
-- Implements a radix tree for the jet-daemon
local pairs = pairs
local next = next
local tinsert = table.insert
local tremove = table.remove
local new = function()
local j = {}
-- the table that holds the radix_tree
j.radix_tree = {}
-- elments that can be filled by several functions
-- and be returned as set of possible hits
j.radix_elements = {}
-- internal tree instance or table of tree instances
-- used to hold parts of the tree that may be interesting afterwards
j.return_tree = {}
-- this FSM is used for string comparison
-- can evaluate if the radix tree contains or ends with a specific string
local lookup_fsm = function (wordpart,next_state,next_letter)
if wordpart:sub(next_state,next_state) ~= next_letter then
if wordpart:sub(1,1) ~= next_letter then
return false,0
else
return false,1
end
end
if #wordpart == next_state then
return true,next_state
else
return false,next_state
end
end
-- evaluate if the radix tree starts with a specific string
-- returns pointer to subtree
local root_lookup
root_lookup = function(tree_instance,part)
if #part == 0 then
j.return_tree = tree_instance
else
local s = part:sub(1,1)
if tree_instance[s] ~= true then
root_lookup(tree_instance[s], part:sub(2))
end
end
end
-- evaluate if the radix tree contains or ends with a specific string
-- returns list of pointers to subtrees
local leaf_lookup
leaf_lookup = function(tree_instance,word,state)
local next_state = state + 1
for k,v in pairs(tree_instance) do
if v ~= true then
local hit,next_state = lookup_fsm(word,next_state,k)
if hit == true then
tinsert(j.return_tree,v)
else
leaf_lookup(v,word,next_state)
end
end
end
end
-- takes a single tree or a list of trees
-- traverses the trees and adds all elements to j.radix_elements
local radix_traverse
radix_traverse = function(tree_instance)
for k,v in pairs(tree_instance) do
if v == true then
j.radix_elements[k] = true
elseif v ~= true then
radix_traverse(v)
end
end
end
-- adds a new element to the tree
local add_to_tree
add_to_tree = function(tree_instance,fullword,part)
part = part or fullword
if #part == 0 then
tree_instance[fullword] = true
else
local s = part:sub(1,1)
if tree_instance[s] == true or tree_instance[s] == nil then
tree_instance[s] = {}
end
add_to_tree(tree_instance[s],fullword,part:sub(2))
end
end
-- removes an element from the tree
local remove_from_tree
remove_from_tree = function(tree_instance,fullword,part)
part = part or fullword
if #part == 0 then
tree_instance[fullword] = nil
else
local s = part:sub(1,1)
if tree_instance[s] == true then
return
end
remove_from_tree(tree_instance[s],fullword,part:sub(2))
end
end
-- performs the respective actions for the parts of a fetcher
-- that can be handled by a radix tree
-- fills j.radix_elements with all hits that were found
local match_parts = function(tree_instance,parts)
j.radix_elements = {}
if parts['equals'] then
j.return_tree = {}
root_lookup(tree_instance,parts['equals'])
if j.return_tree[parts['equals']] == true then
j.radix_elements[parts['equals']] = true
end
else
local temp_tree = tree_instance
if parts['startsWith'] then
j.return_tree = {}
root_lookup(temp_tree,parts['startsWith'])
temp_tree = j.return_tree
end
if parts['contains'] then
j.return_tree = {}
leaf_lookup(temp_tree,parts['contains'],0)
temp_tree = j.return_tree
end
if parts['endsWith'] then
j.return_tree = {}
leaf_lookup(temp_tree,parts['endsWith'],0)
for k,t in pairs(j.return_tree) do
for _,v in pairs(t) do
if v ~= true then
j.return_tree[k] = nil
break
end
end
end
temp_tree = j.return_tree
end
if temp_tree then
radix_traverse(temp_tree)
end
end
end
-- evaluates if the fetch operation can be handled
-- completely or partially by the radix tree
-- returns elements from the j.radix_tree if it can be handled
-- and nil otherwise
local get_possible_matches = function(peer,params,fetch_id,is_case_insensitive)
local involves_path_match = params.path
local involves_value_match = params.value or params.valueField
local level = 'impossible'
local radix_expressions = {}
if involves_path_match and not is_case_insensitive then
for name,value in pairs(params.path) do
if name == 'equals' or name == 'startsWith' or name == 'endsWith' or name == 'contains' then
if radix_expressions[name] then
level = 'impossible'
break
end
radix_expressions[name] = value
if level == 'partial_pending' or involves_value_match then
level = 'partial'
elseif level ~= 'partial' then
level = 'all'
end
else
if level == 'easy' or level == 'partial' then
level = 'partial'
else
level = 'partial_pending'
end
end
end
if level == 'partial_pending' then
level = 'impossible'
end
end
if level ~= 'impossible' then
match_parts(j.radix_tree,radix_expressions)
return j.radix_elements
else
return nil
end
end
j.add = function(word)
add_to_tree(j.radix_tree,word)
end
j.remove = function(word)
remove_from_tree(j.radix_tree,word)
end
j.get_possible_matches = get_possible_matches
-- for unit testing
j.match_parts = function(parts,xxx)
match_parts(j.radix_tree,parts,xxx)
end
j.found_elements = function()
return j.radix_elements
end
return j
end
return {
new = new
}
|
fix usage of next. don't use expensive type comparisons.
|
fix usage of next. don't use expensive type comparisons.
|
Lua
|
mit
|
lipp/lua-jet
|
3c7097a8972ac5eaf58fe737a1c615ada1afb3d4
|
src/inputkeymaputils/src/Shared/ProximityPromptInputUtils.lua
|
src/inputkeymaputils/src/Shared/ProximityPromptInputUtils.lua
|
--[=[
Utility functions to configure a proximity prompt based upon the
input key map given.
@class ProximityPromptInputUtils
]=]
local require = require(script.Parent.loader).load(script)
local InputKeyMapList = require("InputKeyMapList")
local InputModeTypes = require("InputModeTypes")
local InputKeyMap = require("InputKeyMap")
local InputModeType = require("InputModeType")
local ProximityPromptInputUtils = {}
--[=[
Creates an InputKeyMapList from a proximity prompt.
@param prompt ProximityPrompt
@return InputKeyMapList
]=]
function ProximityPromptInputUtils.newInputKeyMapFromPrompt(prompt)
assert(typeof(prompt) == "Instance", "Bad prompt")
return InputKeyMapList.new("custom", {
InputKeyMap.new(InputModeTypes.Gamepads, { prompt.GamepadKeyCode });
InputKeyMap.new(InputModeTypes.Keyboard, { prompt.KeyboardKeyCode })
}, {
bindingName = prompt.ActionText;
rebindable = false;
})
end
--[=[
Sets the key codes for a proximity prompt to match an inputKeyMapList
@param prompt ProximityPrompt
@param inputKeyMapList InputKeyMapList
]=]
function ProximityPromptInputUtils.configurePromptFromInputKeyMap(prompt, inputKeyMapList)
assert(typeof(prompt) == "Instance", "Bad prompt")
assert(type(inputKeyMapList) == "table", "Bad inputKeyMapList")
local keyboard = ProximityPromptInputUtils.getFirstInputKeyCode(inputKeyMapList, InputModeTypes.Keyboard)
local gamepad = ProximityPromptInputUtils.getFirstInputKeyCode(inputKeyMapList, InputModeTypes.Gamepads)
if keyboard then
prompt.KeyboardKeyCode = keyboard
end
if gamepad then
prompt.GamepadKeyCode = gamepad
end
end
--[=[
Picks the first keyCode that matches the inputModeType.
@param inputKeyMapList InputKeyMapList
@param inputModeType InputModeType
@return KeyCode?
]=]
function ProximityPromptInputUtils.getFirstInputKeyCode(inputKeyMapList, inputModeType)
assert(type(inputKeyMapList) == "table", "Bad inputKeyMapList")
assert(InputModeType.isInputModeType(inputModeType), "Bad inputModeType")
for _, item in pairs(inputKeyMapList) do
for _, entry in pairs(item.inputTypes) do
if typeof(entry) == "EnumItem"
and entry.EnumType == Enum.KeyCode
and inputModeType:IsValid(entry) then
return entry
end
end
end
return nil
end
return ProximityPromptInputUtils
|
--[=[
Utility functions to configure a proximity prompt based upon the
input key map given.
@class ProximityPromptInputUtils
]=]
local require = require(script.Parent.loader).load(script)
local InputKeyMapList = require("InputKeyMapList")
local InputModeTypes = require("InputModeTypes")
local InputKeyMap = require("InputKeyMap")
local InputModeType = require("InputModeType")
local ProximityPromptInputUtils = {}
--[=[
Creates an InputKeyMapList from a proximity prompt.
@param prompt ProximityPrompt
@return InputKeyMapList
]=]
function ProximityPromptInputUtils.newInputKeyMapFromPrompt(prompt)
assert(typeof(prompt) == "Instance", "Bad prompt")
return InputKeyMapList.new("custom", {
InputKeyMap.new(InputModeTypes.Gamepads, { prompt.GamepadKeyCode });
InputKeyMap.new(InputModeTypes.Keyboard, { prompt.KeyboardKeyCode });
InputKeyMap.new(InputModeTypes.Touch, { "Tap" });
}, {
bindingName = prompt.ActionText;
rebindable = false;
})
end
--[=[
Sets the key codes for a proximity prompt to match an inputKeyMapList
@param prompt ProximityPrompt
@param inputKeyMapList InputKeyMapList
]=]
function ProximityPromptInputUtils.configurePromptFromInputKeyMap(prompt, inputKeyMapList)
assert(typeof(prompt) == "Instance", "Bad prompt")
assert(type(inputKeyMapList) == "table", "Bad inputKeyMapList")
local keyboard = ProximityPromptInputUtils.getFirstInputKeyCode(inputKeyMapList, InputModeTypes.Keyboard)
local gamepad = ProximityPromptInputUtils.getFirstInputKeyCode(inputKeyMapList, InputModeTypes.Gamepads)
if keyboard then
prompt.KeyboardKeyCode = keyboard
end
if gamepad then
prompt.GamepadKeyCode = gamepad
end
end
--[=[
Picks the first keyCode that matches the inputModeType.
@param inputKeyMapList InputKeyMapList
@param inputModeType InputModeType
@return KeyCode?
]=]
function ProximityPromptInputUtils.getFirstInputKeyCode(inputKeyMapList, inputModeType)
assert(type(inputKeyMapList) == "table", "Bad inputKeyMapList")
assert(InputModeType.isInputModeType(inputModeType), "Bad inputModeType")
for _, item in pairs(inputKeyMapList) do
for _, entry in pairs(item.inputTypes) do
if typeof(entry) == "EnumItem"
and entry.EnumType == Enum.KeyCode
and inputModeType:IsValid(entry) then
return entry
end
end
end
return nil
end
return ProximityPromptInputUtils
|
fix: Proximity prompt has tap in the custom input prompt too
|
fix: Proximity prompt has tap in the custom input prompt too
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
11fb712fe116554a746fa700768b2e510e164501
|
test/bench/memtier.test.lua
|
test/bench/memtier.test.lua
|
#!/usr/bin/env tarantool
local tap = require('tap')
local fio = require('fio')
local has_popen, popen = pcall(require, 'popen')
package.cpath = './?.so;' .. package.cpath
local memcached = require('memcached')
local test = tap.test('memcached benchmarks')
if not has_popen then
test:plan(0)
os.exit(0)
end
test:plan(3)
local is_test_run = os.getenv('LISTEN')
if type(box.cfg) == 'function' then
box.cfg{
wal_mode = 'none',
memtx_memory = 100 * 1024 * 1024,
}
box.schema.user.grant('guest', 'read,write,execute', 'universe')
end
local port = 11211
local mc = memcached.create('memcached', tostring(port), {})
local function run_memtier(instance, memtier_path, proto)
instance:cfg({
protocol = proto,
})
local memtier_proto = 'memcache_' .. proto
local memtier_argv = {
memtier_path,
'--server=127.0.0.1',
string.format('--port=%d', port),
string.format('--protocol=%s', memtier_proto),
'--threads=10',
'--test-time=2',
'--hide-histogram'
}
local stdout = is_test_run and popen.opts.PIPE or popen.opts.INHERIT
local stderr = is_test_run and popen.opts.PIPE or popen.opts.INHERIT
local ph = popen.new(memtier_argv, {
stdout = stdout,
stderr = stderr,
})
local res = ph:wait()
ph:close()
return res.exit_code
end
-- path to memtier_benchmark in case of tarantool that run in project root dir
local memtier_path = 'test/bench/memtier_benchmark'
if not fio.path.exists(memtier_path) then
-- path to memtier_benchmark in case of test-run
memtier_path = './memtier_benchmark'
end
test:is(fio.path.exists(memtier_path), true, 'memtier_benchmark binary is available')
test:is(run_memtier(mc, memtier_path, 'text'), 0, 'memtier with text protocol')
test:is(run_memtier(mc, memtier_path, 'binary'), 0, 'memtier with binary protocol')
os.exit(0)
|
#!/usr/bin/env tarantool
local tap = require('tap')
local fio = require('fio')
local has_popen, popen = pcall(require, 'popen')
package.cpath = './?.so;' .. package.cpath
local memcached = require('memcached')
local test = tap.test('memcached benchmarks')
if not has_popen then
test:plan(0)
os.exit(0)
end
test:plan(3)
local is_test_run = os.getenv('LISTEN')
if type(box.cfg) == 'function' then
box.cfg{
wal_mode = 'none',
memtx_memory = 100 * 1024 * 1024,
}
box.schema.user.grant('guest', 'read,write,execute', 'universe')
end
local port = 11211
local mc = memcached.create('memcached', tostring(port), {})
local function run_memtier(instance, memtier_path, proto)
instance:cfg({
protocol = proto,
})
local memtier_proto = 'memcache_' .. proto
local memtier_argv = {
memtier_path,
'--server=127.0.0.1',
string.format('--port=%d', port),
string.format('--protocol=%s', memtier_proto),
'--threads=10',
'--test-time=2',
'--hide-histogram'
}
local stdout = is_test_run and popen.opts.DEVNULL or popen.opts.INHERIT
local stderr = is_test_run and popen.opts.DEVNULL or popen.opts.INHERIT
local ph = popen.new(memtier_argv, {
stdout = stdout,
stderr = stderr,
})
local res = ph:wait()
ph:close()
return res.exit_code
end
-- path to memtier_benchmark in case of tarantool that run in project root dir
local memtier_path = 'test/bench/memtier_benchmark'
if not fio.path.exists(memtier_path) then
-- path to memtier_benchmark in case of test-run
memtier_path = './memtier_benchmark'
end
test:is(fio.path.exists(memtier_path), true, 'memtier_benchmark binary is available')
test:is(run_memtier(mc, memtier_path, 'text'), 0, 'memtier with text protocol')
test:is(run_memtier(mc, memtier_path, 'binary'), 0, 'memtier with binary protocol')
os.exit(test:check() and 0 or 1)
|
test: fixes for memtier benchmark wrapper
|
test: fixes for memtier benchmark wrapper
Suppress output with DEVNULL instead of PIPE when test-run is used for
running benchmark and reflect test run status in exit code.
Follows up #81
|
Lua
|
bsd-2-clause
|
tarantool/memcached,tarantool/memcached
|
839f5643e92f5c8f5624359c668cb68bcf012180
|
test_scripts/Polices/build_options/ATF_P_Check_STATUS_vai_USER_Request.lua
|
test_scripts/Polices/build_options/ATF_P_Check_STATUS_vai_USER_Request.lua
|
---------------------------------------------------------------------------------------------
-- Requirements summary:
-- [PolicyTableUpdate] OnStatusUpdate(UPDATE_NEEDED) on new PTU request
--
-- Note: copy PTUfilename - ptu.json on this way /tmp/fs/mp/images/ivsu_cache/
-- Description:
-- SDL should request PTU in case new application is registered and is not listed in PT
-- 1. Used preconditions
-- SDL is built with "-DEXTENDED_POLICY: PROPRIETARY" flag
-- Connect mobile phone over WiFi.
-- 2. Performed steps
-- Register new application
-- Send user request SDL.UpdateSDL
--
-- Expected result:
-- PTU is requested. PTS is created.
-- SDL->HMI: SDL.OnStatusUpdate(UPDATING)
-- SDL->HMI: BasicCommunication.PolicyUpdate
-------------------------------------------------------------------------------------------
--[[ General configuration parameters ]]
config.defaultProtocolVersion = 2
config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0"
--[[ Required Shared libraries ]]
local commonFunctions = require ('user_modules/shared_testcases/commonFunctions')
local commonSteps = require('user_modules/shared_testcases/commonSteps')
local commonPreconditions = require('user_modules/shared_testcases/commonPreconditions')
--[[ Local Variables ]]
--NewTestSuiteNumber = 0
--[[ General Precondition before ATF start]]
commonSteps:DeleteLogsFileAndPolicyTable()
--[[ General Settings for configuration ]]
Test = require('connecttest')
require('user_modules/AppTypes')
--[[ Local Functions ]]
local function policyUpdate(self)
local pathToSnaphot = "/tmp/fs/mp/images/ivsu_cache/ptu.json"
local RequestIdGetURLS = self.hmiConnection:SendRequest("SDL.GetURLS", { service = 7 })
EXPECT_HMIRESPONSE(RequestIdGetURLS)
:Do(function(_,_)
self.hmiConnection:SendNotification("BasicCommunication.OnSystemRequest",
{
requestType = "PROPRIETARY",
appID = self.applications ["Test Application"],
fileName = "PTU"
}
)
end)
EXPECT_NOTIFICATION("OnSystemRequest", {requestType = "PROPRIETARY" })
:Do(function(_,_)
local CorIdSystemRequest = self.mobileSession:SendRPC ("SystemRequest",
{
requestType = "PROPRIETARY",
fileName = "PTU"
},
pathToSnaphot
)
EXPECT_HMICALL("BasicCommunication.SystemRequest")
:Do(function(_,data)
self.hmiConnection:SendResponse(data.id,"BasicCommunication.SystemRequest", "SUCCESS", {})
end)
EXPECT_RESPONSE(CorIdSystemRequest, {success = true, resultCode = "SUCCESS"})
:Do(function(_,_)
self.hmiConnection:SendNotification("SDL.OnReceivedPolicyUpdate",
{
policyfile = "/tmp/fs/mp/images/ivsu_cache/PTU"
})
end)
:Do(function(_,_)
EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {status = "UP_TO_DATE"})
end)
end)
end
-- [[ Preconditions ]]
commonFunctions:newTestCasesGroup("Preconditions")
function Test:Preconditions_ActivateApplication()
local RequestId = self.hmiConnection:SendRequest("SDL.ActivateApp", {appID = self.applications["Test Application"]})
EXPECT_HMIRESPONSE(RequestId)
:Do(function(_,data)
if data.result.isSDLAllowed ~= true then
RequestId = self.hmiConnection:SendRequest("SDL.GetUserFriendlyMessage", {language = "EN-US", messageCodes = {"DataConsent"}})
EXPECT_HMIRESPONSE(RequestId)
:Do(function(_,_)
self.hmiConnection:SendNotification("SDL.OnAllowSDLFunctionality", {allowed = true, source = "GUI", device = {id = config.deviceMAC, name = "127.0.0.1"}})
EXPECT_HMICALL("BasicCommunication.ActivateApp")
:Do(function(_,_)
self.hmiConnection:SendResponse(data.id,"BasicCommunication.ActivateApp", "SUCCESS", {})
end)
:Times(2)
end)
end
end)
EXPECT_NOTIFICATION("OnHMIStatus", {hmiLevel = "FULL", audioStreamingState = "AUDIBLE", systemContext = "MAIN"})
end
function Test:Preconditions_MoveSystem_UP_TO_DATE()
policyUpdate(self)
end
--[[ Test ]]
commonFunctions:newTestCasesGroup ("Test")
function Test:TestStep_Check_User_Request_UpdateSDL()
local RequestIdUpdateSDL = self.hmiConnection:SendRequest("SDL.UpdateSDL")
EXPECT_HMIRESPONSE(RequestIdUpdateSDL,{result = {code = 0, method = "SDL.UpdateSDL", result = "UPDATING" }})
end
--[[ Postconditions ]]
commonFunctions:newTestCasesGroup("Postconditions")
function Test.Postcondition_SDLStop()
StopSDL()
end
|
---------------------------------------------------------------------------------------------
-- Requirements summary:
-- [PolicyTableUpdate] OnStatusUpdate(UPDATE_NEEDED) on new PTU request
--
-- Note: copy PTUfilename - ptu.json on this way /tmp/fs/mp/images/ivsu_cache/
-- Description:
-- SDL should request PTU in case new application is registered and is not listed in PT
-- 1. Used preconditions
-- SDL is built with "-DEXTENDED_POLICY: PROPRIETARY" flag
-- Connect mobile phone over WiFi.
-- 2. Performed steps
-- Register new application
-- Send user request SDL.UpdateSDL
--
-- Expected result:
-- PTU is requested. PTS is created.
-- SDL->HMI: SDL.OnStatusUpdate(UPDATING)
-- SDL->HMI: BasicCommunication.PolicyUpdate
-------------------------------------------------------------------------------------------
--[[ General configuration parameters ]]
config.defaultProtocolVersion = 2
config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0"
--[[ Required Shared libraries ]]
local commonFunctions = require ('user_modules/shared_testcases/commonFunctions')
local commonSteps = require('user_modules/shared_testcases/commonSteps')
--[[ Local Variables ]]
--NewTestSuiteNumber = 0
--[[ General Precondition before ATF start]]
commonSteps:DeleteLogsFileAndPolicyTable()
--[[ General Settings for configuration ]]
Test = require('connecttest')
require('user_modules/AppTypes')
--[[ Local Functions ]]
local function policyUpdate(self)
local pathToSnaphot = "files/ptu.json"
local RequestIdGetURLS = self.hmiConnection:SendRequest("SDL.GetURLS", { service = 7 })
EXPECT_HMIRESPONSE(RequestIdGetURLS)
:Do(function(_,_)
self.hmiConnection:SendNotification("BasicCommunication.OnSystemRequest",
{
requestType = "PROPRIETARY",
appID = self.applications ["Test Application"],
fileName = "PTU"
}
)
end)
EXPECT_NOTIFICATION("OnSystemRequest", {requestType = "PROPRIETARY" })
:Do(function(_,_)
local CorIdSystemRequest = self.mobileSession:SendRPC ("SystemRequest",
{
requestType = "PROPRIETARY",
fileName = "PTU"
},
pathToSnaphot
)
EXPECT_HMICALL("BasicCommunication.SystemRequest")
:Do(function(_,data)
self.hmiConnection:SendResponse(data.id,"BasicCommunication.SystemRequest", "SUCCESS", {})
end)
EXPECT_RESPONSE(CorIdSystemRequest, {success = true, resultCode = "SUCCESS"})
:Do(function(_,_)
self.hmiConnection:SendNotification("SDL.OnReceivedPolicyUpdate",
{
policyfile = "/tmp/fs/mp/images/ivsu_cache/PTU"
})
end)
:Do(function(_,_)
EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {status = "UP_TO_DATE"})
end)
end)
end
-- [[ Preconditions ]]
commonFunctions:newTestCasesGroup("Preconditions")
function Test:Preconditions_ActivateApplication()
local RequestId = self.hmiConnection:SendRequest("SDL.ActivateApp", {appID = self.applications["Test Application"]})
EXPECT_HMIRESPONSE(RequestId)
:Do(function(_,data)
if data.result.isSDLAllowed ~= true then
RequestId = self.hmiConnection:SendRequest("SDL.GetUserFriendlyMessage", {language = "EN-US", messageCodes = {"DataConsent"}})
EXPECT_HMIRESPONSE(RequestId)
:Do(function(_,_)
self.hmiConnection:SendNotification("SDL.OnAllowSDLFunctionality", {allowed = true, source = "GUI", device = {id = config.deviceMAC, name = "127.0.0.1"}})
EXPECT_HMICALL("BasicCommunication.ActivateApp")
:Do(function(_,_)
self.hmiConnection:SendResponse(data.id,"BasicCommunication.ActivateApp", "SUCCESS", {})
end)
:Times(2)
end)
end
end)
EXPECT_NOTIFICATION("OnHMIStatus", {hmiLevel = "FULL", audioStreamingState = "AUDIBLE", systemContext = "MAIN"})
end
function Test:Preconditions_MoveSystem_UP_TO_DATE()
policyUpdate(self)
end
--[[ Test ]]
commonFunctions:newTestCasesGroup ("Test")
function Test:TestStep_Check_User_Request_UpdateSDL()
local RequestIdUpdateSDL = self.hmiConnection:SendRequest("SDL.UpdateSDL")
EXPECT_HMIRESPONSE(RequestIdUpdateSDL,{result = {code = 0, method = "SDL.UpdateSDL", result = "UPDATING" }})
end
--[[ Postconditions ]]
commonFunctions:newTestCasesGroup("Postconditions")
function Test.Postcondition_SDLStop()
StopSDL()
end
|
Fix issues
|
Fix issues
|
Lua
|
bsd-3-clause
|
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
|
1000d76a79472044a063b59003c730fda9c72209
|
packages/shared-state/files/usr/lib/lua/shared-state.lua
|
packages/shared-state/files/usr/lib/lua/shared-state.lua
|
#!/usr/bin/lua
--! Minimalistic CRDT-like shared state structure suitable for mesh networks
--!
--! Copyright (C) 2019 Gioacchino Mazzurco <gio@altermundi.net>
--!
--! This program is free software: you can redistribute it and/or modify
--! it under the terms of the GNU Affero General Public License version 3 as
--! published by the Free Software Foundation.
--!
--! This program is distributed in the hope that it will be useful,
--! but WITHOUT ANY WARRANTY; without even the implied warranty of
--! MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
--! GNU Affero General Public License for more details.
--!
--! You should have received a copy of the GNU Affero General Public License
--! along with this program. If not, see <http://www.gnu.org/licenses/>.
local fs = require("nixio.fs")
local http = require("luci.httpclient")
local JSON = require("luci.jsonc")
local nixio = require("nixio")
local uci = require("uci")
local function SharedState(dataType, pLogger)
--! Name of the CRDT is mandatory
if type(dataType) ~= "string" or dataType:len() < 1 then return nil end
--! Map<Key, {bleachTTL, author, data}>
--! bleachTTL is the count of how much bleaching should occur before the
--! entry expires
--! author is the name of the host who generated that entry
--! data is the value of the entry
local self_storage = {}
--! File descriptor of the persistent file storage
local self_storageFD = nil
--! true if self_storage has changed after loading
local self_changed = false
local self_dataDir = "/var/shared-state/data/"
local self_dataFile = "/var/shared-state/data/"..dataType..".json"
local self_hooksDir = "/etc/shared-state/hooks/"..dataType.."/"
--! true when persistent storage file is locked by this instance
local self_locked = false
local self_log = function (level, message)
end
if type(logger) == "function" then self_log = logger end
local sharedState = {}
--! Returns true it at least one entry expired, false otherwise
function sharedState.bleach()
local substancialChange = false
for k,v in pairs(self_storage) do
if(v.bleachTTL < 2) then
self_storage[k] = nil
substancialChange = true
else
v.bleachTTL = v.bleachTTL-1
end
self_changed = true
end
return substancialChange
end
function sharedState.insert(key, data, bleachTTL)
bleachTTL = bleachTTL or 30
self_storage[key] = {
bleachTTL=bleachTTL,
author=io.input("/proc/sys/kernel/hostname"):read("*line"),
data=data
}
self_changed = true
end
function sharedState.load()
sharedState.merge(JSON.parse(self_storageFD:readall()), false)
end
function sharedState.lock(maxwait)
if self_locked then return end
maxwait = maxwait or 10
fs.mkdirr(self_dataDir)
self_storageFD = nixio.open(
self_dataFile, nixio.open_flags("rdwr", "creat") )
for i=1,maxwait do
if not self_storageFD:lock("tlock") then
nixio.nanosleep(1)
else
self_locked = true
break
end
end
if not self_locked then
self_log( "err",
arg[0], arg[1], arg[2], "Failed acquiring lock on data!" )
os.exit(-165)
end
end
function sharedState.merge(stateSlice, notifyInsert)
local stateSlice = stateSlice or {}
if(notifyInsert == nil) then notifyInsert = true end
for key,rv in pairs(stateSlice) do
if rv.bleachTTL <= 0 then
self_log( "debug", "sharedState.merge got expired entry" )
self_changed = true
else
local lv = self_storage[key]
if( lv == nil ) then
self_storage[key] = rv
self_changed = self_changed or notifyInsert
elseif ( lv.bleachTTL < rv.bleachTTL ) then
self_log( "debug", "Updating entry for: "..key.." older: "..
lv.bleachTTL.." newer: "..rv.bleachTTL )
self_storage[key] = rv
self_changed = self_changed or notifyInsert
end
end
end
end
function sharedState.notifyHooks()
if self_changed then
local jsonString = sharedState.toJsonString()
for hook in fs.dir(self_hooksDir) do
local cStdin = io.popen(self_hooksDir.."/"..hook, "w")
cStdin:write(jsonString)
cStdin:close()
end
end
end
function sharedState.remove(key)
if(self_storage[key] ~= nil and self_storage[key].data ~= nil)
then sharedState.insert(key, nil) end
end
function sharedState.save()
if self_changed then
local outFd = io.open(self_dataFile, "w")
outFd:write(sharedState.toJsonString())
outFd:close()
outFd = nil
end
end
function sharedState.sync(urls)
urls = urls or {}
if #urls < 1 then
local uci_cursor = uci:cursor()
local fixed_candidates =
uci_cursor:get("shared-state", "options","candidates") or {}
for _, line in pairs(fixed_candidates) do
table.insert(
urls,
line.."/"..dataType )
end
io.input(io.popen(arg[0].."-get_candidates_neigh"))
for line in io.lines() do
table.insert(
urls,
"http://["..line.."]/cgi-bin/shared-state/"..dataType )
end
end
for _,url in ipairs(urls) do
local options = {}
options.sndtimeo = 3
options.rcvtimeo = 3
options.method = 'POST'
options.body = sharedState.toJsonString()
-- Alias WK:2622 Workaround https://github.com/openwrt/luci/issues/2622
local startTP = os.time() -- WK:2622
local success, response = pcall(http.request_to_buffer, url, options)
local endTP = os.time() -- WK:2622
if success and type(response) == "string" and response:len() > 1 then
local parsedJson = JSON.parse(response)
if parsedJson then sharedState.merge(parsedJson) end
else
self_log( "debug", "httpclient interal error requesting "..url )
-- WK:2622
for tFpath in fs.glob("/tmp/lua_*") do
local mStat = fs.stat(tFpath)
if mStat and
mStat.atime >= startTP and mStat.atime <= endTP and
mStat.ctime >= startTP and mStat.ctime <= endTP and
mStat.mtime >= startTP and mStat.mtime <= endTP then
os.remove(tFpath)
end
end
end
end
end
function sharedState.toJsonString()
return JSON.stringify(self_storage)
end
function sharedState.unlock()
if not self_locked then return end
self_storageFD:lock("ulock")
self_storageFD:close()
self_storageFD = nil
self_locked = false
end
return sharedState
end
return SharedState
|
#!/usr/bin/lua
--! Minimalistic CRDT-like shared state structure suitable for mesh networks
--!
--! Copyright (C) 2019 Gioacchino Mazzurco <gio@altermundi.net>
--!
--! This program is free software: you can redistribute it and/or modify
--! it under the terms of the GNU Affero General Public License version 3 as
--! published by the Free Software Foundation.
--!
--! This program is distributed in the hope that it will be useful,
--! but WITHOUT ANY WARRANTY; without even the implied warranty of
--! MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
--! GNU Affero General Public License for more details.
--!
--! You should have received a copy of the GNU Affero General Public License
--! along with this program. If not, see <http://www.gnu.org/licenses/>.
local fs = require("nixio.fs")
local http = require("luci.httpclient")
local JSON = require("luci.jsonc")
local nixio = require("nixio")
local uci = require("uci")
local function SharedState(dataType, pLogger)
--! Name of the CRDT is mandatory
if type(dataType) ~= "string" or dataType:len() < 1 then return nil end
--! Map<Key, {bleachTTL, author, data}>
--! bleachTTL is the count of how much bleaching should occur before the
--! entry expires
--! author is the name of the host who generated that entry
--! data is the value of the entry
local self_storage = {}
--! File descriptor of the persistent file storage
local self_storageFD = nil
--! true if self_storage has changed after loading
local self_changed = false
local self_dataDir = "/var/shared-state/data/"
local self_dataFile = "/var/shared-state/data/"..dataType..".json"
local self_hooksDir = "/etc/shared-state/hooks/"..dataType.."/"
--! true when persistent storage file is locked by this instance
local self_locked = false
local self_log = function (level, message)
end
if type(logger) == "function" then self_log = logger end
local sharedState = {}
--! Returns true it at least one entry expired, false otherwise
function sharedState.bleach()
local substancialChange = false
for k,v in pairs(self_storage) do
if(v.bleachTTL < 2) then
self_storage[k] = nil
substancialChange = true
else
v.bleachTTL = v.bleachTTL-1
end
self_changed = true
end
return substancialChange
end
function sharedState.insert(key, data, bleachTTL)
bleachTTL = bleachTTL or 30
self_storage[key] = {
bleachTTL=bleachTTL,
author=io.input("/proc/sys/kernel/hostname"):read("*line"),
data=data
}
self_changed = true
end
function sharedState.load()
sharedState.merge(JSON.parse(self_storageFD:readall()), false)
end
function sharedState.lock(maxwait)
if self_locked then return end
maxwait = maxwait or 10
fs.mkdirr(self_dataDir)
self_storageFD = nixio.open(
self_dataFile, nixio.open_flags("rdwr", "creat") )
for i=1,maxwait do
if not self_storageFD:lock("tlock") then
nixio.nanosleep(1)
else
self_locked = true
break
end
end
if not self_locked then
self_log( "err",
arg[0], arg[1], arg[2], "Failed acquiring lock on data!" )
os.exit(-165)
end
end
function sharedState.merge(stateSlice, notifyInsert)
local stateSlice = stateSlice or {}
if(notifyInsert == nil) then notifyInsert = true end
for key,rv in pairs(stateSlice) do
if rv.bleachTTL <= 0 then
self_log( "debug", "sharedState.merge got expired entry" )
self_changed = true
else
local lv = self_storage[key]
if( lv == nil ) then
self_storage[key] = rv
self_changed = self_changed or notifyInsert
elseif ( lv.bleachTTL < rv.bleachTTL ) then
self_log( "debug", "Updating entry for: "..key.." older: "..
lv.bleachTTL.." newer: "..rv.bleachTTL )
self_storage[key] = rv
self_changed = self_changed or notifyInsert
end
end
end
end
function sharedState.notifyHooks()
if self_changed then
local jsonString = sharedState.toJsonString()
if not fs.dir(self_hooksDir) then return end
for hook in fs.dir(self_hooksDir) do
local cStdin = io.popen(self_hooksDir.."/"..hook, "w")
cStdin:write(jsonString)
cStdin:close()
end
end
end
function sharedState.remove(key)
if(self_storage[key] ~= nil and self_storage[key].data ~= nil)
then sharedState.insert(key, nil) end
end
function sharedState.save()
if self_changed then
local outFd = io.open(self_dataFile, "w")
outFd:write(sharedState.toJsonString())
outFd:close()
outFd = nil
end
end
function sharedState.sync(urls)
urls = urls or {}
if #urls < 1 then
local uci_cursor = uci:cursor()
local fixed_candidates =
uci_cursor:get("shared-state", "options","candidates") or {}
for _, line in pairs(fixed_candidates) do
table.insert(
urls,
line.."/"..dataType )
end
io.input(io.popen(arg[0].."-get_candidates_neigh"))
for line in io.lines() do
table.insert(
urls,
"http://["..line.."]/cgi-bin/shared-state/"..dataType )
end
end
for _,url in ipairs(urls) do
local options = {}
options.sndtimeo = 3
options.rcvtimeo = 3
options.method = 'POST'
options.body = sharedState.toJsonString()
-- Alias WK:2622 Workaround https://github.com/openwrt/luci/issues/2622
local startTP = os.time() -- WK:2622
local success, response = pcall(http.request_to_buffer, url, options)
local endTP = os.time() -- WK:2622
if success and type(response) == "string" and response:len() > 1 then
local parsedJson = JSON.parse(response)
if parsedJson then sharedState.merge(parsedJson) end
else
self_log( "debug", "httpclient interal error requesting "..url )
-- WK:2622
for tFpath in fs.glob("/tmp/lua_*") do
local mStat = fs.stat(tFpath)
if mStat and
mStat.atime >= startTP and mStat.atime <= endTP and
mStat.ctime >= startTP and mStat.ctime <= endTP and
mStat.mtime >= startTP and mStat.mtime <= endTP then
os.remove(tFpath)
end
end
end
end
end
function sharedState.toJsonString()
return JSON.stringify(self_storage)
end
function sharedState.unlock()
if not self_locked then return end
self_storageFD:lock("ulock")
self_storageFD:close()
self_storageFD = nil
self_locked = false
end
return sharedState
end
return SharedState
|
Fixes when shared-state plugin doesnt have any hooks defined.
|
Fixes when shared-state plugin doesnt have any hooks defined.
|
Lua
|
agpl-3.0
|
libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages
|
758c277d5748ddae9dae1d26b533250c476c6682
|
src/lgix/GObject-Object.lua
|
src/lgix/GObject-Object.lua
|
------------------------------------------------------------------------------
--
-- LGI Object handling.
--
-- Copyright (c) 2010, 2011 Pavel Holejsovsky
-- Licensed under the MIT license:
-- http://www.opensource.org/licenses/mit-license.php
--
------------------------------------------------------------------------------
local pairs = pairs
local core = require 'lgi._core'
local gi = core.gi
local repo = core.repo
local Value = repo.GObject.Value
local Type = repo.GObject.Type
local Closure = repo.GObject.Closure
local Object = repo.GObject.Object
-- Object constructor, 'param' contains table with properties/signals
-- to initialize.
local parameter_info = gi.GObject.Parameter
local object_new = core.callable.new(gi.GObject.Object.methods.new)
function Object:_new(args)
-- Process 'args' table, separate properties from other fields.
local params, others, safe = {}, {}, {}
for name, arg in pairs(args or {}) do
local argtype = self[name]
if gi.isinfo(argtype) and argtype.is_property then
local param = core.record.new(parameter_info)
name = argtype.name
-- Store the name string in some safe Lua place ('safe'
-- table), because param is GParameter, which contains only
-- non-owning pointer to the string, and it could be
-- Lua-GC'ed while still referenced by GParameter instance.
safe[#safe + 1] = name
param.name = name
local gtype = Type.from_typeinfo(argtype.typeinfo)
Value.init(param.value, gtype)
local marshaller = Value.find_marshaller(gtype, argtype.typeinfo)
marshaller(param.value, nil, arg)
params[#params + 1] = param
else
others[name] = arg
end
end
-- Create the object.
local object = object_new(self._gtype, params)
-- Attach arguments previously filtered out from creation.
for name, func in pairs(others) do object[name] = func end
return object
end
-- Initially unowned creation is similar to normal GObject creation,
-- but we have to ref_sink newly created object.
local InitiallyUnowned = repo.GObject.InitiallyUnowned
function InitiallyUnowned:_new(args)
local object = Object._new(self, args)
return Object.ref_sink(object)
end
-- Reading 'class' yields real instance of the object class.
Object._attribute = { class = {} }
function Object._attribute.class:get()
return core.object.query(self, 'class')
end
-- Custom _element implementation, checks dynamically inherited
-- interfaces and dynamic properties.
local inherited_element = Object._element
function Object:_element(object, name)
local element, category = inherited_element(self, object, name)
if element then return element, category end
-- Everything else works only if we have object instance.
if not object then return nil end
-- List all interfaces implemented by this object and try whether
-- they can handle specified _element request.
local interfaces = Type.interfaces(core.object.query(object, 'gtype'))
for i = 1, #interfaces do
local info = gi[core.gtype(interfaces[i])]
local iface = repo[info.namespace][info.name]
element, category = iface and iface:_element(object, name)
if element then return element, category end
end
-- Element not found in the repo (typelib), try whether dynamic
-- property of the specified name exists.
local class = core.record.cast(core.object.query(object, 'class'), Object._class)
local property = Object._class.find_property(class, name:gsub('_', '%-'))
if property then return property, '_paramspec' end
-- If nothing else is found, return simple artificial attribute
-- which reads/writes object's env table.
local env = core.object.query(object, 'env')
return { get = function(obj) return env.name end,
set = function(obj, val) env.name = val end, }, '_attribute'
end
-- Sets/gets property using specified marshaller attributes.
local function marshal_property(obj, name, flags, gtype, marshaller, ...)
-- Check access rights of the property.
local mode = select('#', ...) > 0 and 'WRITABLE' or 'READABLE'
if not core.has_bit(flags, repo.GObject.ParamFlags[mode]) then
error(("%s: `%s' not %s"):format(core.object.query(obj, 'repo')._name,
name, mode:lower()))
end
local value = Value(gtype)
if mode == 'WRITABLE' then
marshaller(value, nil, ...)
Object.set_property(obj, name, value)
else
Object.get_property(obj, name, value)
return marshaller(value)
end
end
-- GI property accessor.
function Object:_access_property(object, property, ...)
local typeinfo = property.typeinfo
local gtype = Type.from_typeinfo(typeinfo)
local marshaller = Value.find_marshaller(gtype, typeinfo, property.transfer)
return marshal_property(object, property.name, property.flags,
gtype, marshaller, ...)
end
-- GLib property accessor (paramspec).
function Object:_access_paramspec(object, pspec, ...)
return marshal_property(object, pspec.name, pspec.flags, pspec.value_type,
Value.find_marshaller(pspec.value_type), ...)
end
local quark_from_string = repo.GLib.quark_from_string
local signal_lookup = repo.GObject.signal_lookup
local signal_connect_closure_by_id = repo.GObject.signal_connect_closure_by_id
local signal_emitv = repo.GObject.signal_emitv
-- Connects signal to specified object instance.
local function connect_signal(obj, gtype, name, closure, detail, after)
return signal_connect_closure_by_id(
obj, signal_lookup(name, gtype), quark_from_string(detail), closure,
after or false)
end
-- Emits signal on specified object instance.
local function emit_signal(obj, gtype, info, detail, ...)
-- Compile callable info.
local call_info = Closure.CallInfo.new(info)
-- Marshal input arguments.
local retval, params, keepalive = call_info:pre_call(obj, ...)
-- Invoke the signal.
signal_emitv(params, signal_lookup(info.name, gtype),
quark_from_string(detail), retval)
-- Unmarshal results.
return call_info:post_call(params, retval)
end
-- Signal accessor.
function Object:_access_signal(object, info, ...)
local gtype = self._gtype
if select('#', ...) > 0 then
-- Assignment means 'connect signal without detail'.
connect_signal(object, gtype, info.name, Closure((...), info))
else
-- Reading yields table with signal operations.
local pad = {}
function pad:connect(target, detail, after)
return connect_signal(object, gtype, info.name,
Closure(target, info), detail, after)
end
function pad:emit(detail, ...)
return emit_signal(object, gtype, info, detail, object, ...)
end
-- If signal supports details, add metatable implementing
-- __newindex for connecting in the 'on_signal['detail'] =
-- handler' form.
if info.is_signal and info.flags.detailed then
local mt = {}
function mt:__newindex(detail, target)
connect_signal(object, gtype, info.name, Closure(target, info),
detail)
end
setmetatable(pad, mt)
end
-- Return created signal pad.
return pad
end
end
|
------------------------------------------------------------------------------
--
-- LGI Object handling.
--
-- Copyright (c) 2010, 2011 Pavel Holejsovsky
-- Licensed under the MIT license:
-- http://www.opensource.org/licenses/mit-license.php
--
------------------------------------------------------------------------------
local pairs = pairs
local core = require 'lgi._core'
local gi = core.gi
local repo = core.repo
local Value = repo.GObject.Value
local Type = repo.GObject.Type
local Closure = repo.GObject.Closure
local Object = repo.GObject.Object
-- Object constructor, 'param' contains table with properties/signals
-- to initialize.
local parameter_info = gi.GObject.Parameter
local object_new = core.callable.new(gi.GObject.Object.methods.new)
function Object:_new(args)
-- Process 'args' table, separate properties from other fields.
local params, others, safe = {}, {}, {}
for name, arg in pairs(args or {}) do
local argtype = self[name]
if gi.isinfo(argtype) and argtype.is_property then
local param = core.record.new(parameter_info)
name = argtype.name
-- Store the name string in some safe Lua place ('safe'
-- table), because param is GParameter, which contains only
-- non-owning pointer to the string, and it could be
-- Lua-GC'ed while still referenced by GParameter instance.
safe[#safe + 1] = name
param.name = name
local gtype = Type.from_typeinfo(argtype.typeinfo)
Value.init(param.value, gtype)
local marshaller = Value.find_marshaller(gtype, argtype.typeinfo)
marshaller(param.value, nil, arg)
params[#params + 1] = param
else
others[name] = arg
end
end
-- Create the object.
local object = object_new(self._gtype, params)
-- Attach arguments previously filtered out from creation.
for name, func in pairs(others) do object[name] = func end
return object
end
-- Initially unowned creation is similar to normal GObject creation,
-- but we have to ref_sink newly created object.
local InitiallyUnowned = repo.GObject.InitiallyUnowned
function InitiallyUnowned:_new(args)
local object = Object._new(self, args)
return Object.ref_sink(object)
end
-- Reading 'class' yields real instance of the object class.
Object._attribute = { class = {} }
function Object._attribute.class:get()
return core.object.query(self, 'class')
end
-- Custom _element implementation, checks dynamically inherited
-- interfaces and dynamic properties.
local inherited_element = Object._element
function Object:_element(object, name)
local element, category = inherited_element(self, object, name)
if element then return element, category end
-- Everything else works only if we have object instance.
if not object then return nil end
-- List all interfaces implemented by this object and try whether
-- they can handle specified _element request.
local interfaces = Type.interfaces(core.object.query(object, 'gtype'))
for i = 1, #interfaces do
local info = gi[core.gtype(interfaces[i])]
local iface = repo[info.namespace][info.name]
if iface then element, category = iface:_element(object, name) end
if element then return element, category end
end
-- Element not found in the repo (typelib), try whether dynamic
-- property of the specified name exists.
local class = core.record.cast(core.object.query(object, 'class'),
Object._class)
local property = Object._class.find_property(class, name:gsub('_', '%-'))
if property then return property, '_paramspec' end
-- If nothing else is found, return simple artificial attribute
-- which reads/writes object's env table.
local env = core.object.query(object, 'env')
return { get = function(obj) return env.name end,
set = function(obj, val) env.name = val end, }, '_attribute'
end
-- Sets/gets property using specified marshaller attributes.
local function marshal_property(obj, name, flags, gtype, marshaller, ...)
-- Check access rights of the property.
local mode = select('#', ...) > 0 and 'WRITABLE' or 'READABLE'
if not core.has_bit(flags, repo.GObject.ParamFlags[mode]) then
error(("%s: `%s' not %s"):format(core.object.query(obj, 'repo')._name,
name, mode:lower()))
end
local value = Value(gtype)
if mode == 'WRITABLE' then
marshaller(value, nil, ...)
Object.set_property(obj, name, value)
else
Object.get_property(obj, name, value)
return marshaller(value)
end
end
-- GI property accessor.
function Object:_access_property(object, property, ...)
local typeinfo = property.typeinfo
local gtype = Type.from_typeinfo(typeinfo)
local marshaller = Value.find_marshaller(gtype, typeinfo, property.transfer)
return marshal_property(object, property.name, property.flags,
gtype, marshaller, ...)
end
-- GLib property accessor (paramspec).
function Object:_access_paramspec(object, pspec, ...)
return marshal_property(object, pspec.name, pspec.flags, pspec.value_type,
Value.find_marshaller(pspec.value_type), ...)
end
local quark_from_string = repo.GLib.quark_from_string
local signal_lookup = repo.GObject.signal_lookup
local signal_connect_closure_by_id = repo.GObject.signal_connect_closure_by_id
local signal_emitv = repo.GObject.signal_emitv
-- Connects signal to specified object instance.
local function connect_signal(obj, gtype, name, closure, detail, after)
return signal_connect_closure_by_id(
obj, signal_lookup(name, gtype), quark_from_string(detail), closure,
after or false)
end
-- Emits signal on specified object instance.
local function emit_signal(obj, gtype, info, detail, ...)
-- Compile callable info.
local call_info = Closure.CallInfo.new(info)
-- Marshal input arguments.
local retval, params, keepalive = call_info:pre_call(obj, ...)
-- Invoke the signal.
signal_emitv(params, signal_lookup(info.name, gtype),
quark_from_string(detail), retval)
-- Unmarshal results.
return call_info:post_call(params, retval)
end
-- Signal accessor.
function Object:_access_signal(object, info, ...)
local gtype = self._gtype
if select('#', ...) > 0 then
-- Assignment means 'connect signal without detail'.
connect_signal(object, gtype, info.name, Closure((...), info))
else
-- Reading yields table with signal operations.
local pad = {}
function pad:connect(target, detail, after)
return connect_signal(object, gtype, info.name,
Closure(target, info), detail, after)
end
function pad:emit(detail, ...)
return emit_signal(object, gtype, info, detail, object, ...)
end
-- If signal supports details, add metatable implementing
-- __newindex for connecting in the 'on_signal['detail'] =
-- handler' form.
if info.is_signal and info.flags.detailed then
local mt = {}
function mt:__newindex(detail, target)
connect_signal(object, gtype, info.name, Closure(target, info),
detail)
end
setmetatable(pad, mt)
end
-- Return created signal pad.
return pad
end
end
|
Fix access of interface elements from object instances
|
Fix access of interface elements from object instances
|
Lua
|
mit
|
zevv/lgi,psychon/lgi,pavouk/lgi
|
6f18f5b0e6b5c47f8c770e75fbd4c7aaa02942c3
|
src/npge/algo/BlastHits.lua
|
src/npge/algo/BlastHits.lua
|
local makeblastdb = function(bank_fname, consensus_fname)
local args = {
'makeblastdb',
'-dbtype nucl',
'-out', bank_fname,
'-in', consensus_fname,
}
-- not os.execute to suppress messages produced by blast
local f = assert(io.popen(table.concat(args, ' ')))
f:read('*a')
f:close()
end
local blastn_cmd = function(bank, input, options)
local config = require 'npge.config'
local evalue = options.evalue or config.blast.EVALUE
local workers = options.workers or 1
local dust = options.dust or config.blast.DUST
local dust = dust and 'yes' or 'no'
local args = {
'blastn',
'-task blastn',
'-db', bank,
'-query', input,
'-evalue', tostring(evalue),
'-num_threads', workers,
'-dust', dust,
}
return table.concat(args, ' ')
end
local ori = function(start, stop)
if start < stop then
return 1
else
return -1
end
end
local read_blast = function(file, bs, hits_filter)
local new_blocks = {}
local query, subject
local query_row, subject_row
local query_start, subject_start
local query_stop, subject_stop
local good_hit = function()
return query and subject and query < subject and
query_row and subject_row
end
local try_add = function()
if good_hit() then
assert(query_row)
assert(subject_row)
assert(query_start)
assert(query_stop)
assert(subject_start)
assert(subject_stop)
local Fragment = require 'npge.model.Fragment'
local query_seq = bs:sequence_by_name(query)
assert(query_seq)
local query_ori = ori(query_start, query_stop)
local query_f = Fragment(query_seq,
query_start - 1, query_stop - 1, query_ori)
local subject_seq = bs:sequence_by_name(subject)
assert(subject_seq)
local subject_ori = ori(subject_start, subject_stop)
local subject_f = Fragment(subject_seq,
subject_start - 1, subject_stop - 1,
subject_ori)
local Block = require 'npge.model.Block'
local query_row1 = table.concat(query_row)
local subject_row1 = table.concat(subject_row)
local block = Block({
{query_f, query_row1},
{subject_f, subject_row1},
})
if not hits_filter or hits_filter(block) then
table.insert(new_blocks, block)
end
end
query_row = nil
subject_row = nil
query_start = nil
query_stop = nil
subject_start = nil
subject_stop = nil
end
local starts_with = require 'npge.util.starts_with'
local split = require 'npge.util.split'
local trim = require 'npge.util.trim'
local unpack = require 'npge.util.unpack'
local file_is_empty = true
for line in file:lines() do
file_is_empty = false
if starts_with(line, 'Query=') then
-- Example: Query= consensus000567
try_add()
query = split(line, '=')[2]
query = trim(query)
elseif line:sub(1, 1) == '>' then
-- Example: > consensus000567
try_add()
subject = trim(line:sub(2))
elseif starts_with(line, ' Score =') then
-- Example: Score = 82.4 bits (90), ...
try_add()
query_row = {}
subject_row = {}
elseif good_hit() then
if starts_with(line, 'Query ') then
-- Example: Query 1 GCGCG 5
local _, start, row, stop = unpack(split(line))
if not query_start then
query_start = assert(tonumber(start))
end
query_stop = assert(tonumber(stop))
table.insert(query_row, row)
elseif starts_with(line, 'Sbjct ') then
-- Example: Sbjct 1 GCGCG 5
local _, start, row, stop = unpack(split(line))
if not subject_start then
subject_start = assert(tonumber(start))
end
subject_stop = assert(tonumber(stop))
table.insert(subject_row, row)
end
end
end
try_add()
assert(not file_is_empty, "blastn returned empty file")
local BlockSet = require 'npge.model.BlockSet'
return BlockSet(bs:sequences(), new_blocks)
end
return function(blockset, options)
-- possible options:
-- - evalue
-- - dust
-- - workers
-- - hits_filter
-- (filtering function, accepts hit, returns true/false)
options = options or {}
local algo = require 'npge.algo'
local util = require 'npge.util'
local consensus_fname = os.tmpname()
util.write_it(consensus_fname,
algo.WriteSequencesToFasta(blockset))
local bank_fname = os.tmpname()
makeblastdb(bank_fname, consensus_fname)
assert(util.file_exists(bank_fname .. '.nhr'))
local cmd = blastn_cmd(bank_fname, consensus_fname, options)
local f = assert(io.popen(cmd, 'r'))
local hits = read_blast(f, blockset, options.hits_filter)
f:close()
os.remove(consensus_fname)
os.remove(bank_fname)
os.remove(bank_fname .. '.nhr')
os.remove(bank_fname .. '.nin')
os.remove(bank_fname .. '.nsq')
return hits
end
|
local makeblastdb = function(bank_fname, consensus_fname)
local args = {
'makeblastdb',
'-dbtype nucl',
'-out', bank_fname,
'-in', consensus_fname,
}
-- not os.execute to suppress messages produced by blast
local f = assert(io.popen(table.concat(args, ' ')))
f:read('*a')
f:close()
end
local blastn_cmd = function(bank, input, options)
local config = require 'npge.config'
local evalue = options.evalue or config.blast.EVALUE
local workers = options.workers or 1
local dust = options.dust or config.blast.DUST
local dust = dust and 'yes' or 'no'
local args = {
'blastn',
'-task blastn',
'-db', bank,
'-query', input,
'-evalue', tostring(evalue),
'-num_threads', workers,
'-dust', dust,
}
return table.concat(args, ' ')
end
local ori = function(start, stop)
if start < stop then
return 1
else
return -1
end
end
local read_blast = function(file, bs, hits_filter)
local new_blocks = {}
local query, subject
local query_row, subject_row
local query_start, subject_start
local query_stop, subject_stop
local good_hit = function()
return query and subject and query < subject and
query_row and subject_row
end
local try_add = function()
if good_hit() then
assert(query_row)
assert(subject_row)
assert(query_start)
assert(query_stop)
assert(subject_start)
assert(subject_stop)
local Fragment = require 'npge.model.Fragment'
local query_seq = bs:sequence_by_name(query)
assert(query_seq)
local query_ori = ori(query_start, query_stop)
local query_f = Fragment(query_seq,
query_start - 1, query_stop - 1, query_ori)
local subject_seq = bs:sequence_by_name(subject)
assert(subject_seq)
local subject_ori = ori(subject_start, subject_stop)
local subject_f = Fragment(subject_seq,
subject_start - 1, subject_stop - 1,
subject_ori)
local Block = require 'npge.model.Block'
local query_row1 = table.concat(query_row)
local subject_row1 = table.concat(subject_row)
local block = Block({
{query_f, query_row1},
{subject_f, subject_row1},
})
if not hits_filter or hits_filter(block) then
table.insert(new_blocks, block)
end
end
query_row = nil
subject_row = nil
query_start = nil
query_stop = nil
subject_start = nil
subject_stop = nil
end
local starts_with = require 'npge.util.starts_with'
local split = require 'npge.util.split'
local trim = require 'npge.util.trim'
local unpack = require 'npge.util.unpack'
local file_is_empty = true
for line in file:lines() do
file_is_empty = false
if starts_with(line, 'Query=') then
-- Example: Query= consensus000567
try_add()
query = split(line, '=')[2]
query = trim(query)
elseif line:sub(1, 1) == '>' then
-- Example: > consensus000567
try_add()
subject = trim(line:sub(2))
elseif starts_with(line, ' Score =') then
-- Example: Score = 82.4 bits (90), ...
try_add()
query_row = {}
subject_row = {}
elseif good_hit() then
local parse_alignment = function(line)
local parts = split(line)
assert(#parts == 4 or #parts == 3)
if #parts == 4 then
local _, start, row, stop = unpack(parts)
return start, row, stop
end
if #parts == 3 then
local _, row = unpack(parts)
return nil, row, nil
end
end
if starts_with(line, 'Query ') then
-- Example: Query 1 GCGCG 5
local start, row, stop = parse_alignment(line)
if start and stop then
if not query_start then
query_start = assert(tonumber(start))
end
query_stop = assert(tonumber(stop))
end
table.insert(query_row, row)
elseif starts_with(line, 'Sbjct ') then
-- Example: Sbjct 1 GCGCG 5
local start, row, stop = parse_alignment(line)
if start and stop then
if not subject_start then
subject_start = assert(tonumber(start))
end
subject_stop = assert(tonumber(stop))
end
table.insert(subject_row, row)
end
end
end
try_add()
assert(not file_is_empty, "blastn returned empty file")
local BlockSet = require 'npge.model.BlockSet'
return BlockSet(bs:sequences(), new_blocks)
end
return function(blockset, options)
-- possible options:
-- - evalue
-- - dust
-- - workers
-- - hits_filter
-- (filtering function, accepts hit, returns true/false)
options = options or {}
local algo = require 'npge.algo'
local util = require 'npge.util'
local consensus_fname = os.tmpname()
util.write_it(consensus_fname,
algo.WriteSequencesToFasta(blockset))
local bank_fname = os.tmpname()
makeblastdb(bank_fname, consensus_fname)
assert(util.file_exists(bank_fname .. '.nhr'))
local cmd = blastn_cmd(bank_fname, consensus_fname, options)
local f = assert(io.popen(cmd, 'r'))
local hits = read_blast(f, blockset, options.hits_filter)
f:close()
os.remove(consensus_fname)
os.remove(bank_fname)
os.remove(bank_fname .. '.nhr')
os.remove(bank_fname .. '.nin')
os.remove(bank_fname .. '.nsq')
return hits
end
|
BlastHits: fix whole row of gaps case
|
BlastHits: fix whole row of gaps case
I failed to reproduce this in tests.
Blast can produce the following output:
Query 31492 GAGCGCAGCGGCCGTATTCTTCACTGCCCCACTGCCCCACTGCCCCACTGCCCCACT--- 31548
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Sbjct 5309 GAGCGCAGCGGCCGTATTCTTCACTGCCCCACTGCCCCACTGCCCCACTGCCCCACTGCC 5250
Query ------------------------------------------------------------
Sbjct 5249 CCACTGCCCCACTGCCCCACTGCCCCACTGCCCCACTGCCCCACTGCCCCACTGCCCCAC 5190
Query 31549 -GCCCTACTCATTCAACGGAACCACGCCGCAATCACCGGCTTGCGACCCGAAGACCAGTC 31607
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Sbjct 5189 TGCCCTACTCATTCAACGGAACCACGCCGCAATCACCGGCTTGCGACCCGAAGACCAGTC 5130
|
Lua
|
mit
|
npge/lua-npge,npge/lua-npge,starius/lua-npge,starius/lua-npge,starius/lua-npge,npge/lua-npge
|
328d5c17c44b4c7cb0623103c926dbae215745e4
|
init.lua
|
init.lua
|
require 'libpaths'
local assert = assert
local debug = debug
local pcall = pcall
local type = type
local ipairs = ipairs
local os = os
function paths.is_win()
return paths.uname():match('Windows')
end
function paths.is_mac()
return paths.uname():match('Darwin')
end
if paths.is_win() then
paths.home = os.getenv('HOMEDRIVE') or 'C:'
paths.home = paths.home .. ( os.getenv('HOMEPATH') or '\\' )
else
paths.home = os.getenv('HOME') or '.'
end
function paths.files(s)
local d = paths.dir(s)
local n = 0
return function()
n = n + 1
if (d and n <= #d) then
return d[n]
else
return nil
end
end
end
function paths.thisfile(arg, depth)
local s = debug.getinfo(depth or 2).source
if type(s) ~= "string" then
s = nil
elseif s:match("^@") then -- when called from a file
s = concat(s:sub(2))
elseif s:match("^qt[.]") then -- when called from a qtide editor
local function z(s) return qt[s].fileName:tostring() end
local b, f = pcall(z, s:sub(4));
if b and f and f ~= "" then s = f else s = nil end
end
if type(arg) == "string" then
if s then s = concat(paths.dirname(s), arg) else s = arg end
end
return s
end
function paths.dofile(f, depth)
local s = paths.thisfile(nil, 1 + (depth or 2))
if s and s ~= "" then
f = concat(paths.dirname(s),f)
end
return dofile(f)
end
function paths.rmall(d, more)
if more ~= 'yes' then
return nil, "missing second argument ('yes')"
elseif paths.filep(d) then
return os.remove(d)
elseif paths.dirp(d) then
for f in paths.files(d) do
if f ~= '.' and f ~= '..' then
local ff = concat(d, f)
local r0,r1,r2 = paths.rmall(ff, more)
if not r0 then
return r0,r1,ff
end
end
end
return paths.rmdir(d)
else
return nil, "not a file or directory", d
end
end
function paths.findprogram(...)
for _,exe in ipairs{...} do
if paths.is_win() then
if not exe:match('[.]exe$') then
exe = exe .. '.exe'
end
local path, k, x = os.getenv("PATH") or "."
for dir in path:gmatch('[^;]+') do
x = concat(dir, exe)
if paths.filep(x) then return x end
end
local function clean(s)
if s:match('^"') then return s:match('[^"]+') else return s end
end
k = 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\' .. exe
x = paths.getregistryvalue('HKEY_CURRENT_USER', k, '')
if type(x) == 'string' then return clean(x) end
x = paths.getregistryvalue('HKEY_LOCAL_MACHINE', k, '')
if type(x) == 'string' then return clean(x) end
k = 'Applications\\' .. exe .. '\\shell\\open\\command'
x = paths.getregistryvalue('HKEY_CLASSES_ROOT', k, '')
if type(x) == 'string' then return clean(x) end
else
local path = os.getenv("PATH") or "."
for dir in path:gmatch('[^:]+') do
local x = concat(dir, exe)
if paths.filep(x) then return x end
end
end
end
return nil
end
return paths
|
require 'libpaths'
local assert = assert
local debug = debug
local pcall = pcall
local type = type
local ipairs = ipairs
local os = os
function paths.is_win()
return paths.uname():match('Windows')
end
function paths.is_mac()
return paths.uname():match('Darwin')
end
if paths.is_win() then
paths.home = os.getenv('HOMEDRIVE') or 'C:'
paths.home = paths.home .. ( os.getenv('HOMEPATH') or '\\' )
else
paths.home = os.getenv('HOME') or '.'
end
function paths.files(s)
local d = paths.dir(s)
local n = 0
return function()
n = n + 1
if (d and n <= #d) then
return d[n]
else
return nil
end
end
end
function paths.thisfile(arg, depth)
local s = debug.getinfo(depth or 2).source
if type(s) ~= "string" then
s = nil
elseif s:match("^@") then -- when called from a file
s = paths.concat(s:sub(2))
elseif s:match("^qt[.]") then -- when called from a qtide editor
local function z(s) return qt[s].fileName:tostring() end
local b, f = pcall(z, s:sub(4));
if b and f and f ~= "" then s = f else s = nil end
end
if type(arg) == "string" then
if s then s = paths.concat(paths.dirname(s), arg) else s = arg end
end
return s
end
function paths.dofile(f, depth)
local s = paths.thisfile(nil, 1 + (depth or 2))
if s and s ~= "" then
f = paths.concat(paths.dirname(s),f)
end
return dofile(f)
end
function paths.rmall(d, more)
if more ~= 'yes' then
return nil, "missing second argument ('yes')"
elseif paths.filep(d) then
return os.remove(d)
elseif paths.dirp(d) then
for f in paths.files(d) do
if f ~= '.' and f ~= '..' then
local ff = paths.concat(d, f)
local r0,r1,r2 = paths.rmall(ff, more)
if not r0 then
return r0,r1,ff
end
end
end
return paths.rmdir(d)
else
return nil, "not a file or directory", d
end
end
function paths.findprogram(...)
for _,exe in ipairs{...} do
if paths.is_win() then
if not exe:match('[.]exe$') then
exe = exe .. '.exe'
end
local path, k, x = os.getenv("PATH") or "."
for dir in path:gmatch('[^;]+') do
x = paths.concat(dir, exe)
if paths.filep(x) then return x end
end
local function clean(s)
if s:match('^"') then return s:match('[^"]+') else return s end
end
k = 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\' .. exe
x = paths.getregistryvalue('HKEY_CURRENT_USER', k, '')
if type(x) == 'string' then return clean(x) end
x = paths.getregistryvalue('HKEY_LOCAL_MACHINE', k, '')
if type(x) == 'string' then return clean(x) end
k = 'Applications\\' .. exe .. '\\shell\\open\\command'
x = paths.getregistryvalue('HKEY_CLASSES_ROOT', k, '')
if type(x) == 'string' then return clean(x) end
else
local path = os.getenv("PATH") or "."
for dir in path:gmatch('[^:]+') do
local x = paths.concat(dir, exe)
if paths.filep(x) then return x end
end
end
end
return nil
end
return paths
|
fix 5.2 compatibility patch
|
fix 5.2 compatibility patch
|
Lua
|
bsd-3-clause
|
LinusU/paths,nicholas-leonard/paths,torch/paths
|
6801f6075db62801ba738233c1f83f98a19d38af
|
modules/admin-full/luasrc/model/cbi/admin_network/network.lua
|
modules/admin-full/luasrc/model/cbi/admin_network/network.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local sys = require "luci.sys"
local wa = require "luci.tools.webadmin"
local fs = require "nixio.fs"
local netstate = luci.model.uci.cursor_state():get_all("network")
m = Map("network", translate("Interfaces"))
local created
local netstat = sys.net.deviceinfo()
s = m:section(TypedSection, "interface", "")
s.addremove = true
s.anonymous = false
s.extedit = luci.dispatcher.build_url("admin", "network", "network") .. "/%s"
s.template = "cbi/tblsection"
s.override_scheme = true
function s.filter(self, section)
return section ~= "loopback" and section
end
function s.create(self, section)
if TypedSection.create(self, section) then
created = section
else
self.invalid_cts = true
end
end
function s.parse(self, ...)
TypedSection.parse(self, ...)
if created then
m.uci:save("network")
luci.http.redirect(luci.dispatcher.build_url("admin", "network", "network")
.. "/" .. created)
end
end
up = s:option(Flag, "up")
function up.cfgvalue(self, section)
return netstate[section] and netstate[section].up or "0"
end
function up.write(self, section, value)
local call
if value == "1" then
call = "ifup"
elseif value == "0" then
call = "ifdown"
end
os.execute(call .. " " .. section .. " >/dev/null 2>&1")
end
ifname = s:option(DummyValue, "ifname", translate("Device"))
function ifname.cfgvalue(self, section)
return netstate[section] and netstate[section].ifname
end
ifname.titleref = luci.dispatcher.build_url("admin", "network", "vlan")
if luci.model.uci.cursor():load("firewall") then
zone = s:option(DummyValue, "_zone", translate("Zone"))
zone.titleref = luci.dispatcher.build_url("admin", "network", "firewall", "zones")
function zone.cfgvalue(self, section)
return table.concat(wa.network_get_zones(section) or { "-" }, ", ")
end
end
hwaddr = s:option(DummyValue, "_hwaddr",
translate("<abbr title=\"Media Access Control\">MAC</abbr>-Address"),
translate("Hardware Address"))
function hwaddr.cfgvalue(self, section)
local ix = self.map:get(section, "ifname") or ""
local mac = fs.readfile("/sys/class/net/" .. ix .. "/address")
if not mac then
mac = luci.util.exec("ifconfig " .. ix)
mac = mac and mac:match(" ([A-F0-9:]+)%s*\n")
end
if mac and #mac > 0 then
return mac:upper()
end
return "?"
end
ipaddr = s:option(DummyValue, "ipaddr",
translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>" ..
"-Address"))
function ipaddr.cfgvalue(self, section)
return table.concat(wa.network_get_addresses(section), ", ")
end
txrx = s:option(DummyValue, "_txrx", translate("Traffic"),
translate("transmitted / received"))
function txrx.cfgvalue(self, section)
local ix = self.map:get(section, "ifname")
local rx = netstat and netstat[ix] and netstat[ix][1]
rx = rx and wa.byte_format(tonumber(rx)) or "-"
local tx = netstat and netstat[ix] and netstat[ix][9]
tx = tx and wa.byte_format(tonumber(tx)) or "-"
return string.format("%s / %s", tx, rx)
end
errors = s:option(DummyValue, "_err", translate("Errors"),
translate("TX / RX"))
function errors.cfgvalue(self, section)
local ix = self.map:get(section, "ifname")
local rx = netstat and netstat[ix] and netstat[ix][3]
local tx = netstat and netstat[ix] and netstat[ix][11]
rx = rx and tostring(rx) or "-"
tx = tx and tostring(tx) or "-"
return string.format("%s / %s", tx, rx)
end
return m
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local sys = require "luci.sys"
local wa = require "luci.tools.webadmin"
local fs = require "nixio.fs"
local netstate = luci.model.uci.cursor_state():get_all("network")
m = Map("network", translate("Interfaces"))
local created
local netstat = sys.net.deviceinfo()
s = m:section(TypedSection, "interface", "")
s.addremove = true
s.anonymous = false
s.extedit = luci.dispatcher.build_url("admin", "network", "network") .. "/%s"
s.template = "cbi/tblsection"
s.override_scheme = true
function s.filter(self, section)
return section ~= "loopback" and section
end
function s.create(self, section)
if TypedSection.create(self, section) then
created = section
else
self.invalid_cts = true
end
end
function s.parse(self, ...)
TypedSection.parse(self, ...)
if created then
m.uci:save("network")
luci.http.redirect(luci.dispatcher.build_url("admin", "network", "network")
.. "/" .. created)
end
end
up = s:option(Flag, "up")
function up.cfgvalue(self, section)
return netstate[section] and netstate[section].up or "0"
end
function up.write(self, section, value)
local call
if value == "1" then
call = "ifup"
elseif value == "0" then
call = "ifdown"
end
os.execute(call .. " " .. section .. " >/dev/null 2>&1")
end
ifname = s:option(DummyValue, "ifname", translate("Device"))
function ifname.cfgvalue(self, section)
return netstate[section] and netstate[section].ifname
end
ifname.titleref = luci.dispatcher.build_url("admin", "network", "vlan")
if luci.model.uci.cursor():load("firewall") then
zone = s:option(DummyValue, "_zone", translate("Zone"))
zone.titleref = luci.dispatcher.build_url("admin", "network", "firewall", "zones")
function zone.cfgvalue(self, section)
return table.concat(wa.network_get_zones(section) or { "-" }, ", ")
end
end
hwaddr = s:option(DummyValue, "_hwaddr",
translate("<abbr title=\"Media Access Control\">MAC</abbr>-Address"),
translate("Hardware Address"))
function hwaddr.cfgvalue(self, section)
local ix = self.map:get(section, "ifname") or ""
ix = (type(ix) == "table") and ix[1] or ix
local mac = fs.readfile("/sys/class/net/" .. ix .. "/address")
if not mac then
mac = luci.util.exec("ifconfig " .. ix)
mac = mac and mac:match(" ([A-F0-9:]+)%s*\n")
end
if mac and #mac > 0 then
return mac:upper()
end
return "?"
end
ipaddr = s:option(DummyValue, "ipaddr",
translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>" ..
"-Address"))
function ipaddr.cfgvalue(self, section)
return table.concat(wa.network_get_addresses(section), ", ")
end
txrx = s:option(DummyValue, "_txrx", translate("Traffic"),
translate("transmitted / received"))
function txrx.cfgvalue(self, section)
local ix = self.map:get(section, "ifname")
local rx = netstat and netstat[ix] and netstat[ix][1]
rx = rx and wa.byte_format(tonumber(rx)) or "-"
local tx = netstat and netstat[ix] and netstat[ix][9]
tx = tx and wa.byte_format(tonumber(tx)) or "-"
return string.format("%s / %s", tx, rx)
end
errors = s:option(DummyValue, "_err", translate("Errors"),
translate("TX / RX"))
function errors.cfgvalue(self, section)
local ix = self.map:get(section, "ifname")
local rx = netstat and netstat[ix] and netstat[ix][3]
local tx = netstat and netstat[ix] and netstat[ix][11]
rx = rx and tostring(rx) or "-"
tx = tx and tostring(tx) or "-"
return string.format("%s / %s", tx, rx)
end
return m
|
modules/admin-full: fix crash on network interface overview page
|
modules/admin-full: fix crash on network interface overview page
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@6099 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci
|
784e43b234a6b993dde63d60940e5c9276de4bca
|
letsjustchat.lua
|
letsjustchat.lua
|
#!/usr/bin/env carbon
-- Lets just chat!
event = require("libs.event")
logger = require("libs.logger")
loader = require("libs.loader")
logger.log("Main", logger.normal, "Loading Init files...")
local loaded, loadtime = loader.load("init.d/*")
logger.log("Main", logger.normal, "Loaded "..tostring(loaded).." Init Files. Took "..tostring(loadtime).."s.")
-- Chat interface
srv.GET("/", mw.new(function()
-- TODO: Replace stub
content("Go away. (For now.)")
end))
-- Chat logic
srv.GET("/ws", mw.ws(function()
-- Small variables we use later.
local deflen = 10
local minlen = 1
local maxlen = 30
local maxmsglen = 1024
local disallowed = {
["join"] = true,
["left"] = true,
["error"] = true,
["info"] = true,
}
-- Require libraries we use.
event = require("libs.event")
rpc = require("libs.multirpc")
server = server or require("libs.servercheck")
local clientid = context.ClientIP() -- Use simply the client IP + Port as the ID.
-- TODO: Actual chan logic.
local name = query("name")
if name == nil or name == "" then
ws.send(ws.TextMessage, "error * Please choose a name by connecting to the WebSocket with the query argument name set to your preferred name.")
return
elseif #name > maxlen then -- Exceeds maximum name length
ws.send(ws.TextMessage, "error * Name exceeds max length.")
return
end
if not server.user_valid(name) then
ws.send(ws.TextMessage, "error * Name contains invalid characters and/or is restricted.")
return
end
local chan = query("chan") or "lobby"
-- Fail if username is already existing.
local started = kvstore.get("started:"..chan)
if not started then
rpc.call("log.normal", "Chat", "Looks like "..chan.." is getting some activity!")
event.handle("chan:"..chan, function(callee, action, name, clientid, msg)
usercount = usercount or 0
db = db or {}
action = action:lower()
local function pub(a, nme, m)
for user, userid in pairs(db) do
if user ~= name then
local wsok = kvstore.get("client:"..userid)
wsok.WriteMessage(1, convert.stringtocharslice(a..(nme and (" " .. nme) or "")..(m and (" " .. m) or ""))) -- Dark magic
end
end
end
if callee == "server" then
-- Reassigned:
-- action = selector/name
-- name, clientid, msg = args
if action == "*" then -- Broadcast.
pub(name, clientid, msg) -- These are actually different things then..
else -- Target name
local cid = db[action]
if cid then
local wsok = kvstore.get("client:"..cid)
wsok.WriteMessage(1, convert.stringtocharslice(name..(clientid and (" " .. clientid) or "")..(msg and (" " .. msg) or ""))) -- Dark magic
end
end
else
if action == "join" then
db[name] = clientid
usercount = usercount + 1
kvstore.set("users:"..channel, db)
pub("join", name)
event.fire("user:join", channel, name, db)
elseif action == "left" then
db[name] = nil
usercount = usercount - 1
kvstore.set("users:"..channel, db)
event.fire("user:left", channel, name, db)
pub("left", name)
if usercount == 0 then -- Teardown
kvstore.del("users:"..channel)
kvstore.del("started:"..channel)
rpc.call("log.normal", "Chat", "Channel "..channel.." seems to have lost it's userbase... :(")
return false
end
elseif action == "!" then -- ! = ATTENTION!
(msg.." "):gsub("^(%w+) (.*)", function(rpc_cmd, arguments)
rpc.call("attention:"..rpc_cmd, channel, name, arguments)
end)
else
pub(action, name, msg)
end
end
end, {
["channel"] = chan
})
kvstore.set("started:"..chan, true)
end
if (kvstore.get("users:"..chan) or {})[name] then
ws.send(ws.TextMessage, "User already existing.")
return
end
-- Fire new user event
kvstore.set("client:"..clientid, ws.con)
event.fire("chan:"..chan, "client", "join", name, clientid)
local matchfunc = function(cmd, args)
if cmd and cmd ~= "" then
if disallowed[cmd] then
ws.send(ws.TextMessage, "error * Disallowed command.")
else
event.fire("chan:"..chan, "client", cmd, name, clientid, args)
end
end
end
-- Chat loop
while true do
local p, msg, err = ws.read()
if err then
break
end
if msg then
if #msg < maxmsglen then
local matched = false
msg:gsub("^([%w!_-]-) (.-)$", function(cmd, args)
matched = true
matchfunc(cmd, args)
end)
if not matched then
msg:gsub("^([%w!_-]-)$", function(cmd)
matchfunc(cmd)
end)
end
else
ws.send(ws.TextMessage, "error * Command exceeded maximum length of "..tostring(maxmsglen)..".")
end
end
os.sleep(0.5)
end
-- Finalize
event.fire("chan:"..chan, "client", "left", name, chan, clientid)
end))
|
#!/usr/bin/env carbon
-- Lets just chat!
event = require("libs.event")
logger = require("libs.logger")
loader = require("libs.loader")
logger.log("Main", logger.normal, "Loading Init files...")
local loaded, loadtime = loader.load("init.d/*")
logger.log("Main", logger.normal, "Loaded "..tostring(loaded).." Init Files. Took "..tostring(loadtime).."s.")
-- Chat interface
srv.GET("/", mw.new(function()
-- TODO: Replace stub
content("Go away. (For now.)")
end))
-- Chat logic
srv.GET("/ws", mw.ws(function()
-- Small variables we use later.
local deflen = 10
local minlen = 1
local maxlen = 30
local maxmsglen = 1024
local disallowed = {
["join"] = true,
["left"] = true,
["error"] = true,
["info"] = true,
}
-- Require libraries we use.
event = require("libs.event")
rpc = require("libs.multirpc")
server = server or require("libs.servercheck")
local clientid = context.ClientIP() -- Use simply the client IP + Port as the ID.
-- TODO: Actual chan logic.
local name = query("name")
if name == nil or name == "" then
ws.send(ws.TextMessage, "error * Please choose a name by connecting to the WebSocket with the query argument name set to your preferred name.")
return
elseif #name > maxlen then -- Exceeds maximum name length
ws.send(ws.TextMessage, "error * Name exceeds max length.")
return
end
if not server.user_valid(name) then
ws.send(ws.TextMessage, "error * Name contains invalid characters and/or is restricted.")
return
end
local chan = query("chan") or "lobby"
-- Fail if username is already existing.
local started = kvstore.get("started:"..chan)
if not started then
rpc.call("log.normal", "Chat", "Looks like "..chan.." is getting some activity!")
event.handle("chan:"..chan, function(callee, action, name, clientid, msg)
usercount = usercount or 0
db = db or {}
action = action:lower()
local function pub(a, nme, m)
for user, userid in pairs(db) do
if user ~= name then
local wsok = kvstore.get("client:"..userid)
if wsok then
wsok.WriteMessage(1, convert.stringtocharslice(a..(nme and (" " .. nme) or "")..(m and (" " .. m) or ""))) -- Dark magic
else
event.fire("client:"..channel, "client", "left", name, clientid)
end
end
end
end
if callee == "server" then
-- Reassigned:
-- action = selector/name
-- name, clientid, msg = args
if action == "*" then -- Broadcast.
pub(name, clientid, msg) -- These are actually different things then..
else -- Target name
local cid = db[action]
if cid then
local wsok = kvstore.get("client:"..cid)
if wsok then
wsok.WriteMessage(1, convert.stringtocharslice(name..(clientid and (" " .. clientid) or "")..(msg and (" " .. msg) or ""))) -- Dark magic
else
event.fire("client:"..channel, "client", "left", name, clientid)
end
end
end
else
if action == "join" then
db[name] = clientid
usercount = usercount + 1
kvstore.set("users:"..channel, db)
pub("join", name)
event.fire("user:join", channel, name, db)
elseif action == "left" then
db[name] = nil
usercount = usercount - 1
kvstore.set("users:"..channel, db)
event.fire("user:left", channel, name, db)
pub("left", name)
if usercount == 0 then -- Teardown
kvstore.del("users:"..channel)
kvstore.del("started:"..channel)
rpc.call("log.normal", "Chat", "Channel "..channel.." seems to have lost it's userbase... :(")
return false
end
elseif action == "!" then -- ! = ATTENTION!
(msg.." "):gsub("^(%w+) (.*)", function(rpc_cmd, arguments)
rpc.call("attention:"..rpc_cmd, channel, name, arguments)
end)
else
pub(action, name, msg)
end
end
end, {
["channel"] = chan
})
kvstore.set("started:"..chan, true)
end
if (kvstore.get("users:"..chan) or {})[name] then
ws.send(ws.TextMessage, "User already existing.")
return
end
-- Fire new user event
kvstore.set("client:"..clientid, ws.con)
event.fire("chan:"..chan, "client", "join", name, clientid)
local matchfunc = function(cmd, args)
if cmd and cmd ~= "" then
if disallowed[cmd] then
ws.send(ws.TextMessage, "error * Disallowed command.")
else
event.fire("chan:"..chan, "client", cmd, name, clientid, args)
end
end
end
-- Chat loop
while true do
local p, msg, err = ws.read()
if err then
break
end
if msg then
if #msg < maxmsglen then
local matched = false
msg:gsub("^([%w!_-]-) (.-)$", function(cmd, args)
matched = true
matchfunc(cmd, args)
end)
if not matched then
msg:gsub("^([%w!_-]-)$", function(cmd)
matchfunc(cmd)
end)
end
else
ws.send(ws.TextMessage, "error * Command exceeded maximum length of "..tostring(maxmsglen)..".")
end
end
os.sleep(0.5)
end
-- Finalize
event.fire("chan:"..chan, "client", "left", name, clientid)
end))
|
Small fix for websocket errors.
|
Small fix for websocket errors.
|
Lua
|
mit
|
vifino/letsjustchat
|
b1257ee0a5d940f495b145d967302223239e8817
|
src/gamepad.lua
|
src/gamepad.lua
|
-- PibePlayer's GamePad Interface
-- by @PibePlayer
--[[How to use:
Buttons:
(1: Exit Button - 2: Up - 3: Down - 4: Left - 5: Right
6: X - 7: Z)
Practical Use:
gamepad=require "gamepad"
g=gamepad:new() --initialization
g:update() --updates itself
g:draw() --draws the buttons
g.b[n].ispressed --gets pressed state of button n
g.b[n].isnewpress --gets if pressed state of button n is new
g.b[n]:keeppressed --keeps a button pressed until :release()
g.b[n]:keepreleased--keeps a button released until :release()
g.b[n]:release --releases a :keeppressed/:keepreleased button
--]]
gamepad={}
gamepad.__index=gamepad
gamepad.exiting = false
gamepad.button={}
gamepad.button.__index=gamepad.button
function gamepad.button:new(x,y,spr,key)
tbtn={}
setmetatable(tbtn,gamepad.button)
tbtn.x=x
tbtn.y=y
tbtn.key=key
tbtn.spr=spr or 0
tbtn.keep=0
tbtn.oldpress=false
tbtn.ispressed=false
tbtn.isnewpress=false
return tbtn
end
function gamepad.button:pressed(x,y,rb,lb)
if (lb and x>=self.x and x<=self.x+16 and
y>=self.y and y<=self.y+16) or self.keep==1 or (self.key~=nil and api.key(self.key) or false) and self.keep~=2 then
return true
end
return false
end
function gamepad.button:keeppressed()
self.keep=1
end
function gamepad.button:keepreleased()
self.keep=2
end
function gamepad.button:release()
self.keep=0
end
function gamepad.button:update()
self.oldpress=self.ispressed
self.ispressed=self:pressed(api.mstat())
self.isnewpress= self.ispressed and not self.oldpress
end
function gamepad.button:draw()
if self.ispressed then
api.sspr(self.spr*8,32,8,8,self.x,self.y+2,16,16)
return
end
api.sspr(self.spr*8,24,8,8,self.x,self.y,16,16)
end
function gamepad:new()
tg={}
setmetatable(tg,gamepad)
tg.b={gamepad.button:new(15,10,7,"q"),
gamepad.button:new(30,75,0,"up"),gamepad.button:new(30,105,1,"down"),
gamepad.button:new(15,90,2,"left"),gamepad.button:new(45,90,3,"right"),
gamepad.button:new(150,105,4,"x"),gamepad.button:new(165,90,5,"z")}
return tg
end
function gamepad:update()
if self.b[1].ispressed then
gamepad.exiting = true
end
for k,v in pairs(self.b) do
self.b[k]:update()
end
end
function gamepad:draw()
for k,v in pairs(self.b) do
self.b[k]:draw()
end
end
return gamepad
|
-- PibePlayer's GamePad Interface
-- by @PibePlayer
--[[How to use:
Buttons:
(1: Exit Button - 2: Left - 3: Right - 4: Up - 5: Down
6: X - 7: Z)
Practical Use:
gamepad=require "gamepad"
g=gamepad:new() --initialization
g:update() --updates itself
g:draw() --draws the buttons
g.b[n].ispressed --gets pressed state of button n
g.b[n].isnewpress --gets if pressed state of button n is new
g.b[n]:keeppressed --keeps a button pressed until :release()
g.b[n]:keepreleased--keeps a button released until :release()
g.b[n]:release --releases a :keeppressed/:keepreleased button
--]]
gamepad={}
gamepad.__index=gamepad
gamepad.exiting = false
gamepad.button={}
gamepad.button.__index=gamepad.button
function gamepad.button:new(x,y,spr,key)
tbtn={}
setmetatable(tbtn,gamepad.button)
tbtn.x=x
tbtn.y=y
tbtn.key=key
tbtn.spr=spr or 0
tbtn.keep=0
tbtn.oldpress=false
tbtn.ispressed=false
tbtn.isnewpress=false
return tbtn
end
function gamepad.button:pressed(x,y,rb,lb)
if (lb and x>=self.x and x<=self.x+16 and
y>=self.y and y<=self.y+16) or self.keep==1 or (self.key~=nil and api.key(self.key) or false) and self.keep~=2 then
return true
end
return false
end
function gamepad.button:keeppressed()
self.keep=1
end
function gamepad.button:keepreleased()
self.keep=2
end
function gamepad.button:release()
self.keep=0
end
function gamepad.button:update()
self.oldpress=self.ispressed
self.ispressed=self:pressed(api.mstat())
self.isnewpress= self.ispressed and not self.oldpress
end
function gamepad.button:draw()
if self.ispressed then
api.sspr(self.spr*8,32,8,8,self.x,self.y+2,16,16)
return
end
api.sspr(self.spr*8,24,8,8,self.x,self.y,16,16)
end
function gamepad:new()
tg={}
setmetatable(tg,gamepad)
tg.b={gamepad.button:new(15,10,7,"q"),
gamepad.button:new(15,90,2,"left"),gamepad.button:new(45,90,3,"right"),
gamepad.button:new(30,75,0,"up"),gamepad.button:new(30,105,1,"down"),
gamepad.button:new(150,105,4,"x"),gamepad.button:new(165,90,5,"z")}
return tg
end
function gamepad:update()
if self.b[1].ispressed then
gamepad.exiting = true
end
for k,v in pairs(self.b) do
self.b[k]:update()
end
end
function gamepad:draw()
for k,v in pairs(self.b) do
self.b[k]:draw()
end
end
return gamepad
|
Fixed wrong gamepad relation between numbers and buttons
|
Fixed wrong gamepad relation between numbers and buttons
|
Lua
|
mit
|
FreeBlues/neko8
|
660ee9263287eddf480683c450fbb4d6100c36b0
|
statistics.lua
|
statistics.lua
|
field_count = 10
timeout = 0.05
function increment_or_insert(space, key, field)
retry = true
while retry do
status, result = pcall(box.update, space, key, '+p', field, 1)
if status then
--success update or tuple is not exist
retry = false
if result == nil then
--insert new tuple
tuple = {}
for i = 2, field_count do tuple[i] = 0 end
tuple[1] = os.date("%d_%m_%y")
tuple[tonumber(field)] = 1
box.insert(space, key, unpack(tuple))
end
else
--exception
if result == "Tuple is marked as read-only" then
box.fiber.sleep(timeout)
else
retry = false
print("space="..space.." key="..key.." field="..field.." :"..result)
end
end
end
end
|
field_count = 10
timeout = 0.006
max_attempts = 5
function increment_or_insert(space, key, field)
retry = true
count = 0
while retry do
status, result = pcall(box.update, space, key, '+p', field, 1)
if status then
--success update or tuple is not exist
retry = false
if result == nil then
--insert new tuple
tuple = {}
for i = 2, field_count do tuple[i] = 0 end
tuple[1] = string.sub(key, -8)
tuple[tonumber(field)] = 1
box.insert(space, key, unpack(tuple))
end
else
--exception
count = count + 1
if count == max_attempts then
print("max attempts reached for space="..space.." key="..key.." field="..field)
break
end
box.fiber.sleep(timeout)
end
end
end
|
fix date, add logging, max attempts
|
fix date, add logging, max attempts
|
Lua
|
bsd-2-clause
|
mailru/tntlua,spectrec/tntlua,grechkin-pogrebnyakov/tntlua,BHYCHIK/tntlua,derElektrobesen/tntlua
|
4e8c79aa7cb1e929d555e9721420f3a4ac386260
|
MMOCoreORB/bin/scripts/managers/jedi/village/village_jedi_manager_township.lua
|
MMOCoreORB/bin/scripts/managers/jedi/village/village_jedi_manager_township.lua
|
-- Additional Includes.
-- includeFile("village/fs_experience_converter_conv_handler.lua")
local ObjectManager = require("managers.object.object_manager")
local ScreenPlay = require("screenplays.screenplay")
-- Utils.
local Logger = require("utils.logger")
require("utils.helpers")
VillageJediManagerTownship = ScreenPlay:new {
screenplayName = "VillageJediManagerTownship"
}
local currentPhase = Object:new {phase = nil}
VILLAGE_CONFIGURATION_FILE_STRING = "./conf/villagephase.txt"
VILLAGE_PHASE_ONE = 1
VILLAGE_PHASE_TWO = 2
VILLAGE_PHASE_THREE = 3
VILLAGE_PHASE_FOUR = 4
VILLAGE_TOTAL_NUMBER_OF_PHASES = 4
local VILLAGE_PHASE_CHANGE_TIME = 120 * 1000 -- Testing value.
--local VILLAGE_PHASE_CHANGE_TIME = 3 * 7 * 24 * 60 * 60 * 1000 -- Three Weeks.
-- Key is the mobile name, value is the spawn parameters.
VillagerMobilesPhaseOne = {
quharek = {name="quharek",respawn=60, x=5373, z=78, y=-4181, header=0, cellid=0},
whip = {name="whip",respawn=60, x=5283, z=78, y=-4226, header=0, cellid=0},
captain_sarguillo = {name="captain_sarguillo",respawn=60, x=5313, z=78,y= -4161, header=0, cellid=0},
sivarra_mechaux = {name="sivarra_mechaux",respawn=60, x=5391, z=78, y=-4075, header=0, cellid=0}
}
VillagerMobiles = {
paemos = {name="paemos",respawn=60, x=5173, z=78, y=-4081, header=0, cellid=0}
}
-- Set the current Village Phase for the first time.
function VillageJediManagerTownship.setCurrentPhaseInit()
local phaseChange = hasServerEvent("VillagePhaseChange")
if (phaseChange == false) then
VillageJediManagerTownship.setCurrentPhase(VILLAGE_PHASE_ONE)
createServerEvent(VILLAGE_PHASE_CHANGE_TIME, "VillageJediManagerTownship", "switchToNextPhase", "VillagePhaseChange")
end
end
-- Set the current Village Phase.
function VillageJediManagerTownship.setCurrentPhase(nextPhase)
currentPhase.phase = nextPhase
local file = io.open(VILLAGE_CONFIGURATION_FILE_STRING, "w+")
file:write(nextPhase)
file:flush()
file:close()
end
function VillageJediManagerTownship.getCurrentPhase()
if (currentPhase.phase == nil) then
local file = io.open(VILLAGE_CONFIGURATION_FILE_STRING)
local thePhase = file:read()
VillageJediManagerTownship.setCurrentPhase(thePhase)
file:close()
end
return currentPhase.phase
end
function VillageJediManagerTownship:switchToNextPhase()
local currentPhase = VillageJediManagerTownship.getCurrentPhase()
VillageJediManagerTownship:despawnMobiles(currentPhase)
currentPhase = currentPhase + 1 % VILLAGE_TOTAL_NUMBER_OF_PHASES
VillageJediManagerTownship.setCurrentPhase(currentPhase)
VillageJediManagerTownship:spawnMobiles(currentPhase)
end
function VillageJediManagerTownship:start()
if (isZoneEnabled("dathomir")) then
Logger:log("Starting the Village Township Screenplay.", LT_INFO)
VillageJediManagerTownship.setCurrentPhaseInit()
VillageJediManagerTownship:spawnMobiles(VillageJediManagerTownship.getCurrentPhase())
end
end
-- Spawning functions.
function VillageJediManagerTownship:spawnMobiles(pCurrentPhase)
foreach(VillagerMobiles, function(mobile)
local theSpawnedMobile = spawnMobile("dathomir", value.name, value.respawn, value.x, value.z, value.y, value.header, value.cellid)
Logger:log("Spawning a Village NPC at " .. value.x .. " - " .. value.y, LT_INFO)
ObjectManager.withSceneObject(theSpawnedMobile, function(villageMobile)
writeData("village:npc:oid:" .. value.name, villageMobile:getObjectID())
Logger:log("Saving a Village NPC with a objectID of " .. villageMobile:getObjectID(), LT_INFO)
end)
end)
if (pCurrentPhase == VILLAGE_PHASE_ONE) then
foreach(VillagerMobilesPhaseOne, function(mobile)
local theSpawnedMobile = spawnMobile("dathomir", value.name, value.respawn, value.x, value.z, value.y, value.header, value.cellid)
Logger:log("Spawning a Village NPC at " .. value.x .. " - " .. value.y, LT_INFO)
ObjectManager.withSceneObject(theSpawnedMobile, function(villageMobile)
writeData("village:npc:oid:" .. value.name, villageMobile:getObjectID())
Logger:log("Saving a Village NPC with a objectID of " .. villageMobile:getObjectID(), LT_INFO)
end)
end)
end
end
-- Despawn and cleanup all possible mobiles.
function VillageJediManagerTownship:despawnMobiles(pCurrentPhase)
foreach(VillagerMobiles, function(mobile)
local objectID = readData("village:npc:oid:".. value.name)
local spawnedLookup = getSceneObject(objectID)
ObjectManager.withSceneObject(spawnedLookup, function(villageMobile)
villageMobile:destroyObjectFromWorld()
villageMobile:destroyObjectFromDatabase()
deleteData("village:npc:oid:".. value.name)
Logger:log("Despawning " .. value.name, LT_INFO)
end)
end)
foreach(VillagerMobilesPhaseOne, function(mobile)
local objectID = readData("village:npc:oid:".. value.name)
local spawnedLookup = getSceneObject(objectID)
ObjectManager.withSceneObject(spawnedLookup, function(villageMobile)
villageMobile:destroyObjectFromWorld()
villageMobile:destroyObjectFromDatabase()
deleteData("village:npc:oid:".. value.name)
Logger:log("Despawning " .. value.name, LT_INFO)
end)
end)
end
registerScreenPlay("VillageJediManagerTownship", true)
return VillageJediManagerTownship
|
-- Additional Includes.
-- includeFile("village/fs_experience_converter_conv_handler.lua")
local ObjectManager = require("managers.object.object_manager")
local ScreenPlay = require("screenplays.screenplay")
-- Utils.
local Logger = require("utils.logger")
require("utils.helpers")
VillageJediManagerTownship = ScreenPlay:new {
screenplayName = "VillageJediManagerTownship"
}
local currentPhase = Object:new {phase = nil}
VILLAGE_CONFIGURATION_FILE_STRING = "./conf/villagephase.txt"
VILLAGE_PHASE_ONE = 1
VILLAGE_PHASE_TWO = 2
VILLAGE_PHASE_THREE = 3
VILLAGE_PHASE_FOUR = 4
VILLAGE_TOTAL_NUMBER_OF_PHASES = 4
local VILLAGE_PHASE_CHANGE_TIME = 120 * 1000 -- Testing value.
--local VILLAGE_PHASE_CHANGE_TIME = 3 * 7 * 24 * 60 * 60 * 1000 -- Three Weeks.
-- Key is the mobile name, value is the spawn parameters.
VillagerMobilesPhaseOne = {
quharek = {name="quharek",respawn=60, x=5373, z=78, y=-4181, header=0, cellid=0},
whip = {name="whip",respawn=60, x=5283, z=78, y=-4226, header=0, cellid=0},
captain_sarguillo = {name="captain_sarguillo",respawn=60, x=5313, z=78,y= -4161, header=0, cellid=0},
sivarra_mechaux = {name="sivarra_mechaux",respawn=60, x=5391, z=78, y=-4075, header=0, cellid=0}
}
VillagerMobiles = {
paemos = {name="paemos",respawn=60, x=5173, z=78, y=-4081, header=0, cellid=0}
}
-- Set the current Village Phase for the first time.
function VillageJediManagerTownship.setCurrentPhaseInit()
local phaseChange = hasServerEvent("VillagePhaseChange")
if (phaseChange == false) then
VillageJediManagerTownship.setCurrentPhase(VILLAGE_PHASE_ONE)
createServerEvent(VILLAGE_PHASE_CHANGE_TIME, "VillageJediManagerTownship", "switchToNextPhase", "VillagePhaseChange")
end
end
-- Set the current Village Phase.
function VillageJediManagerTownship.setCurrentPhase(nextPhase)
currentPhase.phase = nextPhase
local file = io.open(VILLAGE_CONFIGURATION_FILE_STRING, "w+")
file:write(nextPhase)
file:flush()
file:close()
end
function VillageJediManagerTownship.getCurrentPhase()
if (currentPhase.phase == nil) then
local file = io.open(VILLAGE_CONFIGURATION_FILE_STRING)
local thePhase = file:read()
VillageJediManagerTownship.setCurrentPhase(thePhase)
file:close()
end
return currentPhase.phase
end
function VillageJediManagerTownship:switchToNextPhase()
local currentPhase = VillageJediManagerTownship.getCurrentPhase()
VillageJediManagerTownship:despawnMobiles(currentPhase)
currentPhase = currentPhase + 1 % VILLAGE_TOTAL_NUMBER_OF_PHASES
VillageJediManagerTownship.setCurrentPhase(currentPhase)
VillageJediManagerTownship:spawnMobiles(currentPhase)
end
function VillageJediManagerTownship:start()
if (isZoneEnabled("dathomir")) then
Logger:log("Starting the Village Township Screenplay.", LT_INFO)
VillageJediManagerTownship.setCurrentPhaseInit()
VillageJediManagerTownship:spawnMobiles(VillageJediManagerTownship.getCurrentPhase())
end
end
-- Spawning functions.
function VillageJediManagerTownship:spawnMobiles(pCurrentPhase)
foreach(VillagerMobiles, function(mobile)
local theSpawnedMobile = spawnMobile("dathomir", mobile.name, mobile.respawn, mobile.x, mobile.z, mobile.y, mobile.header, mobile.cellid)
Logger:log("Spawning a Village NPC at " .. mobile.x .. " - " .. mobile.y, LT_INFO)
ObjectManager.withSceneObject(theSpawnedMobile, function(villageMobile)
writeData("village:npc:oid:" .. mobile.name, villageMobile:getObjectID())
Logger:log("Saving a Village NPC with a objectID of " .. villageMobile:getObjectID(), LT_INFO)
end)
end)
if (pCurrentPhase == VILLAGE_PHASE_ONE) then
foreach(VillagerMobilesPhaseOne, function(mobile)
local theSpawnedMobile = spawnMobile("dathomir", mobile.name, mobile.respawn, mobile.x, mobile.z, mobile.y, mobile.header, mobile.cellid)
Logger:log("Spawning a Village NPC at " .. mobile.x .. " - " .. mobile.y, LT_INFO)
ObjectManager.withSceneObject(theSpawnedMobile, function(villageMobile)
writeData("village:npc:oid:" .. mobile.name, villageMobile:getObjectID())
Logger:log("Saving a Village NPC with a objectID of " .. villageMobile:getObjectID(), LT_INFO)
end)
end)
end
end
-- Despawn and cleanup all possible mobiles.
function VillageJediManagerTownship:despawnMobiles(pCurrentPhase)
foreach(VillagerMobiles, function(mobile)
local objectID = readData("village:npc:oid:".. mobile.name)
local spawnedLookup = getSceneObject(objectID)
ObjectManager.withSceneObject(spawnedLookup, function(villageMobile)
villageMobile:destroyObjectFromWorld()
villageMobile:destroyObjectFromDatabase()
deleteData("village:npc:oid:".. mobile.name)
Logger:log("Despawning " .. mobile.name, LT_INFO)
end)
end)
foreach(VillagerMobilesPhaseOne, function(mobile)
local objectID = readData("village:npc:oid:".. mobile.name)
local spawnedLookup = getSceneObject(objectID)
ObjectManager.withSceneObject(spawnedLookup, function(villageMobile)
villageMobile:destroyObjectFromWorld()
villageMobile:destroyObjectFromDatabase()
deleteData("village:npc:oid:".. mobile.name)
Logger:log("Despawning " .. mobile.name, LT_INFO)
end)
end)
end
registerScreenPlay("VillageJediManagerTownship", true)
return VillageJediManagerTownship
|
[fixed] Spawning of Villager npc's in township script.
|
[fixed] Spawning of Villager npc's in township script.
Change-Id: I342f0d60165fed4d0bf6377f6b8eceae3fc610ee
|
Lua
|
agpl-3.0
|
lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo
|
2099afdbbc40afba71f0689ae29868a8b1341c7b
|
modules/admin-full/luasrc/model/cbi/admin_network/routes.lua
|
modules/admin-full/luasrc/model/cbi/admin_network/routes.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.tools.webadmin")
m = Map("network", translate("Routes"), translate("a_n_routes1"))
local routes6 = luci.sys.net.routes6()
local bit = require "bit"
s = m:section(TypedSection, "route", translate("Static IPv4 Routes"))
s.addremove = true
s.anonymous = true
s.template = "cbi/tblsection"
iface = s:option(ListValue, "interface", translate("Interface"))
luci.tools.webadmin.cbi_add_networks(iface)
s:option(Value, "target", translate("Target"), translate("Host-<abbr title=\"Internet Protocol Address\">IP</abbr> or Network"))
s:option(Value, "netmask", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Netmask"), translate("if target is a network")).rmemepty = true
s:option(Value, "gateway", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Gateway"))
if routes6 then
s = m:section(TypedSection, "route6", translate("Static IPv6 Routes"))
s.addremove = true
s.anonymous = true
s.template = "cbi/tblsection"
iface = s:option(ListValue, "interface", translate("Interface"))
luci.tools.webadmin.cbi_add_networks(iface)
s:option(Value, "target", translate("Target"), translate("<abbr title=\"Internet Protocol Version 6\">IPv6</abbr>-Address or Network (CIDR)"))
s:option(Value, "gateway", translate("<abbr title=\"Internet Protocol Version 6\">IPv6</abbr>-Gateway")).rmempty = true
end
return m
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.tools.webadmin")
m = Map("network",
translate("Routes"),
translate("Routes specify over which interface and gateway a certain host or network " ..
"can be reached."))
local routes6 = luci.sys.net.routes6()
local bit = require "bit"
s = m:section(TypedSection, "route", translate("Static IPv4 Routes"))
s.addremove = true
s.anonymous = true
s.template = "cbi/tblsection"
iface = s:option(ListValue, "interface", translate("Interface"))
luci.tools.webadmin.cbi_add_networks(iface)
s:option(Value, "target", translate("Target"), translate("Host-<abbr title=\"Internet Protocol Address\">IP</abbr> or Network"))
s:option(Value, "netmask", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Netmask"), translate("if target is a network")).rmemepty = true
s:option(Value, "gateway", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Gateway"))
if routes6 then
s = m:section(TypedSection, "route6", translate("Static IPv6 Routes"))
s.addremove = true
s.anonymous = true
s.template = "cbi/tblsection"
iface = s:option(ListValue, "interface", translate("Interface"))
luci.tools.webadmin.cbi_add_networks(iface)
s:option(Value, "target", translate("Target"), translate("<abbr title=\"Internet Protocol Version 6\">IPv6</abbr>-Address or Network (CIDR)"))
s:option(Value, "gateway", translate("<abbr title=\"Internet Protocol Version 6\">IPv6</abbr>-Gateway")).rmempty = true
end
return m
|
modules/admin-full: fix static routes page
|
modules/admin-full: fix static routes page
|
Lua
|
apache-2.0
|
artynet/luci,slayerrensky/luci,Kyklas/luci-proto-hso,Noltari/luci,tobiaswaldvogel/luci,teslamint/luci,zhaoxx063/luci,ff94315/luci-1,aa65535/luci,chris5560/openwrt-luci,opentechinstitute/luci,wongsyrone/luci-1,Hostle/luci,teslamint/luci,jlopenwrtluci/luci,oyido/luci,dwmw2/luci,nwf/openwrt-luci,teslamint/luci,Hostle/luci,bittorf/luci,tcatm/luci,981213/luci-1,keyidadi/luci,oneru/luci,rogerpueyo/luci,obsy/luci,harveyhu2012/luci,lbthomsen/openwrt-luci,bittorf/luci,wongsyrone/luci-1,Wedmer/luci,harveyhu2012/luci,aircross/OpenWrt-Firefly-LuCI,Hostle/openwrt-luci-multi-user,hnyman/luci,palmettos/test,nwf/openwrt-luci,ollie27/openwrt_luci,tobiaswaldvogel/luci,fkooman/luci,forward619/luci,sujeet14108/luci,remakeelectric/luci,lcf258/openwrtcn,oneru/luci,LazyZhu/openwrt-luci-trunk-mod,LazyZhu/openwrt-luci-trunk-mod,LuttyYang/luci,forward619/luci,nmav/luci,oneru/luci,jlopenwrtluci/luci,maxrio/luci981213,forward619/luci,oyido/luci,Hostle/openwrt-luci-multi-user,LazyZhu/openwrt-luci-trunk-mod,Hostle/openwrt-luci-multi-user,joaofvieira/luci,fkooman/luci,zhaoxx063/luci,cshore/luci,sujeet14108/luci,openwrt-es/openwrt-luci,Sakura-Winkey/LuCI,tcatm/luci,RedSnake64/openwrt-luci-packages,jchuang1977/luci-1,florian-shellfire/luci,thess/OpenWrt-luci,palmettos/cnLuCI,sujeet14108/luci,teslamint/luci,dismantl/luci-0.12,openwrt/luci,Hostle/openwrt-luci-multi-user,artynet/luci,tobiaswaldvogel/luci,urueedi/luci,Hostle/luci,marcel-sch/luci,chris5560/openwrt-luci,obsy/luci,palmettos/cnLuCI,cshore-firmware/openwrt-luci,urueedi/luci,cshore-firmware/openwrt-luci,cshore/luci,jorgifumi/luci,david-xiao/luci,jlopenwrtluci/luci,aa65535/luci,cappiewu/luci,nwf/openwrt-luci,harveyhu2012/luci,oneru/luci,Kyklas/luci-proto-hso,MinFu/luci,cshore/luci,tcatm/luci,palmettos/test,openwrt-es/openwrt-luci,artynet/luci,ff94315/luci-1,tobiaswaldvogel/luci,slayerrensky/luci,keyidadi/luci,lcf258/openwrtcn,jlopenwrtluci/luci,kuoruan/luci,forward619/luci,bittorf/luci,cshore-firmware/openwrt-luci,hnyman/luci,kuoruan/lede-luci,jchuang1977/luci-1,zhaoxx063/luci,dismantl/luci-0.12,maxrio/luci981213,Wedmer/luci,bright-things/ionic-luci,ollie27/openwrt_luci,ReclaimYourPrivacy/cloak-luci,bright-things/ionic-luci,joaofvieira/luci,NeoRaider/luci,remakeelectric/luci,daofeng2015/luci,tobiaswaldvogel/luci,david-xiao/luci,sujeet14108/luci,palmettos/test,opentechinstitute/luci,deepak78/new-luci,ff94315/luci-1,aa65535/luci,Sakura-Winkey/LuCI,shangjiyu/luci-with-extra,kuoruan/lede-luci,cappiewu/luci,marcel-sch/luci,kuoruan/luci,cshore-firmware/openwrt-luci,wongsyrone/luci-1,bright-things/ionic-luci,Sakura-Winkey/LuCI,Hostle/openwrt-luci-multi-user,deepak78/new-luci,LazyZhu/openwrt-luci-trunk-mod,981213/luci-1,hnyman/luci,thesabbir/luci,tobiaswaldvogel/luci,Hostle/luci,obsy/luci,nmav/luci,981213/luci-1,aa65535/luci,cshore/luci,palmettos/cnLuCI,aa65535/luci,ollie27/openwrt_luci,chris5560/openwrt-luci,Noltari/luci,nwf/openwrt-luci,schidler/ionic-luci,db260179/openwrt-bpi-r1-luci,remakeelectric/luci,oyido/luci,oyido/luci,urueedi/luci,RuiChen1113/luci,fkooman/luci,lbthomsen/openwrt-luci,cshore-firmware/openwrt-luci,lcf258/openwrtcn,thesabbir/luci,jorgifumi/luci,nmav/luci,jlopenwrtluci/luci,slayerrensky/luci,Sakura-Winkey/LuCI,dwmw2/luci,thesabbir/luci,Sakura-Winkey/LuCI,RuiChen1113/luci,daofeng2015/luci,ollie27/openwrt_luci,NeoRaider/luci,dwmw2/luci,Wedmer/luci,opentechinstitute/luci,jorgifumi/luci,hnyman/luci,artynet/luci,schidler/ionic-luci,sujeet14108/luci,NeoRaider/luci,rogerpueyo/luci,wongsyrone/luci-1,chris5560/openwrt-luci,mumuqz/luci,taiha/luci,openwrt-es/openwrt-luci,dismantl/luci-0.12,opentechinstitute/luci,ReclaimYourPrivacy/cloak-luci,male-puppies/luci,urueedi/luci,981213/luci-1,palmettos/cnLuCI,joaofvieira/luci,LuttyYang/luci,rogerpueyo/luci,981213/luci-1,obsy/luci,nmav/luci,Noltari/luci,hnyman/luci,mumuqz/luci,urueedi/luci,hnyman/luci,thesabbir/luci,ReclaimYourPrivacy/cloak-luci,mumuqz/luci,florian-shellfire/luci,forward619/luci,deepak78/new-luci,bittorf/luci,cshore-firmware/openwrt-luci,lbthomsen/openwrt-luci,openwrt-es/openwrt-luci,taiha/luci,kuoruan/lede-luci,artynet/luci,thesabbir/luci,MinFu/luci,david-xiao/luci,zhaoxx063/luci,daofeng2015/luci,cshore-firmware/openwrt-luci,palmettos/cnLuCI,thess/OpenWrt-luci,jchuang1977/luci-1,openwrt/luci,keyidadi/luci,fkooman/luci,taiha/luci,aircross/OpenWrt-Firefly-LuCI,florian-shellfire/luci,openwrt-es/openwrt-luci,palmettos/test,aa65535/luci,RedSnake64/openwrt-luci-packages,maxrio/luci981213,obsy/luci,ReclaimYourPrivacy/cloak-luci,david-xiao/luci,deepak78/new-luci,shangjiyu/luci-with-extra,fkooman/luci,mumuqz/luci,kuoruan/luci,bright-things/ionic-luci,rogerpueyo/luci,RuiChen1113/luci,keyidadi/luci,wongsyrone/luci-1,981213/luci-1,openwrt-es/openwrt-luci,kuoruan/luci,palmettos/cnLuCI,aircross/OpenWrt-Firefly-LuCI,tcatm/luci,keyidadi/luci,hnyman/luci,urueedi/luci,artynet/luci,palmettos/cnLuCI,wongsyrone/luci-1,marcel-sch/luci,david-xiao/luci,openwrt-es/openwrt-luci,ReclaimYourPrivacy/cloak-luci,ollie27/openwrt_luci,chris5560/openwrt-luci,schidler/ionic-luci,nwf/openwrt-luci,Hostle/luci,daofeng2015/luci,florian-shellfire/luci,NeoRaider/luci,nmav/luci,remakeelectric/luci,Hostle/luci,LazyZhu/openwrt-luci-trunk-mod,lcf258/openwrtcn,RedSnake64/openwrt-luci-packages,nmav/luci,rogerpueyo/luci,openwrt-es/openwrt-luci,jchuang1977/luci-1,LuttyYang/luci,dwmw2/luci,obsy/luci,thesabbir/luci,teslamint/luci,bright-things/ionic-luci,chris5560/openwrt-luci,cshore/luci,shangjiyu/luci-with-extra,Sakura-Winkey/LuCI,openwrt/luci,lcf258/openwrtcn,RuiChen1113/luci,LuttyYang/luci,jlopenwrtluci/luci,maxrio/luci981213,thesabbir/luci,palmettos/test,oyido/luci,ReclaimYourPrivacy/cloak-luci,lbthomsen/openwrt-luci,remakeelectric/luci,NeoRaider/luci,openwrt/luci,male-puppies/luci,tobiaswaldvogel/luci,slayerrensky/luci,rogerpueyo/luci,slayerrensky/luci,nwf/openwrt-luci,ff94315/luci-1,rogerpueyo/luci,jlopenwrtluci/luci,urueedi/luci,nwf/openwrt-luci,bittorf/luci,RuiChen1113/luci,Wedmer/luci,openwrt/luci,keyidadi/luci,shangjiyu/luci-with-extra,jlopenwrtluci/luci,fkooman/luci,MinFu/luci,male-puppies/luci,kuoruan/luci,Hostle/luci,aircross/OpenWrt-Firefly-LuCI,bright-things/ionic-luci,artynet/luci,taiha/luci,taiha/luci,daofeng2015/luci,tcatm/luci,teslamint/luci,cshore-firmware/openwrt-luci,wongsyrone/luci-1,Wedmer/luci,jchuang1977/luci-1,teslamint/luci,cshore/luci,lbthomsen/openwrt-luci,joaofvieira/luci,aa65535/luci,obsy/luci,jorgifumi/luci,schidler/ionic-luci,LuttyYang/luci,palmettos/test,schidler/ionic-luci,ff94315/luci-1,tcatm/luci,joaofvieira/luci,mumuqz/luci,nmav/luci,tobiaswaldvogel/luci,kuoruan/lede-luci,bright-things/ionic-luci,male-puppies/luci,opentechinstitute/luci,oneru/luci,cappiewu/luci,schidler/ionic-luci,jchuang1977/luci-1,mumuqz/luci,marcel-sch/luci,slayerrensky/luci,david-xiao/luci,NeoRaider/luci,hnyman/luci,taiha/luci,sujeet14108/luci,opentechinstitute/luci,chris5560/openwrt-luci,MinFu/luci,aircross/OpenWrt-Firefly-LuCI,NeoRaider/luci,harveyhu2012/luci,lcf258/openwrtcn,taiha/luci,ollie27/openwrt_luci,deepak78/new-luci,dismantl/luci-0.12,jorgifumi/luci,oyido/luci,artynet/luci,taiha/luci,david-xiao/luci,openwrt/luci,bittorf/luci,tcatm/luci,cappiewu/luci,florian-shellfire/luci,tcatm/luci,kuoruan/lede-luci,male-puppies/luci,Hostle/openwrt-luci-multi-user,kuoruan/luci,LazyZhu/openwrt-luci-trunk-mod,Kyklas/luci-proto-hso,teslamint/luci,ollie27/openwrt_luci,marcel-sch/luci,oneru/luci,fkooman/luci,db260179/openwrt-bpi-r1-luci,maxrio/luci981213,daofeng2015/luci,artynet/luci,jorgifumi/luci,dwmw2/luci,kuoruan/luci,dwmw2/luci,palmettos/test,RuiChen1113/luci,lcf258/openwrtcn,opentechinstitute/luci,shangjiyu/luci-with-extra,schidler/ionic-luci,ff94315/luci-1,Wedmer/luci,kuoruan/lede-luci,marcel-sch/luci,db260179/openwrt-bpi-r1-luci,rogerpueyo/luci,lbthomsen/openwrt-luci,thess/OpenWrt-luci,male-puppies/luci,keyidadi/luci,remakeelectric/luci,jorgifumi/luci,shangjiyu/luci-with-extra,florian-shellfire/luci,thess/OpenWrt-luci,bittorf/luci,schidler/ionic-luci,LazyZhu/openwrt-luci-trunk-mod,Sakura-Winkey/LuCI,Hostle/openwrt-luci-multi-user,cshore/luci,nwf/openwrt-luci,jorgifumi/luci,sujeet14108/luci,florian-shellfire/luci,cappiewu/luci,aa65535/luci,keyidadi/luci,Noltari/luci,Kyklas/luci-proto-hso,shangjiyu/luci-with-extra,Noltari/luci,db260179/openwrt-bpi-r1-luci,joaofvieira/luci,oyido/luci,dismantl/luci-0.12,sujeet14108/luci,LazyZhu/openwrt-luci-trunk-mod,dismantl/luci-0.12,Sakura-Winkey/LuCI,deepak78/new-luci,fkooman/luci,slayerrensky/luci,db260179/openwrt-bpi-r1-luci,opentechinstitute/luci,urueedi/luci,cappiewu/luci,oneru/luci,zhaoxx063/luci,dismantl/luci-0.12,981213/luci-1,zhaoxx063/luci,nmav/luci,db260179/openwrt-bpi-r1-luci,thess/OpenWrt-luci,aircross/OpenWrt-Firefly-LuCI,cshore/luci,LuttyYang/luci,Wedmer/luci,RedSnake64/openwrt-luci-packages,Noltari/luci,ReclaimYourPrivacy/cloak-luci,Hostle/openwrt-luci-multi-user,palmettos/cnLuCI,remakeelectric/luci,Noltari/luci,maxrio/luci981213,kuoruan/lede-luci,RuiChen1113/luci,kuoruan/luci,MinFu/luci,obsy/luci,thess/OpenWrt-luci,joaofvieira/luci,LuttyYang/luci,openwrt/luci,RedSnake64/openwrt-luci-packages,MinFu/luci,oyido/luci,zhaoxx063/luci,harveyhu2012/luci,RedSnake64/openwrt-luci-packages,oneru/luci,mumuqz/luci,maxrio/luci981213,jchuang1977/luci-1,kuoruan/lede-luci,deepak78/new-luci,ollie27/openwrt_luci,florian-shellfire/luci,MinFu/luci,ff94315/luci-1,Kyklas/luci-proto-hso,jchuang1977/luci-1,Wedmer/luci,lcf258/openwrtcn,forward619/luci,harveyhu2012/luci,lcf258/openwrtcn,Kyklas/luci-proto-hso,marcel-sch/luci,david-xiao/luci,lbthomsen/openwrt-luci,db260179/openwrt-bpi-r1-luci,male-puppies/luci,deepak78/new-luci,shangjiyu/luci-with-extra,harveyhu2012/luci,chris5560/openwrt-luci,ReclaimYourPrivacy/cloak-luci,forward619/luci,Hostle/luci,LuttyYang/luci,aircross/OpenWrt-Firefly-LuCI,NeoRaider/luci,zhaoxx063/luci,daofeng2015/luci,thess/OpenWrt-luci,Noltari/luci,dwmw2/luci,palmettos/test,marcel-sch/luci,lbthomsen/openwrt-luci,wongsyrone/luci-1,db260179/openwrt-bpi-r1-luci,nmav/luci,RuiChen1113/luci,mumuqz/luci,cappiewu/luci,maxrio/luci981213,Noltari/luci,Kyklas/luci-proto-hso,dwmw2/luci,bittorf/luci,thess/OpenWrt-luci,openwrt/luci,ff94315/luci-1,male-puppies/luci,remakeelectric/luci,forward619/luci,lcf258/openwrtcn,daofeng2015/luci,RedSnake64/openwrt-luci-packages,cappiewu/luci,MinFu/luci,joaofvieira/luci,thesabbir/luci,bright-things/ionic-luci,slayerrensky/luci
|
c0566411d4bd70caab0ddcf62b1510f46cbf0a8e
|
spec/os_spec.lua
|
spec/os_spec.lua
|
describe('lift.os', function()
local WAIT = 100 -- how much to wait for a process to finish
if os.getenv('CI') then
WAIT = 200
end
local os = require 'lift.os'
local ls = require 'lift.string'
local async = require 'lift.async'
local config = require 'lift.config'
local su = require 'spec.util'
it('offers sh() to execute a shell command', su.async(function()
local out, err = assert(os.sh'echo Hello world!|cat')
assert.equal('Hello world!\n', out)
assert.equal('', err)
out, err = assert(os.sh[[lua -e "io.write'Hello from stdout'"]])
assert.equal('Hello from stdout', out)
assert.equal('', err)
out, err = assert(os.sh[[lua -e "io.stderr:write'Hello from stderr'"]])
assert.equal('', out)
assert.equal('Hello from stderr', err)
out, err = os.sh'invalid_cmd error'
assert.Nil(out)
assert.match('shell command failed', err)
end))
describe("child processes", function()
it("can be started with spawn()", su.async(function()
local c = assert(os.spawn{file = config.LUA_EXE_PATH, '-e', 'os.exit(7)',
stdin = 'ignore', stdout = 'ignore', stderr = 'ignore'})
assert.is_number(c.pid)
assert.is_nil(c.status)
assert.is_nil(c.signal)
async.sleep(WAIT)
assert.equal(7, c.status)
assert.equal(0, c.signal)
end))
it("can be terminated with :kill()", su.async(function()
local c = assert(os.spawn{file = 'sleep', '3',
stdin = 'ignore', stdout = 'ignore', stderr = 'ignore'})
assert.is_number(c.pid)
assert.is_nil(c.status)
assert.is_nil(c.signal)
c:kill()
async.sleep(WAIT)
assert.equal(15, c.signal) -- sigterm
assert.error(function() c:kill() end,
'process:kill() called after process termination')
end))
it("can inherit fds from parent and be waited for", su.async(function()
local c = assert(os.spawn{file = config.LUA_EXE_PATH,
'-e', 'print[[Hello from child process]]',
stdin = 'ignore', stdout = 'inherit', stderr = 'inherit'})
assert.Nil(c.status)
c:wait()
assert.equal(0, c.status, c.signal)
end))
it("can be waited for with a timeout", su.async(function()
-- with enough time
local c = assert(os.spawn{file = config.LUA_EXE_PATH,
'-e', 'print[[this is fast]]',
stdin = 'ignore', stdout = 'ignore', stderr = 'ignore'})
assert.Nil(c.status)
local status, signal = c:wait(300)
assert.equal(0, status, signal)
-- without enough time
c = assert(os.spawn{file = 'sleep', '5',
stdin = 'ignore', stdout = 'ignore', stderr = 'ignore'})
assert.Nil(c.status)
status, signal = c:wait(300)
c:kill()
assert.False(status)
assert.equal(signal, 'timed out')
end))
it("can be read from (stdout, stderr)", su.async(function()
local c = assert(os.spawn{file = config.LUA_EXE_PATH,
'-e', 'print[[Hello world]]', stdin = 'ignore'})
assert.Nil(c:try_read())
assert.Nil(c.stderr:try_read())
c:wait() -- await exit before reading
assert.equal('Hello world\n', ls.native_to_lf(c:try_read()))
assert.Nil(c.stderr:try_read())
end))
it("can be written to (stdin) and read from (stdout)", su.async(function()
local c = assert(os.spawn{file = 'cat'})
c:write('One')
c.stdin:write('Two')
c:write() -- shuts down stdin, causing 'cat' to exit
assert.Nil(c.stdout:try_read())
assert.Nil(c.stderr:try_read())
c:wait() -- await exit before reading
assert.equal('OneTwo', c:try_read())
assert.Nil(c.stderr:try_read())
end))
it("can be written to (stdin) and read from (stderr)", su.async(function()
local c = assert(os.spawn{file = 'lua',
'-e', 'io.stderr:write(io.read())', stdout = 'ignore'})
c:write('Hello from stderr')
c:write() -- shuts down stdin, causing the process to exit
assert.Nil(c.stdout)
assert.Nil(c.stderr:try_read())
c:wait() -- await exit before reading
assert.equal('Hello from stderr', c.stderr:try_read())
end))
it("can be written to (stdin) and read from (stdout) synchronously", su.async(function()
local c = assert(os.spawn{file = 'cat'})
c:write('One')
c.stdin:write('Two')
assert.equal('OneTwo', c:read())
c:write('Three')
assert.equal('Three', c:read())
c:write()
assert.Nil(c:read())
assert.Nil(c.stderr:read())
end))
it("can be piped to another process", su.async(function()
local echo1 = assert(os.spawn{file = config.LUA_EXE_PATH,
'-e', 'io.write[[OneTwoThree]]', stdin = 'ignore'})
local echo2 = assert(os.spawn{file = config.LUA_EXE_PATH,
'-e', 'io.write[[FourFive]]', stdin = 'ignore'})
local cat1 = assert(os.spawn{file = 'cat'})
local cat2 = assert(os.spawn{file = 'cat'})
cat1:pipe(cat2)
echo1:pipe(cat1, true) -- pipe to cat1 and keep cat1 open
echo1.stdout:wait_end()
echo2:pipe(cat1) -- pipe to cat1 and shut down cat1
echo2.stdout:wait_end()
local sb = {cat2:read(), cat2:read()}
assert.equal('OneTwoThreeFourFive', table.concat(sb))
end))
end)
end)
|
describe('lift.os', function()
local WAIT = 100 -- how much to wait for a process to finish
if os.getenv('CI') then
WAIT = 200
end
local os = require 'lift.os'
local ls = require 'lift.string'
local async = require 'lift.async'
local config = require 'lift.config'
local su = require 'spec.util'
it('offers sh() to execute a shell command', su.async(function()
local out, err = assert(os.sh'echo Hello world!|cat')
assert.equal('Hello world!\n', out)
assert.equal('', err)
out, err = assert(os.sh[[lua -e "io.write'Hello from stdout'"]])
assert.equal('Hello from stdout', out)
assert.equal('', err)
out, err = assert(os.sh[[lua -e "io.stderr:write'Hello from stderr'"]])
assert.equal('', out)
assert.equal('Hello from stderr', err)
out, err = os.sh'invalid_cmd error'
assert.Nil(out)
assert.match('shell command failed', err)
end))
describe("child processes", function()
it("can be started with spawn()", su.async(function()
local c = assert(os.spawn{file = config.LUA_EXE_PATH, '-e', 'os.exit(7)',
stdin = 'ignore', stdout = 'ignore', stderr = 'ignore'})
assert.is_number(c.pid)
assert.is_nil(c.status)
assert.is_nil(c.signal)
async.sleep(WAIT)
assert.equal(7, c.status)
assert.equal(0, c.signal)
end))
it("can be terminated with :kill()", su.async(function()
local c = assert(os.spawn{file = 'sleep', '3',
stdin = 'ignore', stdout = 'ignore', stderr = 'ignore'})
assert.is_number(c.pid)
assert.is_nil(c.status)
assert.is_nil(c.signal)
c:kill()
async.sleep(WAIT)
assert.equal(15, c.signal) -- sigterm
assert.error(function() c:kill() end,
'process:kill() called after process termination')
end))
it("can inherit fds from parent and be waited for", su.async(function()
local c = assert(os.spawn{file = config.LUA_EXE_PATH,
'-e', 'print[[Hello from child process]]',
stdin = 'ignore', stdout = 'inherit', stderr = 'inherit'})
assert.Nil(c.status)
c:wait()
assert.equal(0, c.status, c.signal)
end))
it("can be waited for with a timeout", su.async(function()
-- with enough time
local c = assert(os.spawn{file = config.LUA_EXE_PATH,
'-e', 'print[[this is fast]]',
stdin = 'ignore', stdout = 'ignore', stderr = 'ignore'})
assert.Nil(c.status)
local status, signal = c:wait(300)
assert.equal(0, status, signal)
-- without enough time
c = assert(os.spawn{file = 'sleep', '5',
stdin = 'ignore', stdout = 'ignore', stderr = 'ignore'})
assert.Nil(c.status)
status, signal = c:wait(300)
c:kill()
assert.False(status)
assert.equal(signal, 'timed out')
end))
it("can be read from (stdout, stderr)", su.async(function()
local c = assert(os.spawn{file = config.LUA_EXE_PATH,
'-e', 'print[[Hello world]]', stdin = 'ignore'})
assert.Nil(c:try_read())
assert.Nil(c.stderr:try_read())
c:wait() -- await exit before reading
assert.equal('Hello world\n', ls.native_to_lf(c:try_read()))
assert.Nil(c.stderr:try_read())
end))
it("can be written to (stdin) and read from (stdout)", su.async(function()
local c = assert(os.spawn{file = 'cat'})
c:write('One')
c.stdin:write('Two')
c:write() -- shuts down stdin, causing 'cat' to exit
assert.Nil(c.stdout:try_read())
assert.Nil(c.stderr:try_read())
c:wait() -- await exit before reading
local sb = {c:try_read(), c:try_read()}
assert.equal('OneTwo', table.concat(sb))
assert.Nil(c.stderr:try_read())
end))
it("can be written to (stdin) and read from (stderr)", su.async(function()
local c = assert(os.spawn{file = 'lua',
'-e', 'io.stderr:write(io.read())', stdout = 'ignore'})
c:write('Hello from stderr')
c:write() -- shuts down stdin, causing the process to exit
assert.Nil(c.stdout)
assert.Nil(c.stderr:try_read())
c:wait() -- await exit before reading
assert.equal('Hello from stderr', c.stderr:try_read())
end))
it("can be written to (stdin) and read from (stdout) synchronously", su.async(function()
local c = assert(os.spawn{file = 'cat'})
c:write('One')
c.stdin:write('Two')
assert.equal('OneTwo', c:read())
c:write('Three')
assert.equal('Three', c:read())
c:write()
assert.Nil(c:read())
assert.Nil(c.stderr:read())
end))
it("can be piped to another process", su.async(function()
local echo1 = assert(os.spawn{file = config.LUA_EXE_PATH,
'-e', 'io.write[[OneTwoThree]]', stdin = 'ignore'})
local echo2 = assert(os.spawn{file = config.LUA_EXE_PATH,
'-e', 'io.write[[FourFive]]', stdin = 'ignore'})
local cat1 = assert(os.spawn{file = 'cat'})
local cat2 = assert(os.spawn{file = 'cat'})
cat1:pipe(cat2)
echo1:pipe(cat1, true) -- pipe to cat1 and keep cat1 open
echo1.stdout:wait_end()
echo2:pipe(cat1) -- pipe to cat1 and shut down cat1
echo2.stdout:wait_end()
local sb = {cat2:read(), cat2:read()}
assert.equal('OneTwoThreeFourFive', table.concat(sb))
end))
end)
end)
|
Fix test
|
Fix test
|
Lua
|
mit
|
tbastos/lift
|
f61e5a22d7d76561cfb10a8d83e14e324d2a772a
|
src/luarocks/build/cmake.lua
|
src/luarocks/build/cmake.lua
|
--- Build back-end for CMake-based modules.
--module("luarocks.build.cmake", package.seeall)
local cmake = {}
local fs = require("luarocks.fs")
local util = require("luarocks.util")
local cfg = require("luarocks.cfg")
--- Driver function for the "cmake" build back-end.
-- @param rockspec table: the loaded rockspec.
-- @return boolean or (nil, string): true if no errors ocurred,
-- nil and an error message otherwise.
function cmake.run(rockspec)
assert(type(rockspec) == "table")
local build = rockspec.build
local variables = build.variables or {}
-- Pass Env variables
variables.CMAKE_MODULE_PATH=os.getenv("CMAKE_MODULE_PATH")
variables.CMAKE_LIBRARY_PATH=os.getenv("CMAKE_LIBRARY_PATH")
variables.CMAKE_INCLUDE_PATH=os.getenv("CMAKE_INCLUDE_PATH")
util.variable_substitutions(variables, rockspec.variables)
local ok, err_msg = fs.is_tool_available(rockspec.variables.CMAKE, "CMake")
if not ok then
return nil, err_msg
end
-- If inline cmake is present create CMakeLists.txt from it.
if type(build.cmake) == "string" then
local cmake_handler = assert(io.open(fs.current_dir().."/CMakeLists.txt", "w"))
cmake_handler:write(build.cmake)
cmake_handler:close()
end
-- Execute cmake with variables.
local args = ""
if cfg.cmake_generator then
args = args .. ' -G"'..cfg.cmake_generator.. '"'
end
for k,v in pairs(variables) do
args = args .. ' -D' ..k.. '="' ..v.. '"'
end
if not fs.execute_string(rockspec.variables.CMAKE.." -H. -Bbuild.luarocks "..args) then
return nil, "Failed cmake."
end
if not fs.execute_string(rockspec.variables.CMAKE.." --build build.luarocks --config Release") then
return nil, "Failed building."
end
if not fs.execute_string(rockspec.variables.CMAKE.." --build build.luarocks --target install --config Release") then
return nil, "Failed installing."
end
return true
end
return cmake
|
--- Build back-end for CMake-based modules.
--module("luarocks.build.cmake", package.seeall)
local cmake = {}
local fs = require("luarocks.fs")
local util = require("luarocks.util")
local cfg = require("luarocks.cfg")
--- Driver function for the "cmake" build back-end.
-- @param rockspec table: the loaded rockspec.
-- @return boolean or (nil, string): true if no errors ocurred,
-- nil and an error message otherwise.
function cmake.run(rockspec)
assert(type(rockspec) == "table")
local build = rockspec.build
local variables = build.variables or {}
-- Pass Env variables
variables.CMAKE_MODULE_PATH=os.getenv("CMAKE_MODULE_PATH")
variables.CMAKE_LIBRARY_PATH=os.getenv("CMAKE_LIBRARY_PATH")
variables.CMAKE_INCLUDE_PATH=os.getenv("CMAKE_INCLUDE_PATH")
util.variable_substitutions(variables, rockspec.variables)
local ok, err_msg = fs.is_tool_available(rockspec.variables.CMAKE, "CMake")
if not ok then
return nil, err_msg
end
-- If inline cmake is present create CMakeLists.txt from it.
if type(build.cmake) == "string" then
local cmake_handler = assert(io.open(fs.current_dir().."/CMakeLists.txt", "w"))
cmake_handler:write(build.cmake)
cmake_handler:close()
end
-- Execute cmake with variables.
local args = ""
if cfg.cmake_generator then
args = args .. ' -G"'..cfg.cmake_generator.. '"'
end
for k,v in pairs(variables) do
args = args .. ' -D' ..k.. '="' ..v.. '"'
end
-- Generate 64 bit build if appropiate.
if not not cfg.arch:match("%-x86_64$") then
args = args .. " -DCMAKE_GENERATOR_PLATFORM=x64"
end
if not fs.execute_string(rockspec.variables.CMAKE.." -H. -Bbuild.luarocks "..args) then
return nil, "Failed cmake."
end
if not fs.execute_string(rockspec.variables.CMAKE.." --build build.luarocks --config Release") then
return nil, "Failed building."
end
if not fs.execute_string(rockspec.variables.CMAKE.." --build build.luarocks --target install --config Release") then
return nil, "Failed installing."
end
return true
end
return cmake
|
cmake backend: Generate 64 bits build when appropiate
|
cmake backend: Generate 64 bits build when appropiate
Adds -DCMAKE_GENERATOR_PLATFORM=x64 when needed. It seems that
CMake does not do that by default (although I might be wrong on that).
fixes #382
|
Lua
|
mit
|
robooo/luarocks,robooo/luarocks,rrthomas/luarocks,coderstudy/luarocks,luarocks/luarocks,lxbgit/luarocks,ignacio/luarocks,rrthomas/luarocks,xpol/luainstaller,ignacio/luarocks,ignacio/luarocks,aryajur/luarocks,usstwxy/luarocks,keplerproject/luarocks,xpol/luavm,xpol/luainstaller,xpol/luarocks,robooo/luarocks,starius/luarocks,tst2005/luarocks,xiaq/luarocks,xiaq/luarocks,xiaq/luarocks,xpol/luavm,xpol/luavm,luarocks/luarocks,tst2005/luarocks,lxbgit/luarocks,tst2005/luarocks,tarantool/luarocks,keplerproject/luarocks,xpol/luavm,usstwxy/luarocks,coderstudy/luarocks,usstwxy/luarocks,xpol/luarocks,luarocks/luarocks,aryajur/luarocks,tarantool/luarocks,tarantool/luarocks,lxbgit/luarocks,starius/luarocks,keplerproject/luarocks,xiaq/luarocks,rrthomas/luarocks,xpol/luainstaller,ignacio/luarocks,robooo/luarocks,coderstudy/luarocks,xpol/luavm,keplerproject/luarocks,coderstudy/luarocks,rrthomas/luarocks,xpol/luarocks,aryajur/luarocks,aryajur/luarocks,xpol/luarocks,usstwxy/luarocks,xpol/luainstaller,lxbgit/luarocks,tst2005/luarocks,starius/luarocks,starius/luarocks
|
b1f7c2486be9bf054eabc4181944133588127778
|
premake4.lua
|
premake4.lua
|
local action = _ACTION or ""
solution "island"
location ( "build" )
configurations { "Debug", "Release" }
platforms {"native", "x64", "x32"}
targetdir("build")
language "C"
configuration "vs*"
defines { "_CRT_SECURE_NO_WARNINGS" }
configuration "Debug"
defines { "DEBUG" }
flags { "Symbols"}
configuration "Release"
defines { "NDEBUG" }
flags { "Optimize"}
project "glfw"
kind "StaticLib"
includedirs { "3rdparty/glfw/include" }
files
{
"3rdparty/glfw/src/clipboard.c",
"3rdparty/glfw/src/context.c",
"3rdparty/glfw/src/gamma.c",
"3rdparty/glfw/src/init.c",
"3rdparty/glfw/src/input.c",
"3rdparty/glfw/src/joystick.c",
"3rdparty/glfw/src/monitor.c",
"3rdparty/glfw/src/time.c",
"3rdparty/glfw/src/window.c",
"3rdparty/glfw/src/input.c",
"3rdparty/glfw/src/input.c",
}
targetdir("build")
defines { "_GLFW_USE_OPENGL" }
configuration "windows"
defines { "_GLFW_WIN32", "_GLFW_WGL" }
files
{
"3rdparty/glfw/src/win32*.c",
"3rdparty/glfw/src/wgl_context.c",
"3rdparty/glfw/src/winmm_joystick.c",
}
project "glew"
kind "StaticLib"
includedirs { "3rdparty/glew" }
files { "3rdparty/glew/*.c" }
defines "GLEW_STATIC"
project "nanovg"
kind "StaticLib"
includedirs { "3rdparty/nanovg/src" }
files { "3rdparty/nanovg/src/*.c" }
project "libuv"
kind "StaticLib"
includedirs { "3rdparty/libuv/include" }
files { "3rdparty/libuv/src/*.c", "3rdparty/libuv/src/win/*.c" }
project "lua"
os.copyfile("3rdparty/lua/src/luaconf.h.orig", "3rdparty/lua/src/luaconf.h")
kind "StaticLib"
includedirs { "3rdparty/lua/src" }
files { "3rdparty/lua/src/*.c"}
excludes
{
"3rdparty/lua/src/loadlib_rel.c",
"3rdparty/lua/src/lua.c",
"3rdparty/lua/src/luac.c",
"3rdparty/lua/src/print.c",
}
|
local action = _ACTION or ""
solution "island"
location (".project")
configurations { "Debug", "Release" }
platforms {"native", "x64", "x32"}
targetdir ("bin")
language "C"
configuration "vs*"
defines { "_CRT_SECURE_NO_WARNINGS" }
configuration "Debug"
targetsuffix "_d"
defines { "DEBUG" }
flags { "Symbols"}
configuration "Release"
defines { "NDEBUG" }
flags { "Optimize"}
project "glfw"
kind "StaticLib"
includedirs { "3rdparty/glfw/include" }
files
{
"3rdparty/glfw/src/clipboard.c",
"3rdparty/glfw/src/context.c",
"3rdparty/glfw/src/gamma.c",
"3rdparty/glfw/src/init.c",
"3rdparty/glfw/src/input.c",
"3rdparty/glfw/src/joystick.c",
"3rdparty/glfw/src/monitor.c",
"3rdparty/glfw/src/time.c",
"3rdparty/glfw/src/window.c",
"3rdparty/glfw/src/input.c",
"3rdparty/glfw/src/input.c",
}
targetdir("build")
defines { "_GLFW_USE_OPENGL" }
configuration "windows"
defines { "_GLFW_WIN32", "_GLFW_WGL" }
files
{
"3rdparty/glfw/src/win32*.c",
"3rdparty/glfw/src/wgl_context.c",
"3rdparty/glfw/src/winmm_joystick.c",
}
project "glew"
kind "StaticLib"
includedirs { "3rdparty/glew" }
files { "3rdparty/glew/*.c" }
defines "GLEW_STATIC"
project "nanovg"
kind "StaticLib"
includedirs { "3rdparty/nanovg/src" }
files { "3rdparty/nanovg/src/*.c" }
project "libuv"
kind "StaticLib"
includedirs { "3rdparty/libuv/include" }
files { "3rdparty/libuv/src/*.c", "3rdparty/libuv/src/win/*.c" }
project "lua"
os.copyfile("3rdparty/lua/src/luaconf.h.orig", "3rdparty/lua/src/luaconf.h")
kind "StaticLib"
includedirs { "3rdparty/lua/src" }
files { "3rdparty/lua/src/*.c"}
excludes
{
"3rdparty/lua/src/loadlib_rel.c",
"3rdparty/lua/src/lua.c",
"3rdparty/lua/src/luac.c",
"3rdparty/lua/src/print.c",
}
|
Add suffix to debug binaries.
|
Add suffix to debug binaries.
|
Lua
|
mit
|
island-org/island,island-org/island
|
6d931d5b931e89d3b7f4237fac2bcd3ecb9a2721
|
bin/TerrainEditorData/LuaScripts/TerrainEditFilters/roadbuilder2.lua
|
bin/TerrainEditorData/LuaScripts/TerrainEditFilters/roadbuilder2.lua
|
-- New road builder
return
{
name="Road Builder v2.0",
description="Construct a road from the current list of waypoints.",
options=
{
{name="Spline", type="spline", value=nil},
{name="Bed width", type="value", value=16},
{name="Bed Hardness", type="value", value=0.5},
{name="Paving Width", type="value", value=6},
{name="Paving Hardness", type="value", value=0.5},
{name="Paving Layer", type="list", value="Layer 2", list={"Layer 1","Layer 2","Layer 3","Layer 4","Layer 5","Layer 6","Layer 7","Layer 8"}},
{name="Segment steps", type="value", value=10},
{name="Distort?", type="flag", value=false},
{name="Distortion power", type="value", value=4},
{name="Use Mask 0?", type="flag", value=false},
{name="Invert Mask 0?", type="flag", value=false},
{name="Use Mask 1?", type="flag", value=false},
{name="Invert Mask 1?", type="flag", value=false},
{name="Use Mask 2?", type="flag", value=false},
{name="Invert Mask 2?", type="flag", value=false},
},
execute=function(self)
--print("1")
local ops=GetOptions(self.options)
local bedwidth=self.options[2].value
local bedhardness=self.options[3].value
local pavingwidth=self.options[4].value
local pavinghardness=self.options[5].value
local layername=ops["Paving Layer"]
local which=0
if layername=="Layer 1" then which=0
elseif layername=="Layer 2" then which=1
elseif layername=="Layer 3" then which=2
elseif layername=="Layer 4" then which=3
elseif layername=="Layer 5" then which=4
elseif layername=="Layer 6" then which=5
elseif layername=="Layer 7" then which=6
elseif layername=="Layer 8" then which=7
end
local segments=self.options[7].value
local distort=self.options[8].value
local power=self.options[9].value
local ms=MaskSettings(ops["Use Mask 0?"], ops["Invert Mask 0?"], ops["Use Mask 1?"], ops["Invert Mask 1?"], ops["Use Mask 2?"], ops["Invert Mask 2?"])
local buffer=CArray2Dd(TerrainState:GetTerrainWidth(), TerrainState:GetTerrainHeight())
local blend=CArray2Dd(TerrainState:GetTerrainWidth(), TerrainState:GetTerrainHeight())
blend:fill(0)
local c
local spline=ops["Spline"]
if spline==nil then print("No spline selected for road builder.") return end
local plist=RasterVertexList()
for _,c in ipairs(spline.knots) do
local pos=c.position
local norm=TerrainState:WorldToNormalized(pos)
local hx=math.floor(norm.x*TerrainState:GetTerrainWidth())
local hy=math.floor(norm.y*TerrainState:GetTerrainHeight())
local ht=TerrainState:GetHeightValue(hx,hy)
plist:push_back(RasterVertex(hx,hy,ht))
end
local curve=RasterVertexList()
TessellateLineList(plist, curve, segments)
-- Build road bed quadlist and rasterize
local quad=RasterVertexList()
BuildQuadStrip(curve, quad, bedwidth)
RasterizeQuadStrip(buffer, quad)
-- Iterate roadbed quadlist and set alternate verts to 0 and 1, rasterize to blend and apply the paving modifier
for c=0,quad:size()-1,1 do
local v=quad:at(c)
v.val_=c % 2
end
RasterizeQuadStrip(blend, quad)
ApplyBedFunction(blend, bedhardness, true)
if distort and xdistort and ydistort then
DistortBuffer(blend, xdistort, ydistort, power)
end
--BlendHeightWithRasterizedBuffer(TerrainState.hmap, buffer, blend)
--TerrainState.terrain:ApplyHeightMap()
print("blend")
TerrainState:BlendHeightBuffer(buffer,blend,ms)
quad=RasterVertexList()
BuildQuadStrip(curve, quad, pavingwidth)
blend:fill(0)
local color
if which==0 then color=Color(1,0,0,0)
elseif which==1 then color=Color(0,1,0,0)
elseif which==2 then color=Color(0,0,1,0)
else color=Color(0,0,0,1)
end
for c=0,quad:size()-1,1 do
local v=quad:at(c)
v.val_=c % 2
end
RasterizeQuadStrip(blend, quad)
ApplyBedFunction(blend, pavinghardness, true)
if distort then
DistortBuffer(blend, xdistort, ydistort, power)
end
TerrainState:SetLayerBufferMax(blend,which,ms)
--BlendRasterizedBuffer8Max(TerrainState.blend1,TerrainState.blend2,blend,pavinglayer,mask,usemask,invertmask)
--TerrainState.blendtex1:SetData(TerrainState.blend1, false)
--TerrainState.blendtex2:SetData(TerrainState.blend2, false)
end,
}
|
-- New road builder
return
{
name="Road Builder v2.0",
description="Construct a road from the current list of waypoints.",
options=
{
{name="Spline", type="spline", value=nil},
{name="Bed width", type="value", value=16},
{name="Bed Hardness", type="value", value=0.5},
{name="Paving Width", type="value", value=6},
{name="Paving Hardness", type="value", value=0.5},
{name="Paving Layer", type="list", value="Layer 2", list={"Layer 1","Layer 2","Layer 3","Layer 4","Layer 5","Layer 6","Layer 7","Layer 8"}},
{name="Segment steps", type="value", value=10},
{name="Distort?", type="flag", value=false},
{name="Distortion power", type="value", value=4},
{name="Use Mask 0?", type="flag", value=false},
{name="Invert Mask 0?", type="flag", value=false},
{name="Use Mask 1?", type="flag", value=false},
{name="Invert Mask 1?", type="flag", value=false},
{name="Use Mask 2?", type="flag", value=false},
{name="Invert Mask 2?", type="flag", value=false},
},
execute=function(self)
--print("1")
local ops=GetOptions(self.options)
local bedwidth=self.options[2].value
local bedhardness=self.options[3].value
local pavingwidth=self.options[4].value
local pavinghardness=self.options[5].value
local layername=ops["Paving Layer"]
local which=0
if layername=="Layer 1" then which=0
elseif layername=="Layer 2" then which=1
elseif layername=="Layer 3" then which=2
elseif layername=="Layer 4" then which=3
elseif layername=="Layer 5" then which=4
elseif layername=="Layer 6" then which=5
elseif layername=="Layer 7" then which=6
elseif layername=="Layer 8" then which=7
end
local segments=self.options[7].value
local distort=self.options[8].value
local power=self.options[9].value
local ms=MaskSettings(ops["Use Mask 0?"], ops["Invert Mask 0?"], ops["Use Mask 1?"], ops["Invert Mask 1?"], ops["Use Mask 2?"], ops["Invert Mask 2?"])
local buffer=CArray2Dd(TerrainState:GetTerrainWidth(), TerrainState:GetTerrainHeight())
local blend=CArray2Dd(TerrainState:GetTerrainWidth(), TerrainState:GetTerrainHeight())
blend:fill(0)
local c
local spline=ops["Spline"]
if spline==nil then print("No spline selected for road builder.") return end
local plist=RasterVertexList()
for _,c in ipairs(spline.knots) do
local pos=c.position
local norm=TerrainState:WorldToNormalized(pos)
local hx=math.floor(norm.x*TerrainState:GetTerrainWidth())
local hy=math.floor(norm.y*TerrainState:GetTerrainHeight())
local ht=TerrainState:GetHeightValue(hx,(TerrainState:GetTerrainHeight()-1)-hy)
plist:push_back(RasterVertex(hx,hy,ht))
end
local curve=RasterVertexList()
TessellateLineList(plist, curve, segments)
-- Build road bed quadlist and rasterize
local quad=RasterVertexList()
BuildQuadStrip(curve, quad, bedwidth)
RasterizeQuadStrip(buffer, quad)
-- Iterate roadbed quadlist and set alternate verts to 0 and 1, rasterize to blend and apply the paving modifier
for c=0,quad:size()-1,1 do
local v=quad:at(c)
v.val_=c % 2
end
RasterizeQuadStrip(blend, quad)
ApplyBedFunction(blend, bedhardness, true)
if distort and xdistort and ydistort then
DistortBuffer(blend, xdistort, ydistort, power)
end
--BlendHeightWithRasterizedBuffer(TerrainState.hmap, buffer, blend)
--TerrainState.terrain:ApplyHeightMap()
print("blend")
TerrainState:BlendHeightBuffer(buffer,blend,ms)
quad=RasterVertexList()
BuildQuadStrip(curve, quad, pavingwidth)
blend:fill(0)
local color
if which==0 then color=Color(1,0,0,0)
elseif which==1 then color=Color(0,1,0,0)
elseif which==2 then color=Color(0,0,1,0)
else color=Color(0,0,0,1)
end
for c=0,quad:size()-1,1 do
local v=quad:at(c)
v.val_=c % 2
end
RasterizeQuadStrip(blend, quad)
ApplyBedFunction(blend, pavinghardness, true)
if distort then
DistortBuffer(blend, xdistort, ydistort, power)
end
TerrainState:SetLayerBufferMax(blend,which,ms)
--BlendRasterizedBuffer8Max(TerrainState.blend1,TerrainState.blend2,blend,pavinglayer,mask,usemask,invertmask)
--TerrainState.blendtex1:SetData(TerrainState.blend1, false)
--TerrainState.blendtex2:SetData(TerrainState.blend2, false)
end,
}
|
Fix spline elevations.
|
Fix spline elevations.
|
Lua
|
mit
|
JTippetts/U3DTerrainEditor,JTippetts/U3DTerrainEditor,JTippetts/U3DTerrainEditor,JTippetts/U3DTerrainEditor
|
364d39c5babe32e702c0ceeeb898ee345ec60d32
|
verizon.lua
|
verizon.lua
|
local url_count = 0
local tries = 0
local item_type = os.getenv('item_type')
local item_value = os.getenv('item_value')
read_file = function(file)
if file then
local f = assert(io.open(file))
local data = f:read("*all")
f:close()
return data
else
return ""
end
end
wget.callbacks.download_child_p = function(urlpos, parent, depth, start_url_parsed, iri, verdict, reason)
local url = urlpos["url"]["url"]
-- Skip redirect from mysite.verizon.net and members.bellatlantic.net
if url == "http://entertainment.verizon.com/" then
return false
elseif string.match(url, "bellatlantic%.net/([^/]+)/") or
string.match(url, "verizon%.net/([^/]+)/") then
local directory_name_verizon = string.match(url, "verizon%.net/([^/]+)/")
directory_name_verizon = string.gsub(directory_name_verizon, '%%7E', '~')
local directory_name_bellatlantic = string.match(url, "bellatlantic%.net/([^/]+)/")
directory_name_bellatlantic = string.gsub(directory_name_bellatlantic, '%%7E', '~')
if directory_name_verizon ~= item_value then
-- do not want someone else's homepage
-- io.stdout:write("\n Reject " .. url .. " " .. directory_name .. "\n")
-- io.stdout:flush()
return false
elseif directory_name_bellatlantic ~= item_value then
-- do not want someone else's homepage
-- io.stdout:write("\n Reject " .. url .. " " .. directory_name .. "\n")
-- io.stdout:flush()
return false
else
return verdict
end
else
return verdict
end
end
wget.callbacks.httploop_result = function(url, err, http_stat)
-- NEW for 2014: Slightly more verbose messages because people keep
-- complaining that it's not moving or not working
local status_code = http_stat["statcode"]
url_count = url_count + 1
io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \r")
io.stdout:flush()
if status_code >= 500 or
(status_code >= 400 and status_code ~= 404 and status_code ~= 403) then
io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 10")
tries = tries + 1
if tries >= 5 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
return wget.actions.ABORT
else
return wget.actions.CONTINUE
end
else
return wget.actions.NOTHING
end
tries = 0
-- We're okay; sleep a bit (if we have to) and continue
local sleep_time = 0.1 * (math.random(75, 1000) / 100.0)
-- if string.match(url["host"], "cdn") or string.match(url["host"], "media") then
-- -- We should be able to go fast on images since that's what a web browser does
-- sleep_time = 0
-- end
if sleep_time > 0.001 then
os.execute("sleep " .. sleep_time)
end
return wget.actions.NOTHING
end
|
local url_count = 0
local tries = 0
local item_type = os.getenv('item_type')
local item_value = os.getenv('item_value')
read_file = function(file)
if file then
local f = assert(io.open(file))
local data = f:read("*all")
f:close()
return data
else
return ""
end
end
wget.callbacks.download_child_p = function(urlpos, parent, depth, start_url_parsed, iri, verdict, reason)
local url = urlpos["url"]["url"]
-- Skip redirect from mysite.verizon.net and members.bellatlantic.net
if url == "http://entertainment.verizon.com/" then
return false
elseif string.match(url, "bellatlantic%.net/([^/]+)/") or
string.match(url, "verizon%.net/([^/]+)/") then
local directory_name_verizon = string.match(url, "verizon%.net/([^/]+)/")
directory_name_verizon = string.gsub(directory_name_verizon, '%%7E', '~')
local directory_name_bellatlantic = string.match(url, "bellatlantic%.net/([^/]+)/")
directory_name_bellatlantic = string.gsub(directory_name_bellatlantic, '%%7E', '~')
if directory_name_verizon ~= item_value and
directory_name_bellatlantic ~= item_value then
-- do not want someone else's homepage
-- io.stdout:write("\n Reject " .. url .. " " .. directory_name .. "\n")
-- io.stdout:flush()
return false
else
return verdict
end
else
return verdict
end
end
wget.callbacks.httploop_result = function(url, err, http_stat)
-- NEW for 2014: Slightly more verbose messages because people keep
-- complaining that it's not moving or not working
local status_code = http_stat["statcode"]
url_count = url_count + 1
io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \r")
io.stdout:flush()
if status_code >= 500 or
(status_code >= 400 and status_code ~= 404 and status_code ~= 403) then
io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 10")
tries = tries + 1
if tries >= 5 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
return wget.actions.ABORT
else
return wget.actions.CONTINUE
end
else
return wget.actions.NOTHING
end
tries = 0
-- We're okay; sleep a bit (if we have to) and continue
-- local sleep_time = 0.1 * (math.random(75, 1000) / 100.0)
local sleep_time = 0
-- if string.match(url["host"], "cdn") or string.match(url["host"], "media") then
-- -- We should be able to go fast on images since that's what a web browser does
-- sleep_time = 0
-- end
if sleep_time > 0.001 then
os.execute("sleep " .. sleep_time)
end
return wget.actions.NOTHING
end
|
verizon.lua: fixed problem in script
|
verizon.lua: fixed problem in script
|
Lua
|
unlicense
|
ArchiveTeam/verizon-grab,ArchiveTeam/verizon-grab,ArchiveTeam/verizon-grab
|
3938319134b8d88ce3dbc332f30c85a0dad2c87c
|
src/lounge/lua/playlist.lua
|
src/lounge/lua/playlist.lua
|
#!/lounge/bin/janosh -f
function remove(key, op, value)
Janosh:transaction(function()
value = tonumber(value)
idx = tonumber(Janosh:get("/playlist/index").index)
Janosh:remove_t("/playlist/items/#" .. value .. "/.")
if value < idx then
Janosh:set_t("/playlist/index", idx - 1);
end
end)
end
function clear(key, op, value)
Janosh:transaction(function()
Janosh:remove_t("/playlist/items/.")
Janosh:mkarr_t("/playlist/items/.")
end)
end
function shift(key,op,value)
param = JSON:decode(value)
Janosh:shift_t("/playlist/items/#" .. param.from .. "/.", "/playlist/items/#" .. param.to .. "/.")
end
function load(key,op,value)
Janosh:transaction(function()
urls = JSON:decode(value)
for u in urls do
Janosh:publish("showUrl", "W", u);
end
end)
end
Janosh:subscribe("playlistRemove", remove)
Janosh:subscribe("playlistClear", clear)
Janosh:subscribe("playlistShift", shift)
Janosh:subscribe("playlistLoad", load)
while true do
Janosh:sleep(1000000)
end
|
#!/lounge/bin/janosh -f
function remove(key, op, value)
Janosh:transaction(function()
value = tonumber(value)
idx = tonumber(Janosh:get("/playlist/index").index)
Janosh:remove_t("/playlist/items/#" .. value .. "/.")
if value < idx then
Janosh:set_t("/playlist/index", idx - 1);
end
end)
end
function clear(key, op, value)
Janosh:transaction(function()
Janosh:remove_t("/playlist/items/.")
Janosh:mkarr_t("/playlist/items/.")
end)
end
function shift(key,op,value)
param = JSON:decode(value)
Janosh:transaction(function()
idx = tonumber(Janosh:get("/playlist/index").index) - 1
Janosh:shift_t("/playlist/items/#" .. param.from .. "/.", "/playlist/items/#" .. param.to .. "/.")
print(idx,param.from)
if idx == tonumber(param.from) then
Janosh:set_t("/playlist/index", tostring(tonumber(param.to) + 1))
elseif idx >= tonumber(param.to) and idx < tonumber(param.from) then
Janosh:set_t("/playlist/index", tostring(idx + 2))
elseif idx <= tonumber(param.to) and idx > tonumber(param.from) then
Janosh:set_t("/playlist/index", tostring(idx))
end
end)
end
function load(key,op,value)
Janosh:transaction(function()
urls = JSON:decode(value)
for u in urls do
Janosh:publish("showUrl", "W", u);
end
end)
end
Janosh:subscribe("playlistRemove", remove)
Janosh:subscribe("playlistClear", clear)
Janosh:subscribe("playlistShift", shift)
Janosh:subscribe("playlistLoad", load)
while true do
Janosh:sleep(1000000)
end
|
fixed index handling on shift
|
fixed index handling on shift
|
Lua
|
agpl-3.0
|
screeninvader/ScreenInvader,screeninvader/ScreenInvader
|
8a5972485f673d441a5a9e1e811af3721bdb4259
|
mod_carbons/mod_carbons.lua
|
mod_carbons/mod_carbons.lua
|
-- XEP-0280: Message Carbons implementation for Prosody
-- Copyright (C) 2011 Kim Alvefur
--
-- This file is MIT/X11 licensed.
local st = require "util.stanza";
local jid_bare = require "util.jid".bare;
local xmlns_carbons = "urn:xmpp:carbons:1";
local xmlns_forward = "urn:xmpp:forward:0";
local host_sessions = hosts[module.host].sessions;
local full_sessions, bare_sessions = full_sessions, bare_sessions;
local function toggle_carbons(event)
local origin, stanza = event.origin, event.stanza;
if stanza.attr.type == "set" then
local state = stanza.tags[1].name;
module:log("debug", "%s %sd carbons", origin.full_jid, state);
origin.want_carbons = state == "enable";
origin.send(st.reply(stanza));
return true
end
end
module:hook("iq/self/"..xmlns_carbons..":disable", toggle_carbons);
module:hook("iq/self/"..xmlns_carbons..":enable", toggle_carbons);
local function message_handler(event, c2s)
local origin, stanza = event.origin, event.stanza;
local orig_type = stanza.attr.type;
local orig_to = stanza.attr.to;
if not (orig_type == nil
or orig_type == "normal"
or orig_type == "chat") then
return -- No carbons for messages of type error or headline
end
-- Stanza sent by a local client
local bare_jid = origin.username .. "@" .. origin.host;
local target_session = origin;
local top_priority = false;
local user_sessions = host_sessions[origin.username];
-- Stanza about to be delivered to a local client
if not c2s then
bare_jid = jid_bare(orig_to);
target_session = full_sessions[orig_to]
user_sessions = bare_sessions[bare_jid];
if not target_session and user_sessions then
-- The top resources will already receive this message per normal routing rules,
-- so we are going to skip them in order to avoid sending duplicated messages.
local top_resources = user_sessions.top_resources;
top_priority = top_resources and top_resources[1].priority
end
end
if not user_sessions then
module:log("debug", "Skip carbons for offline user");
return -- No use in sending carbons to an offline user
end
if not c2s and stanza:get_child("private", xmlns_carbons) then
stanza:maptags(function(tag)
return tag.attr.xmlns == xmlns_carbons
and tag.name == "private" and tag or nil;
end);
module:log("debug", "Message tagged private, ignoring");
return
end
-- Create the carbon copy and wrap it as per the Stanza Forwarding XEP
local copy = st.clone(stanza);
copy.attr.xmlns = "jabber:client";
local carbon = st.message{ from = bare_jid, type = orig_type, }
:tag(c2s and "sent" or "received", { xmlns = xmlns_carbons }):up()
:tag("forwarded", { xmlns = xmlns_forward })
:add_child(copy):reset();
user_sessions = user_sessions and user_sessions.sessions;
for _, session in pairs(user_sessions) do
-- Carbons are sent to resources that have enabled it
if session.want_carbons
-- but not the resource that sent the message, or the one that it's directed to
and session ~= target_session
-- and isn't among the top resources that would receive the message per standard routing rules
and (not c2s or session.priority ~= top_priority) then
carbon.attr.to = session.full_jid;
module:log("debug", "Sending carbon to %s", session.full_jid);
session.send(carbon);
end
end
end
local function c2s_message_handler(event)
return message_handler(event, true)
end
-- Stanzas sent by local clients
module:hook("pre-message/bare", c2s_message_handler, 1);
module:hook("pre-message/full", c2s_message_handler, 1);
-- Stanzas to local clients
module:hook("message/bare", message_handler, 1);
module:hook("message/full", message_handler, 1);
module:add_feature(xmlns_carbons);
|
-- XEP-0280: Message Carbons implementation for Prosody
-- Copyright (C) 2011 Kim Alvefur
--
-- This file is MIT/X11 licensed.
local st = require "util.stanza";
local jid_bare = require "util.jid".bare;
local xmlns_carbons = "urn:xmpp:carbons:1";
local xmlns_forward = "urn:xmpp:forward:0";
local host_sessions = hosts[module.host].sessions;
local full_sessions, bare_sessions = full_sessions, bare_sessions;
local function toggle_carbons(event)
local origin, stanza = event.origin, event.stanza;
if stanza.attr.type == "set" then
local state = stanza.tags[1].name;
module:log("debug", "%s %sd carbons", origin.full_jid, state);
origin.want_carbons = state == "enable";
origin.send(st.reply(stanza));
return true
end
end
module:hook("iq/self/"..xmlns_carbons..":disable", toggle_carbons);
module:hook("iq/self/"..xmlns_carbons..":enable", toggle_carbons);
local function message_handler(event, c2s)
local origin, stanza = event.origin, event.stanza;
local orig_type = stanza.attr.type;
local orig_from = stanza.attr.from;
local orig_to = stanza.attr.to;
if not (orig_type == nil
or orig_type == "normal"
or orig_type == "chat") then
return -- No carbons for messages of type error or headline
end
-- Stanza sent by a local client
local bare_jid = origin.type == "c2s" and origin.username .. "@" .. origin.host or jid_bare(orig_from);
local target_session = origin;
local top_priority = false;
local user_sessions = host_sessions[origin.username];
-- Stanza about to be delivered to a local client
if not c2s then
bare_jid = jid_bare(orig_to);
target_session = full_sessions[orig_to]
user_sessions = bare_sessions[bare_jid];
if not target_session and user_sessions then
-- The top resources will already receive this message per normal routing rules,
-- so we are going to skip them in order to avoid sending duplicated messages.
local top_resources = user_sessions.top_resources;
top_priority = top_resources and top_resources[1].priority
end
end
if not user_sessions then
module:log("debug", "Skip carbons for offline user");
return -- No use in sending carbons to an offline user
end
if not c2s and stanza:get_child("private", xmlns_carbons) then
stanza:maptags(function(tag)
return tag.attr.xmlns == xmlns_carbons
and tag.name == "private" and tag or nil;
end);
module:log("debug", "Message tagged private, ignoring");
return
end
-- Create the carbon copy and wrap it as per the Stanza Forwarding XEP
local copy = st.clone(stanza);
copy.attr.xmlns = "jabber:client";
local carbon = st.message{ from = bare_jid, type = orig_type, }
:tag(c2s and "sent" or "received", { xmlns = xmlns_carbons }):up()
:tag("forwarded", { xmlns = xmlns_forward })
:add_child(copy):reset();
user_sessions = user_sessions and user_sessions.sessions;
for _, session in pairs(user_sessions) do
-- Carbons are sent to resources that have enabled it
if session.want_carbons
-- but not the resource that sent the message, or the one that it's directed to
and session ~= target_session
-- and isn't among the top resources that would receive the message per standard routing rules
and (not c2s or session.priority ~= top_priority) then
carbon.attr.to = session.full_jid;
module:log("debug", "Sending carbon to %s", session.full_jid);
session.send(carbon);
end
end
end
local function c2s_message_handler(event)
return message_handler(event, true)
end
-- Stanzas sent by local clients
module:hook("pre-message/bare", c2s_message_handler, 1);
module:hook("pre-message/full", c2s_message_handler, 1);
-- Stanzas to local clients
module:hook("message/bare", message_handler, 1);
module:hook("message/full", message_handler, 1);
module:add_feature(xmlns_carbons);
|
mod_carbons: Fix handling of messages from remote hosts
|
mod_carbons: Fix handling of messages from remote hosts
|
Lua
|
mit
|
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
|
a3ef61f1658b1a4dad91ec737e0075051bb692ba
|
triggerfield/noobia_henry.lua
|
triggerfield/noobia_henry.lua
|
-- INSERT INTO triggerfields VALUES (37,20,100,'triggerfield.noobia_henry');
-- INSERT INTO triggerfields VALUES (37,21,100,'triggerfield.noobia_henry');
-- INSERT INTO triggerfields VALUES (37,22,100,'triggerfield.noobia_henry');
-- INSERT INTO triggerfields VALUES (38,20,100,'triggerfield.noobia_henry');
-- INSERT INTO triggerfields VALUES (38,22,100,'triggerfield.noobia_henry');
-- INSERT INTO triggerfields VALUES (39,20,100,'triggerfield.noobia_henry');
-- INSERT INTO triggerfields VALUES (39,21,100,'triggerfield.noobia_henry');
-- INSERT INTO triggerfields VALUES (39,22,100,'triggerfield.noobia_henry');
require("base.common")
module("triggerfield.noobia_henry", package.seeall)
function MoveToField(Character)
-- for Noobia: the char has to walk to a specific field (this triggerfield); he gets a message and we add a LTEvalue so that we remember he was at the field
local callbackNewbie = function(dialogNewbie)
find, myEffect = Character.effects:find(13)
if find then
myEffect:addValue("noobiaHenry",1)
end
end
if Character:getPlayerLanguage() == 0 then
dialogNewbie = MessageDialog("Sehr gut!","Um mit dem Menschen zu sprechen, ffne die Sprachkonsole mit Return, schreibe ein Wort und drcke wieder Enter. Alle NPCs (NonPlayerCharacters) reagieren auf bestimmte Schlsselwrter wenn du in ihrer Nhe stehst. Versuche den Menschen um 'Hilfe' zu bitten. Ist die Sprachkonsole leer, kannst du sie mit erneutem Drcken der Returntaste schlieen.", callbackNewbie)
else
dialogNewbie = MessageDialog("Very good!", "translation", callbackNewbie)
end
Character:requestMessageDialog(dialogNewbie)
end
|
-- INSERT INTO triggerfields VALUES (37,20,100,'triggerfield.noobia_henry');
-- INSERT INTO triggerfields VALUES (37,21,100,'triggerfield.noobia_henry');
-- INSERT INTO triggerfields VALUES (37,22,100,'triggerfield.noobia_henry');
-- INSERT INTO triggerfields VALUES (38,20,100,'triggerfield.noobia_henry');
-- INSERT INTO triggerfields VALUES (38,22,100,'triggerfield.noobia_henry');
-- INSERT INTO triggerfields VALUES (39,20,100,'triggerfield.noobia_henry');
-- INSERT INTO triggerfields VALUES (39,21,100,'triggerfield.noobia_henry');
-- INSERT INTO triggerfields VALUES (39,22,100,'triggerfield.noobia_henry');
require("base.common")
module("triggerfield.noobia_henry", package.seeall)
function MoveToField(Character)
-- for Noobia: the char has to walk to a specific field (this triggerfield); he gets a message and we add a LTEvalue so that we remember he was at the field
found, value = Character.effects:findValue("noobiaHenry");
if not value then --Didn't visit the triggerfield yet
local callbackNewbie = function(dialogNewbie)
find, myEffect = Character.effects:find(13)
if find then
myEffect:addValue("noobiaHenry",1)
end
end
if Character:getPlayerLanguage() == 0 then
dialogNewbie = MessageDialog("Sehr gut!","Um mit dem Menschen zu sprechen, ffne die Sprachkonsole mit Return, schreibe ein Wort und drcke wieder Enter. Alle NPCs (NonPlayerCharacters) reagieren auf bestimmte Schlsselwrter wenn du in ihrer Nhe stehst. Versuche den Menschen um 'Hilfe' zu bitten. Ist die Sprachkonsole leer, kannst du sie mit erneutem Drcken der Returntaste schlieen.", callbackNewbie)
else
dialogNewbie = MessageDialog("Very good!", "translation", callbackNewbie)
end
Character:requestMessageDialog(dialogNewbie)
end
end
|
Trying to fix this triggerfield
|
Trying to fix this triggerfield
|
Lua
|
agpl-3.0
|
Illarion-eV/Illarion-Content,vilarion/Illarion-Content,LaFamiglia/Illarion-Content,Baylamon/Illarion-Content,KayMD/Illarion-Content
|
382a33f40a76cedc945ae6895a1341118ca48e4e
|
modules/admin-full/luasrc/model/cbi/admin_network/network.lua
|
modules/admin-full/luasrc/model/cbi/admin_network/network.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local sys = require "luci.sys"
local wa = require "luci.tools.webadmin"
local fs = require "nixio.fs"
local netstate = luci.model.uci.cursor_state():get_all("network")
m = Map("network", translate("Interfaces"))
local created
local netstat = sys.net.deviceinfo()
s = m:section(TypedSection, "interface", "")
s.addremove = true
s.anonymous = false
s.extedit = luci.dispatcher.build_url("admin", "network", "network") .. "/%s"
s.template = "cbi/tblsection"
s.override_scheme = true
function s.filter(self, section)
return section ~= "loopback" and section
end
function s.create(self, section)
if TypedSection.create(self, section) then
created = section
else
self.invalid_cts = true
end
end
function s.parse(self, ...)
TypedSection.parse(self, ...)
if created then
m.uci:save("network")
luci.http.redirect(luci.dispatcher.build_url("admin", "network", "network")
.. "/" .. created)
end
end
up = s:option(Flag, "up")
function up.cfgvalue(self, section)
return netstate[section] and netstate[section].up or "0"
end
function up.write(self, section, value)
local call
if value == "1" then
call = "ifup"
elseif value == "0" then
call = "ifdown"
end
os.execute(call .. " " .. section .. " >/dev/null 2>&1")
end
ifname = s:option(DummyValue, "ifname", translate("Device"))
function ifname.cfgvalue(self, section)
return netstate[section] and netstate[section].ifname
end
ifname.titleref = luci.dispatcher.build_url("admin", "network", "vlan")
if luci.model.uci.cursor():load("firewall") then
zone = s:option(DummyValue, "_zone", translate("Zone"))
zone.titleref = luci.dispatcher.build_url("admin", "network", "firewall", "zones")
function zone.cfgvalue(self, section)
return table.concat(wa.network_get_zones(section) or { "-" }, ", ")
end
end
hwaddr = s:option(DummyValue, "_hwaddr",
translate("<abbr title=\"Media Access Control\">MAC</abbr>-Address"),
translate("Hardware Address"))
function hwaddr.cfgvalue(self, section)
local ix = self.map:get(section, "ifname") or ""
local mac = fs.readfile("/sys/class/net/" .. ix .. "/address")
if not mac then
mac = luci.util.exec("ifconfig " .. ix)
mac = mac and mac:match(" ([A-F0-9:]+)%s*\n")
end
if mac and #mac > 0 then
return mac:upper()
end
return "?"
end
ipaddr = s:option(DummyValue, "ipaddr",
translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>" ..
"-Address"))
function ipaddr.cfgvalue(self, section)
return table.concat(wa.network_get_addresses(section), ", ")
end
txrx = s:option(DummyValue, "_txrx", translate("Traffic"),
translate("transmitted / received"))
function txrx.cfgvalue(self, section)
local ix = self.map:get(section, "ifname")
local rx = netstat and netstat[ix] and netstat[ix][1]
rx = rx and wa.byte_format(tonumber(rx)) or "-"
local tx = netstat and netstat[ix] and netstat[ix][9]
tx = tx and wa.byte_format(tonumber(tx)) or "-"
return string.format("%s / %s", tx, rx)
end
errors = s:option(DummyValue, "_err", translate("Errors"),
translate("TX / RX"))
function errors.cfgvalue(self, section)
local ix = self.map:get(section, "ifname")
local rx = netstat and netstat[ix] and netstat[ix][3]
local tx = netstat and netstat[ix] and netstat[ix][11]
rx = rx and tostring(rx) or "-"
tx = tx and tostring(tx) or "-"
return string.format("%s / %s", tx, rx)
end
return m
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local sys = require "luci.sys"
local wa = require "luci.tools.webadmin"
local fs = require "nixio.fs"
local netstate = luci.model.uci.cursor_state():get_all("network")
m = Map("network", translate("Interfaces"))
local created
local netstat = sys.net.deviceinfo()
s = m:section(TypedSection, "interface", "")
s.addremove = true
s.anonymous = false
s.extedit = luci.dispatcher.build_url("admin", "network", "network") .. "/%s"
s.template = "cbi/tblsection"
s.override_scheme = true
function s.filter(self, section)
return section ~= "loopback" and section
end
function s.create(self, section)
if TypedSection.create(self, section) then
created = section
else
self.invalid_cts = true
end
end
function s.parse(self, ...)
TypedSection.parse(self, ...)
if created then
m.uci:save("network")
luci.http.redirect(luci.dispatcher.build_url("admin", "network", "network")
.. "/" .. created)
end
end
up = s:option(Flag, "up")
function up.cfgvalue(self, section)
return netstate[section] and netstate[section].up or "0"
end
function up.write(self, section, value)
local call
if value == "1" then
call = "ifup"
elseif value == "0" then
call = "ifdown"
end
os.execute(call .. " " .. section .. " >/dev/null 2>&1")
end
ifname = s:option(DummyValue, "ifname", translate("Device"))
function ifname.cfgvalue(self, section)
return netstate[section] and netstate[section].ifname
end
ifname.titleref = luci.dispatcher.build_url("admin", "network", "vlan")
if luci.model.uci.cursor():load("firewall") then
zone = s:option(DummyValue, "_zone", translate("Zone"))
zone.titleref = luci.dispatcher.build_url("admin", "network", "firewall", "zones")
function zone.cfgvalue(self, section)
return table.concat(wa.network_get_zones(section) or { "-" }, ", ")
end
end
hwaddr = s:option(DummyValue, "_hwaddr",
translate("<abbr title=\"Media Access Control\">MAC</abbr>-Address"),
translate("Hardware Address"))
function hwaddr.cfgvalue(self, section)
local ix = self.map:get(section, "ifname") or ""
ix = (type(ix) == "table") and ix[1] or ix
local mac = fs.readfile("/sys/class/net/" .. ix .. "/address")
if not mac then
mac = luci.util.exec("ifconfig " .. ix)
mac = mac and mac:match(" ([A-F0-9:]+)%s*\n")
end
if mac and #mac > 0 then
return mac:upper()
end
return "?"
end
ipaddr = s:option(DummyValue, "ipaddr",
translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>" ..
"-Address"))
function ipaddr.cfgvalue(self, section)
return table.concat(wa.network_get_addresses(section), ", ")
end
txrx = s:option(DummyValue, "_txrx", translate("Traffic"),
translate("transmitted / received"))
function txrx.cfgvalue(self, section)
local ix = self.map:get(section, "ifname")
local rx = netstat and netstat[ix] and netstat[ix][1]
rx = rx and wa.byte_format(tonumber(rx)) or "-"
local tx = netstat and netstat[ix] and netstat[ix][9]
tx = tx and wa.byte_format(tonumber(tx)) or "-"
return string.format("%s / %s", tx, rx)
end
errors = s:option(DummyValue, "_err", translate("Errors"),
translate("TX / RX"))
function errors.cfgvalue(self, section)
local ix = self.map:get(section, "ifname")
local rx = netstat and netstat[ix] and netstat[ix][3]
local tx = netstat and netstat[ix] and netstat[ix][11]
rx = rx and tostring(rx) or "-"
tx = tx and tostring(tx) or "-"
return string.format("%s / %s", tx, rx)
end
return m
|
modules/admin-full: fix crash on network interface overview page
|
modules/admin-full: fix crash on network interface overview page
|
Lua
|
apache-2.0
|
LuttyYang/luci,deepak78/new-luci,keyidadi/luci,david-xiao/luci,shangjiyu/luci-with-extra,hnyman/luci,Kyklas/luci-proto-hso,florian-shellfire/luci,bittorf/luci,jorgifumi/luci,lcf258/openwrtcn,florian-shellfire/luci,ff94315/luci-1,aa65535/luci,Kyklas/luci-proto-hso,dwmw2/luci,mumuqz/luci,forward619/luci,kuoruan/luci,florian-shellfire/luci,Hostle/openwrt-luci-multi-user,aircross/OpenWrt-Firefly-LuCI,openwrt/luci,zhaoxx063/luci,palmettos/cnLuCI,chris5560/openwrt-luci,hnyman/luci,ollie27/openwrt_luci,daofeng2015/luci,harveyhu2012/luci,bittorf/luci,MinFu/luci,bright-things/ionic-luci,cshore-firmware/openwrt-luci,fkooman/luci,cshore/luci,nwf/openwrt-luci,keyidadi/luci,db260179/openwrt-bpi-r1-luci,dismantl/luci-0.12,ff94315/luci-1,openwrt-es/openwrt-luci,sujeet14108/luci,palmettos/cnLuCI,harveyhu2012/luci,maxrio/luci981213,taiha/luci,ReclaimYourPrivacy/cloak-luci,teslamint/luci,harveyhu2012/luci,db260179/openwrt-bpi-r1-luci,hnyman/luci,lcf258/openwrtcn,bittorf/luci,palmettos/cnLuCI,remakeelectric/luci,jlopenwrtluci/luci,fkooman/luci,hnyman/luci,aircross/OpenWrt-Firefly-LuCI,ollie27/openwrt_luci,remakeelectric/luci,Wedmer/luci,rogerpueyo/luci,oneru/luci,dismantl/luci-0.12,teslamint/luci,ff94315/luci-1,db260179/openwrt-bpi-r1-luci,Hostle/luci,RuiChen1113/luci,nmav/luci,981213/luci-1,openwrt/luci,palmettos/cnLuCI,urueedi/luci,florian-shellfire/luci,chris5560/openwrt-luci,schidler/ionic-luci,zhaoxx063/luci,oyido/luci,oyido/luci,urueedi/luci,RedSnake64/openwrt-luci-packages,cshore/luci,bright-things/ionic-luci,Wedmer/luci,bright-things/ionic-luci,LazyZhu/openwrt-luci-trunk-mod,shangjiyu/luci-with-extra,ollie27/openwrt_luci,tobiaswaldvogel/luci,Noltari/luci,wongsyrone/luci-1,cappiewu/luci,sujeet14108/luci,urueedi/luci,forward619/luci,deepak78/new-luci,aircross/OpenWrt-Firefly-LuCI,zhaoxx063/luci,ollie27/openwrt_luci,lcf258/openwrtcn,cappiewu/luci,Wedmer/luci,ReclaimYourPrivacy/cloak-luci,maxrio/luci981213,LuttyYang/luci,bright-things/ionic-luci,artynet/luci,RedSnake64/openwrt-luci-packages,lbthomsen/openwrt-luci,tobiaswaldvogel/luci,joaofvieira/luci,bittorf/luci,slayerrensky/luci,slayerrensky/luci,dismantl/luci-0.12,bittorf/luci,rogerpueyo/luci,kuoruan/lede-luci,taiha/luci,MinFu/luci,lcf258/openwrtcn,RedSnake64/openwrt-luci-packages,tobiaswaldvogel/luci,joaofvieira/luci,tcatm/luci,hnyman/luci,NeoRaider/luci,oneru/luci,cshore/luci,sujeet14108/luci,kuoruan/lede-luci,remakeelectric/luci,openwrt/luci,fkooman/luci,cappiewu/luci,joaofvieira/luci,palmettos/test,Kyklas/luci-proto-hso,taiha/luci,jorgifumi/luci,slayerrensky/luci,openwrt/luci,zhaoxx063/luci,aa65535/luci,dismantl/luci-0.12,Hostle/luci,schidler/ionic-luci,ReclaimYourPrivacy/cloak-luci,ff94315/luci-1,LazyZhu/openwrt-luci-trunk-mod,dismantl/luci-0.12,remakeelectric/luci,RuiChen1113/luci,schidler/ionic-luci,oneru/luci,tobiaswaldvogel/luci,thess/OpenWrt-luci,obsy/luci,Hostle/luci,mumuqz/luci,oneru/luci,fkooman/luci,aa65535/luci,NeoRaider/luci,zhaoxx063/luci,daofeng2015/luci,thess/OpenWrt-luci,MinFu/luci,obsy/luci,sujeet14108/luci,nwf/openwrt-luci,daofeng2015/luci,LuttyYang/luci,aircross/OpenWrt-Firefly-LuCI,teslamint/luci,ollie27/openwrt_luci,taiha/luci,aircross/OpenWrt-Firefly-LuCI,thesabbir/luci,cshore-firmware/openwrt-luci,981213/luci-1,ReclaimYourPrivacy/cloak-luci,thess/OpenWrt-luci,nmav/luci,cshore/luci,kuoruan/lede-luci,oyido/luci,male-puppies/luci,tcatm/luci,kuoruan/lede-luci,david-xiao/luci,ff94315/luci-1,keyidadi/luci,tcatm/luci,dismantl/luci-0.12,RedSnake64/openwrt-luci-packages,bright-things/ionic-luci,david-xiao/luci,ff94315/luci-1,thess/OpenWrt-luci,981213/luci-1,lcf258/openwrtcn,deepak78/new-luci,lbthomsen/openwrt-luci,oyido/luci,cappiewu/luci,florian-shellfire/luci,nmav/luci,NeoRaider/luci,marcel-sch/luci,tobiaswaldvogel/luci,mumuqz/luci,slayerrensky/luci,tcatm/luci,chris5560/openwrt-luci,Hostle/openwrt-luci-multi-user,opentechinstitute/luci,jorgifumi/luci,aircross/OpenWrt-Firefly-LuCI,Wedmer/luci,RuiChen1113/luci,thess/OpenWrt-luci,male-puppies/luci,palmettos/cnLuCI,joaofvieira/luci,jorgifumi/luci,nwf/openwrt-luci,opentechinstitute/luci,kuoruan/lede-luci,dismantl/luci-0.12,oneru/luci,sujeet14108/luci,thesabbir/luci,artynet/luci,lbthomsen/openwrt-luci,MinFu/luci,ReclaimYourPrivacy/cloak-luci,obsy/luci,sujeet14108/luci,Hostle/openwrt-luci-multi-user,remakeelectric/luci,Hostle/openwrt-luci-multi-user,opentechinstitute/luci,LuttyYang/luci,schidler/ionic-luci,kuoruan/luci,dwmw2/luci,LazyZhu/openwrt-luci-trunk-mod,LuttyYang/luci,obsy/luci,oneru/luci,marcel-sch/luci,wongsyrone/luci-1,harveyhu2012/luci,harveyhu2012/luci,nmav/luci,rogerpueyo/luci,chris5560/openwrt-luci,deepak78/new-luci,openwrt/luci,palmettos/cnLuCI,jlopenwrtluci/luci,zhaoxx063/luci,dwmw2/luci,thesabbir/luci,bittorf/luci,fkooman/luci,Hostle/openwrt-luci-multi-user,jlopenwrtluci/luci,teslamint/luci,cshore/luci,LuttyYang/luci,joaofvieira/luci,daofeng2015/luci,981213/luci-1,openwrt-es/openwrt-luci,Hostle/luci,shangjiyu/luci-with-extra,keyidadi/luci,tcatm/luci,schidler/ionic-luci,Noltari/luci,cshore-firmware/openwrt-luci,urueedi/luci,dwmw2/luci,openwrt/luci,artynet/luci,wongsyrone/luci-1,tcatm/luci,cshore/luci,fkooman/luci,ReclaimYourPrivacy/cloak-luci,wongsyrone/luci-1,ff94315/luci-1,RuiChen1113/luci,david-xiao/luci,teslamint/luci,deepak78/new-luci,jchuang1977/luci-1,jchuang1977/luci-1,Noltari/luci,palmettos/test,obsy/luci,Kyklas/luci-proto-hso,obsy/luci,daofeng2015/luci,lcf258/openwrtcn,deepak78/new-luci,slayerrensky/luci,dwmw2/luci,Sakura-Winkey/LuCI,LazyZhu/openwrt-luci-trunk-mod,lbthomsen/openwrt-luci,nmav/luci,oneru/luci,palmettos/test,marcel-sch/luci,male-puppies/luci,chris5560/openwrt-luci,urueedi/luci,palmettos/cnLuCI,chris5560/openwrt-luci,joaofvieira/luci,jchuang1977/luci-1,david-xiao/luci,bittorf/luci,oyido/luci,urueedi/luci,thess/OpenWrt-luci,Sakura-Winkey/LuCI,jlopenwrtluci/luci,thess/OpenWrt-luci,nwf/openwrt-luci,zhaoxx063/luci,jorgifumi/luci,aircross/OpenWrt-Firefly-LuCI,981213/luci-1,remakeelectric/luci,dwmw2/luci,sujeet14108/luci,MinFu/luci,opentechinstitute/luci,taiha/luci,daofeng2015/luci,cappiewu/luci,obsy/luci,opentechinstitute/luci,forward619/luci,db260179/openwrt-bpi-r1-luci,opentechinstitute/luci,obsy/luci,hnyman/luci,teslamint/luci,bright-things/ionic-luci,artynet/luci,Noltari/luci,Hostle/openwrt-luci-multi-user,nmav/luci,rogerpueyo/luci,thess/OpenWrt-luci,Sakura-Winkey/LuCI,rogerpueyo/luci,RuiChen1113/luci,thesabbir/luci,palmettos/test,openwrt-es/openwrt-luci,wongsyrone/luci-1,openwrt/luci,maxrio/luci981213,dwmw2/luci,wongsyrone/luci-1,palmettos/cnLuCI,remakeelectric/luci,remakeelectric/luci,palmettos/test,hnyman/luci,tobiaswaldvogel/luci,oneru/luci,maxrio/luci981213,kuoruan/lede-luci,shangjiyu/luci-with-extra,RuiChen1113/luci,Hostle/openwrt-luci-multi-user,dwmw2/luci,Kyklas/luci-proto-hso,LazyZhu/openwrt-luci-trunk-mod,urueedi/luci,Wedmer/luci,cshore/luci,hnyman/luci,florian-shellfire/luci,fkooman/luci,shangjiyu/luci-with-extra,deepak78/new-luci,Hostle/openwrt-luci-multi-user,kuoruan/lede-luci,teslamint/luci,forward619/luci,jorgifumi/luci,forward619/luci,opentechinstitute/luci,wongsyrone/luci-1,LazyZhu/openwrt-luci-trunk-mod,schidler/ionic-luci,openwrt-es/openwrt-luci,cshore-firmware/openwrt-luci,forward619/luci,palmettos/test,zhaoxx063/luci,jlopenwrtluci/luci,palmettos/test,NeoRaider/luci,lcf258/openwrtcn,keyidadi/luci,sujeet14108/luci,Sakura-Winkey/LuCI,jorgifumi/luci,tobiaswaldvogel/luci,Sakura-Winkey/LuCI,981213/luci-1,lcf258/openwrtcn,tcatm/luci,daofeng2015/luci,kuoruan/luci,artynet/luci,slayerrensky/luci,keyidadi/luci,nwf/openwrt-luci,Hostle/luci,taiha/luci,lbthomsen/openwrt-luci,Sakura-Winkey/LuCI,lbthomsen/openwrt-luci,thesabbir/luci,fkooman/luci,Wedmer/luci,Hostle/luci,teslamint/luci,lcf258/openwrtcn,jorgifumi/luci,jchuang1977/luci-1,openwrt-es/openwrt-luci,mumuqz/luci,LuttyYang/luci,openwrt-es/openwrt-luci,RedSnake64/openwrt-luci-packages,db260179/openwrt-bpi-r1-luci,shangjiyu/luci-with-extra,mumuqz/luci,forward619/luci,aa65535/luci,ollie27/openwrt_luci,kuoruan/luci,cshore-firmware/openwrt-luci,Hostle/luci,artynet/luci,chris5560/openwrt-luci,aa65535/luci,aa65535/luci,kuoruan/luci,rogerpueyo/luci,shangjiyu/luci-with-extra,Wedmer/luci,RedSnake64/openwrt-luci-packages,bright-things/ionic-luci,cappiewu/luci,kuoruan/luci,bright-things/ionic-luci,ff94315/luci-1,Kyklas/luci-proto-hso,schidler/ionic-luci,cshore-firmware/openwrt-luci,openwrt-es/openwrt-luci,Noltari/luci,mumuqz/luci,kuoruan/luci,david-xiao/luci,jchuang1977/luci-1,keyidadi/luci,slayerrensky/luci,kuoruan/luci,david-xiao/luci,Noltari/luci,harveyhu2012/luci,taiha/luci,cshore-firmware/openwrt-luci,maxrio/luci981213,marcel-sch/luci,maxrio/luci981213,male-puppies/luci,oyido/luci,tcatm/luci,nwf/openwrt-luci,Sakura-Winkey/LuCI,lbthomsen/openwrt-luci,male-puppies/luci,marcel-sch/luci,mumuqz/luci,aa65535/luci,thesabbir/luci,bittorf/luci,male-puppies/luci,jlopenwrtluci/luci,oyido/luci,Sakura-Winkey/LuCI,MinFu/luci,schidler/ionic-luci,NeoRaider/luci,wongsyrone/luci-1,forward619/luci,Hostle/luci,aa65535/luci,artynet/luci,jchuang1977/luci-1,opentechinstitute/luci,cshore/luci,jlopenwrtluci/luci,cappiewu/luci,maxrio/luci981213,jchuang1977/luci-1,jchuang1977/luci-1,NeoRaider/luci,NeoRaider/luci,daofeng2015/luci,NeoRaider/luci,jlopenwrtluci/luci,kuoruan/lede-luci,deepak78/new-luci,Wedmer/luci,openwrt-es/openwrt-luci,rogerpueyo/luci,nmav/luci,lcf258/openwrtcn,LazyZhu/openwrt-luci-trunk-mod,LazyZhu/openwrt-luci-trunk-mod,db260179/openwrt-bpi-r1-luci,taiha/luci,rogerpueyo/luci,cappiewu/luci,db260179/openwrt-bpi-r1-luci,male-puppies/luci,thesabbir/luci,ollie27/openwrt_luci,RedSnake64/openwrt-luci-packages,db260179/openwrt-bpi-r1-luci,keyidadi/luci,RuiChen1113/luci,david-xiao/luci,Noltari/luci,cshore-firmware/openwrt-luci,MinFu/luci,urueedi/luci,shangjiyu/luci-with-extra,male-puppies/luci,tobiaswaldvogel/luci,florian-shellfire/luci,nmav/luci,florian-shellfire/luci,Kyklas/luci-proto-hso,marcel-sch/luci,981213/luci-1,ReclaimYourPrivacy/cloak-luci,harveyhu2012/luci,RuiChen1113/luci,oyido/luci,maxrio/luci981213,MinFu/luci,thesabbir/luci,Noltari/luci,marcel-sch/luci,joaofvieira/luci,joaofvieira/luci,ReclaimYourPrivacy/cloak-luci,artynet/luci,Noltari/luci,openwrt/luci,ollie27/openwrt_luci,LuttyYang/luci,nwf/openwrt-luci,lbthomsen/openwrt-luci,palmettos/test,chris5560/openwrt-luci,marcel-sch/luci,slayerrensky/luci,nmav/luci,nwf/openwrt-luci,artynet/luci,mumuqz/luci
|
ded2434dac6e73be5d21ae0080a6349700b4be06
|
lib/gsmake/sync/github.com/gsmake/curl/src/plugin/lua/plugin.lua
|
lib/gsmake/sync/github.com/gsmake/curl/src/plugin/lua/plugin.lua
|
local fs = require "lemoon.fs"
local sys = require "lemoon.sys"
local class = require "lemoon.class"
local filepath = require "lemoon.filepath"
local logger = class.new("lemoon.log","gsmake")
local console = class.new("lemoon.log","console")
task.sync_init = function(self)
if sys.host() == "Windows" then
curl = filepath.join(loader.Path,"tools/win32/curl.exe")
unzip = filepath.join(loader.Path,"tools/win32/7z.exe")
else
local ok, curlpath = sys.lookup("curl")
if not ok then
throw("curl program not found !!!!!!!")
end
curl = curlpath
local ok, unzippath = sys.lookup("7z")
if not ok then
throw("7z program not found !!!!!!!")
end
unzip = unzippath
end
end
task.sync_remote = function(self,name,version,url)
print(string.format("sync remote package:%s",url))
local workdir = filepath.join(loader.Config.GlobalRepo,"curl",name)
if not fs.exists(workdir) then
fs.mkdir(workdir,true)
end
local exec = sys.exec(curl)
exec:dir(workdir)
-- --
local tmpfile = string.format("%s.tmp",version)
--
exec:start("-o",tmpfile,"-k",url)
if 0 ~= exec:wait() then
console:E("download remote package error :%s",url)
return true
end
local outputdir = filepath.join(workdir,version)
-- if fs.exists(outputdir) then
-- fs.rm(outputdir,true)
-- end
local exec = sys.exec(unzip)
exec:dir(workdir)
exec:start("x","-aoa",string.format("-o%s",version),filepath.join(workdir,tmpfile))
if 0 ~= exec:wait() then
console:E("download remote package error :%s",url)
return true
end
local sourcepath = nil
fs.list(outputdir,function(entry)
if entry == "." or entry == ".." then return end
sourcepath = filepath.join(outputdir,entry)
end)
assert(sourcepath,"7z bug checker")
loader.GSMake.Repo:save_source(name,version,sourcepath,sourcepath,true)
end
task.sync_remote.Desc = "curl downloader#sync_remote"
task.sync_remote.Prev = "sync_init"
task.sync_source = function(self,install_path)
end
task.sync_source.Desc = "curl downloader#sync_source"
task.sync_source.Prev = "sync_init"
|
local fs = require "lemoon.fs"
local sys = require "lemoon.sys"
local class = require "lemoon.class"
local filepath = require "lemoon.filepath"
local logger = class.new("lemoon.log","gsmake")
local console = class.new("lemoon.log","console")
task.sync_init = function(self)
if sys.host() == "Windows" then
curl = filepath.join(self.Package.Path,"tools/win32/curl.exe")
unzip = filepath.join(self.Package.Path,"tools/win32/7z.exe")
else
local ok, curlpath = sys.lookup("curl")
if not ok then
throw("curl program not found !!!!!!!")
end
curl = curlpath
local ok, unzippath = sys.lookup("7z")
if not ok then
throw("7z program not found !!!!!!!")
end
unzip = unzippath
end
end
task.sync_remote = function(self,name,version,url)
print(string.format("sync remote package:%s",url))
local workdir = filepath.join(loader.Config.GlobalRepo,"curl",name)
if not fs.exists(workdir) then
fs.mkdir(workdir,true)
end
print(curl)
local exec = sys.exec(curl)
exec:dir(workdir)
-- --
local tmpfile = string.format("%s.tmp",version)
--
exec:start("-o",tmpfile,"-k",url)
if 0 ~= exec:wait() then
console:E("download remote package error :%s",url)
return true
end
local outputdir = filepath.join(workdir,version)
-- if fs.exists(outputdir) then
-- fs.rm(outputdir,true)
-- end
local exec = sys.exec(unzip)
exec:dir(workdir)
exec:start("x","-aoa",string.format("-o%s",version),filepath.join(workdir,tmpfile))
if 0 ~= exec:wait() then
console:E("download remote package error :%s",url)
return true
end
local sourcepath = nil
fs.list(outputdir,function(entry)
if entry == "." or entry == ".." then return end
sourcepath = filepath.join(outputdir,entry)
end)
assert(sourcepath,"7z bug checker")
loader.GSMake.Repo:save_source(name,version,sourcepath,sourcepath,true)
end
task.sync_remote.Desc = "curl downloader#sync_remote"
task.sync_remote.Prev = "sync_init"
task.sync_source = function(self,install_path)
end
task.sync_source.Desc = "curl downloader#sync_source"
task.sync_source.Prev = "sync_init"
|
fix windows curl lookup bug
|
fix windows curl lookup bug
|
Lua
|
mit
|
gsmake/gsmake,gsmake/gsmake
|
246be3208a36a7a917995c2bd691e11ae2f64288
|
modules/admin-full/luasrc/model/cbi/admin_system/fstab.lua
|
modules/admin-full/luasrc/model/cbi/admin_system/fstab.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.tools.webadmin")
local fs = require "luci.fs"
local devices = {}
luci.util.update(devices, fs.glob("/dev/sd*") or {})
luci.util.update(devices, fs.glob("/dev/hd*") or {})
luci.util.update(devices, fs.glob("/dev/scd*") or {})
luci.util.update(devices, fs.glob("/dev/mmc*") or {})
local size = {}
for i, dev in ipairs(devices) do
local s = tonumber((luci.fs.readfile("/sys/class/block/%s/size" % dev:sub(6))))
size[dev] = s and math.floor(s / 2048)
end
m = Map("fstab", translate("a_s_fstab"))
local mounts = luci.sys.mounts()
v = m:section(Table, mounts, translate("a_s_fstab_active"))
fs = v:option(DummyValue, "fs", translate("filesystem"))
mp = v:option(DummyValue, "mountpoint", translate("a_s_fstab_mountpoint"))
avail = v:option(DummyValue, "avail", translate("a_s_fstab_avail"))
function avail.cfgvalue(self, section)
return luci.tools.webadmin.byte_format(
( tonumber(mounts[section].available) or 0 ) * 1024
) .. " / " .. luci.tools.webadmin.byte_format(
( tonumber(mounts[section].blocks) or 0 ) * 1024
)
end
used = v:option(DummyValue, "used", translate("a_s_fstab_used"))
function used.cfgvalue(self, section)
return ( mounts[section].percent or "0%" ) .. " (" ..
luci.tools.webadmin.byte_format(
( tonumber(mounts[section].used) or 0 ) * 1024
) .. ")"
end
mount = m:section(TypedSection, "mount", translate("a_s_fstab_mountpoints"), translate("a_s_fstab_mountpoints1"))
mount.anonymous = true
mount.addremove = true
mount.template = "cbi/tblsection"
mount:option(Flag, "enabled", translate("enable"))
dev = mount:option(Value, "device", translate("device"), translate("a_s_fstab_device1"))
for i, d in ipairs(devices) do
dev:value(d, size[d] and "%s (%s MB)" % {d, size[d]})
end
mount:option(Value, "target", translate("a_s_fstab_mountpoint"))
mount:option(Value, "fstype", translate("filesystem"), translate("a_s_fstab_fs1"))
mount:option(Value, "options", translate("options"), translatef("manpage", "siehe '%s' manpage", "mount"))
swap = m:section(TypedSection, "swap", "SWAP", translate("a_s_fstab_swap1"))
swap.anonymous = true
swap.addremove = true
swap.template = "cbi/tblsection"
swap:option(Flag, "enabled", translate("enable"))
dev = swap:option(Value, "device", translate("device"), translate("a_s_fstab_device1"))
for i, d in ipairs(devices) do
dev:value(d, size[d] and "%s (%s MB)" % {d, size[d]})
end
return m
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.tools.webadmin")
local fs = require "luci.fs"
local devices = {}
luci.util.update(devices, fs.glob("/dev/sd*") or {})
luci.util.update(devices, fs.glob("/dev/hd*") or {})
luci.util.update(devices, fs.glob("/dev/scd*") or {})
luci.util.update(devices, fs.glob("/dev/mmc*") or {})
local size = {}
for i, dev in ipairs(devices) do
local s = tonumber((luci.fs.readfile("/sys/class/block/%s/size" % dev:sub(6))))
size[dev] = s and math.floor(s / 2048)
end
m = Map("fstab", translate("a_s_fstab"))
local mounts = luci.sys.mounts()
v = m:section(Table, mounts, translate("a_s_fstab_active"))
fs = v:option(DummyValue, "fs", translate("filesystem"))
mp = v:option(DummyValue, "mountpoint", translate("a_s_fstab_mountpoint"))
avail = v:option(DummyValue, "avail", translate("a_s_fstab_avail"))
function avail.cfgvalue(self, section)
return luci.tools.webadmin.byte_format(
( tonumber(mounts[section].available) or 0 ) * 1024
) .. " / " .. luci.tools.webadmin.byte_format(
( tonumber(mounts[section].blocks) or 0 ) * 1024
)
end
used = v:option(DummyValue, "used", translate("a_s_fstab_used"))
function used.cfgvalue(self, section)
return ( mounts[section].percent or "0%" ) .. " (" ..
luci.tools.webadmin.byte_format(
( tonumber(mounts[section].used) or 0 ) * 1024
) .. ")"
end
mount = m:section(TypedSection, "mount", translate("a_s_fstab_mountpoints"), translate("a_s_fstab_mountpoints1"))
mount.anonymous = true
mount.addremove = true
mount.template = "cbi/tblsection"
mount:option(Flag, "enabled", translate("enable")).rmempty = false
dev = mount:option(Value, "device", translate("device"), translate("a_s_fstab_device1"))
for i, d in ipairs(devices) do
dev:value(d, size[d] and "%s (%s MB)" % {d, size[d]})
end
mount:option(Value, "target", translate("a_s_fstab_mountpoint"))
mount:option(Value, "fstype", translate("filesystem"), translate("a_s_fstab_fs1"))
mount:option(Value, "options", translate("options"), translatef("manpage", "siehe '%s' manpage", "mount"))
swap = m:section(TypedSection, "swap", "SWAP", translate("a_s_fstab_swap1"))
swap.anonymous = true
swap.addremove = true
swap.template = "cbi/tblsection"
swap:option(Flag, "enabled", translate("enable")).rmempty = false
dev = swap:option(Value, "device", translate("device"), translate("a_s_fstab_device1"))
for i, d in ipairs(devices) do
dev:value(d, size[d] and "%s (%s MB)" % {d, size[d]})
end
return m
|
Fix: Mountpoints cannot be disabled
|
Fix: Mountpoints cannot be disabled
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@4602 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
ReclaimYourPrivacy/cloak-luci,saraedum/luci-packages-old,jschmidlapp/luci,zwhfly/openwrt-luci,ch3n2k/luci,yeewang/openwrt-luci,phi-psi/luci,gwlim/luci,vhpham80/luci,phi-psi/luci,freifunk-gluon/luci,yeewang/openwrt-luci,stephank/luci,gwlim/luci,yeewang/openwrt-luci,saraedum/luci-packages-old,jschmidlapp/luci,saraedum/luci-packages-old,eugenesan/openwrt-luci,ThingMesh/openwrt-luci,ReclaimYourPrivacy/cloak-luci,zwhfly/openwrt-luci,8devices/carambola2-luci,freifunk-gluon/luci,zwhfly/openwrt-luci,eugenesan/openwrt-luci,dtaht/cerowrt-luci-3.3,projectbismark/luci-bismark,projectbismark/luci-bismark,stephank/luci,dtaht/cerowrt-luci-3.3,zwhfly/openwrt-luci,vhpham80/luci,eugenesan/openwrt-luci,freifunk-gluon/luci,ch3n2k/luci,alxhh/piratenluci,Canaan-Creative/luci,dtaht/cerowrt-luci-3.3,ThingMesh/openwrt-luci,ReclaimYourPrivacy/cloak-luci,gwlim/luci,8devices/carambola2-luci,eugenesan/openwrt-luci,Canaan-Creative/luci,eugenesan/openwrt-luci,projectbismark/luci-bismark,gwlim/luci,Flexibity/luci,phi-psi/luci,8devices/carambola2-luci,alxhh/piratenluci,Flexibity/luci,zwhfly/openwrt-luci,ch3n2k/luci,yeewang/openwrt-luci,freifunk-gluon/luci,8devices/carambola2-luci,alxhh/piratenluci,projectbismark/luci-bismark,ch3n2k/luci,alxhh/piratenluci,Flexibity/luci,saraedum/luci-packages-old,jschmidlapp/luci,vhpham80/luci,freifunk-gluon/luci,Flexibity/luci,freifunk-gluon/luci,Canaan-Creative/luci,Flexibity/luci,Canaan-Creative/luci,projectbismark/luci-bismark,Flexibity/luci,ReclaimYourPrivacy/cloak-luci,ThingMesh/openwrt-luci,freifunk-gluon/luci,phi-psi/luci,stephank/luci,ReclaimYourPrivacy/cloak-luci,ch3n2k/luci,yeewang/openwrt-luci,Flexibity/luci,zwhfly/openwrt-luci,ch3n2k/luci,Canaan-Creative/luci,dtaht/cerowrt-luci-3.3,alxhh/piratenluci,jschmidlapp/luci,projectbismark/luci-bismark,phi-psi/luci,ReclaimYourPrivacy/cloak-luci,jschmidlapp/luci,gwlim/luci,8devices/carambola2-luci,dtaht/cerowrt-luci-3.3,saraedum/luci-packages-old,zwhfly/openwrt-luci,ThingMesh/openwrt-luci,ReclaimYourPrivacy/cloak-luci,jschmidlapp/luci,yeewang/openwrt-luci,8devices/carambola2-luci,projectbismark/luci-bismark,yeewang/openwrt-luci,projectbismark/luci-bismark,jschmidlapp/luci,Canaan-Creative/luci,Canaan-Creative/luci,ReclaimYourPrivacy/cloak-luci,freifunk-gluon/luci,ThingMesh/openwrt-luci,saraedum/luci-packages-old,vhpham80/luci,vhpham80/luci,gwlim/luci,phi-psi/luci,stephank/luci,Canaan-Creative/luci,alxhh/piratenluci,stephank/luci,jschmidlapp/luci,ThingMesh/openwrt-luci,ThingMesh/openwrt-luci,eugenesan/openwrt-luci,stephank/luci,vhpham80/luci,saraedum/luci-packages-old,eugenesan/openwrt-luci,zwhfly/openwrt-luci,gwlim/luci,8devices/carambola2-luci,ch3n2k/luci,phi-psi/luci,dtaht/cerowrt-luci-3.3,zwhfly/openwrt-luci,alxhh/piratenluci,Flexibity/luci
|
350724470e02ce9f2ce2de13e51c0d35f3d2475e
|
cardshifter-fx/src/main/resources/com/cardshifter/core/start.lua
|
cardshifter-fx/src/main/resources/com/cardshifter/core/start.lua
|
-- Always name this function "startGame"
function startGame(game)
local endturnAction = require "src/main/resources/com/cardshifter/core/actions/player/endturn"
game:on('actionUsed', onActionUsed)
game:on('turnStart', onTurnStart)
local numPlayers = game:getPlayers():size()
for i = 0, numPlayers - 1 do
local player = game:getPlayer(i)
print("Player: " .. player:toString())
player:addAction("End Turn", endturnAction.isAllowed, endturnAction.perform)
player.data.life = 10
player.data.mana = 0
player.data.manaMax = 0
player.data.scrap = 0
player.data.cardType = 'Player'
local field = game:createZone(player, "Battlefield")
field:setGloballyKnown(true)
player.data.battlefield = field
local deck = game:createZone(player, "Deck")
player.data.deck = deck
local hand = game:createZone(player, "Hand")
hand:setKnown(player, true)
player.data.hand = hand
for i = 1, 4 do
local card
for strength = 1, 5 do
card = createCreature(deck, strength, strength, strength, 'B0T')
if strength == 2 then
card.data.strength = card.data.strength + 1
end
end
card = createCreature(deck, 5, 4, 4, 'Bio')
card = createCreature(deck, 5, 5, 3, 'Bio')
card = createCreature(deck, 5, 3, 5, 'Bio')
card = createEnchantment(deck, 1, 0, 1)
card = createEnchantment(deck, 0, 1, 1)
card = createEnchantment(deck, 3, 0, 3)
card = createEnchantment(deck, 0, 3, 3)
card = createSpecialEnchantment(deck, 2, 2, 5)
end
deck:shuffle()
for i=1,5 do
drawCard(player)
end
end
-- Turn Start event is not called when starting game (player should not draw card), setup initial mana for first player
firstPlayer = game:getFirstPlayer()
firstPlayer.data.mana = 1
firstPlayer.data.manaMax = 1
end
function createSpecialEnchantment(deck, strength, health, cost)
local enchantspecialAction = require "src/main/resources/com/cardshifter/core/actions/card/enchantspecial"
-- A special enchantment can only target a creature that has been enchanted already
local card = deck:createCardOnBottom()
card:addTargetAction("Enchant", enchantspecialAction.isAllowed, enchantspecialAction.perform, enchantspecialAction.isTargetAllowed)
card.data.manaCost = 0
card.data.scrapCost = cost
card.data.enchStrength = strength
card.data.enchHealth = health
card.data.cardType = 'Enchantment'
return card
end
function createEnchantment(deck, strength, health, cost)
local enchantAction = require "src/main/resources/com/cardshifter/core/actions/card/enchant"
-- Can only target creatureType == 'Bio'
local card = deck:createCardOnBottom()
card:addTargetAction("Enchant", enchantAction.isAllowed, enchantAction.perform, enchantAction.isTargetAllowed)
card.data.manaCost = 0
card.data.scrapCost = cost
card.data.enchStrength = strength
card.data.enchHealth = health
card.data.cardType = 'Enchantment'
return card
end
function createCreature(deck, cost, strength, health, creatureType)
local playAction = require "src/main/resources/com/cardshifter/core/actions/card/play"
local attackAction = require "src/main/resources/com/cardshifter/core/actions/card/attack"
local scrapAction = require "src/main/resources/com/cardshifter/core/actions/card/scrap"
local card = deck:createCardOnBottom()
card:addAction("Play", playAction.isAllowed, playAction.perform)
card:addTargetAction("Attack", attackAction.isAllowed, attackAction.perform, attackAction.isTargetAllowed)
card:addAction("Scrap", scrapAction.isAllowed, scrapAction.perform)
card.data.manaCost = cost
card.data.strength = strength
card.data.health = health
card.data.enchantments = 0
card.data.creatureType = creatureType
card.data.cardType = 'Creature'
card.data.sickness = 1
card.data.attacksAvailable = 1
return card
end
function onActionUsed(card, action)
print("(This is Lua) Action Used! " .. card:toString() .. " with action " .. action:toString())
end
function onTurnStart(player, event)
print("(This is Lua) Turn Start! " .. player:toString())
if player.data.deck:isEmpty() then
print("(This is Lua) Deck is empty!")
end
local field = player.data.battlefield
local iterator = field:getCards():iterator()
while iterator:hasNext() do
local card = iterator:next()
if card.data.sickness > 0 then
card.data.sickness = card.data.sickness - 1
print("Card on field now has sickness" .. card.data.sickness)
end
card.data.attacksAvailable = 1
end
drawCard(player)
player.data.manaMax = player.data.manaMax + 1
player.data.mana = player.data.manaMax
end
function drawCard(player)
local card = player.data.deck:getTopCard()
card:moveToBottomOf(player.data.hand)
end
|
-- Always name this function "startGame"
function startGame(game)
local endturnAction = require "src/main/resources/com/cardshifter/core/actions/player/endturn"
game:on('actionUsed', onActionUsed)
game:on('turnStart', onTurnStart)
local numPlayers = game:getPlayers():size()
for i = 0, numPlayers - 1 do
local player = game:getPlayer(i)
print("Player: " .. player:toString())
player:addAction("End Turn", endturnAction.isAllowed, endturnAction.perform)
player.data.life = 10
player.data.mana = 0
player.data.manaMax = 0
player.data.scrap = 0
player.data.cardType = 'Player'
local field = game:createZone(player, "Battlefield")
field:setGloballyKnown(true)
player.data.battlefield = field
local deck = game:createZone(player, "Deck")
player.data.deck = deck
local hand = game:createZone(player, "Hand")
hand:setKnown(player, true)
player.data.hand = hand
for i = 1, 4 do
local card
for strength = 1, 5 do
card = createCreature(deck, strength, strength, strength, 'B0T')
if strength == 2 then
card.data.strength = card.data.strength + 1
end
end
card = createCreature(deck, 5, 4, 4, 'Bio')
card = createCreature(deck, 5, 5, 3, 'Bio')
card = createCreature(deck, 5, 3, 5, 'Bio')
card = createEnchantment(deck, 1, 0, 1)
card = createEnchantment(deck, 0, 1, 1)
card = createEnchantment(deck, 3, 0, 3)
card = createEnchantment(deck, 0, 3, 3)
card = createSpecialEnchantment(deck, 2, 2, 5)
end
deck:shuffle()
for i=1,5 do
drawCard(player)
end
end
-- Turn Start event is not called when starting game (player should not draw card), setup initial mana for first player
firstPlayer = game:getFirstPlayer()
firstPlayer.data.mana = 1
firstPlayer.data.manaMax = 1
end
function createSpecialEnchantment(deck, strength, health, cost)
local enchantspecialAction = require "src/main/resources/com/cardshifter/core/actions/card/enchantspecial"
-- A special enchantment can only target a creature that has been enchanted already
local card = deck:createCardOnBottom()
card:addTargetAction("Enchant", enchantspecialAction.isAllowed, enchantspecialAction.perform, enchantspecialAction.isTargetAllowed)
card.data.manaCost = 0
card.data.scrapCost = cost
card.data.enchStrength = strength
card.data.enchHealth = health
card.data.cardType = 'Enchantment'
return card
end
function createEnchantment(deck, strength, health, cost)
local enchantAction = require "src/main/resources/com/cardshifter/core/actions/card/enchant"
-- Can only target creatureType == 'Bio'
local card = deck:createCardOnBottom()
card:addTargetAction("Enchant", enchantAction.isAllowed, enchantAction.perform, enchantAction.isTargetAllowed)
card.data.manaCost = 0
card.data.scrapCost = cost
card.data.enchStrength = strength
card.data.enchHealth = health
card.data.cardType = 'Enchantment'
return card
end
function createCreature(deck, cost, strength, health, creatureType)
local playAction = require "src/main/resources/com/cardshifter/core/actions/card/play"
local attackAction = require "src/main/resources/com/cardshifter/core/actions/card/attack"
local scrapAction = require "src/main/resources/com/cardshifter/core/actions/card/scrap"
local card = deck:createCardOnBottom()
card:addAction("Play", playAction.isAllowed, playAction.perform)
card:addTargetAction("Attack", attackAction.isAllowed, attackAction.perform, attackAction.isTargetAllowed)
card:addAction("Scrap", scrapAction.isAllowed, scrapAction.perform)
card.data.manaCost = cost
card.data.strength = strength
card.data.health = health
card.data.enchantments = 0
card.data.creatureType = creatureType
card.data.cardType = 'Creature'
card.data.sickness = 1
card.data.attacksAvailable = 1
return card
end
function onActionUsed(card, action)
print("(This is Lua) Action Used! " .. card:toString() .. " with action " .. action:toString())
end
function onTurnStart(player, event)
print("(This is Lua) Turn Start! " .. player:toString())
local field = player.data.battlefield
local iterator = field:getCards():iterator()
while iterator:hasNext() do
local card = iterator:next()
if card.data.sickness > 0 then
card.data.sickness = card.data.sickness - 1
print("Card on field now has sickness" .. card.data.sickness)
end
card.data.attacksAvailable = 1
end
if not drawCard(player) then
player.data.life = player.data.life - 1
if player.data.life <= 0 then
player:getGame():gameOver()
end
print("(This is Lua) Deck is empty! One damage taken.")
end
player.data.manaMax = player.data.manaMax + 1
player.data.mana = player.data.manaMax
end
function drawCard(player)
if player.data.deck:isEmpty() then
return false
end
local card = player.data.deck:getTopCard()
card:moveToBottomOf(player.data.hand)
return true
end
|
Also fixed #13 for JavaFX
|
Also fixed #13 for JavaFX
|
Lua
|
apache-2.0
|
Cardshifter/Cardshifter,Cardshifter/Cardshifter,June92/Cardshifter,SirPython/Cardshifter,June92/Cardshifter,June92/Cardshifter,SirPython/Cardshifter,SirPython/Cardshifter,Cardshifter/Cardshifter
|
83f3faf4a3a66fa720652507cacda5cb7640e5e3
|
otouto/plugins/currency.lua
|
otouto/plugins/currency.lua
|
local currency = {}
currency.command = 'cash [Menge] <von> <zu>'
function currency:init(config)
currency.triggers = {
"^/cash ([A-Za-z]+)$",
"^/cash ([A-Za-z]+) ([A-Za-z]+)$",
"^/cash (%d+[%d%.,]*) ([A-Za-z]+) ([A-Za-z]+)$",
"^(/eur)$"
}
currency.doc = [[*
]]..config.cmd_pat..[[cash* _[Menge]_ _<von>_ _<zu>_
Beispiel: _]]..config.cmd_pat..[[cash 5 USD EUR_]]
end
function currency:action(msg, config)
if not matches[2] then
from = string.upper(matches[1])
to = 'EUR'
amount = 1
elseif matches[3] then
from = string.upper(matches[2])
to = string.upper(matches[3])
amount = matches[1]
else
from = string.upper(matches[1])
to = string.upper(matches[2])
amount = 1
end
local amount = string.gsub(amount, ",", ".")
amount = tonumber(amount)
local result = 1
local BASE_URL = 'https://www.google.com/finance/converter'
if from == to then
utilities.send_reply(self, msg, 'Jaja, sehr witzig...')
return
end
local url = BASE_URL..'?from='..from..'&to='..to..'&a='..amount
local str, res = https.request(url)
if res ~= 200 then
utilities.send_reply(self, msg, config.errors.connection)
return
end
local str = str:match('<span class=bld>(.*) %u+</span>')
if not str then
utilities.send_reply(self, msg, 'Keine gültige Währung - sieh dir die Währungsliste bei [Google Finanzen](https://www.google.com/finance/converter) an.', true)
return
end
local result = string.format('%.2f', str)
local result = string.gsub(result, "%.", ",")
local amount = tostring(string.gsub(amount, "%.", ","))
local output = amount..' '..from..' = *'..result..' '..to..'*'
utilities.send_reply(self, msg, output, true)
end
return currency
|
local currency = {}
currency.command = 'cash [Menge] <von> <zu>'
function currency:init(config)
currency.triggers = {
"^/cash ([A-Za-z]+)$",
"^/cash ([A-Za-z]+) ([A-Za-z]+)$",
"^/cash (%d+[%d%.,]*) ([A-Za-z]+) ([A-Za-z]+)$",
"^(/cash)$"
}
currency.inline_triggers = {
"^c ([A-Za-z]+)$",
"^c ([A-Za-z]+) ([A-Za-z]+)$",
"^c (%d+[%d%.,]*) ([A-Za-z]+) ([A-Za-z]+)$"
}
currency.doc = [[*
]]..config.cmd_pat..[[cash* _[Menge]_ _<von>_ _<zu>_
*]]..config.cmd_pat..[[cash* _<von>_: Rechnet in Euro um
*]]..config.cmd_pat..[[cash* _<von>_ _<zu>_: Rechnet mit der Einheit 1
Beispiel: _]]..config.cmd_pat..[[cash 5 USD EUR_]]
end
local BASE_URL = 'https://api.fixer.io'
function currency:inline_callback(inline_query, config, matches)
if not matches[2] then -- first pattern
base = 'EUR'
to = string.upper(matches[1])
amount = 1
elseif matches[3] then -- third pattern
base = string.upper(matches[2])
to = string.upper(matches[3])
amount = matches[1]
else -- second pattern
base = string.upper(matches[1])
to = string.upper(matches[2])
amount = 1
end
local value, iserr = currency:convert_money(base, to, amount)
if iserr then utilities.answer_inline_query(self, inline_query) return end
local output = amount..' '..base..' = *'..value..' '..to..'*'
if tonumber(amount) == 1 then
title = amount..' '..base..' entspricht'
else
title = amount..' '..base..' entsprechen'
end
local results = '[{"type":"article","id":"20","title":"'..title..'","description":"'..value..' '..to..'","thumb_url":"https://anditest.perseus.uberspace.de/inlineQuerys/currency/cash.jpg","thumb_width":157,"thumb_height":140,"input_message_content":{"message_text":"'..output..'","parse_mode":"Markdown"}}]'
utilities.answer_inline_query(self, inline_query, results, 3600)
end
function currency:convert_money(base, to, amount)
local url = BASE_URL..'/latest?base='..base..'&symbols='..to
local amount = string.gsub(amount, ",", ".")
local amount = tonumber(amount)
local res, code = https.request(url)
if code ~= 200 and code ~= 422 then
return 'NOCONNECT', true
end
local res, code = https.request(url)
local data = json.decode(res)
if data.error then
return 'WRONGBASE', true
end
local rate = data.rates[to]
if not rate then
return 'WRONGCONVERTRATE', true
end
if amount == 1 then
value = round(rate, 2)
else
value = round(rate * amount, 2)
end
local value = tostring(string.gsub(value, "%.", ","))
return value
end
function currency:action(msg, config, matches)
if matches[1] == '/cash' then
utilities.send_reply(self, msg, currency.doc, true)
return
elseif not matches[2] then -- first pattern
base = 'EUR'
to = string.upper(matches[1])
amount = 1
elseif matches[3] then -- third pattern
base = string.upper(matches[2])
to = string.upper(matches[3])
amount = matches[1]
else -- second pattern
base = string.upper(matches[1])
to = string.upper(matches[2])
amount = 1
end
if from == to then
utilities.send_reply(self, msg, 'Jaja, sehr witzig...')
return
end
local value = currency:convert_money(base, to, amount)
if value == 'NOCONNECT' then
utilities.send_reply(self, msg, config.errors.connection)
return
elseif value == 'WRONGBASE' then
utilities.send_reply(self, msg, 'Keine gültige Basiswährung.')
return
elseif value == 'WRONGCONVERTRATE' then
utilities.send_reply(self, msg, 'Keine gültige Umwandlungswährung.')
return
end
local output = amount..' '..base..' = *'..value..' '..to..'*'
utilities.send_reply(self, msg, output, true)
end
return currency
|
Currency: Stelle auf Fixer.io um und ergänze Inline (danke @Centzilius)
|
Currency: Stelle auf Fixer.io um und ergänze Inline (danke @Centzilius)
|
Lua
|
agpl-3.0
|
Brawl345/Brawlbot-v2
|
4c1c749057fa1c760b2338d82e824e99774ddeb6
|
deps/buffer.lua
|
deps/buffer.lua
|
--[[
Copyright 2014-2015 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
exports.name = "luvit/buffer"
exports.version = "1.0.0"
local Object = require('core').Object
local ffi = require('ffi')
ffi.cdef([[
void *malloc (size_t __size);
void free (void *__ptr);
]])
local buffer = exports
local Buffer = Object:extend()
buffer.Buffer = Buffer
function Buffer:initialize(length)
if type(length) == "number" then
self.length = length
self.ctype = ffi.gc(ffi.cast("unsigned char*", ffi.C.malloc(length)), ffi.C.free)
elseif type(length) == "string" then
local string = length
self.length = #string
self.ctype = ffi.cast("unsigned char*", string)
else
error("Input must be a string or number")
end
end
function Buffer.meta:__ipairs()
local index = 0
return function ()
if index < self.length then
index = index + 1
return index, self[index]
end
end
end
function Buffer.meta:__tostring()
return ffi.string(self.ctype)
end
function Buffer.meta:__concat(other)
return tostring(self) .. tostring(other)
end
function Buffer.meta:__index(key)
if type(key) == "number" then
if key < 1 or key > self.length then error("Index out of bounds") end
return self.ctype[key - 1]
end
return Buffer[key]
end
function Buffer.meta:__newindex(key, value)
if type(key) == "number" then
if key < 1 or key > self.length then error("Index out of bounds") end
self.ctype[key - 1] = value
return
end
rawset(self, key, value)
end
function Buffer:inspect()
local parts = {}
for i = 1, tonumber(self.length) do
parts[i] = bit.tohex(self[i], 2)
end
return "<Buffer " .. table.concat(parts, " ") .. ">"
end
local function compliment8(value)
return value < 0x80 and value or -0x100 + value
end
function Buffer:readUInt8(offset)
return self[offset]
end
function Buffer:readInt8(offset)
return compliment8(self[offset])
end
local function compliment16(value)
return value < 0x8000 and value or -0x10000 + value
end
function Buffer:readUInt16LE(offset)
return bit.lshift(self[offset + 1], 8) +
self[offset]
end
function Buffer:readUInt16BE(offset)
return bit.lshift(self[offset], 8) +
self[offset + 1]
end
function Buffer:readInt16LE(offset)
return compliment16(self:readUInt16LE(offset))
end
function Buffer:readInt16BE(offset)
return compliment16(self:readUInt16BE(offset))
end
function Buffer:readUInt32LE(offset)
return self[offset + 3] * 0x1000000 +
bit.lshift(self[offset + 2], 16) +
bit.lshift(self[offset + 1], 8) +
self[offset]
end
function Buffer:readUInt32BE(offset)
return self[offset] * 0x1000000 +
bit.lshift(self[offset + 1], 16) +
bit.lshift(self[offset + 2], 8) +
self[offset + 3]
end
function Buffer:readInt32LE(offset)
return bit.tobit(self:readUInt32LE(offset))
end
function Buffer:readInt32BE(offset)
return bit.tobit(self:readUInt32BE(offset))
end
function Buffer:toString(i, j)
local offset = i and i - 1 or 0
return ffi.string(self.ctype + offset, (j or self.length) - offset)
end
return buffer
|
--[[
Copyright 2014-2015 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
exports.name = "luvit/buffer"
exports.version = "1.0.0"
local Object = require('core').Object
local ffi = require('ffi')
ffi.cdef([[
void *malloc (size_t __size);
void free (void *__ptr);
]])
local buffer = exports
local Buffer = Object:extend()
buffer.Buffer = Buffer
--avoid bugs when link with static run times lib, eg. /MT link flags
local C = ffi.os=='Windows' and ffi.load('msvcrt') or ffi.C
function Buffer:initialize(length)
if type(length) == "number" then
self.length = length
self.ctype = ffi.gc(ffi.cast("unsigned char*", C.malloc(length)), C.free)
elseif type(length) == "string" then
local string = length
self.length = #string
self.ctype = ffi.gc(ffi.cast("unsigned char*", C.malloc(self.length)), C.free)
ffi.copy(self.ctype,string,self.length)
else
error("Input must be a string or number")
end
end
function Buffer.meta:__ipairs()
local index = 0
return function ()
if index < self.length then
index = index + 1
return index, self[index]
end
end
end
function Buffer.meta:__tostring()
return ffi.string(self.ctype,self.length)
end
function Buffer.meta:__concat(other)
return tostring(self) .. tostring(other)
end
function Buffer.meta:__index(key)
if type(key) == "number" then
if key < 1 or key > self.length then error("Index out of bounds") end
return self.ctype[key - 1]
end
return Buffer[key]
end
function Buffer.meta:__newindex(key, value)
if type(key) == "number" then
if key < 1 or key > self.length then error("Index out of bounds") end
self.ctype[key - 1] = value
return
end
rawset(self, key, value)
end
function Buffer:inspect()
local parts = {}
for i = 1, tonumber(self.length) do
parts[i] = bit.tohex(self[i], 2)
end
return "<Buffer " .. table.concat(parts, " ") .. ">"
end
local function compliment8(value)
return value < 0x80 and value or -0x100 + value
end
function Buffer:readUInt8(offset)
return self[offset]
end
function Buffer:readInt8(offset)
return compliment8(self[offset])
end
local function compliment16(value)
return value < 0x8000 and value or -0x10000 + value
end
function Buffer:readUInt16LE(offset)
return bit.lshift(self[offset + 1], 8) +
self[offset]
end
function Buffer:readUInt16BE(offset)
return bit.lshift(self[offset], 8) +
self[offset + 1]
end
function Buffer:readInt16LE(offset)
return compliment16(self:readUInt16LE(offset))
end
function Buffer:readInt16BE(offset)
return compliment16(self:readUInt16BE(offset))
end
function Buffer:readUInt32LE(offset)
return self[offset + 3] * 0x1000000 +
bit.lshift(self[offset + 2], 16) +
bit.lshift(self[offset + 1], 8) +
self[offset]
end
function Buffer:readUInt32BE(offset)
return self[offset] * 0x1000000 +
bit.lshift(self[offset + 1], 16) +
bit.lshift(self[offset + 2], 8) +
self[offset + 3]
end
function Buffer:readInt32LE(offset)
return bit.tobit(self:readUInt32LE(offset))
end
function Buffer:readInt32BE(offset)
return bit.tobit(self:readUInt32BE(offset))
end
function Buffer:toString(i, j)
local offset = i and i - 1 or 0
return ffi.string(self.ctype + offset, (j or self.length) - offset)
end
return buffer
|
fix bug when luajit link with static run times lib, eg. /MT link flags
|
fix bug when luajit link with static run times lib, eg. /MT link flags
|
Lua
|
apache-2.0
|
bsn069/luvit,kaustavha/luvit,bsn069/luvit,zhaozg/luvit,zhaozg/luvit,kaustavha/luvit,luvit/luvit,luvit/luvit,bsn069/luvit,kaustavha/luvit
|
003db709c33e3b1c73141c683bc234e63883f3fa
|
src/premake5.lua
|
src/premake5.lua
|
vk_path = os.getenv("VULKAN_SDK");
if (vk_path == nil) then
vk_path = os.getenv("VK_SDK_PATH")
end
if (vk_path == nil) then
print("No vulkan sdk path. Set environment variable VULKAN_SDK or VK_SDK_PATH to the vulkan sdk directory")
os.exit()
end
workspace("Frodo")
startproject "Sandbox"
location "../solution/"
cppdialect "c++14"
platforms "x64"
configurations {
"Release",
"Debug"
}
includedirs {
"Frodo-core/",
vk_path .. "/Include/vulkan/"
}
-- Global
floatingpoint "Fast"
intrinsics "on"
architecture "x86_64"
defines "FD_PLATFORM_X64"
callingconvention "FastCall"
filter {"Release"}
optimize "Speed"
inlining "Auto"
filter {"Debug"}
optimize "Off"
inlining "Disabled"
-- Windows Specific
filter("system:windows")
defines {
"FD_WINDOWS",
"_CRT_NON_CONFORMING_SWPRINTFS",
"_CRT_SECURE_NO_WARNINGS"
}
filter {"system:windows", "Release"}
buildoptions {
"/GL",
"/sdl-",
"/Ot",
"/GS-",
"/arch:AVX2"
}
linkoptions {
"/LTCG:incremental"
}
filter {"system:windows", "Debug"}
buildoptions {
"/sdl",
"/arch:AVX2"
}
-- Linux Specific
filter("system:linux")
defines {
"FD_LINUX"
}
filter {"system:linux", "Release"}
buildoptions {
"-msse4.1",
"-mfma",
"-mavx2",
"-fpermissive"
}
filter {"system:linux", "Debug"}
buildoptions {
"-msse4.1",
"-mfma",
"-mavx2",
"-fpermissive"
}
filter ""
targetdir "../bin/%{cfg.buildcfg}/%{cfg.platform}/"
objdir "../bin/%{cfg.buildcfg}/%{cfg.platform}/intermediates"
project("Frodo-core")
kind "StaticLib"
location "../solution/Frodo-core/"
files {
"Frodo-core/**.cpp",
"Frodo-core/**.h",
"Frodo-core/**.c"
}
filter {"system:linux"}
removefiles {
"Frodo-core/**WIN*.*"
}
filter {"system:windows"}
removefiles {
"Frodo-core/**LNX*.*"
}
filter ""
project("Sandbox")
kind "ConsoleApp"
location "../solution/Sandbox"
dependson "Frodo-core"
files {
"Sandbox/**.cpp",
"Sandbox/**.h"
}
includedirs {
"Sandbox/"
}
libdirs { vk_path .. "/Lib/" }
links "Frodo-core"
links "vulkan-1"
filter {"system:windows"}
postbuildcommands { "call \"$(SolutionDir)../src/post.bat\" \"$(SolutionDir)../src/Sandbox/res\"" }
|
vk_path = os.getenv("VULKAN_SDK");
if (vk_path == nil) then
vk_path = os.getenv("VK_SDK_PATH")
end
if (vk_path == nil) then
print("No vulkan sdk path. Set environment variable VULKAN_SDK or VK_SDK_PATH to the vulkan sdk directory")
os.exit()
end
workspace("Frodo")
startproject "Sandbox"
location "../solution/"
cppdialect "c++14"
platforms "x64"
configurations {
"Release",
"Debug"
}
includedirs {
"Frodo-core/",
vk_path .. "/Include/vulkan/"
}
-- Global
floatingpoint "Fast"
intrinsics "on"
architecture "x86_64"
defines "FD_PLATFORM_X64"
callingconvention "FastCall"
filter {"Release"}
optimize "Speed"
inlining "Auto"
defines "FD_RELEASE"
filter {"Debug"}
optimize "Off"
inlining "Disabled"
defines "FD_DEBUG"
-- Windows Specific
filter("system:windows")
defines {
"FD_WINDOWS",
"_CRT_NON_CONFORMING_SWPRINTFS",
"_CRT_SECURE_NO_WARNINGS"
}
filter {"system:windows", "Release"}
buildoptions {
"/GL",
"/sdl-",
"/Ot",
"/GS-",
"/arch:AVX2"
}
linkoptions {
"/LTCG:incremental"
}
filter {"system:windows", "Debug"}
buildoptions {
"/sdl",
"/arch:AVX2"
}
-- Linux Specific
filter("system:linux")
defines {
"FD_LINUX"
}
filter {"system:linux", "Release"}
buildoptions {
"-msse4.1",
"-mfma",
"-mavx2",
"-fpermissive"
}
filter {"system:linux", "Debug"}
buildoptions {
"-msse4.1",
"-mfma",
"-mavx2",
"-fpermissive"
}
filter ""
targetdir "../bin/%{cfg.buildcfg}/%{cfg.platform}/"
objdir "../bin/%{cfg.buildcfg}/%{cfg.platform}/intermediates"
project("Frodo-core")
kind "StaticLib"
location "../solution/Frodo-core/"
files {
"Frodo-core/**.cpp",
"Frodo-core/**.h",
"Frodo-core/**.c"
}
filter {"system:linux"}
removefiles {
"Frodo-core/**WIN*.*"
}
filter {"system:windows"}
removefiles {
"Frodo-core/**LNX*.*"
}
filter ""
project("Sandbox")
kind "ConsoleApp"
location "../solution/Sandbox"
dependson "Frodo-core"
files {
"Sandbox/**.cpp",
"Sandbox/**.h"
}
includedirs {
"Sandbox/"
}
libdirs { vk_path .. "/Lib/" }
links "Frodo-core"
links "vulkan-1"
filter {"system:windows"}
postbuildcommands { "call \"$(SolutionDir)../src/post.bat\" \"$(SolutionDir)../src/Sandbox/res\"" }
|
Fixed defines: FD_DEBUG and FD_RELEASE
|
Fixed defines: FD_DEBUG and FD_RELEASE
|
Lua
|
mit
|
JeppeSRC/Frodo,JeppeSRC/Frodo,JeppeSRC/Frodo
|
46f09b9e6c3d36fe6f7b1866c5fee42117acc1e2
|
plugins/exporter.koplugin/base.lua
|
plugins/exporter.koplugin/base.lua
|
--[[--
Base for highlight exporters.
Each target should inherit from this class and implement *at least* an `export` function.
@module baseexporter
]]
local BaseExporter = {
clipping_dir = require("datastorage"):getDataDir() .. "/clipboard"
}
function BaseExporter:new(o)
o = o or {}
assert(type(o.name) == "string", "name is mandatory")
setmetatable(o, self)
self.__index = self
return o:_init()
end
function BaseExporter:_init()
self.extension = self.extension or self.name
self.is_remote = self.is_remote or false
self.version = self.version or "1.0.0"
self:loadSettings()
return self
end
--[[--
Export timestamp
@treturn string timestamp
]]
function BaseExporter:getTimeStamp()
local ts = self.timestamp or os.time()
return os.date("%Y-%m-%d %H:%M:%S", ts)
end
--[[--
Exporter version
@treturn string version
]]
function BaseExporter:getVersion()
return self.name .. "/" .. self.version
end
--[[--
Loads settings for the exporter
]]
function BaseExporter:loadSettings()
local plugin_settings = G_reader_settings:readSetting("exporter") or {}
self.settings = plugin_settings[self.name] or {}
end
--[[--
Saves settings for the exporter
]]
function BaseExporter:saveSettings()
local plugin_settings = G_reader_settings:readSetting("exporter") or {}
plugin_settings[self.name] = self.settings
G_reader_settings:saveSetting("exporter", plugin_settings)
self.new_settings = true
end
--[[--
Exports a table of booknotes to local format or remote service
@param t table of booknotes
@treturn bool success
]]
function BaseExporter:export(t) end
--[[--
File path where the exporter writes its output
@param t table of booknotes
@treturn string absolute path or nil
]]
function BaseExporter:getFilePath(t)
if not self.is_remote then
return string.format("%s/%s-%s.%s",
self.clipping_dir,
self:getTimeStamp(),
#t == 1 and t[1].title or "all-books",
self.extension)
end
end
--[[--
Configuration menu for the exporter
@treturn table menu with exporter settings
]]
function BaseExporter:getMenuTable()
return {
text = self.name:gsub("^%l", string.upper),
checked_func = function()
return self:isEnabled()
end,
callback = function()
self:toggleEnabled()
end,
}
end
--[[--
Checks if the exporter is ready to export
@treturn bool ready
]]
function BaseExporter:isReadyToExport()
return true
end
--[[--
Checks if the exporter was enabled by the user and it is ready to export
@treturn bool enabled
]]
function BaseExporter:isEnabled()
return self.settings.enabled and self:isReadyToExport()
end
--[[--
Toggles exporter enabled state if it's ready to export
]]
function BaseExporter:toggleEnabled()
if self:isReadyToExport() then
self.settings.enabled = not self.settings.enabled
self:saveSettings()
end
end
return BaseExporter
|
--[[--
Base for highlight exporters.
Each target should inherit from this class and implement *at least* an `export` function.
@module baseexporter
]]
local getSafeFilename = require("util").getSafeFilename
local BaseExporter = {
clipping_dir = require("datastorage"):getDataDir() .. "/clipboard"
}
function BaseExporter:new(o)
o = o or {}
assert(type(o.name) == "string", "name is mandatory")
setmetatable(o, self)
self.__index = self
return o:_init()
end
function BaseExporter:_init()
self.extension = self.extension or self.name
self.is_remote = self.is_remote or false
self.version = self.version or "1.0.0"
self:loadSettings()
return self
end
--[[--
Export timestamp
@treturn string timestamp
]]
function BaseExporter:getTimeStamp()
local ts = self.timestamp or os.time()
return os.date("%Y-%m-%d-%H-%M-%S", ts)
end
--[[--
Exporter version
@treturn string version
]]
function BaseExporter:getVersion()
return self.name .. "/" .. self.version
end
--[[--
Loads settings for the exporter
]]
function BaseExporter:loadSettings()
local plugin_settings = G_reader_settings:readSetting("exporter") or {}
self.settings = plugin_settings[self.name] or {}
end
--[[--
Saves settings for the exporter
]]
function BaseExporter:saveSettings()
local plugin_settings = G_reader_settings:readSetting("exporter") or {}
plugin_settings[self.name] = self.settings
G_reader_settings:saveSetting("exporter", plugin_settings)
self.new_settings = true
end
--[[--
Exports a table of booknotes to local format or remote service
@param t table of booknotes
@treturn bool success
]]
function BaseExporter:export(t) end
--[[--
File path where the exporter writes its output
@param t table of booknotes
@treturn string absolute path or nil
]]
function BaseExporter:getFilePath(t)
if not self.is_remote then
local filename = string.format("%s-%s.%s",
self:getTimeStamp(),
#t == 1 and t[1].title or "all-books",
self.extension)
return self.clipping_dir .. "/" .. getSafeFilename(filename)
end
end
--[[--
Configuration menu for the exporter
@treturn table menu with exporter settings
]]
function BaseExporter:getMenuTable()
return {
text = self.name:gsub("^%l", string.upper),
checked_func = function()
return self:isEnabled()
end,
callback = function()
self:toggleEnabled()
end,
}
end
--[[--
Checks if the exporter is ready to export
@treturn bool ready
]]
function BaseExporter:isReadyToExport()
return true
end
--[[--
Checks if the exporter was enabled by the user and it is ready to export
@treturn bool enabled
]]
function BaseExporter:isEnabled()
return self.settings.enabled and self:isReadyToExport()
end
--[[--
Toggles exporter enabled state if it's ready to export
]]
function BaseExporter:toggleEnabled()
if self:isReadyToExport() then
self.settings.enabled = not self.settings.enabled
self:saveSettings()
end
end
return BaseExporter
|
exporter.koplugin: use safe filename
|
exporter.koplugin: use safe filename
fix #9130: files missing in some devices.
|
Lua
|
agpl-3.0
|
koreader/koreader,NiLuJe/koreader,poire-z/koreader,poire-z/koreader,NiLuJe/koreader,Frenzie/koreader,Frenzie/koreader,koreader/koreader
|
83c86bf78d306eaf5ef808f46b979ab04993ed96
|
extensions/hints/init.lua
|
extensions/hints/init.lua
|
--- === hs.hints ===
---
--- Switch focus with a transient per-application keyboard shortcut
local hints = require "hs.hints.internal"
local screen = require "hs.screen"
local window = require "hs.window"
local hotkey = require "hs.hotkey"
local modal_hotkey = hotkey.modal
--- hs.hints.hintChars
--- Variable
--- This controls the set of characters that will be used for window hints. They must be characters found in hs.keycodes.map
--- The default is the letters A-Z.
hints.hintChars = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"}
--- hs.hints.style
--- Variable
--- If this is set to "vimperator", every window hint starts with the first character
--- of the parent application's title
hints.style = "default"
--- hs.hints.fontName
--- Variable
--- A fully specified family-face name, preferrably the PostScript name, such as Helvetica-BoldOblique or Times-Roman. (The Font Book app displays PostScript names of fonts in the Font Info panel.)
--- The default value is the system font
hints.fontName = nil
--- hs.hints.fontSize
--- Variable
--- The size of font that should be used. A value of 0.0 will use the default size.
hints.fontSize = 0.0
local openHints = {}
local takenPositions = {}
local hintDict = {}
local modalKey = nil
local bumpThresh = 40^2
local bumpMove = 80
function hints.bumpPos(x,y)
for i, pos in ipairs(takenPositions) do
if ((pos.x-x)^2 + (pos.y-y)^2) < bumpThresh then
return hints.bumpPos(x,y+bumpMove)
end
end
return {x = x,y = y}
end
function hints.addWindow(dict, win)
local n = dict['count']
if n == nil then
dict['count'] = 0
n = 0
end
local m = (n % #hints.hintChars) + 1
local char = hints.hintChars[m]
if n < #hints.hintChars then
dict[char] = win
else
if type(dict[char]) == "userdata" then
-- dict[m] is already occupied by another window
-- which me must convert into a new dictionary
local otherWindow = dict[char]
dict[char] = {}
hints.addWindow(dict, otherWindow)
end
hints.addWindow(dict[char], win)
end
dict['count'] = dict['count'] + 1
end
function hints.displayHintsForDict(dict, prefixstring)
for key, val in pairs(dict) do
if type(val) == "userdata" then -- this is a window
local win = val
local app = win:application()
local fr = win:frame()
local sfr = win:screen():frame()
if app and win:isStandard() then
local c = {x = fr.x + (fr.w/2) - sfr.x, y = fr.y + (fr.h/2) - sfr.y}
c = hints.bumpPos(c.x, c.y)
if c.y < 0 then
print("hs.hints: Skipping offscreen window: "..win:title())
else
-- print(win:title().." x:"..c.x.." y:"..c.y) -- debugging
local hint = hints.new(c.x, c.y, prefixstring .. key, app:bundleID(), win:screen(), hints.fontName, hints.fontSize)
table.insert(takenPositions, c)
table.insert(openHints, hint)
end
end
elseif type(val) == "table" then -- this is another window dict
hints.displayHintsForDict(val, prefixstring .. key)
end
end
end
function hints.processChar(char)
if hintDict[char] ~= nil then
hints.closeHints()
if type(hintDict[char]) == "userdata" then
if hintDict[char] then hintDict[char]:focus() end
modalKey:exit()
elseif type(hintDict[char]) == "table" then
hintDict = hintDict[char]
if hintDict.count == 1 then
hintDict.A:focus()
modalKey:exit()
else
takenPositions = {}
hints.displayHintsForDict(hintDict, "")
end
end
end
end
function hints.setupModal()
k = modal_hotkey.new(nil, nil)
k:bind({}, 'escape', function() hints.closeHints(); k:exit() end)
for _, c in ipairs(hints.hintChars) do
k:bind({}, c, function() hints.processChar(c) end)
end
return k
end
--- hs.hints.windowHints()
--- Function
--- Displays a keyboard hint for switching focus to each window
---
--- Parameters:
--- * None
---
--- Returns:
--- * None
---
--- Notes:
--- * If there are more windows open than there are characters available in hs.hints.hintChars,
--- we resort to multi-character hints
--- * If hints.style is set to "vimperator", every window hint is prefixed with the first
--- character of the parent application's name
function hints.windowHints()
if (modalKey == nil) then
modalKey = hints.setupModal()
end
hints.closeHints()
hintDict = {}
for i, win in ipairs(window.allWindows()) do
local app = win:application()
if app and win:isStandard() then
if hints.style == "vimperator" then
if app and win:isStandard() then
local appchar = string.upper(string.sub(app:title(), 1, 1))
modalKey:bind({}, appchar, function() hints.processChar(appchar) end)
if hintDict[appchar] == nil then
hintDict[appchar] = {}
end
hints.addWindow(hintDict[appchar], win)
end
else
hints.addWindow(hintDict, win)
end
end
end
takenPositions = {}
if next(hintDict) ~= nil then
hints.displayHintsForDict(hintDict, "")
modalKey:enter()
end
end
function hints.closeHints()
for _, hint in ipairs(openHints) do
hint:close()
end
openHints = {}
takenPositions = {}
end
return hints
|
--- === hs.hints ===
---
--- Switch focus with a transient per-application keyboard shortcut
local hints = require "hs.hints.internal"
local screen = require "hs.screen"
local window = require "hs.window"
local hotkey = require "hs.hotkey"
local modal_hotkey = hotkey.modal
--- hs.hints.hintChars
--- Variable
--- This controls the set of characters that will be used for window hints. They must be characters found in hs.keycodes.map
--- The default is the letters A-Z.
hints.hintChars = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"}
--- hs.hints.style
--- Variable
--- If this is set to "vimperator", every window hint starts with the first character
--- of the parent application's title
hints.style = "default"
--- hs.hints.fontName
--- Variable
--- A fully specified family-face name, preferrably the PostScript name, such as Helvetica-BoldOblique or Times-Roman. (The Font Book app displays PostScript names of fonts in the Font Info panel.)
--- The default value is the system font
hints.fontName = nil
--- hs.hints.fontSize
--- Variable
--- The size of font that should be used. A value of 0.0 will use the default size.
hints.fontSize = 0.0
local openHints = {}
local takenPositions = {}
local hintDict = {}
local modalKey = nil
local bumpThresh = 40^2
local bumpMove = 80
function hints.bumpPos(x,y)
for i, pos in ipairs(takenPositions) do
if ((pos.x-x)^2 + (pos.y-y)^2) < bumpThresh then
return hints.bumpPos(x,y+bumpMove)
end
end
return {x = x,y = y}
end
function hints.addWindow(dict, win)
local n = dict['count']
if n == nil then
dict['count'] = 0
n = 0
end
local m = (n % #hints.hintChars) + 1
local char = hints.hintChars[m]
if n < #hints.hintChars then
dict[char] = win
else
if type(dict[char]) == "userdata" then
-- dict[m] is already occupied by another window
-- which me must convert into a new dictionary
local otherWindow = dict[char]
dict[char] = {}
hints.addWindow(dict, otherWindow)
end
hints.addWindow(dict[char], win)
end
dict['count'] = dict['count'] + 1
end
function hints.displayHintsForDict(dict, prefixstring)
for key, val in pairs(dict) do
if type(val) == "userdata" then -- this is a window
local win = val
local app = win:application()
local fr = win:frame()
local sfr = win:screen():frame()
if app and win:isStandard() then
local c = {x = fr.x + (fr.w/2) - sfr.x, y = fr.y + (fr.h/2) - sfr.y}
local d = hints.bumpPos(c.x, c.y)
if d.y > (sfr.y + sfr.h - bumpMove) then
d.x = d.x + bumpMove
d.y = fr.y + (fr.h/2) - sfr.y
d = hints.bumpPos(d.x, d.y)
end
c = d
if c.y < 0 then
print("hs.hints: Skipping offscreen window: "..win:title())
else
-- print(win:title().." x:"..c.x.." y:"..c.y) -- debugging
local hint = hints.new(c.x, c.y, prefixstring .. key, app:bundleID(), win:screen(), hints.fontName, hints.fontSize)
table.insert(takenPositions, c)
table.insert(openHints, hint)
end
end
elseif type(val) == "table" then -- this is another window dict
hints.displayHintsForDict(val, prefixstring .. key)
end
end
end
function hints.processChar(char)
if hintDict[char] ~= nil then
hints.closeHints()
if type(hintDict[char]) == "userdata" then
if hintDict[char] then hintDict[char]:focus() end
modalKey:exit()
elseif type(hintDict[char]) == "table" then
hintDict = hintDict[char]
if hintDict.count == 1 then
hintDict.A:focus()
modalKey:exit()
else
takenPositions = {}
hints.displayHintsForDict(hintDict, "")
end
end
end
end
function hints.setupModal()
k = modal_hotkey.new(nil, nil)
k:bind({}, 'escape', function() hints.closeHints(); k:exit() end)
for _, c in ipairs(hints.hintChars) do
k:bind({}, c, function() hints.processChar(c) end)
end
return k
end
--- hs.hints.windowHints()
--- Function
--- Displays a keyboard hint for switching focus to each window
---
--- Parameters:
--- * None
---
--- Returns:
--- * None
---
--- Notes:
--- * If there are more windows open than there are characters available in hs.hints.hintChars,
--- we resort to multi-character hints
--- * If hints.style is set to "vimperator", every window hint is prefixed with the first
--- character of the parent application's name
function hints.windowHints()
if (modalKey == nil) then
modalKey = hints.setupModal()
end
hints.closeHints()
hintDict = {}
for i, win in ipairs(window.allWindows()) do
local app = win:application()
if app and win:isStandard() then
if hints.style == "vimperator" then
if app and win:isStandard() then
local appchar = string.upper(string.sub(app:title(), 1, 1))
modalKey:bind({}, appchar, function() hints.processChar(appchar) end)
if hintDict[appchar] == nil then
hintDict[appchar] = {}
end
hints.addWindow(hintDict[appchar], win)
end
else
hints.addWindow(hintDict, win)
end
end
end
takenPositions = {}
if next(hintDict) ~= nil then
hints.displayHintsForDict(hintDict, "")
modalKey:enter()
end
end
function hints.closeHints()
for _, hint in ipairs(openHints) do
hint:close()
end
openHints = {}
takenPositions = {}
end
return hints
|
Fix hs.hints to not run icons off the bottom of the screen if there are lots of them. Closes #211
|
Fix hs.hints to not run icons off the bottom of the screen if there are
lots of them. Closes #211
|
Lua
|
mit
|
ocurr/hammerspoon,junkblocker/hammerspoon,knl/hammerspoon,lowne/hammerspoon,bradparks/hammerspoon,cmsj/hammerspoon,junkblocker/hammerspoon,TimVonsee/hammerspoon,knl/hammerspoon,heptal/hammerspoon,chrisjbray/hammerspoon,Hammerspoon/hammerspoon,tmandry/hammerspoon,latenitefilms/hammerspoon,zzamboni/hammerspoon,CommandPost/CommandPost-App,wsmith323/hammerspoon,dopcn/hammerspoon,latenitefilms/hammerspoon,knu/hammerspoon,asmagill/hammerspoon,chrisjbray/hammerspoon,tmandry/hammerspoon,chrisjbray/hammerspoon,heptal/hammerspoon,Hammerspoon/hammerspoon,latenitefilms/hammerspoon,hypebeast/hammerspoon,joehanchoi/hammerspoon,Habbie/hammerspoon,wsmith323/hammerspoon,Stimim/hammerspoon,zzamboni/hammerspoon,heptal/hammerspoon,Habbie/hammerspoon,ocurr/hammerspoon,CommandPost/CommandPost-App,peterhajas/hammerspoon,TimVonsee/hammerspoon,knu/hammerspoon,Habbie/hammerspoon,cmsj/hammerspoon,asmagill/hammerspoon,joehanchoi/hammerspoon,latenitefilms/hammerspoon,kkamdooong/hammerspoon,hypebeast/hammerspoon,TimVonsee/hammerspoon,bradparks/hammerspoon,zzamboni/hammerspoon,chrisjbray/hammerspoon,ocurr/hammerspoon,emoses/hammerspoon,heptal/hammerspoon,bradparks/hammerspoon,zzamboni/hammerspoon,wvierber/hammerspoon,CommandPost/CommandPost-App,joehanchoi/hammerspoon,zzamboni/hammerspoon,latenitefilms/hammerspoon,lowne/hammerspoon,trishume/hammerspoon,junkblocker/hammerspoon,heptal/hammerspoon,knu/hammerspoon,hypebeast/hammerspoon,hypebeast/hammerspoon,dopcn/hammerspoon,Stimim/hammerspoon,wsmith323/hammerspoon,emoses/hammerspoon,zzamboni/hammerspoon,cmsj/hammerspoon,nkgm/hammerspoon,Hammerspoon/hammerspoon,joehanchoi/hammerspoon,bradparks/hammerspoon,dopcn/hammerspoon,kkamdooong/hammerspoon,trishume/hammerspoon,wvierber/hammerspoon,cmsj/hammerspoon,Hammerspoon/hammerspoon,bradparks/hammerspoon,lowne/hammerspoon,emoses/hammerspoon,CommandPost/CommandPost-App,Hammerspoon/hammerspoon,wvierber/hammerspoon,wsmith323/hammerspoon,junkblocker/hammerspoon,emoses/hammerspoon,wsmith323/hammerspoon,Stimim/hammerspoon,trishume/hammerspoon,knu/hammerspoon,knu/hammerspoon,lowne/hammerspoon,ocurr/hammerspoon,junkblocker/hammerspoon,chrisjbray/hammerspoon,kkamdooong/hammerspoon,nkgm/hammerspoon,peterhajas/hammerspoon,nkgm/hammerspoon,lowne/hammerspoon,nkgm/hammerspoon,asmagill/hammerspoon,latenitefilms/hammerspoon,Hammerspoon/hammerspoon,tmandry/hammerspoon,asmagill/hammerspoon,knl/hammerspoon,peterhajas/hammerspoon,nkgm/hammerspoon,joehanchoi/hammerspoon,dopcn/hammerspoon,asmagill/hammerspoon,knl/hammerspoon,kkamdooong/hammerspoon,Habbie/hammerspoon,wvierber/hammerspoon,CommandPost/CommandPost-App,CommandPost/CommandPost-App,Habbie/hammerspoon,Stimim/hammerspoon,ocurr/hammerspoon,TimVonsee/hammerspoon,kkamdooong/hammerspoon,asmagill/hammerspoon,wvierber/hammerspoon,hypebeast/hammerspoon,chrisjbray/hammerspoon,knu/hammerspoon,cmsj/hammerspoon,emoses/hammerspoon,knl/hammerspoon,peterhajas/hammerspoon,Stimim/hammerspoon,dopcn/hammerspoon,cmsj/hammerspoon,peterhajas/hammerspoon,Habbie/hammerspoon,TimVonsee/hammerspoon
|
46e942b9f84e9bc899d7be577d6c1b883a6097aa
|
luasrc/mch/logger.lua
|
luasrc/mch/logger.lua
|
#!/usr/bin/env lua
-- -*- lua -*-
-- Copyright 2012 Appwill Inc.
-- Author : KDr2
--
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
--
module("mch.logger", package.seeall)
logging = require("logging")
mchutil = require("mch.util")
mchvars = require("mch.vars")
function get_logger(appname)
local logger = mchvars.get(appname, "__LOGGER")
if logger then return logger end
local filename = "/dev/stderr"
local level = "DEBUG"
local log_config = mchutil.get_config(appname, "logger")
if log_config and type(log_config.file) == "string" then
filename = log_config.file
end
if log_config and type(log_config.level) == "string" then
level = log_config.level
end
local f = io.open(filename, "a")
if not f then
return nil, string.format("file `%s' could not be opened for writing", filename)
end
f:setvbuf("line")
local function log_appender(self, level, message)
local date = os.date("%m-%d %H:%M:%S")
local frame = debug.getinfo(2)
local s = string.format('[%s] [%s] [%s:%d] %s\n',
date, level,
string.gsub(frame.short_src, '%.lua$', ''),
frame.currentline,
message)
f:write(s)
return true
end
logger = logging.new(log_appender)
logger:setLevel(level)
mchvars.set(appname, "__LOGGER", logger)
logger._log = logger.log
logger._setLevel = logger.setLevel
logger.log=function(self, level, ...)
local _logger = get_logger(ngx.var.MOOCHINE_APP_NAME)
_logger._log(self, level, ...)
end
logger.setLevel=function(self, level, ...)
local _logger = get_logger(ngx.var.MOOCHINE_APP_NAME)
_logger:_log("ERROR", "Can not setLevel")
end
-- for _, l in ipairs(logging.LEVEL) do -- logging does not export this variable :(
local levels = {d = "DEBUG", i = "INFO", w = "WARN", e = "ERROR", f = "FATAL"}
for k, l in ipairs(levels) do
logger[k] = function(self, ...)
logger.log(self, l, ...)
end
logger[string.lower(l)] = logger[k]
end
return logger
end
function logger()
local logger = get_logger(ngx.var.MOOCHINE_APP_NAME)
return logger
end
|
#!/usr/bin/env lua
-- -*- lua -*-
-- Copyright 2012 Appwill Inc.
-- Author : KDr2
--
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
--
module("mch.logger", package.seeall)
logging = require("logging")
mchutil = require("mch.util")
mchvars = require("mch.vars")
function get_logger(appname)
local logger = mchvars.get(appname, "__LOGGER")
if logger then return logger end
local filename = "/dev/stderr"
local level = "DEBUG"
local log_config = mchutil.get_config(appname, "logger")
if log_config and type(log_config.file) == "string" then
filename = log_config.file
end
if log_config and type(log_config.level) == "string" then
level = log_config.level
end
local f = io.open(filename, "a")
if not f then
return nil, string.format("file `%s' could not be opened for writing", filename)
end
f:setvbuf("line")
local function log_appender(self, level, message)
local date = os.date("%m-%d %H:%M:%S")
local frame = debug.getinfo(2)
local s = string.format('[%s] [%s] [%s:%d] %s\n',
date, level,
string.gsub(frame.short_src, '%.lua$', ''),
frame.currentline,
message)
f:write(s)
return true
end
logger = logging.new(log_appender)
logger:setLevel(level)
mchvars.set(appname, "__LOGGER", logger)
logger._log = logger.log
logger._setLevel = logger.setLevel
logger.log=function(self, level, ...)
local _logger = get_logger(ngx.var.MOOCHINE_APP_NAME)
_logger._log(self, level, ...)
end
logger.setLevel=function(self, level, ...)
local _logger = get_logger(ngx.var.MOOCHINE_APP_NAME)
_logger:_log("ERROR", "Can not setLevel")
end
-- for _, l in ipairs(logging.LEVEL) do -- logging does not export this variable :(
local levels = {d = "DEBUG", i = "INFO", w = "WARN", e = "ERROR", f = "FATAL"}
for k, l in pairs(levels) do
logger[k] = logger[string.lower(l)]
end
return logger
end
function logger()
local logger = get_logger(ngx.var.MOOCHINE_APP_NAME)
return logger
end
|
fix logger's shortened method
|
fix logger's shortened method
|
Lua
|
apache-2.0
|
lilien1010/moochine,lilien1010/moochine,lilien1010/moochine,appwilldev/moochine,appwilldev/moochine
|
b7e6caee95ea498313ab759175e08a77e970e17f
|
source/scenes/singlePlayer/game.lua
|
source/scenes/singlePlayer/game.lua
|
-- TODO: clean this up!
require "source/utilities/vector"
require "source/utilities/extensions/math"
require "source/scenes/singlePlayer/enemy"
require "source/pathfinder"
local Towers = require "assets/towers"
-- import
local flower = flower
local math = math
local vector = vector
local MOAIGridSpace = MOAIGridSpace
local ipairs = ipairs
game = flower.class()
function game:init(t)
-- TODO: pass is variables instead of hardcoding them
self.texture = "hex-tiles.png"
self.width = 50
self.height = 100
self.tileWidth = 128
self.tileHeight = 111
self.radius = 24
self.default_tile = 0
self.direction = 1
self.sideSelect = -1
self.selectName = ""
self.selectCost = ""
self.selectDamage = ""
self.selectRange = ""
self.selectDescription = ""
self.currentCash = 200
self.currentInterest = "0%"
self.currentScore = 0
self.layer = t.layer
self.map = t.map
self:buildGrid()
end
-- This function is used by the guiUtilities file to generate
-- the status field in the UI
function game:generateStatus()
return "Selected: " .. self.selectName ..
"\nCost:" .. self.selectCost ..
"\n" .. self.selectDescription ..
"\nRange:" .. self.selectRange .. " Damage:".. self.selectDamage ..
"\n\nCash: " .. self.currentCash
end
function game:buildGrid()
self.width = self.map.width or self.width
self.height = self.map.height or self.height
self.default_tile = self.map.default_tile or self.default_tile
self.grid = flower.MapImage(self.texture,
self.width,
self.height,
self.tileWidth,
self.tileHeight,
self.radius)
self.grid:setShape(MOAIGridSpace.HEX_SHAPE)
self.grid:setLayer(self.layer)
self.grid:setRepeat(false, false)
self.grid:setPos(0,0)
--print(self.height, self.width)
for i = 1,self.width do
for j = 1,self.height do
self.grid.grid:setTile(i, j, self.default_tile)
end
end
for i, data in ipairs(self.map.tiles) do
for j, pos in ipairs(data) do
self.grid.grid:setTile(pos[1], pos[2], i)
end
end
local targetPos = self.map.paths and self.map.paths[1][#self.map.paths[1]] or self.map.targetPosition
self.path = not self.map.paths and findPath(self.grid.grid, vector{targetPos[1], targetPos[2]})
end
function game:run()
local spawnColor = {1, 0, 0, 1}
self.enemies = {}
-- Timer controlling when enemies spawn
local spawnTimer = flower.Executors.callLoopTime(0.5, function()
-- Extract starting position from map
local startPosition = self.map.paths and self.map.paths[1][1] or self.map.startPosition
if type(startPosition) == "function" then startPosition = startPosition() end
-- Convert starting position into world space
startPosition = vector{self.grid.grid:getTileLoc(startPosition[1], startPosition[2], MOAIGridSpace.TILE_CENTER)}
local newEnemy = enemy {
layer = self.layer,
width = 10, height = 10,
pos = startPosition,
color = spawnColor,
speed = math.randomFloatBetween(2, 5),
grid = self.grid.grid,
map = self.map,
path = self.path,
}
table.insert(self.enemies, newEnemy)
end)
-- Timer controlling when the enemies change color(in the future this could change the wave type)
local colorTimer = flower.Executors.callLoopTime(4, function()
spawnColor = math.generateRandomNumbers(0.1, 1, 4)
spawnColor[4] = math.clamp(spawnColor[4], 0.95, 1.0)
end)
-- Timer to simulate the destruction of enemies
--[[local destroyTimer = flower.Executors.callLoopTime(1, function()
if #self.enemies > 0 then
local randomEnemy = math.random(1, #self.enemies)
self.enemies[randomEnemy]:remove()
table.remove(self.enemies, randomEnemy)
end
end)]]
self.timers = {}
table.insert(self.timers, spawnTimer)
table.insert(self.timers, destroyTimer)
table.insert(self.timers, colorTimer)
self:paused(false)
flower.Executors.callLoop(self.loop, self)
end
function game:loop()
for i, enemy in ipairs(self.enemies) do
if not enemy:update() then
enemy:remove()
table.remove(self.enemies, i)
end
end
while self:paused() do
coroutine.yield()
end
return self:stopped()
end
function game:paused(p)
if p ~= nil then
for i, timer in ipairs(self.timers) do
if p then
timer:pause()
else
timer:start()
end
end
self.isPaused = p
else
return self.isPaused
end
end
function game:stopped(s)
if s ~= nil then
if s == true then
for i, timer in ipairs(self.timers) do
flower.Executors.cancel(timer)
end
for i, enemy in ipairs(self.enemies) do
enemy:remove()
end
end
self.isStopped = s
else
return self.isStopped
end
end
function game:onTouchDown(pos)
local tile = self.grid:getTile(pos[1], pos[2])
-- TODO: highlight map tile
if tile == 5 and self.sideSelect ~= -1 then
if self.currentCash >= Towers[self.sideSelect].cost then
self.currentCash = self.currentCash - Towers[self.sideSelect].cost
self.grid:setTile(pos[1], pos[2], self.sideSelect)
-- TODO: update statusUI for cost
else
-- TODO: alert for insufficient funds
end
elseif tile ~= 5 then
-- TODO: change statusUI for tower select from here
-- TODO: upgrade and sell options appear
end
end
|
-- TODO: clean this up!
require "source/utilities/vector"
require "source/utilities/extensions/math"
require "source/scenes/singlePlayer/enemy"
require "source/pathfinder"
local Towers = require "assets/towers"
-- import
local flower = flower
local math = math
local vector = vector
local MOAIGridSpace = MOAIGridSpace
local ipairs = ipairs
game = flower.class()
function game:init(t)
-- TODO: pass is variables instead of hardcoding them
self.texture = "hex-tiles.png"
self.width = 50
self.height = 100
self.tileWidth = 128
self.tileHeight = 111
self.radius = 24
self.default_tile = 0
self.direction = 1
self.sideSelect = -1
self.selectName = ""
self.selectCost = ""
self.selectDamage = ""
self.selectRange = ""
self.selectDescription = ""
self.currentCash = 200
self.currentInterest = "0%"
self.currentScore = 0
self.layer = t.layer
self.map = t.map
self:buildGrid()
end
-- This function is used by the guiUtilities file to generate
-- the status field in the UI
function game:generateStatus()
return "Selected: " .. self.selectName ..
"\nCost:" .. self.selectCost ..
"\n" .. self.selectDescription ..
"\nRange:" .. self.selectRange .. " Damage:".. self.selectDamage ..
"\n\nCash: " .. self.currentCash
end
function game:buildGrid()
self.width = self.map.width or self.width
self.height = self.map.height or self.height
self.default_tile = self.map.default_tile or self.default_tile
self.grid = flower.MapImage(self.texture,
self.width,
self.height,
self.tileWidth,
self.tileHeight,
self.radius)
self.grid:setShape(MOAIGridSpace.HEX_SHAPE)
self.grid:setLayer(self.layer)
self.grid:setRepeat(false, false)
self.grid:setPos(0,0)
--print(self.height, self.width)
for i = 1,self.width do
for j = 1,self.height do
self.grid.grid:setTile(i, j, self.default_tile)
end
end
for i, data in ipairs(self.map.tiles) do
for j, pos in ipairs(data) do
self.grid.grid:setTile(pos[1], pos[2], i)
end
end
local targetPos = self.map.paths and self.map.paths[1][#self.map.paths[1]] or self.map.targetPosition
self.path = not self.map.paths and findPath(self.grid.grid, vector{targetPos[1], targetPos[2]})
end
function game:run()
local spawnColor = {1, 0, 0, 1}
self.enemies = {}
-- Timer controlling when enemies spawn
local spawnTimer = flower.Executors.callLoopTime(0.5, function()
-- Extract starting position from map
local startPosition = self.map.paths and self.map.paths[1][1] or self.map.startPosition
if type(startPosition) == "function" then startPosition = startPosition() end
-- Convert starting position into world space
startPosition = vector{self.grid.grid:getTileLoc(startPosition[1], startPosition[2], MOAIGridSpace.TILE_CENTER)}
local newEnemy = enemy {
layer = self.layer,
width = 10, height = 10,
pos = startPosition,
color = spawnColor,
speed = math.randomFloatBetween(2, 5),
grid = self.grid.grid,
map = self.map,
path = self.path,
}
table.insert(self.enemies, newEnemy)
end)
-- Timer controlling when the enemies change color(in the future this could change the wave type)
local colorTimer = flower.Executors.callLoopTime(4, function()
spawnColor = math.generateRandomNumbers(0.1, 1, 4)
spawnColor[4] = math.clamp(spawnColor[4], 0.95, 1.0)
end)
-- Timer to simulate the destruction of enemies
--[[local destroyTimer = flower.Executors.callLoopTime(1, function()
if #self.enemies > 0 then
local randomEnemy = math.random(1, #self.enemies)
self.enemies[randomEnemy]:remove()
table.remove(self.enemies, randomEnemy)
end
end)]]
self.timers = {}
table.insert(self.timers, spawnTimer)
table.insert(self.timers, destroyTimer)
table.insert(self.timers, colorTimer)
self:paused(false)
flower.Executors.callLoop(self.loop, self)
end
function game:loop()
for i = #self.enemies, 1, -1 do
local enemy = self.enemies[i]
if not enemy:update() then
enemy:remove()
table.remove(self.enemies, i)
end
end
while self:paused() do
coroutine.yield()
end
return self:stopped()
end
function game:paused(p)
if p ~= nil then
for i, timer in ipairs(self.timers) do
if p then
timer:pause()
else
timer:start()
end
end
self.isPaused = p
else
return self.isPaused
end
end
function game:stopped(s)
if s ~= nil then
if s == true then
for i, timer in ipairs(self.timers) do
flower.Executors.cancel(timer)
end
for i, enemy in ipairs(self.enemies) do
enemy:remove()
end
end
self.isStopped = s
else
return self.isStopped
end
end
function game:onTouchDown(pos)
local tile = self.grid:getTile(pos[1], pos[2])
-- TODO: highlight map tile
if tile == 5 and self.sideSelect ~= -1 then
if self.currentCash >= Towers[self.sideSelect].cost then
self.currentCash = self.currentCash - Towers[self.sideSelect].cost
self.grid:setTile(pos[1], pos[2], self.sideSelect)
-- TODO: update statusUI for cost
else
-- TODO: alert for insufficient funds
end
elseif tile ~= 5 then
-- TODO: change statusUI for tower select from here
-- TODO: upgrade and sell options appear
end
end
|
Fixed bug where an enemy would not be updated.
|
Fixed bug where an enemy would not be updated.
|
Lua
|
mit
|
BryceMehring/Hexel
|
6cafd14a03843927eef53e80d9080f5730b2ac9b
|
scripts/case.lua
|
scripts/case.lua
|
-- demlo script
-- Set case in tags either to title case or sentence case.
-- See https://en.wikipedia.org/wiki/Letter_case.
-- Global options.
local sentencecase = scase or false
local constants = const or {}
-- TODO: No verb? (am, are, was, is) No word > 3 chars? (against, between, from, into, onto)
const_en = const_en or {
'a',
'an',
'and',
'as',
'at',
'but',
'by',
'for',
'if',
'in',
'nor',
'not',
'of',
'on',
'so',
'the',
'to',
'via',
}
const_music = const_music or {
'CD',
'CD1',
'CD2',
'CD3',
'CD4',
'CD5',
'CD6',
'CD7',
'CD8',
'CD9',
'DJ',
'EP',
'feat',
'FX',
}
const_common = const_common or {
'KO',
'OK',
'TV',
'vs',
}
-- Some common units.
const_units = const_units or {
'bps',
'Gbps',
'GHz',
'h', -- hour
'Hz',
'kbps',
'kg',
'kHz',
'km',
'kph',
'Mbps',
'MHz',
'ms',
's', -- second
}
-- Word starting in Mac[X] where [X] is a consonant. See http://visca.com/regexdict/.
const_mac = const_mac or {
'Mache',
'Machete',
'Machicolate',
'Machicolation',
'Machinate',
'Machination',
'Machine',
'Machinery',
'Machinist',
'Machismo',
'Macho',
'Machzor',
'Mackerel',
'Mackinaw',
'Mackintosh',
'Mackle',
'Macle',
'Macrame',
'Macro',
'Macrobiotics',
'Macrocephaly',
'Macroclimate',
'Macrocode',
'Macrocosm',
'Macrocyte',
'Macrocytosis',
'Macroeconomics',
'Macroevolution',
'Macrofossil',
'Macrogamete',
'Macroglobulin',
'Macroglobulinemia',
'Macrograph',
'Macrography',
'Macroinstruction',
'Macromere',
'Macromolecule',
'Macron',
'Macronucleus',
'Macronutrient',
'Macrophage',
'Macrophysics',
'Macrophyte',
'Macropterous',
'Macroscopic',
'Macrosporangium',
'Macrospore',
}
local function pluralize(const)
local result = {}
for _, word in ipairs(const) do
local lastchar = word:sub(-1)
local plural
if lastchar == 'y' then
plural = word:sub(1, -2) .. "ies"
elseif lastchar == 's' then
plural = word
else
plural = word .. "s"
end
result[#result+1] = word
result[#result+1] = plural
end
return result
end
-- Build a table of constants suitable to be passed to 'setcase' as argument.
local function append_constants(const, new)
if type(const) ~= 'table' then
const = {}
end
for _, word in ipairs(new) do
const[word:upper()] = word
end
return const
end
-- "Constants" are written as provided, except if they begin a sentence in which
-- case the first letter is uppercase.
--
-- * Roman numerals are left as is. If lowercase, they are not considered as
-- roman numerals to prevent conflict with common words.
--
-- * Names like D'Arcy, O'Reilly, McDonald and MacNeil are properly handled.
--
-- Options:
--
-- sentencecase: when set to true, only the first letter of every sentence will
-- be capitalized, the other words that are not subject to the rules will be
-- lowercase.
--
-- This script was inspired by http://www.pement.org/awk/titlecase.awk.txt.
local function setcase(input, const, sentencecase)
-- Process words from 'input' one by one and append them to 'output'.
local output = {}
-- Digits and apostrophes are considered part of a word. There are different
-- symbols for apostrophe, some of them which are not ASCII. Apostrophes are
-- assumed not to start or end the word, so that to avoid confusion with
-- quotes.
for nonword, word in input:gmatch([[([^\pL\pN]*)([\pL\pN][\pL\pN'´’]*[\pL\pN]|[\pL\pN])]]) do
-- The uppercase/lowercase versions are used to ease matching and save some
-- function calls.
local upper = word:upper()
local lower = word:lower()
-- Append non-word chars preceding 'word' to 'output'.
table.insert(output, nonword)
-- Control if 'word' should be matched or not.
local unmatched = true
-- Rule 1: Constant strings.
local var = const[upper]
if var then
word = const[upper] or word
debug('Match constant [' .. word .. ']')
unmatched = false
end
-- Rule 2: Roman numerals.
-- If 'word' matches with uppercase roman numerals we keep it. We assume
-- roman numerals are already uppercase in the input, otherwise we cannot
-- distinguish between normal words and numerals (e.g. Liv, civil, did, dim,
-- lid, mid-, mild, Vic).
if unmatched and word:match('^[IVXLCDM]+$') then
unmatched = false
debug('Match Roman numerals in [' .. word .. ']')
end
-- Rule 3: Names like D'Arcy or O'Reilly.
-- If 'sentencecase', we do not process this rule: this is helpful for
-- languages like French where "d'" appears a lot.
if unmatched and not sentencecase and upper:match([=[^[DO]['´’][\pL\pN]]=]) then
word = upper:sub(1, 3) .. lower:sub(4)
unmatched = false
debug('Match on mixed case: ' .. word)
end
-- Rule 4: Names like MacNeil or McDonald.
if unmatched and upper:match('^MA?C[B-DF-HJ-NP-TV-Z]') then
unmatched = false
debug('Match on MacX: ' .. word)
if upper:sub(2, 2) == 'A' then
word = upper:sub(1, 1) .. 'ac' .. upper:sub(4, 4) .. lower:sub(5)
else
word = upper:sub(1, 1) .. 'c' .. upper:sub(3, 3) .. lower:sub(4)
end
end
-- If one of the above rule is hit, we append the resulting 'word' as is to
-- 'output', otherwise we capitalize/lowercase it.
if not unmatched then table.insert(output, word)
elseif sentencecase then table.insert(output, lower)
else table.insert(output, upper:sub(1, 1) .. lower:sub(2))
end
end
-- Append remaining non-word chars to 'output'.
table.insert(output, input:match([[([^\pL\pN]*)$]]))
-- Everything should be converted now.
output = table.concat(output)
-- Exception 1: Capitalize first word. This is needed in case the string
-- starts with a lowercase constant.
output = output:gsub([=[[\pL\pN]]=], function (c) return c:upper() end, 1)
-- Exception 2: Capitalize first word after some punctuation marks.
output = output:gsub([[([{}[\]?!():.-][^\pL\pN]*)(\p{Ll})]], function (r, c) return r .. c:upper() end)
-- Exception 3: Capitalize first word right after a quote.
output = output:gsub([[([^\pL\pN]["'´’])(\p{Ll})]], function (r, c) return r .. c:upper() end)
return output
end
constants = append_constants(constants, const_en)
constants = append_constants(constants, const_music)
constants = append_constants(constants, const_common)
constants = append_constants(constants, const_units)
local const_mac_pl = pluralize(const_mac)
if sentencecase then
for _, word in ipairs(const_mac_pl) do
constants[word:upper()] = word:lower()
end
else
constants = append_constants(constants, const_mac_pl)
end
for k, v in pairs(output.tags) do
output.tags[k] = setcase(v, constants, sentencecase)
end
|
-- demlo script
-- Set case in tags either to title case or sentence case.
-- See https://en.wikipedia.org/wiki/Letter_case.
-- Global options.
local sentencecase = scase or false
local const_custom = const or {}
-- TODO: No verb? (am, are, was, is) No word > 3 chars? (against, between, from, into, onto)
const_en = const_en or {
'a',
'an',
'and',
'as',
'at',
'but',
'by',
'for',
'if',
'in',
'nor',
'not',
'of',
'on',
'so',
'the',
'to',
'via',
}
const_music = const_music or {
'CD',
'CD1',
'CD2',
'CD3',
'CD4',
'CD5',
'CD6',
'CD7',
'CD8',
'CD9',
'DJ',
'EP',
'feat',
'FX',
}
const_common = const_common or {
'KO',
'OK',
'TV',
'vs',
}
-- Some common units.
const_units = const_units or {
'bps',
'Gbps',
'GHz',
'h', -- hour
'Hz',
'kbps',
'kg',
'kHz',
'km',
'kph',
'Mbps',
'MHz',
'ms',
's', -- second
}
-- Word starting in Mac[X] where [X] is a consonant. See http://visca.com/regexdict/.
const_mac = const_mac or {
'Mache',
'Machete',
'Machicolate',
'Machicolation',
'Machinate',
'Machination',
'Machine',
'Machinery',
'Machinist',
'Machismo',
'Macho',
'Machzor',
'Mackerel',
'Mackinaw',
'Mackintosh',
'Mackle',
'Macle',
'Macrame',
'Macro',
'Macrobiotics',
'Macrocephaly',
'Macroclimate',
'Macrocode',
'Macrocosm',
'Macrocyte',
'Macrocytosis',
'Macroeconomics',
'Macroevolution',
'Macrofossil',
'Macrogamete',
'Macroglobulin',
'Macroglobulinemia',
'Macrograph',
'Macrography',
'Macroinstruction',
'Macromere',
'Macromolecule',
'Macron',
'Macronucleus',
'Macronutrient',
'Macrophage',
'Macrophysics',
'Macrophyte',
'Macropterous',
'Macroscopic',
'Macrosporangium',
'Macrospore',
}
local function pluralize(const)
local result = {}
for _, word in ipairs(const) do
local lastchar = word:sub(-1)
local plural
if lastchar == 'y' then
plural = word:sub(1, -2) .. "ies"
elseif lastchar == 's' then
plural = word
else
plural = word .. "s"
end
result[#result+1] = word
result[#result+1] = plural
end
return result
end
-- Build a table of constants suitable to be passed to 'setcase' as argument.
local function append_constants(const, new)
if type(const) ~= 'table' then
const = {}
end
for _, word in ipairs(new) do
const[word:upper()] = word
end
return const
end
-- "Constants" are written as provided, except if they begin a sentence in which
-- case the first letter is uppercase.
--
-- * Roman numerals are left as is. If lowercase, they are not considered as
-- roman numerals to prevent conflict with common words.
--
-- * Names like D'Arcy, O'Reilly, McDonald and MacNeil are properly handled.
--
-- Options:
--
-- sentencecase: when set to true, only the first letter of every sentence will
-- be capitalized, the other words that are not subject to the rules will be
-- lowercase.
--
-- This script was inspired by http://www.pement.org/awk/titlecase.awk.txt.
local function setcase(input, const, sentencecase)
-- Process words from 'input' one by one and append them to 'output'.
local output = {}
-- Digits and apostrophes are considered part of a word. There are different
-- symbols for apostrophe, some of them which are not ASCII. Apostrophes are
-- assumed not to start or end the word, so that to avoid confusion with
-- quotes.
for nonword, word in input:gmatch([[([^\pL\pN]*)([\pL\pN][\pL\pN'´’]*[\pL\pN]|[\pL\pN])]]) do
-- The uppercase/lowercase versions are used to ease matching and save some
-- function calls.
local upper = word:upper()
local lower = word:lower()
-- Append non-word chars preceding 'word' to 'output'.
table.insert(output, nonword)
-- Control if 'word' should be matched or not.
local unmatched = true
-- Rule 1: Constant strings.
local var = const[upper]
if var then
word = const[upper] or word
debug('Match constant [' .. word .. ']')
unmatched = false
end
-- Rule 2: Roman numerals.
-- If 'word' matches with uppercase roman numerals we keep it. We assume
-- roman numerals are already uppercase in the input, otherwise we cannot
-- distinguish between normal words and numerals (e.g. Liv, civil, did, dim,
-- lid, mid-, mild, Vic).
if unmatched and word:match('^[IVXLCDM]+$') then
unmatched = false
debug('Match Roman numerals in [' .. word .. ']')
end
-- Rule 3: Names like D'Arcy or O'Reilly.
-- If 'sentencecase', we do not process this rule: this is helpful for
-- languages like French where "d'" appears a lot.
if unmatched and not sentencecase and upper:match([=[^[DO]['´’][\pL\pN]]=]) then
word = upper:sub(1, 3) .. lower:sub(4)
unmatched = false
debug('Match on mixed case: ' .. word)
end
-- Rule 4: Names like MacNeil or McDonald.
if unmatched and upper:match('^MA?C[B-DF-HJ-NP-TV-Z]') then
unmatched = false
debug('Match on MacX: ' .. word)
if upper:sub(2, 2) == 'A' then
word = upper:sub(1, 1) .. 'ac' .. upper:sub(4, 4) .. lower:sub(5)
else
word = upper:sub(1, 1) .. 'c' .. upper:sub(3, 3) .. lower:sub(4)
end
end
-- If one of the above rule is hit, we append the resulting 'word' as is to
-- 'output', otherwise we capitalize/lowercase it.
if not unmatched then table.insert(output, word)
elseif sentencecase then table.insert(output, lower)
else table.insert(output, upper:sub(1, 1) .. lower:sub(2))
end
end
-- Append remaining non-word chars to 'output'.
table.insert(output, input:match([[([^\pL\pN]*)$]]))
-- Everything should be converted now.
output = table.concat(output)
-- Exception 1: Capitalize first word. This is needed in case the string
-- starts with a lowercase constant.
output = output:gsub([=[[\pL\pN]]=], function (c) return c:upper() end, 1)
-- Exception 2: Capitalize first word after some punctuation marks.
output = output:gsub([[([{}[\]?!():.-/][^\pL\pN]*)(\p{Ll})]], function (r, c) return r .. c:upper() end)
-- Exception 3: Capitalize first word right after a quote.
output = output:gsub([[([^\pL\pN]["'´’])(\p{Ll})]], function (r, c) return r .. c:upper() end)
return output
end
local constants = {}
constants = append_constants(constants, const_en)
constants = append_constants(constants, const_music)
constants = append_constants(constants, const_common)
constants = append_constants(constants, const_units)
constants = append_constants(constants, const_custom)
local const_mac_pl = pluralize(const_mac)
if sentencecase then
for _, word in ipairs(const_mac_pl) do
constants[word:upper()] = word:lower()
end
else
constants = append_constants(constants, const_mac_pl)
end
for k, v in pairs(output.tags) do
output.tags[k] = setcase(v, constants, sentencecase)
end
|
scripts/case.lua: Capitalize after '/' and fix unused user-defined 'const'
|
scripts/case.lua: Capitalize after '/' and fix unused user-defined 'const'
|
Lua
|
mit
|
Ambrevar/Demlo,Ambrevar/Demlo
|
5fd032d4aac74d577b8f30dd4d616710decd3cae
|
gga.lua
|
gga.lua
|
solution "gga"
configurations {"Release", "Debug" }
location (_OPTIONS["to"])
-------------------------------------
-- glfw static lib
-------------------------------------
project "glfw_proj"
targetname "glfw"
language "C"
kind "StaticLib"
defines {
"_CRT_SECURE_NO_WARNINGS"
}
includedirs {
"./3rdParty/glfw/include"
}
files {
"./3rdParty/glfw/src/internal.h",
"./3rdParty/glfw/src/glfw_config.h",
"./3rdParty/glfw/include/GLFW/glfw3.h",
"./3rdParty/glfw/include/GLFW/glfw3native.h",
"./3rdParty/glfw/src/context.c",
"./3rdParty/glfw/src/init.c",
"./3rdParty/glfw/src/input.c",
"./3rdParty/glfw/src/monitor.c",
"./3rdParty/glfw/src/window.c"
}
configuration "windows"
defines {
"_GLFW_WIN32"
}
files {
"./3rdParty/glfw/src/vulkan.c",
"./3rdParty/glfw/src/win32_platform.h",
"./3rdParty/glfw/src/win32_joystick.h",
"./3rdParty/glfw/src/wgl_context.h",
"./3rdParty/glfw/src/egl_context.c",
"./3rdParty/glfw/src/win32_init.c",
"./3rdParty/glfw/src/win32_joystick.c",
"./3rdParty/glfw/src/win32_monitor.c",
"./3rdParty/glfw/src/win32_time.c",
"./3rdParty/glfw/src/win32_tls.c",
"./3rdParty/glfw/src/win32_window.c",
"./3rdParty/glfw/src/wgl_context.c",
"./3rdParty/glfw/src/egl_context.c"
}
targetdir "./lib"
links { "gdi32" }
configuration "Debug"
defines { "_DEBUG" }
flags { "Symbols" }
links { "msvcrtd" }
targetdir "./lib/debug"
configuration "Release"
defines { "NDEBUG" }
flags { "OptimizeSize" }
links { "msvcrt" }
targetdir "./lib/release"
-------------------------------------
-- glew static lib
-------------------------------------
project "glew_proj"
targetname "glew"
language "C"
kind "StaticLib"
includedirs {
"./3rdParty/glew/include"
}
files {
"./3rdParty/glew/src/**.h",
"./3rdParty/glew/src/**.c",
"./3rdParty/glew/include/GL/**.h"
}
configuration "windows"
defines {
"WIN32",
"_LIB",
"WIN32_LEAN_AND_MEAN",
"GLEW_STATIC"
}
targetdir "./lib"
configuration "Debug"
defines { "_DEBUG" }
flags { "Symbols" }
links { "msvcrtd" }
targetdir "./lib/debug"
configuration "Release"
defines { "NDEBUG" }
flags { "OptimizeSize" }
links { "msvcrt" }
targetdir "./lib/release"
-------------------------------------
-- top level gga project
-------------------------------------
project "gga"
targetname "gga"
language "C++"
kind "ConsoleApp"
flags {
"No64BitChecks",
"StaticRuntime"
}
includedirs {
"./lib",
"./3rdParty/glew/include",
"./3rdParty/glfw/include/"
}
libdirs {
"./lib"
}
links {
"glfw_proj",
"glew_proj"
}
files {
"./src/**.h",
"./src/**.cpp"
}
configuration "Debug"
defines { "_DEBUG" }
flags { "Symbols" }
libdirs { "./lib/debug" }
links { "glew", "glfw" }
configuration "Release"
defines { "NDEBUG" }
flags { "OptimizeSize" }
libdirs { "./lib/release" }
links { "glew", "glfw" }
configuration "windows"
defines { "_WIN32" }
targetdir "./bin/windows"
if _ACTION == "clean" then
os.rmdir("bin")
os.rmdir("build")
end
newoption {
trigger = "to",
value = "path",
description = "Set the output location for the generated files"
}
|
solution "gga"
configurations {"Release", "Debug" }
location (_OPTIONS["to"])
-------------------------------------
-- glfw static lib
-------------------------------------
project "glfw_proj"
targetname "glfw"
language "C"
kind "StaticLib"
defines {
"_CRT_SECURE_NO_WARNINGS"
}
includedirs {
"./3rdParty/glfw/include"
}
files {
"./3rdParty/glfw/src/internal.h",
"./3rdParty/glfw/src/glfw_config.h",
"./3rdParty/glfw/include/GLFW/glfw3.h",
"./3rdParty/glfw/include/GLFW/glfw3native.h",
"./3rdParty/glfw/src/context.c",
"./3rdParty/glfw/src/init.c",
"./3rdParty/glfw/src/input.c",
"./3rdParty/glfw/src/monitor.c",
"./3rdParty/glfw/src/window.c"
}
configuration "windows"
defines {
"_GLFW_WIN32"
}
files {
"./3rdParty/glfw/src/vulkan.c",
"./3rdParty/glfw/src/win32_platform.h",
"./3rdParty/glfw/src/win32_joystick.h",
"./3rdParty/glfw/src/wgl_context.h",
"./3rdParty/glfw/src/egl_context.c",
"./3rdParty/glfw/src/win32_init.c",
"./3rdParty/glfw/src/win32_joystick.c",
"./3rdParty/glfw/src/win32_monitor.c",
"./3rdParty/glfw/src/win32_time.c",
"./3rdParty/glfw/src/win32_tls.c",
"./3rdParty/glfw/src/win32_window.c",
"./3rdParty/glfw/src/wgl_context.c",
"./3rdParty/glfw/src/egl_context.c"
}
targetdir "./lib"
links { "gdi32" }
configuration "Debug"
defines { "_DEBUG" }
flags { "Symbols" }
targetdir "./lib/debug"
configuration "Release"
defines { "NDEBUG" }
flags { "OptimizeSize" }
targetdir "./lib/release"
-------------------------------------
-- glew static lib
-------------------------------------
project "glew_proj"
targetname "glew"
language "C"
kind "StaticLib"
includedirs {
"./3rdParty/glew/include"
}
files {
"./3rdParty/glew/src/**.h",
"./3rdParty/glew/src/**.c",
"./3rdParty/glew/include/GL/**.h"
}
configuration "windows"
defines {
"WIN32",
"_LIB",
"WIN32_LEAN_AND_MEAN",
"GLEW_STATIC"
}
targetdir "./lib"
configuration "Debug"
defines { "_DEBUG" }
flags { "Symbols" }
targetdir "./lib/debug"
configuration "Release"
defines { "NDEBUG" }
flags { "OptimizeSize" }
targetdir "./lib/release"
-------------------------------------
-- top level gga project
-------------------------------------
project "gga"
targetname "gga"
language "C++"
kind "ConsoleApp"
flags {
"No64BitChecks",
"StaticRuntime"
}
includedirs {
"./lib",
"./3rdParty/glew/include",
"./3rdParty/glfw/include/"
}
libdirs {
"./lib"
}
links {
"glfw_proj",
"glew_proj"
}
files {
"./src/**.h",
"./src/**.cpp"
}
configuration "Debug"
defines { "_DEBUG" }
flags { "Symbols" }
libdirs { "./lib/debug" }
links { "glew", "glfw", "msvcrtd" }
configuration "Release"
defines { "NDEBUG" }
flags { "OptimizeSize" }
libdirs { "./lib/release" }
links { "glew", "glfw", "msvcrt" }
configuration "windows"
defines { "_WIN32" }
targetdir "./bin/windows"
if _ACTION == "clean" then
os.rmdir("bin")
os.rmdir("build")
end
newoption {
trigger = "to",
value = "path",
description = "Set the output location for the generated files"
}
|
linking mistake with msvcrt on Windows fixed.
|
linking mistake with msvcrt on Windows fixed.
|
Lua
|
mit
|
mrTag/GreatGreenArkleseizure,mrTag/GreatGreenArkleseizure
|
9c332b96f366235dbcf6f2e490e6aef32fb9f189
|
spec/cl_spec.lua
|
spec/cl_spec.lua
|
-- Tests the commandline options by executing busted through
-- os.execute(). It can be run through the following command:
--
-- busted --pattern=cl_test.lua --defer-print
local ditch
local error_started
local error_start = function()
if ditch == "" then return end
print("================================================")
print("== Error block follows ==")
print("================================================")
error_started = true
end
local error_end = function()
if ditch == "" then return end
print("================================================")
print("== Error block ended, all according to plan ==")
print("================================================")
error_started = false
end
-- if exitcode >256, then take MSB as exit code
local modexit = function(exitcode)
if exitcode>255 then
return math.floor(exitcode/256), exitcode - math.floor(exitcode/256)*256
else
return exitcode
end
end
local path = require("pl.path")
local = " > /dev/null 2>&1"
if path.is_windows then
ditch = " 1> NUL 2>NUL"
end
--ditch = "" -- uncomment this line, to show output of failing commands, for debugging
describe("Tests the busted command-line options", function()
setup(function()
require("pl")
end)
after_each(function()
if error_started then
print("================================================")
print("== Error block ended, something was wrong ==")
print("================================================")
error_started = false
end
end)
it("tests running with --tags specified", function()
local success, exitcode
error_start()
success, exitcode = utils.execute("busted --pattern=_tags.lua$"..ditch)
assert.is_false(success)
assert.is_equal(modexit(exitcode), 3)
success, exitcode = utils.execute("busted --pattern=_tags.lua$ --tags=tag1"..ditch)
assert.is_false(success)
assert.is_equal(modexit(exitcode), 2)
success, exitcode = utils.execute("busted --pattern=_tags.lua$ --tags=tag1,tag2"..ditch)
assert.is_false(success)
assert.is_equal(modexit(exitcode), 3)
error_end()
end)
it("tests running with --lang specified", function()
local success, exitcode
error_start()
success, exitcode = utils.execute("busted --pattern=cl_success.lua$ --lang=en"..ditch)
assert.is_true(success)
assert.is_equal(modexit(exitcode), 0)
success, exitcode = utils.execute("busted --pattern=cl_success --lang=not_found_here"..ditch)
assert.is_false(success)
assert.is_equal(modexit(exitcode), 1) -- busted errors out on non-available language
error_end()
end)
it("tests running with --version specified", function()
local success, exitcode
success, exitcode = utils.execute("busted --version"..ditch)
assert.is_true(success)
assert.is_equal(modexit(exitcode), 0)
end)
it("tests running with --help specified", function()
local success, exitcode
success, exitcode = utils.execute("busted --help"..ditch)
assert.is_true(success)
assert.is_equal(modexit(exitcode), 0)
end)
it("tests running a non-compiling testfile", function()
local success, exitcode
error_start()
success, exitcode = utils.execute("busted --pattern=cl_compile_fail.lua$"..ditch)
assert.is_false(success)
assert.is_equal(modexit(exitcode), 1)
error_end()
end)
it("tests running a testfile throwing errors when being run", function()
local success, exitcode
error_start()
success, exitcode = utils.execute("busted --pattern=cl_execute_fail.lua$"..ditch)
assert.is_false(success)
assert.is_equal(modexit(exitcode), 1)
error_end()
end)
it("tests running with --output specified", function()
local success, exitcode
error_start()
success, exitcode = utils.execute("busted --pattern=cl_success.lua$ --output=TAP"..ditch)
assert.is_true(success)
assert.is_equal(modexit(exitcode), 0)
success, exitcode = utils.execute("busted --pattern=cl_two_failures.lua$ --output=not_found_here"..ditch)
assert.is_false(success)
assert.is_equal(modexit(exitcode), 1) -- 1 for outputter missing
error_end()
end)
end)
|
local path = require("pl.path")
local ditch = " > /dev/null 2>&1"
if path.is_windows then
ditch = " 1> NUL 2>NUL"
end
--ditch = "" -- uncomment this line, to show output of failing commands, for debugging
local error_started
local error_start = function()
if ditch ~= "" then return end
print("================================================")
print("== Error block follows ==")
print("================================================")
error_started = true
end
local error_end = function()
if ditch ~= "" then return end
print("================================================")
print("== Error block ended, all according to plan ==")
print("================================================")
error_started = false
end
-- if exitcode >256, then take MSB as exit code
local modexit = function(exitcode)
if exitcode>255 then
return math.floor(exitcode/256), exitcode - math.floor(exitcode/256)*256
else
return exitcode
end
end
describe("Tests the busted command-line options", function()
setup(function()
require("pl")
end)
after_each(function()
if error_started then
print("================================================")
print("== Error block ended, something was wrong ==")
print("================================================")
error_started = false
end
end)
it("tests running with --tags specified", function()
local success, exitcode
error_start()
success, exitcode = utils.execute("busted --pattern=_tags.lua$"..ditch)
assert.is_false(success)
assert.is_equal(modexit(exitcode), 3)
success, exitcode = utils.execute("busted --pattern=_tags.lua$ --tags=tag1"..ditch)
assert.is_false(success)
assert.is_equal(modexit(exitcode), 2)
success, exitcode = utils.execute("busted --pattern=_tags.lua$ --tags=tag1,tag2"..ditch)
assert.is_false(success)
assert.is_equal(modexit(exitcode), 3)
error_end()
end)
it("tests running with --lang specified", function()
local success, exitcode
error_start()
success, exitcode = utils.execute("busted --pattern=cl_success.lua$ --lang=en"..ditch)
assert.is_true(success)
assert.is_equal(modexit(exitcode), 0)
success, exitcode = utils.execute("busted --pattern=cl_success --lang=not_found_here"..ditch)
assert.is_false(success)
assert.is_equal(modexit(exitcode), 1) -- busted errors out on non-available language
error_end()
end)
it("tests running with --version specified", function()
local success, exitcode
success, exitcode = utils.execute("busted --version"..ditch)
assert.is_true(success)
assert.is_equal(modexit(exitcode), 0)
end)
it("tests running with --help specified", function()
local success, exitcode
success, exitcode = utils.execute("busted --help"..ditch)
assert.is_true(success)
assert.is_equal(modexit(exitcode), 0)
end)
it("tests running a non-compiling testfile", function()
local success, exitcode
error_start()
success, exitcode = utils.execute("busted --pattern=cl_compile_fail.lua$"..ditch)
assert.is_false(success)
assert.is_equal(modexit(exitcode), 1)
error_end()
end)
it("tests running a testfile throwing errors when being run", function()
local success, exitcode
error_start()
success, exitcode = utils.execute("busted --pattern=cl_execute_fail.lua$"..ditch)
assert.is_false(success)
assert.is_equal(modexit(exitcode), 1)
error_end()
end)
it("tests running with --output specified", function()
local success, exitcode
error_start()
success, exitcode = utils.execute("busted --pattern=cl_success.lua$ --output=TAP"..ditch)
assert.is_true(success)
assert.is_equal(modexit(exitcode), 0)
success, exitcode = utils.execute("busted --pattern=cl_two_failures.lua$ --output=not_found_here"..ditch)
assert.is_false(success)
assert.is_equal(modexit(exitcode), 1) -- 1 for outputter missing
error_end()
end)
end)
|
bugfix
|
bugfix
|
Lua
|
mit
|
leafo/busted,istr/busted,mpeterv/busted,o-lim/busted,nehz/busted,ryanplusplus/busted,xyliuke/busted,sobrinho/busted,Olivine-Labs/busted,DorianGray/busted
|
cab4d9d23ec9d9786827477654c8b9b9d1f22967
|
obj/commands/Node.lua
|
obj/commands/Node.lua
|
local Command = require("obj.Command")
--- test command
local Node = Command:clone()
Node.name = "Node"
Node.keywords = {}
--- Execute the command
function Node:execute(input,user,par)
if par == "tcp" then
if user.node or user.master then
return Request:subexecute(input,user,par)
end
end
return false
end
function Node:subexecute(input,user,par)
if input2 then--input2 should be the index of a Node
local node = nodes[input2]
if node then --That is a vaild Node
if input3 then--input3 should be the order to execute
if Node.orders[input3] then--This is a valid order
return Node.orders[input3](node,input4,input5,par == 'tcp' and user or nil)
else
return "That is not a vaild order."
end
else
return "Please issue an order with the command."
end
else
return "That is not a vaild Node."
end
else
return "Please select a Node when issuing a Node command"
end
return false
end
Node.orders = {}
Node.orders["stop"] = function(node,re)
if re then re = 'restart' end
node:send('stop ' .. (re or ''))
return node:toString() .. ' stopping ' .. (re and 'restarting' or '')
end
return Node
|
local Command = require("obj.Command")
--- test command
local Node = Command:clone()
Node.name = "Node"
Node.keywords = {}
--- Execute the command
function Node:execute(input,user,par)
if par == "tcp" then
return Node:subexecute(input,user,par)
end
return false
end
function Node:subexecute(input,user,par)
local words = string.Words(input)
local input1, input2, input3 ,input4 = words[1],words[2],words[3],words[4]
if input2 then--input2 should be the index of a Node
local node = nodes[input2]
if node then --That is a vaild Node
if input3 then--input3 should be the order to execute
if Node.orders[input3] then--This is a valid order
return Node.orders[input3](node,input4,input5,par == 'tcp' and user or nil)
else
return "That is not a vaild order."
end
else
return "Please issue an order with the command."
end
else
return "That is not a vaild Node."
end
else
return "Please select a Node when issuing a Node command"
end
return false
end
Node.orders = {}
Node.orders["stop"] = function(node,re)
if re then re = 'restart' end
node:send('stop ' .. (re or ''))
return node:toString() .. ' stopping ' .. (re and 'restarting' or '')
end
return Node
|
minor error fixes
|
minor error fixes
fixed some minor errors
|
Lua
|
mit
|
PhilMo6/Lua_pi_pan,PhilMo6/Lua_pi_pan,PhilMo6/Lua_pi_pan,PhilMo6/Lua_pi_pan
|
111d95cea2841eb11a141a06b255897b2fa4bb19
|
src/logfactory/LogReader.lua
|
src/logfactory/LogReader.lua
|
local LogReader = {};
-- ------------------------------------------------
-- Constants
-- ------------------------------------------------
local EVENT_NEW_COMMIT = 'NEW_COMMIT';
local EVENT_CHANGED_FILE = 'LOGREADER_CHANGED_FILE';
local MOD_ADD = 'A';
local MOD_DELETE = 'D';
-- ------------------------------------------------
-- Local Variables
-- ------------------------------------------------
local log;
local index;
local commitTimer;
local commitDelay;
local play;
local rewind;
local observers;
-- ------------------------------------------------
-- Local Functions
-- ------------------------------------------------
---
-- Notify observers about the event.
-- @param event
-- @param ...
--
local function notify(event, ...)
for i = 1, #observers do
observers[i]:receive(event, ...);
end
end
---
-- This function will take a git modifier and return the direct
-- opposite of it.
-- @param modifier
--
local function reverseGitStatus(modifier)
if modifier == MOD_ADD then
return MOD_DELETE;
elseif modifier == MOD_DELETE then
return MOD_ADD;
end
return modifier;
end
local function applyNextCommit()
if index == #log then
return;
end
index = index + 1;
notify(EVENT_NEW_COMMIT, log[index].email, log[index].author);
for i = 1, #log[index] do
local change = log[index][i];
notify(EVENT_CHANGED_FILE, change.modifier, change.path, change.file, 'normal');
end
end
local function reverseCurCommit()
if index == 0 then
return;
end
notify(EVENT_NEW_COMMIT, log[index].email, log[index].author);
for i = 1, #log[index] do
local change = log[index][i];
notify(EVENT_CHANGED_FILE, reverseGitStatus(change.modifier), change.path, change.file, 'normal');
end
index = index - 1;
end
---
-- Fast forwards the graph from the current position to the
-- target position. We ignore author assigments and modifications
-- and only are interested in additions and deletions.
-- @param to -- The index of the commit to go to.
--
local function fastForward(to)
-- We start at index + 1 because the current index has already
-- been loaded (or it was 0 and therefore nonrelevant anyway).
for i = index + 1, to do
index = i; -- Update the index.
local commit = log[index];
for j = 1, #commit do
local change = commit[j];
-- Ignore modifications we just need to know about additions and deletions.
if change.modifier ~= 'M' then
notify(EVENT_CHANGED_FILE, change.modifier, change.path, change.file, 'fast');
end
end
end
end
---
-- Quickly rewinds the graph from the current position to the
-- target position. We ignore author assigments and modifications
-- and only are interested in additions and deletions.
-- @param to -- The index of the commit to go to.
--
local function fastBackward(to)
-- We start at the current index, because it has already been loaded
-- and we have to reverse it too.
for i = index, to, -1 do
index = i;
-- When we have reached the target commit, we update the index, but
-- don't reverse the changes it made.
if index == to then break end
local commit = log[index];
for j = #commit, 1, -1 do
local change = commit[j];
-- Ignore modifications we just need to know about additions and deletions.
if change.modifier ~= 'M' then
notify(EVENT_CHANGED_FILE, reverseGitStatus(change.modifier), change.path, change.file, 'fast');
end
end
end
end
-- ------------------------------------------------
-- Public Functions
-- ------------------------------------------------
---
-- Loads the file and stores it line for line in a lua table.
-- @param logpath
--
function LogReader.init(gitlog, delay, playmode, autoplay)
log = gitlog;
-- Set default values.
index = 0;
if playmode == 'default' then
rewind = false;
elseif playmode == 'rewind' then
fastForward(#log);
rewind = true;
else
error("Unsupported playmode '" .. playmode .. "' - please use either 'default' or 'rewind'");
end
commitTimer = 0;
commitDelay = delay;
play = autoplay;
observers = {};
end
function LogReader.update(dt)
if not play then return end
commitTimer = commitTimer + dt;
if commitTimer > commitDelay then
if rewind then
reverseCurCommit();
else
applyNextCommit();
end
commitTimer = 0;
end
end
function LogReader.toggleSimulation()
play = not play;
end
function LogReader.toggleRewind()
rewind = not rewind;
end
function LogReader.loadNextCommit()
play = false;
applyNextCommit();
end
function LogReader.loadPrevCommit()
play = false;
reverseCurCommit();
end
---
-- Sets the reader to a new commit index. If the
-- index is the same as the current one, the input is
-- ignored. If the target commit is smaller (aka older)
-- as the current one we fast-rewind the graph to that
-- position. If the target commit is bigger than the
-- current one, we fast-forward instead.
--
function LogReader.setCurrentIndex(ni)
if log[ni] then
if index == ni then
return;
elseif index < ni then
fastForward(ni);
elseif index > ni then
fastBackward(ni);
end
end
end
function LogReader.getTotalCommits()
return #log;
end
function LogReader.getCurrentIndex()
return index;
end
function LogReader.getCurrentDate()
return index ~= 0 and log[index].date or '';
end
---
-- Register an observer.
-- @param observer
--
function LogReader.register(observer)
observers[#observers + 1] = observer;
end
-- ------------------------------------------------
-- Return Module
-- ------------------------------------------------
return LogReader;
|
local LogReader = {};
-- ------------------------------------------------
-- Constants
-- ------------------------------------------------
local EVENT_NEW_COMMIT = 'NEW_COMMIT';
local EVENT_CHANGED_FILE = 'LOGREADER_CHANGED_FILE';
local MOD_ADD = 'A';
local MOD_DELETE = 'D';
-- ------------------------------------------------
-- Local Variables
-- ------------------------------------------------
local log;
local index;
local commitTimer;
local commitDelay;
local play;
local rewind;
local observers;
-- ------------------------------------------------
-- Local Functions
-- ------------------------------------------------
---
-- Notify observers about the event.
-- @param event
-- @param ...
--
local function notify(event, ...)
for i = 1, #observers do
observers[i]:receive(event, ...);
end
end
---
-- This function will take a git modifier and return the direct
-- opposite of it.
-- @param modifier
--
local function reverseGitStatus(modifier)
if modifier == MOD_ADD then
return MOD_DELETE;
elseif modifier == MOD_DELETE then
return MOD_ADD;
end
return modifier;
end
local function applyNextCommit()
if index == #log then
return;
end
index = index + 1;
notify(EVENT_NEW_COMMIT, log[index].email, log[index].author);
for i = 1, #log[index] do
local change = log[index][i];
notify(EVENT_CHANGED_FILE, change.modifier, change.path, change.file, change.extension, 'normal');
end
end
local function reverseCurCommit()
if index == 0 then
return;
end
notify(EVENT_NEW_COMMIT, log[index].email, log[index].author);
for i = 1, #log[index] do
local change = log[index][i];
notify(EVENT_CHANGED_FILE, reverseGitStatus(change.modifier), change.path, change.file, change.extension, 'normal');
end
index = index - 1;
end
---
-- Fast forwards the graph from the current position to the
-- target position. We ignore author assigments and modifications
-- and only are interested in additions and deletions.
-- @param to -- The index of the commit to go to.
--
local function fastForward(to)
-- We start at index + 1 because the current index has already
-- been loaded (or it was 0 and therefore nonrelevant anyway).
for i = index + 1, to do
index = i; -- Update the index.
local commit = log[index];
for j = 1, #commit do
local change = commit[j];
-- Ignore modifications we just need to know about additions and deletions.
if change.modifier ~= 'M' then
notify(EVENT_CHANGED_FILE, change.modifier, change.path, change.file, change.extension, 'fast');
end
end
end
end
---
-- Quickly rewinds the graph from the current position to the
-- target position. We ignore author assigments and modifications
-- and only are interested in additions and deletions.
-- @param to -- The index of the commit to go to.
--
local function fastBackward(to)
-- We start at the current index, because it has already been loaded
-- and we have to reverse it too.
for i = index, to, -1 do
index = i;
-- When we have reached the target commit, we update the index, but
-- don't reverse the changes it made.
if index == to then break end
local commit = log[index];
for j = #commit, 1, -1 do
local change = commit[j];
-- Ignore modifications we just need to know about additions and deletions.
if change.modifier ~= 'M' then
notify(EVENT_CHANGED_FILE, reverseGitStatus(change.modifier), change.path, change.file, change.extension, 'fast');
end
end
end
end
-- ------------------------------------------------
-- Public Functions
-- ------------------------------------------------
---
-- Loads the file and stores it line for line in a lua table.
-- @param logpath
--
function LogReader.init(gitlog, delay, playmode, autoplay)
log = gitlog;
-- Set default values.
index = 0;
if playmode == 'default' then
rewind = false;
elseif playmode == 'rewind' then
fastForward(#log);
rewind = true;
else
error("Unsupported playmode '" .. playmode .. "' - please use either 'default' or 'rewind'");
end
commitTimer = 0;
commitDelay = delay;
play = autoplay;
observers = {};
end
function LogReader.update(dt)
if not play then return end
commitTimer = commitTimer + dt;
if commitTimer > commitDelay then
if rewind then
reverseCurCommit();
else
applyNextCommit();
end
commitTimer = 0;
end
end
function LogReader.toggleSimulation()
play = not play;
end
function LogReader.toggleRewind()
rewind = not rewind;
end
function LogReader.loadNextCommit()
play = false;
applyNextCommit();
end
function LogReader.loadPrevCommit()
play = false;
reverseCurCommit();
end
---
-- Sets the reader to a new commit index. If the
-- index is the same as the current one, the input is
-- ignored. If the target commit is smaller (aka older)
-- as the current one we fast-rewind the graph to that
-- position. If the target commit is bigger than the
-- current one, we fast-forward instead.
--
function LogReader.setCurrentIndex(ni)
if log[ni] then
if index == ni then
return;
elseif index < ni then
fastForward(ni);
elseif index > ni then
fastBackward(ni);
end
end
end
function LogReader.getTotalCommits()
return #log;
end
function LogReader.getCurrentIndex()
return index;
end
function LogReader.getCurrentDate()
return index ~= 0 and log[index].date or '';
end
---
-- Register an observer.
-- @param observer
--
function LogReader.register(observer)
observers[#observers + 1] = observer;
end
-- ------------------------------------------------
-- Return Module
-- ------------------------------------------------
return LogReader;
|
Fix file extension not being sent to the graph
|
Fix file extension not being sent to the graph
|
Lua
|
mit
|
rm-code/logivi
|
fee2aa29b34edb8b96a6145b3e7e192b03fa59cf
|
spec/keycloak_spec.lua
|
spec/keycloak_spec.lua
|
local _M = require 'oauth.keycloak'
local test_backend_client = require 'resty.http_ng.backend.test'
describe('Keycloak', function()
local test_backend
before_each(function() test_backend = test_backend_client.new() end)
after_each(function() test_backend.verify_no_outstanding_expectations() end)
describe('.new', function()
it('accepts configuration', function()
local keycloak = assert(_M.new({ public_key = 'foobar' }))
assert.equals('-----BEGIN PUBLIC KEY-----\nfoobar\n-----END PUBLIC KEY-----', keycloak.config.public_key)
end)
end)
describe('.authorize', function()
it('connects to keycloak', function()
local keycloak = _M.new{ server = 'http://example.com', realm = 'foobar', client = test_backend }
ngx.var = { is_args = "?", args = "client_id=foo" }
stub(ngx.req, 'get_uri_args', function() return { response_type = 'code', client_id = 'foo', redirect_uri = 'bar'} end)
test_backend.expect{ url = 'http://example.com/auth/realms/foobar/protocol/openid-connect/auth?client_id=foo' }
.respond_with{ status = 200 , body = 'foo', headers = {} }
stub(_M, 'respond_and_exit')
keycloak:authorize()
assert.spy(_M.respond_and_exit).was.called_with(200, 'foo', {})
end)
end)
describe('.get_token', function()
it('')
end)
end)
|
local _M = require 'oauth.keycloak'
local test_backend_client = require 'resty.http_ng.backend.test'
describe('Keycloak', function()
local test_backend
before_each(function() test_backend = test_backend_client.new() end)
after_each(function() test_backend.verify_no_outstanding_expectations() end)
describe('.new', function()
it('accepts configuration', function()
local keycloak = assert(_M.new({ endpoint = 'http://www.example.com:80/auth/realms/test', public_key = 'foobar' }))
assert.equals('-----BEGIN PUBLIC KEY-----\nfoobar\n-----END PUBLIC KEY-----', keycloak.config.public_key)
assert.equals('http://www.example.com:80/auth/realms/test', keycloak.config.endpoint)
assert.equals('http://www.example.com:80/auth/realms/test/protocol/openid-connect/auth', keycloak.config.authorize_url)
assert.equals('http://www.example.com:80/auth/realms/test/protocol/openid-connect/token', keycloak.config.token_url)
end)
it('fails with nil public_key', function()
assert.has_error(function () _M.new({endpoint = 'http://www.example.com:80/auth/realms/test', public_key = nil }) end, "missing keycloak configuration" )
end)
it('fails with nil endpoint', function()
assert.has_error(function () _M.new({endpoint = nil, public_key = 'foobar' }) end, "missing keycloak configuration" )
end)
end)
describe('.authorize', function()
it('connects to keycloak', function()
local keycloak = _M.new({ endpoint = 'http://www.example.com:80/auth/realms/test', public_key = 'foobar', client = test_backend })
stub(_M, 'check_credentials', function () return true end)
ngx.var = { is_args = "?", args = "client_id=foo" }
stub(ngx.req, 'get_uri_args', function() return { response_type = 'code', client_id = 'foo', redirect_uri = 'bar' } end)
test_backend.expect{ url = 'http://www.example.com:80/auth/realms/test/protocol/openid-connect/auth?client_id=foo' }
.respond_with{ status = 200 , body = 'foo', headers = {} }
stub(_M, 'respond_and_exit')
keycloak:authorize()
assert.spy(_M.respond_and_exit).was.called_with(200, 'foo', {})
end)
it('returns error when response_type missing', function()
local keycloak = _M.new({ endpoint = 'http://www.example.com:80/auth/realms/test', public_key = 'foobar'})
stub(_M, 'check_credentials', function () return true end)
ngx.var = { is_args = "?", args = "" }
stub(ngx.req, 'get_uri_args', function() return { client_id = 'foo', redirect_uri = 'bar' } end)
stub(_M, 'respond_with_error')
keycloak:authorize()
assert.spy(_M.respond_with_error).was.called_with(400, 'invalid_request')
end)
it('returns error when credentials are wrong', function ()
local keycloak = _M.new({ endpoint = 'http://www.example.com:80/auth/reams/test', public_key = 'foobar'})
stub(_M, 'check_credentials', function () return false end)
stub(ngx.req, 'get_uri_args', function() return { response_type = 'code', client_id = 'foo', redirect_uri = 'bar' } end)
stub(_M, 'respond_with_error')
keycloak:authorize()
assert.spy(_M.respond_with_error).was.called_with(401, 'invalid_client')
end)
end)
describe('.get_token', function()
it('connects to keycloak', function()
local keycloak = _M.new({ endpoint = 'http://www.example.com:80/auth/realms/test', public_key = 'foobar', client = test_backend })
stub(ngx.location, 'capture', function () return { status = 200 } end )
ngx.var = { is_args = "?", args = "client_id=foo" }
stub(ngx.req, 'read_body', function() return { } end)
stub(ngx.req, 'get_post_args', function() return { grant_type = 'authorization_code', client_id = 'foo', redirect_uri = 'bar', code = 'baz'} end)
test_backend.expect{ url = 'http://www.example.com:80/auth/realms/test/protocol/openid-connect/token'}
.respond_with{ status = 200 , body = 'foo', headers = {} }
stub(_M, 'respond_and_exit')
keycloak:get_token()
assert.spy(_M.respond_and_exit).was.called_with(200, 'foo', {})
end)
it('returns "invalid_request" when grant_type missing', function ()
local keycloak = _M.new({ endpoint = 'http://www.example.com:80/auth/realms/test', public_key = 'foobar'})
ngx.var = { is_args = "?", args = "client_id=foo" }
stub(ngx.req, 'read_body', function() return { } end)
stub(ngx.req, 'get_post_args', function() return { client_id = 'foo', redirect_uri = 'bar', code = 'baz'} end)
stub(_M, 'respond_with_error')
keycloak:get_token()
assert.spy(_M.respond_with_error).was.called_with(400, 'invalid_request')
end)
it('returns "unsupported_grant_type" when grant_type not "recognised"', function ()
local keycloak = _M.new({ endpoint = 'http://www.example.com:80/auth/realms/test', public_key = 'foobar'})
ngx.var = { is_args = "?", args = "client_id=foo" }
stub(ngx.req, 'read_body', function() return { } end)
stub(ngx.req, 'get_post_args', function() return { grant_type = 'foo' } end)
stub(_M, 'respond_with_error')
keycloak:get_token()
assert.spy(_M.respond_with_error).was.called_with(400, 'unsupported_grant_type')
end)
it('returns "invalid_request" when required params not sent', function ()
local keycloak = _M.new({ endpoint = 'http://www.example.com:80/auth/realms/test', public_key = 'foobar'})
ngx.var = { is_args = "?", args = "client_id=foo" }
stub(ngx.req, 'read_body', function() return { } end)
stub(ngx.req, 'get_post_args', function() return { grant_type = 'authorization_code' } end)
stub(_M, 'respond_with_error')
keycloak:get_token()
assert.spy(_M.respond_with_error).was.called_with(400, 'invalid_request')
end)
it('returns "invalid_client" when credentials are wrong', function ()
local keycloak = _M.new({ endpoint = 'http://www.example.com:80/auth/realms/test', public_key = 'foobar'})
stub(_M, 'check_credentials', function () return false end)
ngx.var = { is_args = "?", args = "client_id=foo" }
stub(ngx.req, 'read_body', function() return { } end)
stub(ngx.req, 'get_post_args', function() return { grant_type = 'authorization_code', client_id = 'foo', redirect_uri = 'bar', code = 'baz'} end)
stub(_M, 'respond_with_error')
keycloak:get_token()
assert.spy(_M.respond_with_error).was.called_with(401, 'invalid_client')
end)
end)
end)
|
Add some keycloak tests
|
Add some keycloak tests
Add some keycloak tests
Some more keycloak tests
Some more keycloak tests
Fix tests
Fix tests
Some more tests
Some more tests
|
Lua
|
mit
|
3scale/apicast,3scale/apicast,3scale/docker-gateway,3scale/apicast,3scale/apicast,3scale/docker-gateway
|
379b6fa3fdcee7c840246a15b917e50b47423105
|
Modules/Utility/Binder.lua
|
Modules/Utility/Binder.lua
|
--- Bind class to Roblox Instance
-- @classmod Binder
local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore"))
local CollectionService = game:GetService("CollectionService")
local Maid = require("Maid")
local fastSpawn = require("fastSpawn")
local Binder = {}
Binder.__index = Binder
Binder.ClassName = "Binder"
function Binder.new(tagName, class)
local self = setmetatable({}, Binder)
self._maid = Maid.new()
self._tagName = tagName or error("No tagName")
self._class = class or error("No class")
for _, inst in pairs(CollectionService:GetTagged(self._tagName)) do
fastSpawn(function()
self:_add(inst)
end)
end
self._maid:GiveTask(CollectionService:GetInstanceAddedSignal(self._tagName):Connect(function(inst)
self:_add(inst)
end))
self._maid:GiveTask(CollectionService:GetInstanceRemovedSignal(self._tagName):Connect(function(inst)
self:_remove(inst)
end))
return self
end
function Binder:Get(inst)
return self._maid[inst]
end
function Binder:_add(inst)
if type(self._class) == "function" then
self._maid[inst] = self._class(inst)
elseif self._class.Create then
self._maid[inst] = self._class:Create(inst)
else
self._maid[inst] = self._class.new(inst)
end
end
function Binder:_remove(inst)
self._maid[inst] = nil
end
function Binder:Destroy()
self._maid:DoCleaning()
end
return Binder
|
--- Bind class to Roblox Instance
-- @classmod Binder
local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore"))
local CollectionService = game:GetService("CollectionService")
local Maid = require("Maid")
local fastSpawn = require("fastSpawn")
local Binder = {}
Binder.__index = Binder
Binder.ClassName = "Binder"
function Binder.new(tagName, class)
local self = setmetatable({}, Binder)
self._maid = Maid.new()
self._tagName = tagName or error("No tagName")
self._class = class or error("No class")
for _, inst in pairs(CollectionService:GetTagged(self._tagName)) do
fastSpawn(function()
self:_add(inst)
end)
end
self._maid:GiveTask(CollectionService:GetInstanceAddedSignal(self._tagName):Connect(function(inst)
self:_add(inst)
end))
self._maid:GiveTask(CollectionService:GetInstanceRemovedSignal(self._tagName):Connect(function(inst)
self:_remove(inst)
end))
return self
end
function Binder:Bind(inst)
CollectionService:AddTag(inst, self._tagName)
return self:Get(inst)
end
function Binder:Get(inst)
return self._maid[inst]
end
function Binder:_add(inst)
if self._maid[inst] then
return
end
if type(self._class) == "function" then
self._maid[inst] = self._class(inst)
elseif self._class.Create then
self._maid[inst] = self._class:Create(inst)
else
self._maid[inst] = self._class.new(inst)
end
end
function Binder:_remove(inst)
self._maid[inst] = nil
end
function Binder:Destroy()
self._maid:DoCleaning()
end
return Binder
|
Fix binder and add :Bind method
|
Fix binder and add :Bind method
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
62fade570951964115136f2cd47487633cd529be
|
libs/core/luasrc/init.lua
|
libs/core/luasrc/init.lua
|
--[[
LuCI - Lua Configuration Interface
Description:
Main class
FileId:
$Id$
License:
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
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 require = require
module "luci"
local v = require "luci.version"
__version__ = v.luciversion or "0.9"
__appname__ = v.luciname or "LuCI"
|
--[[
LuCI - Lua Configuration Interface
Description:
Main class
FileId:
$Id$
License:
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
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 require = require
-- Make sure that bitlib is loaded
if not _G.bit then
_G.bit = require "bit"
end
module "luci"
local v = require "luci.version"
__version__ = v.luciversion or "0.9"
__appname__ = v.luciname or "LuCI"
|
libs/core: make sure that bitlib is loaded, fixes some sdk problems
|
libs/core: make sure that bitlib is loaded, fixes some sdk problems
|
Lua
|
apache-2.0
|
Sakura-Winkey/LuCI,slayerrensky/luci,lcf258/openwrtcn,jchuang1977/luci-1,rogerpueyo/luci,bittorf/luci,tcatm/luci,keyidadi/luci,aircross/OpenWrt-Firefly-LuCI,fkooman/luci,LazyZhu/openwrt-luci-trunk-mod,981213/luci-1,cappiewu/luci,remakeelectric/luci,chris5560/openwrt-luci,LuttyYang/luci,palmettos/test,florian-shellfire/luci,MinFu/luci,remakeelectric/luci,aa65535/luci,oyido/luci,shangjiyu/luci-with-extra,palmettos/cnLuCI,cshore-firmware/openwrt-luci,rogerpueyo/luci,jorgifumi/luci,bittorf/luci,slayerrensky/luci,kuoruan/luci,Noltari/luci,RedSnake64/openwrt-luci-packages,maxrio/luci981213,teslamint/luci,slayerrensky/luci,openwrt-es/openwrt-luci,981213/luci-1,daofeng2015/luci,ollie27/openwrt_luci,joaofvieira/luci,RedSnake64/openwrt-luci-packages,male-puppies/luci,cshore-firmware/openwrt-luci,chris5560/openwrt-luci,ollie27/openwrt_luci,NeoRaider/luci,nmav/luci,fkooman/luci,thess/OpenWrt-luci,male-puppies/luci,ReclaimYourPrivacy/cloak-luci,marcel-sch/luci,ff94315/luci-1,jorgifumi/luci,aa65535/luci,tobiaswaldvogel/luci,Kyklas/luci-proto-hso,palmettos/cnLuCI,Noltari/luci,tcatm/luci,oyido/luci,dismantl/luci-0.12,Hostle/openwrt-luci-multi-user,palmettos/test,palmettos/cnLuCI,jchuang1977/luci-1,jorgifumi/luci,florian-shellfire/luci,Noltari/luci,hnyman/luci,openwrt/luci,LazyZhu/openwrt-luci-trunk-mod,NeoRaider/luci,LazyZhu/openwrt-luci-trunk-mod,aa65535/luci,hnyman/luci,opentechinstitute/luci,marcel-sch/luci,dwmw2/luci,981213/luci-1,maxrio/luci981213,LuttyYang/luci,jlopenwrtluci/luci,thess/OpenWrt-luci,artynet/luci,thess/OpenWrt-luci,ollie27/openwrt_luci,forward619/luci,openwrt/luci,nwf/openwrt-luci,bright-things/ionic-luci,cappiewu/luci,forward619/luci,ff94315/luci-1,RuiChen1113/luci,deepak78/new-luci,Sakura-Winkey/LuCI,Hostle/luci,palmettos/test,oneru/luci,chris5560/openwrt-luci,keyidadi/luci,thess/OpenWrt-luci,male-puppies/luci,oneru/luci,db260179/openwrt-bpi-r1-luci,openwrt/luci,db260179/openwrt-bpi-r1-luci,nmav/luci,dwmw2/luci,981213/luci-1,jlopenwrtluci/luci,Kyklas/luci-proto-hso,male-puppies/luci,schidler/ionic-luci,hnyman/luci,artynet/luci,tobiaswaldvogel/luci,NeoRaider/luci,cappiewu/luci,mumuqz/luci,deepak78/new-luci,remakeelectric/luci,daofeng2015/luci,bittorf/luci,florian-shellfire/luci,palmettos/cnLuCI,marcel-sch/luci,Wedmer/luci,mumuqz/luci,teslamint/luci,db260179/openwrt-bpi-r1-luci,dwmw2/luci,nmav/luci,LuttyYang/luci,teslamint/luci,opentechinstitute/luci,forward619/luci,MinFu/luci,forward619/luci,marcel-sch/luci,cshore-firmware/openwrt-luci,sujeet14108/luci,cappiewu/luci,Hostle/luci,oneru/luci,lcf258/openwrtcn,mumuqz/luci,male-puppies/luci,cshore-firmware/openwrt-luci,LazyZhu/openwrt-luci-trunk-mod,zhaoxx063/luci,david-xiao/luci,taiha/luci,lbthomsen/openwrt-luci,wongsyrone/luci-1,RedSnake64/openwrt-luci-packages,maxrio/luci981213,florian-shellfire/luci,nwf/openwrt-luci,deepak78/new-luci,hnyman/luci,tobiaswaldvogel/luci,tcatm/luci,aa65535/luci,harveyhu2012/luci,dwmw2/luci,Kyklas/luci-proto-hso,nwf/openwrt-luci,opentechinstitute/luci,aircross/OpenWrt-Firefly-LuCI,daofeng2015/luci,Wedmer/luci,tcatm/luci,thesabbir/luci,deepak78/new-luci,openwrt-es/openwrt-luci,kuoruan/luci,tobiaswaldvogel/luci,remakeelectric/luci,cshore/luci,ollie27/openwrt_luci,bittorf/luci,maxrio/luci981213,urueedi/luci,zhaoxx063/luci,lcf258/openwrtcn,keyidadi/luci,nmav/luci,RedSnake64/openwrt-luci-packages,ff94315/luci-1,tobiaswaldvogel/luci,joaofvieira/luci,chris5560/openwrt-luci,daofeng2015/luci,ReclaimYourPrivacy/cloak-luci,lbthomsen/openwrt-luci,maxrio/luci981213,zhaoxx063/luci,jlopenwrtluci/luci,dwmw2/luci,urueedi/luci,MinFu/luci,male-puppies/luci,zhaoxx063/luci,shangjiyu/luci-with-extra,bright-things/ionic-luci,Wedmer/luci,thess/OpenWrt-luci,david-xiao/luci,Sakura-Winkey/LuCI,jlopenwrtluci/luci,shangjiyu/luci-with-extra,taiha/luci,artynet/luci,thesabbir/luci,sujeet14108/luci,jlopenwrtluci/luci,Sakura-Winkey/LuCI,remakeelectric/luci,deepak78/new-luci,artynet/luci,jchuang1977/luci-1,openwrt/luci,obsy/luci,lbthomsen/openwrt-luci,taiha/luci,daofeng2015/luci,Wedmer/luci,daofeng2015/luci,palmettos/cnLuCI,jorgifumi/luci,obsy/luci,jorgifumi/luci,wongsyrone/luci-1,sujeet14108/luci,mumuqz/luci,cshore/luci,ReclaimYourPrivacy/cloak-luci,taiha/luci,schidler/ionic-luci,zhaoxx063/luci,oyido/luci,Sakura-Winkey/LuCI,shangjiyu/luci-with-extra,hnyman/luci,lcf258/openwrtcn,bright-things/ionic-luci,maxrio/luci981213,marcel-sch/luci,mumuqz/luci,Hostle/openwrt-luci-multi-user,teslamint/luci,palmettos/cnLuCI,jlopenwrtluci/luci,lbthomsen/openwrt-luci,openwrt/luci,kuoruan/luci,teslamint/luci,bittorf/luci,dwmw2/luci,nmav/luci,urueedi/luci,shangjiyu/luci-with-extra,Hostle/openwrt-luci-multi-user,981213/luci-1,nmav/luci,openwrt-es/openwrt-luci,shangjiyu/luci-with-extra,dwmw2/luci,keyidadi/luci,Noltari/luci,RuiChen1113/luci,urueedi/luci,joaofvieira/luci,artynet/luci,harveyhu2012/luci,jchuang1977/luci-1,daofeng2015/luci,teslamint/luci,kuoruan/luci,dismantl/luci-0.12,Kyklas/luci-proto-hso,Hostle/luci,jchuang1977/luci-1,MinFu/luci,thesabbir/luci,kuoruan/lede-luci,db260179/openwrt-bpi-r1-luci,jorgifumi/luci,palmettos/test,artynet/luci,nwf/openwrt-luci,Noltari/luci,remakeelectric/luci,dismantl/luci-0.12,openwrt-es/openwrt-luci,ff94315/luci-1,hnyman/luci,oyido/luci,shangjiyu/luci-with-extra,NeoRaider/luci,obsy/luci,kuoruan/lede-luci,tobiaswaldvogel/luci,bright-things/ionic-luci,oneru/luci,slayerrensky/luci,thesabbir/luci,lcf258/openwrtcn,Noltari/luci,palmettos/test,male-puppies/luci,urueedi/luci,marcel-sch/luci,openwrt/luci,tcatm/luci,rogerpueyo/luci,thess/OpenWrt-luci,deepak78/new-luci,teslamint/luci,cshore/luci,MinFu/luci,hnyman/luci,obsy/luci,RuiChen1113/luci,db260179/openwrt-bpi-r1-luci,dismantl/luci-0.12,Wedmer/luci,fkooman/luci,Wedmer/luci,rogerpueyo/luci,joaofvieira/luci,opentechinstitute/luci,obsy/luci,schidler/ionic-luci,artynet/luci,lcf258/openwrtcn,obsy/luci,urueedi/luci,ollie27/openwrt_luci,aircross/OpenWrt-Firefly-LuCI,Wedmer/luci,openwrt-es/openwrt-luci,nwf/openwrt-luci,aa65535/luci,cshore-firmware/openwrt-luci,zhaoxx063/luci,bittorf/luci,bright-things/ionic-luci,slayerrensky/luci,ollie27/openwrt_luci,schidler/ionic-luci,jlopenwrtluci/luci,keyidadi/luci,Sakura-Winkey/LuCI,db260179/openwrt-bpi-r1-luci,sujeet14108/luci,NeoRaider/luci,aircross/OpenWrt-Firefly-LuCI,Kyklas/luci-proto-hso,Noltari/luci,Hostle/openwrt-luci-multi-user,LazyZhu/openwrt-luci-trunk-mod,openwrt-es/openwrt-luci,david-xiao/luci,wongsyrone/luci-1,lbthomsen/openwrt-luci,joaofvieira/luci,oneru/luci,LuttyYang/luci,daofeng2015/luci,kuoruan/lede-luci,981213/luci-1,david-xiao/luci,taiha/luci,maxrio/luci981213,harveyhu2012/luci,oneru/luci,opentechinstitute/luci,lbthomsen/openwrt-luci,ReclaimYourPrivacy/cloak-luci,rogerpueyo/luci,david-xiao/luci,Noltari/luci,RuiChen1113/luci,oneru/luci,tcatm/luci,bright-things/ionic-luci,cshore/luci,dwmw2/luci,lcf258/openwrtcn,male-puppies/luci,oneru/luci,ReclaimYourPrivacy/cloak-luci,rogerpueyo/luci,Noltari/luci,thesabbir/luci,cshore/luci,palmettos/cnLuCI,harveyhu2012/luci,urueedi/luci,david-xiao/luci,palmettos/test,MinFu/luci,tcatm/luci,marcel-sch/luci,wongsyrone/luci-1,bittorf/luci,RuiChen1113/luci,MinFu/luci,wongsyrone/luci-1,bittorf/luci,chris5560/openwrt-luci,forward619/luci,bright-things/ionic-luci,fkooman/luci,kuoruan/luci,RedSnake64/openwrt-luci-packages,harveyhu2012/luci,cshore-firmware/openwrt-luci,nwf/openwrt-luci,david-xiao/luci,mumuqz/luci,schidler/ionic-luci,opentechinstitute/luci,chris5560/openwrt-luci,lbthomsen/openwrt-luci,kuoruan/lede-luci,cshore/luci,openwrt/luci,shangjiyu/luci-with-extra,tobiaswaldvogel/luci,jchuang1977/luci-1,jchuang1977/luci-1,fkooman/luci,tobiaswaldvogel/luci,db260179/openwrt-bpi-r1-luci,slayerrensky/luci,marcel-sch/luci,david-xiao/luci,urueedi/luci,nmav/luci,openwrt-es/openwrt-luci,LuttyYang/luci,opentechinstitute/luci,sujeet14108/luci,palmettos/test,jlopenwrtluci/luci,teslamint/luci,harveyhu2012/luci,harveyhu2012/luci,oyido/luci,taiha/luci,thesabbir/luci,chris5560/openwrt-luci,aa65535/luci,MinFu/luci,slayerrensky/luci,maxrio/luci981213,ollie27/openwrt_luci,deepak78/new-luci,oyido/luci,aa65535/luci,aircross/OpenWrt-Firefly-LuCI,florian-shellfire/luci,LazyZhu/openwrt-luci-trunk-mod,nmav/luci,thess/OpenWrt-luci,palmettos/test,Sakura-Winkey/LuCI,sujeet14108/luci,schidler/ionic-luci,thess/OpenWrt-luci,bright-things/ionic-luci,remakeelectric/luci,LuttyYang/luci,sujeet14108/luci,Hostle/luci,dismantl/luci-0.12,oyido/luci,openwrt-es/openwrt-luci,schidler/ionic-luci,zhaoxx063/luci,schidler/ionic-luci,hnyman/luci,joaofvieira/luci,Hostle/openwrt-luci-multi-user,cshore/luci,aircross/OpenWrt-Firefly-LuCI,kuoruan/lede-luci,ff94315/luci-1,aa65535/luci,NeoRaider/luci,jchuang1977/luci-1,LazyZhu/openwrt-luci-trunk-mod,kuoruan/lede-luci,lcf258/openwrtcn,ollie27/openwrt_luci,palmettos/cnLuCI,Hostle/luci,taiha/luci,openwrt/luci,NeoRaider/luci,florian-shellfire/luci,Hostle/openwrt-luci-multi-user,kuoruan/luci,opentechinstitute/luci,aircross/OpenWrt-Firefly-LuCI,lcf258/openwrtcn,kuoruan/lede-luci,slayerrensky/luci,forward619/luci,forward619/luci,LazyZhu/openwrt-luci-trunk-mod,ReclaimYourPrivacy/cloak-luci,taiha/luci,mumuqz/luci,fkooman/luci,keyidadi/luci,artynet/luci,Hostle/luci,cappiewu/luci,tcatm/luci,RuiChen1113/luci,ReclaimYourPrivacy/cloak-luci,lbthomsen/openwrt-luci,kuoruan/lede-luci,ff94315/luci-1,florian-shellfire/luci,Kyklas/luci-proto-hso,Hostle/openwrt-luci-multi-user,rogerpueyo/luci,artynet/luci,nwf/openwrt-luci,wongsyrone/luci-1,oyido/luci,ReclaimYourPrivacy/cloak-luci,deepak78/new-luci,thesabbir/luci,thesabbir/luci,cappiewu/luci,RedSnake64/openwrt-luci-packages,Sakura-Winkey/LuCI,cshore/luci,kuoruan/luci,nwf/openwrt-luci,RuiChen1113/luci,wongsyrone/luci-1,chris5560/openwrt-luci,fkooman/luci,Hostle/luci,obsy/luci,db260179/openwrt-bpi-r1-luci,Hostle/openwrt-luci-multi-user,obsy/luci,rogerpueyo/luci,lcf258/openwrtcn,cshore-firmware/openwrt-luci,keyidadi/luci,wongsyrone/luci-1,RedSnake64/openwrt-luci-packages,sujeet14108/luci,RuiChen1113/luci,dismantl/luci-0.12,NeoRaider/luci,mumuqz/luci,forward619/luci,keyidadi/luci,cshore-firmware/openwrt-luci,florian-shellfire/luci,jorgifumi/luci,kuoruan/luci,joaofvieira/luci,Hostle/luci,dismantl/luci-0.12,zhaoxx063/luci,ff94315/luci-1,981213/luci-1,cappiewu/luci,Wedmer/luci,LuttyYang/luci,cappiewu/luci,jorgifumi/luci,joaofvieira/luci,ff94315/luci-1,LuttyYang/luci,fkooman/luci,remakeelectric/luci,Kyklas/luci-proto-hso,nmav/luci
|
9f9d269a4a84255a6120c60a801033f06be75e4c
|
busted/modules/files/terra.lua
|
busted/modules/files/terra.lua
|
local path = require 'pl.path'
local ret = {}
local terra_available, terralib = not not terralib, terralib --grab the injected global if it exists
if not terra_available then
terra_available, terralib = pcall(require, 'terra') --otherwise, attempt to load terra as a shared library
end
local getTrace = function(filename, info)
local index = info.traceback:find('\n%s*%[C]')
info.traceback = info.traceback:sub(1, index)
return info
end
ret.match = function(busted, filename)
return path.extension(filename) == '.t'
end
ret.load = function(busted, filename)
if not terra_available then
error "unable to load terra, try running without terra language support enabled or installing terra."
else
local file, err = terralib.loadfile(filename)
if not file then
busted.publish({ 'error', 'file' }, { descriptor = 'file', name = filename }, nil, err, {})
end
return file, getTrace
end
end
return ret
|
local path = require 'pl.path'
local ret = {}
local terra_available, terralib = not not terralib, terralib --luacheck: ignore
if not terra_available then
terra_available, terralib = pcall(require, 'terra') --otherwise, attempt to load terra as a shared library
end
local getTrace = function(filename, info)
local index = info.traceback:find('\n%s*%[C]')
info.traceback = info.traceback:sub(1, index)
return info
end
ret.match = function(busted, filename)
return path.extension(filename) == '.t'
end
ret.load = function(busted, filename)
if not terra_available then
error "unable to load terra, try running without terra language support enabled or installing terra."
else
local file, err = terralib.loadfile(filename)
if not file then
busted.publish({ 'error', 'file' }, { descriptor = 'file', name = filename }, nil, err, {})
end
return file, getTrace
end
end
return ret
|
fix(ci) fix linter errors introduced by terra change
|
fix(ci) fix linter errors introduced by terra change
|
Lua
|
mit
|
Olivine-Labs/busted
|
65a551f363df76f7334d5326f3fb8b3280fcc357
|
ladleutil.lua
|
ladleutil.lua
|
local ladleutil = {}
mime = require('mimetypes')
function ladleutil.scandir(directory)
local i, t, popen = 0, {}, io.popen
for filename in popen('ls -a "'..directory..'"'):lines() do
i = i + 1
t[i] = filename
end
return t
end
function ladleutil.getRequestedFileInfo(request)
local file = request["uri"]
-- retrieve mime type for file based on extension
local ext = string.match(file, "%.%l%l%l%l?") or ""
local mimetype = mime.getMime(ext)
if not mimetype then
mimetype = "text/html" -- fallback. didn't think out something
-- better
end
local flags
if mime.isBinary(ext) == false then
-- if file is ASCII, use just read flag
flags = "r"
else
-- otherwise file is binary, so also use binary flag (b)
-- note: this is for operating systems which read binary
-- files differently to plain text such as Windows
flags = "rb"
end
return file, mimetype, flags
end
function ladleutil.fileExists(filename)
local f = io.open(filename, 'r')
if f then
f:close()
return true
else
return false
end
end
function ladleutil.receiveHTTPRequest(client)
local request = ""
local line,err = ""
repeat
local line, err = client:receive("*l")
if line
then
request = request .. "\r\n" .. line
end
until not line or line:len()==0 or err
return request,err
end
function ladleutil.parseRequest(request)
local request_table = {}
local request_text = request
local line = ""
repeat
local a,b = request_text:find("\r*\n")
line = request_text:sub(0,a-1)
request_text = request_text:sub(b+1)
until line:len() > 0
request_table["method"],request_table["url"],request_table["protocol"] = line:match("^(.-) +(.-) +(.-)$")
while request_text:len() > 0 do
local a,b = request_text:find("\r*\n")
local line = request_text:sub(0,a-1)
request_text = request_text:sub(b+1)
if line:len()>0
then
local key, value = line:match("^(.-): +(.+)$")
request_table[key] = value
end
end
query_string = (request_table["url"]):match("^/[a-zA-Z.,0-9/]*%??(.*)$") or ""
uri = (request_table["url"]):match("^/([a-zA-Z.,0-9/]*)%??.*$") or ""
request_table["query_string"] = query_string -- TODO: base64 decode?
request_table["uri"] = uri
return request_table
end
-- decides which prep to run etc
function ladleutil.prepMain(request, client)
end
-- display error message and server information
-- used while serving pages (for different errors like 404, 500 etc)
function ladleutil.err(message,client)
client:send(message)
client:send("\n\nLadle web server\n")
end
return ladleutil
|
local ladleutil = {}
mime = require('mimetypes')
function ladleutil.scandir(directory)
local i, t, popen = 0, {}, io.popen
for filename in popen('ls -a "'..directory..'"'):lines() do
i = i + 1
t[i] = filename
end
return t
end
function ladleutil.getRequestedFileInfo(request)
local file = request["uri"]
-- retrieve mime type for file based on extension
local ext = string.match(file, "%.%l%l%l?%l?$") or ""
local mimetype = mime.getMime(ext)
local flags
if mime.isBinary(ext) == false then
-- if file is ASCII, use just read flag
flags = "r"
else
-- otherwise file is binary, so also use binary flag (b)
-- note: this is for operating systems which read binary
-- files differently to plain text such as Windows
flags = "rb"
end
return file, mimetype, flags
end
function ladleutil.fileExists(filename)
local f = io.open(filename, 'r')
if f then
f:close()
return true
else
return false
end
end
function ladleutil.receiveHTTPRequest(client)
local request = ""
local line,err = ""
repeat
local line, err = client:receive("*l")
if line
then
request = request .. "\r\n" .. line
end
until not line or line:len()==0 or err
return request,err
end
function ladleutil.parseQueryString(query_string)
-- From lua-wiki
local urldecode = function (str)
str = string.gsub (str, "+", " ")
str = string.gsub (str, "%%(%x%x)",
function(h) return string.char(tonumber(h,16)) end
)
str = string.gsub (str, "\r\n", "\n")
return str
end
local retval = {}
while query_string:len()>0 do
local a,b = query_string:find('=')
local c = nil
local index = query_string:sub( 0, a-1 )
b,c = query_string:find('&')
local value = ""
if b
then
value = query_string:sub( a+1, b-1 )
query_string = query_string:sub(b+1)
else
value = query_string:sub( a+1 )
query_string = ""
end
index = urldecode(index)
retval[index] = urldecode(value)
end
return retval
end
function ladleutil.parseRequest(request)
local request_table = {}
local request_text = request
local line = ""
local a,b = request_text:find("\r*\n")
if not a or not b
then
ladleutil.trace("ladleutil.parseRequest(request):")
ladleutil.trace("Suspicious request:")
ladleutil.trace(request)
ladleutil.trace("=======================================================")
ladleutil.trace("Newlines (\\r\\n) not found")
return {}
end
repeat
local a,b = request_text:find("\r*\n")
line = request_text:sub(0,a-1)
request_text = request_text:sub(b+1)
until line:len() > 0
request_table["method"],request_table["url"],request_table["protocol"] = line:match("^([^ ]-) +([^ ]-) +([^ ]-)$")
while request_text:len() > 0 do
local a,b = request_text:find("\r*\n")
local line = request_text:sub(0,a-1)
request_text = request_text:sub(b+1)
if line:len()>0
then
local key, value = line:match("^([^:]*): +(.+)$")
request_table[key] = value
end
end
query_string = (request_table["url"]):match("^/[^?]*%??(.*)$") or ""
uri = (request_table["url"]):match("^/([^?]*)%??.*$") or ""
request_table["query_string"] = query_string -- TODO: base64 decode?
request_table["query"] = ladleutil.parseQueryString(query_string)
request_table["uri"] = uri
return request_table
end
-- decides which prep to run etc
function ladleutil.prepMain(request, client)
end
-- display error message and server information
-- used while serving pages (for different errors like 404, 500 etc)
function ladleutil.err(message,client)
client:send(message)
client:send("\n\nLadle web server\n")
end
function ladleutil.trace(message)
print(os.date() .. ": " .. message)
end
return ladleutil
|
Fixes, improvements: add query string parsing and urldecode
|
Fixes, improvements: add query string parsing and urldecode
getRequestedFileInfo(): improve pattern, remove unnecessary check
parseQueryString(): parse query string, urldecode from lua-wiki
parseRequest(): hunting for weird requests, improve patterns
trace(): trying to centralize output
|
Lua
|
mit
|
danielrempel/ladle
|
ffa479fbf9b1f367780a6cfa57d907a18a6fb58f
|
mod_smacks/mod_smacks.lua
|
mod_smacks/mod_smacks.lua
|
local st = require "util.stanza";
local t_insert, t_remove = table.insert, table.remove;
local math_min = math.min;
local tonumber, tostring = tonumber, tostring;
local add_filter = require "util.filters".add_filter;
local timer = require "util.timer";
local xmlns_sm = "urn:xmpp:sm:2";
local sm_attr = { xmlns = xmlns_sm };
local resume_timeout = 300;
local max_unacked_stanzas = 0;
module:add_event_hook("stream-features",
function (session, features)
features:tag("sm", sm_attr):tag("optional"):up():up();
end);
module:hook("s2s-stream-features",
function (data)
data.features:tag("sm", sm_attr):tag("optional"):up():up();
end);
module:hook_stanza(xmlns_sm, "enable",
function (session, stanza)
module:log("debug", "Enabling stream management");
session.smacks = true;
-- Overwrite process_stanza() and send()
local queue = {};
session.outgoing_stanza_queue = queue;
session.last_acknowledged_stanza = 0;
local _send = session.sends2s or session.send;
local function new_send(stanza)
local attr = stanza.attr;
if attr and not attr.xmlns then -- Stanza in default stream namespace
queue[#queue+1] = st.clone(stanza);
end
local ok, err = _send(stanza);
if ok and #queue > max_unacked_stanzas and not session.awaiting_ack then
session.awaiting_ack = true;
return _send(st.stanza("r", { xmlns = xmlns_sm }));
end
return ok, err;
end
if session.sends2s then
session.sends2s = new_send;
else
session.send = new_send;
end
session.handled_stanza_count = 0;
add_filter(session, "stanzas/in", function (stanza)
if not stanza.attr.xmlns then
session.handled_stanza_count = session.handled_stanza_count + 1;
session.log("debug", "Handled %d incoming stanzas", session.handled_stanza_count);
end
return stanza;
end);
if not stanza.attr.resume then -- FIXME: Resumption should be a different spec :/
_send(st.stanza("enabled", sm_attr));
return true;
end
end, 100);
module:hook_stanza(xmlns_sm, "r", function (origin, stanza)
if not origin.smacks then
module:log("debug", "Received ack request from non-smack-enabled session");
return;
end
module:log("debug", "Received ack request, acking for %d", origin.handled_stanza_count);
-- Reply with <a>
(origin.sends2s or origin.send)(st.stanza("a", { xmlns = xmlns_sm, h = tostring(origin.handled_stanza_count) }));
return true;
end);
module:hook_stanza(xmlns_sm, "a", function (origin, stanza)
if not origin.smacks then return; end
origin.awaiting_ack = nil;
-- Remove handled stanzas from outgoing_stanza_queue
--log("debug", "ACK: h=%s, last=%s", stanza.attr.h or "", origin.last_acknowledged_stanza or "");
local handled_stanza_count = tonumber(stanza.attr.h)-origin.last_acknowledged_stanza;
local queue = origin.outgoing_stanza_queue;
if handled_stanza_count > #queue then
module:log("warn", "The client says it handled %d new stanzas, but we only sent %d :)",
handled_stanza_count, #queue);
for i=1,#queue do
module:log("debug", "Q item %d: %s", i, tostring(queue[i]));
end
end
for i=1,math_min(handled_stanza_count,#queue) do
t_remove(origin.outgoing_stanza_queue, 1);
end
origin.last_acknowledged_stanza = origin.last_acknowledged_stanza + handled_stanza_count;
return true;
end);
--TODO: Optimise... incoming stanzas should be handled by a per-session
-- function that has a counter as an upvalue (no table indexing for increments,
-- and won't slow non-198 sessions). We can also then remove the .handled flag
-- on stanzas
function handle_unacked_stanzas(session)
local queue = session.outgoing_stanza_queue;
local error_attr = { type = "cancel" };
if #queue > 0 then
session.outgoing_stanza_queue = {};
for i=1,#queue do
local reply = st.reply(queue[i]);
if reply.attr.to ~= session.full_jid then
reply.attr.type = "error";
reply:tag("error", error_attr)
:tag("recipient-unavailable", {xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas"});
core_process_stanza(session, reply);
end
end
end
end
local _destroy_session = sessionmanager.destroy_session;
function sessionmanager.destroy_session(session, err)
if session.smacks then
if not session.resumption_token then
local queue = session.outgoing_stanza_queue;
if #queue > 0 then
module:log("warn", "Destroying session with %d unacked stanzas:", #queue);
for i=1,#queue do
module:log("warn", "::%s", tostring(queue[i]));
end
handle_unacked_stanzas(session);
end
else
session.hibernating = true;
timer.add_task(resume_timeout, function ()
if session.hibernating then
session.resumption_token = nil;
sessionmanager.destroy_session(session); -- Re-destroy
end
end);
return; -- Postpone destruction for now
end
end
return _destroy_session(session, err);
end
|
local st = require "util.stanza";
local t_insert, t_remove = table.insert, table.remove;
local math_min = math.min;
local tonumber, tostring = tonumber, tostring;
local add_filter = require "util.filters".add_filter;
local timer = require "util.timer";
local xmlns_sm = "urn:xmpp:sm:2";
local sm_attr = { xmlns = xmlns_sm };
local resume_timeout = 300;
local max_unacked_stanzas = 0;
module:hook("stream-features",
function (event)
event.features:tag("sm", sm_attr):tag("optional"):up():up();
end);
module:hook("s2s-stream-features",
function (event)
event.features:tag("sm", sm_attr):tag("optional"):up():up();
end);
module:hook_stanza(xmlns_sm, "enable",
function (session, stanza)
module:log("debug", "Enabling stream management");
session.smacks = true;
-- Overwrite process_stanza() and send()
local queue = {};
session.outgoing_stanza_queue = queue;
session.last_acknowledged_stanza = 0;
local _send = session.sends2s or session.send;
local function new_send(stanza)
local attr = stanza.attr;
if attr and not attr.xmlns then -- Stanza in default stream namespace
queue[#queue+1] = st.clone(stanza);
end
local ok, err = _send(stanza);
if ok and #queue > max_unacked_stanzas and not session.awaiting_ack then
session.awaiting_ack = true;
return _send(st.stanza("r", { xmlns = xmlns_sm }));
end
return ok, err;
end
if session.sends2s then
session.sends2s = new_send;
else
session.send = new_send;
end
session.handled_stanza_count = 0;
add_filter(session, "stanzas/in", function (stanza)
if not stanza.attr.xmlns then
session.handled_stanza_count = session.handled_stanza_count + 1;
session.log("debug", "Handled %d incoming stanzas", session.handled_stanza_count);
end
return stanza;
end);
if not stanza.attr.resume then -- FIXME: Resumption should be a different spec :/
_send(st.stanza("enabled", sm_attr));
return true;
end
end, 100);
module:hook_stanza(xmlns_sm, "r", function (origin, stanza)
if not origin.smacks then
module:log("debug", "Received ack request from non-smack-enabled session");
return;
end
module:log("debug", "Received ack request, acking for %d", origin.handled_stanza_count);
-- Reply with <a>
(origin.sends2s or origin.send)(st.stanza("a", { xmlns = xmlns_sm, h = tostring(origin.handled_stanza_count) }));
return true;
end);
module:hook_stanza(xmlns_sm, "a", function (origin, stanza)
if not origin.smacks then return; end
origin.awaiting_ack = nil;
-- Remove handled stanzas from outgoing_stanza_queue
--log("debug", "ACK: h=%s, last=%s", stanza.attr.h or "", origin.last_acknowledged_stanza or "");
local handled_stanza_count = tonumber(stanza.attr.h)-origin.last_acknowledged_stanza;
local queue = origin.outgoing_stanza_queue;
if handled_stanza_count > #queue then
module:log("warn", "The client says it handled %d new stanzas, but we only sent %d :)",
handled_stanza_count, #queue);
for i=1,#queue do
module:log("debug", "Q item %d: %s", i, tostring(queue[i]));
end
end
for i=1,math_min(handled_stanza_count,#queue) do
t_remove(origin.outgoing_stanza_queue, 1);
end
origin.last_acknowledged_stanza = origin.last_acknowledged_stanza + handled_stanza_count;
return true;
end);
--TODO: Optimise... incoming stanzas should be handled by a per-session
-- function that has a counter as an upvalue (no table indexing for increments,
-- and won't slow non-198 sessions). We can also then remove the .handled flag
-- on stanzas
function handle_unacked_stanzas(session)
local queue = session.outgoing_stanza_queue;
local error_attr = { type = "cancel" };
if #queue > 0 then
session.outgoing_stanza_queue = {};
for i=1,#queue do
local reply = st.reply(queue[i]);
if reply.attr.to ~= session.full_jid then
reply.attr.type = "error";
reply:tag("error", error_attr)
:tag("recipient-unavailable", {xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas"});
core_process_stanza(session, reply);
end
end
end
end
local _destroy_session = sessionmanager.destroy_session;
function sessionmanager.destroy_session(session, err)
if session.smacks then
if not session.resumption_token then
local queue = session.outgoing_stanza_queue;
if #queue > 0 then
module:log("warn", "Destroying session with %d unacked stanzas:", #queue);
for i=1,#queue do
module:log("warn", "::%s", tostring(queue[i]));
end
handle_unacked_stanzas(session);
end
else
session.hibernating = true;
timer.add_task(resume_timeout, function ()
if session.hibernating then
session.resumption_token = nil;
sessionmanager.destroy_session(session); -- Re-destroy
end
end);
return; -- Postpone destruction for now
end
end
return _destroy_session(session, err);
end
|
mod_smacks: Fixed to use the correct events API.
|
mod_smacks: Fixed to use the correct events API.
|
Lua
|
mit
|
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
|
55d01a56851543f397b5dd1eeda809cf412b36fa
|
hostinfo/misc.lua
|
hostinfo/misc.lua
|
--[[
Copyright 2015 Rackspace
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local table = require('table')
local misc = require('virgo/util/misc')
local async = require('async')
local childProcess = require('childprocess')
local string = require('string')
local fs = require('fs')
local function execFileToBuffers(command, args, options, callback)
local child, stdout, stderr, exitCode
stdout = {}
stderr = {}
callback = misc.fireOnce(callback)
child = childProcess.spawn(command, args, options)
child.stdout:on('data', function (chunk)
table.insert(stdout, chunk)
end)
child.stderr:on('data', function (chunk)
table.insert(stderr, chunk)
end)
async.parallel({
function(callback)
child.stdout:on('end', callback)
end,
function(callback)
child.stderr:on('end', callback)
end,
function(callback)
local onExit
function onExit(code)
exitCode = code
callback()
end
child:on('exit', onExit)
end
}, function(err)
callback(err, exitCode, table.concat(stdout, ""), table.concat(stderr, ""))
end)
end
local function readCast(filePath, errHandler, outTable, casterFunc, callback)
-- Sanity checks
if (type(filePath) ~= 'string') then filePath = '' end
if (type(errHandler) ~= 'table') then errHandler = {} end
if (type(outTable) ~= 'table') then outTable = {} end
if (type(casterFunc) ~= 'function') then
function casterFunc(...) end
end
if (type(callback) ~= 'function') then
function callback(...) end
end
local obj = {}
fs.exists(filePath, function(err, file)
if err then
table.insert(errHandler, string.format('fs.exists in fstab.lua erred: %s', err))
return callback()
end
if file then
fs.readFile(filePath, function(err, data)
if err then
table.insert(errHandler, string.format('fs.readline erred: %s', err))
return callback()
end
for line in data:gmatch("[^\r\n]+") do
local iscomment = string.match(line, '^#')
local isblank = string.len(line:gsub("%s+", "")) <= 0
if not iscomment and not isblank then
-- split the line and assign key vals
local iter = line:gmatch("%S+")
casterFunc(iter, obj, line)
end
end
-- Flatten single entry objects
if #obj == 1 then obj = obj[1] end
table.insert(outTable, obj)
return callback()
end)
else
table.insert(errHandler, 'file not found')
return callback()
end
end)
end
return {execFileToBuffers=execFileToBuffers, readCast=readCast}
|
--[[
Copyright 2015 Rackspace
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local table = require('table')
local misc = require('virgo/util/misc')
local async = require('async')
local childProcess = require('childprocess')
local string = require('string')
local fs = require('fs')
local function execFileToBuffers(command, args, options, callback)
local child, stdout, stderr, exitCode
stdout = {}
stderr = {}
callback = misc.fireOnce(callback)
child = childProcess.spawn(command, args, options)
child.stdout:on('data', function (chunk)
table.insert(stdout, chunk)
end)
child.stderr:on('data', function (chunk)
table.insert(stderr, chunk)
end)
async.parallel({
function(callback)
child.stdout:on('end', callback)
end,
function(callback)
child.stderr:on('end', callback)
end,
function(callback)
local onExit
function onExit(code)
exitCode = code
callback()
end
child:on('exit', onExit)
end
}, function(err)
callback(err, exitCode, table.concat(stdout, ""), table.concat(stderr, ""))
end)
end
local function readCast(filePath, errHandler, outTable, casterFunc, callback)
-- Sanity checks
if (type(filePath) ~= 'string') then filePath = '' end
if (type(errHandler) ~= 'table') then errHandler = {} end
if (type(outTable) ~= 'table') then outTable = {} end
if (type(casterFunc) ~= 'function') then
function casterFunc(...) end
end
if (type(callback) ~= 'function') then
function callback(...) end
end
local obj = {}
fs.exists(filePath, function(err, file)
if err then
table.insert(errHandler, string.format('fs.exists in fstab.lua erred: %s', err))
return callback()
end
if file then
fs.readFile(filePath, function(err, data)
if err then
table.insert(errHandler, string.format('fs.readline erred: %s', err))
return callback()
end
for line in data:gmatch("[^\r\n]+") do
local iscomment = string.match(line, '^#')
local isblank = string.len(line:gsub("%s+", "")) <= 0
if not iscomment and not isblank then
-- split the line and assign key vals
local iter = line:gmatch("%S+")
casterFunc(iter, obj, line)
end
end
-- Flatten single entry objects
if #obj == 1 then obj = obj[1] end
-- Dont insert empty objects into the outTable
if next(obj) then table.insert(outTable, obj) end
return callback()
end)
else
table.insert(errHandler, 'file not found')
return callback()
end
end)
end
return {execFileToBuffers=execFileToBuffers, readCast=readCast}
|
fix(hostinfo/misc): make the readcast function not insert empty objects into the outtable. Fixes #805
|
fix(hostinfo/misc): make the readcast function not insert empty objects into the outtable. Fixes #805
|
Lua
|
apache-2.0
|
virgo-agent-toolkit/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent
|
02ddce7ab28ac5d7c91b05a5695c611e0c4e1c03
|
packages/unichar/init.lua
|
packages/unichar/init.lua
|
local base = require("packages.base")
local package = pl.class(base)
package._name = "unichar"
function package:registerCommands ()
self:registerCommand("unichar", function(_, content)
local cp = content[1]
if type(cp) ~= "string" then SU.error("Bad argument to \\unicode") end
local hlist = SILE.typesetter.state.nodes
local char = SU.utf8charfromcodepoint(cp)
if #hlist > 1 and hlist[#hlist].is_unshaped then
hlist[#hlist].text = hlist[#hlist].text .. char
else
SILE.typesetter:typeset(char)
end
end)
end
package.documentation = [[
\begin{document}
\use[module=packages.unichar]
SILE is Unicode compatible, and expects its input files to be in the UTF-8 encoding.
(The actual range of Unicode characters supported will depend on the supported ranges of the fonts that SILE is using to typeset.)
Some Unicode characters are hard to locate on a standard keyboard, and so are difficult to enter into SILE documents.
The \autodoc:package{unichar} package helps with this problem by providing a command to enter Unicode codepoints.
After loading \autodoc:package{unichar}, the \autodoc:command{\unichar} command becomes available:
\begin{verbatim}
\line
\\unichar\{U+263A\} \% produces \font[family=Symbola]{\unichar{U+263A}}
\line
\end{verbatim}
If the argument to \autodoc:command{\unichar} begins \code{U+}, \code{u+}, \code{0x} or \code{0X}, then it is assumed to be a hexadecimal value.
Otherwise it is assumed to be a decimal codepoint.
\end{document}
]]
return package
|
local base = require("packages.base")
local package = pl.class(base)
package._name = "unichar"
function package:registerCommands ()
self:registerCommand("unichar", function(_, content)
local cp = content[1]
if type(cp) ~= "string" then SU.error("Bad argument to \\unicode") end
local hlist = SILE.typesetter.state.nodes
local char = SU.utf8charfromcodepoint(cp)
if #hlist > 1 and hlist[#hlist].is_unshaped then
hlist[#hlist].text = hlist[#hlist].text .. char
else
SILE.typesetter:typeset(char)
end
end)
end
package.documentation = [[
\begin{document}
\use[module=packages.unichar]
SILE is Unicode compatible, and expects its input files to be in the UTF-8 encoding.
(The actual range of Unicode characters supported will depend on the supported ranges of the fonts that SILE is using to typeset.)
Some Unicode characters are hard to locate on a standard keyboard, and so are difficult to enter into SILE documents.
The \autodoc:package{unichar} package helps with this problem by providing a command to enter Unicode codepoints.
After loading \autodoc:package{unichar}, the \autodoc:command{\unichar} command becomes available:
\begin{verbatim}
\line
% Note we are directly outputing the unicode to workaround https://github.com/sile-typesetter/sile/issues/991
\\unichar\{U+263A\} \% produces \font[family=Symbola]{☺}
\line
\end{verbatim}
If the argument to \autodoc:command{\unichar} begins \code{U+}, \code{u+}, \code{0x} or \code{0X}, then it is assumed to be a hexadecimal value.
Otherwise it is assumed to be a decimal codepoint.
\end{document}
]]
return package
|
docs(packages): Fixup unichar documentation, work around known bug (#1549)
|
docs(packages): Fixup unichar documentation, work around known bug (#1549)
|
Lua
|
mit
|
alerque/sile,alerque/sile,alerque/sile,alerque/sile
|
b0731f9f8067b460325e86ca3cde2d1c96cf9ff9
|
libs/web/luasrc/dispatcher.lua
|
libs/web/luasrc/dispatcher.lua
|
--[[
LuCI - Dispatcher
Description:
The request dispatcher and module dispatcher generators
FileId:
$Id$
License:
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
module("luci.dispatcher", package.seeall)
require("luci.http")
require("luci.sys")
require("luci.fs")
-- Local dispatch database
local tree = {nodes={}}
-- Index table
local index = {}
-- Global request object
request = {}
-- Active dispatched node
dispatched = nil
-- Status fields
built_index = false
built_tree = false
-- Builds a URL
function build_url(...)
return luci.http.dispatcher() .. "/" .. table.concat(arg, "/")
end
-- Sends a 404 error code and renders the "error404" template if available
function error404(message)
luci.http.status(404, "Not Found")
message = message or "Not Found"
require("luci.template")
if not pcall(luci.template.render, "error404") then
luci.http.prepare_content("text/plain")
print(message)
end
return false
end
-- Sends a 500 error code and renders the "error500" template if available
function error500(message)
luci.http.status(500, "Internal Server Error")
require("luci.template")
if not pcall(luci.template.render, "error500", {message=message}) then
luci.http.prepare_content("text/plain")
print(message)
end
return false
end
-- Creates a request object for dispatching
function httpdispatch()
local pathinfo = luci.http.env.PATH_INFO or ""
local c = tree
for s in pathinfo:gmatch("([%w-]+)") do
table.insert(request, s)
end
dispatch()
end
-- Dispatches a request
function dispatch()
if not built_tree then
createtree()
end
local c = tree
local track = {}
for i, s in ipairs(request) do
c = c.nodes[s]
if not c or c.leaf then
break
end
for k, v in pairs(c) do
track[k] = v
end
end
if track.i18n then
require("luci.i18n").loadc(track.i18n)
end
if track.setgroup then
luci.sys.process.setgroup(track.setgroup)
end
if track.setuser then
luci.sys.process.setuser(track.setuser)
end
-- Init template engine
local tpl = require("luci.template")
tpl.viewns.translate = function(...) return require("luci.i18n").translate(...) end
tpl.viewns.controller = luci.http.dispatcher()
tpl.viewns.uploadctrl = luci.http.dispatcher_upload()
tpl.viewns.media = luci.config.main.mediaurlbase
tpl.viewns.resource = luci.config.main.resourcebase
tpl.viewns.REQUEST_URI = luci.http.env.SCRIPT_NAME .. luci.http.env.PATH_INFO
if c and type(c.target) == "function" then
dispatched = c
stat, mod = pcall(require, c.module)
if stat then
luci.util.updfenv(c.target, mod)
end
stat, err = pcall(c.target)
if not stat then
error500(err)
end
else
error404()
end
end
-- Generates the dispatching tree
function createindex()
index = {}
local path = luci.sys.libpath() .. "/controller/"
local suff = ".lua"
--[[if pcall(require, "fastindex") then
createindex_fastindex(path, suff)
else
createindex_plain(path, suff)
end]]--
createindex_plain(path, suff)
built_index = true
end
-- Uses fastindex to create the dispatching tree
function createindex_fastindex(path, suffix)
local fi = fastindex.new("index")
fi.add(path .. "*" .. suffix)
fi.add(path .. "*/*" .. suffix)
fi.scan()
for k, v in pairs(fi.indexes) do
index[v[2]] = v[1]
end
end
-- Calls the index function of all available controllers
function createindex_plain(path, suffix)
local cache = nil
local controllers = luci.util.combine(
luci.fs.glob(path .. "*" .. suffix) or {},
luci.fs.glob(path .. "*/*" .. suffix) or {}
)
if indexcache then
cache = luci.fs.mtime(indexcache)
if not cache then
luci.fs.mkdir(indexcache)
luci.fs.chmod(indexcache, "a=,u=rwx")
cache = luci.fs.mtime(indexcache)
end
end
for i,c in ipairs(controllers) do
local module = "luci.controller." .. c:sub(#path+1, #c-#suffix):gsub("/", ".")
local cachefile = indexcache .. "/" .. module
local stime
local ctime
if cache then
stime = luci.fs.mtime(c) or 0
ctime = luci.fs.mtime(cachefile) or 0
end
if not cache or stime > ctime then
stat, mod = pcall(require, module)
if stat and mod and type(mod.index) == "function" then
index[module] = mod.index
if cache then
luci.fs.writefile(cachefile, luci.util.dump(mod.index))
end
end
else
index[module] = loadfile(cachefile)
end
end
end
-- Creates the dispatching tree from the index
function createtree()
if not built_index then
createindex()
end
require("luci.i18n")
-- Load default translation
luci.i18n.loadc("default")
local scope = luci.util.clone(_G)
for k,v in pairs(_M) do
if type(v) == "function" then
scope[k] = v
end
end
for k, v in pairs(index) do
scope._NAME = k
setfenv(v, scope)
local stat, err = pcall(v)
if not stat then
error500(err)
os.exit(1)
end
end
built_tree = true
end
-- Shortcut for creating a dispatching node
function entry(path, target, title, order, add)
add = add or {}
local c = node(path)
c.target = target
c.title = title
c.order = order
c.module = getfenv(2)._NAME
for k,v in pairs(add) do
c[k] = v
end
return c
end
-- Fetch a dispatching node
function node(...)
local c = tree
if arg[1] and type(arg[1]) == "table" then
arg = arg[1]
end
for k,v in ipairs(arg) do
if not c.nodes[v] then
c.nodes[v] = {nodes={}, module=getfenv(2)._NAME}
end
c = c.nodes[v]
end
return c
end
-- Subdispatchers --
function alias(...)
local req = arg
return function()
request = req
dispatch()
end
end
function rewrite(n, ...)
local req = arg
return function()
for i=1,n do
table.remove(request, 1)
end
for i,r in ipairs(req) do
table.insert(request, i, r)
end
dispatch()
end
end
function call(name)
return function() getfenv()[name]() end
end
function template(name)
require("luci.template")
return function() luci.template.render(name) end
end
function cbi(model)
require("luci.cbi")
require("luci.template")
return function()
local stat, res = pcall(luci.cbi.load, model)
if not stat then
error500(res)
return true
end
local stat, err = pcall(res.parse, res)
if not stat then
error500(err)
return true
end
luci.template.render("cbi/header")
res:render()
luci.template.render("cbi/footer")
end
end
|
--[[
LuCI - Dispatcher
Description:
The request dispatcher and module dispatcher generators
FileId:
$Id$
License:
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
module("luci.dispatcher", package.seeall)
require("luci.http")
require("luci.sys")
require("luci.fs")
-- Dirty OpenWRT fix
if (os.time() < luci.fs.mtime(luci.sys.libpath() .. "/dispatcher.lua")) then
os.execute('date -s '..os.date('%m%d%H%M%Y', luci.fs.mtime(luci.sys.libpath() .. "/dispatcher.lua")))
end
-- Local dispatch database
local tree = {nodes={}}
-- Index table
local index = {}
-- Global request object
request = {}
-- Active dispatched node
dispatched = nil
-- Status fields
built_index = false
built_tree = false
-- Builds a URL
function build_url(...)
return luci.http.dispatcher() .. "/" .. table.concat(arg, "/")
end
-- Sends a 404 error code and renders the "error404" template if available
function error404(message)
luci.http.status(404, "Not Found")
message = message or "Not Found"
require("luci.template")
if not pcall(luci.template.render, "error404") then
luci.http.prepare_content("text/plain")
print(message)
end
return false
end
-- Sends a 500 error code and renders the "error500" template if available
function error500(message)
luci.http.status(500, "Internal Server Error")
require("luci.template")
if not pcall(luci.template.render, "error500", {message=message}) then
luci.http.prepare_content("text/plain")
print(message)
end
return false
end
-- Creates a request object for dispatching
function httpdispatch()
local pathinfo = luci.http.env.PATH_INFO or ""
local c = tree
for s in pathinfo:gmatch("([%w-]+)") do
table.insert(request, s)
end
dispatch()
end
-- Dispatches a request
function dispatch()
if not built_tree then
createtree()
end
local c = tree
local track = {}
for i, s in ipairs(request) do
c = c.nodes[s]
if not c or c.leaf then
break
end
for k, v in pairs(c) do
track[k] = v
end
end
if track.i18n then
require("luci.i18n").loadc(track.i18n)
end
if track.setgroup then
luci.sys.process.setgroup(track.setgroup)
end
if track.setuser then
luci.sys.process.setuser(track.setuser)
end
-- Init template engine
local tpl = require("luci.template")
tpl.viewns.translate = function(...) return require("luci.i18n").translate(...) end
tpl.viewns.controller = luci.http.dispatcher()
tpl.viewns.uploadctrl = luci.http.dispatcher_upload()
tpl.viewns.media = luci.config.main.mediaurlbase
tpl.viewns.resource = luci.config.main.resourcebase
tpl.viewns.REQUEST_URI = luci.http.env.SCRIPT_NAME .. luci.http.env.PATH_INFO
if c and type(c.target) == "function" then
dispatched = c
stat, mod = pcall(require, c.module)
if stat then
luci.util.updfenv(c.target, mod)
end
stat, err = pcall(c.target)
if not stat then
error500(err)
end
else
error404()
end
end
-- Generates the dispatching tree
function createindex()
index = {}
local path = luci.sys.libpath() .. "/controller/"
local suff = ".lua"
--[[if pcall(require, "fastindex") then
createindex_fastindex(path, suff)
else
createindex_plain(path, suff)
end]]--
createindex_plain(path, suff)
built_index = true
end
-- Uses fastindex to create the dispatching tree
function createindex_fastindex(path, suffix)
local fi = fastindex.new("index")
fi.add(path .. "*" .. suffix)
fi.add(path .. "*/*" .. suffix)
fi.scan()
for k, v in pairs(fi.indexes) do
index[v[2]] = v[1]
end
end
-- Calls the index function of all available controllers
function createindex_plain(path, suffix)
local cache = nil
local controllers = luci.util.combine(
luci.fs.glob(path .. "*" .. suffix) or {},
luci.fs.glob(path .. "*/*" .. suffix) or {}
)
if indexcache then
cache = luci.fs.mtime(indexcache)
if not cache then
luci.fs.mkdir(indexcache)
luci.fs.chmod(indexcache, "a=,u=rwx")
cache = luci.fs.mtime(indexcache)
end
end
for i,c in ipairs(controllers) do
local module = "luci.controller." .. c:sub(#path+1, #c-#suffix):gsub("/", ".")
local cachefile = indexcache .. "/" .. module
local stime
local ctime
if cache then
stime = luci.fs.mtime(c) or 0
ctime = luci.fs.mtime(cachefile) or 0
end
if not cache or stime > ctime then
stat, mod = pcall(require, module)
if stat and mod and type(mod.index) == "function" then
index[module] = mod.index
if cache then
luci.fs.writefile(cachefile, luci.util.dump(mod.index))
end
end
else
index[module] = loadfile(cachefile)
end
end
end
-- Creates the dispatching tree from the index
function createtree()
if not built_index then
createindex()
end
require("luci.i18n")
-- Load default translation
luci.i18n.loadc("default")
local scope = luci.util.clone(_G)
for k,v in pairs(_M) do
if type(v) == "function" then
scope[k] = v
end
end
for k, v in pairs(index) do
scope._NAME = k
setfenv(v, scope)
local stat, err = pcall(v)
if not stat then
error500(err)
os.exit(1)
end
end
built_tree = true
end
-- Shortcut for creating a dispatching node
function entry(path, target, title, order, add)
add = add or {}
local c = node(path)
c.target = target
c.title = title
c.order = order
c.module = getfenv(2)._NAME
for k,v in pairs(add) do
c[k] = v
end
return c
end
-- Fetch a dispatching node
function node(...)
local c = tree
if arg[1] and type(arg[1]) == "table" then
arg = arg[1]
end
for k,v in ipairs(arg) do
if not c.nodes[v] then
c.nodes[v] = {nodes={}, module=getfenv(2)._NAME}
end
c = c.nodes[v]
end
return c
end
-- Subdispatchers --
function alias(...)
local req = arg
return function()
request = req
dispatch()
end
end
function rewrite(n, ...)
local req = arg
return function()
for i=1,n do
table.remove(request, 1)
end
for i,r in ipairs(req) do
table.insert(request, i, r)
end
dispatch()
end
end
function call(name)
return function() getfenv()[name]() end
end
function template(name)
require("luci.template")
return function() luci.template.render(name) end
end
function cbi(model)
require("luci.cbi")
require("luci.template")
return function()
local stat, res = pcall(luci.cbi.load, model)
if not stat then
error500(res)
return true
end
local stat, err = pcall(res.parse, res)
if not stat then
error500(err)
return true
end
luci.template.render("cbi/header")
res:render()
luci.template.render("cbi/footer")
end
end
|
* Added timing fix
|
* Added timing fix
git-svn-id: edf5ee79c2c7d29460bbb5b398f55862cc26620d@2222 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
ch3n2k/luci,Flexibity/luci,freifunk-gluon/luci,vhpham80/luci,8devices/carambola2-luci,yeewang/openwrt-luci,alxhh/piratenluci,Canaan-Creative/luci,eugenesan/openwrt-luci,vhpham80/luci,ch3n2k/luci,saraedum/luci-packages-old,phi-psi/luci,yeewang/openwrt-luci,dtaht/cerowrt-luci-3.3,ReclaimYourPrivacy/cloak-luci,jschmidlapp/luci,yeewang/openwrt-luci,Canaan-Creative/luci,8devices/carambola2-luci,ThingMesh/openwrt-luci,ThingMesh/openwrt-luci,freifunk-gluon/luci,ReclaimYourPrivacy/cloak-luci,Canaan-Creative/luci,eugenesan/openwrt-luci,freifunk-gluon/luci,ThingMesh/openwrt-luci,freifunk-gluon/luci,vhpham80/luci,alxhh/piratenluci,freifunk-gluon/luci,projectbismark/luci-bismark,Flexibity/luci,zwhfly/openwrt-luci,phi-psi/luci,phi-psi/luci,ReclaimYourPrivacy/cloak-luci,zwhfly/openwrt-luci,ThingMesh/openwrt-luci,alxhh/piratenluci,phi-psi/luci,vhpham80/luci,stephank/luci,ch3n2k/luci,dtaht/cerowrt-luci-3.3,ReclaimYourPrivacy/cloak-luci,eugenesan/openwrt-luci,alxhh/piratenluci,stephank/luci,stephank/luci,projectbismark/luci-bismark,alxhh/piratenluci,yeewang/openwrt-luci,saraedum/luci-packages-old,zwhfly/openwrt-luci,ch3n2k/luci,zwhfly/openwrt-luci,phi-psi/luci,Canaan-Creative/luci,stephank/luci,jschmidlapp/luci,freifunk-gluon/luci,gwlim/luci,eugenesan/openwrt-luci,vhpham80/luci,stephank/luci,zwhfly/openwrt-luci,ReclaimYourPrivacy/cloak-luci,ch3n2k/luci,freifunk-gluon/luci,dtaht/cerowrt-luci-3.3,saraedum/luci-packages-old,saraedum/luci-packages-old,jschmidlapp/luci,projectbismark/luci-bismark,Canaan-Creative/luci,alxhh/piratenluci,zwhfly/openwrt-luci,Flexibity/luci,Canaan-Creative/luci,phi-psi/luci,jschmidlapp/luci,ReclaimYourPrivacy/cloak-luci,Flexibity/luci,ThingMesh/openwrt-luci,Flexibity/luci,eugenesan/openwrt-luci,8devices/carambola2-luci,zwhfly/openwrt-luci,gwlim/luci,dtaht/cerowrt-luci-3.3,gwlim/luci,zwhfly/openwrt-luci,Flexibity/luci,Canaan-Creative/luci,freifunk-gluon/luci,ThingMesh/openwrt-luci,jschmidlapp/luci,Flexibity/luci,ThingMesh/openwrt-luci,dtaht/cerowrt-luci-3.3,gwlim/luci,8devices/carambola2-luci,eugenesan/openwrt-luci,jschmidlapp/luci,projectbismark/luci-bismark,ch3n2k/luci,ReclaimYourPrivacy/cloak-luci,gwlim/luci,alxhh/piratenluci,saraedum/luci-packages-old,8devices/carambola2-luci,jschmidlapp/luci,phi-psi/luci,zwhfly/openwrt-luci,saraedum/luci-packages-old,saraedum/luci-packages-old,8devices/carambola2-luci,eugenesan/openwrt-luci,gwlim/luci,jschmidlapp/luci,Canaan-Creative/luci,stephank/luci,yeewang/openwrt-luci,Flexibity/luci,ReclaimYourPrivacy/cloak-luci,yeewang/openwrt-luci,projectbismark/luci-bismark,ch3n2k/luci,gwlim/luci,vhpham80/luci,dtaht/cerowrt-luci-3.3,projectbismark/luci-bismark,projectbismark/luci-bismark,yeewang/openwrt-luci,projectbismark/luci-bismark,8devices/carambola2-luci
|
e9fb9abca54a15dc8b4139e437d2b29c68d6d4eb
|
LanguageModel.lua
|
LanguageModel.lua
|
require 'torch'
require 'nn'
require 'VanillaRNN'
require 'LSTM'
require 'GRU'
require 'GRIDGRU'
local utils = require 'util.utils'
local LM, parent = torch.class('nn.LanguageModel', 'nn.Module')
function LM:__init(kwargs)
self.idx_to_token = utils.get_kwarg(kwargs, 'idx_to_token')
self.token_to_idx = {}
self.vocab_size = 0
for idx, token in pairs(self.idx_to_token) do
self.token_to_idx[token] = idx
self.vocab_size = self.vocab_size + 1
end
self.model_type = utils.get_kwarg(kwargs, 'model_type')
self.wordvec_dim = utils.get_kwarg(kwargs, 'wordvec_size')
self.rnn_size = utils.get_kwarg(kwargs, 'rnn_size')
self.num_layers = utils.get_kwarg(kwargs, 'num_layers')
self.dropout = utils.get_kwarg(kwargs, 'dropout')
self.batchnorm = utils.get_kwarg(kwargs, 'batchnorm')
local V, D, H = self.vocab_size, self.wordvec_dim, self.rnn_size
self.net = nn.Sequential()
self.rnns = {}
self.bn_view_in = {}
self.bn_view_out = {}
self.net:add(nn.LookupTable(V, D))
for i = 1, self.num_layers do
local prev_dim = H
if i == 1 then prev_dim = D end
local rnn
if self.model_type == 'rnn' then
rnn = nn.VanillaRNN(prev_dim, H)
elseif self.model_type == 'lstm' then
rnn = nn.LSTM(prev_dim, H)
elseif self.model_type == 'gru' then
rnn = nn.GRU(prev_dim, H)
elseif self.model_type == 'gridgru' then
rnn = nn.GRIDGRU(D, H)
end
rnn.remember_states = true
table.insert(self.rnns, rnn)
self.net:add(rnn)
if self.batchnorm == 1 then
local view_in = nn.View(1, 1, -1):setNumInputDims(3)
table.insert(self.bn_view_in, view_in)
self.net:add(view_in)
self.net:add(nn.BatchNormalization(H))
local view_out = nn.View(1, -1):setNumInputDims(2)
table.insert(self.bn_view_out, view_out)
self.net:add(view_out)
end
if self.dropout > 0 then
self.net:add(nn.Dropout(self.dropout))
end
end
-- After all the RNNs run, we will have a tensor of shape (N, T, H);
-- we want to apply a 1D temporal convolution to predict scores for each
-- vocab element, giving a tensor of shape (N, T, V). Unfortunately
-- nn.TemporalConvolution is SUPER slow, so instead we will use a pair of
-- views (N, T, H) -> (NT, H) and (NT, V) -> (N, T, V) with a nn.Linear in
-- between. Unfortunately N and T can change on every minibatch, so we need
-- to set them in the forward pass.
self.view1 = nn.View(1, 1, -1):setNumInputDims(3)
self.view2 = nn.View(1, -1):setNumInputDims(2)
self.net:add(self.view1)
if self.model_type == 'gridgru' then
self.net:add(nn.Linear(D, V))
else
self.net:add(nn.Linear(H, V))
end
self.net:add(self.view2)
end
function LM:updateOutput(input)
local N, T = input:size(1), input:size(2)
self.view1:resetSize(N * T, -1)
self.view2:resetSize(N, T, -1)
for _, view_in in ipairs(self.bn_view_in) do
view_in:resetSize(N * T, -1)
end
for _, view_out in ipairs(self.bn_view_out) do
view_out:resetSize(N, T, -1)
end
return self.net:forward(input)
end
function LM:backward(input, gradOutput, scale)
return self.net:backward(input, gradOutput, scale)
end
function LM:parameters()
return self.net:parameters()
end
function LM:training()
self.net:training()
parent.training(self)
end
function LM:evaluate()
self.net:evaluate()
parent.evaluate(self)
end
function LM:resetStates()
for i, rnn in ipairs(self.rnns) do
rnn:resetStates()
end
end
function LM:encode_string(s)
local encoded = torch.LongTensor(#s)
for i = 1, #s do
local token = s:sub(i, i)
local idx = self.token_to_idx[token]
assert(idx ~= nil, 'Got invalid idx')
encoded[i] = idx
end
return encoded
end
function LM:decode_string(encoded)
assert(torch.isTensor(encoded) and encoded:dim() == 1)
local s = ''
for i = 1, encoded:size(1) do
local idx = encoded[i]
local token = self.idx_to_token[idx]
s = s .. token
end
return s
end
--[[
Sample from the language model. Note that this will reset the states of the
underlying RNNs.
Inputs:
- init: String of length T0
- max_length: Number of characters to sample
Returns:
- sampled: (1, max_length) array of integers, where the first part is init.
--]]
function LM:sample(kwargs)
local T = utils.get_kwarg(kwargs, 'length', 100)
local start_text = utils.get_kwarg(kwargs, 'start_text', '')
local verbose = utils.get_kwarg(kwargs, 'verbose', 0)
local sample = utils.get_kwarg(kwargs, 'sample', 1)
local temperature = utils.get_kwarg(kwargs, 'temperature', 1)
local sampled = torch.LongTensor(1, T)
self:resetStates()
local scores, first_t
if #start_text > 0 then
if verbose > 0 then
print('Seeding with: "' .. start_text .. '"')
end
local x = self:encode_string(start_text):view(1, -1)
local T0 = x:size(2)
sampled[{{}, {1, T0}}]:copy(x)
scores = self:forward(x)[{{}, {T0, T0}}]
first_t = T0 + 1
else
if verbose > 0 then
print('Seeding with uniform probabilities')
end
local w = self.net:get(1).weight
scores = w.new(1, 1, self.vocab_size):fill(1)
first_t = 1
end
local _, next_char = nil, nil
for t = first_t, T do
if sample == 0 then
_, next_char = scores:max(3)
next_char = next_char[{{}, {}, 1}]
else
local probs = torch.div(scores, temperature):double():exp():squeeze()
probs:div(torch.sum(probs))
next_char = torch.multinomial(probs, 1):view(1, 1)
end
sampled[{{}, {t, t}}]:copy(next_char)
scores = self:forward(next_char)
end
self:resetStates()
return self:decode_string(sampled[1])
end
function LM:clearState()
self.net:clearState()
end
|
require 'torch'
require 'nn'
require 'VanillaRNN'
require 'LSTM'
require 'GRU'
require 'GRIDGRU'
local utils = require 'util.utils'
local LM, parent = torch.class('nn.LanguageModel', 'nn.Module')
function LM:__init(kwargs)
self.idx_to_token = utils.get_kwarg(kwargs, 'idx_to_token')
self.token_to_idx = {}
self.vocab_size = 0
for idx, token in pairs(self.idx_to_token) do
self.token_to_idx[token] = idx
self.vocab_size = self.vocab_size + 1
end
self.model_type = utils.get_kwarg(kwargs, 'model_type')
self.wordvec_dim = utils.get_kwarg(kwargs, 'wordvec_size')
self.rnn_size = utils.get_kwarg(kwargs, 'rnn_size')
self.num_layers = utils.get_kwarg(kwargs, 'num_layers')
self.dropout = utils.get_kwarg(kwargs, 'dropout')
self.batchnorm = utils.get_kwarg(kwargs, 'batchnorm')
local V, D, H = self.vocab_size, self.wordvec_dim, self.rnn_size
self.net = nn.Sequential()
self.rnns = {}
self.bn_view_in = {}
self.bn_view_out = {}
self.net:add(nn.LookupTable(V, D))
for i = 1, self.num_layers do
local prev_dim = H
if i == 1 then prev_dim = D end
local rnn
if self.model_type == 'rnn' then
rnn = nn.VanillaRNN(prev_dim, H)
elseif self.model_type == 'lstm' then
rnn = nn.LSTM(prev_dim, H)
elseif self.model_type == 'gru' then
rnn = nn.GRU(prev_dim, H)
elseif self.model_type == 'gridgru' then
rnn = nn.GRIDGRU(D, H)
end
rnn.remember_states = true
table.insert(self.rnns, rnn)
self.net:add(rnn)
if self.batchnorm == 1 then
local view_in = nn.View(1, 1, -1):setNumInputDims(3)
table.insert(self.bn_view_in, view_in)
self.net:add(view_in)
self.net:add(nn.BatchNormalization((self.model_type == 'gridgru') and D or H))
local view_out = nn.View(1, -1):setNumInputDims(2)
table.insert(self.bn_view_out, view_out)
self.net:add(view_out)
end
if self.dropout > 0 then
self.net:add(nn.Dropout(self.dropout))
end
end
-- After all the RNNs run, we will have a tensor of shape (N, T, H);
-- we want to apply a 1D temporal convolution to predict scores for each
-- vocab element, giving a tensor of shape (N, T, V). Unfortunately
-- nn.TemporalConvolution is SUPER slow, so instead we will use a pair of
-- views (N, T, H) -> (NT, H) and (NT, V) -> (N, T, V) with a nn.Linear in
-- between. Unfortunately N and T can change on every minibatch, so we need
-- to set them in the forward pass.
self.view1 = nn.View(1, 1, -1):setNumInputDims(3)
self.view2 = nn.View(1, -1):setNumInputDims(2)
self.net:add(self.view1)
if self.model_type == 'gridgru' then
self.net:add(nn.Linear(D, V))
else
self.net:add(nn.Linear(H, V))
end
self.net:add(self.view2)
end
function LM:updateOutput(input)
local N, T = input:size(1), input:size(2)
self.view1:resetSize(N * T, -1)
self.view2:resetSize(N, T, -1)
for _, view_in in ipairs(self.bn_view_in) do
view_in:resetSize(N * T, -1)
end
for _, view_out in ipairs(self.bn_view_out) do
view_out:resetSize(N, T, -1)
end
return self.net:forward(input)
end
function LM:backward(input, gradOutput, scale)
return self.net:backward(input, gradOutput, scale)
end
function LM:parameters()
return self.net:parameters()
end
function LM:training()
self.net:training()
parent.training(self)
end
function LM:evaluate()
self.net:evaluate()
parent.evaluate(self)
end
function LM:resetStates()
for i, rnn in ipairs(self.rnns) do
rnn:resetStates()
end
end
function LM:encode_string(s)
local encoded = torch.LongTensor(#s)
for i = 1, #s do
local token = s:sub(i, i)
local idx = self.token_to_idx[token]
assert(idx ~= nil, 'Got invalid idx')
encoded[i] = idx
end
return encoded
end
function LM:decode_string(encoded)
assert(torch.isTensor(encoded) and encoded:dim() == 1)
local s = ''
for i = 1, encoded:size(1) do
local idx = encoded[i]
local token = self.idx_to_token[idx]
s = s .. token
end
return s
end
--[[
Sample from the language model. Note that this will reset the states of the
underlying RNNs.
Inputs:
- init: String of length T0
- max_length: Number of characters to sample
Returns:
- sampled: (1, max_length) array of integers, where the first part is init.
--]]
function LM:sample(kwargs)
local T = utils.get_kwarg(kwargs, 'length', 100)
local start_text = utils.get_kwarg(kwargs, 'start_text', '')
local verbose = utils.get_kwarg(kwargs, 'verbose', 0)
local sample = utils.get_kwarg(kwargs, 'sample', 1)
local temperature = utils.get_kwarg(kwargs, 'temperature', 1)
local sampled = torch.LongTensor(1, T)
self:resetStates()
local scores, first_t
if #start_text > 0 then
if verbose > 0 then
print('Seeding with: "' .. start_text .. '"')
end
local x = self:encode_string(start_text):view(1, -1)
local T0 = x:size(2)
sampled[{{}, {1, T0}}]:copy(x)
scores = self:forward(x)[{{}, {T0, T0}}]
first_t = T0 + 1
else
if verbose > 0 then
print('Seeding with uniform probabilities')
end
local w = self.net:get(1).weight
scores = w.new(1, 1, self.vocab_size):fill(1)
first_t = 1
end
local _, next_char = nil, nil
for t = first_t, T do
if sample == 0 then
_, next_char = scores:max(3)
next_char = next_char[{{}, {}, 1}]
else
local probs = torch.div(scores, temperature):double():exp():squeeze()
probs:div(torch.sum(probs))
next_char = torch.multinomial(probs, 1):view(1, 1)
end
sampled[{{}, {t, t}}]:copy(next_char)
scores = self:forward(next_char)
end
self:resetStates()
return self:decode_string(sampled[1])
end
function LM:clearState()
self.net:clearState()
end
|
Fix GridGRU BatchNorm dimension error
|
Fix GridGRU BatchNorm dimension error
GridGRU causes `BatchNormalization.lua:80: got D-feature tensor, expected H` if D ~= H.
|
Lua
|
mit
|
antihutka/torch-rnn,tmp6154/torch-rnn
|
0194d832842fc8e32988751cad7211a69fc3b4d7
|
lua/entities/gmod_starfall_hologram/cl_init.lua
|
lua/entities/gmod_starfall_hologram/cl_init.lua
|
include( "shared.lua" )
ENT.RenderGroup = RENDERGROUP_BOTH
-- Umsgs may be recieved before the entity is initialized, place
-- them in here until initialization.
local msgQueueNames = {}
local msgQueueData = {}
local function msgQueueAdd ( umname, ent, udata )
local names, data = msgQueueNames[ ent ], msgQueueData[ ent ]
if not names then
names, data = {}, {}
msgQueueNames[ ent ] = names
msgQueueData[ ent ] = data
end
local i = #names + 1
names[ i ] = umname
data[ i ] = udata
end
local function msgQueueProcess ( ent )
local entid = ent:EntIndex()
local names, data = msgQueueNames[ entid ], msgQueueData[ entid ]
if names then
for i = 1 , #names do
local name = names[ i ]
if name == "scale" then
ent:SetScale( data[ i ] )
elseif name == "clip" then
ent:UpdateClip( unpack( data[ i ] ) )
end
end
msgQueueNames[ entid ] = nil
msgQueueData[ entid ] = nil
end
end
-- ------------------------ MAIN FUNCTIONS ------------------------ --
function ENT:Initialize()
self.clips = {}
self.unlit = false
self.scale = Vector(1,1,1)
self.initialised = true
msgQueueProcess(self)
end
function ENT:Draw()
-- Setup clipping
local l = #self.clips
if l > 0 then
render.EnableClipping(true)
for i=1,l do
local clip = self.clips[i]
if clip.enabled then
local norm = clip.normal
local origin = clip.origin
if clip.islocal then
norm = self:LocalToWorld(norm) - self:GetPos()
origin = self:LocalToWorld(origin)
end
render.PushCustomClipPlane(norm, norm:Dot(origin))
end
end
end
render.SuppressEngineLighting(self.unlit)
self:DrawModel()
render.SuppressEngineLighting(false)
for i=1,#self.clips do render.PopCustomClipPlane() end
render.EnableClipping(false)
end
-- ------------------------ CLIPPING ------------------------ --
--- Updates a clip plane definition.
function ENT:UpdateClip(index, enabled, origin, normal, islocal)
local clip = self.clips[index]
if not clip then
clip = {}
self.clips[index] = clip
end
clip.enabled = enabled
clip.normal = normal
clip.origin = origin
clip.islocal = islocal
end
net.Receive("starfall_hologram_clip", function ()
local entid = net.ReadUInt( 32 )
local holoent = Entity( entid )
if ( not IsValid( holoent ) ) or ( not holoent.initialised ) then
-- Uninitialized
msgQueueAdd( "clip", entid, {
net.ReadUInt( 16 ),
net.ReadBit() ~= 0,
Vector( net.ReadDouble(), net.ReadDouble(), net.ReadDouble() ),
Vector( net.ReadDouble(), net.ReadDouble(), net.ReadDouble() ),
net.ReadBit() ~= 0
} )
else
holoent:UpdateClip (
net.ReadUInt( 16 ),
net.ReadBit() ~= 0,
Vector( net.ReadDouble(), net.ReadDouble(), net.ReadDouble() ),
Vector( net.ReadDouble(), net.ReadDouble(), net.ReadDouble() ),
net.ReadBit() ~= 0
)
end
end )
-- ------------------------ SCALING ------------------------ --
--- Sets the hologram scale
-- @param scale Vector scale
function ENT:SetScale ( scale )
self.scale = scale
local m = Matrix()
m:Scale( scale )
self:EnableMatrix( "RenderMultiply", m )
local propmax = self:OBBMaxs()
local propmin = self:OBBMins()
propmax.x = scale.x * propmax.x
propmax.y = scale.y * propmax.y
propmax.z = scale.z * propmax.z
propmin.x = scale.x * propmin.x
propmin.y = scale.y * propmin.y
propmin.z = scale.z * propmin.z
self:SetRenderBounds( propmax, propmin )
end
net.Receive("starfall_hologram_scale", function ()
local entid = net.ReadUInt( 32 )
local holoent = Entity( entid )
if ( not IsValid ( holoent ) ) or ( not holoent.initialised ) then
-- Uninitialized
msgQueueAdd( "scale", entid, Vector(net.ReadDouble(), net.ReadDouble(), net.ReadDouble()) )
else
holoent:SetScale( Vector( net.ReadDouble(), net.ReadDouble(), net.ReadDouble() ) )
end
end )
|
include( "shared.lua" )
ENT.RenderGroup = RENDERGROUP_BOTH
-- Umsgs may be recieved before the entity is initialized, place
-- them in here until initialization.
local msgQueueNames = {}
local msgQueueData = {}
local function msgQueueAdd ( umname, ent, udata )
local names, data = msgQueueNames[ ent ], msgQueueData[ ent ]
if not names then
names, data = {}, {}
msgQueueNames[ ent ] = names
msgQueueData[ ent ] = data
end
local i = #names + 1
names[ i ] = umname
data[ i ] = udata
end
local function msgQueueProcess ( ent )
local entid = ent:EntIndex()
local names, data = msgQueueNames[ entid ], msgQueueData[ entid ]
if names then
for i = 1 , #names do
local name = names[ i ]
if name == "scale" then
ent:SetScale( data[ i ] )
elseif name == "clip" then
ent:UpdateClip( unpack( data[ i ] ) )
end
end
msgQueueNames[ entid ] = nil
msgQueueData[ entid ] = nil
end
end
-- ------------------------ MAIN FUNCTIONS ------------------------ --
function ENT:Initialize()
self.clips = {}
self.unlit = false
self.scale = Vector(1,1,1)
self.initialised = true
msgQueueProcess(self)
end
function ENT:setupClip()
-- Setup Clipping
local l = #self.clips
if l > 0 then
render.EnableClipping( true )
for i = 1, l do
local clip = self.clips[ i ]
if clip.enabled then
local norm = clip.normal
local origin = clip.origin
if clip.islocal then
norm = self:LocalToWorld( norm ) - self:GetPos()
origin = self:LocalToWorld( origin )
end
render.PushCustomClipPlane( norm, norm:Dot( origin ) )
end
end
end
end
function ENT:finishClip()
for i = 1, #self.clips do
render.PopCustomClipPlane()
end
render.EnableClipping( false )
end
function ENT:setupRenderGroup()
local alpha = self:GetColor().a
if alpha == 0 then return end
if alpha ~= 255 then
self.RenderGroup = RENDERGROUP_BOTH
else
self.RenderGroup = RENDERGROUP_OPAQUE
end
end
function ENT:Draw()
self:setupRenderGroup()
self:setupClip()
render.SuppressEngineLighting( self.unlit )
self:DrawModel()
render.SuppressEngineLighting( false )
self:finishClip()
end
-- ------------------------ CLIPPING ------------------------ --
--- Updates a clip plane definition.
function ENT:UpdateClip(index, enabled, origin, normal, islocal)
local clip = self.clips[index]
if not clip then
clip = {}
self.clips[index] = clip
end
clip.enabled = enabled
clip.normal = normal
clip.origin = origin
clip.islocal = islocal
end
net.Receive("starfall_hologram_clip", function ()
local entid = net.ReadUInt( 32 )
local holoent = Entity( entid )
if ( not IsValid( holoent ) ) or ( not holoent.initialised ) then
-- Uninitialized
msgQueueAdd( "clip", entid, {
net.ReadUInt( 16 ),
net.ReadBit() ~= 0,
Vector( net.ReadDouble(), net.ReadDouble(), net.ReadDouble() ),
Vector( net.ReadDouble(), net.ReadDouble(), net.ReadDouble() ),
net.ReadBit() ~= 0
} )
else
holoent:UpdateClip (
net.ReadUInt( 16 ),
net.ReadBit() ~= 0,
Vector( net.ReadDouble(), net.ReadDouble(), net.ReadDouble() ),
Vector( net.ReadDouble(), net.ReadDouble(), net.ReadDouble() ),
net.ReadBit() ~= 0
)
end
end )
-- ------------------------ SCALING ------------------------ --
--- Sets the hologram scale
-- @param scale Vector scale
function ENT:SetScale ( scale )
self.scale = scale
local m = Matrix()
m:Scale( scale )
self:EnableMatrix( "RenderMultiply", m )
local propmax = self:OBBMaxs()
local propmin = self:OBBMins()
propmax.x = scale.x * propmax.x
propmax.y = scale.y * propmax.y
propmax.z = scale.z * propmax.z
propmin.x = scale.x * propmin.x
propmin.y = scale.y * propmin.y
propmin.z = scale.z * propmin.z
self:SetRenderBounds( propmax, propmin )
end
net.Receive("starfall_hologram_scale", function ()
local entid = net.ReadUInt( 32 )
local holoent = Entity( entid )
if ( not IsValid ( holoent ) ) or ( not holoent.initialised ) then
-- Uninitialized
msgQueueAdd( "scale", entid, Vector(net.ReadDouble(), net.ReadDouble(), net.ReadDouble()) )
else
holoent:SetScale( Vector( net.ReadDouble(), net.ReadDouble(), net.ReadDouble() ) )
end
end )
|
Change RenderGroup based upon hologram alpha.
|
Change RenderGroup based upon hologram alpha.
Fixes #44
|
Lua
|
bsd-3-clause
|
INPStarfall/Starfall,Xandaros/Starfall,Xandaros/Starfall,Jazzelhawk/Starfall,Jazzelhawk/Starfall,INPStarfall/Starfall,Ingenious-Gaming/Starfall,Ingenious-Gaming/Starfall
|
f767678f47ef5fb7e9f7dfdd869cd84e61142385
|
lib/etcd.lua
|
lib/etcd.lua
|
local http = require("http")
local cjson = require("cjson")
-- Client implements a new etcd Client
local Client = {}
local keyPrefix = "/v1/keys"
function Client:new(url)
local c = {}
setmetatable(c, self)
self.__index = self
c.base_url = url or "http://127.0.0.1:4001"
return c
end
function Client:_keyURL(key)
return self.base_url .. keyPrefix .. "/" .. key
end
function Client:_handleRequest(body, code)
if code ~= 200 then
local err = {errorCode = code}
return nil, err
end
value = cjson.decode(body)
if value.errorCode ~= nil then
return nil, err
end
return value
end
function Client:get(key)
local url = self:_keyURL(key)
local body, code = http.request(url)
return self:_handleRequest(body, code)
end
-- Set
function Client:set(key, value)
local url = self:_keyURL(key)
local body, code = http.request(url, "value="..value)
return self:_handleRequest(body, code)
end
return {
Client = Client
}
|
local http = require("http")
local cjson = require("cjson")
-- Client implements a new etcd Client
local Client = {}
local keyPrefix = "/v1/keys"
-- new returns a new etcd.Client object
function Client:new(url)
local c = {}
setmetatable(c, self)
self.__index = self
c.base_url = url or "http://127.0.0.1:4001"
return c
end
-- _keyURL generates the URL for an etcd key based on the base_url and prefix
function Client:_keyURL(key)
return self.base_url .. keyPrefix .. "/" .. key
end
-- _handleRequest unwraps an etcd request
function Client:_handleRequest(body, code)
if code ~= 200 then
local err = {errorCode = code}
return nil, err
end
value = cjson.decode(body)
if value.errorCode ~= nil then
return nil, err
end
return value
end
-- get grabs a key out of the etcd data store
function Client:get(key)
local url = self:_keyURL(key)
local body, code = http.request(url)
return self:_handleRequest(body, code)
end
-- set places the key and value into the etcd data store
function Client:set(key, value)
local url = self:_keyURL(key)
local body, code = http.request(url, "value="..value)
return self:_handleRequest(body, code)
end
return {
Client = Client
}
|
fix(etcd): add some doc strings
|
fix(etcd): add some doc strings
|
Lua
|
apache-2.0
|
kgrvamsi/corelb,coreos/corelb,dmitryint/corelb
|
4bc29ea5fcec3e655426026f24d418953df5f938
|
luasnake/game.lua
|
luasnake/game.lua
|
-- game.lua
local game = {} ; game.__index = game
require('graphics')
local sound = require('sounds')
local Grid = require('grid')
local Fruit = require('fruit')
local Snake = require('snake')
local directions = {["up"] = 1, ["right"] = 2, ["down"] = 3, ["left"] = 4}
local configFile = "config.txt"
function game.new()
local g = setmetatable({
rate = 0.075,
rateMin = 0.05,
rateLoss = 0.00025,
playing = false,
paused = false,
ended = false,
stats = false, -- Display stats in bottom right corner
special = false,
muted = false,
mode = 1, -- 1: Can't pass through walls or self,
-- 2: Can pass through walls but not self,
-- 3: Can pass through walls and self
modeChanged = false,
score = 0,
highScore = 0
}, game)
return g
end
function game:render()
canvas:clear()
canvas:renderTo(drawBackground)
if self.playing and not self.ended then
canvas:renderTo(drawGrid)
canvas:renderTo(drawScore)
if self.stats then
canvas:renderTo(drawStats)
end
elseif self.ended then
canvas:renderTo(drawGameOver)
else
canvas:renderTo(drawTitle)
end
if self.paused then
canvas:renderTo(drawPausebox)
end
love.graphics.draw(canvas)
end
function game:tick()
if self.playing and not self.paused and not self.ended then
snake.direction = snake.nextDirection
local x, y = snake:move()
if not grid:isFree(x, y) then
if fruit:collision(x, y) then
fruit:move()
snake:extend(5)
if self.rate > self.rateMin then
self.rate = self.rate - self.rateLoss
end
if fruit.kind == "normal" then
self:scores(10)
sound:trigger("eat")
else
self:endSpecial()
self:scores(50)
sound:trigger("eat_special")
end
if (self.score == 100) or ((self.score % 300) == 0) then
self:enterSpecial()
end
elseif self.mode ~= 3 then
self:over()
end
end
if not grid:canPlaceAt(x, y) and self.mode == 1 then
self:over()
end
grid:clear()
fruit:set(fruit.x, fruit.y)
snake.tail:update()
snake.x, snake.y = x, y
snake.head:set(x, y)
sound:trigger("move")
end
end
function game:input(key)
if self.playing and not self.paused then
if key == "escape" then
self:pause()
elseif directions[key] then
-- Test to stop snake doubling back on itself, unless GM3
if (self.mode ~= 3 and math.abs(directions[key] - snake.direction) ~= 2)
or (self.mode == 3) then
snake.nextDirection = directions[key]
end
elseif key == "1" or key == "2" or key == "3" then
self.mode = tonumber(key)
self.modeChanged = true
-- Development Modes :3
elseif key == "s" and dev then
self.stats = not self.stats
elseif key == "p" and dev then
self:enterSpecial()
-- Muting Sounds
elseif key == "m" then
self:mute()
end
else
if self.paused then
self:pause()
end
self:play()
end
if self.ended then
self:restart()
end
end
-- General Game Methods
function game:init()
self:loadConfig()
canvas = love.graphics.newCanvas()
grid = Grid.new(40, 40, 15)
snake = Snake.new()
snake:extend(4)
fruit = Fruit.new()
fruit:move()
end
function game:restart()
self.ended = false
self.paused = false
self.score = 0
self.rate = 0.075
self.special = false
-- As scores can only be obtained in GM1, reset this flag if we changed back
if self.mode == 1 then
self.modeChanged = false
end
self:init()
end
function game:play()
self.playing = true
end
function game:pause()
self.paused = not self.paused
end
function game:over()
sound:trigger("die")
self.ended = true
if self:isHighScore() then
self:saveConfig()
end
end
function game:mute()
self.muted = not self.muted
self:saveConfig()
end
-- High Score Methods
function game:scores(increase)
self.score = self.score + increase
end
function game:isHighScore()
return (self.score > self.highScore) and not self.modeChanged
end
function game:loadConfig()
if love.filesystem.exists(configFile) then
local config, _ = love.filesystem.read(configFile)
local t = {}
for k, v in string.gmatch(config, "(%w+)=(%w+)") do
t[k] = v
end
self.highScore = tonumber(t["highScore"])
self.muted = t["muted"]
end
end
function game:saveConfig()
local score = 0
if self:isHighScore() then
score = self.score
else
score = self.highScore
end
local config = "highScore=" .. tostring(score)..
",muted=" .. tostring(self.muted)
love.filesystem.write(configFile, config)
end
-- Special Fruit Mode
function game:enterSpecial()
if self.special == false then
self.tRate = self.rate
self.rate = self.rate - 0.02
self.special = true
fruit.kind = "special"
end
end
function game:endSpecial()
self.rate = self.tRate
self.special = false
fruit.kind = "normal"
end
return game
|
-- game.lua
local game = {} ; game.__index = game
require('graphics')
local sound = require('sounds')
local Grid = require('grid')
local Fruit = require('fruit')
local Snake = require('snake')
local directions = {["up"] = 1, ["right"] = 2, ["down"] = 3, ["left"] = 4}
local configFile = "config.txt"
function game.new()
local g = setmetatable({
rate = 0.075,
rateMin = 0.05,
rateLoss = 0.00025,
playing = false,
paused = false,
ended = false,
stats = false, -- Display stats in bottom right corner
special = false,
muted = false,
mode = 1, -- 1: Can't pass through walls or self,
-- 2: Can pass through walls but not self,
-- 3: Can pass through walls and self
modeChanged = false,
score = 0,
highScore = 0
}, game)
return g
end
function game:render()
canvas:clear()
canvas:renderTo(drawBackground)
if self.playing and not self.ended then
canvas:renderTo(drawGrid)
canvas:renderTo(drawScore)
if self.stats then
canvas:renderTo(drawStats)
end
elseif self.ended then
canvas:renderTo(drawGameOver)
else
canvas:renderTo(drawTitle)
end
if self.paused then
canvas:renderTo(drawPausebox)
end
love.graphics.draw(canvas)
end
function game:tick()
if self.playing and not self.paused and not self.ended then
snake.direction = snake.nextDirection
local x, y = snake:move()
if not grid:isFree(x, y) then
if fruit:collision(x, y) then
fruit:move()
snake:extend(5)
if self.rate > self.rateMin then
self.rate = self.rate - self.rateLoss
end
if fruit.kind == "normal" then
self:scores(10)
sound:trigger("eat")
else
self:endSpecial()
self:scores(50)
sound:trigger("eat_special")
end
if (self.score == 100) or ((self.score % 300) == 0) then
self:enterSpecial()
end
elseif self.mode ~= 3 then
self:over()
end
end
if not grid:canPlaceAt(x, y) and self.mode == 1 then
self:over()
end
grid:clear()
fruit:set(fruit.x, fruit.y)
snake.tail:update()
snake.x, snake.y = x, y
snake.head:set(x, y)
sound:trigger("move")
end
end
function game:input(key)
if key == "q" then
self:exit()
elseif self.ended then
self:restart()
elseif self.paused then
self:pause()
elseif self.playing then
if key == "escape" then
self:pause()
elseif directions[key] then
-- Test to stop snake doubling back on itself, unless GM3
if (self.mode ~= 3 and math.abs(directions[key] - snake.direction) ~= 2)
or (self.mode == 3) then
snake.nextDirection = directions[key]
end
elseif key == "1" or key == "2" or key == "3" then
self.mode = tonumber(key)
self.modeChanged = true
-- Development Mode :3
elseif key == "s" and dev then
self.stats = not self.stats
-- Muting Sounds
elseif key == "m" then
self:mute()
end
else
self:play()
end
end
-- General Game Methods
function game:init()
self:loadConfig()
canvas = love.graphics.newCanvas()
grid = Grid.new(40, 40, 15)
snake = Snake.new()
snake:extend(4)
fruit = Fruit.new()
fruit:move()
end
function game:restart()
self.ended = false
self.paused = false
self.score = 0
self.rate = 0.075
self.special = false
-- As scores can only be obtained in GM1, reset this flag if we changed back
if self.mode == 1 then
self.modeChanged = false
end
self:init()
end
function game:play()
self.playing = true
end
function game:pause()
self.paused = not self.paused
end
function game:over()
sound:trigger("die")
self.ended = true
if self:isHighScore() then
self:saveConfig()
end
end
function game:mute()
self.muted = not self.muted
self:saveConfig()
end
function game:exit()
love.event.quit()
end
-- High Score Methods
function game:scores(increase)
self.score = self.score + increase
end
function game:isHighScore()
return (self.score > self.highScore) and not self.modeChanged
end
function game:loadConfig()
if love.filesystem.exists(configFile) then
local config, _ = love.filesystem.read(configFile)
local t = {}
for k, v in string.gmatch(config, "--(%w+)=(%w+)") do
t[k] = v
end
self.highScore = tonumber(t["highScore"])
if t["muted"] == "true" then
self.muted = true
else
self.muted = false
end
end
end
function game:saveConfig()
local score = 0
if self:isHighScore() then
score = self.score
else
score = self.highScore
end
local config = "--highScore=" .. tostring(score) .. "--muted=" .. tostring(self.muted)
love.filesystem.write(configFile, config)
end
-- Special Fruit Mode
function game:enterSpecial()
if self.special == false then
self.tRate = self.rate
self.rate = self.rate - 0.02
self.special = true
fruit.kind = "special"
end
end
function game:endSpecial()
self.rate = self.tRate
self.special = false
fruit.kind = "normal"
end
return game
|
Can now quit by pressing q, some refactoring, fixed config bug
|
Can now quit by pressing q, some refactoring, fixed config bug
|
Lua
|
apache-2.0
|
owenjones/LuaSnake
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.