hexsha
stringlengths 40
40
| size
int64 5
129k
| content
stringlengths 5
129k
| avg_line_length
float64 4
98.3
| max_line_length
int64 5
660
| alphanum_fraction
float64 0.25
0.98
|
---|---|---|---|---|---|
acf68f2b6f974ef38b3355cf6fbba60c5fc0638b | 7,015 |
-- This is a simple interface form making queries to postgres on top of
-- ngx_postgres
--
-- Add the following upstream to your http:
--
-- upstream database {
-- postgres_server 127.0.0.1 dbname=... user=... password=...;
-- }
--
-- Add the following location to your server:
--
-- location /query {
-- postgres_pass database;
-- postgres_query $echo_request_body;
-- }
--
import concat from table
local raw_query
proxy_location = "/query"
local logger
import type, tostring, pairs, select from _G
import
FALSE
NULL
TRUE
build_helpers
format_date
is_raw
raw
from require "lapis.db.base"
backends = {
default: (_proxy=proxy_location) ->
parser = require "rds.parser"
raw_query = (str) ->
logger.query str if logger
res, m = ngx.location.capture _proxy, {
body: str
}
out, err = parser.parse res.body
error "#{err}: #{str}" unless out
if resultset = out.resultset
return resultset
out
raw: (fn) ->
with raw_query
raw_query = fn
pgmoon: ->
import after_dispatch, increment_perf from require "lapis.nginx.context"
config = require("lapis.config").get!
pg_config = assert config.postgres, "missing postgres configuration"
local pgmoon_conn
raw_query = (str) ->
pgmoon = ngx and ngx.ctx.pgmoon or pgmoon_conn
unless pgmoon
import Postgres from require "pgmoon"
pgmoon = Postgres pg_config
assert pgmoon\connect!
if ngx
ngx.ctx.pgmoon = pgmoon
after_dispatch -> pgmoon\keepalive!
else
pgmoon_conn = pgmoon
start_time = if ngx and config.measure_performance
ngx.update_time!
ngx.now!
logger.query str if logger
res, err = pgmoon\query str
if start_time
ngx.update_time!
increment_perf "db_time", ngx.now! - start_time
increment_perf "db_count", 1
if not res and err
error "#{str}\n#{err}"
res
}
set_backend = (name="default", ...) ->
assert(backends[name]) ...
init_logger = ->
if ngx or os.getenv "LAPIS_SHOW_QUERIES"
logger = require "lapis.logging"
init_db = ->
config = require("lapis.config").get!
default_backend = config.postgres and config.postgres.backend or "default"
set_backend default_backend
escape_identifier = (ident) ->
if type(ident) == "table" and ident[1] == "raw"
return ident[2]
ident = tostring ident
'"' .. (ident\gsub '"', '""') .. '"'
escape_literal = (val) ->
switch type val
when "number"
return tostring val
when "string"
return "'#{(val\gsub "'", "''")}'"
when "boolean"
return val and "TRUE" or "FALSE"
when "table"
return "NULL" if val == NULL
if val[1] == "raw" and val[2]
return val[2]
error "don't know how to escape value: #{val}"
interpolate_query, encode_values, encode_assigns, encode_clause = build_helpers escape_literal, escape_identifier
append_all = (t, ...) ->
for i=1, select "#", ...
t[#t + 1] = select i, ...
raw_query = (...) ->
init_logger!
init_db! -- sets raw query to default backend
raw_query ...
query = (str, ...) ->
if select("#", ...) > 0
str = interpolate_query str, ...
raw_query str
_select = (str, ...) ->
query "SELECT " .. str, ...
_insert = (tbl, values, ...) ->
if values._timestamp
values._timestamp = nil
time = format_date!
values.created_at or= time
values.updated_at or= time
buff = {
"INSERT INTO "
escape_identifier(tbl)
" "
}
encode_values values, buff
returning = {...}
if next returning
append_all buff, " RETURNING "
for i, r in ipairs returning
append_all buff, escape_identifier r
append_all buff, ", " if i != #returning
raw_query concat buff
add_cond = (buffer, cond, ...) ->
append_all buffer, " WHERE "
switch type cond
when "table"
encode_clause cond, buffer
when "string"
append_all buffer, interpolate_query cond, ...
_update = (table, values, cond, ...) ->
if values._timestamp
values._timestamp = nil
values.updated_at or= format_date!
buff = {
"UPDATE "
escape_identifier(table)
" SET "
}
encode_assigns values, buff
if cond
add_cond buff, cond, ...
raw_query concat buff
_delete = (table, cond, ...) ->
buff = {
"DELETE FROM "
escape_identifier(table)
}
if cond
add_cond buff, cond, ...
raw_query concat buff
-- truncate many tables
_truncate = (...) ->
tables = concat [escape_identifier t for t in *{...}], ", "
raw_query "TRUNCATE " .. tables .. " RESTART IDENTITY"
parse_clause = do
local grammar
make_grammar = ->
basic_keywords = {"where", "having", "limit", "offset"}
import P, R, C, S, Cmt, Ct, Cg, V from require "lpeg"
alpha = R("az", "AZ", "__")
alpha_num = alpha + R("09")
white = S" \t\r\n"^0
some_white = S" \t\r\n"^1
word = alpha_num^1
single_string = P"'" * (P"''" + (P(1) - P"'"))^0 * P"'"
double_string = P'"' * (P'""' + (P(1) - P'"'))^0 * P'"'
strings = single_string + double_string
-- case insensitive word
ci = (str) ->
import S from require "lpeg"
local p
for c in str\gmatch "."
char = S"#{c\lower!}#{c\upper!}"
p = if p
p * char
else
char
p * -alpha_num
balanced_parens = P {
P"(" * (V(1) + strings + (P(1) - ")"))^0 * P")"
}
order_by = ci"order" * some_white * ci"by" / "order"
group_by = ci"group" * some_white * ci"by" / "group"
keyword = order_by + group_by
for k in *basic_keywords
part = ci(k) / k
keyword += part
keyword = keyword * white
clause_content = (balanced_parens + strings + (word + P(1) - keyword))^1
outer_join_type = (ci"left" + ci"right" + ci"full") * (white * ci"outer")^-1
join_type = (ci"natural" * white)^-1 * ((ci"inner" + outer_join_type) * white)^-1
start_join = join_type * ci"join"
join_body = (balanced_parens + strings + (P(1) - start_join - keyword))^1
join_tuple = Ct C(start_join) * C(join_body)
joins = (#start_join * Ct join_tuple^1) / (joins) -> {"join", joins}
clause = Ct (keyword * C clause_content)
grammar = white * Ct joins^-1 * clause^0
(clause) ->
make_grammar! unless grammar
if out = grammar\match clause
{ unpack t for t in *out }
encode_case = (exp, t, on_else) ->
buff = {
"CASE ", exp
}
for k,v in pairs t
append_all buff, "\nWHEN ", escape_literal(k), " THEN ", escape_literal(v)
if on_else != nil
append_all buff, "\nELSE ", escape_literal on_else
append_all buff, "\nEND"
concat buff
{
:query, :raw, :is_raw, :NULL, :TRUE, :FALSE, :escape_literal,
:escape_identifier, :encode_values, :encode_assigns, :encode_clause,
:interpolate_query, :parse_clause, :format_date, :encode_case
:set_backend
select: _select
insert: _insert
update: _update
delete: _delete
truncate: _truncate
}
| 22.924837 | 113 | 0.60727 |
fa5b0cdadecc86d50818b437f127c2fa2727ca6e | 336 | shiftl = zb2rhd6DVDef1HudHiUoSefZysEkRDL8vdtRmta9KbgyoRw8n
data =>
(for 0 (get data "length") [0 0 0 0] i => seed =>
m = (mod i 4)
f = n =>
(if (eql m n)
v = (get seed (nts m))
(add
(sub (shiftl v 5) v)
(get data (nts i)))
(get seed (nts n)))
[(f 0) (f 1) (f 2) (f 3)])
| 24 | 58 | 0.467262 |
9ff689bf1a7272b97865ccd22d11ae47d3a7f7ed | 672 | howl.aux.lpeg_lexer ->
comment = capture 'comment', span(';', eol)
operator = capture 'operator', S'/.%^#,(){}[]'
dq_string = capture 'string', span('"', '"', P'\\')
number = capture 'number', digit^1 * alpha^-1
delimiter = any { space, S'/.,(){}[]^#' }
name = complement(delimiter)^1
identifier = capture 'identifier', name
keyword = capture 'constant', P':' * P':'^0 * name
fcall = capture('operator', P'(') * capture('function', complement(delimiter))^1
specials = capture 'special', word({ 'true', 'false' }) * #delimiter^1
any {
dq_string,
comment,
number,
fcall,
keyword,
specials,
identifier,
operator,
}
| 25.846154 | 82 | 0.584821 |
04964b739b09828640aae162fb934b24bc4c126b | 2,349 | -- Copyright 2014-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
gio = require 'ljglibs.gio'
glib = require 'ljglibs.glib'
ffi = require 'ffi'
core = require 'ljglibs.core'
require 'ljglibs.gobject.object'
callbacks = require 'ljglibs.callbacks'
jit = require 'jit'
import catch_error, get_error from glib
C = ffi.C
ffi_string, ffi_new = ffi.string, ffi.new
buf_t = ffi.typeof 'unsigned char[?]'
InputStream = core.define 'GInputStream < GObject', {
properties: {
has_pending: => C.g_input_stream_has_pending(@) != 0
is_closed: => C.g_input_stream_is_closed(@) != 0
}
close: => catch_error C.g_input_stream_close, @, nil
read: (count = 4096) =>
return '' if count == 0
buf = ffi_new buf_t, count
read = catch_error C.g_input_stream_read, @, buf, count, nil
return nil if read == 0
ffi_string buf, read
read_all: (count = 4096) =>
return '' if count == 0
buf = ffi_new buf_t, count
read = ffi_new 'gsize[1]'
catch_error C.g_input_stream_read_all, @, buf, count, read, nil
return nil if read[0] == 0
ffi_string buf, read[0]
read_async: (count = 4096, priority = glib.PRIORITY_DEFAULT, callback) =>
if count == 0
callback true, ''
return
buf = ffi_new buf_t, count
local handle
handler = (source, res) ->
callbacks.unregister handle
status, ret, err_code = get_error C.g_input_stream_read_finish, @, res
if not status
callback false, ret, err_code
else
read = ret
val = read != 0 and ffi_string(buf, read) or nil
callback true, val
handle = callbacks.register handler, 'input-read-async'
C.g_input_stream_read_async @, buf, count, priority, nil, gio.async_ready_callback, callbacks.cast_arg(handle.id)
close_async: (callback) =>
local handle
handler = (source, res) ->
callbacks.unregister handle
status, ret, err_code = get_error C.g_input_stream_close_finish, @, res
if not status
callback false, ret, err_code
else
callback true
handle = callbacks.register handler, 'input-close-async'
C.g_input_stream_close_async @, 0, nil, gio.async_ready_callback, callbacks.cast_arg(handle.id)
}
jit.off InputStream.read_async
jit.off InputStream.close_async
InputStream
| 28.301205 | 117 | 0.678161 |
3a01635ee90232d005e8a938b4daa197df52f42a | 1,632 | -- Test drawing
require "dorc"
testObj=
x:120
y:68
cx:120
cy:68
mode:"idle"
tic:0
transcolor:14
modes:
idle:
sprt: 256
spriteSeqLen:1
trans:14
ox:-2
oy:-1
w:2
h:2
-- mocks of TIC-80 API with assertions
FLGREG=0x14404
export peek=(addr)->
d=
[256]:1
d[addr-FLGREG]
export peek4=(addr,low)->
d=
[256]:1
id=(addr / ((low and 1 or 0) + 2))-FLGREG
d[id]
export mget=(x,y)->0
testDrawingIdleFrames=->
print "testing tic:#{testObj.tic}"
updateFrames testObj
assert testObj.sprite==256,"Sprite id should be 256, got #{testObj.sprite}"
testObj.tic+=1
print "testing tic:#{testObj.tic}"
updateFrames testObj
assert testObj.sprite==256,"Sprite id should be 256, got #{testObj.sprite}"
testObj.tic+=1
print "testing tic:#{testObj.tic}"
updateFrames testObj
assert testObj.sprite==256,"Sprite id should be 256, got #{testObj.sprite}"
testObj.tic+=1
print "testing tic:#{testObj.tic}"
updateFrames testObj
assert testObj.sprite==256,"Sprite id should be 256, got #{testObj.sprite}"
testDrawingIdleFrames!
print "Test run complete"
testWordwrap=(input,expectedlines,width)->
actual=wordwrap input,width
for i,line in ipairs expectedlines
assert actual[i]==line,"Lines don't match ['#{line}', '#{actual[i]}']"
testWordwrap(
"The brown cow said, \"Wow!\", but she was not the first to see the red balloon pop. It was the goose in the cart who ran away with the donkey's lunch.",
{
"The brown cow said,",
"\"Wow!\", but she was",
"not the first to ",
"see the red balloon",
"pop. It was the ",
"goose in the cart ",
"who ran away with ",
"the donkey's lunch.",
},
20)
| 20.923077 | 154 | 0.681373 |
5f7439ffdd8eff59502662874134fafd2164fa65 | 573 | state = require "src"
FOV = 1200
project = (fov, point) ->
scale = fov / (fov + point[#point])
point2 = {}
for coord in *point
point2[#point2 + 1] = coord * scale
if #point2 - (#point - 1) == 0
return point2, scale
export projectn = (dimension, fov, point) ->
point2, scale = project fov, point
if dimension - #point2 == 0
return point2, scale
else
projectn dimension, fov, point2
with love
.graphics.setBackgroundColor 1, 1, 1
.load = -> state\load!
.update = (dt) -> state\update dt
.draw = -> state\draw! | 19.758621 | 44 | 0.593368 |
142c89a890ffda035696d35a9b212792b87f3d52 | 266 | (get {
isChecksum: zb2rhgTfh2fo9AmE7xmkDnn3Vtm7DFQopSopYeKiDS35wWtZW
toChecksum: zb2rhnhr6fbAa5z19B1zYn5giehHmuvWGT7qGGFKxdWe5NjiU
isValid: zb2rhXEQ7G9ZseYJHosRVGFzyxf6Z2YzHkiWuY3wTkLG5EcZ5
withoutPrefix: zb2rhWtPgKPHnaZTzFV1YVoAnKyziyiu3FNbfvunH1edEzkzA
})
| 38 | 66 | 0.898496 |
2f9640c0450ed666e9818c7da5ed2932f3962f6d | 83 | path = 'game/entities/guns/'
handgun = require path .. 'handgun'
{
:handgun
} | 11.857143 | 35 | 0.626506 |
82aea26cea30e523ebc65a258a2fc600afa653f0 | 434 | class Res
@statusMessage = {
[200]: "OK"
[404]: "Not Found"
}
new: (client) =>
@client = client
@statusCode = 200
status: (code) =>
@statusCode = code
return @
send: (body="") =>
body = "HTTP/1.1 #{@statusCode} #{@@statusMessage[@statusCode]}\nContent-Type: application/json\n\n#{body}"
@client\send body
return @
notFound: (msg="") =>
@status 404
@send msg
return Res
| 17.36 | 111 | 0.5553 |
4f0d7a5231aed2b9f9e9ae60d48396e88ad05ca0 | 1,279 | require "busted"
require "tests.mock_love"
import config, extract_love_version, set_love_title from require "LunoPunk.Config"
LunoPunk = nil
setVersion = (str) ->
love.getVersion = -> string.match str, "(%d+).(%d+).?(%d+)"
LunoPunk = extract_love_version str
check_love = (str, release, major, minor, patch) ->
setVersion str
assert.are.equal release, LunoPunk.love_version.release
assert.are.equal tonumber(major), tonumber(LunoPunk.love_version.major)
assert.are.equal tonumber(minor), tonumber(LunoPunk.love_version.minor)
assert.are.equal tonumber(patch), tonumber(LunoPunk.love_version.patch)
describe "Config", ->
before_each ->
setVersion "0.8.0"
it "extract_love_version", ->
check_love "0.8.0", "0.8", 0, 8, 0
check_love "0.9.0", "0.9", 0, 9, 0
check_love "0.10.0", "0.10", 0, 10, 0
it "set_love_title", ->
versiond_check = (version) ->
setVersion version
t = set_love_title!
assert.are.equal "LunoPunk (development)", t
t = set_love_title nil, true
assert.are.equal "LunoPunk", t
t = set_love_title "FuBar"
assert.are.equal "FuBar (development)", t
t = set_love_title "FuBar", true
assert.are.equal "FuBar", t
love.graphics.setCaption = ->
versiond_check "0.8.0"
versiond_check "0.9.0"
pending "config"
| 26.645833 | 82 | 0.700547 |
58261fb4d2b852204d801952345756c8aa38a038 | 129 | spacewars.AddCommand "ooc", (player, arguments) ->
text = table.concat arguments, ""
spacewars.chat player, player\Nick!, text | 32.25 | 50 | 0.728682 |
cee5c21c91a3a5a235a7503d1f4334d98d704a05 | 4,461 | util = require'util'
simplehttp = util.simplehttp
json = util.json
urlEncode = util.urlEncode
client_name = 'ivar2 - entur_irc'
access_token = 'jwt bearer token'
--getToken = (name) ->
-- data = simplehttp{
-- method: 'POST',
-- url: 'https://partner.entur.org/oauth/token',
-- headers: 'content-type: application/json',
-- data: '{
-- "client_id": "ivar2",
-- "client_secret": "raviravi",
-- "audience":"https://api.entur.io",
-- "grant_type":"client_credentials"
-- }'
-- }
--
-- info = json.decode data
-- acess_token = info.access_token
--
formatLeg = (leg) ->
if leg == 'foot'
return '👟'
if leg == 'bus'
return '🚌'
if leg == 'water'
return '🚤'
if leg == 'metro'
return '🚇'
if leg == 'tram'
return '🚊'
if leg == 'air'
return '✈'
if leg == 'rail'
return '🚄'
if leg == 'coach'
return '🚍'
return leg
parseDate = (datestr) ->
year, month, day, hour, min, sec = datestr\match "([^-]+)%-([^-]+)%-([^T]+)T([^:]+):([^:]+):(%d%d)"
return os.time{
year: year,
month: month,
day: day,
hour: hour,
min: min,
sec: sec,
}
getStop = (name) ->
data = simplehttp{
url:"https://api.entur.io/geocoder/v1/autocomplete?text=#{urlEncode name}&lang=nn",-- nynorsk!
headers: {
['Et-Client-Name']: client_name
}
}
info = json.decode data
if info
_, feature = next info.features
return feature
getRoutes = (source, destination, arg) =>
if not arg or arg == '' or not arg\match','
patt = @ChannelCommandPattern('^%pentur (17:00,)<from>,<to>(, 17:00)', "entur", destination)\sub(1)
patt = patt\gsub('^%^%%p', '!')
@Msg('privmsg', destination, source, 'Usage: '..patt)
return
args = util.split(arg, ',')
frm_idx = 1
to_idx = 2
time_idx = 3
if args[1]\match '%d'
frm_idx = 2
to_idx = 3
time_idx = 1
frm = args[frm_idx]
to = args[to_idx]
frm = getStop(frm)
to = getStop(to)
datetime = ''
if args[time_idx]
hour, minute = args[time_idx]\match '(%d%d).*(%d%d)'
time = os.date("%Y-%m-%dT#{hour}:#{minute}:%S%z")
datetime = 'dateTime: \\"'..time..'\\" '
if time_idx == 3
datetime ..= 'arriveBy: true '
print(json.encode(frm))
print(json.encode(to))
graphql = '{
trip(
'..datetime..'
from: {
coordinates: {
latitude: '..frm.geometry.coordinates[2]..',
longitude:' ..frm.geometry.coordinates[1]..',
}
},
to: {
coordinates: {
latitude: '..to.geometry.coordinates[2]..',
longitude:' ..to.geometry.coordinates[1]..',
}
},
numTripPatterns: 3,
) {
dateTime
fromPlace {
name
}
toPlace {
name
}
tripPatterns {
startTime
endTime
duration
waitingTime
distance
walkTime
walkDistance
legs {
mode
fromPlace {
name
}
toPlace {
name
}
}
}
}
}
'
graphql = graphql\gsub '\n', ''
post_data = '{"query":"'..graphql..'","variables":null}'
print post_data
data, uri, response = simplehttp {url:'https://api.entur.io/journey-planner/v2/graphql', method:'POST', data:post_data , headers:{['Et-Client-Name']: client_name, ['Content-Type']:'application/json'}}
if response.status_code != 200
say data
else
out = {}
print data
data = json.decode(data).data
for i, trip in ipairs data.trip.tripPatterns
time = parseDate trip.startTime
datetime = os.date '*t', time
relative = (time - os.time!) / 60
a_time = parseDate trip.endTime
a_datetime = os.date '*t', a_time
legs = {}
for leg in *trip.legs
-- don't include the walking to the station, just ugly
if #legs == 0 and leg.mode == 'foot'
continue
legs[#legs+1] = formatLeg(leg.mode)
-- don't include walking from the station to the destiation, just ugly
if legs[#legs] == formatLeg('foot') and #legs > 1
legs[#legs] = nil
if #legs == 0
legs[#legs+1] = formatLeg('foot')
legs = table.concat legs, ''
out[#out+1] = "#{datetime.hour}:#{string.format('%02d', datetime.min)} (#{string.format('%d', relative)}m) [#{legs}]-> #{a_datetime.hour}:#{string.format('%02d', a_datetime.min)}"
say table.concat(out, ', ')
PRIVMSG:
'^%pstop (.*)$': (s, d, a) =>
say json.encode(getStop(a))
'^%pentur%s*(.*)$': getRoutes
| 23.603175 | 202 | 0.552567 |
18c8638818232b2b585430bce6c0d6bb641c791b | 21,389 | export script_name = "ASSWipe"
export script_description = "Performs script cleanup, removes unnecessary tags and lines."
export script_version = "0.5.0"
export script_author = "line0"
export script_namespace = "l0.ASSWipe"
DependencyControl = require "l0.DependencyControl"
version = DependencyControl{
feed: "https://raw.githubusercontent.com/TypesettingTools/line0-Aegisub-Scripts/master/DependencyControl.json",
{
{"a-mo.LineCollection", version: "1.3.0", url: "https://github.com/TypesettingTools/Aegisub-Motion",
feed: "https://raw.githubusercontent.com/TypesettingTools/Aegisub-Motion/DepCtrl/DependencyControl.json"},
{"a-mo.ConfigHandler", version: "1.1.4", url: "https://github.com/TypesettingTools/Aegisub-Motion",
feed: "https://raw.githubusercontent.com/TypesettingTools/Aegisub-Motion/DepCtrl/DependencyControl.json"},
{"l0.ASSFoundation", version: "0.5.0", url: "https://github.com/TypesettingTools/ASSFoundation",
feed: "https://raw.githubusercontent.com/TypesettingTools/ASSFoundation/master/DependencyControl.json"},
{"l0.Functional", version: "0.5.0", url: "https://github.com/TypesettingTools/Functional",
feed: "https://raw.githubusercontent.com/TypesettingTools/Functional/master/DependencyControl.json"},
{"SubInspector.Inspector", version: "0.7.2", url: "https://github.com/TypesettingTools/SubInspector",
feed: "https://raw.githubusercontent.com/TypesettingTools/SubInspector/master/DependencyControl.json"},
"json"
}
}
LineCollection, ConfigHandler, ASS, Functional, SubInspector, json = version\requireModules!
ffms, min, concat, sort = aegisub.frame_from_ms, math.min, table.concat, table.sort
{:list, :math, :string, :table, :unicode, :util, :re } = Functional
logger = version\getLogger!
reportMsg = [[
Done. Processed %d lines in %d seconds.
— Cleaned %d lines (%d%%)
— Removed %d invisible lines (%d%%)
— Combined %d consecutive identical lines (%d%%)
— Filtered %d clips and %d occurences of junk data
— Purged %d invisible contours (%d in drawings, %d in clips)
— Failed to purge %d invisible contours due to rendering inconsistencies
— Converted %d drawings/clips to floating-point
— Filtered %d records of extra data
— Total space saved: %.2f KB
]]
hints = {
cleanLevel: [[
0: no cleaning
1: remove empty tag sections
2: deduplicate tags inside sections
3: deduplicate tags globally,
4: remove tags matching the style defaults and otherwise ineffective tags]]
tagsToKeep: "Don't remove these tags even if they match the style defaults for the line."
filterClips: "Removes clips that don't affect the rendered output."
removeInvisible: "Deletes lines that don't generate any visible output."
combineLines: "Merges non-animated lines that render to an identical result and have consecutive times (without overlaps or gaps)."
removeJunk: "Removes any 'in-line comments' and things not starting with a \\ from tag sections."
scale2float: "Converts drawings and clips with a scale parameter to a floating-point representation."
tagSortOrder: "Determines the order cleaned tags will be ordered inside a tag section. Resets always go first, transforms last."
fixDrawings: "Removes extraneous ordinates from broken drawings to make them parseable. May or may not changed the rendered output."
purgeContoursDraw: "Removes all contours of a drawing that are not visible on the canvas."
purgeContoursClip: "Removes all contours of a clip that do not affect the appearance of the line."
stripComments: "Removes any comments encapsulated in {curly brackets}."
purgeContoursIgnoreHashMismatch: "Removes invisible contours even if it causes a SubInspector hash mismatch when comparing the result to the original line. This may or may not visually affect your drawing, so never use this option unsupervised!"
}
defaultSortOrder = [[
\an, \pos, \move, \org, \fscx, \fscy, \frz, \fry, \frx, \fax, \fay, \fn, \fs, \fsp, \b, \i, \u, \s, \bord, \xbord, \ybord,
\shad, \xshad, \yshad, \1c, \2c, \3c, \4c, \alpha, \1a, \2a, \3a, \4a, \blur, \be, \fad, \fade, clip_rect, iclip_rect,
clip_vect, iclip_vect, \q, \p, \k, \kf, \K, \ko, junk, unknown
]]
karaokeTags = table.concat table.pluck(table.filter(ASS.tagMap, (tag) -> tag.props.karaoke), "overrideName"), ", "
-- to be moved into ASSFoundation.Functional
sortWithKeys = (tbl, comparator) ->
-- shellsort written by Rici Lake
-- c/p from http://lua-users.org/wiki/LuaSorting, with index argument added to comparator
incs = { 1391376, 463792, 198768, 86961, 33936, 13776, 4592, 1968, 861, 336, 112, 48, 21, 7, 3, 1 }
n = #tbl
for h in *incs
for i = h+1, n
a = tbl[i]
for j = i-h, 1, -h
b = tbl[j]
break unless comparator a, b, i, j
tbl[i] = b
i = j
tbl[i] = a
return tbl
-- returns if we can merge line b into a while still maintain b's layer order
isMergeable = (a, b, linesByFrame) ->
for i = b.firstFrame, b.lastFrame
group = linesByFrame[i]
local pos
unless group.sorted
-- ensure line group is sorted by layer blending order
sortWithKeys group, (x, y, i, j) ->
pos or= i if x == b
return x.layer < y.layer or x.layer == y.layer and i < j
group.sorted = true
-- get line position in blending order
pos or= i for i, v in ipairs group when v == b
-- as b is merged into a, it gets a's layer number
-- so we can only merge if the new layer number does not change the blending order in any of the frames b is visible in
lower = group[pos-1]
return false unless (not lower or a.layer > lower.layer or a.layer == lower.layer and a.number > lower.number)
higher = group[pos+1]
return false unless (not higher or a.layer < higher.layer or a.layer == higher.layer and a.number < higher.number)
return true
mergeLines = (lines, start, cmbCnt, bytes, linesByFrame) ->
-- queue merged lines for deletion and collect statistics
if lines[start].merged
return lines[start], cmbCnt+1, bytes + #lines[start].raw + 1
-- merge applicable lines into first mergeable by extending its end time
-- then mark all merged lines
merged = lines[start]
for i=start+1,lines.n
line = lines[i]
break if line.merged or line.start_time != merged.end_time or not isMergeable merged, line, linesByFrame
lines[i].merged = true
merged.end_time = lines[i].end_time
-- update lines by frame index
for f = line.firstFrame, line.lastFrame
group = linesByFrame[f]
pos = i for i, v in ipairs group when v == line
group[pos] = merged
return nil, cmbCnt, bytes
removeInvisibleContoursOptCollectBounds = (contour, _, sectionContourIndex, sliceContourIndex, _, sliceRawContours, sliceSize, linePre, linePost, isAnimated, boundsBatch) ->
prevContours = concat sliceRawContours, " ", 1, sliceContourIndex-1
nextContours = sliceContourIndex <= sliceSize and concat(sliceRawContours, " ", sliceContourIndex+1) or ""
text = "#{linePre}#{prevContours}#{(#prevContours == 0 or #nextContours == 0) and "" or " "}#{nextContours}#{linePost}"
boundsBatch\add contour.parent.parent, text, sectionContourIndex, isAnimated
rawContour = sliceRawContours[sliceContourIndex]
removeInvisibleContoursOptPurge = (contour, contours, i, _, _, allBounds, orgBounds) ->
bounds, allBounds[i] = allBounds[i]
return false if orgBounds\equal bounds
removeInvisibleContoursOpt = (section, orgBounds) ->
cutOff, ass, contourCnt = false, section.parent, #section.contours
sliceSize = math.ceil 10e4 / contourCnt
if contourCnt > 100
logger\hint "Cleaning complex drawing with %d contours (slice size: %s)...", contourCnt, sliceSize
selectSurroundingSections = (sect, _, _, _, toTheLeft) ->
if toTheLeft
cutOff = true if section == sect
else
if section == sect
cutOff = false
return false
return not cutOff
lineStringPre, drwState = ass\getString nil, nil, selectSurroundingSections, false, true
lineStringPost = ass\getString nil, drwState, selectSurroundingSections, false, false
allBounds, sliceContours, sliceStartIndex = {}
isAnimated = ass\isAnimated!
for sliceStartIndex = 1, contourCnt, sliceSize
sliceEndIndex = min sliceStartIndex+sliceSize-1, contourCnt
sliceContours = [cnt\getTagParams! for cnt in *section.contours[sliceStartIndex, sliceEndIndex]]
boundsBatch = ASS.LineBoundsBatch!
section\callback removeInvisibleContoursOptCollectBounds, sliceStartIndex, sliceEndIndex, nil, nil,
sliceContours, sliceSize, lineStringPre, lineStringPost, isAnimated, boundsBatch
boundsBatch\run true, allBounds
lineStringPre ..= concat sliceContours, " "
boundsBatch = nil
collectgarbage!
_, purgeCnt = section\callback removeInvisibleContoursOptPurge, nil, nil, nil, nil, allBounds, orgBounds
return purgeCnt
stripComments = () -> false
process = (sub, sel, res) ->
ASS.config.fixDrawings = res.fixDrawings
lines = LineCollection sub, sel
linesToDelete, delCnt, linesToCombine, cmbCnt, lineCnt, debugError = {}, 0, {}, 0, #lines.lines, false
tagNames = res.filterClips and util.copy(ASS.tagNames.clips) or {}
tagNames[#tagNames+1] = res.removeJunk and "junk"
stats = { bytes: 0, junk: 0, clips: 0, start: os.time!, cleaned: 0,
scale2float: 0, contoursDraw: 0, contoursDrawSkipped: 0, contoursClip: 0, extra: 0 }
linesByFrame = {}
-- create proper tag name lists from user input which may be override tag names or mixed
res.tagsToKeep = ASS\getTagNames string.split res.tagsToKeep, ",%s", nil, false
res.tagSortOrder = ASS\getTagNames string.split res.tagSortOrder, ",%s", nil, false
res.mergeConsecutiveExcept = ASS\getTagNames string.split res.mergeConsecutiveExcept, ",%s", nil, false
res.extraDataFilter = string.split res.extraDataFilter, ",%s", nil, false
callback = (lines, line, i) ->
aegisub.cancel! if aegisub.progress.is_cancelled!
aegisub.progress.task "Cleaning %d of %d lines..."\format i, lineCnt if i%10==0
aegisub.progress.set 100*i/lineCnt
unless line.styleRef
logger\warn "WARNING: Line #%d is using undefined style '%s', skipping...\n— %s", i, line.style, line.text
return
-- filter extra data
if line.extra and res.extraDataMode != "Keep all"
removed, r = switch res.extraDataMode
when "Remove all"
removed = line.extra
line.extra = nil
removed, table.length removed
when "Remove all except"
table.removeKeysExcept line.extra, res.extraDataFilter
when "Keep all except"
table.removeKeys line.extra, res.extraDataFilter
stats.extra += r
success, data = pcall ASS\parse, line
unless success
logger\warn "Couldn't parse line #%d: %s", i, data
return
-- it is essential to run SubInspector on a ASSFoundation-built line (rather than the original)
-- because ASSFoundation rounds tag values to a sane precision, which is not visible but
-- will produce a hash mismatch compared to the original line. However we must avoid that to
-- not trigger the ASSWipe bug detection
orgText, oldBounds = line.text, data\getLineBounds false, true
orgTextParsed = oldBounds.rawText
orgTagTypes = ["#{tag.__tag.name}(#{table.concat({tag\getTagParams!}, ",")})" for tag in *data\getTags!]
removeInvisibleContours = (contour) ->
contour.disabled = true
if oldBounds\equal data\getLineBounds!
if contour.parent.class == ASS.Section.Drawing
stats.contoursDraw += 1
else stats.contoursClip += 1
return false
contour.disabled = false
-- remove invisible lines
if res.removeInvisible and oldBounds.w == 0
stats.bytes += #line.raw + 1
delCnt += 1
linesToDelete[delCnt], line.ASS = line
return
purgedContourCount = 0
if res.purgeContoursDraw or res.scale2float
cb = (section) ->
-- remove invisible contours from drawings
if res.purgeContoursDraw
purgedContourCount = removeInvisibleContoursOpt section, oldBounds
-- un-scale drawings
if res.scale2float and section.scale > 1
section.scale\set 1
stats.scale2float += 1
data\callback cb, ASS.Section.Drawing
if purgedContourCount > 0
if res.purgeContoursDraw and not res.purgeContoursIgnoreHashMismatch and not data\getLineBounds!\equal oldBounds
line.text = orgText
data = ASS\parse line
stats.contoursDrawSkipped += purgedContourCount
else
stats.contoursDraw += purgedContourCount
oldBounds = data\getLineBounds! if res.purgeContoursIgnoreHashMismatch
-- pogressively build a table of visible lines by frame
-- which is required to check mergeability of consecutive identical lines
if res.combineLines
line.firstFrame = ffms line.start_time
line.lastFrame = -1 + ffms line.end_time
for i = line.firstFrame, line.lastFrame
lbf = linesByFrame[i]
if lbf
lbf[lbf.n+1] = line
lbf.n += 1
else linesByFrame[i] = {line, n: 1}
-- collect lines to combine
unless oldBounds.animated
ltc = linesToCombine[oldBounds.firstHash]
if ltc
ltc[ltc.n+1] = line
ltc.n += 1
else linesToCombine[oldBounds.firstHash] = {line, n: 1}
mergeConsecutiveTagSections = if not res.mergeConsecutive
false
elseif #res.mergeConsecutiveExcept == 0
true
else
exceptions = list.makeSet res.mergeConsecutiveExcept
(sourceSection, targetSection) ->
predicate = (tag) -> exceptions[tag.__tag.name]
not table.find(sourceSection.tags, predicate) and not table.find targetSection.tags, predicate
-- clean tags
data\cleanTags res.cleanLevel, mergeConsecutiveTagSections, res.tagsToKeep, res.tagSortOrder
newBounds = data\getLineBounds!
if res.stripComments
data\stripComments!
--data\callback stripComments, ASS.Section.Comment
if res.filterClips or res.removeJunk
data\modTags tagNames, (tag) ->
-- remove junk
if tag.class == ASS.Tag.Unknown
stats.junk += 1
return false
if tag.class == ASS.Tag.ClipVect
-- un-scale clips
if res.scale2float and tag.scale>1
tag.scale\set 1
stats.scale2float += 1
-- purge ineffective contours from clips
if res.purgeContoursClip
tag\callback removeInvisibleContours
-- filter clips
tag.disabled = true
if data\getLineBounds!\equal newBounds
stats.clips += 1
return false
tag.disabled = false
data\commit nil, res.cleanLevel == 0
-- reclaim some memory
line.ASS, line.undoText = nil
if orgText != line.text
if not newBounds\equal oldBounds
debugError = true
logger\warn "Cleaning affected output on line #%d, rolling back...", line.humanizedNumber
logger\warn "—— Before: %s\n—— Parsed: %s\n—— After: %s\n—— Style: %s\n—— Tags: %s", orgText, orgTextParsed, line.text, line.styleRef.name, table.concat orgTagTypes, "; "
logger\warn "—— Hash Before: %s (%s); Hash After: %s (%s)\n",
oldBounds.firstHash, oldBounds.animated and "animated" or "static",
newBounds.firstHash, newBounds.animated and "animated" or "static"
line.text = orgText
elseif #line.text < #orgText
stats.cleaned += 1
stats.bytes += #orgText - #line.text
aegisub.cancel! if aegisub.progress.is_cancelled!
lines\runCallback callback, true
-- sort lines which are to be combined by time
sortFunc = (a, b) ->
return true if a.start_time < b.start_time
return false if a.start_time > b.start_time
return true if a.layer < b.layer
return false if a.layer > b.layer
return true if a.number < b.number
return false
linesToCombineSorted, l = {}, 1
for _, group in pairs linesToCombine
continue if group.n < 2
sort group, sortFunc
linesToCombineSorted[l] = group
l += 1
sort linesToCombineSorted, (a, b) -> sortFunc a[1], b[1]
-- combine lines
for group in *linesToCombineSorted
for j=1, group.n
linesToDelete[delCnt+cmbCnt+1], cmbCnt, stats.bytes = mergeLines group, j, cmbCnt, stats.bytes, linesByFrame
lines\replaceLines!
lines\deleteLines linesToDelete
logger\warn json.encode {Styles: lines.styles, Configuration: res} if debugError
logger\warn reportMsg, lineCnt, os.time!-stats.start, stats.cleaned, 100*stats.cleaned/lineCnt,
delCnt, 100*delCnt/lineCnt, cmbCnt, 100*cmbCnt/lineCnt, stats.clips, stats.junk,
stats.contoursClip+stats.contoursDraw, stats.contoursDraw, stats.contoursClip, stats.contoursDrawSkipped,
stats.scale2float, stats.extra, stats.bytes/1000
if debugError
logger\warn [[However, ASSWipe possibly encountered bugs while cleaning.
Affected lines have been rolled back to their previous state, so your script is most likely fine.
Please copy the whole log window contents and send them to line0.]]
return lines\getSelection!
showDialog = (sub, sel, res) ->
dlg = {
main: {
removeInvisible: class: "checkbox", x: 0, y: 0, width: 2, height: 1, value: true, config: true, label: "Remove invisible lines", hint: hints.removeInvisible
combineLines: class: "checkbox", x: 0, y: 1, width: 2, height: 1, value: true, config: true, label: "Combine consecutive identical lines", hint: hints.combineLines
mergeConsecutive: class: "checkbox", x: 2, y: 0, width: 12, height: 1, value: true, config: true, label: "Merge consecutive tag sections unless it contains any of:", hint: hints.mergeConsecutive
mergeConsecutiveExcept: class: "textbox", x: 2, y: 1, width: 12, height: 2, value: karaokeTags, config: true, hint: hints.mergeConsecutiveExcept
cleanLevelLabel: class: "label", x: 0, y: 4, width: 1, height: 1, label: "Tag cleanup level: "
cleanLevel: class: "intedit", x: 1, y: 4, width: 1, height: 1, min: 0, max: 4, value: 4, config: true, hint: hints.cleanLevel
tagsToKeepLabel: class: "label", x: 4, y: 4, width: 1, height: 1, label: "Keep default tags: "
tagsToKeep: class: "textbox", x: 4, y: 5, width: 10, height: 2, value: "\\pos", config:true, hint: hints.tagsToKeep
tagSortOrderLabel: class: "label", x: 4, y: 7, width: 1, height: 1, label: "Tag sort order: "
stripComments: class: "checkbox", x: 0, y: 5, width: 2, height: 1, value: true, config: true, label: "Strip comments", hint: hints.stripComments
removeJunk: class: "checkbox", x: 0, y: 6, width: 2, height: 1, value: true, config: true, label: "Remove junk from tag sections", hint: hints.removeJunk
tagSortOrder: class: "textbox", x: 4, y: 8, width: 10, height: 3, value: defaultSortOrder, config: true, hint: hints.tagSortOrder
filterClips: class: "checkbox", x: 0, y: 11, width: 2, height: 1, value: true, config: true, label: "Filter clips", hint: hints.filterClips
scale2float: class: "checkbox", x: 0, y: 12, width: 2, height: 1, value: true, config: true, label: "Un-scale drawings and clips", hint: hints.scale2float
fixDrawings: class: "checkbox", x: 0, y: 13, width: 2, height: 1, value: false, config: true, label: "Try to fix broken drawings", hint: hints.fixDrawings
purgeContoursLabel: class: "label", x: 0, y: 14, width: 2, height: 1, label: "Purge invisible contours: "
purgeContoursDraw: class: "checkbox", x: 4, y: 14, width: 3, height: 1, value: false, config: true, label: "from drawings", hint: hints.purgeContoursDraw
purgeContoursClip: class: "checkbox", x: 7, y: 14, width: 6, height: 1, value: false, config: true, label: "from clips", hint: hints.purgeContoursClip
purgeContoursIgnoreHashMismatch: class: "checkbox", x: 4, y: 15, width: 9, height: 1, value: false, config: true, label: "ignore rendering inconsistencies", hint: hints.purgeContoursIgnoreHashMismatch
extraDataLabel: class: "label", x: 0, y: 17, width: 1, height: 1, label: "Filter extra data: "
extraDataMode: class: "dropdown", x: 1, y: 17, width: 1, height: 1, value: "Keep All", config: true, items: {"Keep all", "Remove all", "Keep all except", "Remove all except"}, hint: hints.extraData
extraDataFilter: class: "textbox", x: 4, y: 17, width: 10, height: 3, value: "", config: true, hint: hints.extraData
quirksModeLabel: class: "label", x: 0, y: 21, width: 2, height: 1, label: "Quirks mode: "
quirksMode: class: "dropdown", x: 4, y: 21, width: 2, height: 1, value: "VSFilter", config: true, items: [k for k, v in pairs ASS.Quirks], hint: hints.quirksMode
}
}
options = ConfigHandler dlg, version.configFile, false, script_version, version.configDir
options\read!
options\updateInterface "main"
btn, res = aegisub.dialog.display dlg.main
if btn
options\updateConfiguration res, "main"
options\write!
ASS.config.quirks = ASS.Quirks[res.quirksMode]
process sub, sel, res
version\registerMacro showDialog, ->
if aegisub.project_properties!.video_file == ""
return false, "A video must be loaded to run #{script_name}."
else return true, script_description
| 47.850112 | 247 | 0.68755 |
64fad5a2e8666b50e37eb30aa7f88737cc8900d9 | 4,200 | make = (x, y) ->
player = {
:x, :y
w: 20 -- width
h: 20 -- height
dx: 0 -- delta x, velocity x
dy: 0 -- delta y, velocity y
frcx: 7 -- friction x
frcy: 3 -- friction y
acc: 15 -- acceleration
jump: 11 -- jump force
jumped: false -- did the player jump
grounded: false -- is the player on the ground
gravity: 45 -- modified gravity ..
gravity_og: 45 -- constantly lerping towards original gravity
wall_x: 0 -- -1: touching left wall, 0: not touching, 1: touching right wall
wall_fx: .7 -- horizontal wall jump force, multiplied with the jump force
wall_fy: .735 -- vertical jump force
dir_x: 1 -- horizontal direction, for sprite drawing
dy_lerp_zero: false
jump_hold: false
jump_hold_time: 2
original_jump_hold_time: 2
running: false
can_run: false
run_acc: 3
a: 0
}
player.update = (dt) =>
if @running
@a += dt * 75
else
@a += dt * 20
@gravity = math.lerp @gravity, @gravity_og, dt * 3
if @wall_x ~= 0
@gravity = @gravity_og
@grounded = false
@wall_x = 0
if @dy_lerp_zero
@dy = math.lerp @dy, 0, dt * 20
@dy_lerp_zero = false if @dy < 0.01
if @jump_hold
@jump_hold_time -= dt
if @jump_hold_time <= 0
@jump_hold = false
@jump_hold_time = @original_jump_hold_time
@x, @y, @collisions = game.world\move @, @x + @dx, @y + @dy
for c in *@collisions
c.other\trigger @ if c.other.trigger
if c.other.key == "die"
love.load!
continue
if c.normal.y ~= 0
if c.normal.y == -1
@grounded = true
@can_run = true
if c.other.key == "jump"
@dy = -@dy * 3
continue
@dy = 0
if c.normal.x ~= 0
unless @grounded and @wall_x ~= 0
@gravity /= 1.25
@dx -= c.normal.x * .5 * dt
@dx = 0
@wall_x = c.normal.x
@trigger_flag = false
if @jumped
@gravity -= 1.5 * dt
-- apply gravity
@dy += @gravity * dt
with love.keyboard
if .isDown "d"
if @running
@dx += @acc * @run_acc * dt
else
@dx += @acc * dt
if .isDown "a"
if @running
@dx -= @acc * @run_acc * dt
else
@dx -= @acc * dt
if .isDown "lshift"
@running = true if @can_run
if @grounded
@dx = math.lerp @dx, 0, @frcx * dt
else
@dx = math.lerp @dx, 0, @frcy * dt
if @jump_hold
@dy = math.lerp @dy, 0, @frcy / (100 * @jump_hold_time) * dt
else
@dy = math.lerp @dy, 0, @frcy * dt
@jumped = @dy < 0
@camera_follow dt * 4
a = math.sign @dx
@dir_x = -a if a ~= 0
player.draw = =>
sprite = game.sprites.player
width = sprite\getWidth!
height = sprite\getHeight!
rot = 0
if @dx^2 > 0.5 and @grounded
rot = -@dir_x * 0.075 * math.sin @a
with love.graphics
.setColor 1, 1, 1
.draw sprite, @x + width / 2, @y + height / 2, rot, @dir_x, 1, width / 2, height / 2
player.press = (key) =>
if key == "space"
if @grounded
@dy = -@jump
@jumped = true
@jump_hold = true
if @wall_x ~= 0
@jump_hold_time = 100
else if @wall_x ~= 0
if @running
@dy = -@jump * @wall_fy
@dx = @jump * @wall_fx * @wall_x * 2
else
@dy = -@jump * @wall_fy
@dx = @jump * @wall_fx * @wall_x
@jumped = true
@wall_x = 0
player.camera_follow = (t) =>
with game.camera
.x = math.lerp .x, (@x + @dx * 20) * .sx, t
.y = math.lerp .y, (@y + @dy * 2) * .sy, t
.r = math.lerp .r, 0, t * .75
player.release = (key) =>
if @jumped
if key == "space"
@dy_lerp_zero = true
@jump_hold = false
if @running
if key == "lshift"
@running = false
if key == "r"
love.load!
player
{
:make
} | 19.811321 | 90 | 0.481667 |
cac2645d7a1a447cff9f77ad0b33f3d65f5ac8b6 | 310 | import create_table, add_column, create_index, types from require("lapis.db.schema")
{
[1]: =>
create_table "listens", {
{"id", types.text primary_key: true}
{"created_at", types.time}
{"updated_at", types.time}
{"count", types.integer}
}
}
| 25.833333 | 84 | 0.548387 |
85dfa124e29a8600cb7e2ba0225543e04bd6bb5c | 505 |
import parse_query_string from require "lapis.util"
assert_shape = (obj, shape) ->
assert shape obj
extract_params = (str) ->
params = assert parse_query_string str
{k,v for k,v in pairs params when type(k) == "string"}
make_http = (handle) ->
http_requests = {}
fn = =>
@http_provider = "test"
{
request: (req) ->
table.insert http_requests, req
handle req if handle
1, 200, {}
}
fn, http_requests
{:extract_params, :make_http, :assert_shape}
| 19.423077 | 56 | 0.629703 |
eb9bf7895cf3ec41aebfe43c1c719bbbd3a8d7f8 | 1,703 | -- Convert a Lua table to a string representation of the Tcl dictionary
M = {}
T = require("PackageToolkit").module
head = (T.import ..., "../_lists/_head").head
tail = (T.import ..., "../_lists/_tail").tail
trim = (T.import ..., "../_strings/_trim").trim
append = (T.import ..., "../_lists/_append").append
get_keys = (T.import ..., "_keys").keys
add_brackets = (T.import ..., "_tcl_add_brackets").add_brackets
M.tcl = (t, pretty=false, expand=false, indent=" ") ->
quote = (obj) ->
if type(obj) =="string" and string.match obj, "%s" -- check whether whitespace is found
if expand == true
return string.format "[ join [ list %s ] ]", obj
else
return string.format "{%s}", (trim obj, "%s")
else
return tostring obj
format_item = (k, v) ->
if type(k) == "number"
return string.format "%s", v
else
return string.format "%s %s", (quote k), v
aux = (dict, keys, accum, prefix) ->
if #keys == 0
if pretty == true
sep = string.format "\n%s%s", prefix, indent
return add_brackets (table.concat accum, sep), prefix, indent, true, expand
else
return add_brackets (table.concat accum, " "), "", "", false, expand
else
k = head keys
v = ""
if type(dict[k]) == "table"
v = aux dict[k], (get_keys dict[k]), {}, indent
else
v = quote dict[k]
new_item = format_item k, v
return aux dict, (tail keys), (append accum, new_item), prefix
return aux t, (get_keys t), {}, ""
return M | 38.704545 | 95 | 0.52202 |
adf1310afd54e9813df24686b85767134505d475 | 471 | bitser = require('benchmarks.bitser')
bitser.loads(bitser.dumps({}))
{
description: 'bitser'
serialize:
largeNumArray: bitser.dumps
largeU32Array: bitser.dumps
smallNumArray: bitser.dumps
smallU8Array: bitser.dumps
simpleTable: bitser.dumps
deepTable: bitser.dumps
deserialize:
largeNumArray: bitser.loads
largeU32Array: bitser.loads
smallNumArray: bitser.loads
smallU8Array: bitser.loads
simpleTable: bitser.loads
deepTable: bitser.loads
}
| 20.478261 | 37 | 0.768577 |
4f5ae426268aa902b29072904236917281029533 | 907 |
utils = require("utils")
bz_handle = require("bz_handle")
core = require("core")
net = require("net").net
rx = require("rx")
Module = require("module")
import Observable from rx
import applyMeta, getMeta, proxyCall, protectedCall, namespace, instanceof, isIn, assignObject, getFullName, Store from utils
import Handle from bz_handle
class CommandManager extends Module
new: (parent) =>
super(parent)
@commands = {}
start: (...) =>
update: (...) =>
command: (command, a = "") =>
ret = {pcall(() ->
args = {}
for arg in a:gmatch("%w+")
table.insert(args, arg)
if @commands[command]
return
)}
table.remove(ret,1)
return unpack(ret)
namespace("component",ComponentManager, UnitComponent)
commandManager = core\useModule(CommandManager)
return {
:CommandManager,
:commandManager
}
| 19.297872 | 126 | 0.618523 |
277e4adfb676d9e8562ad03a746fb9e37dc2c05a | 2,624 | -- Copyright 2014-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
glib = require 'ljglibs.glib'
{:File} = require 'ljglibs.gio'
with_tmpfile = (contents, f) ->
p = os.tmpname!
fh = io.open p, 'wb'
fh\write contents
fh\close!
status, err = pcall f, p
os.remove p
error err unless status
with_stream_for = (contents, f) ->
with_tmpfile contents, (p) ->
f File(p)\read!
describe 'InputStream', ->
setup -> set_howl_loop!
describe 'read(count)', ->
it 'reads up to <count> bytes or to EOF', ->
with_stream_for "foobar", (stream) ->
-- for files all will be read
assert.same 'foo', stream\read 3
assert.same 'bar', stream\read 10
it 'returns nil upon EOF', ->
with_stream_for "foobar", (stream) ->
stream\read_all 10
assert.is_nil stream\read!
describe 'read_all(count)', ->
it 'reads <count> bytes or to EOF', ->
with_stream_for "foobar", (stream) ->
assert.same 'foo', stream\read_all 3
assert.same 'bar', stream\read_all 10
it 'returns nil upon EOF', ->
with_stream_for "foobar", (stream) ->
stream\read_all 10
assert.is_nil stream\read_all!
describe 'read_async(count, priority, handler)', ->
it 'invokes the handler with the status and up to <count> bytes read', (done) ->
with_stream_for "foobar", (stream) ->
stream\read_async 3, glib.PRIORITY_LOW, async (status, buf) ->
assert.is_true status
assert.same 'foo', buf
done!
it 'reads up to EOF', (done) ->
with_stream_for "foobar", (stream) ->
stream\read_async 10, glib.PRIORITY_LOW, async (status, buf) ->
assert.is_true status
assert.same 'foobar', buf
done!
it 'passes <true, nil> when at EOF', (done) ->
with_stream_for "foobar", (stream) ->
stream\read_all!
stream\read_async 10, glib.PRIORITY_LOW, async (status, buf) ->
assert.is_true status
assert.is_nil buf
done!
describe 'close_async(handler)', ->
it 'invokes the handler with the status and any eventual error message', (done) ->
with_stream_for "foobar", (stream) ->
stream\close_async async (status, err) ->
assert.is_true status
assert.is_nil err
done!
describe '.is_closed', ->
it 'is true when the stream is closed and false otherwise', ->
with_stream_for "foobar", (stream) ->
assert.is_false stream.is_closed
stream\close!
assert.is_true stream.is_closed
| 31.614458 | 86 | 0.61814 |
7b1820b165cf670c6cd3f6c349856cbdfd0786d8 | 431 | bytesLength = zb2rhbRAVvyLUE9tCysrnWvP7guviTgXQWzcK41KocGrhnvnH
bytesSlice = zb2rhg1FpG1nrxVEGvjp1gfU2tCP9sRmXXL77HjL2qnCfjUmv
listToArray = zb2rhj3APjEyBffYfDUhef71pdkvq8N5HkixVN1hmCacPXJth
n => bytes =>
l = (bytesLength bytes)
empty = val => end => end
list = (for 0 (div l n) empty i => list =>
chunk = (bytesSlice bytes (mul i n) (mul (add i 1) n))
val => end => (list val (val chunk end)))
(listToArray list)
| 35.916667 | 63 | 0.723898 |
8ca0d428a902b4f8136c7f8d770a844761638f8e | 592 | export class Heart extends Pickup
new: =>
super!
@value = 1
@hasBeenCollected = false
with @graphic = Image("#{Settings.folders.graphics}/heart.png")
.origin.x = 5
.origin.y = 4
update: (dt) =>
super(dt)
if (@hasBeenCollected)
return
collect: (actor) =>
if (@hasBeenCollected)
return
super(actor)
if (actor.__class.__name == "Player")
actor\takeHeal(@value)
@removeSelf!
@hasBeenCollected = true
| 23.68 | 72 | 0.483108 |
460651e063d6b66ca4e547249dcaf3f48ca77ba3 | 194 | M = {}
me = ...
FX = require "FunctionalX"
T = (require "PackageToolkit").module
M.main = (...) ->
m = {
T.import me, "n2"
}
return unpack (FX.module.call m, ...)
return M | 17.636364 | 41 | 0.515464 |
c3616116bf7a3068ca3f75b1dbbb3f5d46f5efa0 | 1,908 |
import unindent, with_dev from require "spec.helpers"
describe "moonscript.errors", ->
local moonscript, errors, util, to_lua
-- with_dev ->
moonscript = require "moonscript.base"
errors = require "moonscript.errors"
util = require "moonscript.util"
{:to_lua} = moonscript
get_rewritten_line_no = (fname) ->
fname = "spec/error_inputs/#{fname}.moon"
chunk = moonscript.loadfile fname
success, err = pcall chunk
error "`#{fname}` is supposed to have runtime error!" if success
source = tonumber err\match "^.-:(%d+):"
line_table = assert require("moonscript.line_tables")["@#{fname}"], "missing line table"
errors.reverse_line_number fname, line_table, source, {}
describe "error rewriting", ->
tests = {
"first": 24
"second": 16
"third": 11
}
for name, expected_no in pairs tests
it "should rewrite line number", ->
assert.same get_rewritten_line_no(name), expected_no
describe "line map", ->
it "should create line table", ->
moon_code = unindent [[
print "hello world"
if something
print "cats"
]]
lua_code, posmap = assert to_lua moon_code
-- print util.debug_posmap(posmap, moon_code, lua_code)
assert.same { 1, 23, 36, 21 }, posmap
it "should create line table for multiline string", ->
moon_code = unindent [[
print "one"
x = [==[
one
two
thre
yes
no
]==]
print "two"
]]
lua_code, posmap = assert to_lua moon_code
-- print util.debug_posmap(posmap, moon_code, lua_code)
assert.same {[1]: 1, [2]: 13, [7]: 13, [8]: 57}, posmap
describe "error reporting", ->
it "should compile bad code twice", ->
code, err = to_lua "{b=5}"
assert.truthy err
code, err2 = to_lua "{b=5}"
assert.same err, err2
| 26.5 | 92 | 0.599057 |
9d71029b28c326c3ae5ea73f606c6d7d533c1a91 | 301 | Caste = require('vendor/caste/lib/caste')
class Transition extends Caste
new: (@fromScene, @toScene, data = {}) =>
@player = data.player or @fromScene.player
@fromWarp = data.fromWarp
@toWarp = data.toWarp
@toPosition = data.toPosition
@offset = data.offset
@direction = data.direction
| 25.083333 | 44 | 0.704319 |
97be64bcf44982a6e43aea3f0bb8d7dcc654a085 | 7,795 |
util = require "lapis.util"
json = require "cjson"
unpack = unpack or table.unpack
tests = {
{
-> util.parse_query_string "field1=value1&field2=value2&field3=value3"
{
{"field1", "value1"}
{"field2", "value2"}
{"field3", "value3"}
field1: "value1"
field2: "value2"
field3: "value3"
}
}
{
-> util.parse_query_string "blahblah"
{
{ "blahblah"}
blahblah: true
}
}
{
-> util.parse_query_string "hello=wo%22rld&thing"
{
{ "hello", 'wo"rld' }
{ "thing" }
hello: 'wo"rld'
thing: true
}
}
{
-> util.parse_query_string "hello=&thing=123&world="
{
{"hello", ""}
{"thing", "123"}
{"world", ""}
hello: ""
thing: "123"
world: ""
}
}
{
-> util.parse_query_string "null"
{
{"null"}
null: true
}
}
{
-> util.underscore "ManifestRocks"
"manifest_rocks"
}
{
-> util.underscore "ABTestPlatform"
"abtest_platform"
}
{
-> util.underscore "HELLO_WORLD"
"" -- TODO: fix
}
{
-> util.underscore "whats_up"
"whats__up" -- TODO: fix
}
{
-> util.camelize "hello"
"Hello"
}
{
-> util.camelize "world_wide_i_web"
"WorldWideIWeb"
}
{
-> util.camelize util.underscore "ManifestRocks"
"ManifestRocks"
}
{
->
util.encode_query_string {
{"dad", "day"}
"hello[hole]": "wor=ld"
}
"dad=day&hello%5bhole%5d=wor%3dld"
}
{
->
util.encode_query_string {
{"cold", "zone"}
"hello": true
"world": false
}
"cold=zone&hello"
}
{
->
util.encode_query_string {
"world": false
}
""
}
{
->
util.encode_query_string {
"null": true
}
"null"
}
{ -- stripping invalid types
->
json.decode util.to_json {
color: "blue"
data: {
height: 10
fn: =>
}
}
{
color: "blue", data: { height: 10}
}
}
{ -- encoding null values
->
util.to_json {
nothing: json.null
}
'{"nothing":null}'
}
{
->
util.build_url {
path: "/test"
scheme: "http"
host: "localhost.com"
port: "8080"
fragment: "cool_thing"
query: "dad=days"
}
"http://localhost.com:8080/test?dad=days#cool_thing"
}
{
->
util.build_url {
host: "dad.com"
path: "/test"
fragment: "cool_thing"
}
"//dad.com/test#cool_thing"
}
{
->
util.build_url {
scheme: ""
host: "leafo.net"
}
"//leafo.net"
}
{
-> util.time_ago os.time! - 34234349
{
{"years", 1}
{"days", 31}
{"hours", 5}
{"minutes", 32}
{"seconds", 29}
years: 1
days: 31
hours: 5
minutes: 32
seconds: 29
}
}
{
-> util.time_ago os.time! + 34234349
{
{"years", 1}
{"days", 31}
{"hours", 5}
{"minutes", 32}
{"seconds", 29}
years: 1
days: 31
hours: 5
minutes: 32
seconds: 29
}
}
{
-> util.time_ago_in_words os.time! - 34234349
"1 year ago"
}
{
-> util.time_ago_in_words os.time! - 34234349, 2
"1 year, 31 days ago"
}
{
-> util.time_ago_in_words os.time! - 34234349, 10
"1 year, 31 days, 5 hours, 32 minutes, 29 seconds ago"
}
{
-> util.time_ago_in_words os.time!
"0 seconds ago"
}
{
-> util.parse_cookie_string "__utma=54729783.634507326.1355638425.1366820216.1367111186.43; __utmc=54729783; __utmz=54729783.1364225235.36.12.utmcsr=t.co|utmccn=(referral)|utmcmd=referral|utmcct=/Q95kO2iEje; __utma=163024063.1111023767.1355638932.1367297108.1367341173.42; __utmb=163024063.1.10.1367341173; __utmc=163024063; __utmz=163024063.1366693549.37.11.utmcsr=t.co|utmccn=(referral)|utmcmd=referral|utmcct=/UYMGwvGJNo"
{
__utma: '163024063.1111023767.1355638932.1367297108.1367341173.42'
__utmz: '163024063.1366693549.37.11.utmcsr=t.co|utmccn=(referral)|utmcmd=referral|utmcct=/UYMGwvGJNo'
__utmb: '163024063.1.10.1367341173'
__utmc: '163024063'
}
}
{
-> util.slugify "What is going on right now?"
"what-is-going-on-right-now"
}
{
-> util.slugify "whhaa $%#$ hooo"
"whhaa-hooo"
}
{
-> util.slugify "what-about-now"
"what-about-now"
}
{
-> util.slugify "hello - me"
"hello-me"
}
{
-> util.slugify "cow _ dogs"
"cow-dogs"
}
{
-> util.uniquify { "hello", "hello", "world", "another", "world" }
{ "hello", "world", "another" }
}
{
-> util.trim "what the heck"
"what the heck"
}
{
-> util.trim "
blah blah "
"blah blah"
}
{
-> util.trim " hello#{" "\rep 20000}world "
"hello#{" "\rep 20000}world"
}
{
-> util.trim_filter {
" ", " thing ",
yes: " "
okay: " no "
}
{ -- TODO: fix indexing?
nil, "thing", okay: "no"
}
}
{
-> util.trim_filter {
hello: " hi"
world: " hi"
yeah: " "
}, {"hello", "yeah"}, 0
{ hello: "hi", yeah: 0 }
}
{
->
util.key_filter {
hello: "world"
foo: "bar"
}, "hello", "yeah"
{ hello: "world" }
}
{
-> "^%()[12332]+$"\match(util.escape_pattern "^%()[12332]+$") and true
true
}
{
-> util.title_case "hello"
"Hello"
}
{
-> util.title_case "hello world"
"Hello World"
}
{
-> util.title_case "hello-world"
"Hello-world"
}
{
-> util.title_case "What my 200 Dollar thing You love to eat"
"What My 200 Dollar Thing You Love To Eat"
}
}
describe "lapis.util", ->
for group in *tests
it "should match", ->
input = group[1]!
if #group > 2
assert.one_of input, { unpack group, 2 }
else
assert.same input, group[2]
it "should autoload", ->
package.loaded["things.hello_world"] = "yeah"
package.loaded["things.cool_thing"] = "cool"
mod = util.autoload "things"
assert.equal "yeah", mod.HelloWorld
assert.equal "cool", mod.cool_thing
assert.equal nil, mod.not_here
assert.equal nil, mod.not_here
assert.equal "cool", mod.cool_thing
it "should autoload with starting table", ->
package.loaded["things.hello_world"] = "yeah"
package.loaded["things.cool_thing"] = "cool"
mod = util.autoload "things", { dad: "world" }
assert.equal "yeah", mod.HelloWorld
assert.equal "cool", mod.cool_thing
assert.equal "world", mod.dad
it "should autoload with multiple prefixes", ->
package.loaded["things.hello_world"] = "yeah"
package.loaded["things.cool_thing"] = "cool"
package.loaded["wings.cool_thing"] = "very cool"
package.loaded["wings.hats"] = "off to you"
mod = util.autoload "wings", "things"
assert.equal "off to you", mod.hats
assert.equal "very cool", mod.CoolThing
assert.equal "yeah", mod.hello_world
assert.equal "yeah", mod.HelloWorld
it "should singularize words", ->
words = {
{"banks", "bank"}
{"chemists", "chemist"}
{"hospitals", "hospital"}
{"letters", "letter"}
{"vallys", "vally"}
{"keys", "key"}
{"industries", "industry"}
{"ladies", "lady"}
{"heroes", "hero"}
{"torpedoes", "torpedo"}
{"purchases", "purchase"}
{"addresses", "address"}
{"responses", "response"}
-- these will never work
-- {"halves", "half"}
-- {"leaves", "leaf"}
-- {"wives", "wife"}
}
for {plural, single} in *words
assert.same single, util.singularize plural
| 17.837529 | 430 | 0.525593 |
b3d540fa16ec0bf309e78d6fb185a366fcb8e853 | 1,506 | export modinfo = {
type: "function"
id: "Chat"
func: (Msg) ->
chatPart = (LocalPlayer.Character and LocalPlayer.Character\FindFirstChild"Head") or (Probe)
if chatPart
Part = CreateInstance"Part"{
_Init: (obj) ->
Spawn -> obj\BreakJoints!
Parent: workspace
CanColide: false
Transparency: 1
CFrame: chatPart.CFrame * CFrame.new 0,3,0
CreateInstance"BodyPosition"{
_Init: (obj) ->
Spawn ->
part = obj.Parent
for i = 3, 100
obj.position = chatPart.Position
wait!
maxForce: Vector3.new 1/0,1/0,1/0
position: chatPart.Position
}
CreateInstance"BillboardGui"{
_Init: (obj) ->
Spawn ->
obj.Adornee = obj.Parent
Spawn ->
for i = 3, 100
obj.StudsOffset = Vector3.new 0,i/10,0
wait!
Parent: chatPart
Size: UDim2.new 1, 0, 1, 0
StudsOffset: Vector3.new 0,3,0
CreateInstance"Frame"{
Size: UDim2.new 1, 0, 1, 0
BackgroundTransparency: 1
CreateInstance"TextLabel"{
_Init: (obj) ->
Spawn ->
for i = 3, 100
obj.TextTransparency = i / 100
wait!
Text: Msg
Size: UDim2.new 1,0,1,0
FontSize: "Size36"
Font: "ArialBold"
TextStrokeTransparency: 0
BackgroundTransparency: 1
TextColor3: Color3.new 2/3,2/3,2/3
BackgroundColor3: Color3.new 0,0,0
}
}
}
}
if ConfigSystem "Get", "ChatToTablets"
Output Msg, {Colors.White}
} | 25.525424 | 94 | 0.579017 |
5109a5b44aac7941bc068d257d4ee6ec66721c26 | 847 | Dorothy!
AttributeItemView = require "View.Control.Unit.AttributeItem"
Class AttributeItemView,
__init:(args)=>
@valueFormat = args.valueFormat
@_selected = false
@slot "Tapped",-> @selected = not @selected
value:property => @label.text,
(value)=>
if value ~= nil
format = @valueFormat
switch tolua.type value
when "boolean"
@label.text = tostring value
when "oVec2"
@label.text = string.format format..", "..format,value.x,value.y
when "CCSize"
@label.text = string.format format..", "..format,value.width,value.height
else
@label.text = string.format format,value
@label.texture.antiAlias = false
else
@label.text = ""
selected:property => @_selected,
(value)=>
@_selected = value
@frame.visible = value
@emit "Selected",@
| 26.46875 | 80 | 0.62928 |
cd3cc4669d201009436e0b0f7ffa90e97d31ed26 | 220 | PRIVMSG:
'^%pexcuse': (source, destination) =>
ivar2.util.simplehttp 'http://www.programmerexcuses.com/', (html) ->
cruft, match = html\match[[<center(.*)>(.-)</a></center>]]
if match
say match
| 31.428571 | 72 | 0.581818 |
36a437d984bd5f5b29a3b84f64ae404bcc7399b3 | 559 | GS = require 'hump.gamestate'
Tetrominoes = require 'Tetrominoes'
Menu = require 'menu'
class Intro
init: =>
@menu = Menu({
{tag: "Play", action: -> GS.push Tetrominoes}
{tag: "Quit", action: -> love.event.quit!}
})
@font = love.graphics.newFont(16)
resume: =>
@menu.curr_option = 1
@menu.key_dt = 0
update: (dt) =>
@menu\update dt
draw: =>
love.graphics.setFont @font
love.graphics.setColor 1, 1, 1, 1
love.graphics.print 'Tetrominoes' .. (debug and ' (DEBUG)' or ''), 10, 10
@menu\draw 10, 30
| 22.36 | 77 | 0.593918 |
87b55a2f3f1eaa706569c17919950ebdf93e7355 | 8,796 |
import concat, insert from table
_G = _G
import type, pairs, ipairs, tostring, getfenv, setfenv, getmetatable,
setmetatable, table from _G
import locked_fn, release_fn from require "lapis.util.functions"
CONTENT_FOR_PREFIX = "_content_for_"
escape_patt = do
punct = "[%^$()%.%[%]*+%-?]"
(str) ->
(str\gsub punct, (p) -> "%"..p)
html_escape_entities = {
['&']: '&'
['<']: '<'
['>']: '>'
['"']: '"'
["'"]: '''
}
html_unescape_entities = {}
for key,value in pairs html_escape_entities
html_unescape_entities[value] = key
html_escape_pattern = "[" .. concat([escape_patt char for char in pairs html_escape_entities]) .. "]"
escape = (text) ->
(text\gsub html_escape_pattern, html_escape_entities)
unescape = (text) ->
(text\gsub "(&[^&]-;)", (enc) ->
decoded = html_unescape_entities[enc]
decoded if decoded else enc)
strip_tags = (html) ->
html\gsub "<[^>]+>", ""
void_tags = {
"area"
"base"
"br"
"col"
"command"
"embed"
"hr"
"img"
"input"
"keygen"
"link"
"meta"
"param"
"source"
"track"
"wbr"
}
for tag in *void_tags
void_tags[tag] = true
------------------
classnames = (t) ->
if type(t) == "string"
return t
ccs = for k,v in pairs t
if type(k) == "number"
continue if v == ""
v
else
continue unless v
k
table.concat ccs, " "
element_attributes = (buffer, t) ->
return unless type(t) == "table"
for k,v in pairs t
if type(k) == "string" and not k\match "^__"
vtype = type(v)
if vtype == "boolean"
if v
buffer\write " ", k
else
if vtype == "table" and k == "class"
v = classnames v
continue if v == ""
else
v = tostring v
buffer\write " ", k, "=", '"', escape(v), '"'
nil
element = (buffer, name, attrs, ...) ->
with buffer
\write "<", name
element_attributes(buffer, attrs)
if void_tags[name]
-- check if it has content
has_content = false
for thing in *{attrs, ...}
t = type thing
switch t
when "string"
has_content = true
break
when "table"
if thing[1]
has_content = true
break
unless has_content
\write "/>"
return buffer
\write ">"
\write_escaped attrs, ...
\write "</", name, ">"
class Buffer
builders: {
html_5: (...) ->
raw '<!DOCTYPE HTML>'
if type((...)) == "table"
html ...
else
html lang: "en", ...
}
new: (@buffer) =>
@old_env = {}
@i = #@buffer
@make_scope!
with_temp: (fn) =>
old_i, old_buffer = @i, @buffer
@i = 0
@buffer = {}
fn!
with @buffer
@i, @buffer = old_i, old_buffer
make_scope: =>
@scope = setmetatable { [Buffer]: true }, {
__index: (scope, name) ->
handler = switch name
when "widget"
@\render_widget
when "render"
@\render
when "capture"
(fn) -> table.concat @with_temp fn
when "element"
(...) -> element @, ...
when "text"
@\write_escaped
when "raw"
@\write
unless handler
default = @old_env[name]
return default unless default == nil
unless handler
builder = @builders[name]
unless builder == nil
handler = (...) -> @call builder, ...
unless handler
handler = (...) -> element @, name, ...
scope[name] = handler
handler
}
render: (mod_name, ...) =>
widget = require mod_name
@render_widget widget ...
render_widget: (w) =>
-- instantiate widget if it's a class
if w.__init and w.__base
w = w!
if current = @widget
w\_inherit_helpers current
w\render @
call: (fn, ...) =>
env = getfenv fn
if env == @scope
return fn!
before = @old_env
@old_env = env
clone = locked_fn fn
setfenv clone, @scope
out = {clone ...}
release_fn clone
@old_env = before
unpack out
write_escaped: (thing, next_thing, ...) =>
switch type thing
when "string"
@write escape thing
when "table"
for chunk in *thing
@write_escaped chunk
else
@write thing
if next_thing -- keep the tail call
@write_escaped next_thing, ...
write: (thing, next_thing, ...) =>
switch type thing
when "string"
@i += 1
@buffer[@i] = thing
when "number"
@write tostring thing
when "nil"
nil -- ignore
when "table"
for chunk in *thing
@write chunk
when "function"
@call thing
else
error "don't know how to handle: " .. type(thing)
if next_thing -- keep tail call
@write next_thing, ...
html_writer = (fn) ->
(buffer) -> Buffer(buffer)\write fn
render_html = (fn) ->
buffer = {}
html_writer(fn) buffer
concat buffer
helper_key = setmetatable {}, __tostring: -> "::helper_key::"
-- ensures that all methods are called in the buffer's scope
class Widget
@__inherited: (cls) =>
cls.__base.__call = (...) => @render ...
@include: (other_cls) =>
import mixin_class from require "lapis.util"
other_cls = require other_cls if type(other_cls) == "string"
mixin_class @, other_cls
new: (opts) =>
-- copy in options
if opts
for k,v in pairs opts
if type(k) == "string"
@[k] = v
_set_helper_chain: (chain) => rawset @, helper_key, chain
_get_helper_chain: => rawget @, helper_key
_find_helper: (name) =>
if chain = @_get_helper_chain!
for h in *chain
helper_val = h[name]
if helper_val != nil
-- call functions in scope of helper
value = if type(helper_val) == "function"
(w, ...) -> helper_val h, ...
else
helper_val
return value
_inherit_helpers: (other) =>
@_parent = other
-- add helpers from parents
if other_helpers = other\_get_helper_chain!
for helper in *other_helpers
@include_helper helper
-- insert table onto end of helper_chain
include_helper: (helper) =>
if helper_chain = @[helper_key]
insert helper_chain, helper
else
@_set_helper_chain { helper }
nil
content_for: (name, val) =>
full_name = CONTENT_FOR_PREFIX .. name
return @_buffer\write @[full_name] unless val
if helper = @_get_helper_chain![1]
layout_opts = helper.layout_opts
val = if type(val) == "string"
escape val
else
getfenv(val).capture val
existing = layout_opts[full_name]
switch type existing
when "nil"
layout_opts[full_name] = val
when "table"
table.insert layout_opts[full_name], val
else
layout_opts[full_name] = {existing, val}
has_content_for: (name) =>
full_name = CONTENT_FOR_PREFIX .. name
not not @[full_name]
content: => -- implement me
render_to_string: (...) =>
buffer = {}
@render buffer, ...
concat buffer
render_to_file: (file, ...) =>
opened_file = false
file = if type(file) == "string"
opened_file = true
assert io.open file, "w"
buffer = setmetatable {}, {
__newindex: (key, val) =>
file\write val
true
}
@render buffer, ...
if opened_file
file\close!
true
render: (buffer, ...) =>
@_buffer = if buffer.__class == Buffer
buffer
else
Buffer buffer
old_widget = @_buffer.widget
@_buffer.widget = @
meta = getmetatable @
index = meta.__index
index_is_fn = type(index) == "function"
seen_helpers = {}
scope = setmetatable {}, {
__tostring: meta.__tostring
__index: (scope, key) ->
value = if index_is_fn
index scope, key
else
index[key]
-- run method in buffer scope
if type(value) == "function"
wrapped = if Widget.__base[key] and key != "content"
value
else
(...) -> @_buffer\call value, ...
scope[key] = wrapped
return wrapped
-- look for helper
if value == nil and not seen_helpers[key]
helper_value = @_find_helper key
seen_helpers[key] = true
if helper_value != nil
scope[key] = helper_value
return helper_value
value
}
setmetatable @, __index: scope
@content ...
setmetatable @, meta
@_buffer.widget = old_widget
nil
{ :Widget, :Buffer, :html_writer, :render_html, :escape, :unescape, :classnames, :element, :CONTENT_FOR_PREFIX }
| 21.611794 | 112 | 0.548317 |
1a89f9bbe2f4e558a8cb4e075411d87075e64766 | 20,524 | socket = require "pgmoon.socket"
import insert from table
import rshift, lshift, band, bxor from require "pgmoon.bit"
unpack = table.unpack or unpack
-- Protocol documentation:
-- https://www.postgresql.org/docs/current/protocol-message-formats.html
VERSION = "1.13.0"
_len = (thing, t=type(thing)) ->
switch t
when "string"
#thing
when "table"
l = 0
for inner in *thing
inner_t = type inner
if inner_t == "string"
l += #inner
else
l += _len inner, inner_t
l
else
error "don't know how to calculate length of #{t}"
_debug_msg = (str) ->
require("moon").dump [p for p in str\gmatch "[^%z]+"]
flipped = (t) ->
keys = [k for k in pairs t]
for key in *keys
t[t[key]] = key
t
MSG_TYPE = flipped {
status: "S"
auth: "R"
backend_key: "K"
ready_for_query: "Z"
query: "Q"
notice: "N"
notification: "A"
password: "p"
row_description: "T"
data_row: "D"
command_complete: "C"
error: "E"
}
ERROR_TYPES = flipped {
severity: "S"
code: "C"
message: "M"
position: "P"
detail: "D"
schema: "s"
table: "t"
constraint: "n"
}
PG_TYPES = {
[16]: "boolean"
[17]: "bytea"
[20]: "number" -- int8
[21]: "number" -- int2
[23]: "number" -- int4
[700]: "number" -- float4
[701]: "number" -- float8
[1700]: "number" -- numeric
[114]: "json" -- json
[3802]: "json" -- jsonb
-- arrays
[1000]: "array_boolean" -- bool array
[1005]: "array_number" -- int2 array
[1007]: "array_number" -- int4 array
[1016]: "array_number" -- int8 array
[1021]: "array_number" -- float4 array
[1022]: "array_number" -- float8 array
[1231]: "array_number" -- numeric array
[1009]: "array_string" -- text array
[1015]: "array_string" -- varchar array
[1002]: "array_string" -- char array
[1014]: "array_string" -- bpchar array
[2951]: "array_string" -- uuid array
[199]: "array_json" -- json array
[3807]: "array_json" -- jsonb array
}
NULL = "\0"
tobool = (str) ->
str == "t"
class Postgres
convert_null: false
NULL: {"NULL"}
:PG_TYPES
default_config: {
application_name: "pgmoon"
user: "postgres"
host: "127.0.0.1"
port: "5432"
ssl: false
}
-- custom types supplementing PG_TYPES
type_deserializers: {
json: (val, name) =>
import decode_json from require "pgmoon.json"
decode_json val
bytea: (val, name) =>
@decode_bytea val
array_boolean: (val, name) =>
import decode_array from require "pgmoon.arrays"
decode_array val, tobool
array_number: (val, name) =>
import decode_array from require "pgmoon.arrays"
decode_array val, tonumber
array_string: (val, name) =>
import decode_array from require "pgmoon.arrays"
decode_array val
array_json: (val, name) =>
import decode_array from require "pgmoon.arrays"
import decode_json from require "pgmoon.json"
decode_array val, decode_json
hstore: (val, name) =>
import decode_hstore from require "pgmoon.hstore"
decode_hstore val
}
set_type_oid: (oid, name) =>
unless rawget(@, "PG_TYPES")
@PG_TYPES = {k,v for k,v in pairs @PG_TYPES}
@PG_TYPES[assert tonumber oid] = name
setup_hstore: =>
res = unpack @query "SELECT oid FROM pg_type WHERE typname = 'hstore'"
assert res, "hstore oid not found"
@set_type_oid tonumber(res.oid), "hstore"
-- config={}
-- host: server hostname
-- port: server port
-- user: the username to authenticate with
-- password: the username to authenticate with
-- database: database to connect to
-- application_name: name assigned to connection to server
-- socket_type: type of socket to use (nginx, luasocket, cqueues)
-- ssl: enable ssl connections
-- ssl_verify: verify the certificate
-- cqueues_openssl_context: manually created openssl.ssl.context for cqueues sockets
-- luasec_opts: manually created options for LuaSocket ssl connections
new: (@_config={}) =>
@config = setmetatable {}, {
__index: (t, key) ->
value = @_config[key]
if value == nil
@default_config[key]
else
value
}
@sock, @sock_type = socket.new @config.socket_type
connect: =>
unless @sock
@sock = socket.new @sock_type
connect_opts = switch @sock_type
when "nginx"
{
pool: @config.pool_name or "#{@config.host}:#{@config.port}:#{@config.database}:#{@config.user}"
pool_size: @config.pool_size
backlog: @config.backlog
}
ok, err = @sock\connect @config.host, @config.port, connect_opts
return nil, err unless ok
if @sock\getreusedtimes! == 0
if @config.ssl
success, err = @send_ssl_message!
return nil, err unless success
success, err = @send_startup_message!
return nil, err unless success
success, err = @auth!
return nil, err unless success
success, err = @wait_until_ready!
return nil, err unless success
true
settimeout: (...) =>
@sock\settimeout ...
disconnect: =>
sock = @sock
@sock = nil
sock\close!
keepalive: (...) =>
sock = @sock
@sock = nil
sock\setkeepalive ...
-- see: http://25thandclement.com/~william/projects/luaossl.pdf
create_cqueues_openssl_context: =>
return unless @config.ssl_verify != nil or @config.cert or @config.key or @config.ssl_version
ssl_context = require("openssl.ssl.context")
out = ssl_context.new @config.ssl_version
if @config.ssl_verify == true
out\setVerify ssl_context.VERIFY_PEER
if @config.ssl_verify == false
out\setVerify ssl_context.VERIFY_NONE
if @config.cert
out\setCertificate @config.cert
if @config.key
out\setPrivateKey @config.key
out
create_luasec_opts: =>
{
key: @config.key
certificate: @config.cert
cafile: @config.cafile
protocol: @config.ssl_version
verify: @config.ssl_verify and "peer" or "none"
}
auth: =>
t, msg = @receive_message!
return nil, msg unless t
unless MSG_TYPE.auth == t
@disconnect!
if MSG_TYPE.error == t
return nil, @parse_error msg
error "unexpected message during auth: #{t}"
auth_type = @decode_int msg, 4
switch auth_type
when 0 -- trust
true
when 3 -- cleartext password
@cleartext_auth msg
when 5 -- md5 password
@md5_auth msg
when 10 -- AuthenticationSASL
@scram_sha_256_auth msg
else
error "don't know how to auth: #{auth_type}"
cleartext_auth: (msg) =>
assert @config.password, "missing password, required for connect"
@send_message MSG_TYPE.password, {
@config.password
NULL
}
@check_auth!
-- https://www.postgresql.org/docs/current/sasl-authentication.html#SASL-SCRAM-SHA-256
scram_sha_256_auth: (msg) =>
assert @config.password, "missing password, required for connect"
import random_bytes, x509_digest from require "pgmoon.crypto"
-- '18' is the number set by postgres on the server side
rand_bytes = assert random_bytes 18
import encode_base64 from require "pgmoon.util"
c_nonce = encode_base64 rand_bytes
nonce = "r=" .. c_nonce
saslname = ""
username = "n=" .. saslname
client_first_message_bare = username .. "," .. nonce
plus = false
bare = false
if msg\match "SCRAM%-SHA%-256%-PLUS"
plus = true
elseif msg\match "SCRAM%-SHA%-256"
bare = true
else
error "unsupported SCRAM mechanism name: " .. tostring(msg)
local gs2_cbind_flag
local gs2_header
local cbind_input
local mechanism_name
if bare
gs2_cbind_flag = "n"
gs2_header = gs2_cbind_flag .. ",,"
cbind_input = gs2_header
mechanism_name = "SCRAM-SHA-256" .. NULL
elseif plus
cb_name = "tls-server-end-point"
gs2_cbind_flag = "p=" .. cb_name
gs2_header = gs2_cbind_flag .. ",,"
mechanism_name = "SCRAM-SHA-256-PLUS" .. NULL
cbind_data = do
if @sock_type == "cqueues"
openssl_x509 = @sock\getpeercertificate!
openssl_x509\digest "sha256", "s"
else
pem, signature = if @sock_type == "nginx"
ssl = require("resty.openssl.ssl").from_socket(@sock)
server_cert = ssl\get_peer_certificate()
server_cert\to_PEM!, server_cert\get_signature_name!
else
server_cert = @sock\getpeercertificate()
server_cert\pem!, server_cert\getsignaturename!
signature = signature\lower!
-- upgrade the signature if necessary
if signature\match("^md5") or signature\match("^sha1")
signature = "sha256"
assert x509_digest(pem, signature)
cbind_input = gs2_header .. cbind_data
client_first_message = gs2_header .. client_first_message_bare
@send_message MSG_TYPE.password, {
mechanism_name
@encode_int #client_first_message
client_first_message
}
t, msg = @receive_message()
unless t
return nil, msg
server_first_message = msg\sub 5
int32 = @decode_int msg, 4
if int32 == nil or int32 != 11
return nil, "server_first_message error: " .. msg
channel_binding = "c=" .. encode_base64 cbind_input
nonce = server_first_message\match "([^,]+)"
unless nonce
return nil, "malformed server message (nonce)"
client_final_message_without_proof = channel_binding .. "," .. nonce
xor = (a, b) ->
result = for i=1,#a
x = a\byte i
y = b\byte i
unless x and y
return nil
string.char bxor x, y
table.concat result
salt = server_first_message\match ",s=([^,]+)"
unless salt
return nil, "malformed server message (salt)"
i = server_first_message\match ",i=(.+)"
unless i
return nil, "malformed server message (iteraton count)"
if tonumber(i) < 4096
return nil, "the iteration-count sent by the server is less than 4096"
import kdf_derive_sha256, hmac_sha256, digest_sha256 from require "pgmoon.crypto"
salted_password, err = kdf_derive_sha256 @config.password, salt, tonumber i
unless salted_password
return nil, err
client_key, err = hmac_sha256 salted_password, "Client Key"
unless client_key
return nil, err
stored_key, err = digest_sha256 client_key
unless stored_key
return nil, err
auth_message = "#{client_first_message_bare },#{server_first_message },#{client_final_message_without_proof}"
client_signature, err = hmac_sha256 stored_key, auth_message
unless client_signature
return nil, err
proof = xor client_key, client_signature
unless proof
return nil, "failed to generate the client proof"
client_final_message = "#{client_final_message_without_proof },p=#{encode_base64 proof}"
@send_message MSG_TYPE.password, {
client_final_message
}
t, msg = @receive_message()
unless t
return nil, msg
server_key, err = hmac_sha256 salted_password, "Server Key"
unless server_key
return nil, err
server_signature, err = hmac_sha256 server_key, auth_message
unless server_signature
return nil, err
server_signature = encode_base64 server_signature
sent_server_signature = msg\match "v=([^,]+)"
if server_signature != sent_server_signature then
return nil, "authentication exchange unsuccessful"
@check_auth!
md5_auth: (msg) =>
import md5 from require "pgmoon.crypto"
salt = msg\sub 5, 8
assert @config.password, "missing password, required for connect"
@send_message MSG_TYPE.password, {
"md5"
md5 md5(@config.password .. @config.user) .. salt
NULL
}
@check_auth!
check_auth: =>
t, msg = @receive_message!
return nil, msg unless t
switch t
when MSG_TYPE.error
nil, @parse_error msg
when MSG_TYPE.auth
true
else
error "unknown response from auth"
query: (q) =>
if q\find NULL
return nil, "invalid null byte in query"
@post q
local row_desc, data_rows, command_complete, err_msg
local result, notifications
num_queries = 0
while true
t, msg = @receive_message!
return nil, msg unless t
switch t
when MSG_TYPE.data_row
data_rows or= {}
insert data_rows, msg
when MSG_TYPE.row_description
row_desc = msg
when MSG_TYPE.error
err_msg = msg
when MSG_TYPE.command_complete
command_complete = msg
next_result = @format_query_result row_desc, data_rows, command_complete
num_queries += 1
if num_queries == 1
result = next_result
elseif num_queries == 2
result = { result, next_result }
else
insert result, next_result
row_desc, data_rows, command_complete = nil
when MSG_TYPE.ready_for_query
break
when MSG_TYPE.notification
notifications = {} unless notifications
insert notifications, @parse_notification(msg)
-- when MSG_TYPE.notice
-- TODO: do something with notices
if err_msg
return nil, @parse_error(err_msg), result, num_queries, notifications
result, num_queries, notifications
post: (q) =>
@send_message MSG_TYPE.query, {q, NULL}
wait_for_notification: =>
while true
t, msg = @receive_message!
return nil, msg unless t
switch t
when MSG_TYPE.notification
return @parse_notification(msg)
format_query_result: (row_desc, data_rows, command_complete) =>
local command, affected_rows
if command_complete
command = command_complete\match "^%w+"
affected_rows = tonumber command_complete\match "(%d+)%z$"
if row_desc
return {} unless data_rows
fields = @parse_row_desc row_desc
num_rows = #data_rows
for i=1,num_rows
data_rows[i] = @parse_data_row data_rows[i], fields
if affected_rows and command != "SELECT"
data_rows.affected_rows = affected_rows
return data_rows
if affected_rows
{ :affected_rows }
else
true
parse_error: (err_msg) =>
local severity, message, detail, position
error_data = {}
offset = 1
while offset <= #err_msg
t = err_msg\sub offset, offset
str = err_msg\match "[^%z]+", offset + 1
break unless str
offset += 2 + #str
if field = ERROR_TYPES[t]
error_data[field] = str
switch t
when ERROR_TYPES.severity
severity = str
when ERROR_TYPES.message
message = str
when ERROR_TYPES.position
position = str
when ERROR_TYPES.detail
detail = str
msg = "#{severity}: #{message}"
if position
msg = "#{msg} (#{position})"
if detail
msg = "#{msg}\n#{detail}"
msg, error_data
parse_row_desc: (row_desc) =>
num_fields = @decode_int row_desc\sub(1,2)
offset = 3
fields = for i=1,num_fields
name = row_desc\match "[^%z]+", offset
offset += #name + 1
-- 4: object id of table
-- 2: attribute number of column (4)
-- 4: object id of data type (6)
data_type = @decode_int row_desc\sub offset + 6, offset + 6 + 3
data_type = @PG_TYPES[data_type] or "string"
-- 2: data type size (10)
-- 4: type modifier (12)
-- 2: format code (16)
-- we only know how to handle text
format = @decode_int row_desc\sub offset + 16, offset + 16 + 1
assert 0 == format, "don't know how to handle format"
offset += 18
{name, data_type}
fields
parse_data_row: (data_row, fields) =>
-- 2: number of values
num_fields = @decode_int data_row\sub(1,2)
out = {}
offset = 3
for i=1,num_fields
field = fields[i]
continue unless field
{field_name, field_type} = field
-- 4: length of value
len = @decode_int data_row\sub offset, offset + 3
offset += 4
if len < 0
out[field_name] = @NULL if @convert_null
continue
value = data_row\sub offset, offset + len - 1
offset += len
switch field_type
when "number"
value = tonumber value
when "boolean"
value = value == "t"
when "string"
nil
else
if fn = @type_deserializers[field_type]
value = fn @, value, field_type
out[field_name] = value
out
parse_notification: (msg) =>
pid = @decode_int msg\sub 1, 4
offset = 4
channel, payload = msg\match "^([^%z]+)%z([^%z]*)%z$", offset + 1
unless channel
error "parse_notification: failed to parse notification"
{
operation: "notification"
pid: pid
channel: channel
payload: payload
}
wait_until_ready: =>
while true
t, msg = @receive_message!
return nil, msg unless t
if MSG_TYPE.error == t
@disconnect!
return nil, @parse_error(msg)
break if MSG_TYPE.ready_for_query == t
true
receive_message: =>
t, err = @sock\receive 1
unless t
@disconnect!
return nil, "receive_message: failed to get type: #{err}"
len, err = @sock\receive 4
unless len
@disconnect!
return nil, "receive_message: failed to get len: #{err}"
len = @decode_int len
len -= 4
msg = @sock\receive len
t, msg
send_startup_message: =>
assert @config.user, "missing user for connect"
assert @config.database, "missing database for connect"
data = {
@encode_int 196608
"user", NULL
@config.user, NULL
"database", NULL
@config.database, NULL
"application_name", NULL
@config.application_name, NULL
NULL
}
@sock\send {
@encode_int _len(data) + 4
data
}
send_ssl_message: =>
success, err = @sock\send {
@encode_int 8,
@encode_int 80877103
}
return nil, err unless success
t, err = @sock\receive 1
return nil, err unless t
if t == MSG_TYPE.status
switch @sock_type
when "nginx"
@sock\sslhandshake false, nil, @config.ssl_verify
when "luasocket"
@sock\sslhandshake @config.luasec_opts or @create_luasec_opts!
when "cqueues"
@sock\starttls @config.cqueues_openssl_context or @create_cqueues_openssl_context!
else
error "don't know how to do ssl handshake for socket type: #{@sock_type}"
elseif t == MSG_TYPE.error or @config.ssl_required
@disconnect!
nil, "the server does not support SSL connections"
else
true -- no SSL support, but not required by client
send_message: (t, data, len) =>
len = _len data if len == nil
len += 4 -- includes the length of the length integer
@sock\send {
t
@encode_int len
data
}
decode_int: (str, bytes=#str) =>
switch bytes
when 4
d, c, b, a = str\byte 1, 4
a + lshift(b, 8) + lshift(c, 16) + lshift(d, 24)
when 2
b, a = str\byte 1, 2
a + lshift(b, 8)
else
error "don't know how to decode #{bytes} byte(s)"
-- create big endian binary string of number
encode_int: (n, bytes=4) =>
switch bytes
when 4
a = band n, 0xff
b = band rshift(n, 8), 0xff
c = band rshift(n, 16), 0xff
d = band rshift(n, 24), 0xff
string.char d, c, b, a
else
error "don't know how to encode #{bytes} byte(s)"
decode_bytea: (str) =>
if str\sub(1, 2) == '\\x'
str\sub(3)\gsub '..', (hex) ->
string.char tonumber hex, 16
else
str\gsub '\\(%d%d%d)', (oct) ->
string.char tonumber oct, 8
encode_bytea: (str) =>
string.format "E'\\\\x%s'", str\gsub '.', (byte) ->
string.format '%02x', string.byte byte
escape_identifier: (ident) =>
'"' .. (tostring(ident)\gsub '"', '""') .. '"'
escape_literal: (val) =>
switch type val
when "number"
return tostring val
when "string"
return "'#{(val\gsub "'", "''")}'"
when "boolean"
return val and "TRUE" or "FALSE"
error "don't know how to escape value: #{val}"
__tostring: =>
"<Postgres socket: #{@sock}>"
{ :Postgres, new: Postgres, :VERSION }
| 24.520908 | 113 | 0.613769 |
9f899115d043299e9eb8df49fee70d4bacb85a2b | 398 | import NewExpr,NewExprVal,ExprIndex,ExprToString,AddItem from require "Data.API.Expression"
for item in *{
{
Name:"String"
Text:"String"
Type:"String"
MultiLine:false
TypeIgnore:false
Group:"String"
Desc:"Raw string."
CodeOnly:true
ToCode:=> "\"#{ @[2]\gsub('\"','\\\"') }\""
Create:NewExprVal ""
Args:false
__index:ExprIndex
__tostring:ExprToString
}
}
AddItem item
| 18.952381 | 91 | 0.673367 |
5d8935ecb9e769a70355511a2abb6398b64b6c84 | 1,723 | actions = { }
actionPrefix = "resultAction"
newAction = (element, board) ->
->
element\triggerCallbacks element.resultValue, board
bindNewAction = (board) =>
for i = 1, #actions + 1
if actions[i] == nil
actions[i] = true
_G[actionPrefix .. i] = newAction @, board
return i
unbindAction = (i) ->
return unless i
_G[actionPrefix .. i] = nil
actions[i] = nil
export class Element extends CallbackHandler
x: 0
y: 0
width: 400
height: 400
text: ""
fontSize: 8
enabled: true
new: (options) =>
super!
@actions = { }
if (type options) == "table"
if options.callback != nil
@addCallback options.callback, options.callbackOwner
@x = options.x
@y = options.y
@width = options.width
@height = options.height
@text = options.text
@fontSize = options.fontSize
@enabled = options.enabled
@board = options.board
@resultValue = (options.resultValue == nil) and @ or options.resultValue
else
@resultValue = @
draw: (board, overrides) =>
return if not @enabled
board = board or @board
@erase board
action = bindNewAction @, board
@actions[board] = action
overrides = overrides or { }
overrides.callback = actionPrefix .. action
board\addElement @, overrides
erase: (board) =>
board = board or @board
return false unless @actions[board]
unbindAction @actions[board]
@actions[board] = nil
board\removeElement @
update: (board, overrides) =>
board = board or @board
return false unless @actions[board]
overrides = overrides or { }
overrides.callback = actionPrefix .. @actions[board]
board\updateElement @, overrides
| 24.614286 | 78 | 0.630876 |
db65416a197bfc4aff9711de3d063a2fe6aa7857 | 526 | import run_with_scope, defaultbl from require "moon"
import insert from require "table"
local parse_to_table
args = (first, ...)->
if #{...}>0
{first, ...}
else
first
call = (name, first, ...)=>
if type(first) == "function"
insert @_buffer, {:name, value: parse_to_table first, args ...}
else
insert @_buffer, {:name, value: args first, ...}
index = (name)=>
(...) -> call @, name, ...
parse_to_table = (fn)->
buf = {}
run_with_scope fn, defaultbl {_buffer:buf}, index
buf
parse_to_table
| 19.481481 | 67 | 0.612167 |
fe08dc35a33845eaaa1639819dc7068071ffda06 | 130 | export class Entity
Index: -1
Class: "unkown"
@EngineType: () -> "Entity"
__tostring: () => "Entity [#{@Index}][#{@Class}]"
| 16.25 | 50 | 0.584615 |
904b5ce39dacfc4cb68d818e427ba1f8b01c895d | 311 | package.path = "pieces/?.lua;" .. package.path
require "config"
require "bishop"
require "queen"
require "knight"
require "rook"
board = {}
for i = 0, Config.rows
board[i] = {}
p = Knight()
p\set_pos(6, 3)
moves = p\get_possible_moves(board)
print #moves
print "#{move[1]} #{move[2]}" for move in *moves
| 17.277778 | 48 | 0.655949 |
7a166c5280d2672691d8bb17e55643208a8f72d2 | 25 | require "lapis.db.schema" | 25 | 25 | 0.8 |
0704f122a5a450f5dd75cbfa9b164cfc188fae46 | 5,260 | -- Copyright 2014-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
View = require 'aullar.view'
Buffer = require 'aullar.buffer'
styles = require 'aullar.styles'
describe 'DisplayLines', ->
local view, buffer, display_lines
setup ->
styles.define 'b1', background: '#112233'
styles.define 'b2', background: '#445566'
styles.define 'b3', background: '#112233'
before_each ->
buffer = Buffer!
view = View buffer
display_lines = view.display_lines
context '(one individual line)', ->
describe 'background_ranges(line)', ->
it 'returns ranges along with the style definition for styles runs with backgrounds', ->
buffer.text = 'back to back'
buffer.styling\set 1, 4, 'b1'
buffer.styling\set 9, 12, 'b2'
ranges = display_lines[1].background_ranges
assert.equals 2, #ranges
assert.same { start_offset: 1, end_offset: 5, style: { background: '#112233', alpha: 1 } }, ranges[1]
assert.same { start_offset: 9, end_offset: 13, style: { background: '#445566', alpha: 1 } }, ranges[2]
it 'merges adjacent ranges', ->
buffer.text = 'background'
buffer.styling\set 1, 5, 'b1'
buffer.styling\set 5, 10, 'b3'
ranges = display_lines[1].background_ranges
assert.equals 1, #ranges
assert.same { start_offset: 1, end_offset: 11, style: { background: '#112233', alpha: 1 } }, ranges[1]
describe '.indentation', ->
it 'is the indentation level for the line', ->
buffer.text = "zero\n two\n four\n\ttab\n"
view.config.view_tab_size = 5
assert.equals 0, display_lines[1].indent
assert.equals 2, display_lines[2].indent
assert.equals 4, display_lines[3].indent
assert.equals 5, display_lines[4].indent
context 'display blocks', ->
it 'multiple adjacent lines with whole-line backgrounds are part of a single block', ->
-- 8 16 24
buffer.text = 'before\nblock 1\nblock 2\nafter'
buffer.styling\set 1, 6, 'b1' -- styled up until eol
buffer.styling\set 8, 23, 'b2' -- styled over eols
assert.is_nil display_lines[1].block
assert.is_not_nil display_lines[2].block
assert.is_not_nil display_lines[3].block
assert.is_nil display_lines[4].block
assert.equals display_lines[2].block, display_lines[3].block
block = display_lines[2].block
assert.equals 2, block.start_line
assert.equals 3, block.end_line
it 'a single line with a whole-line background does not belong to a block', ->
-- 8 15
buffer.text = 'before\nblock?\nafter'
buffer.styling\set 8, 14, 'b2' -- styled over eols
assert.is_nil display_lines[2].block
it 'the width of a block is the width of the longest line', ->
buffer.text = 'block 1\nblock 2 longer'
buffer.styling\set 1, #buffer.text, 'b1'
block = display_lines[1].block
assert.not_equals display_lines[1].width, block.width
assert.equals display_lines[2].width, block.width
context 'block merging', ->
before_each ->
-- 8 16 24 31
buffer.text = 'before\nblock 2\nblock 3\nblock4\nafter'
buffer.styling\set 8, 30, 'b1'
for nr = 1, 5
display_lines[nr].block -- force block evaluation
it 'finds and merges previous blocks, including intermediate lines', ->
block = display_lines[2].block
display_lines[3] = nil
display_lines[4] = nil
assert.equals block, display_lines[4].block
assert.equals block, display_lines[3].block
it 'finds and merges subsequent blocks, including intermediate lines', ->
block = display_lines[4].block
display_lines[2] = nil
display_lines[3] = nil
assert.equals block, display_lines[2].block
assert.equals block, display_lines[3].block
describe 'window management (cached lines)', ->
before_each ->
lines = {}
for i = 1, 30
lines[#lines + 1] = "This is line #{i}"
buffer.text = table.concat lines, '\n'
it 'caches lines for the set window, plus 25% of the window size', ->
display_lines\set_window 10, 20
for i = 1, 30 -- ref them all
display_lines[i]
for i = 1, 7
assert.is_nil rawget display_lines, i
for i = 8, 22
assert.is_not_nil rawget display_lines, i
for i = 23, 30
assert.is_nil rawget display_lines, i
it 'removes existing entries when setting the window', ->
for i = 1, 30 -- ref them all
display_lines[i]
assert.is_not_nil rawget display_lines, 7
assert.is_not_nil rawget display_lines, 23
display_lines\set_window 10, 20
assert.is_nil rawget display_lines, 7
assert.is_nil rawget display_lines, 23
it 'updates .min and .max when setting the window', ->
display_lines[5]
display_lines[25]
assert.equals 5, display_lines.min
assert.equals 25, display_lines.max
display_lines\set_window 10, 20
assert.equals 22, display_lines.max
assert.equals 8, display_lines.min
| 35.540541 | 110 | 0.63384 |
74694c4c806519fac831d3bf79e539734b81d3b7 | 667 | export class Text extends Graphic
new: (font, text) =>
super!
@text = love.graphics.newText(font, text)
@quad = nil
draw: (x=0, y=0, r=@orientation, [email protected], [email protected], [email protected], [email protected], [email protected], [email protected]) =>
cr, cg, cb, ca = love.graphics.getColor!
love.graphics.setColor(@color[1], @color[2], @color[3], @opacity)
if (@quad != nil)
love.graphics.draw(@text, @quad, @x + x, @y + y, r, sx, sy, ox, oy, kx, ky)
else
love.graphics.draw(@text, @x + x, @y + y, r, sx, sy, ox, oy, kx, ky)
love.graphics.setColor(cr, cg, cb, aa)
| 39.235294 | 126 | 0.526237 |
e7d9529ee9edb145140ed4d1d76afd83e9c816b4 | 1,419 | lapis = require "lapis"
import after_dispatch from require "lapis.nginx.context"
import to_json from require "lapis.util"
migrations=require "lapis.db.migrations"
config = (require "lapis.config").get!
class extends lapis.Application
@before_filter =>
if config.measure_performance
after_dispatch ->
print to_json ngx.ctx.performance
@modules or={}
@session.modules or={}
"/_lazuli/console": if config.enable_console
(require "lapis.console").make!
else
=> "console disabled in config"
"/_lazuli/migrate": if config.enable_web_migration
=>
migrations.create_migrations_table!
migrations.run_migrations require "migrations"
else
=> "web migration disabled in config"
new: (...)=>
@modules or={}
super ...
enable: (feature,forcelapis=false)=>
if not forcelapis
have,fn=pcall require, "lazuli.modules."..feature..".enabler"
if have and type(fn)=="function"
return fn @
super feature
superroute: (r,f)=>
App=@__parent
cache=nil
name=next r
cont=f or r[1]
r[1]=nil
@__base[r]= =>
if not cache
for app_route in pairs App.__base
if type(app_route) == "table"
app_route_name = next app_route
if app_route_name == name
cache=App.__base[app_route]
break
if cont
cont @, cache(@)
else
cache(@)
| 27.288462 | 67 | 0.630726 |
77ede7f7c3a108c5f114a20748131c6b3947dd90 | 1,116 | -- Copyright 2014-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
ffi = require 'ffi'
require 'ljglibs.cdefs.gio'
core = require 'ljglibs.core'
C, ffi_string = ffi.C, ffi.string
core.define 'GFileInfo', {
constants: {
prefix: 'G_FILE_'
'TYPE_UNKNOWN',
'TYPE_REGULAR',
'TYPE_DIRECTORY',
'TYPE_SYMBOLIC_LINK',
'TYPE_SPECIAL',
'TYPE_SHORTCUT',
'TYPE_MOUNTABLE'
}
properties: {
name: => ffi_string C.g_file_info_get_name @
is_hidden: => C.g_file_info_get_is_hidden(@) != 0
is_backup: => C.g_file_info_get_is_backup(@) != 0
is_symlink: => C.g_file_info_get_is_symlink(@) != 0
filetype: => C.g_file_info_get_file_type @
size: => tonumber C.g_file_info_get_size @
etag: => ffi_string C.g_file_info_get_etag @
}
get_attribute_string: (attribute) => ffi_string C.g_file_info_get_attribute_string @, attribute
get_attribute_boolean: (attribute) => C.g_file_info_get_attribute_boolean(@, attribute) != 0
get_attribute_uint64: (attribute) => C.g_file_info_get_attribute_uint64 @, attribute
}
| 30.162162 | 97 | 0.712366 |
f9c5fb772f8546f33502becea6a238e777fa6ccf | 226 | M = {}
name = "test_windows"
me = ...
FX = require "FunctionalX"
TK = require("PackageToolkit")
case = TK.test.case
M[name] = ->
fn = FX.os.windows
case fn, {}, {true}, "numeric.range case 1"
return true
return M | 18.833333 | 47 | 0.610619 |
064094dfec94bf9ad66fc7bf63b2a761b46334cf | 2,443 | -- This Lua implementation was based on this repository, thanks
-- https://github.com/luciopaiva/graham-scan
checkOrientation = (p1, p2, p3) -> (p2[2] - p1[2]) * (p3[1] - p2[1]) - (p3[2] - p2[2]) * (p2[1] - p1[1])
getAngle = (p1, p2) -> math.atan2(p2[2] - p1[2], p2[1] - p1[1])
euclideanDistanceSquared = (p1, p2) ->
x = (p2[1] - p1[1]) ^ 2
y = (p2[2] - p1[2]) ^ 2
return x + y
class GrahamScan
new: => @points = {}
clear: => GrahamScan!
getPoints: => @points
setPoints: (points) => @points = points
addPoint: (point) => table.insert(@points, point)
addPoints: (points) =>
for k, v in ipairs points
@addPoint v
getHull: =>
ArrayFrom = (t, fn) ->
val = {}
for k, v in ipairs t
val[k] = fn(v, k)
return val
pivot = @preparePivotPoint!
indexes = ArrayFrom @points, (point, i) -> i
angles = ArrayFrom @points, (point) -> getAngle(pivot, point)
distances = ArrayFrom @points, (point) -> euclideanDistanceSquared(pivot, point)
table.sort indexes, (i, j) ->
if angles[i] == angles[j]
return distances[i] < distances[j]
return angles[i] < angles[j]
for i = 2, #indexes - 1
indexes[i] = -1 if angles[indexes[i]] == angles[indexes[i + 1]]
hull = {}
for i = 1, #indexes
index = indexes[i]
point = @points[index]
if index != -1
if #hull < 3
table.insert hull, point
else
while checkOrientation(hull[#hull - 1], hull[#hull], point) > 0
table.remove hull
table.insert hull, point
return #hull < 3 and {} or hull
preparePivotPoint: =>
pivot = @points[1]
pivotIndex = 1
for i = 2, #@points
point = @points[i]
if point[2] < pivot[2] or point[2] == pivot[2] and point[1] < pivot[1]
pivot = point
pivotIndex = i
return pivot
test_points = {
{0, 0}
{0, 20}
{20, 20}
{20, 0}
{10, 10}
}
make = GrahamScan!
make\setPoints test_points -- make\addPoints(test_points)
result = make\getHull!
for k, v in ipairs result
print("{x = #{v[1]}, y = #{v[2]}}") | 28.406977 | 105 | 0.481375 |
5718a95b189407d2160809187098df58ce081a49 | 14,335 | require "spec.helpers" -- for one_of
db = require "lapis.db.postgres"
schema = require "lapis.db.postgres.schema"
unpack = unpack or table.unpack
value_table = { hello: "world", age: 34 }
import sorted_pairs from require "spec.helpers"
tests = {
-- lapis.db.postgres
{
-> db.escape_identifier "dad"
'"dad"'
}
{
-> db.escape_identifier "select"
'"select"'
}
{
-> db.escape_identifier 'love"fish'
'"love""fish"'
}
{
-> db.escape_identifier db.raw "hello(world)"
"hello(world)"
}
{
-> db.escape_literal 3434
"3434"
}
{
-> db.escape_literal "cat's soft fur"
"'cat''s soft fur'"
}
{
-> db.escape_literal db.raw "upper(username)"
"upper(username)"
}
{
-> db.escape_literal db.list {1,2,3,4,5}
"(1, 2, 3, 4, 5)"
}
{
-> db.escape_literal db.list {"hello", "world", db.TRUE}
"('hello', 'world', TRUE)"
}
{
-> db.escape_literal db.list {"foo", db.raw "lower(name)"}
"('foo', lower(name))"
}
{
-> db.escape_literal db.array {1,2,3,4,5}
"ARRAY[1,2,3,4,5]"
}
{
-> db.interpolate_query "select * from cool where hello = ?", "world"
"select * from cool where hello = 'world'"
}
{
-> db.encode_values(value_table)
[[("hello", "age") VALUES ('world', 34)]]
[[("age", "hello") VALUES (34, 'world')]]
}
{
-> db.encode_assigns(value_table)
[["hello" = 'world', "age" = 34]]
[["age" = 34, "hello" = 'world']]
}
{
-> db.encode_assigns thing: db.NULL
[["thing" = NULL]]
}
{
-> db.encode_clause thing: db.NULL
[["thing" IS NULL]]
}
{
-> db.encode_clause cool: true, id: db.list {1,2,3,5}
[["id" IN (1, 2, 3, 5) AND "cool" = TRUE]]
[["cool" = TRUE AND "id" IN (1, 2, 3, 5)]]
}
{
-> db.interpolate_query "update items set x = ?", db.raw"y + 1"
"update items set x = y + 1"
}
{
-> db.interpolate_query "update items set x = false where y in ?", db.list {"a", "b"}
"update items set x = false where y in ('a', 'b')"
}
{
-> db.select "* from things where id = ?", "cool days"
[[SELECT * from things where id = 'cool days']]
}
{
-> db.insert "cats", age: 123, name: "catter"
[[INSERT INTO "cats" ("name", "age") VALUES ('catter', 123)]]
[[INSERT INTO "cats" ("age", "name") VALUES (123, 'catter')]]
}
{
-> db.update "cats", { age: db.raw"age - 10" }, "name = ?", "catter"
[[UPDATE "cats" SET "age" = age - 10 WHERE name = 'catter']]
}
{
-> db.update "cats", { age: db.raw"age - 10" }, { name: db.NULL }
[[UPDATE "cats" SET "age" = age - 10 WHERE "name" IS NULL]]
}
{
-> db.update "cats", { age: db.NULL }, { name: db.NULL }
[[UPDATE "cats" SET "age" = NULL WHERE "name" IS NULL]]
}
{
-> db.update "cats", { color: "red" }, { weight: 1200, length: 392 }
[[UPDATE "cats" SET "color" = 'red' WHERE "weight" = 1200 AND "length" = 392]]
[[UPDATE "cats" SET "color" = 'red' WHERE "length" = 392 AND "weight" = 1200]]
}
{
-> db.update "cats", { color: "red" }, { weight: 1200, length: 392 }, "weight", "color"
[[UPDATE "cats" SET "color" = 'red' WHERE "weight" = 1200 AND "length" = 392 RETURNING "weight", "color"]]
[[UPDATE "cats" SET "color" = 'red' WHERE "length" = 392 AND "weight" = 1200 RETURNING "weight", "color"]]
}
{
-> db.update "cats", { age: db.NULL }, { name: db.NULL }, db.raw "*"
[[UPDATE "cats" SET "age" = NULL WHERE "name" IS NULL RETURNING *]]
}
{
-> db.delete "cats"
[[DELETE FROM "cats"]]
}
{
-> db.delete "cats", "name = ?", "rump"
[[DELETE FROM "cats" WHERE name = 'rump']]
}
{
-> db.delete "cats", name: "rump"
[[DELETE FROM "cats" WHERE "name" = 'rump']]
}
{
-> db.delete "cats", name: "rump", dad: "duck"
[[DELETE FROM "cats" WHERE "name" = 'rump' AND "dad" = 'duck']]
[[DELETE FROM "cats" WHERE "dad" = 'duck' AND "name" = 'rump']]
}
{
-> db.delete "cats", { color: "red" }, "name", "color"
[[DELETE FROM "cats" WHERE "color" = 'red' RETURNING "name", "color"]]
}
{
-> db.delete "cats", { color: "red" }, db.raw "*"
[[DELETE FROM "cats" WHERE "color" = 'red' RETURNING *]]
}
{
-> db.insert "cats", { hungry: true }
[[INSERT INTO "cats" ("hungry") VALUES (TRUE)]]
}
{
-> db.insert "cats", { age: 123, name: "catter" }, "age"
[[INSERT INTO "cats" ("name", "age") VALUES ('catter', 123) RETURNING "age"]]
[[INSERT INTO "cats" ("age", "name") VALUES (123, 'catter') RETURNING "age"]]
}
{
-> db.insert "cats", { age: 123, name: "catter" }, "age", "name"
[[INSERT INTO "cats" ("name", "age") VALUES ('catter', 123) RETURNING "age", "name"]]
[[INSERT INTO "cats" ("age", "name") VALUES (123, 'catter') RETURNING "age", "name"]]
}
-- lapis.db.postgres.schema
{
-> schema.add_column "hello", "dads", schema.types.integer
[[ALTER TABLE "hello" ADD COLUMN "dads" integer NOT NULL DEFAULT 0]]
}
{
-> schema.rename_column "hello", "dads", "cats"
[[ALTER TABLE "hello" RENAME COLUMN "dads" TO "cats"]]
}
{
-> schema.drop_column "hello", "cats"
[[ALTER TABLE "hello" DROP COLUMN "cats"]]
}
{
-> schema.rename_table "hello", "world"
[[ALTER TABLE "hello" RENAME TO "world"]]
}
{
-> tostring schema.types.integer
"integer NOT NULL DEFAULT 0"
}
{
-> tostring schema.types.integer null: true
"integer DEFAULT 0"
}
{
-> tostring schema.types.integer null: true, default: 100, unique: true
"integer DEFAULT 100 UNIQUE"
}
{
-> tostring schema.types.integer array: true, null: true, default: '{1}', unique: true
"integer[] DEFAULT '{1}' UNIQUE"
}
{
-> tostring schema.types.text array: true, null: false
"text[] NOT NULL"
}
{
-> tostring schema.types.text array: true, null: true
"text[]"
}
{
-> tostring schema.types.integer array: 1
"integer[] NOT NULL"
}
{
-> tostring schema.types.integer array: 3
"integer[][][] NOT NULL"
}
{
-> tostring schema.types.serial
"serial NOT NULL"
}
{
-> tostring schema.types.time
"timestamp NOT NULL"
}
{
-> tostring schema.types.time timezone: true
"timestamp with time zone NOT NULL"
}
{
->
import foreign_key, boolean, varchar, text from schema.types
schema.create_table "user_data", {
{"user_id", foreign_key}
{"email_verified", boolean}
{"password_reset_token", varchar null: true}
{"data", text}
"PRIMARY KEY (user_id)"
}
[[CREATE TABLE "user_data" (
"user_id" integer NOT NULL,
"email_verified" boolean NOT NULL DEFAULT FALSE,
"password_reset_token" character varying(255),
"data" text NOT NULL,
PRIMARY KEY (user_id)
)]]
}
{
->
import foreign_key, boolean, varchar, text from schema.types
schema.create_table "join_stuff", {
{"hello_id", foreign_key}
{"world_id", foreign_key}
}, if_not_exists: true
[[CREATE TABLE IF NOT EXISTS "join_stuff" (
"hello_id" integer NOT NULL,
"world_id" integer NOT NULL
)]]
}
{
-> schema.drop_table "user_data"
[[DROP TABLE IF EXISTS "user_data"]]
}
{
-> schema.create_index "user_data", "thing"
[[CREATE INDEX "user_data_thing_idx" ON "user_data" ("thing")]]
}
{
-> schema.create_index "user_data", "thing", unique: true
[[CREATE UNIQUE INDEX "user_data_thing_idx" ON "user_data" ("thing")]]
}
{
-> schema.create_index "user_data", "thing", unique: true, index_name: "good_idx"
[[CREATE UNIQUE INDEX "good_idx" ON "user_data" ("thing")]]
}
{
-> schema.create_index "user_data", "thing", if_not_exists: true
[[CREATE INDEX IF NOT EXISTS "user_data_thing_idx" ON "user_data" ("thing")]]
}
{
-> schema.create_index "user_data", "thing", unique: true, where: "age > 100"
[[CREATE UNIQUE INDEX "user_data_thing_idx" ON "user_data" ("thing") WHERE age > 100]]
}
{
-> schema.create_index "users", "friend_id", tablespace: "farket"
[[CREATE INDEX "users_friend_id_idx" ON "users" ("friend_id") TABLESPACE "farket"]]
}
{
-> schema.create_index "user_data", "one", "two"
[[CREATE INDEX "user_data_one_two_idx" ON "user_data" ("one", "two")]]
}
{
-> schema.create_index "user_data", db.raw("lower(name)"), "height"
[[CREATE INDEX "user_data_lower_name_height_idx" ON "user_data" (lower(name), "height")]]
}
{
-> schema.drop_index "user_data", "one", "two", "three"
[[DROP INDEX IF EXISTS "user_data_one_two_three_idx"]]
}
{
-> schema.drop_index index_name: "hello_world_idx"
[[DROP INDEX IF EXISTS "hello_world_idx"]]
}
{
-> schema.drop_index "user_data", "one", "two", "three", cascade: true
[[DROP INDEX IF EXISTS "user_data_one_two_three_idx" CASCADE]]
}
{
-> schema.drop_index "users", "height", { index_name: "user_tallness_idx", unique: true }
[[DROP INDEX IF EXISTS "user_tallness_idx"]]
}
{
-> db.parse_clause ""
{}
}
{
-> db.parse_clause "where something = TRUE"
{
where: "something = TRUE"
}
}
{
-> db.parse_clause "where something = TRUE order by things asc"
{
where: "something = TRUE "
order: "things asc"
}
}
{
-> db.parse_clause "where something = 'order by cool' having yeah order by \"limit\" asc"
{
having: "yeah "
where: "something = 'order by cool' "
order: '"limit" asc'
}
}
{
-> db.parse_clause "where not exists(select 1 from things limit 100)"
{
where: "not exists(select 1 from things limit 100)"
}
}
{
-> db.parse_clause "order by color asc"
{
order: "color asc"
}
}
{
-> db.parse_clause "ORDER BY color asc"
{
order: "color asc"
}
}
{
-> db.parse_clause "group BY height"
{
group: "height"
}
}
{
-> db.parse_clause "where x = limitx 100"
{
where: "x = limitx 100"
}
}
{
-> db.parse_clause "join dads on color = blue where hello limit 10"
{
limit: "10"
where: "hello "
join: {
{"join", " dads on color = blue "}
}
}
}
{
-> db.parse_clause "inner join dads on color = blue left outer join hello world where foo"
{
where: "foo"
join: {
{"inner join", " dads on color = blue "}
{"left outer join", " hello world "}
}
}
}
{
-> schema.gen_index_name "hello", "world"
"hello_world_idx"
}
{
-> schema.gen_index_name "yes", "please", db.raw "upper(dad)"
"yes_please_upper_dad_idx"
}
{
-> schema.gen_index_name "hello", "world", index_name: "override_me_idx"
"override_me_idx"
}
{
-> db.encode_case("x", { a: "b" })
[[CASE x
WHEN 'a' THEN 'b'
END]]
}
{
-> db.encode_case("x", { a: "b", foo: true })
[[CASE x
WHEN 'a' THEN 'b'
WHEN 'foo' THEN TRUE
END]]
[[CASE x
WHEN 'foo' THEN TRUE
WHEN 'a' THEN 'b'
END]]
}
{
-> db.encode_case("x", { a: "b" }, false)
[[CASE x
WHEN 'a' THEN 'b'
ELSE FALSE
END]]
}
{
-> db.is_encodable "hello"
true
}
{
-> db.is_encodable 2323
true
}
{
-> db.is_encodable true
true
}
{
-> db.is_encodable ->
false
}
{
->
if _G.newproxy
db.is_encodable newproxy!
else
-- cjson.empty_array is a userdata
db.is_encodable require("cjson").empty_array
false
}
{
-> db.is_encodable db.array {1,2,3}
true
}
{
-> db.is_encodable db.NULL
true
}
{
-> db.is_encodable db.TRUE
true
}
{
-> db.is_encodable db.FALSE
true
}
{
-> db.is_encodable {}
false
}
{
-> db.is_encodable nil
false
}
{
-> db.is_raw "hello"
false
}
{
-> db.is_raw db.raw "hello wrold"
true
}
{
-> db.is_raw db.list {1,2,3}
false
}
}
local old_query_fn
describe "lapis.db.postgres", ->
setup ->
old_query_fn = db.set_backend "raw", (q) -> q
teardown ->
db.set_backend "raw", old_query_fn
for group in *tests
it "should match", ->
output = group[1]!
if #group > 2
assert.one_of output, { unpack group, 2 }
else
assert.same group[2], output
describe "encode_assigns", ->
sorted_pairs!
it "writes output to buffer", ->
buffer = {"hello"}
-- nothing is returned when using buffer
assert.same nil, (db.encode_assigns {
one: "two"
zone: 55
age: db.NULL
}, buffer)
assert.same {
"hello"
'"age"', " = ", "NULL"
", "
'"one"', " = ", "'two'"
", "
'"zone"', " = ", "55"
}, buffer
it "fails when t is empty, buffer unchanged", ->
buffer = {"hello"}
assert.has_error(
-> db.encode_assigns {}, buffer
"encode_assigns passed an empty table"
)
assert.same { "hello" }, buffer
describe "encode_clause", ->
sorted_pairs!
it "writes output to buffer", ->
buffer = {"hello"}
-- nothing is returned when using buffer
assert.same nil, (db.encode_clause {
hello: "world"
lion: db.NULL
}, buffer)
assert.same {
"hello"
'"hello"', " = ", "'world'"
" AND "
'"lion"', " IS NULL"
}, buffer
it "fails when t is empty, buffer unchanged", ->
buffer = {"hello"}
assert.has_error(
-> db.encode_clause {}, buffer
"encode_clause passed an empty table"
)
assert.same { "hello" }, buffer
describe "encode_values", ->
sorted_pairs!
it "writes output to buffer", ->
buffer = {"hello"}
-- nothing is returned when using buffer
assert.same nil, (db.encode_values {
hello: "world"
lion: db.NULL
}, buffer)
assert.same {
"hello"
'(',
'"hello"', ', ', '"lion"'
') VALUES ('
"'world'", ', ', 'NULL'
')'
}, buffer
it "fails when t is empty, buffer unchanged", ->
buffer = {"hello"}
assert.has_error(
-> db.encode_values {}, buffer
"encode_values passed an empty table"
)
assert.same { "hello" }, buffer
| 20.775362 | 110 | 0.548169 |
92d311a06cfeb41aef350b0afac8ffc162e06662 | 868 | import readline, readnumber, ls from require 'mon.util'
(args={}) ->
import bat, adp from args
unless bat or adp
files = ls '/sys/class/power_supply'
for file in *files
bat = file if not bat and string.match file, '^BAT'
adp = file if not adp and string.match file, '^ADP'
return {} unless bat and adp
{
level:
value: -> readnumber "/sys/class/power_supply/#{bat}/capacity"
name: "Battery - #{bat} - Level"
low: {30, 15, 5}
min: 0
max: 100
unit: '%'
status:
value: -> string.lower readline "/sys/class/power_supply/#{bat}/status"
name: "Battery - #{bat} - Status"
levels:
discharging: 2
unknown: 1
charger:
value: ->
status = readnumber "/sys/class/power_supply/#{adp}/online"
if status == 1
'plugged'
else
'unplugged'
name: "Charger - #{adp} - Status"
levels:
unplugged: 2
}
| 24.111111 | 74 | 0.616359 |
6d12715d6f219fa4e03165251540550094cdc29a | 1,922 | -- Copyright 2012-2018 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
{:PropertyObject} = howl.util.moon
{:TextWidget} = howl.ui
{:floor} = math
{:tostring} = _G
class ListWidget extends PropertyObject
new: (@list, opts = {}) =>
super!
@partial = false
@opts = moon.copy opts
@text_widget = TextWidget @opts
@text_widget.visible_rows = 15
list\insert @text_widget.buffer
list.max_rows = @text_widget.visible_rows
list\on_refresh self\_on_refresh
@property showing: get: => @text_widget.showing
@property height: get: => @text_widget.height
@property width: get: => @text_widget.width
@property max_height_request:
set: (height) =>
default_line_height = @text_widget.view\text_dimensions('M').height
@list.max_rows = floor(height / default_line_height)
@list\draw!
@property max_width_request:
set: (width) =>
local default_char_width
if width
default_char_width = @text_widget.view\text_dimensions('W').width
@list.max_cols = floor(width / default_char_width)
else
@list.max_cols = nil
@list\draw!
keymap:
binding_for:
['cursor-up']: => @list\select_prev!
['cursor-down']: => @list\select_next!
['cursor-page-up']: => @list\prev_page!
['cursor-page-down']: => @list\next_page!
to_gobject: => @text_widget\to_gobject!
show: =>
return if @showing
@text_widget\show!
@list\draw!
hide: => @text_widget\hide!
_on_refresh: =>
if @text_widget.showing
@_adjust_height!
@_adjust_width!
@text_widget.view.first_visible_line = 1
_adjust_height: =>
shown_rows = @list.rows_shown
if @opts.never_shrink
@list.min_rows = shown_rows
@text_widget.visible_rows = shown_rows
_adjust_width: =>
if @opts.auto_fit_width
@text_widget\adjust_width_to_fit!
| 25.972973 | 79 | 0.665453 |
c899fc4c69117c8cafb997c29664ff8ac0aef04f | 361 | export modinfo = {
type: "command"
desc: "Spin"
alias: {"spin"}
func: getDoPlayersFunction (v) ->
if v.Character and v.Character.Torso
v.Character.Torso.Anchored = true
Spawn ->
for i=1,360
v.Character.Torso.CFrame = v.Character.Torso.CFrame * CFrame.Angles(math.rad(i),math.rad(i),0)
wait(.01)
v.Character.Torso.Anchored = false
} | 27.769231 | 99 | 0.66759 |
e0dbb6644ebce1046766db53a0446c1af6e76168 | 464 | sqlite = require "lsqlite3"
db = sqlite.open ":memory:"
db\exec [[CREATE TABLE P
(
PNUM int NOT NULL PRIMARY KEY,
PNAME varchar(18) NOT NULL,
COLOR varchar(10) NOT NULL,
WEIGHT decimal(4,1) NOT NULL,
CITY varchar(20) NOT NULL,
UNIQUE (PNAME, COLOR, CITY)
);]]
db\exec [[insert into P values (7, 'Washer', 'Grey', 5, 'Helsinki')]]
stmt = db\prepare [[select * from P where city = 'Helsinki';]]
for r in stmt\nrows!
for k, v in pairs r do print k, v
db\close! | 27.294118 | 69 | 0.674569 |
45179660f87526b1c410bd72330ec6ff783b5b80 | 11,339 |
lapis = require "lapis"
import mock_action, mock_request, assert_request from require "lapis.spec.request"
mock_app = (...) ->
mock_action lapis.Application, ...
describe "find_action", ->
action1 = ->
action2 = ->
class SomeApp extends lapis.Application
[hello: "/cool-dad"]: action1
[world: "/another-dad"]: action2
it "finds action", ->
assert.same action1, (SomeApp\find_action "hello")
assert.same action2, (SomeApp\find_action "world")
assert.same nil, (SomeApp\find_action "nothing")
describe "inheritance", ->
local result
before_each ->
result = nil
class BaseApp extends lapis.Application
"/yeah": => result = "base yeah"
[test_route: "/hello/:var"]: => result = "base test"
class ChildApp extends BaseApp
"/yeah": => result = "child yeah"
"/thing": => result = "child thing"
it "should find route in base app", ->
status, buffer, headers = mock_request ChildApp, "/hello/world", {}
assert.same 200, status
assert.same "base test", result
it "should generate url from route in base", ->
url = mock_action ChildApp, =>
@url_for "test_route", var: "foobar"
assert.same url, "/hello/foobar"
it "should override route in base class", ->
status, buffer, headers = mock_request ChildApp, "/yeah", {}
assert.same 200, status
assert.same "child yeah", result
describe "@include", ->
local result
before_each ->
result = nil
it "should include another app", ->
class SubApp extends lapis.Application
"/hello": => result = "hello"
class App extends lapis.Application
@include SubApp
"/world": => result = "world"
status, buffer, headers = mock_request App, "/hello", {}
assert.same 200, status
assert.same "hello", result
status, buffer, headers = mock_request App, "/world", {}
assert.same 200, status
assert.same "world", result
it "should include another app", ->
class SubApp extends lapis.Application
"/hello": => result = "hello"
class App extends lapis.Application
@include SubApp
"/world": => result = "world"
status, buffer, headers = mock_request App, "/hello", {}
assert.same 200, status
assert.same "hello", result
status, buffer, headers = mock_request App, "/world", {}
assert.same 200, status
assert.same "world", result
it "should merge url table", ->
class SubApp extends lapis.Application
[hello: "/hello"]: => result = "hello"
class App extends lapis.Application
@include SubApp
[world: "/world"]: => result = "world"
app = App!
req = App.Request App!, {}, {}
assert.same "/hello", req\url_for "hello"
assert.same "/world", req\url_for "world"
it "should set sub app prefix path", ->
class SubApp extends lapis.Application
[hello: "/hello"]: => result = "hello"
class App extends lapis.Application
@include SubApp, path: "/sub"
[world: "/world"]: => result = "world"
app = App!
req = App.Request App!, {}, {}
assert.same "/sub/hello", req\url_for "hello"
assert.same "/world", req\url_for "world"
it "should set sub app url name prefix", ->
class SubApp extends lapis.Application
[hello: "/hello"]: => result = "hello"
class App extends lapis.Application
@include SubApp, name: "sub_"
[world: "/world"]: => result = "world"
app = App!
req = App.Request App!, {}, {}
assert.has_error -> req\url_for "hello"
assert.same "/hello", req\url_for "sub_hello"
assert.same "/world", req\url_for "world"
it "should set include options from target app", ->
class SubApp extends lapis.Application
@path: "/sub"
@name: "sub_"
[hello: "/hello"]: => result = "hello"
class App extends lapis.Application
@include SubApp
[world: "/world"]: => result = "world"
app = App!
req = App.Request App!, {}, {}
assert.same "/sub/hello", req\url_for "sub_hello"
assert.same "/world", req\url_for "world"
describe "default route", ->
it "hits default route", ->
local res
class App extends lapis.Application
"/": =>
default_route: =>
res = "bingo!"
status, body = mock_request App, "/hello", {}
assert.same 200, status
assert.same "bingo!", res
describe "default layout", ->
after_each ->
package.loaded["views.test_layout"] = nil
it "uses widget as layout", ->
import Widget from require "lapis.html"
class TestApp extends lapis.Application
layout: class Layout extends Widget
content: =>
h1 "hello world"
@content_for "inner"
div class: "footer"
"/": => "yeah"
status, body = assert_request TestApp, "/"
assert.same [[<h1>hello world</h1>yeah<div class="footer"></div>]], body
it "uses module name as layout", ->
import Widget from require "lapis.html"
class Layout extends Widget
content: =>
div class: "content", ->
@content_for "inner"
package.loaded["views.test_layout"] = Layout
class TestApp extends lapis.Application
layout: "test_layout"
"/": => "yeah"
status, body = assert_request TestApp, "/"
assert.same [[<div class="content">yeah</div>]], body
describe "error capturing", ->
import capture_errors, capture_errors_json, assert_error,
yield_error from require "lapis.application"
it "should capture error", ->
result = "no"
errors = nil
class ErrorApp extends lapis.Application
"/error_route": capture_errors {
on_error: =>
errors = @errors
=>
yield_error "something bad happened!"
result = "yes"
}
assert_request ErrorApp, "/error_route"
assert.same "no", result
assert.same {"something bad happened!"}, errors
it "should capture error as json", ->
result = "no"
class ErrorApp extends lapis.Application
"/error_route": capture_errors_json =>
yield_error "something bad happened!"
result = "yes"
status, body, headers = assert_request ErrorApp, "/error_route"
assert.same "no", result
assert.same [[{"errors":["something bad happened!"]}]], body
assert.same "application/json", headers["Content-Type"]
describe "instancing", ->
it "should match a route", ->
local res
app = lapis.Application!
app\match "/", => res = "root"
app\match "/user/:id", => res = @params.id
app\build_router!
assert_request app, "/"
assert.same "root", res
assert_request app, "/user/124"
assert.same "124", res
it "should should respond to verb", ->
local res
app = lapis.Application!
app\match "/one", ->
app\get "/hello", => res = "get"
app\post "/hello", => res = "post"
app\match "two", ->
app\build_router!
assert_request app, "/hello"
assert.same "get", res
assert_request app, "/hello", post: {}
assert.same "post", res
it "should hit default route", ->
local res
app = lapis.Application!
app\match "/", -> res = "/"
app.default_route = -> res = "default_route"
app\build_router!
assert_request app, "/hello"
assert.same "default_route", res
it "should strip trailing / to find route", ->
local res
app = lapis.Application!
app\match "/hello", -> res = "/hello"
app\match "/world/", -> res = "/world/"
app\build_router!
-- exact match, no default action
assert_request app, "/world/"
assert.same "/world/", res
status, _, headers = assert_request app, "/hello/"
assert.same 301, status
assert.same "http://localhost/hello", headers.location
it "should include another app", ->
do return pending "implement include for instances"
local res
sub_app = lapis.Application!
sub_app\get "/hello", => res = "hello"
app = lapis.Application!
app\get "/cool", => res = "cool"
app\include sub_app
it "should preserve order of route", ->
app = lapis.Application!
routes = for i=1,20
with r = "/route#{i}"
app\get r, =>
app\build_router!
assert.same routes, [tuple[1] for tuple in *app.router.routes]
describe "errors", ->
class ErrorApp extends lapis.Application
"/": =>
error "I am an error!"
it "renders default error page", ->
status, body, h = mock_request ErrorApp, "/", allow_error: true
assert.same 500, status
assert.truthy (body\match "I am an error")
-- only set on test env
assert.truthy h["X-Lapis-Error"]
it "raises error in spec by default", ->
assert.has_error ->
mock_request ErrorApp, "/"
it "renders custom error page", ->
class CustomErrorApp extends lapis.Application
handle_error: (err, msg) =>
assert.truthy @original_request
"hello world", layout: false, status: 444
"/": =>
error "I am an error!"
status, body, h = mock_request CustomErrorApp, "/", allow_error: true
assert.same 444, status
assert.same "hello world", body
-- should still be set
assert.truthy h["X-Lapis-Error"]
describe "custom request", ->
it "renders with custom request (overriding supuport)", ->
class R extends lapis.Application.Request
@support: {
load_session: =>
@session = {"cool"}
write_session: =>
}
local the_session
class A extends lapis.Application
Request: R
"/": =>
the_session = @session
"ok"
mock_request A, "/"
assert.same {"cool"}, the_session
-- should be requrest spec?
describe "inline html", ->
class HtmlApp extends lapis.Application
layout: false
"/": =>
@html -> div "hello world"
it "should render html", ->
status, body = assert_request HtmlApp, "/"
assert.same "<div>hello world</div>", body
-- this should be in request spec...
describe "request:build_url", ->
it "should build url", ->
assert.same "http://localhost", mock_app "/hello", {}, =>
@build_url!
it "should build url with path", ->
assert.same "http://localhost/hello_dog", mock_app "/hello", {}, =>
@build_url "hello_dog"
it "should build url with host and port", ->
assert.same "http://leaf:2000/hello",
mock_app "/hello", { host: "leaf", port: 2000 }, =>
@build_url @req.parsed_url.path
it "doesn't include default port for scheme http", ->
assert.same "http://leaf/whoa",
mock_app "/hello", { host: "leaf", port: 80 }, =>
@build_url "whoa"
it "doesn't include default port for scheme https", ->
assert.same "https://leaf/whoa",
mock_app "/hello", { host: "leaf", scheme: "https", port: 443 }, =>
@build_url "whoa"
it "should build url with overridden query", ->
assert.same "http://localhost/please?yes=no",
mock_app "/hello", {}, =>
@build_url "please?okay=world", { query: "yes=no" }
it "should build url with overridden port and host", ->
assert.same "http://yes:4545/cat?sure=dad",
mock_app "/hello", { host: "leaf", port: 2000 }, =>
@build_url "cat?sure=dad", host: "yes", port: 4545
it "should return arg if already build url", ->
assert.same "http://leafo.net",
mock_app "/hello", { host: "leaf", port: 2000 }, =>
@build_url "http://leafo.net"
| 26.742925 | 82 | 0.61628 |
8e084f767f78a81ff532b9fbc8e24fc1d5504000 | 1,304 | {:activities} = howl
{:File} = howl.io
TYPE_REGULAR = File.TYPE_REGULAR
validate_vc = (name, vc) ->
error '.paths() missing from "' .. name .. '"', 3 if not vc.paths
error '.root missing from "' .. name .. '"', 3 if not vc.root
error '.name missing from "' .. name .. '"', 3 if not vc.name
files = (vc) ->
paths = vc\paths!
activities.run {
title: "Loading files from '#{vc.root}'",
status: -> "Loading files from #{#paths} #{vc.name} entries..",
}, ->
groot = vc.root.gfile
return for i = 1, #paths
activities.yield! if i % 1000 == 0
path = paths[i]
gfile = groot\get_child(path)
File gfile, nil, type: TYPE_REGULAR
decorate_vc = (vc) ->
if not vc.files
vc = setmetatable({:files}, __index: vc)
vc
class VC
available: {}
register: (name, handler) ->
error '`name` missing', 2 if not name
error '`handler` missing', 2 if not handler
error 'required `.find` not provided in handler', 2 if not handler.find
VC.available[name] = handler
unregister: (name) ->
error '`name` missing', 2 if not name
VC.available[name] = nil
for_file: (file) ->
for name, handler in pairs VC.available
vc = handler.find file
if vc
validate_vc name, vc
return decorate_vc(vc)
nil
return VC
| 25.076923 | 75 | 0.604294 |
36ac8eb506d72d203d89c9253a2dc6110ba17e66 | 1,092 | import pi from math
export class Bow extends Item
new: =>
super sprites.bow
@psystem = love.graphics.newParticleSystem sprites.pixel.img, 32
@fireRate = 10
@attackDelay = 5/@fireRate
@canShoot = true
with @psystem
\setParticleLifetime 0.1, 0.1
\setSpeed 100
\setSpread pi * 0.5
\setColors 1, 1, 1, 1
update: (dt) =>
@psystem\update dt
if input\pressed("attack") and not player.disableAttacking and @canShoot
@shoot!
shoot: =>
@canShoot = true
if input\down("attack") and not player.disableAttacking
@canShoot = false
pos = player.pos + player.offset
ax, ay = input\get "attack"
attackDir = Vector(ax, ay)
if attackDir * player.movementDir == 0
attackDir += player.movementDir * 0.2
attackDir = attackDir.normalized
arrowPos = pos + attackDir * 10
arrow = Arrow arrowPos, attackDir
dungeon.currentRoom.entities[arrow] = arrow
tick.delay @shoot, @, @attackDelay
draw: =>
love.graphics.setColor 1, 1, 1
love.graphics.draw @psystem, 0, 0
| 28 | 76 | 0.636447 |
6801321f368192ed643fb68944319d9132494c42 | 7,264 | Gtk = require 'ljglibs.gtk'
import Window from howl.ui
describe 'Window', ->
local win
before_each ->
win = Window!
win\realize!
describe 'add_view(view [, placement, anchor])', ->
it 'adds the specified view', ->
win\add_view Gtk.Label!
assert.equals 1, #win.views
it 'returns a table containing x, y, width, height and the view', ->
label = Gtk.Label!
assert.same { x: 1, y: 1, width: 1, height: 1, view: label }, win\add_view label
it 'adds the new view to the right of the currently focused one by default', ->
entry = Gtk.Entry!
win\add_view entry
entry\grab_focus!
label = Gtk.Label!
assert.same { x: 2, y: 1, width: 1, height: 1, view: label }, win\add_view label
context 'when placement is specified', ->
local view, entry
before_each ->
entry = Gtk.Entry!
win\add_view entry
entry\grab_focus!
view = Gtk.Entry!
it '"right_of" places the view on the right side of the focused child', ->
assert.same { x: 2, y: 1, width: 1, height: 1, :view }, win\add_view view, 'right_of'
it '"left_of" places the view on the left side of the focused child', ->
assert.same { x: 1, y: 1, width: 1, height: 1, :view }, win\add_view view, 'left_of'
it '"above" places the view above the focused child', ->
assert.same { x: 1, y: 1, width: 1, height: 1, :view }, win\add_view view, 'above'
assert.same { x: 1, y: 2, width: 1, height: 1, view: entry }, win\get_view entry
it '"below" places the view below the focused child', ->
assert.same { x: 1, y: 2, width: 1, height: 1, :view }, win\add_view view, 'below'
it 'allows specifying the relative view to use with placement', ->
win\add_view view, 'below'
next_view = Gtk.Label!
assert.same { x: 1, y: 2, width: 1, height: 1, view: next_view }, win\add_view next_view, 'left_of', view
it 'creates new columns as needed', ->
win\add_view view, 'right_of'
next_view = Gtk.Label!
assert.same { x: 2, y: 1, width: 1, height: 1, view: next_view }, win\add_view next_view, 'left_of', view
assert.same { 1, 2, 3 }, [v.x for v in *win.views]
describe 'remove_view(view)', ->
it 'removes the specified view', ->
label = Gtk.Label!
win\add_view label
win\remove_view label
assert.equals 0, #win.views
it 'removes the currently focused child if view is nil', ->
entry = Gtk.Entry!
win\add_view entry
entry\grab_focus!
win\remove_view!
assert.equals 0, #win.views
it 'raises an error if view is nil and no child has focus', ->
label = Gtk.Label!
win\add_view label
assert.raises 'remove', -> win\remove_view!
it 'set focus on its later sibling is possible', ->
left = Gtk.Entry!
middle = Gtk.Entry!
right = Gtk.Entry!
win\add_view left
win\add_view middle
win\add_view right
middle\grab_focus!
win\remove_view middle
assert.is_true right.is_focus
it 'set focus on its earlier sibling if no later sibling exists', ->
left = Gtk.Entry!
middle = Gtk.Entry!
right = Gtk.Entry!
win\add_view left
win\add_view middle
win\add_view right
right\grab_focus!
win\remove_view right
assert.is_true middle.is_focus
describe '.views', ->
it 'is a table of view tables, containing x, y and the view itself', ->
label = Gtk.Label!
win\add_view label
assert.same { { x: 1, y: 1, width: 1, height: 1, view: label } }, win.views
it 'ordered ascendingly', ->
entry = Gtk.Entry!
win\add_view entry
entry\grab_focus!
l1 = Gtk.Label!
l2 = Gtk.Label!
win\add_view l1, 'left_of'
win\add_view l2, 'below'
assert.same { l1, entry, l2 }, [v.view for v in *win.views]
describe '.current_view', ->
it 'is nil if no child is currently focused', ->
assert.is_nil, win.current_view
it 'is a table containing x, y and the view for the currently focused view', ->
e1 = Gtk.Entry!
e2 = Gtk.Entry!
win\add_view e1
win\add_view e2
e1\grab_focus!
assert.same { x: 1, y: 1, width: 1, height: 1, view: e1 }, win.current_view
e2\grab_focus!
assert.same { x: 2, y: 1, width: 1, height: 1, view: e2 }, win.current_view
describe 'siblings(view, wraparound)', ->
context 'when wraparound is false', ->
it 'returns a table of siblings for the specified view when present', ->
left = Gtk.Entry!
right = Gtk.Entry!
bottom = Gtk.Entry!
win\add_view left
win\add_view right, 'right_of', left
win\add_view bottom, 'below', left
assert.same { right: right, down: bottom }, win\siblings left, false
assert.same { left: left, down: bottom }, win\siblings right, false
assert.same { up: left }, win\siblings bottom, false
context 'when wraparound is true', ->
it 'returns a table of siblings for the specified view in a wraparound fashion', ->
left = Gtk.Entry!
right = Gtk.Entry!
bottom = Gtk.Entry!
win\add_view left
win\add_view right, 'right_of', left
win\add_view bottom, 'below', left
assert.same { left: bottom, right: right, up: bottom, down: bottom }, win\siblings left, true
assert.same { left: left, right: bottom, up: bottom, down: bottom }, win\siblings right, true
assert.same { left: right, right: left, up: left, down: left }, win\siblings bottom, true
it 'returns an empty table if there are no siblings', ->
v1 = Gtk.Entry!
win\add_view v1
assert.same {}, win\siblings v1
it 'defaults to the currently focused child if view is not provided', ->
v1 = Gtk.Entry!
win\add_view v1
v1\grab_focus!
assert.same {}, win\siblings!
it 'returns an empty table if view is not provided and no child is focused', ->
assert.same {}, win\siblings!
describe 'column reflowing', ->
local left, right, bottom
before_each ->
left = Gtk.Entry!
right = Gtk.Entry!
bottom = Gtk.Entry!
win\add_view left
win\add_view right
right\grab_focus!
win\add_view bottom, 'below'
it 'single columns as expanded as necessary', ->
assert.same { x: 1, y: 2, width: 2, height: 1, view: bottom }, win\get_view bottom
it 'columns to the right are adjusted after a remove of a left column', ->
win\remove_view left
assert.same { x: 1, y: 1, width: 1, height: 1, view: right }, win\get_view right
it 'columns to the left are adjusted after a remove of a right column', ->
win\remove_view right
assert.same { x: 1, y: 1, width: 1, height: 1, view: left }, win\get_view left
it 'rows are adjusted after removal of a middle column', ->
middle = Gtk.Entry!
win\add_view middle, 'right_of', left
win\remove_view middle
assert.same { x: 1, y: 1, width: 1, height: 1, view: left }, win\get_view left
assert.same { x: 2, y: 1, width: 1, height: 1, view: right }, win\get_view right
| 35.607843 | 113 | 0.609719 |
b699af3abf04b459c01b7087ca01a8055d097f9d | 2,117 | export class UI extends Entity
new: =>
super!
with @heart = ImageSet("#{Settings.folders.graphics}/ui_heart.png", 10, 7)
.y = 5
@maxHearts = 1
@hearts = @maxHearts
@heartHorizontalSpace = 2
@horizontalDivision = 5
with @gem = Image("#{Settings.folders.graphics}/ui_gem.png")
.y = 2
@gems = 0
@initialGems = 0
@showGems = 0
@textMargin = 4
with @gemText = Text(Settings.gemCountFont, "#{@gems}")
.y = 5
@playingGemTween = false
@gemTweenProgress = 0
update: (dt) =>
super(dt)
if (@gemAddTween != nil and @playingGemTween)
if (@gemAddTween\update(dt))
@playingGemTween = false
@showGems = Lume.round(Lume.lerp(@initialGems, @gems, @gemTweenProgress))
@gemText.text\set("#{@showGems}")
draw: =>
super!
-- hearts
x = 8
for i = 0, @maxHearts - 1
if (@hearts - 1 >= i)
@heart\setFrame(1) -- full heart
else
@heart\setFrame(2) -- empty heart
@heart\draw(x, 0)
x += @heart.frame.width + @heartHorizontalSpace
--
x += @horizontalDivision
-- gems
@gem\draw(x, 0)
@gemText\draw(x + @gem.texture\getWidth! + @textMargin, 0)
setHeart: (amount) =>
@hearts = Lume.clamp(amount, 0, @maxHearts)
setGem: (amount) =>
if (@gems == amount)
return
@initialGems = @gems
@gems = amount
diff = @gems - @initialGems
@gemTweenProgress = 0
@gemAddTween = Tween.new(.1 + (diff / 100.0) * .05, @, { gemTweenProgress: 1.0 })
@playingGemTween = true
addGem: (amount) =>
@setGem(@gems + amount)
resetGems: =>
@showGems = 0
@gems = 0
@initialGems = 0
@gemTweenProgress = 0
@gemAddTween = nil
@playingGemTween = false
| 24.905882 | 90 | 0.47898 |
320524db19271f8361b40bc6b697329128d83b9a | 127 | import Model from require "lapis.db.model"
class Users extends Model
@table_name: => "lazuli_modules_user_management_users"
| 25.4 | 56 | 0.80315 |
e5c57403cec7615fd85155578ccbf2022fcaf407 | 3,055 |
util = require "moonscript.util"
import reversed, unpack from util
import ntype from require "moonscript.types"
import concat, insert from table
{
raw: (node) => @add node[2]
lines: (node) =>
for line in *node[2]
@add line
declare: (node) =>
names = node[2]
undeclared = @declare names
if #undeclared > 0
with @line "local "
\append_list [@name name for name in *undeclared], ", "
-- this overrides the existing names with new locals, used for local keyword
declare_with_shadows: (node) =>
names = node[2]
@declare names
with @line "local "
\append_list [@name name for name in *names], ", "
assign: (node) =>
_, names, values = unpack node
undeclared = @declare names
declare = "local "..concat(undeclared, ", ")
has_fndef = false
i = 1
while i <= #values
if ntype(values[i]) == "fndef"
has_fndef = true
i = i +1
with @line!
if #undeclared == #names and not has_fndef
\append declare
else
@add declare, node[-1] if #undeclared > 0
\append_list [@value name for name in *names], ", "
\append " = "
\append_list [@value v for v in *values], ", "
return: (node) =>
@line "return ", if node[2] != "" then @value node[2]
break: (node) =>
"break"
if: (node) =>
cond, block = node[2], node[3]
root = with @block @line "if ", @value(cond), " then"
\stms block
current = root
add_clause = (clause)->
type = clause[1]
i = 2
next = if type == "else"
@block "else"
else
i += 1
@block @line "elseif ", @value(clause[2]), " then"
next\stms clause[i]
current.next = next
current = next
add_clause cond for cond in *node[4,]
root
repeat: (node) =>
cond, block = unpack node, 2
with @block "repeat", @line "until ", @value cond
\stms block
while: (node) =>
_, cond, block = unpack node
with @block @line "while ", @value(cond), " do"
\stms block
for: (node) =>
_, name, bounds, block = unpack node
loop = @line "for ", @name(name), " = ", @value({"explist", unpack bounds}), " do"
with @block loop
\declare {name}
\stms block
-- for x in y ...
-- {"foreach", {names...}, {exp...}, body}
foreach: (node) =>
_, names, exps, block = unpack node
loop = with @line!
\append "for "
with @block loop
loop\append_list [\name name, false for name in *names], ", "
loop\append " in "
loop\append_list [@value exp for exp in *exps], ","
loop\append " do"
\declare names
\stms block
export: (node) =>
_, names = unpack node
if type(names) == "string"
if names == "*"
@export_all = true
elseif names == "^"
@export_proper = true
else
@declare names
nil
run: (code) =>
code\call self
nil
group: (node) =>
@stms node[2]
do: (node) =>
with @block!
\stms node[2]
noop: => -- nothing!
}
| 21.978417 | 86 | 0.546318 |
e066cd5b01d939b3cb4da25df923a07dea6272fe | 10,228 | script_name="Perspective"
script_description="Zeght's perspective.py but in moonscript by Alendt, with a few tweaks from Zahuczky"
script_author=""
script_version="1.1.1"
class Point
new: (@x, @y, @z) =>
if @z == nil
@z = 0
repr: () =>
if math.abs(@z) > 1e5
@x, @y, @z
else
@x, @y
add: (p) =>
return Point @x + p.x, @y + p.y, @z + p.z
sub: (p) =>
return Point @x - p.x, @y - p.y, @z - p.z
length: =>
return math.sqrt @x^2 + @y^2 + @z^2
rot_y: (a) =>
rot_v = Point @x * math.cos(a) - @z * math.sin(a), @y, @x * math.sin(a) + @z * math.cos(a)
return rot_v
rot_x: (a) =>
rot_v = Point @x, @y * math.cos(a) + @z * math.sin(a), -@y * math.sin(a) + @z * math.cos(a)
return rot_v
rot_z: (a) =>
rot_v = Point @x * math.cos(a) + @y * math.sin(a), -@x * math.sin(a) + @y * math.cos(a), @z
return rot_v
mul: (m) =>
return Point @x * m, @y * m, @z * m
vector = (a, b) ->
return Point b.x - a.x, b.y - a.y, b.z - a.z
vec_pr = (a, b) ->
return Point a.y * b.z - a.z * b.y, -a.x * b.z + a.z * b.x, a.x * b.y - a.y * b.x
sc_pr = (a, b) ->
return a.x*b.x + a.y*b.y + a.z*b.z
dist = (a, b) ->
return a\sub(b)\length!
round = (val, n) ->
if n
return math.floor((val * 10^n) + 0.5) / (10^n)
else
return math.floor(val+0.5)
intersect = (l1, l2) ->
if vec_pr(vector(l1[1], l1[2]), vector(l2[1], l2[2]))\length! == 0
return l1[1]\add(vector(l1[1], l1[2])\mul(1e30))
else
d = ((l1[1].x - l1[2].x)*(l2[1].y - l2[2].y) - (l1[1].y - l1[2].y)*(l2[1].x-l2[2].x))
x = (vec_pr(l1[1], l1[2]).z*(l2[1].x-l2[2].x) - vec_pr(l2[1], l2[2]).z*(l1[1].x-l1[2].x))
y = (vec_pr(l1[1], l1[2]).z*(l2[1].y-l2[2].y) - vec_pr(l2[1], l2[2]).z*(l1[1].y-l1[2].y))
x /= d
y /= d
return Point x, y
unrot = (coord_in, org, diag, get_rot) -> --diag=true, get_rot=false
screen_z = 312.5
shift = org\mul(-1)
coord = [c\add(shift) for c in *coord_in]
center = intersect({coord[1], coord[3]}, {coord[2], coord[4]})
center = Point(center.x, center.y, screen_z)
rays = [Point(c.x, c.y, screen_z) for c in *coord]
f = {}
for i = 0, 1
vp1 = vec_pr(rays[1 + i], center)\length!
vp2 = vec_pr(rays[3 + i], center)\length!
a = rays[1 + i]
c = rays[3 + i]\mul(vp1/vp2)
m = a\add(c)\mul(0.5)
r = center.z/m.z
a = a\mul(r)
c = c\mul(r)
table.insert(f, a)
table.insert(f, c)
a, c, b, d = f[1], f[2], f[3], f[4]
ratio = math.abs(dist(a, b) / dist(a, d))
diag_diff = (dist(a, c) - dist(b, d)) / (dist(a, c) + dist(b, d))
n = vec_pr(vector(a,b), vector(a,c))
n0 = vec_pr(vector(rays[1], rays[2]), vector(rays[1], rays[3]))
if sc_pr(n, n0) > 0 export flip = 1 else export flip = -1
if not get_rot
if diag return diag_diff else return ratio
if flip < 0
return nil
fry = math.atan(n.x/n.z)
s = ""
export debfry = round((-fry / math.pi * 180), 2)
s = s.."\\fry"..debfry
rot_n = n\rot_y(fry)
frx = -math.atan(rot_n.y/rot_n.z)
if n0.z < 0
frx += math.pi
export debfrx = round((-frx / math.pi * 180), 2)
s = s.."\\frx"..debfrx
n = vector(a, b)
ab_unrot = vector(a, b)\rot_y(fry)\rot_x(frx)
ac_unrot = vector(a, c)\rot_y(fry)\rot_x(frx)
ad_unrot = vector(a, d)\rot_y(fry)\rot_x(frx)
frz = math.atan2(ab_unrot.y, ab_unrot.x)
export debfrz = round((-frz / math.pi * 180), 2)
s = s.."\\frz"..debfrz
ad_unrot = ad_unrot\rot_z(frz)
fax = ad_unrot.x/ad_unrot.y
if math.abs(fax) > 0.01
s = s.."\\fax"..round(fax, 2)
return s
binary_search = (f, l, r, eps) ->
fl = f(l)
fr = f(r)
if fl <= 0 and fr >= 0
export op = (a, b) ->
if a > b
return true
else
return false
elseif fl >= 0 and fr <= 0
export op = (a, b) ->
if a < b
return true
else
return false
else
return nil
while (r - l > eps)
c = (l + r) / 2
if op(f(c), 0)
r = c
else
l = c
return (l + r) / 2
find_ex = (f, coord) ->
w_center = {0, 0}
w_size = 100000.0
iterations = math.floor(math.log(w_size * 100) / math.log(4))
s = 4
for k = 0, iterations-1
res = {}
for i = -s, s-1
x = w_center[1] + w_size*i/10
for j = -s, s-1
y = w_center[2] + w_size*j/10
table.insert(res, {unrot(coord, Point(x, y), true, false), x, y})
export ex = f(res)
w_center = {ex[2], ex[3]}
w_size = w_size / 3
return Point(ex[2], ex[3])
zero_on_ray = (coord, center, v, a, eps) ->
vrot = v\rot_z(a)
f = (x) ->
p = vrot\mul(x)\add(center)
return unrot(coord, p, true, false)
l = binary_search(f, 0, (center\length! + 1000000) / v\length!, eps)
if l == nil
return nil
p = vrot\mul(l)\add(center)
ratio = unrot(coord, p, false, false)
r = unrot(coord, p, true, false)
if r == nil
return nil
else
return p, ratio
find_rot = (t, n, t_center) ->
for i = 1, n
table.insert(t[i], dist(t_center, t[i][2]))
m = t[1][4]
r = t[1]
for i = 1, n
if m > t[i][4]
m = t[i][4]
r = t[i]
return r[1], r[2], r[3]
find_mn_point = (t) ->
j = 1
for k, v in pairs(t)
if t[j] != nil
j += 1
else break
rs = t[1][1]
rl = t[1]
for i = 1, j-1
if rs > t[i][1]
rs = t[i][1]
rl = t[i]
return rl
find_mx_point = (t) ->
j = 1
for k, v in pairs(t)
if t[j] != nil
j += 1
else break
rs = t[1][1]
rl = t[1]
for i = 1, j-1
if rs < t[i][1]
rs = t[i][1]
rl = t[i]
return rl
count_e = (t) ->
e = 0
for i = 1, 100
if t[i] != nil
e += 1
else break
return e
perspective = (line, tr_org, tr_center, tr_ratio) ->
clip = line.text\match("clip%b()")
if clip == nil
aegisub.log("\\clip missing")
coord = {}
for cx, cy in clip\gmatch("([-%d.]+).([-%d.]+)")
table.insert(coord, Point(cx, cy))
mn_point = find_ex(find_mn_point, coord)
mx_point = find_ex(find_mx_point, coord)
target_ratio = dist(coord[1], coord[2])/dist(coord[1], coord[4])
c = mn_point\add(mx_point)\mul(0.5)
v = mn_point\sub(mx_point)\rot_z(math.pi / 2)\mul(100000)
inf_p = c\add(v)
if unrot(coord, inf_p, true, false) > 0
mn_center = true
export center = mn_point
export other = mx_point
else
mn_center = false
export center = mx_point
export other = mn_point
v = other\sub(center)
rots = {}
steps = 100
for i = 0, steps-1
a = 2 * math.pi * i / steps
zero = {}
zero[1], zero[2] = zero_on_ray(coord, center, v, a, 1e-02)
if zero[1] != nil
p, ratio = zero[1], zero[2]
table.insert(rots, {ratio, p, a})
if tr_org
if line.text\match("org%b()")
export pos_org = line.text\match("org%b()")
elseif line.text\match("pos%b()")
export pos_org = line.text\match("pos%b()")
else
aegisub.log("\\org or \\pos missing")
aegisub.cancel!
px, py = pos_org\match("([-%d.]+).([-%d.]+)")
target_org = Point(px, py)
tf_tags = unrot(coord, target_org, true, true)
if tf_tags == nil
aegisub.log(tf_tags)
else
return ""..tf_tags
if count_e(rots) == 0
aegisub.log("No proper perspective found.")
aegisub.cancel!
if tr_center
t_center = coord[1]\add(coord[2])\add(coord[3])\add(coord[4])\mul(0.25)
ratio, p, a = find_rot(rots, count_e(rots), t_center)
tf_tags = unrot(coord, p, true, true)
if tf_tags == nil
aegisub.log(tf_tags)
else
return "\\org("..round(p.x, 1)..","..round(p.y, 1)..")"..tf_tags
if tr_ratio
segs = {}
for i = 0, count_e(rots)-1
if i == 0
i2 = count_e(rots)
if (rots[i2-1][1] - target_ratio) * (rots[i+1][1] - target_ratio) <= 0
table.insert(segs, {rots[i2-1][3], rots[i+1][3]})
elseif i == 1
i2 = 2
if (rots[i2-1][1] - target_ratio) * (rots[i+1][1] - target_ratio) <= 0
table.insert(segs, {rots[i2-1][3], rots[i+1][3]})
else
if (rots[i][1] - target_ratio) * (rots[i+1][1] - target_ratio) <= 0
table.insert(segs, {rots[i][3], rots[i+1][3]})
for i = 1, count_e(segs)
seg = {}
seg = {segs[i][1], segs[i][2]}
f = (x) ->
t_res = {}
t_res[1], t_res[2] = zero_on_ray(coord, center, v, x, 1e-05)
if t_res[1] != nil
p, ratio = t_res[1], t_res[2]
return (ratio - target_ratio)
else
return 1e7
a = binary_search(f, seg[1], seg[2], 1e-04)
if a == nil then
a = seg[1]
p, ratio = zero_on_ray(coord, center, v, a, 1e-05)
tf_tags = unrot(coord, p, true, true)
if tf_tags != nil
return "\\org("..round(p.x, 1)..","..round(p.y, 1)..")"..tf_tags
delete_old_tag = (line) ->
line.text = line.text\gsub("\\frx([-%d.]+)", "")\gsub("\\fry([-%d.]+)", "")\gsub("\\frz([-%d.]+)", "")\gsub("\\org%b()", "")\gsub("\\fax([-%d.]+)", "")\gsub("\\fay([-%d.]+)", "")
return line.text
warn_for_large_transforms = (frx, fry, frz) ->
WARN_MIRRORED = "Uh-oh! Seems like your text was mirrored! Are you sure that's what you wanted? Here's a reminder: You need to draw your clip in a manner, where the first point of your clip is the upper left, then going clockwise from there."
WARN_ROTATED = "Uh-oh! Seems like your text was rotated a lot! Are you sure that's what you wanted? Here's a reminder: You need to draw your clip in a manner, where the first point of your clip is the upper left, then going clockwise from there."
if fry > 90 and fry < 270 aegisub.debug.out(WARN_MIRRORED)
elseif fry > -270 and fry < -90 aegisub.debug.out(WARN_MIRRORED)
elseif frx > 90 and frx < 270 aegisub.debug.out(WARN_MIRRORED)
elseif frx > -270 and frx < -90 aegisub.debug.out(WARN_MIRRORED)
elseif frz > 90 or frz < -90 aegisub.debug.out(WARN_ROTATED)
-- wrapper/factory function to bake in boolean flags
_perspective = (tr_org, tr_center, tr_ratio) -> (line) ->
perspective line, tr_org, tr_center, tr_ratio
_main = (sub, sel, pers) ->
for si, li in ipairs(sel)
line = sub[li]
result = pers(line)
line.text = delete_old_tag(line)
line.text = line.text\gsub("\\clip", result.."\\clip")
sub[li] = line
warn_for_large_transforms debfrx, debfry, debfrz
aegi1 = (sub, sel) ->
_main sub, sel, _perspective(true, false, false)
aegi2 = (sub, sel) ->
_main sub, sel, _perspective(false, true, false)
aegi3 = (sub, sel) ->
_main sub, sel, _perspective(false, false, true)
aegisub.register_macro("Perspective/Transform for target org", "Transform for target org", aegi1)
aegisub.register_macro("Perspective/Transforms near center of tetragon", "Transforms near center of tetragon", aegi2)
aegisub.register_macro("Perspective/Transforms with target ratio", "Transforms with target ratio", aegi3)
| 26.293059 | 247 | 0.583496 |
5a4e97116784237c50a86191c5fec642b3f19f80 | 6,329 | class Option
-- If optType is a "bool" or an "int", @value is the boolean/integer value of the option.
-- Additionally, when optType is an "int":
-- - opts.step specifies the step on which the values are changed.
-- - opts.min specifies a minimum value for the option.
-- - opts.max specifies a maximum value for the option.
-- - opts.altDisplayNames is a int->string dict, which contains alternative display names
-- for certain values.
-- If optType is a "list", @value is the index of the current option, inside opts.possibleValues.
-- opts.possibleValues is a array in the format
-- {
-- {value, displayValue}, -- Display value can be omitted.
-- {value}
-- }
-- setValue will be called for the constructor argument.
new: (optType, displayText, value, opts) =>
@optType = optType
@displayText = displayText
@opts = opts
@value = 1
self\setValue(value)
-- Whether we have a "previous" option (for left key)
hasPrevious: =>
switch @optType
when "bool"
return true
when "int"
if @opts.min
return @value > @opts.min
else
return true
when "list"
return @value > 1
-- Analogous of hasPrevious.
hasNext: =>
switch @optType
when "bool"
return true
when "int"
if @opts.max
return @value < @opts.max
else
return true
when "list"
return @value < #@opts.possibleValues
leftKey: =>
switch @optType
when "bool"
@value = not @value
when "int"
@value -= @opts.step
if @opts.min and @opts.min > @value
@value = @opts.min
when "list"
@value -= 1 if @value > 1
rightKey: =>
switch @optType
when "bool"
@value = not @value
when "int"
@value += @opts.step
if @opts.max and @opts.max < @value
@value = @opts.max
when "list"
@value += 1 if @value < #@opts.possibleValues
getValue: =>
switch @optType
when "bool"
return @value
when "int"
return @value
when "list"
{value, _} = @opts.possibleValues[@value]
return value
setValue: (value) =>
switch @optType
when "bool"
@value = value
when "int"
-- TODO Should we obey opts.min/max? Or just trust the script to do the right thing(tm)?
@value = value
when "list"
set = false
for i, possiblePair in ipairs @opts.possibleValues
{possibleValue, _} = possiblePair
if possibleValue == value
set = true
@value = i
break
if not set
msg.warn("Tried to set invalid value #{value} to #{@displayText} option.")
getDisplayValue: =>
switch @optType
when "bool"
return @value and "yes" or "no"
when "int"
if @opts.altDisplayNames and @opts.altDisplayNames[@value]
return @opts.altDisplayNames[@value]
else
return "#{@value}"
when "list"
{value, displayValue} = @opts.possibleValues[@value]
return displayValue or value
draw: (ass, selected) =>
if selected
ass\append("#{bold(@displayText)}: ")
else
ass\append("#{@displayText}: ")
-- left arrow unicode
ass\append("◀ ") if self\hasPrevious!
ass\append(self\getDisplayValue!)
-- right arrow unicode
ass\append(" ▶") if self\hasNext!
ass\append("\\N")
class EncodeOptionsPage extends Page
new: (callback) =>
@callback = callback
@currentOption = 1
-- TODO this shouldn't be here.
scaleHeightOpts =
possibleValues: {{-1, "no"}, {240}, {360}, {480}, {720}, {1080}, {1440}, {2160}}
filesizeOpts =
step: 250
min: 0
altDisplayNames:
[0]: "0 (constant quality)"
crfOpts =
step: 1
min: -1
altDisplayNames:
[-1]: "disabled"
fpsOpts =
possibleValues: {{-1, "source"}, {15}, {24}, {30}, {48}, {50}, {60}, {120}, {240}}
-- I really dislike hardcoding this here, but, as said below, order in dicts isn't
-- guaranteed, and we can't use the formats dict keys.
formatIds = {"webm-vp8", "webm-vp9", "mp4", "mp4-nvenc", "raw", "mp3", "gif"}
formatOpts =
possibleValues: [{fId, formats[fId].displayName} for fId in *formatIds]
-- This could be a dict instead of a array of pairs, but order isn't guaranteed
-- by dicts on Lua.
@options = {
{"output_format", Option("list", "Output Format", options.output_format, formatOpts)}
{"twopass", Option("bool", "Two Pass", options.twopass)},
{"apply_current_filters", Option("bool", "Apply Current Video Filters", options.apply_current_filters)}
{"scale_height", Option("list", "Scale Height", options.scale_height, scaleHeightOpts)},
{"strict_filesize_constraint", Option("bool", "Strict Filesize Constraint", options.strict_filesize_constraint)},
{"write_filename_on_metadata", Option("bool", "Write Filename on Metadata", options.write_filename_on_metadata)},
{"target_filesize", Option("int", "Target Filesize", options.target_filesize, filesizeOpts)},
{"crf", Option("int", "CRF", options.crf, crfOpts)},
{"fps", Option("list", "FPS", options.fps, fpsOpts)},
}
@keybinds =
"LEFT": self\leftKey
"RIGHT": self\rightKey
"UP": self\prevOpt
"DOWN": self\nextOpt
"ENTER": self\confirmOpts
"ESC": self\cancelOpts
getCurrentOption: =>
return @options[@currentOption][2]
leftKey: =>
(self\getCurrentOption!)\leftKey!
self\draw!
rightKey: =>
(self\getCurrentOption!)\rightKey!
self\draw!
prevOpt: =>
@currentOption = math.max(1, @currentOption - 1)
self\draw!
nextOpt: =>
@currentOption = math.min(#@options, @currentOption + 1)
self\draw!
confirmOpts: =>
for _, optPair in ipairs @options
{optName, opt} = optPair
-- Set the global options object.
options[optName] = opt\getValue!
self\hide!
self.callback(true)
cancelOpts: =>
self\hide!
self.callback(false)
draw: =>
window_w, window_h = mp.get_osd_size()
ass = assdraw.ass_new()
ass\new_event()
self\setup_text(ass)
ass\append("#{bold('Options:')}\\N\\N")
for i, optPair in ipairs @options
opt = optPair[2]
opt\draw(ass, @currentOption == i)
ass\append("\\N▲ / ▼: navigate\\N")
ass\append("#{bold('ENTER:')} confirm options\\N")
ass\append("#{bold('ESC:')} cancel\\N")
mp.set_osd_ass(window_w, window_h, ass.text)
| 29.03211 | 117 | 0.622689 |
49bb59c0fa72fd773c11a9651f07bdb589631ee1 | 20,440 | -- Copyright 2012-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
import app, activities, breadcrumbs, Buffer, command, config, bindings, bundle, interact, signal, mode, Project from howl
import ActionBuffer, JournalBuffer, ProcessBuffer, BufferPopup, StyledText from howl.ui
import Process from howl.io
serpent = require 'serpent'
get_project_root = ->
buffer = app.editor and app.editor.buffer
file = buffer.file or buffer.directory
error "No file associated with the current view" unless file
project = Project.get_for_file file
error "No project associated with #{file}" unless project
return project.root
belongs_to_project = (buffer, project_root) ->
file = buffer.file or buffer.directory
return false unless file
project = Project.for_file file
return false unless project
return project.root == project_root
command.register
name: 'quit',
description: 'Quit the application'
handler: -> howl.app\quit!
command.alias 'quit', 'q'
command.register
name: 'save-and-quit',
description: 'Save modified buffers and quit the application'
handler: ->
with howl.app
\quit! if \save_all!
command.alias 'save-and-quit', 'wq'
command.register
name: 'quit-without-save',
description: 'Quit the application, disregarding any modified buffers'
handler: -> howl.app\quit true
command.alias 'quit-without-save', 'q!'
command.register
name: 'run'
description: 'Run a command'
handler: command.run
command.register
name: 'new-buffer',
description: 'Opens a new buffer'
handler: ->
breadcrumbs.drop!
app.editor.buffer = howl.app\new_buffer!
command.register
name: 'switch-buffer',
description: 'Switch to another buffer'
input: interact.select_buffer
handler: (buf) ->
breadcrumbs.drop!
app.editor.buffer = buf
command.register
name: 'project-switch-buffer',
description: 'Switch to another buffer in current project'
input: ->
project_root = get_project_root!
return unless project_root
interact.select_buffer
get_buffers: -> [buf for buf in *app.buffers when belongs_to_project buf, project_root]
title: "Buffers under #{project_root}"
handler: (buf) ->
breadcrumbs.drop!
app.editor.buffer = buf
command.register
name: 'buffer-reload',
description: 'Reload the current buffer from file'
handler: ->
buffer = app.editor.buffer
if buffer.modified
unless interact.yes_or_no prompt: 'Buffer is modified, reload anyway? '
log.info "Not reloading; buffer is untouched"
return
buffer\reload true
log.info "Buffer reloaded from file"
command.register
name: 'switch-to-last-hidden-buffer',
description: 'Switch to the last active hidden buffer'
handler: ->
for buffer in *howl.app.buffers
if not buffer.showing
breadcrumbs.drop!
app.editor.buffer = buffer
return
_G.log.error 'No hidden buffer found'
command.register
name: 'set',
description: 'Set a configuration variable'
input: interact.get_variable_assignment
handler: (variable_assignment) ->
target = variable_assignment.target
target[variable_assignment.var] = variable_assignment.value
_G.log.info ('"%s" is now set to "%s" for %s')\format variable_assignment.var, variable_assignment.value, variable_assignment.scope_name
command.register
name: 'describe-key',
description: 'Show information for a key'
handler: ->
buffer = ActionBuffer!
buffer.title = 'Key watcher'
buffer\append 'Press any key to show information for it (press escape to quit)..\n\n', 'string'
editor = howl.app\add_buffer buffer
editor.cursor\eof!
bindings.capture (event, source, translations) ->
buffer.lines\delete 3, #buffer.lines
buffer\append 'Key translations (usable from bindings):\n', 'comment'
buffer\append serpent.block translations, comment: false
buffer\append '\n\nKey event:\n', 'comment'
buffer\append serpent.block event, comment: false
bound_commands = {}
for t in *translations
cmd = bindings.action_for t
cmd = '<function>' if typeof(cmd) == 'function'
bound_commands[t] = cmd
buffer\append '\n\nBound command:\n', 'comment'
buffer\append serpent.block bound_commands, comment: false
if event.key_name == 'escape'
buffer.lines[1] = '(Snooping done, close this buffer at your leisure)'
buffer\style 1, #buffer, 'comment'
buffer.modified = false
else
return false
command.register
name: 'describe-signal',
description: 'Describe a given signal'
input: interact.select_signal
handler: (signal_name) ->
def = signal.all[signal_name]
error "Unknown signal '#{signal_name}'" unless def
buffer = with ActionBuffer!
.title = "Signal: #{signal_name}"
\append "#{def.description}\n\n"
\append "Parameters:"
params = def.parameters
if not params
buffer\append "None"
else
buffer\append '\n\n'
buffer\append StyledText.for_table [ { name, desc } for name, desc in pairs params ], {
{ header: 'Name', style: 'string'},
{ header: 'Description', style: 'comment' }
}
buffer.read_only = true
buffer.modified = false
howl.app\add_buffer buffer
command.register
name: 'bundle-unload'
description: 'Unload a specified bundle'
input: interact.select_loaded_bundle
handler: (name) ->
log.info "Unloading bundle '#{name}'.."
bundle.unload name
log.info "Unloaded bundle '#{name}'"
command.register
name: 'bundle-load'
description: 'Load a specified, currently unloaded, bundle'
input: interact.select_unloaded_bundle
handler: (name) ->
log.info "Loading bundle '#{name}'.."
bundle.load_by_name name
log.info "Loaded bundle '#{name}'"
command.register
name: 'bundle-reload'
description: 'Reload a specified bundle'
input: interact.select_loaded_bundle
handler: (name) ->
log.info "Reloading bundle '#{name}'.."
bundle.unload name if _G.bundles[name]
bundle.load_by_name name
log.info "Reloaded bundle '#{name}'"
command.register
name: 'bundle-reload-current'
description: 'Reload the last active bundle (with files open)'
handler: ->
for buffer in *app.buffers
bundle_name = buffer.file and bundle.from_file(buffer.file) or nil
if bundle_name
command.bundle_reload bundle_name
return
log.warn 'Could not find any currently active bundle to reload'
command.register
name: 'buffer-grep'
description: 'Show buffer lines containing boundary and exact matches in real time'
input: ->
command_line = app.window.command_line
command_line\add_keymap
binding_for: ['buffer-grep']: -> command_line\switch_to 'buffer-grep-regex'
command_line\add_help
key_for: 'buffer-grep'
action: 'Switch to regular expression search'
buffer = app.editor.buffer
return interact.select_line
title: "Buffer grep in #{buffer.title}"
editor: app.editor
lines: buffer.lines
handler: (selection) ->
breadcrumbs.drop!
app.editor.cursor\move_to line: selection.line.nr, column: selection.column
command.register
name: 'buffer-grep-exact'
description: 'Show buffer lines containing exact matches in real time'
input: ->
command_line = app.window.command_line
command_line\add_keymap
binding_for: ['buffer-grep']: -> command_line\switch_to 'buffer-grep'
command_line\add_help
key_for: 'buffer-grep'
action: 'Switch to default search'
buffer = app.editor.buffer
return interact.select_line
title: "Buffer grep exact in #{buffer.title}"
editor: app.editor
lines: buffer.lines
find: (query, text) ->
start_pos, end_pos = text\ufind query, 1, true
if start_pos
return {{start_pos, end_pos - start_pos + 1}}
handler: (selection) ->
breadcrumbs.drop!
app.editor.cursor\move_to line: selection.line.nr, column: selection.column
command.register
name: 'buffer-grep-regex'
description: 'Show buffer lines containing regular expression matches in real time'
input: ->
command_line = app.window.command_line
command_line\add_keymap
binding_for: ['buffer-grep']: -> command_line\switch_to 'buffer-grep-exact'
command_line\add_help
key_for: 'buffer-grep'
action: 'Switch to exact search'
buffer = app.editor.buffer
return interact.select_line
title: "Buffer grep regex in #{buffer.title}"
editor: app.editor
lines: buffer.lines
find: (query, text) ->
ok, rex = pcall -> r(query)
return unless ok
start_pos, end_pos = rex\find text
if start_pos
return {{start_pos, end_pos - start_pos + 1}}
handler: (selection) ->
breadcrumbs.drop!
app.editor.cursor\move_to line: selection.line.nr, column: selection.column
command.register
name: 'buffer-structure'
description: 'Show the structure for the current buffer'
input: ->
buffer = app.editor.buffer
lines = buffer.mode\structure app.editor
cursor_lnr = app.editor.cursor.line
local selected_line
for line in *lines
if line.nr <= cursor_lnr
selected_line = line
if line.nr >= cursor_lnr
break
return interact.select_line
title: "Structure for #{buffer.title}"
:lines
:selected_line
handler: (selection) ->
breadcrumbs.drop!
app.editor.cursor\move_to line: selection.line.nr, column: selection.column
command.register
name: 'navigate-back'
description: 'Goes back to the last location recorded'
handler: ->
if breadcrumbs.previous
breadcrumbs.go_back!
log.info "navigate: now at #{breadcrumbs.location} of #{#breadcrumbs.trail}"
else
log.info "No previous location recorded"
command.register
name: 'navigate-forward'
description: 'Goes to the next location recorced'
handler: ->
if breadcrumbs.next
breadcrumbs.go_forward!
log.info "navigate: now at #{breadcrumbs.location} of #{#breadcrumbs.trail}"
else
log.info "No next location recorded"
command.register
name: 'navigate-go-to'
description: 'Goes to a specific location in the history'
input: ->
to_item = (crumb, i) ->
{:buffer_marker, :file} = crumb
buffer = buffer_marker and buffer_marker.buffer
project = file and Project.for_file(file)
where = if project
file\relative_to_parent(project.root)
elseif file
file.path
else
buffer.title
pos = breadcrumbs.crumb_pos crumb
{
i,
project and project.root.basename or ''
"#{where}@#{pos}"
:buffer, :file, :pos
}
crumbs = breadcrumbs.trail
items = [to_item(b, i) for i, b in ipairs crumbs]
if #items == 0
log.warn "No locations available for navigation"
return nil
selected = interact.select_location
title: "Navigate back to.."
:items
selection: items[breadcrumbs.location] or items[breadcrumbs.location - 1]
columns: {
{ header: 'Position', style: 'number' },
{ header: 'Project', style: 'key' },
{ header: 'Path', style: 'string' }
}
selected and selected.selection
handler: (loc) ->
return unless loc
breadcrumbs.location = loc[1]
command.register
name: 'open-journal'
description: 'Opens the Howl log journal'
handler: ->
app\add_buffer JournalBuffer!
app.editor.cursor\eof!
-----------------------------------------------------------------------
-- Howl eval commands
-----------------------------------------------------------------------
do_howl_eval = (load_f, mode_name, transform_f) ->
editor = app.editor
text = editor.selection.empty and editor.current_line.text or editor.selection.text
text = transform_f and transform_f(text) or text
f = assert load_f text
ret = { pcall f }
if ret[1]
out = ''
for i = 2, #ret
out ..= "\n#{serpent.block ret[i], comment: false}"
if editor.popup
log.info "(Eval) => #{ret[2]}"
else
buf = Buffer mode.by_name mode_name
buf.text = "-- Howl eval (#{mode_name}) =>#{out}"
editor\show_popup BufferPopup buf, scrollable: true
howl.clipboard.push out
else
log.error "(ERROR) => #{ret[2]}"
command.register
name: 'howl-lua-eval'
description: 'Eval the current line or selection as Lua'
handler: ->
do_howl_eval load, 'lua', (text) ->
unless text\match 'return%s'
text = if text\find '\n'
text\gsub "\n([^\n]+)$", "\n return %1"
else
"return #{text}"
text
command.register
name: 'howl-moon-eval'
description: 'Eval the current line or selection as Moonscript'
handler: ->
moonscript = require('moonscript')
transform = (text) ->
initial_indent = text\match '^([ \t]*)%S'
if initial_indent -- remove the initial indent from all lines if any
lines = [l\gsub("^#{initial_indent}", '') for l in text\gmatch('[^\n]+')]
text = table.concat lines, '\n'
moonscript.loadstring text
do_howl_eval transform, 'moonscript'
command.register
name: 'howl-moon-print'
description: 'Compile and show the Lua for the current buffer or selection'
handler: ->
moonscript = require('moonscript.base')
editor = app.editor
buffer = editor.buffer
title = "#{buffer.title} (compiled to Lua)"
text = buffer.text
unless editor.selection.empty
title = "#{buffer.title} (Lua - from selection)"
text = editor.selection.text
lua, err = moonscript.to_lua text
local buf
if not lua
buf = ActionBuffer!
buf\append howl.ui.markup.howl "<error>#{err}</error>"
else
buf = Buffer mode.by_name 'lua'
buf.text = lua
buf.title = title
buf.modified = false
if #buf.lines > 20
breadcrumbs.drop!
editor.buffer = buf
else
buf\insert "-- #{title}\n", 1
editor\show_popup BufferPopup buf, scrollable: true
-----------------------------------------------------------------------
-- Launch commands
-----------------------------------------------------------------------
launch_cmd = (working_directory, cmd) ->
shell = howl.sys.env.SHELL or '/bin/sh'
p = Process {
:cmd,
:shell,
read_stdout: true,
read_stderr: true,
working_directory: working_directory,
}
breadcrumbs.drop!
buffer = ProcessBuffer p
editor = app\add_buffer buffer
editor.cursor\eof!
buffer\pump!
get_project = ->
buffer = app.editor and app.editor.buffer
file = buffer.file or buffer.directory
error "No file associated with the current view" unless file
project = Project.get_for_file file
error "No project associated with #{file}" unless project
return project
command.register
name: 'project-exec',
description: 'Run an external command from within the project directory'
input: -> interact.get_external_command path: get_project!.root
handler: launch_cmd
command.register
name: 'project-build'
description: 'Run the command in config.project_build_command from within the project directory'
handler: -> launch_cmd get_project!.root, (app.editor and app.editor.buffer.config or config).project_build_command
command.register
name: 'exec',
description: 'Run an external command'
input: (path=nil) -> interact.get_external_command :path
handler: launch_cmd
command.register
name: 'save-config'
description: 'Save the current configuration'
handler: ->
config.save_config!
log.info 'Configuration saved'
config.define
name: 'project_build_command'
description: 'The command to execute when project-build is run'
default: 'make'
type_of: 'string'
-----------------------------------------------------------------------
-- File search commands
-----------------------------------------------------------------------
config.define
name: 'file_search_hit_display'
description: 'How to display file search hits in the list'
default: 'rich'
type_of: 'string'
options: -> {
{'plain', 'Display as plain unicolor strings'},
{'highlighted', 'Highlight search terms in hits'} ,
{'rich', 'Show syntax highlighted snippets with highlighted terms'},
}
file_search_hit_mt = {
__tostyled: (item) ->
text = item.text
m = mode.for_file(item.match.file)
if m and m.lexer
styles = m.lexer(text)
return StyledText text, styles
text
__tostring: (item) -> item.text
}
file_search_hit_to_location = (match, search, display_as) ->
hit_display = if display_as == 'rich'
setmetatable {text: match.message, :match}, file_search_hit_mt
else
match.message
path = match.path\truncate(50, omission_prefix: '..')
loc = {
howl.ui.markup.howl "<comment>#{path}</>:<number>#{match.line_nr}</>"
hit_display,
file: match.file,
line_nr: match.line_nr,
column: match.column
}
search = search.ulower
s, e = match.message.ulower\ufind(search, 1, true)
unless s
s, e = match.message\ufind((r(search)))
if loc.column
loc.highlights = {
{ byte_start_column: loc.column, byte_end_column: loc.column + #search }
}
elseif s
loc.highlights = {
{ start_column: s, end_column: e + 1 }
}
if s and display_as != 'plain'
loc.item_highlights = {
nil,
{
{byte_start_column: s, count: e - s + 1}
}
}
loc
do_search = (search, whole_word) ->
project = get_project!
file_search = howl.file_search
matches, searcher = file_search.search project.root, search, :whole_word
unless #matches > 0
log.error "No matches found for '#{search}'"
return matches
matches = file_search.sort matches, project.root, search, app.editor.current_context
display_as = project.config.file_search_hit_display
status = "Loaded 0 out of #{#matches} locations.."
cancel = false
locations = activities.run {
title: "Loading #{#matches} locations..",
status: -> status
cancel: -> cancel = true
}, ->
return for i = 1, #matches
if i % 1000 == 0
break if cancel
status = "Loaded #{i} out of #{#matches}.."
activities.yield!
m = matches[i]
file_search_hit_to_location(m, search, display_as)
locations, searcher, project
command.register
name: 'project-file-search',
description: 'Searches files in the the current project'
input: (...) ->
editor = app.editor
search = nil
whole_word = false
unless app.window.command_line.showing
if editor.selection.empty
search = app.editor.current_context.word.text
whole_word = true unless search.is_empty
else
search = editor.selection.text
if not search or search.is_empty
search = interact.read_text!
if not search or search.is_empty
log.warn "No search query specified"
return
locations, searcher, project = do_search search, whole_word
if #locations > 0
selected = interact.select_location
title: "#{#locations} matches for '#{search}' in #{project.root.short_path} (using #{searcher.name} searcher)"
items: locations
selected and selected.selection
handler: (loc) ->
if loc
app\open loc
command.register
name: 'project-file-search-list',
description: 'Searches files in the the current project, listing results in a buffer'
input: (...) ->
editor = app.editor
search = nil
whole_word = false
unless app.window.command_line.showing
if editor.selection.empty
search = app.editor.current_context.word.text
whole_word = true unless search.is_empty
else
search = editor.selection.text
if not search or search.is_empty
search = interact.read_text!
if not search or search.is_empty
log.warn "No search query specified"
return
locations, searcher, project = do_search search , whole_word
if #locations > 0
matcher = howl.util.Matcher locations
list = howl.ui.List matcher
list_buf = howl.ui.ListBuffer list, {
title: "#{#locations} matches for '#{search}' in #{project.root.short_path} (using #{searcher.name} searcher)"
on_submit: (location) ->
app\open location
}
list_buf.directory = project.root
app\add_buffer list_buf
nil
handler: (loc) ->
| 29.580318 | 140 | 0.659198 |
0bd036bff7e692bc33d43082af833bcf64890c1f | 880 | -- Copyright 2014-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
ffi = require 'ffi'
jit = require 'jit'
require 'ljglibs.cdefs.gtk'
core = require 'ljglibs.core'
gobject = require 'ljglibs.gobject'
C, cast = ffi.C, ffi.cast
gc_ptr = gobject
provider_p = ffi.typeof 'GtkStyleProvider *'
jit.off true, true
core.define 'GtkStyleContext', {
new: -> gc_ptr C.gtk_style_context_new!
add_provider_for_screen: (screen, provider, priority) ->
C.gtk_style_context_add_provider_for_screen screen, cast(provider_p, provider), priority
add_class: (cls) => C.gtk_style_context_add_class @, cls
remove_class: (cls) => C.gtk_style_context_remove_class @, cls
get_background_color: (state) =>
rgba = ffi.new 'GdkRGBA'
C.gtk_style_context_get_background_color @, state, rgba
rgba
}, (spec) -> spec.new!
| 27.5 | 92 | 0.735227 |
e4b7b8eb39f7ef187c6a5d645b759f00e6a6bbcd | 143 | listFold = zb2rhbksBjR3yFP98YrEGss6Yv7wVCgNbYtWiwz9nGRSAoiAa
big =>
(listFold big {
val: x => xs => (if (gtn x 0) 1 xs)
end: 0
})
| 17.875 | 60 | 0.636364 |
08d3378895050974e38333a8e3270087caaf76ab | 2,460 | html2unicode = require'html'
math = require'math'
an = [[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789,.?!"'`()[]{}<>&_]]
ci = 'ⒶⒷⒸⒹⒺⒻⒼⒽⒾⒿⓀⓁⓂⓃⓄⓅⓆⓇⓈⓉⓊⓋⓌⓍⓎⓏⓐⓑⓒⓓⓔⓕⓖⓗⓘⓙⓚⓛⓜⓝⓞⓟⓠⓡⓢⓣⓤⓥⓦⓧⓨⓩ⓪①②③④⑤⑥⑦⑧⑨'
bl = '𝔄𝔅ℭ𝔇𝔈𝔉𝔊ℌℑ𝔍𝔎𝔏𝔐𝔑𝔒𝔓𝔔ℜ𝔖𝔗𝔘𝔙𝔚𝔛𝔜ℨ𝔞𝔟𝔠𝔡𝔢𝔣𝔤𝔥𝔦𝔧𝔨𝔩𝔪𝔫𝔬𝔭𝔮𝔯𝔰𝔱𝔲𝔳𝔴𝔵𝔶𝔷'
ud = [[∀BƆDƎℲפHIſK˥WNOԀQRS┴∩ΛMX⅄Zɐqɔpǝɟƃɥᴉɾʞlɯuodbɹsʇnʌʍxʎz0ƖᄅƐㄣϛ9ㄥ86'˙¿¡,,,)(][}{><⅋‾]]
an2ci = {}
-- Circled letters are 3 bytes, just use sub string
for i=1, #an
f = i*3+1-3
t = i*3
an2ci[an\sub(i,i)] = ci\sub(f, t)
an2bl = {}
i=1
-- Since blackletters have varying byte length, use the common lua pattern to find multibyte chars
for uchar in string.gfind(bl, "([%z\1-\127\194-\244][\128-\191]*)")
an2bl[an\sub(i,i)] = uchar
i = i +1
an2ud = {}
i=1
for uchar in string.gfind(ud, "([%z\1-\127\194-\244][\128-\191]*)")
an2ud[an\sub(i,i)] = uchar
i = i +1
codepoints = (str) ->
str\gmatch("[%z\1-\127\194-\244][\128-\191]*")
unichr = (n) ->
html2unicode('&#x%x;'\format(n))
wireplace = (offset, arg) ->
s = arg or ''
t = {}
for i = 1, #s
bc = string.byte(s, i, i)
-- Replace space width ideographic space for fullwidth offset
if bc == 32 and offset == 0xFEE0
t[#t + 1] = '\227\128\128'
elseif bc == 32
t[#t + 1] = ' '
elseif bc < 0x80 then
t[#t + 1] = html2unicode("&#" .. (offset + bc) .. ";")
else
t[#t + 1] = s\sub(i, i)
table.concat(t, "")
remap = (map, s) ->
table.concat [map[s\sub(i,i)] or s\sub(i,i) for i=1, #s], ''
zalgo = (text, intensity=50) ->
zalgo_chars = {}
for i=0x0300, 0x036f
zalgo_chars[i-0x2ff] = unichr(i)
zalgo_chars[#zalgo_chars + 1] = unichr(0x0488)
zalgo_chars[#zalgo_chars + 0] = unichr(0x0489)
zalgoized = {}
for letter in codepoints(text)
zalgoized[#zalgoized + 1] = letter
zalgo_num = math.random(1, intensity)
for i=1, zalgo_num
zalgoized[#zalgoized + 1] = zalgo_chars[math.random(1, #zalgo_chars)]
table.concat(zalgoized)
PRIVMSG:
'^%pwide (.+)$': (source, destination, arg) =>
say wireplace(0xFEE0, arg)
'^%pblackletter (.+)$': (source, destination, arg) =>
say remap(an2bl, arg)
'^%pcircled (.+)$': (source, destination, arg) =>
say remap(an2ci, arg)
'^%pzalgo (.+)$': (source, destination, arg) =>
say zalgo(arg, 10)
'^%pupsidedown (.+)$': (source, destination, arg) =>
say remap(an2ud, arg)
'^%pflip (.+)$': (source, destination, arg) =>
say remap(an2ud, arg)
| 28.604651 | 98 | 0.578862 |
9d44bb7356e215732179b46644c048a38e62d055 | 5,205 | fs = require "fs"
insert = table.insert
describe 'fs', ->
tmpdir = '/tmp/spook-fs-spec'
after_each ->
fs.rm_rf tmpdir
it 'mkdir_p creates directory structures', ->
fs.mkdir_p tmpdir .. '/my/dir/structure'
assert.true fs.is_dir tmpdir .. '/my/dir/structure'
it 'is_dir returns true for en existing directory and false if not a dir or missing', ->
assert.false fs.is_dir tmpdir
fs.mkdir_p tmpdir
assert.true fs.is_dir tmpdir
it 'is_file returns true for en existing file and false if not a file or missing', ->
fs.mkdir_p tmpdir
assert.false fs.is_file tmpdir
assert.false fs.is_file tmpdir .. '/myfile.txt'
f = assert io.open(tmpdir .. '/myfile.txt', "w")
f\write "hello"
f\close!
assert.true fs.is_file tmpdir .. '/myfile.txt'
it 'is_present returns true for either files or directories', ->
fs.mkdir_p tmpdir
f = assert io.open(tmpdir .. '/myfile.txt', "w")
f\write "hello"
f\close!
assert.true fs.is_present tmpdir
assert.true fs.is_present tmpdir .. '/myfile.txt'
it 'rm_rf removes directory structures', ->
fs.mkdir_p tmpdir .. '/my/dir/structure'
assert.true fs.is_dir tmpdir .. '/my/dir/structure'
fs.rm_rf tmpdir
assert.false fs.is_dir tmpdir
describe 'dirtree', ->
it 'dirtree by default yields only the contents of specified dir', ->
fs.mkdir_p tmpdir .. '/my/dir/structure'
contents = {}
for entry in fs.dirtree tmpdir
insert contents, entry
assert.same {
tmpdir .. '/my'
}, contents
it 'dirtree yields contents of a directory structure recursively when specified', ->
fs.mkdir_p tmpdir .. '/my/dir/structure'
f = assert(io.open(tmpdir .. '/my/dir/file.txt', "w"))
f\write("spec")
f\close!
contents = {}
for entry in fs.dirtree tmpdir, true
insert contents, entry
expected = {
tmpdir .. '/my',
tmpdir .. '/my/dir',
tmpdir .. '/my/dir/structure',
tmpdir .. '/my/dir/file.txt'
}
table.sort(expected)
table.sort(contents)
assert.same expected, contents
it 'dirtree yields contents of a directory recursively, ignoring given patterns when specified', ->
fs.mkdir_p tmpdir .. '/my/dir/structure'
f = assert(io.open(tmpdir .. '/my/dir/file.txt', "w"))
f\write("spec")
f\close!
f = assert(io.open(tmpdir .. '/my/dir/.hidden.txt', "w"))
f\write("hidden")
f\close!
contents = {}
for entry in fs.dirtree tmpdir, true
insert contents, entry
expected = {
tmpdir .. '/my',
tmpdir .. '/my/dir',
tmpdir .. '/my/dir/structure',
tmpdir .. '/my/dir/file.txt'
tmpdir .. '/my/dir/.hidden.txt'
}
table.sort(expected)
table.sort(contents)
assert.same expected, contents
contents = {}
for entry in fs.dirtree tmpdir, recursive: true, ignore: {'^%.hidden%.txt$'}
insert contents, entry
expected = {
tmpdir .. '/my',
tmpdir .. '/my/dir',
tmpdir .. '/my/dir/structure',
tmpdir .. '/my/dir/file.txt'
}
table.sort(expected)
table.sort(contents)
assert.same expected, contents
describe 'name_ext', ->
it 'returns the filename and extension as two parameters', ->
name, ext = fs.name_ext('my/file.dot.ext')
assert.equal 'my/file.dot', name
assert.equal '.ext', ext
it 'returns the filename and nil when file has no extension', ->
name, ext = fs.name_ext('my/file')
assert.equal 'my/file', name
assert.nil ext
describe 'basename', ->
it 'returns the filename without the path', ->
basename = fs.basename('/path/to/my/file.dot.ext')
assert.equal 'file.dot.ext', basename
basename = fs.basename('path/to/my/file.dot.ext')
assert.equal 'file.dot.ext', basename
basename = fs.basename('file.dot.ext')
assert.equal 'file.dot.ext', basename
describe 'dirname', ->
it 'returns the directory containing the given path', ->
dirname = fs.dirname('/path/to/my/file.dot.ext')
assert.equal '/path/to/my', dirname
dirname = fs.dirname('path/to/my/file.dot.ext')
assert.equal 'path/to/my', dirname
dirname = fs.dirname('/path/to/my/')
assert.equal '/path/to', dirname
dirname = fs.dirname('file.dot.ext')
assert.equal '.', dirname
describe 'unique_subtrees', ->
it 'descends all given paths and returns unique directories found', ->
fs.mkdir_p tmpdir .. '/my/dir/a/b/c/a/b/c/d'
fs.mkdir_p tmpdir .. '/my/dir/a/b/c/b/c/d/e'
fs.mkdir_p tmpdir .. '/my/dir/a/b/c/c/d/e/f'
fs.mkdir_p tmpdir .. '/my/dir/a/b/c/d/e/f/g'
basedir = tmpdir .. '/my/dir'
trees = fs.unique_subtrees({
basedir,
basedir .. '/a/b',
basedir .. '/a/b/c',
basedir .. '/a/b/c/a',
basedir .. '/a/b/c/b',
basedir .. '/a/b/c/c',
basedir .. '/a/b/c/d'
})
treemap = {name, true for name in *trees}
unique_trees = [name for name in pairs treemap]
assert.equal 20, #trees
assert.equal #unique_trees, #trees | 32.329193 | 103 | 0.598655 |
8d971254be8e2e395c9e2fddbddeacd8e332d26f | 842 | import Graphic from require "LunoPunk.Graphic"
import Image from require "LunoPunk.graphics.Image"
class Rect extends Graphic
new: (width, height, color = 0xFFFFFF) =>
super!
@__width = width
@__height = height
@__color = color
createImage @
-- TODO renderMode
render: (point, camera) =>
@__point.x = point.x + @x
@__point.y = point.y + @y
@__img\render @__point, camera
createImage = =>
@__img = Image.createRect @__width, @__height, @__color
width: (value) =>
return @__width if value == nil or value == @__width
@__width = value
@__img = createImage @
height: (value) =>
return @__height if value == nil or value == @__height
@__height = value
@__img = createImage @
color: (value) =>
return @__color if value == nil or value == @__color
@__color = value
@__img = createImage @
{ :Rect }
| 22.157895 | 57 | 0.66152 |
2f101243e8e6bac584f86c90e436660cfd5735b4 | 1,191 |
import default_environment from require "lapis.cmd.util"
local popper
-- force code to run in environment, sets up db to execute queries
push = (name_or_env, overrides) ->
assert name_or_env, "missing name or env for push"
config_module = require("lapis.config")
old_getter = config_module.get
env = if type(name_or_env) == "table"
name_or_env
else
old_getter name_or_env
if overrides
env = setmetatable overrides, __index: env
config_module.get = (...) ->
if ...
old_getter ...
else
env
old_popper = popper
popper = ->
config_module.get = old_getter
popper = old_popper
pop = ->
assert(popper, "no environment pushed")!
-- assert_env "test", { for: "feature name", exact: true }
assert_env = (env, opts={}) ->
config = require("lapis.config").get!
pat = if opts.exact
"^#{env}$"
else
"^#{env}"
unless config._name\match pat
suffix = "(#{pat}), you are in `#{config._name}`"
msg = if feature = opts.for
"`#{feature}` can only be run in `#{env}` environment #{suffix}"
else
"aborting, exepcting `#{env}` environment #{suffix}"
error msg
true
{ :push, :pop, :assert_env }
| 21.267857 | 70 | 0.63644 |
1b70dfd3c830caef771ccc7089b12afc56d60bc9 | 1,070 |
class String
startsWith: (value, prefix) ->
value\sub(1, #prefix) == prefix
ends_with: (value, suffix) ->
value\sub(#value + 1 - #suffix) == suffix
split: (value, sep) ->
[x for x in string.gmatch(value, "([^#{sep}]+)")]
join: (separator, list) ->
result = ''
for item in *list
if #result != 0
result ..= separator
result ..= tostring(item)
return result
char_at: (value, index) ->
return value\sub(index, index)
_add_escape_chars: (value) ->
-- gsub is not ideal in cases where we want to do a literal
-- replace, so to do this just escape all special characters with '%'
value = value\gsub("[%(%)%.%%%+%-%*%?%[%]%^%$]", "%%%0")
-- Note that we don't put this all in the return statement to avoid
-- forwarding the multiple return values causing subtle errors
return value
index_of: (haystack, needle) ->
result = haystack\find(String._add_escape_chars(needle))
return result
replace: (value, old, new) ->
return value\gsub(String._add_escape_chars(old), new)
| 28.157895 | 73 | 0.615888 |
fc5fc9a93c63c91a8bb3023a2f530718b4a95405 | 26,515 |
--
-- Copyright (C) 2017-2020 DBotThePony
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
-- of the Software, and to permit persons to whom the Software is furnished to do so,
-- subject to the following conditions:
-- The above copyright notice and this permission notice shall be included in all copies
-- or substantial portions of the Software.
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
-- INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
-- PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
-- FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-- OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-- DEALINGS IN THE SOFTWARE.
net = DLib.net
class PPM2.NetworkChangeState
new: (key = '', keyValid = '', newValue, obj, refValue) =>
@key = key
@keyValid = keyValid
@oldValue = obj[key]
@newValue = newValue
@refValue = refValue
@obj = obj
@objID = obj.netID
@cantApply = false
@networkChange = true
GetValueRef: =>
return @newValue if @refValue == nil
return @refValue
GetPlayer: => @ply
ChangedByClient: => not @networkChange or IsValid(@ply)
ChangedByPlayer: => not @networkChange or IsValid(@ply)
ChangedByServer: => not @networkChange or not IsValid(@ply)
GetKey: => @keyValid
GetVariable: => @keyValid
GetVar: => @keyValid
GetKeyInternal: => @key
GetVariableInternal: => @key
GetVarInternal: => @key
GetNewValue: => @newValue
GetValue: => @newValue
GetCantApply: => @cantApply
SetCantApply: (val) => @cantApply = val
NewValue: => @newValue
GetOldValue: => @oldValue
OldValue: => @oldValue
GetObject: => @obj
GetNWObject: => @obj
GetNetworkedObject: => @obj
GetLength: => @rlen
GetRealLength: => @len
ChangedByNetwork: => @networkChange
Revert: => @obj[@key] = @oldValue if not @cantApply
Apply: => @obj[@key] = @newValue if not @cantApply
Notify: =>
return unless @obj.NETWORKED and (CLIENT and @obj.ent == LocalPlayer() or SERVER)
net.Start(PPM2.NetworkedPonyData.NW_Modify)
net.WriteUInt32(@obj\GetNetworkID())
{:id, :writeFunc} = PPM2.NetworkedPonyData\GetVarInfo(@key)
net.WriteUInt16(id)
writeFunc(@newValue)
net.SendToServer() if CLIENT
net.Broadcast() if SERVER
rFloat = (min = 0, max = 255) ->
return -> math.Clamp(net.ReadFloat(), min, max)
wFloat = net.WriteFloat
rBool = net.ReadBool
wBool = net.WriteBool
if PPM2.NetworkedPonyData and PPM2.NetworkedPonyData.REGISTRY
REGISTRY = PPM2.NetworkedPonyData.REGISTRY
nullify = ->
for _, ent in ipairs ents.GetAll()
if ent.__PPM2_PonyData and ent.__PPM2_PonyData.Remove
ProtectedCall -> ent.__PPM2_PonyData\Remove()
for _, ent in ipairs ents.GetAll()
ent.__PPM2_PonyData = nil
for key, obj in pairs(REGISTRY)
if obj.Remove
ProtectedCall -> obj\Remove()
nullify()
_NW_NextObjectID = PPM2.NetworkedPonyData and PPM2.NetworkedPonyData.NW_NextObjectID or 0
_NW_NextObjectID_CL = PPM2.NetworkedPonyData and PPM2.NetworkedPonyData.NW_NextObjectID_CL or 0x70000000
_NW_WaitID = PPM2.NetworkedPonyData and PPM2.NetworkedPonyData.NW_WaitID or -1
class PPM2.NetworkedPonyData extends PPM2.ModifierBase
@REGISTRY = {}
@GetVarInfo: (strName) => @NW_VarsTable[strName] or false
@AddNetworkVar = (getName = 'Var', readFunc = (->), writeFunc = (->), defValue, enum_runtime_map) =>
defFunc = defValue
defFunc = (-> defValue) if type(defValue) ~= 'function'
strName = "_NW_#{getName}"
@NW_NextVarID += 1
id = @NW_NextVarID
tab = {:strName, :readFunc, :getName, :writeFunc, :defValue, :defFunc, :id}
table.insert(@NW_Vars, tab)
@NW_VarsTable[id] = tab
@NW_VarsTable[strName] = tab
@__base[strName] = defFunc()
@__base["Get#{getName}"] = => @[strName]
@__base["Get#{getName}Ref"] = => @[strName]
if enum_runtime_map
@__base["Get#{getName}"] = => enum_runtime_map[@[strName]]
tab.writeMapped = (val, ...) ->
if isstring(val)
setvalue = val
i = val
val = enum_runtime_map[val]
refvalue = val
error('No such enum value ' .. i) if val == nil
if isnumber(val)
refvalue = val
setvalue = enum_runtime_map[val]
error('No such enum index ' .. val) if enum_runtime_map[val] == nil
writeFunc(val, ...)
else
tab.writeMapped = writeFunc
@__base["Set#{getName}"] = (val = defFunc(), networkNow = true) =>
local refvalue, setvalue
if enum_runtime_map
if isstring(val)
setvalue = val
i = val
val = enum_runtime_map[val]
refvalue = val
error('No such enum value ' .. i) if val == nil
if isnumber(val)
refvalue = val
setvalue = enum_runtime_map[val]
error('No such enum index ' .. val) if enum_runtime_map[val] == nil
else
setvalue = val
oldVal = @[strName]
@[strName] = val
state = PPM2.NetworkChangeState(strName, getName, setvalue, @, refvalue)
state.networkChange = false
@SetLocalChange(state)
return unless networkNow and @NETWORKED and (CLIENT and @ent == LocalPlayer() or SERVER)
net.Start(@@NW_Modify)
net.WriteUInt32(@GetNetworkID())
net.WriteUInt16(id)
writeFunc(val)
net.SendToServer() if CLIENT
net.Broadcast() if SERVER
@__base["Set#{getName}Safe"] = (val = defFunc(), networkNow = true) =>
local refvalue, setvalue
if enum_runtime_map
if isstring(val)
setvalue = val
i = val
val = enum_runtime_map[val]
val = 1 if val == nil
refvalue = val
if isnumber(val)
val = 1 if enum_runtime_map[val] == nil
setvalue = enum_runtime_map[val]
refvalue = val
else
setvalue = val
oldVal = @[strName]
@[strName] = val
state = PPM2.NetworkChangeState(strName, getName, setvalue, @, refvalue)
state.networkChange = false
@SetLocalChange(state)
return unless networkNow and @NETWORKED and (CLIENT and @ent == LocalPlayer() or SERVER)
net.Start(@@NW_Modify)
net.WriteUInt32(@GetNetworkID())
net.WriteUInt16(id)
writeFunc(val)
net.SendToServer() if CLIENT
net.Broadcast() if SERVER
@GetSet = (fname, fvalue) =>
@__base["Get#{fname}"] = => @[fvalue]
@__base["Set#{fname}"] = (fnewValue = @[fvalue]) =>
oldVal = @[fvalue]
@[fvalue] = fnewValue
state = PPM2.NetworkChangeState(fvalue, fname, fnewValue, @)
state.networkChange = false
@SetLocalChange(state)
if CLIENT
hook.Add 'OnEntityCreated', 'PPM2.NW_WAIT', (ent) -> timer.Simple 0, ->
return if not IsValid(ent)
return if not @REGISTRY[ent\EntIndex()]
return if @REGISTRY[ent\EntIndex()].done_setup or IsValid(@REGISTRY[ent\EntIndex()].ent)
@REGISTRY[ent\EntIndex()]\SetupEntity(ent)
hook.Add 'NotifyShouldTransmit', 'PPM2.NW_WAIT', (ent, should) ->
return if not should
return if not @REGISTRY[ent\EntIndex()]
return if @REGISTRY[ent\EntIndex()].done_setup or IsValid(@REGISTRY[ent\EntIndex()].ent)
@REGISTRY[ent\EntIndex()]\SetupEntity(ent)
-- clientside entities
hook.Add 'EntityRemoved', 'PPM2.NW_WAIT', (ent) -> @REGISTRY[ent]\Remove() if @REGISTRY[ent]
@OnNetworkedCreated = (ply = NULL, len = 0, nwobj) =>
if CLIENT
netID = net.ReadUInt32()
entid = net.ReadUInt16()
obj = @Get(netID) or @(netID, entid)
@REGISTRY[entid] = obj
obj.NETWORKED = true
obj.CREATED_BY_SERVER = true
obj.SHOULD_NETWORK = true
obj\ReadNetworkData()
return
ply[@NW_CooldownTimer] = ply[@NW_CooldownTimer] or 0
ply[@NW_CooldownTimerCount] = ply[@NW_CooldownTimerCount] or 0
if ply[@NW_CooldownTimer] < RealTimeL()
ply[@NW_CooldownTimerCount] = 1
ply[@NW_CooldownTimer] = RealTimeL() + 10
else
ply[@NW_CooldownTimerCount] += 1
if ply[@NW_CooldownTimerCount] >= 3
ply[@NW_CooldownMessage] = ply[@NW_CooldownMessage] or 0
if ply[@NW_CooldownMessage] < RealTimeL()
PPM2.Message 'Player ', ply, " is creating #{@__name} too quickly!"
ply[@NW_CooldownMessage] = RealTimeL() + 1
return
waitID = net.ReadUInt32()
obj = @(nil, ply)
obj.SHOULD_NETWORK = true
obj\ReadNetworkData()
obj\Create()
net.Start(@NW_ReceiveID)
net.WriteUInt32(waitID)
net.WriteUInt32(obj.netID)
net.Send(ply)
@OnNetworkedModify = (ply = NULL, len = 0) =>
id = net.ReadUInt32()
obj = @Get(id)
if not obj or IsValid(ply) and obj.ent ~= ply
return if CLIENT
net.Start(@NW_Rejected)
net.WriteUInt32(id)
net.Send(ply)
return
varID = net.ReadUInt16()
varData = @NW_VarsTable[varID]
return unless varData
{:strName, :getName, :readFunc, :writeFunc} = varData
newVal = readFunc()
return if newVal == obj["Get#{getName}"](obj)
state = PPM2.NetworkChangeState(strName, getName, newVal, obj)
state\Apply()
obj\NetworkDataChanges(state)
return if CLIENT
net.Start(@NW_Modify)
net.WriteUInt32(id)
net.WriteUInt16(varID)
writeFunc(newVal)
net.SendOmit(ply)
@OnNetworkedDelete = (ply = NULL, len = 0) =>
id = net.ReadUInt32()
obj = @Get(id)
return unless obj
obj\Remove(true)
@ReadNetworkData = =>
output = {strName, {getName, readFunc()} for _, {:getName, :strName, :readFunc} in ipairs @NW_Vars}
return output
@RenderTasks = {}
@CheckTasks = {}
@Get = (nwID) => @NW_Objects[nwID] or false
@NW_Vars = {}
@NW_VarsTable = {}
@NW_Objects = {}
@O_Slots = {} if CLIENT
@NW_Waiting = {}
@NW_WaitID = _NW_WaitID
@NW_NextVarID = -1
@NW_Create = 'PPM2.NW.Created'
@NW_Modify = 'PPM2.NW.Modified'
@NW_Broadcast = 'PPM2.NW.ModifiedBroadcast'
@NW_Remove = 'PPM2.NW.Removed'
@NW_Rejected = 'PPM2.NW.Rejected'
@NW_ReceiveID = 'PPM2.NW.ReceiveID'
@NW_CooldownTimerCount = 'ppm2_NW_CooldownTimerCount'
@NW_CooldownTimer = 'ppm2_NW_CooldownTimer'
@NW_CooldownMessage = 'ppm2_NW_CooldownMessage'
@NW_NextObjectID = _NW_NextObjectID
@NW_NextObjectID_CL = _NW_NextObjectID_CL
if SERVER
net.pool(@NW_Create)
net.pool(@NW_Modify)
net.pool(@NW_Remove)
net.pool(@NW_ReceiveID)
net.pool(@NW_Rejected)
net.pool(@NW_Broadcast)
net.Receive @NW_Create, (len = 0, ply = NULL, obj) -> @OnNetworkedCreated(ply, len, obj)
net.Receive @NW_Modify, (len = 0, ply = NULL, obj) -> @OnNetworkedModify(ply, len, obj)
net.Receive @NW_Remove, (len = 0, ply = NULL, obj) -> @OnNetworkedDelete(ply, len, obj)
if SERVER
net.ReceiveAntispam(@NW_Create)
net.ReceiveAntispam(@NW_Remove)
net.Receive @NW_ReceiveID, (len = 0, ply = NULL) ->
return if SERVER
waitID = net.ReadUInt32()
netID = net.ReadUInt32()
obj = @NW_Waiting[waitID]
@NW_Waiting[waitID] = nil
return unless obj
obj.NETWORKED = true
@NW_Objects[obj.netID] = nil
obj.netID = netID
obj.waitID = nil
@NW_Objects[netID] = obj
net.Receive @NW_Rejected, (len = 0, ply = NULL) ->
return if SERVER
netID = net.ReadUInt32()
obj = @Get(netID)
return if not obj or obj.__LastReject and obj.__LastReject > RealTimeL()
obj.__LastReject = RealTimeL() + 3
obj.NETWORKED = false
obj\Create()
net.Receive @NW_Broadcast, (len = 0, ply = NULL) ->
return if SERVER
netID = net.ReadUInt32()
obj = @NW_Objects[netID]
return unless obj
obj\ReadNetworkData(len, ply)
@GetSet('UpperManeModel', 'm_upperManeModel')
@GetSet('LowerManeModel', 'm_lowerManeModel')
@GetSet('TailModel', 'm_tailModel')
@GetSet('SocksModel', 'm_socksModel')
@GetSet('HornModel', 'm_hornmodel')
@GetSet('ClothesModel', 'm_clothesmodel')
@GetSet('NewSocksModel', 'm_newSocksModel')
@GetSet('IrisSizeInternal', '_NW_IrisSizeInternal')
@AddNetworkVar('DisableTask', rBool, wBool, false)
@AddNetworkVar('UseFlexLerp', rBool, wBool, true)
@AddNetworkVar('FlexLerpMultiplier', rFloat(0, 10), wFloat, 1)
@SetupModifiers: =>
for key, value in SortedPairs PPM2.PonyDataRegistry
if value.modifiers
@RegisterModifier(key, 0, 0)
@SetModifierMinMaxFinal(key, value.min, value.max) if value.min or value.max
@SetupLerpTables(key)
strName = '_NW_' .. key
funcLerp = 'Calculate' .. key
@__base['Get' .. key] = => @[funcLerp](@, @[strName])
@RegisterModifier('IrisSizeInternal', 0, 0)
@SetupLerpTables('IrisSizeInternal')
@__base['GetIrisSizeInternal'] = => @CalculateIrisSizeInternal(@_NW_IrisSizeInternal)
for key, value in SortedPairs PPM2.PonyDataRegistry
@AddNetworkVar(key, value.read, value.write, value.default, value.enum_runtime_map)
new: (netID, ent) =>
super()
@m_upperManeModel = NULL
@m_lowerManeModel = NULL
@m_tailModel = NULL
@m_socksModel = NULL
@m_newSocksModel = NULL
@_NW_IrisSizeInternal = 0
@lastLerpThink = RealTimeL()
@recomputeTextures = true
@isValid = true
@removed = false
@valid = true
@NETWORKED = false
@SHOULD_NETWORK = false
@[data.strName] = data.defFunc() for _, data in ipairs @@NW_Vars when data.defFunc
if SERVER
@netID = @@NW_NextObjectID
@@NW_NextObjectID += 1
else
netID = -1 if netID == nil
@netID = netID
@@NW_Objects[@netID] = @
if CLIENT
for i = 1, 1024
if not @@O_Slots[i]
@slotID = i
@@O_Slots[i] = @
break
error('no more free pony data edicts') if not @slotID
@entID = isnumber(ent) and ent or ent\EntIndex()
ent = Entity(ent) if isnumber(ent)
@SetupEntity(ent) if IsValid(ent)
GetEntity: => @ent or NULL
IsValid: => @isValid
GetModel: => @modelCached
EntIndex: => @entID
ObjectSlot: => @slotID
GetObjectSlot: => @slotID
Clone: (target = @ent) =>
copy = @@(nil, target)
@ApplyDataToObject(copy)
return copy
SetupEntity: (ent) =>
if getdata = @@REGISTRY[ent]
return if getdata\GetOwner() and IsValid(getdata\GetOwner()) and getdata\GetOwner() ~= ent
getdata\Remove() if getdata.Remove and getdata ~= @
return unless IsValid(ent)
if getdata = @@REGISTRY[ent\EntIndex()]
return if getdata\GetOwner() and IsValid(getdata\GetOwner()) and getdata\GetOwner() ~= ent
getdata\Remove() if getdata.Remove and getdata ~= @
@ent = ent
@done_setup = true
ent\SetPonyData(@)
@entTable = @ent\GetTable()
@modelCached = ent\GetModel()
ent\PPMBonesModifier()
@flightController = PPM2.PonyflyController(@) if not @flightController
@entID = ent\EntIndex()
@lastLerpThink = RealTimeL()
@ModelChanges(@modelCached, @modelCached)
@Reset()
timer.Simple(0, -> @GetRenderController()\CompileTextures() if @GetRenderController()) if CLIENT
@@RenderTasks = [task for i, task in pairs @@NW_Objects when task\IsValid() and IsValid(task.ent) and not task.ent\IsPlayer() and not task\GetDisableTask()]
@@CheckTasks = [task for i, task in pairs @@NW_Objects when task\IsValid() and IsValid(task.ent) and not task\GetDisableTask()]
ModelChanges: (old = @ent\GetModel(), new = old) =>
@modelCached = new
@ent\SetNW2Bool('ppm2_fly', false)
timer.Simple 0.5, ->
return unless IsValid(@ent)
@Reset()
GenericDataChange: (state) =>
hook.Run 'PPM2_PonyDataChanges', @ent, @, state
if state\GetKey() == 'DisableTask'
@@RenderTasks = [task for i, task in pairs @@NW_Objects when task\IsValid() and IsValid(task.ent) and not task.ent\IsPlayer() and not task\GetDisableTask()]
@@CheckTasks = [task for i, task in pairs @@NW_Objects when task\IsValid() and IsValid(task.ent) and not task\GetDisableTask()]
@GetSizeController()\DataChanges(state) if @ent and @GetBodygroupController()
@GetBodygroupController()\DataChanges(state) if @ent and @GetBodygroupController()
@GetWeightController()\DataChanges(state) if @ent and @GetWeightController()
if CLIENT and @ent
@GetRenderController()\DataChanges(state) if @GetRenderController()
ResetScale: =>
if scale = @GetSizeController()
scale\ResetScale()
ModifyScale: =>
if scale = @GetSizeController()
scale\ModifyScale()
GetIsEditor: => @is_editor_data or false
SetIsEditor: (value = false) => @is_editor_data = value
Reset: =>
if scale = @GetSizeController()
scale\Reset()
if CLIENT
@GetWeightController()\Reset() if @GetWeightController() and @GetWeightController().Reset
@GetRenderController()\Reset() if @GetRenderController() and @GetRenderController().Reset
@GetBodygroupController()\Reset() if @GetBodygroupController() and @GetBodygroupController().Reset
GetHoofstepVolume: =>
return 0.8 if @ShouldMuffleHoosteps()
return 1
ShouldMuffleHoosteps: =>
return @GetSocksAsModel() or @GetSocksAsNewModel()
PlayerRespawn: =>
return if not IsValid(@ent)
@entTable.__cachedIsPony = @ent\IsPony()
if not @entTable.__cachedIsPony
return if @alreadyCalledRespawn
@alreadyCalledRespawn = true
@alreadyCalledDeath = true
else
@alreadyCalledRespawn = false
@alreadyCalledDeath = false
@ApplyBodygroups(CLIENT, true)
@ent\SetNW2Bool('ppm2_fly', false)
@ent\PPMBonesModifier()
if scale = @GetSizeController()
scale\PlayerRespawn()
if weight = @GetWeightController()
weight\PlayerRespawn()
if CLIENT
@deathRagdollMerged = false
@GetRenderController()\PlayerRespawn() if @GetRenderController()
@GetBodygroupController()\MergeModels(@ent) if IsValid(@ent) and @GetBodygroupController().MergeModels
PlayerDeath: =>
return if not IsValid(@ent)
if @ent.__ppmBonesModifiers
@ent.__ppmBonesModifiers\Remove()
@entTable.__cachedIsPony = @ent\IsPony()
if not @entTable.__cachedIsPony
return if @alreadyCalledDeath
@alreadyCalledDeath = true
else
@alreadyCalledDeath = false
@ent\SetNW2Bool('ppm2_fly', false)
if scale = @GetSizeController()
scale\PlayerDeath()
if weight = @GetWeightController()
weight\PlayerDeath()
if CLIENT
@DoRagdollMerge()
@GetRenderController()\PlayerDeath() if @GetRenderController()
DoRagdollMerge: =>
return if @deathRagdollMerged
bgController = @GetBodygroupController()
rag = @ent\GetRagdollEntity()
if not bgController.MergeModels
@deathRagdollMerged = true
elseif IsValid(rag)
@deathRagdollMerged = true
bgController\MergeModels(rag)
ApplyBodygroups: (updateModels = CLIENT) => @GetBodygroupController()\ApplyBodygroups(updateModels) if @ent
SetLocalChange: (state) => @GenericDataChange(state)
NetworkDataChanges: (state) => @GenericDataChange(state)
GetPonyRaceFlags: =>
switch @GetRace()
when 'EARTH'
return 0
when 'PEGASUS'
return PPM2.RACE_HAS_WINGS
when 'UNICORN'
return PPM2.RACE_HAS_HORN
when 'ALICORN'
return PPM2.RACE_HAS_HORN + PPM2.RACE_HAS_WINGS
SlowUpdate: =>
@GetBodygroupController()\SlowUpdate() if @GetBodygroupController()
@GetWeightController()\SlowUpdate() if @GetWeightController()
if scale = @GetSizeController()
scale\SlowUpdate()
if SERVER and IsValid(@ent) and @ent\IsPlayer()
arms = @ent\GetHands()
if IsValid(arms)
cond = @GetPonyRaceFlags()\band(PPM2.RACE_HAS_HORN) ~= 0 and @ent\GetInfoBool('ppm2_cl_vm_magic_hands', true) and PPM2.HAND_BODYGROUP_MAGIC or PPM2.HAND_BODYGROUP_HOOVES
arms\SetBodygroup(PPM2.HAND_BODYGROUP_ID, cond)
Think: =>
RenderScreenspaceEffects: =>
time = RealTimeL()
delta = time - @lastLerpThink
@lastLerpThink = time
if @isValid and IsValid(@ent)
for change in *@TriggerLerpAll(delta * 5)
state = PPM2.NetworkChangeState('_NW_' .. change[1], change[1], change[2] + @['_NW_' .. change[1]], @)
state\SetCantApply(true)
@GenericDataChange(state)
GetFlightController: => @flightController
GetRenderController: =>
return @renderController if SERVER or not @isValid or not @modelCached
if not @renderController or @modelRender ~= @modelCached
@modelRender = @modelCached
cls = PPM2.GetRenderController(@modelCached)
return @renderController if @renderController and cls == @renderController.__class
@renderController\Remove() if @renderController
@renderController = cls(@)
return @renderController
GetWeightController: =>
return @weightController if not @isValid or not @modelCached
if not @weightController or @modelWeight ~= @modelCached
@modelWeight = @modelCached
cls = PPM2.GetPonyWeightController(@modelCached)
return @weightController if @weightController and cls == @weightController.__class
@weightController\Remove() if @weightController
@weightController = cls(@)
return @weightController
GetSizeController: =>
return @scaleController if not @isValid or not @modelCached
if not @scaleController or @modelScale ~= @modelCached
@modelScale = @modelCached
cls = PPM2.GetSizeController(@modelCached)
return @scaleController if @scaleController and cls == @scaleController.__class
@scaleController\Remove() if @scaleController
@scaleController = cls(@)
return @scaleController
GetScaleController: => @GetSizeController()
GetBodygroupController: =>
return @bodygroups if not @isValid or not @modelCached
if not @bodygroups or @modelBodygroups ~= @modelCached
@modelBodygroups = @modelCached
cls = PPM2.GetBodygroupController(@modelCached)
return @bodygroups if @bodygroups and cls == @bodygroups.__class
@bodygroups\Remove() if @bodygroups
@bodygroups = cls(@)
@bodygroups.ent = @ent
return @bodygroups
Remove: (byClient = false) =>
@removed = true
@@NW_Objects[@netID] = nil if SERVER or @NETWORKED
@@O_Slots[@slotID] = nil if @slotID and @@O_Slots[@slotID] == @
@isValid = false
@ent = @GetEntity() if not IsValid(@ent)
@@REGISTRY[@ent] = nil if IsValid(@ent) and @@REGISTRY[@ent] == @
@@REGISTRY[@entID] = nil if @@REGISTRY[@entID] == @
@GetWeightController()\Remove() if @GetWeightController()
if CLIENT
@GetRenderController()\Remove() if @GetRenderController()
if IsValid(@ent) and @ent.__ppm2_task_hit
@entTable.__ppm2_task_hit = false
@ent\SetNoDraw(false)
@GetBodygroupController()\Remove() if @GetBodygroupController()
@GetSizeController()\Remove() if @GetSizeController()
@flightController\Switch(false) if @flightController
@@RenderTasks = [task for i, task in pairs @@NW_Objects when task\IsValid() and IsValid(task.ent) and not task.ent\IsPlayer() and not task\GetDisableTask()]
@@CheckTasks = [task for i, task in pairs @@NW_Objects when task\IsValid() and IsValid(task.ent) and not task\GetDisableTask()]
if SERVER and @NETWORKED
net.Start('PPM2.PonyDataRemove')
net.WriteUInt32(@netID)
net.Broadcast()
__tostring: => "[#{@@__name}:#{@netID}|#{@ent}]"
GetOwner: => @ent
IsNetworked: => @NETWORKED
ShouldNetwork: => @SHOULD_NETWORK
SetShouldNetwork: (val = @NETWORKED) => @SHOULD_NETWORK = val
IsLocal: => @isLocal
IsLocalObject: => @isLocal
GetNetworkID: => @netID
NetworkID: => @netID
NetID: => @netID
ComputeMagicColor: =>
color = @GetHornMagicColor()
if not @GetSeparateMagicColor()
if not @GetSeparateEyes()
color = @GetEyeIrisTop()\Lerp(0.5, @GetEyeIrisBottom())
else
lerpLeft = @GetEyeIrisTopLeft()\Lerp(0.5, @GetEyeIrisBottomLeft())
lerpRight = @GetEyeIrisTopRight()\Lerp(0.5, @GetEyeIrisBottomRight())
color = lerpLeft\Lerp(0.5, lerpRight)
return color
ReadNetworkData: (len = 24, ply = NULL, silent = false, applyEntities = true) =>
data = @@ReadNetworkData()
validPly = IsValid(ply)
states = [PPM2.NetworkChangeState(key, keyValid, newVal, @) for key, {keyValid, newVal} in pairs data]
for _, state in ipairs states
if not validPly or applyEntities or not isentity(state\GetValue())
state\Apply()
@NetworkDataChanges(state) unless silent
ReadNetworkDataNotify: (len = 24, ply = NULL, silent = false, applyEntities = true) =>
data = @@ReadNetworkData()
validPly = IsValid(ply)
states = [PPM2.NetworkChangeState(key, keyValid, newVal, @) for key, {keyValid, newVal} in pairs data]
for _, state in ipairs states
if not validPly or applyEntities or not isentity(state\GetValue())
state\Apply()
@NetworkDataChanges(state) unless silent
state\Notify()
NetworkedIterable: (grabEntities = true) =>
data = [{getName, @[strName]} for _, {:strName, :getName} in ipairs @@NW_Vars when grabEntities or not isentity(@[strName])]
return data
ApplyDataToObject: (target, applyEntities = false) =>
target["Set#{key}"](target, value) for {key, value} in *@NetworkedIterable(applyEntities) when target["Set#{key}"]
return target
WriteNetworkData: => writeFunc(@[strName]) for _, {:strName, :writeFunc} in ipairs @@NW_Vars
Create: =>
return if @NETWORKED
return if CLIENT and @CREATED_BY_SERVER -- wtf
@NETWORKED = true if SERVER
@SHOULD_NETWORK = true
if SERVER
net.Start(@@NW_Create)
net.WriteUInt32(@netID)
net.WriteEntity(@ent)
@WriteNetworkData()
if IsValid(@ent) and @ent\IsPlayer()
net.SendOmit(@ent)
else
net.Broadcast()
return
@@NW_WaitID += 1
@waitID = @@NW_WaitID
@@NW_Waiting[@waitID] = @
net.Start(@@NW_Create)
net.WriteUInt32(@waitID)
@WriteNetworkData()
net.SendToServer()
NetworkTo: (targets = {}) =>
net.Start(@@NW_Create)
net.WriteUInt32(@netID)
net.WriteEntity(@ent)
@WriteNetworkData()
net.Send(targets)
CreateOrNetworkAll: =>
if @NETWORKED
net.Start(@@NW_Create)
net.WriteUInt32(@netID)
net.WriteEntity(@ent)
@WriteNetworkData()
net.Broadcast()
return
@Create()
NetworkAll: =>
net.Start(@@NW_Create)
net.WriteUInt32(@netID)
net.WriteEntity(@ent)
@WriteNetworkData()
net.Broadcast()
if CLIENT
net.Receive 'PPM2.PonyDataRemove', ->
readid = net.ReadUInt32()
assert(PPM2.NetworkedPonyData\Get(readid), 'unknown ponydata ' .. readid .. ' to remove')\Remove()
else
hook.Add 'PlayerJoinTeam', 'PPM2.TeamWaypoint', (ply, new) ->
ply.__ppm2_modified_jump = false
hook.Add 'OnPlayerChangedTeam', 'PPM2.TeamWaypoint', (ply, old, new) ->
ply.__ppm2_modified_jump = false
_G.LocalPonyData = () -> LocalPlayer()\GetPonyData()
_G.LocalPonydata = () -> LocalPlayer()\GetPonyData()
do
REGISTRY = PPM2.NetworkedPonyData.REGISTRY
entMeta = FindMetaTable('Entity')
EntIndex = entMeta.EntIndex
entMeta.GetPonyData = =>
index = EntIndex(@)
return REGISTRY[index] if index > 0
return REGISTRY[@]
entMeta.SetPonyData = (data) =>
index = EntIndex(@)
if index > 0
REGISTRY[index] = data
return
REGISTRY[@] = data
if SERVER
net.pool('ppm2_force_wear')
if player.GetCount() ~= 0
for ply in *player.GetHumans()
net.Start('ppm2_force_wear')
net.Send(ply)
| 29.559643 | 173 | 0.698812 |
0c5d1fc5da7982455b2dd54add6b163bf4a82e8d | 1,162 | import create_table, types from require "lapis.db.schema"
{
[1]: =>
create_table "messages", {
{"id", types.id primary_key: true} -- NOTE id type is for MySQL ONLY
{"team_id", types.varchar}
{"team_domain", types.text}
{"channel_id", types.varchar}
{"channel_name", types.text}
{"timestamp", types.varchar unique: true}
{"user_id", types.varchar}
{"user_name", types.text}
{"text", types.text}
}
[2]: =>
create_table "users", {
{"id", types.id primary_key: true}
{"name", types.varchar unique: true}
{"salt", types.text}
{"digest", types.text}
{"perm_view", types.boolean default: false} -- whether or not user has permission to view logs
}
}
-- Example from slack:
--token=7LohdXbdnv3EaqMXNWnmdDri
--team_id=T0001
--team_domain=example
--channel_id=C2147483705
--channel_name=test
--timestamp=1355517523.000005
--user_id=U2147483697
--user_name=Steve
--text=googlebot: What is the air-speed velocity of an unladen swallow?
--trigger_word=googlebot:
| 29.794872 | 106 | 0.596386 |
dfe8885baaafc78495b413115bb8f6d87a04a272 | 2,178 | export class AnimationTrack
new: (frameIds, time) =>
@hasEnded = false
@isLooping = false
@clock = 0
@frames = {}
-- parse frame ids
startRange = -1
for id, rangeDelim in string.gmatch(frameIds, "(%d+)([-]?)")
id = tonumber(id) - 1
if (startRange != -1)
for i = startRange, id
Lume.push(@frames, { id: i, time: 0 })
startRange = -1
continue
if (rangeDelim != nil)
startRange = id
continue
Lume.push(@frames, { id: id, time: 0 })
-- parse frame time
switch (type(time))
when "table"
id = 1
for frameTime in string.gmatch(frameIds, "(%d+)")
@frames[id].time = tonumber(frameTime) / 1000.0
id += 1
when "number"
for id = 1, #@frames
@frames[id].time = time / 1000.0
else
error "Unexpected AnimationTrack time format"
@currentId = 1
@currentFrame = @frames[@currentId]
-- callbacks
@callbacks = {
onEnd: -> return
}
update: (dt) =>
if (@hasEnded)
return
@clock += dt
if (@clock >= @currentFrame.time)
@currentId += 1
@clock = 0
if (@currentId > #@frames)
@callbacks.onEnd!
if (@isLooping)
@currentId = 1
else
@currentId = #@frames
@hasEnded = true
return false
@currentFrame = @frames[@currentId]
return true
return false
reset: =>
@hasEnded = false
@clock = 0
@currentId = 1
@currentFrame = @frames[@currentId]
loop: (looping=true) =>
@isLooping = looping
return @
onEnd: (onEndCallback) =>
@callbacks.onEnd = onEndCallback
return @
| 25.928571 | 69 | 0.416437 |
78ef59129c735a002f82dbcacbad33748b1abd0e | 3,059 | import escape_pattern, parse_content_disposition, build_url from require "lapis.util"
import run_after_dispatch from require "lapis.nginx.context"
flatten_params = (t) ->
{k, type(v) == "table" and v[#v] or v for k,v in pairs t}
parse_multipart = ->
out = {}
upload = require "resty.upload"
input, err = upload\new 8192
return nil, err unless input
input\set_timeout 1000 -- 1 sec
current = { content: {} }
while true
t, res, err = input\read!
switch t
when "body"
table.insert current.content, res
when "header"
name, value = unpack res
if name == "Content-Disposition"
if params = parse_content_disposition value
for tuple in *params
current[tuple[1]] = tuple[2]
else
current[name\lower!] = value
when "part_end"
current.content = table.concat current.content
if current.name
if current["content-type"] -- a file
out[current.name] = current
else
out[current.name] = current.content
current = { content: {} }
when "eof"
break
else
return nil, err or "failed to read upload"
out
ngx_req = {
headers: -> ngx.req.get_headers!
cmd_mth: -> ngx.var.request_method
cmd_url: -> ngx.var.request_uri
relpath: (t) -> t.parsed_url.path
scheme: -> ngx.var.scheme
port: -> ngx.var.server_port
srv: -> ngx.var.server_addr
remote_addr: -> ngx.var.remote_addr
referer: -> ngx.var.http_referer or ""
parsed_url: (t) ->
uri = ngx.var.request_uri
uri = uri\match("(.-)%?") or uri
{
scheme: ngx.var.scheme
path: uri
host: ngx.var.host
port: ngx.var.http_host\match ":(%d+)$"
query: ngx.var.args
}
built_url: (t) ->
build_url t.parsed_url
params_post: (t) ->
content_type = (t.headers["content-type"] or "")\lower!
params = if content_type\match escape_pattern "multipart/form-data"
parse_multipart!
elseif content_type\match escape_pattern "application/x-www-form-urlencoded"
ngx.req.read_body!
flatten_params ngx.req.get_post_args!
params or {}
params_get: ->
flatten_params ngx.req.get_uri_args!
}
lazy_tbl = (tbl, index) ->
setmetatable tbl, {
__index: (key) =>
fn = index[key]
if fn
with res = fn @
@[key] = res
}
build_request = (unlazy=false) ->
with t = lazy_tbl {}, ngx_req
if unlazy
for k in pairs ngx_req
t[k]
build_response = ->
{
req: build_request!
add_header: (k, v) =>
old = @headers[k]
switch type old
when "nil"
@headers[k] = v
when "table"
old[#old + 1] = v
@headers[k] = old
else
@headers[k] = {old, v}
headers: ngx.header
}
dispatch = (app) ->
res = build_response!
app\dispatch res.req, res
ngx.status = res.status if res.status
ngx.print res.content if res.content
run_after_dispatch!
res
{ :build_request, :build_response, :dispatch }
| 23 | 85 | 0.597908 |
89e06d81e878d1a5a9a9b12594222f23e84d8f66 | 1,550 | lapis = require "lapis"
import respond_to, capture_errors_json, assert_error from require "lapis.application"
import assert_valid from require "lapis.validate"
class extends lapis.Application
"/keys": capture_errors_json respond_to {
GET: =>
import Keys from require "models"
out = Keys\select "
where time > now() - '2 days'::interval
group by 1, machine_id
order by t desc
", fields: "date_trunc('hour', time) as t, sum(count), machine_id"
json: {
keys: out
}
}
"/keys/put": capture_errors_json respond_to {
before: =>
assert_valid @params, {
{"machine_id", is_integer: true}
{"password", exists: true}
}
@machine_id = @params.machine_id
GET: =>
import Keys from require "models"
res = Keys\select "
where machine_id = ?
", @machine_id, fields: "max(id)"
json: {
max_id: res.max or -1
}
POST: =>
import Keys from require "models"
import from_json from require "lapis.util"
content_type = assert_error @req.headers["content-type"], "missing content"
assert_error content_type\lower!\match("application/json"), "expecting json body"
ngx.req.read_body!
data = from_json assert ngx.req.get_body_data!
inserted = 0
for {id, time, count} in *data
Keys\create {
:id, :time, :count
machine_id: @machine_id
}
inserted += 1
json: {
success: true
:inserted
}
}
| 24.603175 | 87 | 0.593548 |
d4920d1c0c82d4e63c0b1370ad29e353da22e50e | 1,750 | import insert from table
export sprites = {}
spritesAll = {}
newSprite = (name, colorType, colorName) ->
img = love.graphics.newImage "assets/sprites/#{name}.png"
sprite = {
img: img
width: img\getWidth!
height: img\getHeight!
color: colors[colorType][colorName]
colorType: colorType
colorName:colorName
}
insert spritesAll, sprite
return sprite
sprites.load = =>
@player = newSprite "player", "normal", "blue"
@wall = newSprite "wall", "normal", "white"
@door = {}
@door.top = newSprite "doorTop", "normal", "red"
@door.bottom = newSprite "doorBottom", "normal", "red"
@door.right = newSprite "doorRight", "normal", "red"
@door.left = newSprite "doorLeft", "normal", "red"
@door.topOpen = newSprite "doorTopOpen", "normal", "red"
@door.bottomOpen = newSprite "doorBottomOpen", "normal", "red"
@door.rightOpen = newSprite "doorRightOpen", "normal", "red"
@door.leftOpen = newSprite "doorLeftOpen", "normal", "red"
@bow = newSprite "bow", "normal", "green"
@frame = newSprite "frame", "normal", "white"
@heart = newSprite "heart", "normal", "red"
@key = newSprite "key", "normal", "magenta"
@bomb = newSprite "bomb", "normal", "cyan"
@gold = newSprite "gold", "normal", "yellow"
@ignite = newSprite "ignite", "normal", "red"
@arrow = newSprite "arrowSmall", "normal", "cyan"
@chestClosed = newSprite "chestClosed", "normal", "magenta"
@chestOpen = newSprite "chestOpen", "normal", "magenta"
@stairs = newSprite "stairs", "normal", "yellow"
@undead = newSprite "undead", "normal", "green"
@pixel = newSprite "pixel", "normal", "white"
sprites.refreshColors = =>
for _, sprite in pairs spritesAll
with sprite
.color = colors[.colorType][.colorName]
| 35 | 64 | 0.654857 |
7c8e3171b551453606e9d9f06a85a6deb99acf42 | 294 | simplehttp = require 'simplehttp'
PRIVMSG:
'^%pchopra$': (source, destination) =>
simplehttp 'http://www.wisdomofchopra.com/iframe.php', (html) ->
quote = html\match [[<meta property="og:description" content="'(.+)' www.wisdomofchopra.com" />]]
if quote
say quote
| 32.666667 | 104 | 0.632653 |
e8fd3ec4f957c76b2a40c1199448dc6b53aa0179 | 7,720 | --- Submodule for headers manipulation
-- @module httoolsp.headers
import is_empty_table from require 'httoolsp.utils'
str_sub = string.sub
str_find = string.find
str_gmatch = string.gmatch
str_gsub = string.gsub
str_lower = string.lower
str_count = (s, pattern, i, j) ->
if i
s = str_sub(s, i, j)
count = 0
for _ in str_gmatch(s, pattern)
count += 1
return count
str_strip = (s) -> str_gsub(s, '^%s*(.-)%s*$', '%1')
table_insert = table.insert
table_concat = table.concat
table_sort = table.sort
---- parse_header ----
--- Splits a semicolon-separated string (such as MIME header).
-- Returns a pair (remainder, value) on each call.
-- The remainder serves as a control variable and should be ignored.
-- @local
-- @param[type=string] header
-- @param[type=?string] remainder remainder from previous call
-- @treturn[1] string next remainder
-- @treturn[1] string next value
-- @treturn[2] nil
_parse_header_iter = (header, remainder) ->
if not remainder
-- first iteration
remainder = header
elseif remainder == ''
-- last iteration
return nil
idx = str_find(remainder, ';', 1, true)
while idx and (str_count(remainder, [["]], 1, idx - 1) - str_count(remainder, [[\"]], 1, idx - 1)) % 2 > 0
idx = str_find(remainder, ';', idx + 1, true)
local value
if not idx
value = str_strip(remainder)
remainder = ''
else
value = str_strip(str_sub(remainder, 1, idx - 1))
remainder = str_sub(remainder, idx + 1)
return remainder, value
--- Parse a header into a main value and a table of parameters.
-- This function is partially based on `cgi.parse_header` from CPython.
-- @tparam string header
-- @treturn string main value
-- @treturn table table of parameters
parse_header = (header) ->
params = {}
remainder, value = _parse_header_iter(header)
for _, p in _parse_header_iter, header, remainder
i = str_find(p, '=', 1, true)
if i
pname = str_lower(str_strip(str_sub(p, 1, i - 1)))
pvalue = str_strip(str_sub(p, i + 1))
if #pvalue >= 2 and str_sub(pvalue, 1, 1) == '"' and str_sub(pvalue, -1, -1) == '"'
pvalue = str_sub(pvalue, 2, -2)
pvalue = str_gsub(str_gsub(pvalue, [[\\]], [[\]]), [[\"]], [["]])
params[pname] = pvalue
return value, params
---- parse_accept_header ----
_MEDIA_TYPE_PATTERN = '^[%w!#$&^_.+-]+$'
_parse_media_type = (media_type) ->
type_, subtype = media_type\match '^([^/]+)/([^/]+)$'
if not type_
return nil
if type_ == '*' and subtype ~= '*' then
return nil
if type_ ~= '*' and not type_\match _MEDIA_TYPE_PATTERN
return nil
if subtype ~= '*' and not subtype\match _MEDIA_TYPE_PATTERN
return nil
return type_, subtype
_media_types_sorter = (i, j) -> i[1] > j[1]
_empty_params_to_nil = (params) ->
if is_empty_table params
return nil
return params
__compare_params = (params1, params2) ->
for k, v in pairs params1
if v ~= params2[k]
return false
return true
_compare_params = (params1, params2) ->
if not params1
if params2
return false
return true
if not params2
return false
if not __compare_params params1, params2
return false
return __compare_params params2, params1
--- A class representing parsed `accept` header.
-- Cannot be instantiated directly, use `parse_accept_header`.
-- @type AcceptHeader
class AcceptHeader
--- AcceptHeader initializer. Should not be used directly.
-- @tparam table media_types array of arrays {weight, type, subtype, params}
-- weight: number or nil
-- type: string
-- subtype: string
-- params: table or nil
new: (media_types) =>
_media_types = {}
for {weight, type_, subtype, params} in *media_types
if not weight
weight = 1
if params
params = _empty_params_to_nil params
table_insert _media_types, {weight, type_, subtype, params}
table_sort _media_types, _media_types_sorter
@_media_types = _media_types
__tostring: () =>
if not @_header
list = {}
for {weight, type_, subtype, params} in *@_media_types
item = {
'%s/%s'\format(type_, subtype)
}
if params
for k, v in pairs params
table_insert item, '%s=%s'\format(k, v)
if weight ~= 1
table_insert item, 'q=%s'\format(weight)
table_insert list, table_concat item, ';'
@_header = table_concat list, ','
return @_header
--- Get weight of passed media type.
-- Returns `nil` if media type is not accepted.
-- @tparam string media_type media type
-- @treturn[1] float weight
-- @treturn[2] nil
get_weight: (media_type) =>
media_type, params = parse_header media_type
type_, subtype = _parse_media_type media_type
if not type_
return nil, 'invalid media type'
params = _empty_params_to_nil params
for {weight, c_type, c_subtype, c_params} in *@_media_types
if (c_type == '*' or c_type == type_) and
(c_subtype == '*' or c_subtype == subtype) and
_compare_params(params, c_params)
return weight
return nil
--- Get "best" media type and its weight.
-- Returns `nil` if no media type is accepted.
-- @tparam table media_types array of media types
-- @treturn[1] string media type
-- @treturn[1] float weight
-- @treturn[2] nil
negotiate: (media_types) =>
candidates = {}
for media_type in *media_types
weight = @get_weight media_type
if weight
table_insert candidates, {weight, media_type}
table_sort candidates, _media_types_sorter
best = candidates[1]
if not best
return nil
return best[2], best[1]
--- @section end
--- Parse `accept` header and return instance of `AcceptHeader`.
-- @tparam string header
-- @tparam ?bool strict enable strict mode. Default is `false`.
-- @treturn[1] table `AcceptHeader` instance
-- @treturn[2] nil
-- @treturn[2] string error message
parse_accept_header = (header, strict=false) ->
header = str_strip header
if strict and not header\match '^[%p%w ]*$'
return nil, 'invalid characters in header'
media_types = {}
for media_range in header\gmatch '[^%c,]+'
local weight, type_, subtype
media_type, params = parse_header(media_range)
if #media_type > 1
type_, subtype = _parse_media_type media_type
if type_
weight = params.q
if weight
params.q = nil
weight = tonumber weight
if weight and (weight < 0 or weight > 1)
weight = nil
if not weight
if strict
return nil, "invalid weight: '%s'"\format str_strip media_range
-- set low weight for malformed values
weight = 0.01
table_insert media_types, {weight, type_, subtype, params}
elseif strict
return nil, "invalid media type: '%s'"\format media_type
elseif strict
return nil, "empty media type: '%s'"\format str_strip media_range
return AcceptHeader media_types
:parse_header, :parse_accept_header
| 33.859649 | 110 | 0.590674 |
1401415a068cb8f07367fbd84262ac64e00e8987 | 1,247 | import config from howl
state = ...
local insert_pos
get_edit = (editor) ->
return nil unless insert_pos
cur_line = editor.current_line
if insert_pos >= cur_line.start_pos and insert_pos <= cur_line.end_pos
start_pos = (insert_pos - cur_line.start_pos) + 1
end_pos = (editor.cursor.pos - cur_line.start_pos) + 1
start_pos, end_pos = end_pos, start_pos if end_pos < start_pos
text = cur_line\usub start_pos, end_pos - 1
if text and #text > 0
(editor) -> editor\insert text
exit_insert_mode = (editor) ->
state.insert_edit = get_edit editor
insert_pos = nil
state.change_mode editor, 'command'
editor.cursor.column = math.max 1, editor.cursor.column - 1
insert_map = {
__meta: {
on_enter: (editor) ->
error("Can not enter INSERT: buffer is read-only") if editor.buffer.read_only
name: 'INSERT'
cursor_properties:
style: 'line'
blink_interval: -> config.cursor_blink_interval
}
escape: exit_insert_mode
'ctrl_[': exit_insert_mode
ctrl_i: (editor) -> editor\shift_right!
ctrl_d: (editor) -> editor\shift_left!
}
setmetatable insert_map, {
__call: (_, editor) ->
state.enter_edit_mode editor
insert_pos = editor.cursor.pos
}
return insert_map
| 25.979167 | 83 | 0.695269 |
55e3300579d5f283c221819f49aa1391cea2f459 | 848 | path = "sauce3/wrappers/"
aligns = require path .. "aligns"
blend_modes = require path .. "blend_modes"
filters = require path .. "filters"
formats = require path .. "formats"
keys = require path .. "key_codes"
buttons = require path .. "mouse"
shapes = require path .. "shapes"
wraps = require path .. "texture_wrapping"
key_codes = {}
for k, v in pairs keys
key_codes[v] = k
button_codes = {}
for k, v in pairs buttons
button_codes[v] = k
format_codes = {}
for k, v in pairs formats
format_codes[v] = k
wrap_codes = {}
for k, v in pairs wraps
wrap_codes[v] = k
filter_codes = {}
for k, v in pairs filters
filter_codes[v] = k
{
:keys
:key_codes
:buttons
:button_codes
:formats
:format_codes
:wraps
:wrap_codes
:filters
:filter_codes
:blend_modes
:shapes
:aligns
}
| 16.307692 | 48 | 0.641509 |
d9199152b9c7c582b91ba018a9a3982ab3bacac1 | 163 | export class EmptyScene extends Scene
draw: =>
super!
love.graphics.print("Empty Scene", Settings.screenCenter.x, Settings.screenCenter.y)
| 32.6 | 93 | 0.680982 |
de37e7edda42e7e2d6a00ba75bda755ce556a7cb | 338 | export modinfo = {
type: "command"
desc: "Build Tools"
alias: {"btools"}
func: getDoPlayersFunction (v) ->
if GetBackpack(v)
BinTable = {1, 2, 3, 4}
for i = 1, 3 do
CreateInstance"HopperBin"
Parent: GetBackpack(v)
BinType: BinTable[i]
Output(string.format("Gave building tools to %s",v.Name),{Colors.Green})
} | 26 | 75 | 0.647929 |
2c2ef5088237106c739b82c0419d3b2517cb38a5 | 241 | -- Copyright 2014-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
require 'ljglibs.gio.input_stream'
core = require 'ljglibs.core'
core.define 'GFileInputStream < GInputStream', {
}
| 26.777778 | 79 | 0.763485 |
7d168e843f188ecdd6146b8a58d02bf48ee2a78a | 3,648 | import type from _G
import Object from require "core"
import ChunkEnvironment from "novacbn/lunarbook/api/ChunkEnvironment"
import Transformers from "novacbn/lunarbook/api/Transformers"
-- HACK: temp for now
-- TODO:
-- * once gmodproj has installing support, query .gmodpackages for 'lunarbook-plugin-*' packages
-- * load those from '~/.gmodproj/packages/'
-- * also support book-local plugins via '$BOOK_HOME/.lunarbook/plugins'
LOADED_PLUGINS = {
{name: builtin, exports: loadfile(dependency("novacbn/lunarbook/lib/constants").BOOK_HOME.plugins.."/lunarbook-plugin-builtin.lua")()}
}
-- ::LoadedPlugin(string name, table exports) -> table
-- Represents a plugin loaded by the PluginManager
--
LoadedPlugin = (name, exports) -> {
-- LoadedPlugin::exports -> table
-- Represents the exports of the plugin
--
exports: exports
-- LoadedPlugin::exports -> table
-- Represents the name of the plugin
--
name: name
}
-- PluginManager::PluginManager()
-- Represents the manager of user-installed plugins
-- export
export PluginManager = with Object\extend()
-- PluginManager::plugins -> table
-- Represents the plugins loaded into the manager
--
.plugins = nil
-- PluginManager::initialize(table plugins) -> void
-- Constructor for PluginManager
--
.initialize = (plugins=LOADED_PLUGINS) =>
@plugins = plugins
-- PluginManager::dispatch(string name, any ...) -> void
-- Dispatches and event to the loaded plugins
--
.dispatch = (name, ...) =>
for plugin in *@plugins
plugin.exports[name](...) if plugin.exports[name]
-- PluginManager::configureLayoutEnvironment(ChunkEnvironment environment) -> ChunkEnvironment
-- Configures the Layout ChunkEnvironment via the loaded plugins
--
.configureLayoutEnvironment = (environment=ChunkEnvironment\new()) =>
error("bad argument #1 to 'configureLayoutEnvironment' (expected ChunkEnvironment)") unless type(environment) == "table"
@dispatch("configureLayoutEnvironment", environment)
return environment
-- PluginManager::configureStyleEnvironment(ChunkEnvironment environment) -> ChunkEnvironment
-- Configures the Style ChunkEnvironment via the loaded plugins
--
.configureStyleEnvironment = (environment=ChunkEnvironment\new()) =>
error("bad argument #1 to 'configureStyleEnvironment' (expected ChunkEnvironment)") unless type(environment) == "table"
@dispatch("configureStyleEnvironment", environment)
return environment
-- PluginManager::configureTransformers(Transformers transformers?) -> Transformers
-- Configures a Transformers instance via the loaded plugins
--
.configureTransformers = (transformers=Transformers\new()) =>
error("bad argument #1 to 'configureTransformers' (expected Transformers)") unless type(transformers) == "table"
@dispatch("configureTransformers", transformers)
return transformers
-- PluginManager::processConfiguration(table configuration) -> void
-- Configures the loaded plugins via the provided table
--
.processConfiguration = (configuration) =>
error("bad argument #1 to 'processConfiguration' (expected table)") unless type(configuration) == "table"
local err
for plugin in *@plugins
if plugin.exports.processConfiguration and configuration[plugin.name] ~= nil
err = plugin.exports.processConfiguration(configuration[plugin.name])
error("bad dispatch to 'processConfiguration' (malformed configuration)\n#{err}") if err | 40.087912 | 138 | 0.701206 |
d9d1f486b3a35219e29977ecf51c97374dcd60e1 | 1,748 | howl.util.lpeg_lexer ->
word_special = S"?!.'+-*&|=_"
ident = (alpha + word_special) * (alpha + digit + word_special)^0
identifier = capture 'identifier', ident
str_span = (start_pat, end_pat) ->
start_pat * ((V'nestedb' + P 1) - end_pat)^0 * (end_pat + P(-1))
comment = capture 'comment', P';' * scan_until(eol)
todo_comment = capture 'warning', P';' * P' '^0 * P'TODO' * scan_until(eol)
string = capture 'string', any {
span('"', '"', P('^'))
P { 'nestedb', nestedb: str_span('{','}') }
}
operator = capture 'operator', any {
"%","*","**","+",
"-","/","//","<",
"<<","<=","<>","=",
"==","=?",">",">=",
">>",">>>","?","??"
}
-- numbers
hexadecimal_number = (R('AF') + R('09'))^2 * "h"
float = P('-')^-1 * digit^1 * S'.,' * digit^0
integer = P('0') + (P('-')^-1 * R('19') * R('09')^0)
number = capture 'number', word {
hexadecimal_number,
(float + integer) * (S'eE' * P('-')^-1 * digit^1)^-1
}
-- protocols = word {
-- "http", "ftp", "nntp", "mailto", "file", "finger", "whois", "daytime", "pop", "tcp", "dns"
-- }
special = capture 'special', any {
integer * P('x') * integer -- pair
P('#') * (span('"', '"') + ident)
P('/') * (ident + digit^1) -- refinement
digit^1 * ":" * digit^1 * (":" * digit^1 * ("." * digit^1)^-1)^-1 -- time
P(':') * ident
digit^1 * P('.') * digit^1 * P('.') * (digit^1 * P('.')^-1)^0 -- tuple
P('<') * alpha * (P(1) - '>')^0 * P('>') -- tag
P('%') * (span('"','"') + (P(1) - S(' \n'))^1) -- file
-- protocols * P(':') * (P(1) - S(' \n'))^1 -- URL
}
any {
special
number
string
todo_comment
comment
capture 'variable', ident * P(':')
identifier
operator
}
| 28.193548 | 97 | 0.451373 |
a385f489742a3a66cddef9b819428b1b53e2fd2e | 1,654 | moon = require('moon')
_ = req(..., 'lib.utils')
init = () =>
@class = @@
@type = _.lowerFirst(@@name)
@isInstance = true
class Caste
@name: 'Caste'
@type: 'caste'
@parents: {}
@isClass: true
@__implements: {}
@__inherited: (child) =>
child.name = child.__name
child.type = _.lowerFirst(child.name)
child.parents = _.union(@@parents, { @@ })
for key, value in pairs child.__base
if type(value) == 'table' and value.isHelper
value\apply(child, key)
-- Inherit metamethods
for key, value in pairs @__base
if string.sub(key, 1, 2) == '__'
child.__base[key] or= value
-- Call setup code in constructor, so children do not need to call `super`
constructor = child.__init
child.__init = (...) =>
init(@)
constructor(@, ...)
@implements: (...) =>
mixins = { ... }
for mixin in *mixins
constructor = mixin.__init
mixin.__init = mixin.__base.__apply
moon.mixin(@__base, mixin)
mixin.__init = constructor
table.insert(@__implements, mixin)
-- TODO: invert this, so you're figuring out if a thing is an instance of this class
@is: (value) =>
if value == @ then return true
if value == @name then return true
valueType = type(value)
if valueType == 'string'
return _.some(@parents, (Parent) -> _.includes({ Parent.type, Parent.name }, value))
if valueType == 'table' and value.isInstance
return _.some(@parents, (Parent) -> value.class == Parent)
if valueType == 'table' and value.isClass
return _.some(@parents, (Parent) -> value == Parent)
return false
is: (value) =>
if value == @ then return true
if value == @type then return true
return @@is(value)
| 25.446154 | 87 | 0.640871 |
a76292cfa68ae626fcf51df741172b6ebc0e6b54 | 2,965 | import interact from howl
-- construct a search function suitable for SearchView from a general find(text, query, start) function
-- when called the search function returns an iterator of chunks
find_iterator = (opts) ->
{:buffer, :lines, :find, :parse_query, :parse_line, :once_per_line} = opts
local start_pos, end_pos
if opts.chunk
start_pos = opts.chunk and opts.chunk.start_pos or 1
end_pos = opts.chunk and opts.chunk.end_pos or opts.buffer.length
lines = buffer.lines\for_text_range start_pos, end_pos
else
start_pos = 1
end_pos = buffer.length
lines or= buffer.lines
parsed_lines = {} -- cached results of calling parse_line
-- the search function
(query) ->
if parse_query
query = parse_query query
idx = 0
inc_line = -> idx += 1
get_line = -> lines[idx]
get_parsed_line = ->
parsed_line = parsed_lines[idx]
unless parsed_line
line = get_line!
parsed_line = if parse_line then parse_line(line) else line
parsed_lines[idx] = parsed_line
parsed_line
inc_line!
line = get_line!
search_start = if line.start_pos < start_pos then start_pos - line.start_pos + 1 else 1
-- the iterator of chunks
->
while line
line_start = line.start_pos
-- note we pass in the parsed line and parsed query to find
match_start, match_end, match_info = find get_parsed_line!, query, search_start
if match_start
-- return a chunk for the matched segment
return if line_start + match_end - 1 > end_pos -- match beyond end_pos
if once_per_line
inc_line!
line = get_line!
search_start = 1
else
search_start = match_end + 1
-- some matches (e.g. regex '^') match empty spans
if search_start == match_start
inc_line!
line = get_line!
search_start = 1
return buffer\chunk(line_start + match_start - 1, line_start + match_end - 1), match_info
else
inc_line!
line = get_line!
search_start = 1
interact.register
name: 'buffer_search'
description: 'Search and optionally replace within buffer'
handler: (opts={}) ->
error 'buffer required' unless opts.buffer
error 'find function required' unless opts.find
if opts.chunk and opts.lines
error 'both chunk and lines cannot be specified'
search = find_iterator(opts)
search_view = howl.ui.SearchView
editor: opts.editor or howl.app.editor
buffer: opts.buffer
prompt: opts.prompt
title: opts.title
search: search
replace: opts.replace
preview_lines: opts.lines or opts.buffer.lines
preview_selected_line: opts.selected_line
:search
limit: opts.limit
howl.app.window.command_panel\run search_view, text: opts.text, cancel_for_keymap: opts.cancel_for_keymap, help: opts.help
| 32.944444 | 126 | 0.655312 |
40ebf8e1fd63c342d9e10fcf5fa6eca4fa1ae661 | 331 | import tools, warplib from require("WDDS/Core")
class Autopilot
new: (mode,tX,tY,tZ) =>
@target = {tX,tY,tZ}
@mode = mode
calculateJump: =>
switch(@mode)
when "wander"
x,y,z = warplib.getPosition!
deltaX = @target[1]-x
deltaZ = @target[3]-z
jumpdistance = warplib.getJumpDistance!
when "landing"
| 22.066667 | 47 | 0.637462 |
daeedf9d3e36a3c89983f36cf7116d9bc2fea6db | 78 |
current = ->
return "nginx" if ngx
error "can't find ngx"
{ :current }
| 9.75 | 24 | 0.589744 |
64f970baf9de173678b65102c2689d1895ab265d | 129 | validate_handler = (handler) ->
error "Gimlet handler must be a function" if type(handler) != "function"
{ :validate_handler }
| 25.8 | 73 | 0.72093 |
32e135f9dabccf5c935ef24c158b339443e94024 | 9,165 |
-- Copyright (C) 2018-2020 DBotThePony
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
-- of the Software, and to permit persons to whom the Software is furnished to do so,
-- subject to the following conditions:
-- The above copyright notice and this permission notice shall be included in all copies
-- or substantial portions of the Software.
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
-- INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
-- PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
-- FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-- OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-- DEALINGS IN THE SOFTWARE.
import Entity, DPP2 from _G
entMeta = FindMetaTable('Entity')
local worldspawn
entMeta.DPP2GetPhys = =>
return if @IsPlayer() or @IsNPC() or type(@) == 'NextBot'
worldspawn = Entity(0)\GetPhysicsObject()
switch @GetPhysicsObjectCount()
when 0
return
when 1
phys = @GetPhysicsObject()
return if not IsValid(phys) or phys == worldspawn
return phys
local output
for i = 0, @GetPhysicsObjectCount() - 1
phys = @GetPhysicsObjectNum(i)
if IsValid(phys) and phys ~= worldspawn
output = output or {}
table.insert(output, phys)
return if not output
return output[1] if #output == 1
return output
plyMeta = FindMetaTable('Player')
DPP2.SplitArguments = (argstr = '') ->
stack = {}
backslash = false
inQuotes = false
current = ''
for char in argstr\gmatch('.')
if char == '\\'
if backslash
backslash = false
current ..= '\\'
else
backslash = true
elseif char == '"'
if backslash
backslash = false
current ..= '"'
elseif inQuotes
inQuotes = false
table.insert(stack, current\trim())
current = ''
else
if current\trim() ~= ''
table.insert(stack, current\trim())
current = ''
inQuotes = true
elseif char == ' ' and not inQuotes
if current\trim() ~= ''
table.insert(stack, current\trim())
current = ''
else
backslash = false
current ..= char
table.insert(stack, current\trim()) if current\trim() ~= ''
return stack
DPP2.FindOwned = ->
output = {}
for ent in *ents.GetAll()
if ent\DPP2IsOwned()
table.insert(output, ent)
return output
DPP2.FindPlayerInCommand = (str = '') ->
str = str\trim()\lower()
return false if str == ''
return player.GetBySteamID(str\upper()) if str\startsWith('steam_')
if num = str\tonumber()
ply = Player(num)
return ply if IsValid(ply)
-- todo: better comparison
findPly = false
for ply in *player.GetAll()
nick = ply\Nick()\lower()
return ply if nick == str
if nick\find(str)
findPly = ply
if ply.SteamName
nick = ply\SteamName()\lower()
return ply if nick == str
if nick\find(str)
findPly = ply
return findPly
DPP2.FindPlayerUserIDInCommand = (str = '', allow_any = false) ->
str = str\trim()\lower()
return false if str == ''
if str\startsWith('steam_')
getplayer = player.GetBySteamID(str\upper())
return getplayer\UserID() if getplayer
return getplayer
if num = str\tonumber()
num = num\floor()
if allow_any
return false if num < 1
return num
return num if IsValid(Player(num))
-- todo: better comparison
findPly = false
for ply in *player.GetAll()
nick = ply\Nick()\lower()
return ply\UserID() if nick == str
if nick\find(str)
findPly = ply
if ply.SteamName
nick = ply\SteamName()\lower()
return ply\UserID() if nick == str
if nick\find(str)
findPly = ply
return findPly\UserID() if findPly
return findPly
DPP2.FindPlayersInArgument = (str = '', filter, nobots = false) ->
filter = LocalPlayer() if CLIENT and filter == true
if nobots
filter = {} if not filter
filter = {filter} if type(filter) ~= 'table'
table.insert(filter, ply) for ply in *player.GetAll() when ply\IsBot()
filter = {} if not filter
filter = {filter} if not istable(filter)
filter = for ply in *filter
if isnumber(ply)
ply
else
ply\UserID()
-- player_list = player.GetAll()
player_list = DPP2.GetAllKnownPlayersInfo()
str = str\trim()\lower()
return {DLib.I18n.Localize('command.dpp2.hint.player')} if str == ''
if str\startsWith('steam_')
plyFind = player.GetBySteamID(str\upper())
return {DLib.I18n.Localize('command.dpp2.hint.player')} if plyFind and table.qhasValue(filter, plyFind\UserID())
return {plyFind\Nick()} if plyFind and not table.qhasValue(filter, plyFind\UserID())
output = [ply.steamid for ply in *player_list when ply.steamid\lower()\startsWith(str) and not table.qhasValue(filter, ply.uid)]
return #output ~= 0 and output or {DLib.I18n.Localize('command.dpp2.hint.none')}
if num = str\tonumber()
ply = Player(num)
return {DLib.I18n.Localize('command.dpp2.hint.player')} if IsValid(ply) and table.qhasValue(filter, ply\UserID())
getply = player_list[num] if not table.qhasValue(filter, num)
return {getply.name} if getply
return {ply\Nick()} if IsValid(ply) and not table.qhasValue(filter, ply\UserID())
output = [ply.name for ply in *player_list when ply.uid\tostring()\startsWith(str) and not table.qhasValue(filter, ply.uid)]
return #output ~= 0 and output or {DLib.I18n.Localize('command.dpp2.hint.none')}
findPly = {}
for uid, ply in pairs(player_list)
if not table.qhasValue(filter, uid)
nick = ply.name\lower()
if nick == str or nick\find(str)
table.insert(findPly, ply.name)
elseif IsValid(ply.ent) and ply.ent.SteamName
nick = ply.ent\SteamName()\lower()
if nick == str or nick\find(str)
table.insert(findPly, ply.ent\SteamName())
return #findPly ~= 0 and findPly or {DLib.I18n.Localize('command.dpp2.hint.none')}
DPP2.AutocompleteOwnedEntityArgument = (str2, owned = CLIENT, format = false, filter) ->
owned = nil if SERVER
entsFind = [ent for ent in *ents.GetAll() when ent\DPP2IsOwned()] if owned == false
searchEnts = owned and LocalPlayer()\DPP2FindOwned() or entsFind or ents.GetAll()
output = {}
str2 = str2\lower()
if num = tonumber(str2)
entf = Entity(num)
if IsValid(entf)
if (entf\DPP2GetOwner() == @ or not owned) and (not filter or filter(entf))
table.insert(output, format and string.format('%q', tostring(entf)) or tostring(entf))
else
table.insert(output, '<cannot target!>')
else
for ent in *searchEnts
if ent\EntIndex()\tostring()\startsWith(str) and (not filter or filter(ent))
table.insert(output, format and string.format('%q', tostring(ent)) or tostring(ent))
else
for ent in *searchEnts
str = tostring(ent)
return {format and string.format('%q', str) or str} if str\lower() == str2
if str\lower()\startsWith(str2) and (not filter or filter(ent))
table.insert(output, format and string.format('%q', str) or str)
table.sort(output)
return output
DPP2.FindEntityFromArg = (str, ply = CLIENT and LocalPlayer() or error('You must provide player entity')) ->
ent = Entity(tonumber(str or -1) or -1)
return ent if IsValid(ent)
return ent for ent in *ply\DPP2FindOwned() when tostring(ent) == str
return NULL
DPP2.SpewEntityInspectionOutput = (ent = NULL) =>
if not IsValid(ent)
DPP2.LMessagePlayer(@, 'message.dpp2.inspect.invalid_entity')
else
DPP2.LMessagePlayer(@, 'message.dpp2.inspect.result.class', ent\GetClass() or 'undefined')
pos = ent\GetPos()
DPP2.LMessagePlayer(@, 'message.dpp2.inspect.result.position', pos.x, pos.y, pos.z) if pos
ang = ent\GetAngles()
DPP2.LMessagePlayer(@, 'message.dpp2.inspect.result.angles', ang.p, pos.y, pos.r) if ang
ang = ent\EyeAngles()
DPP2.LMessagePlayer(@, 'message.dpp2.inspect.result.eye_angles', ang.p, pos.y, pos.r) if ang
DPP2.LMessagePlayer(@, 'message.dpp2.inspect.result.table_size', table.Count(ent\GetTable()))
DPP2.LMessagePlayer(@, 'message.dpp2.inspect.result.health', ent\Health())
DPP2.LMessagePlayer(@, 'message.dpp2.inspect.result.max_health', ent\GetMaxHealth())
ownerEntity, ownerSteamID, ownerNickname, ownerUniqueID = ent\DPP2GetOwner()
if ownerSteamID ~= 'world'
DPP2.LMessagePlayer(@, 'message.dpp2.inspect.result.owner_entity', ownerEntity) if IsValid(ownerEntity)
DPP2.LMessagePlayer(@, 'message.dpp2.inspect.result.owner_steamid', ownerSteamID)
DPP2.LMessagePlayer(@, 'message.dpp2.inspect.result.owner_nickname', ownerNickname or '')
DPP2.LMessagePlayer(@, 'message.dpp2.inspect.result.owner_uniqueid', ownerUniqueID)
else
DPP2.LMessagePlayer(@, 'message.dpp2.inspect.result.unowned')
DPP2.LMessagePlayer(@, 'message.dpp2.inspect.result.model', ent\GetModel() or 'undefined')
DPP2.LMessagePlayer(@, 'message.dpp2.inspect.result.skin', ent\GetSkin() or 'undefined')
DPP2.LMessagePlayer(@, 'message.dpp2.inspect.result.bodygroup_count', table.Count(ent\GetBodyGroups() or {})) | 31.603448 | 130 | 0.700709 |
45e837615bca8ae28095aa0c18975bb94d43487f | 67 | M = {}
TK = require "PackageToolkit"
M.dir = TK.module.dir
return M | 16.75 | 29 | 0.686567 |
6add7df2e53071b85afb87bf5797d8d276a73bbf | 3,441 | -- project decrements amount of dimensions
-- number -> table -> table, number
project = (fov, point) ->
scale = fov / (fov + point[#point])
point2 = {}
for coord in *point
point2[#point2 + 1] = coord * scale
if #point2 - (#point - 1) == 0
return point2, scale
-- projectn recursively decrements amount of dimensions
-- ... towards given amount
-- number -> number -> table -> table, scale
projectn = (dimension, fov, point) ->
point2, scale = project fov, point
if dimension - #point2 == 0
return point2, scale
else
projectn dimension, fov, point2
-- line draws a 2d line between two given arbitrary dimensional points
-- number -> table -> table -> nil
line = (fov, p1, p2) ->
pn1, s1 = projectn 2, fov, p1
pn2, s2 = projectn 2, fov, p2
with love.graphics
.line pn1[1] * s1, pn1[2] * s1, pn2[1] * s2, pn2[2] * s2
-- circle draws a 2d circle on a given arbitrary dimensional point
-- number -> string -> table -> number -> table -> nil
circle = (fov, mode, p1, radius, segments) ->
pn1, s1 = projectn 2, fov, p1
with love.graphics
.circle mode, pn1[1] * s1, pn1[2] * s1, radius * s1, segments
-- text on point
print = (fov, msg, p1) ->
pn1, s1 = projectn 2, fov, p1
with love.graphics
.print msg, pn1[1] * s1, pn1[2] * s1, 0, s1, s1
-- triangle draws a 2d triangle between given arbitray dimensional points
-- number -> string -> table -> table -> table -> nil
triangle = (fov, mode, p1, p2, p3) ->
pn1, s1 = projectn 2, fov, p1
pn2, s2 = projectn 2, fov, p2
pn3, s3 = projectn 2, fov, p3
with love.graphics
.polygon mode, pn1[1] * s1, pn1[2] * s1, pn2[1] * s2, pn2[2] * s2, pn3[1] * s3, pn3[2] * s3
square3 = (fov, mode, p1, p2, p3, p4) ->
switch mode
when "fill"
triangle fov, "fill", p1, p2, p3
triangle fov, "fill", p2, p3, p4
triangle fov, "fill", p3, p4, p1
when "cross?"
triangle fov, "fill", p1, p2, p3
triangle fov, "fill", p2, p3, p4
triangle fov, "fill", p3, p4, p1
triangle fov, "fill", p1, p3, p4
when "line"
line fov, p1, p2
line fov, p2, p3
line fov, p3, p4
line fov, p4, p1
-- horizontal
square3h = (fov, mode, p1, width, height) ->
p2 = {p1[1] + width, p1[2], p1[3]}
p3 = {p1[1] + width, p1[2], p1[3] + height}
p4 = {p1[1], p1[2], p1[3] + height}
square3 fov, mode, p1, p2, p3, p4
-- vertical
square3v = (fov, mode, p1, width, height) ->
p2 = {p1[1], p1[2] + width, p1[3]}
p3 = {p1[1], p1[2] + width, p1[3] + height}
p4 = {p1[1], p1[2], p1[3] + height}
square3 fov, mode, p1, p2, p3, p4
-- depth
square3d = (fov, mode, p1, width, height) ->
p2 = {p1[1] + width, p1[2], p1[3]}
p3 = {p1[1] + width, p1[2] + height, p1[3]}
p4 = {p1[1], p1[2] + height, p1[3]}
square3 fov, mode, p1, p2, p3, p4
cube = (fov, mode, p1, width, height, depth) ->
square3h fov, mode, {p1[1], p1[2], p1[3]}, width, height
square3h fov, mode, {p1[1], p1[2] - height, p1[3]}, width, height
square3v fov, mode, {p1[1], p1[2] - height, p1[3]}, width, height
square3v fov, mode, {p1[1] + width, p1[2] - height, p1[3]}, width, height
square3d fov, mode, {p1[1], p1[2] - height, p1[3]}, width, height
{
:project
:projectn
graphics: {
:line
:circle
:triangle
:square3
:square3h
:square3v
:square3d
:cube
:print
}
} | 27.97561 | 95 | 0.566115 |
3ca7fbfaf886d1555a67531fc20894bd4785b87b | 5,027 | export script_name = "Lerp by Character"
export script_description = "Linearly interpolates a specified override tag character-by-character between stops in a line."
export script_version = "0.1.0"
export script_author = "line0"
export script_namespace = "l0.LerpByChar"
DependencyControl = require "l0.DependencyControl"
depCtrl = DependencyControl {
feed: "https://raw.githubusercontent.com/TypesettingTools/line0-Aegisub-Scripts/master/DependencyControl.json",
{
{"a-mo.LineCollection", version: "1.3.0", url: "https://github.com/TypesettingTools/Aegisub-Motion",
feed: "https://raw.githubusercontent.com/TypesettingTools/Aegisub-Motion/DepCtrl/DependencyControl.json"},
{"l0.ASSFoundation", version:"0.4.4", url: "https://github.com/TypesettingTools/ASSFoundation",
feed: "https://raw.githubusercontent.com/TypesettingTools/ASSFoundation/master/DependencyControl.json"},
{"l0.Functional", version: "0.6.0", url: "https://github.com/TypesettingTools/Functional",
feed: "https://raw.githubusercontent.com/TypesettingTools/Functional/master/DependencyControl.json"},
{"a-mo.ConfigHandler", version: "1.1.4", url: "https://github.com/TypesettingTools/Aegisub-Motion",
feed: "https://raw.githubusercontent.com/TypesettingTools/Aegisub-Motion/DepCtrl/DependencyControl.json"},
}
}
LineCollection, ASS, Functional, ConfigHandler = depCtrl\requireModules!
{:list, :math, :string, :table, :unicode, :util, :re } = Functional
logger = depCtrl\getLogger!
dialogs = {
lerpByCharacter: {
{
class: "label", label: "Select a tag to interpolate between states already present in the line.",
x: 0, y: 0, width: 6, height: 1
},
{
class: "label", label: "Tag:",
x: 0, y: 1, width: 1, height: 1
},
tag: {
class: "dropdown",
items: table.pluck table.filter(ASS.tagMap, (tag) -> tag.type.lerp and not tag.props.global), "overrideName",
value: "\\1c", config: true,
x: 1, y: 1, width: 1, height: 1
},
cleanTags: {
class: "checkbox", label: "Omit redundant tags",
value: true, config: true,
x: 0, y: 2, width: 2, height: 1
},
},
}
groupSectionsByTagState = (lineContents, tagName) ->
groups, group = {}
cb = (section, sections, i) ->
if i == 1 or section.instanceOf[ASS.Section.Tag] and 0 < #section\getTags tagName -- TODO: support master tags and resets
tagState = (section\getEffectiveTags true).tags[tagName]
group.endTagState = tagState if group
group = sections: {}, startTagState: tagState, firstLineIndex: i
groups[#groups + 1] = group
elseif i == #sections
group.endTagState = (section\getEffectiveTags true).tags[tagName]
group.sections[#group.sections + 1] = section
lineContents\callback cb
return groups
lerpGroup = (sections, startTagState, endTagState) ->
totalCharCount = list.reduce sections, 0, (totalLength, section) ->
totalLength + (section.instanceOf[ASS.Section.Text] and section.len or 0)
return false if totalCharCount == 0
processedCharCount = 0
lerpedSections, l = {}, 1
for s, section in ipairs sections
unless section.instanceOf[ASS.Section.Text]
lerpedSections[l], l = section, l+1
continue
charCount = section.len
previousSection = sections[s-1]
start = if previousSection and previousSection.instanceOf[ASS.Section.Tag]
previousSection\removeTags startTagState.__tag.name
previousSection\insertTags startTagState\lerp endTagState, processedCharCount / totalCharCount
l, lerpedSections[l], section = l+1, section\splitAtChar 2, true
2
else 1
for i = start, charCount
tag = startTagState\lerp endTagState, (processedCharCount + i-1) / totalCharCount
lerpedSections[l] = ASS.Section.Tag {tag}
l, lerpedSections[l+1], section = l+2, section\splitAtChar 2, true
processedCharCount += charCount
return lerpedSections
showDialog = (macro) ->
options = ConfigHandler dialogs, depCtrl.configFile, false, script_version, depCtrl.configDir
options\read!
options\updateInterface macro
btn, res = aegisub.dialog.display dialogs[macro]
if btn
options\updateConfiguration res, macro
options\write!
return res
lerpByCharacter = (sub, sel) ->
res = showDialog "lerpByCharacter"
return aegisub.cancel! unless res
tagName = ASS.tagNames[res.tag][1]
lines = LineCollection sub, sel
for line in *lines
ass = ASS\parse line
groups = groupSectionsByTagState(ass, tagName)
insertOffset = 0
for group in *groups do with group
lerpedSections = lerpGroup .sections, .startTagState, .endTagState
continue unless lerpedSections
ass\removeSections insertOffset + .firstLineIndex , insertOffset + .firstLineIndex + #.sections - 1
ass\insertSections lerpedSections, insertOffset + .firstLineIndex
insertOffset += #lerpedSections - #.sections
ass\cleanTags 4 if res.cleanTags
ass\commit!
lines\replaceLines!
depCtrl\registerMacro lerpByCharacter
| 38.968992 | 125 | 0.707181 |
ea71c3df2213983443f962e7e3f8eb48228a6ca7 | 1,089 |
import getfenv, setfenv from require "moonscript.util"
-- all undefined Proper globals are automaticlly converted into lpeg.V
wrap_env = (debug, fn) ->
import V, Cmt from require "lpeg"
env = getfenv fn
wrap_name = V
if debug
indent = 0
indent_char = " "
iprint = (...) ->
args = table.concat [tostring a for a in *{...}], ", "
io.stderr\write "#{indent_char\rep(indent)}#{args}\n"
wrap_name = (name) ->
v = V name
v = Cmt("", (str, pos) ->
rest = str\sub(pos, -1)\match "^([^\n]*)"
iprint "* #{name} (#{rest})"
indent += 1
true
) * Cmt(v, (str, pos, ...) ->
iprint name, true
indent -= 1
true, ...
) + Cmt("", ->
iprint name, false
indent -= 1
false
)
v
setfenv fn, setmetatable {}, {
__index: (name) =>
value = env[name]
return value if value != nil
if name\match"^[A-Z][A-Za-z0-9]*$"
v = wrap_name name
return v
error "unknown variable referenced: #{name}"
}
{ :wrap_env }
| 20.942308 | 70 | 0.505969 |
e097049f48aeb86d848124953020e4e2816ab0ba | 10,688 | ----------------------------------------------------------------
-- The module for compiling RoML parsetrees into Lua files.
--
-- @module RomlCompiler
-- @author Richard Voelker
-- @license MIT
----------------------------------------------------------------
local Stack
local Table
local MainRomlBlock
local ConditionalBlock
local ForBlock
local SpaceBlock
local FunctionBlock
local Line
local VariableNamer
local LiteralString
local CompilerPropertyFilter
local CustomObjectBuilder
local RomlCompiler
if game
pluginModel = script.Parent.Parent.Parent.Parent
Stack = require(pluginModel.com.blacksheepherd.datastructure.Stack)
Table = require(pluginModel.com.blacksheepherd.util.Table)
MainRomlBlock = require(pluginModel.com.blacksheepherd.code.MainRomlBlock)
ConditionalBlock = require(pluginModel.com.blacksheepherd.code.ConditionalBlock)
ForBlock = require(pluginModel.com.blacksheepherd.code.ForBlock)
SpaceBlock = require(pluginModel.com.blacksheepherd.code.SpaceBlock)
FunctionBlock = require(pluginModel.com.blacksheepherd.code.FunctionBlock)
Line = require(pluginModel.com.blacksheepherd.code.Line)
VariableNamer = require(pluginModel.com.blacksheepherd.compile.VariableNamer)
LiteralString = require(pluginModel.com.blacksheepherd.compile.LiteralString)
CompilerPropertyFilter = require(pluginModel.com.blacksheepherd.compile.CompilerPropertyFilter)
CustomObjectBuilder = require(pluginModel.com.blacksheepherd.customobject.CustomObjectBuilder)
else
Stack = require "com.blacksheepherd.datastructure.Stack"
Table = require "com.blacksheepherd.util.Table"
MainRomlBlock = require "com.blacksheepherd.code.MainRomlBlock"
ConditionalBlock = require "com.blacksheepherd.code.ConditionalBlock"
ForBlock = require "com.blacksheepherd.code.ForBlock"
SpaceBlock = require "com.blacksheepherd.code.SpaceBlock"
FunctionBlock = require "com.blacksheepherd.code.FunctionBlock"
Line = require "com.blacksheepherd.code.Line"
VariableNamer = require "com.blacksheepherd.compile.VariableNamer"
LiteralString = require "com.blacksheepherd.compile.LiteralString"
CompilerPropertyFilter = require "com.blacksheepherd.compile.CompilerPropertyFilter"
CustomObjectBuilder = require "com.blacksheepherd.customobject.CustomObjectBuilder"
-- {{ TBSHTEMPLATE:BEGIN }}
local addCode
local addCodeFunctions
local mainRomlBlock
local functionTable
local varNamer
local parentNameStack
local creationFunctionStack
mainRomlBlockCreationFunction = (lines) ->
for line in *lines
mainRomlBlock\AddChild MainRomlBlock.BLOCK_CREATION, line
writeLineToVarChangeFunction = (varName, lineString) ->
unless functionTable[varName]
mainRomlBlock\AddChild MainRomlBlock.BLOCK_VARS, Line("local varChange_#{varName}")
functionTable[varName] = FunctionBlock "varChange_#{varName}", ""
mainRomlBlock\AddChild MainRomlBlock.BLOCK_UPDATE_FUNCTIONS, functionTable[varName]
mainRomlBlock\AddChild MainRomlBlock.BLOCK_CREATION, Line("self._vars.#{varName} = RomlVar(vars.#{varName})")
mainRomlBlock\AddChild MainRomlBlock.BLOCK_CREATION, Line("self._vars.#{varName}.Changed:connect(varChange_#{varName})")
mainRomlBlock\AddChild MainRomlBlock.BLOCK_FUNCTION_CALLS, Line("varChange_#{varName}()")
functionTable[varName]\AddLineIfNotAdded lineString
writeVarCode = (className, varName, objectName, changeFunction) ->
if objectName == nil
objectName = varNamer\NameObjectVariable className
mainRomlBlock\AddChild MainRomlBlock.BLOCK_VARS, Line("local #{objectName}")
if functionTable[varName] == nil
functionTable[varName] = FunctionBlock "varChange_#{varName}", ""
mainRomlBlock\AddChild MainRomlBlock.BLOCK_VARS, Line("local varChange_#{varName}")
mainRomlBlock\AddChild MainRomlBlock.BLOCK_UPDATE_FUNCTIONS, functionTable[varName]
mainRomlBlock\AddChild MainRomlBlock.BLOCK_CREATION, Line("self._vars.#{varName} = RomlVar(vars.#{varName})")
mainRomlBlock\AddChild MainRomlBlock.BLOCK_CREATION, Line("self._vars.#{varName}.Changed:connect(varChange_#{varName})")
mainRomlBlock\AddChild MainRomlBlock.BLOCK_FUNCTION_CALLS, Line("varChange_#{varName}()")
changeFunction functionTable[varName], objectName, varName
return objectName
writeObjectToBlock = (builderParam, className, id, classes, properties, children) ->
classesString = "nil"
objectName = nil
if classes and classes[1] == "static"
classesString = Table.ArrayToSingleLineString(classes[2])
elseif classes and classes[1] == "dynamic"
objectName = writeVarCode className, classes[2], objectName, (varChange, objectName, varName) ->
varChange\AddChild Line("#{objectName}:SetClasses(self._vars.#{varName}:GetValue())")
if properties
for name, value in properties\pairs!
if type(value) == "string"
if CustomObjectBuilder.IsACustomObject(className)
properties[name] = CustomObjectBuilder.FilterProperty className, name, value, LiteralString, CompilerPropertyFilter
else
properties[name] = CompilerPropertyFilter.FilterProperty className, name, value
else
objectName = writeVarCode className, value[2], objectName, (varChange, objectName, varName) ->
varChange\AddChild Line("#{objectName}:SetProperties({#{name} = self._vars.#{varName}:GetValue()})")
varChange\AddChild Line("#{objectName}:Refresh()")
properties[name] = nil
if #children > 0 and not objectName
objectName = varNamer\NameObjectVariable(className)
mainRomlBlock\AddChild MainRomlBlock.BLOCK_VARS, Line("local #{objectName}")
objectName = "objTemp" if not objectName
idString = if id == nil then "nil" else "\"#{id}\""
lines = {}
if CustomObjectBuilder.IsACustomObject(className)
mainRomlBlock\AddCustomObjectBuilderRequire!
table.insert(lines, Line("#{objectName} = CustomObjectBuilder.CreateObject(\"#{className}\", self, #{idString}, #{classesString})"))
else
table.insert(lines, Line("#{objectName} = RomlObject(self, #{builderParam}, #{idString}, #{classesString})"))
table.insert(lines, Line("self._objectIds[#{idString}] = #{objectName}")) if id
if properties and properties\Length! > 0
table.insert(lines, Line("#{objectName}:SetProperties(#{Table.HashMapToSingleLineString(properties)})"))
table.insert(lines, Line("#{objectName}:Refresh()"))
table.insert(lines, Line("self:AddChild(#{parentNameStack\Peek!}:AddChild(#{objectName}))"))
creationFunctionStack\Peek!(lines)
creationFunctionStack\Push creationFunctionStack\Peek!
parentNameStack\Push objectName
addCode children
parentNameStack\Pop!
creationFunctionStack\Pop!
addCodeFunctions =
object: (obj) ->
-- {
-- "object"
-- ClassName :string
-- Id :string
-- Classes :array
-- Properties :table
-- Children :array
-- }
_, className, id, classes, properties, children = unpack obj
writeObjectToBlock "\"#{className}\"", className, id, classes, properties, children
clone: (obj) ->
-- {
-- "clone"
-- ClassName :string
-- RobloxObject :string
-- Id :string
-- Classes :array
-- Properties :table
-- Children :array
-- }
_, className, robloxObject, id, classes, properties, children = unpack obj
writeObjectToBlock robloxObject, className, id, classes, properties, children
if: (obj) ->
-- {
-- "if"
-- Condition :string
-- Vars :array
-- Children :array
-- OtherConditionals :array
-- }
_, condition, vars, children, otherConditionals = unpack obj
parentName = parentNameStack\Peek!
if parentName == "self._rootObject"
parentName = "Parent"
else
parentName = string.sub parentName, 4
if creationFunctionStack\Peek! == mainRomlBlockCreationFunction
creationFunctionName = "update#{parentName}"
creationFunction = FunctionBlock creationFunctionName, ""
creationFunction\AddChild Line("#{parentNameStack\Peek!}:RemoveAllChildren()")
mainRomlBlock\AddChild MainRomlBlock.BLOCK_VARS, Line("local #{creationFunctionName}")
mainRomlBlock\AddChild MainRomlBlock.BLOCK_UPDATE_FUNCTIONS, creationFunction
creationFunctionStack\Push (lines) ->
for line in *lines
creationFunction\AddChild line
ifBlock = ConditionalBlock!
ifBlock\AddCondition condition
creationFunctionStack\Peek!({ifBlock})
creationFunctionStack\Push (lines) ->
for line in *lines
ifBlock\AddChild line
for var in *vars
writeLineToVarChangeFunction var, "update#{parentName}()"
addCode children
for conditional in *otherConditionals
-- {
-- Condition :string
-- Vars :array
-- Children :array
-- }
condition, vars, children = unpack conditional
ifBlock\AddCondition condition
for var in *vars
writeLineToVarChangeFunction var, "update#{parentName}()"
addCode children
creationFunctionStack\Pop!
for: (obj) ->
-- {
-- "for"
-- Condition :string
-- Vars :array
-- Children :array
-- }
_, condition, vars, children = unpack obj
parentName = parentNameStack\Peek!
if parentName == "self._rootObject"
parentName = "Parent"
else
parentName = string.sub parentName, 4
if creationFunctionStack\Peek! == mainRomlBlockCreationFunction
creationFunctionName = "update#{parentName}"
creationFunction = FunctionBlock creationFunctionName, ""
creationFunction\AddChild Line("#{parentNameStack\Peek!}:RemoveAllChildren()")
mainRomlBlock\AddChild MainRomlBlock.BLOCK_VARS, Line("local #{creationFunctionName}")
mainRomlBlock\AddChild MainRomlBlock.BLOCK_UPDATE_FUNCTIONS, creationFunction
creationFunctionStack\Push (lines) ->
for line in *lines
creationFunction\AddChild line
forBlock = ForBlock condition
creationFunctionStack\Peek!({forBlock})
creationFunctionStack\Push (lines) ->
for line in *lines
forBlock\AddChild line
for var in *vars
writeLineToVarChangeFunction var, "update#{parentName}()"
addCode children
creationFunctionStack\Pop!
addCode = (tree) ->
if tree
for _, obj in ipairs tree
addCodeFunctions[obj[1]] obj
----------------------------------------------------------------
-- Compile the parsetree into a Lua string.
--
-- @tparam string name The name of the Lua subclass.
-- @tparam table parsetree The parse tree.
-- @treturn string The compiled Lua code.
----------------------------------------------------------------
Compile = (name, parsetree) ->
mainRomlBlock = MainRomlBlock name
functionTable = {}
varNamer = VariableNamer!
parentNameStack = Stack!
creationFunctionStack = Stack!
parentNameStack\Push "self._rootObject"
creationFunctionStack\Push mainRomlBlockCreationFunction
addCode parsetree
mainRomlBlock\Render!
RomlCompiler = { :Compile }
-- {{ TBSHTEMPLATE:END }}
return RomlCompiler
| 37.111111 | 134 | 0.738492 |
21b5dabc6adf619b143d1b718bf6146b4bf2e792 | 1,634 | _env = nil
set_default_environment = (name) ->
_env = name
default_environment = ->
unless _env == nil
return _env
_env = os.getenv "LAPIS_ENVIRONMENT"
import running_in_test from require "lapis.spec"
if running_in_test!
if _env == "production"
error "You attempt to set the `production` environment name while running in a test suite"
_env or= "test"
elseif not _env
_env = "development"
pcall -> _env = require "lapis_environment"
_env
local popper
-- force code to run in environment
push = (name_or_env, overrides) ->
assert name_or_env, "missing name or env for push"
config_module = require("lapis.config")
old_getter = config_module.get
env = if type(name_or_env) == "table"
name_or_env
else
old_getter name_or_env
if overrides
env = setmetatable overrides, __index: env
config_module.get = (...) ->
if ...
old_getter ...
else
env
old_popper = popper
popper = ->
config_module.get = old_getter
popper = old_popper
pop = ->
assert(popper, "no environment pushed")!
-- assert_env "test", { for: "feature name", exact: true }
assert_env = (env, opts={}) ->
config = require("lapis.config").get!
pat = if opts.exact
"^#{env}$"
else
"^#{env}"
unless config._name\match pat
suffix = "(#{pat}), you are in `#{config._name}`"
msg = if feature = opts.for
"`#{feature}` can only be run in `#{env}` environment #{suffix}"
else
"aborting, exepcting `#{env}` environment #{suffix}"
error msg
true
{ :push, :pop, :assert_env, :default_environment, :set_default_environment }
| 21.5 | 96 | 0.649939 |
2bdb9240e4a6d46493453dc03e6c1c8971d5f5ab | 1,528 | Caste = require('vendor/caste/lib/caste')
Criteria = req(..., 'lib.criteria')
class System extends Caste
@Criteria: Criteria
@criteria: Criteria()
active: true
init: () => @entities = {}
add: (...) =>
entities = { ... }
for entity in *entities
table.insert(@entities, entity)
if @onAdd then @onAdd(entity)
return @
remove: (...) =>
entities = { ... }
for entity in *entities
for e = 1, #@entities
ent = @entities[e]
if ent == entity or ent.id == entity
table.remove(@entities, e)
if @onRemove then @onRemove(ent)
break
return @
get: (id) =>
if not id then return @entities
for e = 1, #@entities
entity = @entities[e]
if entity.id == id then return entity
has: (...) =>
entities = { ... }
for entity in *entities
entity = if type(entity) == 'table' then entity.id else entity
if not @get(entity) then return false
return true
getCriteria: () => @@criteria
sync: (...) =>
entities = { ... }
for entity in *entities
matches = @@criteria\matches(entity)
exists = @has(entity)
if matches and not exists then @add(entity)
if not matches and exists then @remove(entity)
return @
start: () => @toggle(true)
stop: () => @toggle(false)
toggle: (active) =>
active = if active != nil then active else not @active
@active = active
if active and type(@onStart) == 'function' then @onStart()
elseif not active and type(@onStop) == 'function' then @onStop()
if type(@onToggle) == 'function' then @onToggle(active)
return @
| 23.875 | 66 | 0.620419 |
fce494fc1164a4f60c3a73c966c451129402193f | 4,429 |
{:make_loader} = require "loadkit"
{:setfenv} = require "moonscript.util"
lfs = require "lfs"
moonscript = require "moonscript"
Document = require "hestia.document"
Template = require "hestia.template"
findMoon = make_loader "moon"
findCss = make_loader "css"
findJs = make_loader "js"
---
-- Represents a project.
---
class
@LUNRADOC_VERSION: "0.5.0"
---
-- @constructor
-- @return Project | nil, string
@fromConfiguration: (filepath = "hestia.cfg") ->
file, reason = io.open filepath, "r"
unless file
return nil, reason
return @@.fromFile file
---
-- @constructor
-- @return (Project)
-- @return (nil, string) Could not parse the configuration file.
@fromFile: (file) ->
content = file\read "*a"
code = moonscript.loadstring '{\n' .. content .. '\n}'
unless code
return nil, "Could not parse configuration file."
with config = @@!
for key, value in pairs code!
switch key
-- FIXME: Not complete.
-- FIXME: Ugly names (we could keep legacy compat, though).
-- FIXME: No checking of valid types and stuff. (automated type checking?)
when "files", "inputPrefix", "outputDirectory", "title", "version", "date", "author", "outputExtension", "hljsstyle"
config[key] = value
-- FIXME: Check file existence and permissions.
when "files", "templateFiles"
config[key] = value
when "template"
config.template = value
else
print "warning: unrecognized key in configuration file: #{key}"
\setDefaultValues!
finalize: =>
@outputDirectory = @outputDirectory\gsub "/%.$", ""
@\updateFilesList!
@documents = with __ = {} -- I really wish we had implicit variables.
for fileName in *@files
document, reason = Document.fromFileName self, fileName
if document
table.insert __, document
else
print "warning: could not import #{fileName}: #{reason}"
print "Registering index."
table.insert @documents, 1, Document.index self
updateFilesList: =>
getFiles = (path) ->
coroutine.wrap ->
for file in lfs.dir path
if file\sub(1, 1) == "."
continue
file = path .. "/" .. file
file = file\gsub("//*", "/")
attributes = lfs.attributes file
if attributes.mode == "directory"
for nFile in getFiles file
coroutine.yield nFile
else
coroutine.yield file
@files = with files = [filename for filename in *(@files or {})]
index = 1
while index <= #files
file = files[index]
attributes = lfs.attributes file
if not attributes or attributes.mode == "directory"
for nFile in getFiles file
if nFile\match '%.moon$'
print "Registering #{nFile}."
table.insert files, nFile
print "Unregistering #{file}"
table.remove files, index
continue
index += 1
.copy = (@files or {}).copy or {}
setDefaultValues: =>
@template or= findMoon "hestia.templates.bulma"
@outputExtension or= ".xhtml"
@discountFlags or= {
"toc", "extrafootnote", "dlextra", "fencedcode"
}
@inputPrefix or= ''
@outputDirectory or= ''
@templateFiles or= {}
loadTemplate: (template = @template) =>
@template, reason = switch type template
when "string"
Template.fromFilePath template
when "function"
Template template
else
nil, "invalid value provided"
unless @template
return nil, reason
return @template
render: (document) =>
with file, reason = io.open document.outputFilePath, "w"
unless file
return nil, reason
\write @template\render document
\close!
true
copyFiles: =>
if type(@files.copy) == 'table'
for file in *@files.copy
status, err = @\copyFile file, @inputPrefix, @outputDirectory
unless status
return nil, err
if type(@templateFiles) == 'table'
for file in *@templateFiles
ofile=file\gsub '^.+/', ''
status , err = @\copyFile file, '', @outputDirectory, ofile
unless status
return nil, err
true
copyFile: (file, inputPrefix, outputDirectory, ofile) =>
ofile or= file
ipath = inputPrefix .. file
opath = outputDirectory .. ofile
print 'copying: %s'\format ipath
print ' ... reading: %s'\format ipath
ihandle,err=io.open ipath, 'r'
unless ihandle
return nil, err
print ' ... writing: %s'\format opath
ohandle,err=io.open opath, 'w'
unless ohandle
return nil, err
ohandle\write ihandle\read'*a'
__tostring: => "<Project: #{@title}>"
| 22.712821 | 121 | 0.644615 |
a0966c4ce246a5a684aa00a0a805c919670c1a5c | 6,231 | VERSION = "1.3.0"
import insert, concat from table
import load, setfenv, assert, type, error, tostring, tonumber, setmetatable from _G
setfenv = setfenv or (fn, env) ->
local name
i = 1
while true
name = debug.getupvalue fn, i
break if not name or name == "_ENV"
i += 1
if name
debug.upvaluejoin fn, i, (-> env), 1
fn
html_escape_entities = {
['&']: '&'
['<']: '<'
['>']: '>'
['"']: '"'
["'"]: '''
}
html_escape = (str) ->
(str\gsub [=[["><'&]]=], html_escape_entities)
get_line = (str, line_num) ->
-- todo: this returns an extra blank line at the end
for line in str\gmatch "([^\n]*)\n?"
return line if line_num == 1
line_num -= 1
pos_to_line = (str, pos) ->
line = 1
for _ in str\sub(1, pos)\gmatch("\n")
line += 1
line
class Compiler
new: =>
@buffer = {}
@i = 0
render: =>
table.concat @buffer
push: (str, ...) =>
i = @i + 1
@buffer[i] = str
@i = i
@push ... if ...
header: =>
@push "local _tostring, _escape, _b, _b_i = ...\n"
footer: =>
@push "return _b"
increment: =>
@push "_b_i = _b_i + 1\n"
mark: (pos) =>
@push "--[[", tostring(pos), "]] "
assign: (...) =>
@push "_b[_b_i] = ", ...
@push "\n" if ...
class Parser
open_tag: "<%"
close_tag: "%>"
modifiers: "^[=-]"
html_escape: true
next_tag: =>
start, stop = @str\find @open_tag, @pos, true
-- no more tags, all done
unless start
@push_raw @pos, #@str
return false
-- add text before
unless start == @pos
@push_raw @pos, start - 1
@pos = stop + 1
modifier = if @str\match @modifiers, @pos
with @str\sub @pos, @pos
@pos += 1
close_start, close_stop = @str\find @close_tag, @pos, true
unless close_start
return nil, @error_for_pos start, "failed to find closing tag"
while @in_string @pos, close_start
close_start, close_stop = @str\find @close_tag, close_stop, true
unless close_start
return nil, @error_for_pos start, "failed to find string close"
trim_newline = if "-" == @str\sub close_start - 1, close_start - 1
close_start -= 1
true
@push_code modifier or "code", @pos, close_start - 1
@pos = close_stop + 1
if trim_newline
if match = @str\match "^\n", @pos
@pos += #match
true
-- see if stop leaves us in the middle of a string
in_string: (start, stop) =>
in_string = false
end_delim = nil
escape = false
pos = 0
skip_until = nil
chunk = @str\sub start, stop
for char in chunk\gmatch "."
pos += 1
if skip_until
continue if pos <= skip_until
skip_until = nil
if end_delim
if end_delim == char and not escape
in_string = false
end_delim = nil
else
if char == "'" or char == '"'
end_delim = char
in_string = true
if char == "["
if lstring = chunk\match "^%[=*%[", pos
lstring_end = lstring\gsub "%[", "]"
lstring_p1, lstring_p2 = chunk\find lstring_end, pos, true
-- no closing lstring, must be inside string
return true unless lstring_p1
skip_until = lstring_p2
escape = char == "\\"
in_string
push_raw: (start, stop) =>
insert @chunks, @str\sub start, stop
push_code: (kind, start, stop) =>
insert @chunks, {
kind, @str\sub(start, stop), start
}
compile: (str) =>
success, err = @parse str
return nil, err unless success
fn, err = @load @chunks_to_lua!
return nil, err unless fn
(...) ->
buffer, err = @run fn, ...
if buffer
concat buffer
else
nil, err
parse: (@str) =>
assert type(@str) == "string", "expecting string for parse"
@pos = 1
@chunks = {}
while true
found, err = @next_tag!
return nil, err if err
break unless found
true
parse_error: (err, code) =>
line_no, err_msg = err\match "%[.-%]:(%d+): (.*)$"
line_no = tonumber line_no
return unless line_no
line = get_line code, line_no
source_pos = tonumber line\match "^%-%-%[%[(%d+)%]%]"
return unless source_pos
@error_for_pos source_pos, err_msg
error_for_pos: (source_pos, err_msg) =>
source_line_no = pos_to_line @str, source_pos
source_line = get_line @str, source_line_no
"#{err_msg} [#{source_line_no}]: #{source_line}"
-- converts lua string into template function
load: (code, name="etlua") =>
code_fn = do
code_ref = code
->
with ret = code_ref
code_ref = nil
fn, err = load code_fn, name
unless fn
-- try to extract meaningful error message
if err_msg = @parse_error err, code
return nil, err_msg
return nil, err
fn
-- takes a function from @load and executes it with correct parameters
run: (fn, env={}, buffer, i, ...) =>
combined_env = setmetatable {}, __index: (name) =>
val = env[name]
val = _G[name] if val == nil
val
unless buffer
buffer = {}
i = 0
setfenv fn, combined_env
fn tostring, html_escape, buffer, i, ...
compile_to_lua: (str, ...) =>
success, err = @parse str
return nil, err unless success
@chunks_to_lua ...
-- generates the code of the template
chunks_to_lua: (compiler_cls=Compiler) =>
r = compiler_cls!
r\header!
for chunk in *@chunks
t = type chunk
t = chunk[1] if t == "table"
switch t
when "string"
r\increment!
r\assign ("%q")\format(chunk)
when "code"
r\mark chunk[3]
r\push chunk[2], "\n"
when "=", "-"
r\increment!
r\mark chunk[3]
r\assign!
if t == "=" and @html_escape
r\push "_escape(_tostring(", chunk[2], "))\n"
else
r\push "_tostring(", chunk[2], ")\n"
else
error "unknown type #{t}"
r\footer!
r\render!
compile = Parser!\compile
render = (str, ...) ->
fn, err = compile(str)
if fn
fn ...
else
nil, err
{ :compile, :render, :Parser, :Compiler, _version: VERSION }
| 21.786713 | 83 | 0.552399 |
5c0486e331a2401b11119ee082c33178e99f1927 | 6,488 | config = (require 'lapis.config').get!
csrf = require 'lapis.csrf'
mail = require 'resty.mail'
validation = require 'validation'
import to_json from require 'lapis.util'
import decode_with_secret, encode_with_secret from require 'lapis.util.encoding'
import validate_functions, validate from require 'lapis.validate'
for i in *{ 'is_email', 'has_filetype', 'smaller_than' }
validate_functions[i] = validation[i]
import Applications, ChosenTasks, Uploads from require 'models'
class SubmitApplication
submit: (params, model, url_builder) =>
errors = { }
tasks = { }
tasklen = #model.tasks
local tid
for k, v in pairs params
if tid = k\match "^tasks%[(%d+)%]$"
tid = tonumber tid
if tid >= 1 and tid <= tasklen
table.insert tasks, tid
else
errors.bad_request = true
validations = {
{ 'firstname', exists: true, max_length: 255, 'invalid_name' },
{ 'lastname', exists: true, max_length: 255, 'invalid_name' },
{ 'email', exists: true, max_length: 255, is_email: true, 'invalid_email' },
{ 'class', one_of: model.form.classes, 'bad_request' }
}
if model.form.all_schools
table.insert(validations, { 'school', exists: true, 'bad_request' })
else
table.insert(validations, { 'school', one_of: model.form.schools, 'bad_request' })
ret = validate params, validations
if #model.tasks == 0
errors.task_number_mismatch = true if #tasks > 0
else
errors.task_number_mismatch = true if #tasks < 2
if ret
errors[e] = true for e in *ret
local class_id
for i, v in pairs model.form.classes
class_id = i if v == params.class
local school_id
if model.form.all_schools
school_id = params.school
else
for i, v in pairs model.form.schools
school_id = i if v == params.school
err_array = { }
for k, _ in pairs errors
table.insert err_array, k
return nil, err_array if #err_array > 0
prev_app = Applications\find email: params.email
if prev_app
if config.disable_email_confirmation
return nil, { 'duplicate_application' }
else
return nil, { 'duplicate_application' } if prev_app.submitted != 0
return nil, { 'too_frequent' } if prev_app.email_sent and os.time! - (tonumber prev_app.email_sent) < config.email_cooldown
prev_app\delete!
local application, err
with params
application, err = Applications\create {
first_name: .firstname
last_name: .lastname
email: .email
class: class_id
school: school_id
submitted: 0
}
if not application
print err
return nil, { 'internal_error' }
appid = application.id
for t in *tasks
ChosenTasks\create {
application_id: appid
task: t
}
url = (url_builder '/prijava/upload/') .. encode_with_secret { id: appid }
fn_ret = true
if not config.disable_email_confirmation
local msg
with model.email
txt = .text\gsub '%%1', url
msg =
from: config.smtp_from
to: { params.email }
subject: .subject,
text: txt
mailer, err = mail.new
host: config.smtp_server,
port: config.smtp_port,
starttls: true,
username: config.smtp_username,
password: config.smtp_password
if not mailer
print err
return nil, { 'internal_error' }
ret, err = mailer\send msg
if not ret
print err
return nil, { 'internal_error' }
else
fn_ret = url
application\update
email_sent: os.time!
fn_ret
get_application: (token) =>
data = decode_with_secret token
return nil if not data or not data.id
appl = Applications\find data.id
return nil if not appl or appl.submitted != 0
appl
store_file: (extension, buf, application_id, context) =>
upl = Uploads\create { :application_id, :context }
return nil, 'could not create upload in database' if not upl
fname = "#{config.uploads_dir}/#{upl.id}.#{extension}"
f = io.open fname, 'wb'
return nil, "could not open file `#{fname}`" if not f
f\write buf
f\close!
upl
upload: (post_params, token, model, tasklist) =>
appl, _ = SubmitApplication.get_application self, token
return nil, { 'no_such_application' } if not appl
validation = {
{ 'pitch', exists: true, 'missing_pitch' }
}
import insert from table
tasks = { }
for t in *appl\get_chosen_tasks!
mtask = tasklist[t.task]
insert tasks, t.task
insert validation, { "tasks[#{t.task}]", is_file: true, 'invalid_file' }
insert validation, { "tasks[#{t.task}]", has_filetype: mtask.filetypes, 'invalid_filetype' }
insert validation, { "tasks[#{t.task}]", smaller_than: config.single_file_limit, 'file_too_big' }
errs = validate post_params, validation
if errs
err_tbl = { }
err_tbl[e] = true for e in *errs
if err_tbl.invalid_file
err_tbl.invalid_filetype = nil
err_tbl.file_too_big = nil
return nil, [k for k, _ in pairs err_tbl]
appl\update { submitted: os.time! }
for i in *tasks
f = post_params["tasks[#{i}]"]
ret = SubmitApplication.store_file self, (validate_functions.has_filetype f, unpack tasklist[i].filetypes), f.content, appl.id, "task #{i}"
return nil, { 'internal_error' } if not ret
f.content = nil
ret = SubmitApplication.store_file self, 'txt', post_params['pitch'], appl.id, "pitch"
return nil, { 'internal_error' } if not ret
true
| 33.271795 | 151 | 0.551326 |
9e8d37511a7cf8cd53a381754c7b2095510a9379 | 98 | import Widget from require "lapis.html"
class UserInfo extends Widget
content: =>
raw @doc
| 16.333333 | 39 | 0.72449 |
26447a8fa476b5f477f5671e9de1aa7e40f7af48 | 593 | --- rust mode for howl from [ta-rust](https://bitbucket.org/a_baez/ta-rust)
-- See @{README.md} for details on usage.
-- @author [Alejandro Baez](https://keybase.io/baez)
-- @copyright 2016
-- @license MIT (see LICENSE)
-- @module mode
import style from howl.ui
style.define 'extension', "special"
style.define 'attribute', "preproc"
style.define 'char', 'constant'
{
lexer: bundle_load('rust_lexer')
comment_syntax: '//'
auto_pairs: {
'(': ')'
'[': ']'
'{': '}'
'"': '"'
}
default_config:
use_tabs: false
tab_width: 4
indent: 4
edge_column: 99
}
| 19.766667 | 75 | 0.618887 |
dbf577d853785563cab6d0d565a2bb242a0d933d | 4,105 | -- Copyright 2012-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
import app, bindings, interact, Project from howl
import File from howl.io
import Window from howl.ui
require 'howl.ui.icons.font_awesome'
require 'howl.interactions.selection_list'
require 'howl.interactions.location_selection'
require 'howl.interactions.buffer_selection'
describe 'buffer_selection', ->
local command_line, editor
buffers = {}
before_each ->
app.window = Window!
app.window\realize!
editor = {
preview: (@buffer) => nil
}
command_line = app.window.command_line
for b in *app.buffers
app\close_buffer b
for title in *{'a1-buffer', 'b-buffer', 'c-buffer', 'a2-buffer'}
b = app\new_buffer!
b.title = title
table.insert buffers, b
it "registers interactions", ->
assert.not_nil interact.select_buffer
describe 'interact.select_buffer', ->
it 'displays a list of active buffers', ->
local buflist
within_activity (-> interact.select_buffer :editor), ->
buflist = get_ui_list_widget_column 2
assert.same {'a1-buffer', 'a2-buffer', 'b-buffer', 'c-buffer'}, buflist
it 'filters the buffer list based on entered text', ->
local buflist
within_activity (-> interact.select_buffer :editor), ->
command_line\write 'a-b'
buflist = get_ui_list_widget_column 2
assert.same {'a1-buffer', 'a2-buffer'}, buflist
it 'previews currently selected buffer in the editor', ->
previews = {}
down_event = {
key_code: 65364
key_name: 'down'
alt: false
control: false
meta: false
shift: false
super: false
}
within_activity (-> interact.select_buffer :editor), ->
table.insert previews, editor.buffer.title
command_line\handle_keypress down_event
table.insert previews, editor.buffer.title
assert.same {'a1-buffer', 'a2-buffer'}, previews
context 'when get_buffers is provided', ->
it 'calls get_buffers to get buffer list', ->
local buflist
get_buffers = -> {buffers[1], buffers[3]}
within_activity (-> interact.select_buffer :editor, :get_buffers), ->
buflist = get_ui_list_widget_column 2
assert.same {'a1-buffer', 'c-buffer'}, buflist
context 'sending binding_for("buffer-close")', ->
keymap = ctrl_w: 'buffer-close'
before_each -> bindings.push keymap
after_each -> bindings.remove keymap
close_event = {
alt: false,
character: "w",
control: true,
key_code: 119,
key_name: "w",
meta: false,
shift: false,
super: false
}
it 'closes selected buffer', ->
local buflist
within_activity (-> interact.select_buffer :editor), ->
command_line\handle_keypress close_event
command_line\handle_keypress close_event
buflist = get_ui_list_widget_column 2
assert.same {'b-buffer', 'c-buffer'}, buflist
it 'preserves filter', ->
local buflist
within_activity (-> interact.select_buffer :editor), ->
command_line\write 'a-b'
command_line\handle_keypress close_event
buflist = get_ui_list_widget_column 2
assert.same {'a2-buffer'}, buflist
context 'duplicate filenames', ->
before_each ->
for b in *app.buffers
app\close_buffer b
paths = {'/project1/some/file1', '/project2/some/file1', '/project2/path1/file2', '/project2/path2/file2'}
for path in *paths
b = app\new_buffer!
b.file = File path
Project.add_root File '/project1'
Project.add_root File '/project2'
it 'uniquifies title by using project name and parent directory prefix', ->
local buflist
within_activity (-> interact.select_buffer :editor), ->
buflist = get_ui_list_widget_column 2
assert.same {'file1 [project1]', 'file1 [project2]', 'path1/file2', 'path2/file2'}, buflist
| 32.579365 | 114 | 0.638002 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.