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
|
---|---|---|---|---|---|
3fd67c7c3c79b08aca5cbd486d51d9fe3af2920c | 3,898 | sql = require'lsqlite3'
openDb = ->
db = sql.open 'cache/trigger.sql'
db\exec [[
CREATE TABLE IF NOT EXISTS trigger (
name UNIQUE ON CONFLICT REPLACE,
pattern UNIQUE ON CONFLICT REPLACE,
destination,
funcstr
);
]]
return db
triggerHelp = (source, destination, argument) =>
help = 'Usage: ¤trigger add <name>|<lua pattern>|<lua code>. Ex: ¤trigger add help|^!help (%w+)|say "%s, you need help. Delete: ¤trigger del <name>. List: ¤trigger list. Show: ¤trigger show <name>"'
patt = @ChannelCommandPattern('^%p', 'triger', destination)
help = help\gsub '¤', patt
say help
-- Construct a safe environ for trigger with two functions; say and reply
--- Preferrably you should be able to cross-call modules here to make aliasing possible
-- TODO: needs a proper sandbox to prevent endless loops, etc
sandbox = (func) ->
(source, destination, ...) =>
-- TODO check destination here to decide if it's a local or global trigger
-- Store args so we can use them in env
arg = {...}
env =
say: (str) ->
@Msg 'privmsg', destination, source, str, unpack(arg),
reply: (str) ->
@Msg 'privmsg', destination, source, source.nick..': '..str, unpack(arg),
print: (str) ->
@Msg 'privmsg', destination, source, str, unpack(arg),
:source
:destination
simplehttp:require'simplehttp'
json:require'json'
:string
:type
:tostring
:tonumber
:ipars
:pairs
:table
:next
--setfenv func, setmetatable(env, {__index: _G })
setfenv func, env
success, err = pcall func, arg
if err
say err
else
success
-- Construct a safe function to run and return a handler
triggerHandler = (source, destination, funcstr) =>
func, err = loadstring funcstr
unless func
say 'Trigger error: %s', err
else
sandbox(func)
-- Register the command
regCommand = (source, destination, name, pattern, funcstr) =>
db = openDb!
ins = db\prepare "INSERT INTO trigger (name, pattern, funcstr, destination) VALUES(?, ?, ?, ?)"
code = ins\bind_values name, pattern, funcstr, destination
code = ins\step!
code = ins\finalize!
db\close!
@RegisterCommand 'trigger', pattern, triggerHandler(@, source, destination, funcstr)
delCommand = (source, destination, name) =>
db = openDb!
-- Find pattern which is used for deletion of handler
stmt = db\prepare "SELECT pattern FROM trigger WHERE name = ?"
code = stmt\bind_values name
code = stmt\step!
if code == sqlite3.DONE
-- Invalid name
db\close!
say 'Invalid name'
return
pattern = stmt\get_values()[1]
-- Delete trigger from db
ins = db\prepare "DELETE FROM trigger WHERE name = ?"
code = ins\bind_values name
code = ins\step!
code = ins\finalize!
db\close!
@UnregisterCommand 'triggers', pattern
say "Trigger #{pattern} deleted"
listTriggers = (source, destination) =>
db = openDb!
stmt = db\prepare "SELECT name FROM trigger"
out = {}
for row in stmt\nrows! do
table.insert out, row.name
db\close!
if #out > 0
say "Triggers: "..table.concat(out, ', ')
else
say "No triggers defined"
showTrigger = (source, destination, name) =>
db = openDb!
stmt = db\prepare "SELECT * FROM trigger WHERE name = ?"
code = stmt\bind_values name
for row in stmt\nrows! do
say "Trigger: \002#{row.name}\002, pattern: #{row.pattern}, code: #{row.funcstr}"
db\close!
-- Register commands on startup
db = openDb!
for row in db\nrows 'SELECT pattern, funcstr, destination FROM trigger'
ivar2\RegisterCommand 'triggers', row.pattern, triggerHandler(ivar2, nil, row.destination, row.funcstr)
db\close!
PRIVMSG:
'^%ptrigger$': triggerHelp
'^%ptrigger add (.+)|(.+)|(.+)$': regCommand
'^%ptrigger del (.+)$': delCommand
'^%ptrigger list$': listTriggers
'^%ptrigger show (.+)$': showTrigger
| 29.089552 | 200 | 0.649564 |
7e56b6f8fb7cf6d2ab34f294df657782d2a606f5 | 68 | with smaug
.draw = ->
.graphics.print "Hello, world!", 10, 10
| 17 | 43 | 0.588235 |
6105c9d127a9071c426a1525c3b4f394c00b360b | 634 | #!/usr/bin/env moon
to_i = (size, x,y) -> y * size + x
value = (left, right, x, y, size) ->
idx = (...) -> to_i size, ...
parts = for i = 0, size - 1
table.concat {
left, "[", idx(i, y), "] * ", right, "[", idx(x, i), "]"
}
table.concat parts, " + "
generate = (left, right, size=4) ->
parts = {}
for y = 0, size - 1
for x = 0, size - 1
table.insert parts, value left, right, x, y, size
table.concat parts, ",\n"
left, right, size = ...
if not left or not right or not size or not tonumber size
print "usage: ./mult.moon left right size"
return
print generate left, right, tonumber size
| 22.642857 | 62 | 0.55205 |
ec5456df2b48eaa1b49d4690e2a1fca0ee19838b | 7,600 |
export script_name = "Bear"
export script_description = "Stuff for Bear^4"
export script_version = "0.0.1"
export script_author = "Myaamori"
export script_namespace = "myaa.Bear"
DependencyControl = require 'l0.DependencyControl'
depctrl = DependencyControl {
{
{"l0.Functional", version: "0.6.0", url: "https://github.com/TypesettingTools/Functional",
feed: "https://raw.githubusercontent.com/TypesettingTools/Functional/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.Line", version: "1.5.3", 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"},
{"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"},
}
}
F, LineCollection, Line, ASS, ConfigHandler = depctrl\requireModules!
findall = (s, c) ->
indices = {}
for i = 1, #s
if s\sub(i, i) == c
table.insert indices, i
return indices
process = (sub, sel, result) ->
lines = LineCollection sub, sel
start_angle = result.startAngle
end_angle = result.finalAngle
start_blur = result.startBlur
end_blur = result.finalBlur
accel = result.gravity
bounces = result.bounces
bounce_size = result.bounceHeight
anim_duration = result.charAnimDuration
delay = result.animDelay
blur_intact = result.leaveBlur
lines_added = 0
lines\runCallback ((lines, line, i) ->
ass = ASS\parse line
line\getPropertiesFromStyle!
str = ass\copy!\stripTags!\getString!
copy = ass\copy!
end_time = line.start_time + delay * (#str - 1) + anim_duration
for j, charline in ipairs ass\splitAtIntervals 1, 4, true
charass = charline.ASS
start_frame = aegisub.frame_from_ms charline.start_time
end_frame = aegisub.frame_from_ms end_time
pos = charass\getPosition!
for frame = start_frame, end_frame + 1
cur_time = aegisub.ms_from_frame(frame) - charline.start_time
p = math.max(0, math.min(1, (cur_time - delay * (j - 1)) / anim_duration))
if p <= 0
continue
curve = p * bounces * math.pi
init_p = math.max(0, math.min(1, p * bounces * 2))
copy = Line charline, lines
copy.start_time = aegisub.ms_from_frame frame
if p >= 1
copy.end_time = line.end_time
else
copy.end_time = aegisub.ms_from_frame (frame + 1)
copy\interpolateTransforms cur_time
copyass = ASS\parse copy
angle = ASS\createTag "angle", (1 - init_p) * start_angle + init_p * end_angle
alpha = ASS\createTag "alpha", (1 - init_p) * 255 + init_p * 0
pos = copyass\getPosition!
pos\add 0, -bounce_size * math.abs(math.sin(curve)) * math.pow((1 - p), accel)
tags = {pos, angle, alpha}
blurtags = copyass\getTags {"blur"}
if #blurtags == 0 or not blur_intact
blur = ASS\createTag "blur", (1 - init_p) * start_blur + init_p * end_blur
table.insert tags, blur
copyass\replaceTags tags
copyass\commit!
lines_added += 1
lines\addLine copy, nil, true, line.number + lines_added
if p >= 1
break
line.comment = true
), true
lines\replaceLines!
lines\insertLines!
return lines\getSelection!
dialog = {
main: {
animDelayLabel: {
class: "label", label: "Animation start delay:",
x: 0, y: 0, width: 1, height: 1
},
animDelay: {
class: "intedit",
value: 20, config: true, min: 1,
x: 1, y: 0, width: 1, height: 1, hint: "The gap in time of the start of the animation between each character (ms)"
},
charAnimDurationLabel: {
class: "label", label: "Character animation duration:",
x: 0, y: 1, width: 1, height: 1
},
charAnimDuration: {
class: "intedit",
value: 500, config: true, min: 0,
x: 1, y: 1, width: 1, height: 1, hint: "The duration of the animation for each character (ms)"
},
startAngleLabel: {
class: "label", label: "Start angle:",
x: 0, y: 2, width: 1, height: 1
},
startAngle: {
class: "floatedit",
value: 15, config: true,
x: 1, y: 2, width: 1, height: 1, hint: "The initial angle of each character (degrees)"
},
finalAngleLabel: {
class: "label", label: "Final angle:",
x: 0, y: 3, width: 1, height: 1
},
finalAngle: {
class: "floatedit",
value: 0, config: true,
x: 1, y: 3, width: 1, height: 1, hint: "The final angle of each character (degrees)"
},
startBlurLabel: {
class: "label", label: "Start blur:",
x: 0, y: 4, width: 1, height: 1
},
startBlur: {
class: "floatedit",
value: 3, config: true,
x: 1, y: 4, width: 1, height: 1, hint: "The initial blur of each character"
},
finalBlurLabel: {
class: "label", label: "Final blur:",
x: 0, y: 5, width: 1, height: 1
},
finalBlur: {
class: "floatedit",
value: 1, config: true,
x: 1, y: 5, width: 1, height: 1, hint: "The final blur of each character"
},
leaveBlur: {
class: "checkbox", label: "Don't overwrite blur",
value: true, config: true,
x: 0, y: 6, width: 2, height: 1, hint: "Leaves the blur intact if already specified on the line"
},
bouncesLabel: {
class: "label", label: "Bounces:",
x: 0, y: 7, width: 1, height: 1
},
bounces: {
class: "intedit",
value: 2, config: true, min: 1,
x: 1, y: 7, width: 1, height: 1, hint: "The number of times each character should bounce"
},
bounceHeightLabel: {
class: "label", label: "Bounce height:",
x: 0, y: 8, width: 1, height: 1
},
bounceHeight: {
class: "intedit",
value: 30, config: true, min: 1,
x: 1, y: 8, width: 1, height: 1, hint: "The height of the bounces"
},
gravityLabel: {
class: "label", label: "Gravity:",
x: 0, y: 9, width: 1, height: 1
},
gravity: {
class: "floatedit",
value: 1.2, config: true, min: 0,
x: 1, y: 9, width: 1, height: 1, hint: "How quickly the bounce height should decrease (1 = linear, 0 = no decrease)"
},
}
}
show_dialog = (sub, sel) ->
options = ConfigHandler dialog, depctrl.configFile, false, script_version, depctrl.configDig
options\read!
options\updateInterface "main"
button, result = aegisub.dialog.display dialog.main
if button
options\updateConfiguration result, "main"
options\write!
return process sub, sel, result
depctrl\registerMacros {
{"Make next episode title", "", show_dialog}
}
| 34.703196 | 122 | 0.588684 |
479c10d0f9863a3aecc6416570ec8eab2cded415 | 1,011 | class Animation
new: ( @initialValue, @endValue, @duration, @updateCb, @finishedCb, @accel = 1 ) =>
@value = @initialValue
@linearProgress = 0
@lastUpdate = mp.get_time!
@durationR = 1/@duration
@isFinished = (@duration <= 0)
@active = false
@isReversed = false
update: ( now ) =>
if @isReversed
@linearProgress = math.max 0, math.min 1, @linearProgress + (@lastUpdate - now)*@durationR
if @linearProgress == 0
@isFinished = true
else
@linearProgress = math.max 0, math.min 1, @linearProgress + (now - @lastUpdate)*@durationR
if @linearProgress == 1
@isFinished = true
@lastUpdate = now
progress = math.pow @linearProgress, @accel
@value = (1 - progress) * @initialValue + progress * @endValue
@.updateCb @value
if @isFinished and @finishedCb
@finishedCb!
return @isFinished
interrupt: ( reverse ) =>
@finishedCb = nil
@lastUpdate = mp.get_time!
@isReversed = reverse
unless @active
@isFinished = false
AnimationQueue.addAnimation @
| 24.658537 | 93 | 0.667656 |
29dead05e65e2d86a6abc3af0478d80e37dde9f3 | 5,395 | {:app, :interact, :Project, :activities, :config} = howl
{:Process} = howl.io
{:PropertyTable} = howl.util
{:get_monotonic_time} = require 'ljglibs.glib'
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
config.define
name: 'ctags_command'
description: 'Command line tool used to generate the "tags" file'
default: 'ctags -R --fields="n"'
type_of: 'string'
generate_tags = ->
buffer = app.editor and app.editor.buffer
file = buffer.file or buffer.directory
cmd = config.for_file(file).ctags_command
cmd_with_args = {}
for arg in cmd\gmatch '%S+'
table.insert cmd_with_args, arg
working_directory = get_project_root!
success, ret = pcall Process.open_pipe, cmd_with_args, :working_directory
if success
process = ret
out, err = activities.run_process {title: "Generating tags..."}, process
unless process.successful
msg = (if err.is_blank then out else err)\gsub '\n', ' '
log.error "Error generating tags! #{cmd}: " .. msg
else
log.error ret
-- A version of generate_tags that doesn't block but doesn't show the nice
-- activity popup window. I can't decide which one is better so will try both for while.
generate_tags_async = ->
buffer = app.editor and app.editor.buffer
file = buffer.file or buffer.directory
cmd = config.for_file(file).ctags_command
cmd_with_args = {}
for arg in cmd\gmatch '%S+'
table.insert cmd_with_args, arg
working_directory = get_project_root!
log.info "Generating tags..."
out, err, p = Process.execute cmd_with_args, :working_directory
if p.successful
log.info "Done generating tags!"
else
msg = (if err.is_blank then out else err)\gsub '\n', ' '
log.error "Error generating tags! #{cmd}: " .. msg
get_query_tag = ->
editor = app.editor
query = nil
if editor.selection.empty
query = editor.current_context.word.text
else
query = editor.selection.text
if not query or query.is_empty
query = interact.read_text prompt: "Enter tag name to jump to: "
query
-- Search for the tags file, starting at the directory of the
-- currently edited file and going up until stop_dir is reached.
-- tags_filename: short file name of the tags file to look for. Typically 'tags' or 'TAGS'
get_tags_file = (tags_filename, stop_dir) ->
buffer = app.editor and app.editor.buffer
file = buffer.file or buffer.directory
dir = file.parent
tags_file = dir\join tags_filename
if not tags_file.exists
while dir != stop_dir do
dir = dir.parent
tags_file = dir\join tags_filename
if tags_file.exists break
tags_file, dir
goto_definition = ->
buffer = app.editor and app.editor.buffer
editor_file = buffer.file or buffer.directory
query_tag = get_query_tag!
if not query_tag or query_tag == ""
log.error "No query tag specified!"
return
tags_file, tags_dir = get_tags_file "tags", get_project_root!
unless tags_file.exists
log.error "Tags file #{tags_file} doesn't exist!"
return
locations = {}
is_duplicate = (loc) ->
for l in *locations
if l.line_nr == loc.line_nr and l.file == loc.file
return true
return false
start = get_monotonic_time!
query_with_parens = '(' .. query_tag .. ')'
query_with_space = query_tag .. ' '
-- TODO: Iterating over every line in the file. This is slow!
-- Also, check if keeping the file in memory is faster.
for line in io.lines tags_file.path do
unless line\starts_with('!')
{ tag, file, excerpt } = line\split '\t'
-- Using starts_with to allow product types in Haskell and Elm.
-- We also check for the tag in parens because Haskell infix functions
-- are listed as (function_name) in the tags file. E.g. (||).
-- TODO: display Haskell instances for a data type? The info is in the tags file
if tag == query_tag or tag\starts_with query_with_space or tag == query_with_parens
line_nr = line\umatch 'line:(%d+)'
file_relpath = if file\starts_with('./')
file\usub(3)
else
file
file_obj = tags_dir\join file_relpath
loc = {
howl.ui.markup.howl "<comment>#{file_relpath}</>:<number>#{line_nr}</>"
excerpt\usub(3, excerpt.ulen - 4) -- Remove the regex markers
file: file_obj
line_nr: tonumber line_nr
score: if file_obj == editor_file -- Currently edited file at the top
30
else
20
}
if not is_duplicate loc
table.insert locations, loc
-- Sort by score (desc) and then alphabetically (asc)
table.sort locations, (a, b) -> if a.score != b.score
a.score > b.score
else
a.file < b.file
duration = (get_monotonic_time! - start) / 1000
-- log.info "Finished tag lookup in #{duration} ms"
if #locations == 1
app\open locations[1]
else if #locations > 1
app\open interact.select_location
title: "Definitions of '#{query_tag}' in #{tags_file.short_path}"
items: locations
columns: { {}, {} }
else
log.error "Tag #{query_tag} not found!"
PropertyTable {
:generate_tags,
:generate_tags_async,
:goto_definition
}
| 30.653409 | 90 | 0.674328 |
1ebc49c19244149d132dff8479246aff695af62f | 6,663 | -- Copyright 2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
howl.util.lpeg_lexer ->
c = capture
nim_identifier = (identifier) ->
word_char = alpha + '_' + digit
pattern = (-B(1) + B(-word_char)) * P(identifier\usub(1, 1))
for char in *identifier\usub(2)
pattern *= P'_'^-1
pattern *= (P(char.ulower) + P(char.uupper))
return pattern * #-word_char
keywords = {
'addr', 'and', 'as', 'asm', 'atomic', 'bind', 'block', 'break', 'case',
'cast', 'concept', 'const', 'continue', 'converter', 'defer', 'discard',
'distinct', 'div', 'do', 'elif', 'else', 'end', 'enum', 'except', 'export',
'finally', 'for', 'from', 'func', 'if', 'import', 'in',
'include', 'interface', 'is', 'isnot', 'iterator', 'let', 'macro',
'method', 'mixin', 'mod', 'nil', 'not', 'notin', 'object', 'of', 'or',
'out', 'proc', 'ptr', 'raise', 'ref', 'return', 'shl', 'shr', 'static',
'template', 'try', 'tuple', 'type', 'using', 'var', 'when', 'while',
'with', 'without', 'xor', 'yield',
}
keyword = c 'keyword', -B'.' * any [nim_identifier(keyword) for keyword in *keywords]
builtin_types = {
"int",
"int8",
"int16",
"int32",
"int64",
"uint",
"uint8",
"uint16",
"uint32",
"uint64",
"float",
"float32",
"float64",
"bool",
"char",
"string",
"cstring",
"pointer",
"expr",
"stmt",
"typedesc",
"void",
"auto",
"any",
"untyped",
"typed",
"range",
"array",
"openArray",
"varargs",
"seq",
"set",
"byte",
"clong",
"culong",
"cchar",
"cschar",
"cshort",
"cint",
"csize",
"clonglong",
"cfloat",
"cdouble",
"clongdouble",
"cuchar",
"cushort",
"cuint",
"culonglong",
"cstringArray",
}
builtin = c 'type', -B'.' * any [nim_identifier(type_name) for type_name in *builtin_types]
comment = c 'comment', P'#' * scan_until(eol)
operator = c 'operator', S'=+-*/<>@$~&%|!?^.:\\[]{}(),'
ident = (alpha + '_')^1 * (alpha + digit + S'_')^0
backquoted_name = span('`', '`')
identifier = c 'identifier', ident
function_name = c('whitespace', space^1) * c('fdecl', any {ident, backquoted_name})
function_export_marker = c('whitespace', space^0) * c('special', P'*'^-1)
proc_fdecl = c('keyword', nim_identifier('proc')) * function_name * function_export_marker
iterator_fdecl = c('keyword', nim_identifier('iterator')) * function_name * function_export_marker
method_fdecl = c('keyword', nim_identifier('method')) * function_name * function_export_marker
template_fdecl = c('keyword', nim_identifier('template')) * function_name * function_export_marker
macro_fdecl = c('keyword', nim_identifier('macro')) * function_name * function_export_marker
boolean = c 'special', nim_identifier('true') + nim_identifier('false')
type_name = c 'type', upper^1 * (alpha + digit + '_')^0
backquoted_type_name = c 'type', P'`' * type_name * P'`'
-- backquoted_type_name = c 'class', P'`' * type_name * P'`'
pragma = c 'preproc', span('{.', '}')
hex_digit_run = xdigit^1 * (P'_' * xdigit^1)^0
hexadecimal_number = P'0' * S'xX' * hex_digit_run
oct_digit_run = R'07'^1 * (P'_' * R'07'^1)^0
octal_number = P'0' * S'oO'^-1 * oct_digit_run
binary_digit_run = S'01'^1 * (P'_' * S'01'^1)^0
binary_number = P'0' * S'bB' * binary_digit_run
digit_run = digit^1 * (P'_' * digit^1)^0
simple_number = digit_run
number_with_point = digit_run * '.' * digit_run
integer_size_suffix = c 'special', P"'" * (P'i' + P'u') * any {'8', '16', '32', '64'}
float_size_suffix = c 'special', P"'" * P'f' * any {'32', '64'}
exponent_suffix = c('special', S'eE') * c('number', S('-+')^-1 * digit_run)
integer = c 'number', any {
octal_number
hexadecimal_number
binary_number
simple_number
}
number = c('number', simple_number) * exponent_suffix * (float_size_suffix^-1)
number += c('number', number_with_point) * (exponent_suffix^-1) * (float_size_suffix^-1)
number += (integer * integer_size_suffix^-1)
number *= #-(alpha + digit + S'_') -- no alphanum should be attached to the number
string = c 'string', span('"', '"', '\\')
tq_string = c 'string', span('"""', '"""' * -P'"')
raw_string = sequence {
c 'special', S'rR'
-- match either two double quotes (which is an escaped quote) or any non-quote character
c 'string', P'"' * (P'""' + complement'"')^0 * P'"'
}
char = c 'char', B(-digit) * span('\'', '\'', '\\')
-- Nim's format strings are a bit complicated... They come in three forms:
-- fmt"string" -> raw string: no backslash escapes, "" is an escaped quote
-- (fmt|&)"""string""" -> triple quote string: no backslash escapes, multiple end quotes
-- &"string" -> standard string (backslash escapes allowed)
nim_fmt_string_chunk = (name, close_p, escape_p) ->
close_p = P(close_p)
escape_p = P(escape_p) if escape_p
stop = close_p + '{'
stop = escape_p + stop if escape_p
choices = any {
c 'string', close_p
P(-1)
sequence {
any {
c 'string', '{{'
V'fmt_string_interpolation'
c 'string', P(1)
}
V"#{name}_fmt_string_chunk"
}
}
if escape_p
escape = sequence {
c 'string', escape_p
V"#{name}_fmt_string_chunk"
}
choices = escape + choices
sequence {
c 'string', scan_until stop
choices
}
P {
'all'
all: any {
number,
V'string',
char,
pragma,
comment,
iterator_fdecl,
proc_fdecl,
method_fdecl,
template_fdecl,
macro_fdecl,
keyword,
builtin,
boolean,
type_name,
backquoted_type_name,
identifier,
operator,
}
string: any {
V'tq_fmt_string'
V'raw_fmt_string'
V'and_fmt_string'
raw_string
tq_string
string
}
fmt_string_interpolation: sequence {
c 'operator', '{'
((V'all' + space + P(1)) - S'}:')^0
c 'special', (P':' * complement'}'^0)^-1
c 'operator', '}'
}
raw_fmt_string: sequence {
c 'special', P'fmt'
c 'string', P'"'
V'raw_fmt_string_chunk'
}
raw_fmt_string_chunk: nim_fmt_string_chunk 'raw', '"', '""'
tq_fmt_string: sequence {
c 'special', any { 'fmt', '&' }
c 'string', P'"""'
V'tq_fmt_string_chunk'
}
tq_fmt_string_chunk: nim_fmt_string_chunk 'tq', '"""' * -P'"'
and_fmt_string: sequence {
c 'special', '&'
c 'string', P'"'
V'and_fmt_string_chunk'
}
and_fmt_string_chunk: nim_fmt_string_chunk 'and', '"', '\\' * P(1)
}
| 26.866935 | 100 | 0.576017 |
014c664953620ced36a5420339d3cc83068039d8 | 3,710 |
-- lua stuff
math = require 'math'
howling = require 'howling'
-- ooc stuff
dye_sprite = require 'dye:dye/sprite'
dye_text = require 'dye:dye/text'
dye_primitives = require 'dye:dye/primitives'
dye_input = require 'dye:dye/input'
quantum_world = require 'quantum:quantum/world'
io_File = require 'sdk:io/File'
-- util stuff
map = require 'butt.map'
-- Where the magic 'appens
class App
new: (@butt) =>
@dye = @butt.dye
@world = quantum_world.World.new()
@world.gravity = -0.71
@world.maxFallVel = -20
@input = @dye.input
@frame = 0
-- set dat clear color
@dye.mainPass.clearColor\set__bang(255, 255, 255)
-- load a map maybe?
@map = map.Map(@, "assets/maps/tuto1.tmx")
@dye\add @map.group
-- PHYSX TEST STARTS
shape = quantum_world.AABBShape.new(32, 64)
@body = quantum_world.Body.new(shape)
@world\addBody @body
@hero = dye_sprite.GlSprite.new("assets/png/hero-idle.png")
@hero.pos = @body.pos
@hero.pos\set__bang(600, 400)
@dye\add @hero
-- PHYSX TEST ENDS
-- maek some text
@text = dye_text.GlText.new 'assets/ttf/noodle.ttf', '', 40
with @text.color
.r = 255
.g = 128
.b = 50
@textbg = dye_primitives.GlRectangle.new(@text.size)
with @textbg.color
.r = 0
.g = 0
.b = 0
@textbg.center = false
@dye\add @textbg
@dye\add @text
@offsetindex = 0
onkp = (kp) ->
@keyPress(kp.scancode)
@input\onKeyPress_any howling.make_closure(onkp, "void", dye_input.KeyPress)
keyPress: (scancode) =>
switch scancode
when dye_input.KeyCode.DOWN
@offsetindex -= 1
when dye_input.KeyCode.UP
@offsetindex += 1
when dye_input.KeyCode.LEFT
return
when dye_input.KeyCode.RIGHT
return
when dye_input.KeyCode.SPACE
if @body.touchesGround
@body.vel.y = 12
else
print "Unknown scancode: #{scancode}"
clampOffsetIndex: =>
if @offsetindex > @map.numLayers
@offsetindex -= @map.numLayers + 1
elseif @offsetindex < 0
@offsetindex += @map.numLayers + 1
focusLayer: =>
for i = 1, tonumber(@map.numLayers)
if @map.layers[i] == nil
continue
sprite = @map.layers[i].sprite
with sprite
if @offsetindex == 0 or i == @offsetindex
.opacity = 1.0
else
.opacity = 0.2
update: =>
-- count frames, yay
@frame += 1
-- update physics
delta = 0.33
for i = 1,3
@world\collide(delta)
@world\step(delta)
speed = 6.5
---- key input
if @input\isPressed(dye_input.KeyCode.LEFT)
@hero.scale.x = -1
@body.vel.x = -speed
elseif @input\isPressed(dye_input.KeyCode.RIGHT)
@hero.scale.x = 1
@body.vel.x = speed
else
@body.vel.x *= 0.85
@clampOffsetIndex()
@focusLayer()
if @offsetindex == 0
@text.value = "all layers"
else if @map.layers[@offsetindex] == nil
@text.value = "layer #{@offsetindex}"
else
layer = @map.layers[@offsetindex]
@text.value = "layer #{@offsetindex}: #{layer.tlayer.name}"
if layer.solid
@text.value = "#{@text.value} - solid"
@text.value = "#{@text.value} - pos #{@body.pos\toString!} - vel #{@body.vel\toString!}"
-- center text
with @text.pos
-- .x = 1280 / 2 - @text.size.x / 2
.x = 200
.y = 40
with @textbg.pos
.x = @text.pos.x - 10
.y = @text.pos.y - 10
with @textbg.size
.x = @text.size.x + 20
.y = @text.size.y + 20
-- update window title
@dye\setTitle "bps = #{math.floor(@butt.loop.fps)}"
-- export da module
return {
:App
}
| 22.349398 | 92 | 0.581671 |
ac46ed2742e2460ad9f67f0d1c1c4255844b3465 | 1,020 | ----------------------------------------------------------------
-- A @{Block} of code which is used as a placeholder for other
-- code @{Block}s or @{Line}s.
--
-- @classmod SpaceBlock
-- @author Richard Voelker
-- @license MIT
----------------------------------------------------------------
local Block
if game
pluginModel = script.Parent.Parent.Parent.Parent
Block = require(pluginModel.com.blacksheepherd.code.Block)
else
Block = require "com.blacksheepherd.code.Block"
-- {{ TBSHTEMPLATE:BEGIN }}
class SpaceBlock extends Block
AddChild: (child) =>
child\SetIndent @_indent
table.insert @_children, child
SetIndent: (indent) =>
super indent
for child in *@_children
child\SetIndent indent
Render: =>
buffer = ""
for i, child in ipairs @_children
buffer ..= child\Render!
if i < #@_children and (child.__class.__name != "SpaceBlock" or child.__class.__name == "SpaceBlock" and #child._children > 0)
buffer ..= "\n"
return buffer
-- {{ TBSHTEMPLATE:END }}
return SpaceBlock
| 24.285714 | 129 | 0.609804 |
7a9d82a8a84a53c97c9c65257882eec80895e15b | 1,454 | describe "GridTable", ->
use "./libraries/moonmod-core/dist/moonmod-core.lua"
dist ->
use "./dist/moonmod-board-ui.lua"
source ->
use "./src/table/Table.moon"
use "./src/table/GridTable.moon"
describe ":new()", ->
it "calls the Table superconstructor with its options", ->
super = stub Table, "__init"
options = { }
table = GridTable options
super\revert!
assert.stub(super).was.called.with table, options
it "creates an empty array for the player seat Transforms", ->
table = GridTable { players: { } }
assert.are.same { }, table.transforms
describe ":calculateSeatTransform", ->
it "creates a Transform representing the position & rotation of the player's hand", ->
options = {
players: { 1, 2, 3, 4 }
locations: {
{ 1, 1 }
{ 2, 3 }
{ 2, 2 }
{ 3, 1 }
}
rowPos: { 1, 2, 3, 4 }
colPos: { 4, 3, 2, 1 }
rowRot: { 45, 90, 135, 270 }
colRot: { 90, 90, 90, 90 }
}
table = GridTable options
transform = table\calculateSeatTransform(3, options)
assert.equals 3, transform.position.data.x
assert.equals Table.boardHeight, transform.position.data.y
assert.equals 2, transform.position.data.z
assert.equals 0, transform.rotation.data.x
assert.equals 180, transform.rotation.data.y
assert.equals 0, transform.rotation.data.z
| 29.673469 | 90 | 0.591472 |
75d8e65e9d14dc092897541c41e4fa3b91691048 | 34 | require "lapis.db.postgres.schema" | 34 | 34 | 0.823529 |
4ed5dd115d57843afbd24b61f04891b43e674607 | 1,911 | -- typekit.global
-- _G handling
-- By daelvn
import DEBUG, GLOBALS from require "typekit.config"
import inspect, log from (require "typekit.debug") DEBUG
import stubError from require "typekit.global.error"
import metatype,
metaindex,
isUpper,
isLower from require "typekit.commons"
-- Gets the current Lua version
--getVersion = (ver=_VERSION) -> ver\match "%d%.%d"
-- Initializes the global environment
initG = ->
return if _G._T
log "global.initG", "Initializing _T"
if GLOBALS
_G._T = {}
_G = (metaindex (i) => (rawget @, "_T")[i]) _G
-- Creates a new Subfunction
-- A Subfunction is a function that can be selected based
-- on some criteria, determined by a second function.
Subfunction = (name, fn, selector) ->
log "global.Subfunction #got", name
this = (metatype "Subfunction") {
:name
reference: fn
:selector
}
setmetatable this, __call: (...) => @.reference ...
-- Creates a new stub
-- name: name of the reference
-- subfnl: table of Subfunctions
Stub = (name, subfnl={}) ->
log "global.Stub #got", name
this = setmetatable { :name, :subfnl },
__index: (idx) =>
if x = (rawget @, "subfnl")[idx]
return x
else
stubError "No Subfunction found with index '#{idx}'"
__call: (...) =>
for name, subfn in pairs subfnl
return subfn ... if subfn.selector ...
stubError "No Subfunction could be inferred"
--
return this
-- Adds stub to _G
addStub = (stub) ->
initG!
_G._T[stub.name] = stub if GLOBALS
-- Adds subfunction to stub
addSubfn = (stub) -> (subfn) -> (rawget stub, "instances")[subfn.name] = subfn
-- Adds simple function as a reference
addReference = (name, fn) ->
log "global.addReference #got", "Adding reference #{name}"
initG!
_G._T[name] = fn if GLOBALS
{
:initG
:Subfunction, :Stub
:addSubfn, :addStub
:addReference
} | 26.541667 | 78 | 0.636839 |
d135114085d83eefa64971ab8b3b52eed45ee4ad | 1,541 | gio = require 'ljglibs.gio'
import Application, File from gio
describe 'Application', ->
local app
after_each -> app\quit!
it 'takes application id and flags as constructor arguments', ->
app = Application 'my.App', Application.HANDLES_OPEN
assert.equal 'my.App', app.application_id
assert.equal gio.Application.HANDLES_OPEN, app.flags
describe 'register()', ->
it 'returns true upon succesful registration', ->
app = Application 'my.GApp', Application.HANDLES_OPEN
assert.is_true app\register!
it 'returns true upon successful registration', ->
app = Application 'my.GApp2', Application.HANDLES_OPEN
assert.is_true app\register!
it 'raises an error upon duplicate registration', ->
app = Application 'my.GApp3', Application.HANDLES_OPEN
assert.is_true app\register!
app = Application 'my.GApp3', Application.HANDLES_OPEN
assert.raises 'already exported', -> app\register!
describe 'run()', ->
it 'accepts a table of strings as parameter', ->
app = Application 'my.RunGApp'
on_activate = spy.new ->
app\on_activate on_activate
app\register!
app\run {'foo'}
describe '(signals)', ->
it 'on_open is called with the files specified', ->
app = Application 'my.OpenGApp', Application.HANDLES_OPEN
app\on_open (cb_app, files) ->
assert.equal app, cb_app
assert.same { '/tmp.foo', '/bin/ls' }, [f.path for f in *files]
app\register!
app\run { 'howl', '/tmp.foo', '/bin/ls' }
| 32.104167 | 71 | 0.662557 |
0f74f9c02741b4720d8714b57ba832d703ea69ce | 711 | package.path = "?.lua;" .. package.path
package.path = "pieces/?.lua;" .. package.path
package.path = "love2d-modules/?.lua;" .. package.path
love.conf = (t) ->
export Settings = {
cell_size: 80,
rows: 8,
columns: 8,
white_color: {
red: 0.9375,
green: 0.84765625,
blue: 0.70703125
},
black_color: {
red: 0.70703125,
green: 0.53125,
blue: 0.38671875
},
font_size: 24
}
-- export rapidjson = require("rapidjson")
-- export settings = rapidjson.load(LOVE2DFOLDER .. "settings.json")
t.window.title = "Fairy Chess"
t.window.icon = "assets/icon.png"
| 22.935484 | 72 | 0.524613 |
0396a9fca4e754d76c69347649262392c83981a1 | 1,596 | socket = require "socket"
colors = require "colors"
import stringGroup, reverse, hexStrToBinaryStr from require "utils"
local *
on = (ips, transitionMs = 0) ->
header = "2A0000340000000000000000000000000000000000000000000000000000000075000000"
payload = "FFFF" .. intToHexStrLittleEndian(transitionMs, 8)
sendPackets(ips, header .. payload)
off = (ips, transitionMs = 0) ->
header = "2A0000340000000000000000000000000000000000000000000000000000000075000000"
payload = "0000" .. intToHexStrLittleEndian(transitionMs, 8)
sendPackets(ips, header .. payload)
set = (ips, color, transitionMs = 0) ->
header = "310000340000000000000000000000000000000000000000000000000000000066000000"
payload = "00" .. colorStrToHexStr(color) .. intToHexStrLittleEndian(transitionMs, 8)
sendPackets(ips, header .. payload)
sendPackets = (ips, data) ->
msg = hexStrToBinaryStr(data)
udp = assert(socket.udp!)
for ip in *ips
udp\sendto(msg, ip, "56700")
udp\close!
colorStrToHexStr = (s) ->
c = colors.new("#" .. s)
r, g, b = colors.hsl_to_rgb(c.H, c.S, c.L)
cMax = math.max(r, g, b)
cMin = math.min(r, g, b)
hueHexStr = intToHexStrLittleEndian(math.ceil(c.H / 360 * 65535), 4)
saturationHexStr = intToHexStrLittleEndian(math.ceil((if cMax == 0 then 0 else (cMax - cMin) / cMax) * 65535), 4)
lightnessHexStr = intToHexStrLittleEndian(math.ceil(cMax * 65535), 4)
hueHexStr .. saturationHexStr .. lightnessHexStr .. "AC0D"
intToHexStrLittleEndian = (n, length = 8) ->
table.concat(reverse(stringGroup(string.format("%0" .. length .. "x", n), 2)))
{ :on, :off, :set }
| 38 | 115 | 0.711779 |
6fbeb375873b3a2d57ef8b05a6c2ee8719402395 | 396 |
flat_value = (op, depth=1) ->
return '"'..op..'"' if type(op) == "string"
return tostring(op) if type(op) != "table"
items = [flat_value item, depth + 1 for item in *op]
pos = op[-1]
"{"..(pos and "["..pos.."] " or "")..table.concat(items, ", ").."}"
value = (op) ->
flat_value op
tree = (block) ->
table.concat [flat_value value for value in *block], "\n"
{ :value, :tree }
| 20.842105 | 69 | 0.54798 |
22beb81344de1cc63828e59973ca0e53187ce87b | 25,470 |
-- 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.
-- editor stuffs
gui.ppm2.dxlevel.not_supported = 'Uw DirectX™ level is te laag. Ten minste 9.0 is vereist. Als je 8.1 voor framerate gebruikt, heb je ofwel de oudste videokaart of slechte drivers.\nOmdat framerate in gmod alleen laag kan zijn vanwege andere addons die zinloze hoge CPU belasting creëren.\nJa, dit bericht zal meerdere malen verschijnen om je te ergeren. Omdat WAT DE NEUK WAAROM ZOU JE MELDINGEN GEVEN OVER ONTBREKENDE TEXTUREN???'
gui.ppm2.dxlevel.toolow = 'DirectX™ level is te laag voor PPM/2'
gui.ppm2.editor.eyes.separate = 'Gebruik gescheiden instellingen voor de ogen'
gui.ppm2.editor.eyes.url = 'Oog URL textuur'
gui.ppm2.editor.eyes.url_desc = 'Bij gebruik van de oog-URL-structuur; De volgende opties hebben geen effect'
gui.ppm2.editor.eyes.lightwarp_desc = 'Lightwarp heeft alleen effect op EyeRefract ogen'
gui.ppm2.editor.eyes.lightwarp = "Lightwarp"
gui.ppm2.editor.eyes.desc1 = "Lightwarp textuur URL invoer\nIt moet 256x16 zijn!"
gui.ppm2.editor.eyes.desc2 = "Glanssterkte\nDeze parameters passen de sterkte van real time reflecties op het oog aan\nOm veranderingen te zien, zet ppm2_cl_reflections convar op 1\nAndere spelers zouden alleen reflecties zien met ppm2_cl_reflecties ingesteld op 1\n0 - is gematteerd; 1 - is gespiegeld"
for _, {tprefix, prefix} in ipairs {{'def', ''}, {'left', 'Left '}, {'right', 'Right '}}
gui.ppm2.editor.eyes[tprefix].lightwarp.shader = "#{prefix}Gebruik EyeRefract shader"
gui.ppm2.editor.eyes[tprefix].lightwarp.cornera = "#{prefix}Gebruik Eye Cornera diffuus"
gui.ppm2.editor.eyes[tprefix].lightwarp.glossiness = "#{prefix}Glans"
gui.ppm2.editor.eyes[tprefix].type = "#{prefix}Oogtype"
gui.ppm2.editor.eyes[tprefix].reflection_type = "#{prefix}Type oogreflectie"
gui.ppm2.editor.eyes[tprefix].lines = "#{prefix}Ooglijnen"
gui.ppm2.editor.eyes[tprefix].derp = "#{prefix}Derp ogen"
gui.ppm2.editor.eyes[tprefix].derp_strength = "#{prefix}Derp oog sterkte"
gui.ppm2.editor.eyes[tprefix].iris_size = "#{prefix}Ooggrootte"
gui.ppm2.editor.eyes[tprefix].points_inside = "#{prefix}Ooglijntjes binnenin"
gui.ppm2.editor.eyes[tprefix].width = "#{prefix}Oogbreedte"
gui.ppm2.editor.eyes[tprefix].height = "#{prefix}Ooghoogte"
gui.ppm2.editor.eyes[tprefix].pupil.width = "#{prefix}Pupil breedte"
gui.ppm2.editor.eyes[tprefix].pupil.height = "#{prefix}Pupil hoogte"
gui.ppm2.editor.eyes[tprefix].pupil.size = "#{prefix}Pupil grootte"
gui.ppm2.editor.eyes[tprefix].pupil.shift_x = "#{prefix}Pupil verschuiving X"
gui.ppm2.editor.eyes[tprefix].pupil.shift_y = "#{prefix}Pupil verschuiving Y"
gui.ppm2.editor.eyes[tprefix].pupil.rotation = "#{prefix}Oog rotatie"
gui.ppm2.editor.eyes[tprefix].background = "#{prefix}Oog achtergrond"
gui.ppm2.editor.eyes[tprefix].pupil_size = "#{prefix}Pupil"
gui.ppm2.editor.eyes[tprefix].top_iris = "#{prefix}Bovenste oog iris"
gui.ppm2.editor.eyes[tprefix].bottom_iris = "#{prefix}Onderste oog iris"
gui.ppm2.editor.eyes[tprefix].line1 = "#{prefix}Oog lijn 1"
gui.ppm2.editor.eyes[tprefix].line2 = "#{prefix}Oog lijn 2"
gui.ppm2.editor.eyes[tprefix].reflection = "#{prefix}Oogreflectie effect"
gui.ppm2.editor.eyes[tprefix].effect = "#{prefix}Oog effect"
gui.ppm2.editor.generic.title = 'PPM/2 Pony Editor'
gui.ppm2.editor.generic.title_file = '%q - PPM/2 Pony Editor'
gui.ppm2.editor.generic.title_file_unsaved = '%q* - PPM/2 Pony Editor (niet opgeslagen wijzigingen!)'
gui.ppm2.editor.generic.yes = 'Yas!'
gui.ppm2.editor.generic.no = 'Noh!'
gui.ppm2.editor.generic.ohno = 'Onoh!'
gui.ppm2.editor.generic.okay = 'Okai ;w;'
gui.ppm2.editor.generic.datavalue = '%s\nGegevenswaarde: %q'
gui.ppm2.editor.generic.url = '%s\n\nLink gaat naar: %s'
gui.ppm2.editor.generic.url_field = 'URL veld'
gui.ppm2.editor.generic.spoiler = 'Mysterieuze spoiler'
gui.ppm2.editor.generic.restart.needed = 'Editor moet opnieuw worden opgestart'
gui.ppm2.editor.generic.restart.text = 'U moet de editor herstarten voor het toepassen van wijzigingen.\nNu herstarten?\nNiet opgeslagen gegevens gaan verloren!'
gui.ppm2.editor.generic.fullbright = 'Vol helder'
gui.ppm2.editor.generic.wtf = 'Om de een of andere reden heeft uw speler geen NetworkedPonyData - Niets te bewerken!\nProbeer ppm2_reload in je console en probeer de editor opnieuw te openen'
gui.ppm2.editor.io.random = 'Willekeurig!'
gui.ppm2.editor.io.newfile.title = 'Nieuw Bestand'
gui.ppm2.editor.io.newfile.confirm = 'Wilt u echt een nieuw bestand aanmaken?'
gui.ppm2.editor.io.newfile.toptext = 'Reset'
gui.ppm2.editor.io.delete.confirm = 'Wilt u dat bestand echt verwijderen?\nHet zal voor altijd verdwenen zijn!\n(een lange tijd!)'
gui.ppm2.editor.io.delete.title = 'Echt verwijderen?'
gui.ppm2.editor.io.filename = 'Bestandsnaam'
gui.ppm2.editor.io.hint = 'Bestand openen door te dubbelklikken'
gui.ppm2.editor.io.reload = 'Bestandslijst opnieuw laden'
gui.ppm2.editor.io.failed = 'Heeft niet kunnen importeren.'
gui.ppm2.editor.io.warn.oldfile = '!!! Het kan wel of niet werken. U zult worden geplet.'
gui.ppm2.editor.io.warn.text = "Op dit moment heeft u uw wijzigingen niet aangegeven.\nWilt u echt een ander bestand openen?"
gui.ppm2.editor.io.warn.header = 'Niet opgeslagen wijzigingen!'
gui.ppm2.editor.io.save.button = 'Opslaan'
gui.ppm2.editor.io.save.text = 'Voer de bestandsnaam in zonder ppm2/ en .dat\nTip: om op te slaan als autoload, type "_current" (zonder citaten)'
gui.ppm2.editor.io.wear = 'Wijzigingen aanbrengen (dragen)'
gui.ppm2.editor.seq.standing = 'Staand'
gui.ppm2.editor.seq.move = 'In beweging'
gui.ppm2.editor.seq.walk = 'Wandelen'
gui.ppm2.editor.seq.sit = 'Zitten'
gui.ppm2.editor.seq.swim = 'Zwemmen'
gui.ppm2.editor.seq.run = 'Rennen'
gui.ppm2.editor.seq.duckwalk = 'Wandel als een eend'
gui.ppm2.editor.seq.duck = 'Doe als een eend'
gui.ppm2.editor.seq.jump = 'Springen'
gui.ppm2.editor.misc.race = 'Ras'
gui.ppm2.editor.misc.weight = 'Gewicht'
gui.ppm2.editor.misc.size = 'Pony grootte'
gui.ppm2.editor.misc.hide_weapons = 'Moet wapens verbergen'
gui.ppm2.editor.misc.chest = 'Mannelijke borstkas'
gui.ppm2.editor.misc.gender = 'Geslacht'
gui.ppm2.editor.misc.wings = 'Vleugels Type'
gui.ppm2.editor.misc.flexes = 'Flexibele besturing'
gui.ppm2.editor.misc.no_flexes2 = 'Geen flexibiliteit op het nieuwe model'
gui.ppm2.editor.misc.no_flexes_desc = 'U kunt elke flexstatuscontroller apart uitschakelen\nDeze buigingen kunnen dus worden aangepast met add-ons van derden (zoals PAC3)'
gui.ppm2.editor.misc.hide_pac3 = 'Entiteiten verbergen wanneer een PAC3 entiteit wordt gebruikt'
gui.ppm2.editor.misc.hide_mane = 'Mane verbergen wanneer een PAC3 entiteit wordt gebruikt'
gui.ppm2.editor.misc.hide_tail = 'Verberg de staart wanneer een PAC3 entiteit wordt gebruikt'
gui.ppm2.editor.misc.hide_socks = 'Sokken verbergen bij gebruik van een PAC3 entiteit'
gui.ppm2.editor.tabs.main = 'Algemeen'
gui.ppm2.editor.tabs.files = 'Bestanden'
gui.ppm2.editor.tabs.old_files = 'Oude Bestanden'
gui.ppm2.editor.tabs.cutiemark = 'Cutiemark'
gui.ppm2.editor.tabs.head = 'Hoofd anatomie'
gui.ppm2.editor.tabs.eyes = 'Ogen'
gui.ppm2.editor.tabs.face = 'Gezicht'
gui.ppm2.editor.tabs.mouth = 'Mond'
gui.ppm2.editor.tabs.left_eye = 'Linker oog'
gui.ppm2.editor.tabs.right_eye = 'Rechter oog'
gui.ppm2.editor.tabs.mane_horn = 'Mane en Hoorn'
gui.ppm2.editor.tabs.mane = 'Mane'
gui.ppm2.editor.tabs.details = 'Details'
gui.ppm2.editor.tabs.url_details = 'URL Details'
gui.ppm2.editor.tabs.url_separated_details = 'URL Gescheiden Details'
gui.ppm2.editor.tabs.ears = 'Oren'
gui.ppm2.editor.tabs.horn = 'Hoorn'
gui.ppm2.editor.tabs.back = 'Rug'
gui.ppm2.editor.tabs.wings = 'Vleugels'
gui.ppm2.editor.tabs.left = 'Links'
gui.ppm2.editor.tabs.right = 'Rechts'
gui.ppm2.editor.tabs.neck = 'Nek'
gui.ppm2.editor.tabs.body = 'Pony lichaam'
gui.ppm2.editor.tabs.tattoos = 'Tatoeages'
gui.ppm2.editor.tabs.tail = 'Staart'
gui.ppm2.editor.tabs.hooves = 'Hoeven anatomie'
gui.ppm2.editor.tabs.bottom_hoof = 'Onder hoef'
gui.ppm2.editor.tabs.legs = 'Benen'
gui.ppm2.editor.tabs.socks = 'Sokken'
gui.ppm2.editor.tabs.newsocks = 'Nieuwe Sokken'
gui.ppm2.editor.tabs.about = 'Over'
gui.ppm2.editor.old_tabs.mane_tail = 'Mane en staart'
gui.ppm2.editor.old_tabs.wings_and_horn_details = 'Vleugels en hoorn details'
gui.ppm2.editor.old_tabs.wings_and_horn = 'Vleugels en hoorn'
gui.ppm2.editor.old_tabs.body_details = 'Lichaam details'
gui.ppm2.editor.old_tabs.mane_tail_detals = 'Mane en staart URL details'
gui.ppm2.editor.cutiemark.display = 'Toon cutiemarkering'
gui.ppm2.editor.cutiemark.type = 'Cutiemark type'
gui.ppm2.editor.cutiemark.size = 'Cutiemark grootte'
gui.ppm2.editor.cutiemark.color = 'Cutiemark kleur'
gui.ppm2.editor.cutiemark.input = 'Cutiemark URL afbeelding invoer veld\nMoet PNG of JPEG zijn (werkt hetzelfde als\nPAC3 URL textuur)'
gui.ppm2.editor.face.eyelashes = 'Wimpers'
gui.ppm2.editor.face.eyelashes_color = 'Wimpers kleur'
gui.ppm2.editor.face.eyelashes_phong = 'Wimpers phong parameters'
gui.ppm2.editor.face.eyebrows_color = 'Wenkbrauwen kleur'
gui.ppm2.editor.face.new_muzzle = 'Gebruik nieuwe snuit voor het mannelijk model'
gui.ppm2.editor.face.nose = 'Neus kleur'
gui.ppm2.editor.face.lips = 'Lippen kleur'
gui.ppm2.editor.face.eyelashes_separate_phong = 'Afzonderlijke wimpers Phong'
gui.ppm2.editor.face.eyebrows_glow = 'Gloeiende wenkbrauwen'
gui.ppm2.editor.face.eyebrows_glow_strength = 'Wenkbrauwen gloed sterkte'
gui.ppm2.editor.face.inherit.lips = 'Neem de Lippen kleur van het lichaam'
gui.ppm2.editor.face.inherit.nose = 'Neem de neus kleur van het lichaam'
gui.ppm2.editor.mouth.fangs = 'Tanden'
gui.ppm2.editor.mouth.alt_fangs = 'Alternatieve hoektanden'
gui.ppm2.editor.mouth.claw = 'Klauwtanden'
gui.ppm2.editor.mouth.teeth = 'Tand kleur'
gui.ppm2.editor.mouth.teeth_phong = 'Tanden phong parameters'
gui.ppm2.editor.mouth.mouth = 'Mond kleur'
gui.ppm2.editor.mouth.mouth_phong = 'Mond phong parameters'
gui.ppm2.editor.mouth.tongue = 'Tong kleur'
gui.ppm2.editor.mouth.tongue_phong = 'Tong phong parameters'
gui.ppm2.editor.mane.type = 'Mane Type'
gui.ppm2.editor.mane.phong = 'Afzonderlijk mane phong instellingen van het lichaam'
gui.ppm2.editor.mane.mane_phong = 'Mane phong parameters'
gui.ppm2.editor.mane.phong_sep = 'Gescheiden bovenste en onderste mane kleuren'
gui.ppm2.editor.mane.up.phong = 'Bovenste Mane Phong instellingen'
gui.ppm2.editor.mane.down.type = 'Onderste Mane Type'
gui.ppm2.editor.mane.down.phong = 'Onderste Mane Phong instellingen'
gui.ppm2.editor.mane.newnotice = 'De volgende opties hebben alleen effect op een nieuw model'
for i = 1, 2
gui.ppm2.editor.mane['color' .. i] = "Mane kleur #{i}"
gui.ppm2.editor.mane.up['color' .. i] = "Bovenste mane kleur #{i}"
gui.ppm2.editor.mane.down['color' .. i] = "Onderste mane kleur #{i}"
for i = 1, 6
gui.ppm2.editor.mane['detail_color' .. i] = "Mane detail kleur #{i}"
gui.ppm2.editor.mane.up['detail_color' .. i] = "Bovenste mane kleur #{i}"
gui.ppm2.editor.mane.down['detail_color' .. i] = "Onderste mane kleur #{i}"
gui.ppm2.editor.url_mane['desc' .. i] = "Mane URL Detail #{i} invoer veld"
gui.ppm2.editor.url_mane['color' .. i] = "Mane URL detail kleur #{i}"
gui.ppm2.editor.url_tail['desc' .. i] = "Staart URL Detail #{i} invoer veld"
gui.ppm2.editor.url_tail['color' .. i] = "Staart URL detail kleur #{i}"
gui.ppm2.editor.url_mane.sep.up['desc' .. i] = "Bovenste mane URL Detail #{i} invoer veld"
gui.ppm2.editor.url_mane.sep.up['color' .. i] = "Bovenste Mane URL detail kleur #{i}"
gui.ppm2.editor.url_mane.sep.down['desc' .. i] = "Onderste mane URL Detail #{i} invoer veld"
gui.ppm2.editor.url_mane.sep.down['color' .. i] = "Onderste Mane URL detail kleur #{i}"
gui.ppm2.editor.ears.bat = 'Vleermuis pony oren'
gui.ppm2.editor.ears.size = 'Oren grootte'
gui.ppm2.editor.horn.detail_color = 'Hoorn detail kleur'
gui.ppm2.editor.horn.glowing_detail = 'Glanzende Hoorn Detail'
gui.ppm2.editor.horn.glow_strength = 'Horn gloed sterkte'
gui.ppm2.editor.horn.separate_color = 'Aparte hoornkleur van het lichaam'
gui.ppm2.editor.horn.color = 'Hoorn kleur'
gui.ppm2.editor.horn.horn_phong = 'Hoorn phong parameters'
gui.ppm2.editor.horn.magic = 'Hoorn magie kleur'
gui.ppm2.editor.horn.separate_magic_color = 'Aparte magische kleur van oogkleur'
gui.ppm2.editor.horn.separate = 'Aparte hoornkleur van het lichaam'
gui.ppm2.editor.horn.separate_phong = 'Aparte hoorn phong instellingen van het lichaam'
for i = 1, 3
gui.ppm2.editor.horn.detail['desc' .. i] = "Hoorn URL detail #{i}"
gui.ppm2.editor.horn.detail['color' .. i] = "URL Detail kleur #{i}"
gui.ppm2.editor.wings.separate_color = 'Aparte vleugel kleur van het lichaam'
gui.ppm2.editor.wings.color = 'Vleugel color'
gui.ppm2.editor.wings.wings_phong = 'Vleugel phong parameters'
gui.ppm2.editor.wings.separate = 'Aparte vleugel kleur van het lichaam'
gui.ppm2.editor.wings.separate_phong = 'Aparte vleugel phong instellingen van het lichaam'
gui.ppm2.editor.wings.bat_color = 'Vleermuis vleugels kleur'
gui.ppm2.editor.wings.bat_skin_color = 'Vleermuis vleugels huidskleur'
gui.ppm2.editor.wings.bat_skin_phong = 'Vleermuis vleugels huid phong parameters'
gui.ppm2.editor.wings.normal = 'Normale vleugels'
gui.ppm2.editor.wings.bat = 'Vleermuisvleugels'
gui.ppm2.editor.wings.bat_skin = 'Vleermuis vleugels huid'
gui.ppm2.editor.wings.left.size = 'Linker vleugel grootte'
gui.ppm2.editor.wings.left.fwd = 'Linker vleugel voor'
gui.ppm2.editor.wings.left.up = 'Linker vleugel boven'
gui.ppm2.editor.wings.left.inside = 'Linker vleugel binnen'
gui.ppm2.editor.wings.right.size = 'Rechter vleugel grootte'
gui.ppm2.editor.wings.right.fwd = 'Rechter vleugel voor'
gui.ppm2.editor.wings.right.up = 'Rechter vleugel boven'
gui.ppm2.editor.wings.right.inside = 'Rechter vleugel binnen'
for i = 1, 3
gui.ppm2.editor.wings.details.def['detail' .. i] = "Vleugels URL detail #{i}"
gui.ppm2.editor.wings.details.def['color' .. i] = "URL Detail kleur #{i}"
gui.ppm2.editor.wings.details.bat['detail' .. i] = "Vleermuisvleugels URL detail #{i}"
gui.ppm2.editor.wings.details.bat['color' .. i] = "Vleermuisvleugels URL Detail kleur #{i}"
gui.ppm2.editor.wings.details.batskin['detail' .. i] = "Vleermuisvleugels huid URL detail #{i}"
gui.ppm2.editor.wings.details.batskin['color' .. i] = "Vleermuisvleugels huid URL Detail kleur #{i}"
gui.ppm2.editor.neck.height = 'Nek hoogte'
gui.ppm2.editor.body.suit = 'Kostuum'
gui.ppm2.editor.body.color = 'Lichaams kleur'
gui.ppm2.editor.body.body_phong = 'Lichaam phong parameters'
gui.ppm2.editor.body.spine_length = 'Rug lengte'
gui.ppm2.editor.body.url_desc = 'Lichaam detail URL afbeelding invoer veld\nMoet PNG of JPEG zijn (werkt hetzelfde als \nPAC3 URL structuur)'
gui.ppm2.editor.body.disable_hoofsteps = 'Hoef stappen uitschakelen'
gui.ppm2.editor.body.disable_wander_sounds = 'Wandelgeluiden uitschakelen'
gui.ppm2.editor.body.disable_new_step_sounds = 'Aangepaste stapgeluiden uitschakelen'
gui.ppm2.editor.body.disable_jump_sound = 'Spring geluid uitschakelen'
gui.ppm2.editor.body.disable_falldown_sound = 'Neer val geluid uitschakelen'
gui.ppm2.editor.body.call_playerfootstep = 'Noem PlayerFootstep bij elk geluid'
gui.ppm2.editor.body.call_playerfootstep_desc = 'Noem PlayerFootstep haak op elk daadwerkelijk geluid dat u hoort.\nMet behulp van deze optie kunnen andere geïnstalleerde addons vertrouwen op PPM2\'s diepgang\ndie luisteren naar PlayerFootstep haak. Dit moet alleen worden uitgeschakeld wanneer u onbetrouwbare resultaten van andere addons krijgt.\nof uw FPS daalt naar lage waarden omdat een van de geïnstalleerde addons slecht gecodeerd is.'
for i = 1, PPM2.MAX_BODY_DETAILS
gui.ppm2.editor.body.detail['desc' .. i] = "Detail #{i}"
gui.ppm2.editor.body.detail['color' .. i] = "Detail kleur #{i}"
gui.ppm2.editor.body.detail['glow' .. i] = "Detail #{i} gloeit"
gui.ppm2.editor.body.detail['glow_strength' .. i] = "Detail #{i} gloeikracht"
gui.ppm2.editor.body.detail.url['desc' .. i] = "Detail #{i}"
gui.ppm2.editor.body.detail.url['color' .. i] = "Detail kleur #{i}"
gui.ppm2.editor.tattoo.edit_keyboard = 'Bewerken met behulp van het toetsenbord'
gui.ppm2.editor.tattoo.type = 'Type'
gui.ppm2.editor.tattoo.over = 'Tatoeage over het lichaam details'
gui.ppm2.editor.tattoo.glow = 'Tatoeage is gloeiend'
gui.ppm2.editor.tattoo.glow_strength = 'De sterkte van de tatoegering gloed'
gui.ppm2.editor.tattoo.color = 'Kleur van Tattoo'
gui.ppm2.editor.tattoo.tweak.rotate = 'Rotatie'
gui.ppm2.editor.tattoo.tweak.x = 'X Positie'
gui.ppm2.editor.tattoo.tweak.y = 'Y Positie'
gui.ppm2.editor.tattoo.tweak.width = 'Breedte Schaal'
gui.ppm2.editor.tattoo.tweak.height = 'Hoogte schaal'
for i = 1, PPM2.MAX_TATTOOS
gui.ppm2.editor.tattoo['layer' .. i] = "Tatoegeringslaag #{i}"
gui.ppm2.editor.tail.type = 'Staart type'
gui.ppm2.editor.tail.size = 'Staart grootte'
gui.ppm2.editor.tail.tail_phong = 'Staart phong parameters'
gui.ppm2.editor.tail.separate = 'Aparte staart phong instellingen van het lichaam'
for i = 1, 2
gui.ppm2.editor.tail['color' .. i] = 'Staart kleur ' .. i
for i = 1, 6
gui.ppm2.editor.tail['detail' .. i] = "Staart detail kleur #{i}"
gui.ppm2.editor.tail.url['detail' .. i] = "Staart URL detail #{i}"
gui.ppm2.editor.tail.url['color' .. i] = "Staart URL detail #{i}"
gui.ppm2.editor.hoof.fluffers = 'Hoef Fluffers'
gui.ppm2.editor.legs.height = 'Benen hoogte'
gui.ppm2.editor.legs.socks.simple = 'Sokken (eenvoudige textuur)'
gui.ppm2.editor.legs.socks.model = 'Sokken (als model)'
gui.ppm2.editor.legs.socks.color = 'Sokken model kleur'
gui.ppm2.editor.legs.socks.socks_phong = 'Sokken phong parameters'
gui.ppm2.editor.legs.socks.texture = 'Sokken textuur'
gui.ppm2.editor.legs.socks.url_texture = 'Sokken URL textuur'
for i = 1, 6
gui.ppm2.editor.legs.socks['color' .. i] = 'Sokken detail kleur ' .. i
gui.ppm2.editor.legs.newsocks.model = 'Sokken (als een nieuw model)'
for i = 1, 3
gui.ppm2.editor.legs.newsocks['color' .. i] = 'Nieuwe sokken kleur ' .. i
gui.ppm2.editor.legs.newsocks.url = 'Nieuwe sokken URL textuur'
-- shared editor stuffs
gui.ppm2.editor.tattoo.help = "Om de bewerkmodus te verlaten, drukt u op Escape of klikt u ergens met de muis
Om tatto te verplaatsen, gebruikt u WASD
Om hoger/lager te schalen gebruikt u de pijlen omhoog/omlaag
Om breder/kleiner te schalen gebruik rechts/links pijlen
Om links/rechts te draaien gebruikt u Q/E"
gui.ppm2.editor.reset_value = 'Reset %s'
gui.ppm2.editor.phong.info = 'Meer info over Phong op de wiki'
gui.ppm2.editor.phong.exponent = 'Phong Exponent - hoe sterk reflecterende eigenschap\nvan een ponyhuid is\nZet bijna op nul om een robotachtige uitstraling te krijgen van uw\npony huid'
gui.ppm2.editor.phong.exponent_text = 'Phong Exponent'
gui.ppm2.editor.phong.boost.title = 'Phong Verhogen - vermenigvuldigt spiegelende kaartreflecties'
gui.ppm2.editor.phong.boost.boost = 'Phong Verhogen'
gui.ppm2.editor.phong.tint.title = 'Tint kleur - welke kleuren weerspiegelt in de kaart\nWit - Weerspiegelt alle kleuren\n(In witte kamer - witte spiegelkaart)'
gui.ppm2.editor.phong.tint.tint = 'Tint kleur'
gui.ppm2.editor.phong.frensel.front.title = 'Phong Voorkant - Fresnel 0 graden reflectie hoekvermenigvuldiger'
gui.ppm2.editor.phong.frensel.front.front = 'Phong Voorkant'
gui.ppm2.editor.phong.frensel.middle.title = 'Phong Midden - Fresnel 45 graden reflectie hoekvermenigvuldiger'
gui.ppm2.editor.phong.frensel.middle.front = 'Phong Midden'
gui.ppm2.editor.phong.frensel.sliding.title = 'Phong glijdend - Fresnel 90 graden reflectie hoekvermenigvuldiger'
gui.ppm2.editor.phong.frensel.sliding.front = 'Phong glijdend'
gui.ppm2.editor.phong.lightwarp = 'Lightwarp'
gui.ppm2.editor.phong.url_lightwarp = 'Lightwarp textuur URL invoer\nIt moet 256x16 zijn!'
gui.ppm2.editor.phong.bumpmap = 'Bumpmap URL invoer'
gui.ppm2.editor.info.discord = "Sluit je aan bij DBot's Discord!"
gui.ppm2.editor.info.ponyscape = "PPM/2 is een Ponyscape project"
gui.ppm2.editor.info.creator = "PPM/2 is gemaakt en ontwikkeld door DBot"
gui.ppm2.editor.info.newmodels = "Nieuwe modellen zijn gemaakt door Durpy"
gui.ppm2.editor.info.cppmmodels = "CPPM modellen (inclusief ponyhanden) behoren tot UnkN', 'http://steamcommunity.com/profiles/76561198084938735"
gui.ppm2.editor.info.oldmodels = "Oude modellen zijn van Scentus en anderen"
gui.ppm2.editor.info.bugs = "Heeft u een bug gevonden? Meld hier!"
gui.ppm2.editor.info.sources = "U kunt hier bronnen vinden"
gui.ppm2.editor.info.githubsources = "Of op de GitHub-mirror"
gui.ppm2.editor.info.thanks = "Met dank aan everypony die kritiek heeft geuit,\ngeholpen en getest van PPM/2!"
-- other stuff
info.ppm2.fly.pegasus = 'Je moet een Pegasus of een Alicorn zijn om te vliegen!'
info.ppm2.fly.cannot = 'Je kunt %s nu niet gebruiken.'
gui.ppm2.emotes.sad = 'Verdrietig'
gui.ppm2.emotes.wild = 'Wild'
gui.ppm2.emotes.grin = 'Grijns'
gui.ppm2.emotes.angry = 'Boos'
gui.ppm2.emotes.tongue = ':P'
gui.ppm2.emotes.angrytongue = '>:P'
gui.ppm2.emotes.pff = 'Pffff!'
gui.ppm2.emotes.kitty = ':3'
gui.ppm2.emotes.owo = 'oWo'
gui.ppm2.emotes.ugh = 'Uuugh'
gui.ppm2.emotes.lips = 'Lippen likken'
gui.ppm2.emotes.scrunch = 'Knarsen'
gui.ppm2.emotes.sorry = 'Sorry'
gui.ppm2.emotes.wink = 'Knipoogje'
gui.ppm2.emotes.right_wink = 'Rechter knipoogje'
gui.ppm2.emotes.licking = 'Likken'
gui.ppm2.emotes.suggestive_lips = 'Suggestieve lippen likken'
gui.ppm2.emotes.suggestive_no_tongue = 'Suggestieve w/o tong'
gui.ppm2.emotes.gulp = 'Slikken'
gui.ppm2.emotes.blah = 'Blah blah blah'
gui.ppm2.emotes.happi = 'Blij'
gui.ppm2.emotes.happi_grin = 'Blije grijns'
gui.ppm2.emotes.duck = 'EEND'
gui.ppm2.emotes.ducks = 'DUCK INSANITY'
gui.ppm2.emotes.quack = 'KWAK'
gui.ppm2.emotes.suggestive = 'Suggestieve w/ tong'
message.ppm2.emotes.invalid = 'Geen emotie met ID: %s'
gui.ppm2.editor.intro.text = "Welkom bij mijn nieuwe..... Robosurgeon voor pony's! Het stelt u in staat om........\n" ..
"hmmm..... een pony te worden, en ja, dit proces is IRREVERSCHAPPELIJK! Maar u hoeft zich geen zorgen te maken,\n" ..
"u verliest geen van uw hersencellen voor, in en na de operatie, omdat het een zeer zachte operatie uitvoert.....\n\n" ..
"Eigenlijk heb ik geen idee, jij biologisch wezen! Zijn mechanische handen zullen je omhullen in de strakste knuffels die je ooit hebt gekregen!\n" ..
"En, alstublieft, niet sterven in het proces, want dit zou VERVALLEN VAN UW LEVENSLANGE GARANTIE veroorzaken..... en je zult geen pony zijn!\n" ..
"----\n\n\n" ..
"Let op: Haal Robosurgeon niet uit elkaar. Ieders handen/handschoenen niet in bewegende delen van Robosurgeon..\n" ..
"Schakel het apparaat niet uit terwijl het werkt.\nProbeer niet te weerstaan aan zijn acties.\n" ..
"Wees altijd voorzichtig met Robosurgeon\n" ..
"Sla nooit Robosurgeon op zijn interface.\n" ..
"DBot's DLibCo neemt geen verantwoordelijkheid voor eventuele schade veroorzaakt door verkeerd gebruik van Robosurgeon.\n" ..
"De garantie vervalt als de gebruiker sterft.\n" ..
"Geen terugbetalingen."
gui.ppm2.editor.intro.title = 'Welkom hier, Mens!!'
gui.ppm2.editor.intro.okay = "Ok, ik zal deze licentie toch nooit lezen"
message.ppm2.debug.race_condition = 'Ontvangen NetworkedPonyData voordat de entiteit op de client werd aangemaakt! Wachten.....'
gui.ppm2.spawnmenu.newmodel = 'Spawn nieuw model'
gui.ppm2.spawnmenu.newmodelnj = 'Spawn nieuw nj model'
gui.ppm2.spawnmenu.oldmodel = 'Spawn oud model'
gui.ppm2.spawnmenu.oldmodelnj = 'Spawn oud nj model'
gui.ppm2.spawnmenu.cppmmodel = 'Spawn CPPM model'
gui.ppm2.spawnmenu.cppmmodelnj = 'Spawn CPPM nj model'
gui.ppm2.spawnmenu.cleanup = 'Opruimen ongebruikt models'
gui.ppm2.spawnmenu.reload = 'Herlaad lokale gegevens'
gui.ppm2.spawnmenu.require = 'Gegevens vereisen van de server'
gui.ppm2.spawnmenu.drawhooves = 'Laat hoeven zien als handen'
gui.ppm2.spawnmenu.nohoofsounds = 'Geen hoefgeluiden'
gui.ppm2.spawnmenu.noflexes = 'Schakel flexes uit (emotes)'
gui.ppm2.spawnmenu.advancedmode = 'Activeer de geavanceerde modus voor PPM2 editor'
gui.ppm2.spawnmenu.reflections = 'Activeer reflecties in real-time'
gui.ppm2.spawnmenu.reflections_drawdist = 'Reflecties tekenen afstand'
gui.ppm2.spawnmenu.reflections_renderdist = 'Reflecties laad afstand'
gui.ppm2.spawnmenu.doublejump = 'Dubbel springen activeert vliegen'
tip.ppm2.in_editor = 'In PPM/2 Editor'
tip.ppm2.camera = "%s's PPM/2 Camera"
message.ppm2.queue_notify = '%i texturen staan in de rij om te worden weergegeven'
gui.ppm2.editor.body.bump = 'Bumpmap sterkte' | 54.423077 | 443 | 0.760346 |
d69aa6d862157019d6230292dab0f22424390242 | 435 | M = {}
name1 = "lists"
name2 = "merge"
TK = require("PackageToolkit")
FX = require("FunctionalX")
M.case = (input1, solution, msg="") ->
print TK.ui.dashed_line 80, '-'
print string.format "test %s.%s()", name1, name2
print msg
result = FX[name1][name2] unpack input1
print "Result: ", unpack result
assert TK.test.equal_lists result, solution
print "VERIFIED!"
print TK.ui.dashed_line 80, '-'
return M | 29 | 52 | 0.645977 |
a8e81ff300acef766973b996b276744e700148f2 | 1,731 | local *
ffi = assert require"ffi", "require LuaJIT"
import band from assert require"bit", "require LuaJIT"
sha1 = assert require"sha1",
"missing: luarocks install sha1 # [email protected]:kikito/sha1.lua.git"
hextou64 = (str) ->
res = ffi.new "uint8_t[?]", 8
str = "0000000000000000#{str}"\sub -16
i = 7
for char in str\gmatch ".."
res[i] = tonumber char, 16
i -= 1
p = ffi.cast "uint64_t*", res
p[0]
itoa = (num) ->
num = hextou64 num if "string" == type num
bnum = ffi.new "uint64_t[?]", 1
bnum[0] = num
p = ffi.cast "uint8_t*", bnum
buf = ffi.new "uint8_t[?]", 8
buf[7-i] = p[i] for i = 0, 7
ffi.string buf, 8
hmac = (key, counter) ->
sha1.hmac key, itoa counter
if _TEST
-- For test purpose
_G.lotp or= {}
lotp._test or= {}
lotp._test.hotp = :hextou64, :hmac, :itoa
--------------------------------------------------------------------------------
class HOTP
length: 6
currentstep: 0
--- :new(seed)
-- @param seed base32 string
-- @returns HOTP
new: (seed) => @seed = seed
--- :digest(password, step?)
-- @param password number
-- @param step number or uint64_t
-- @returns boolean
digest: (password, step) =>
step or= @currentstep
@currentstep = step + 1
password == @\password step
--- :password(step?)
-- @param step number or uint64_t
-- @returns number
password: (step) =>
step or= @currentstep
phrase = (hmac @seed, step)
-- Dynamic truncation
dt = 2 * tonumber (phrase\sub -1), 16
phrase = phrase\sub dt+1, dt+8
num = band (tonumber phrase, 16), 0x7fffffff
num % (10 ^ @length)
| 24.380282 | 80 | 0.538417 |
37e8bfecda4f6ac860ee20562cdbb195e5188816 | 351 | return {
window:
background:
color: '#000000'
status:
color: '#0000ff'
editor:
background:
color: '#ff0000'
header:
background:
color: '#000000'
color: 'darkgrey'
footer:
background:
color: '#dddddd'
color: '#777777'
styles:
default:
color: '#0000ff'
}
| 13.5 | 24 | 0.509972 |
7fd3007347e1c329cf9698ad3a7b9071c5043b05 | 9,939 | -- Copyright 2012-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
import app, dispatch, interact from howl
import Window from howl.ui
describe 'CommandLine', ->
local command_line, run_as_handler
run_in_coroutine = (f) ->
wrapped = coroutine.wrap -> f!
return wrapped!
before_each ->
app.window = Window!
command_line = app.window.command_line
run_as_handler = (f) ->
command_line\run
name: 'within-activity'
handler: -> f!
after_each ->
ok, result = pcall -> app.window.command_line\abort_all!
if not ok
print result
run_as_handler = nil
command_line = nil
app.window = nil
describe 'command_line', ->
describe '\\run(activity_spec)', ->
it 'errors if handler or factory field not in spec', ->
f = -> command_line\run {}
assert.raises 'requires "name" and one of "handler" or "factory" fields', f
describe 'for activity with handler', ->
it 'calls activity handler', ->
handler = spy.new ->
command_line\run
name: 'run-activity'
handler: handler
assert.spy(handler).was_called 1
it 'passes any extra args to handler', ->
handler = spy.new ->
aspec =
name: 'run-activity'
handler: handler
command_line\run aspec, 'a1', 'a2', 'a3'
assert.spy(handler).was_called_with 'a1', 'a2', 'a3'
it 'returns result of handler', ->
result = command_line\run
name: 'run-activity'
handler: -> return 'r1'
assert.equal 'r1', result
describe 'for activity with factory', ->
it 'instantiates facory, calls run method', ->
handler = spy.new ->
run_in_coroutine ->
command_line\run
name: 'run-factory'
factory: ->
run: handler
assert.spy(handler).was_called 1
it 'passes instantiated object, finish function, extra args to run', ->
local args
obj = run: (...) ->
args = {...}
aspec =
name: 'run-factory'
factory: -> obj
run_in_coroutine ->
command_line\run aspec, 'a1', 'a2'
assert.equal args[1], obj
assert.equal 'function', type(args[2])
assert.equal 'a1', args[3]
assert.equal 'a2', args[4]
it 'returns result passed in finish function', ->
local result
run_in_coroutine ->
result = command_line\run
name: 'run-factory'
factory: ->
run: (finish) => finish('r2')
assert.equal 'r2', result
describe '\\run_after_finish(f)', ->
it 'calls f! immediately after the current activity stack exits', ->
nextf = spy.new ->
command_line\run
name: 'run-activity'
handler: ->
command_line\run_after_finish nextf
assert.spy(nextf).was_called 1
describe '.text', ->
it 'cannot be set when no running activity', ->
f = -> command_line.text = 'hello'
assert.raises 'no running activity', f
it 'returns nil when no running activity', ->
assert.equals nil, command_line.text
it 'updates the text displayed in the command_widget', ->
run_as_handler ->
command_line.text = 'hello'
assert.equal 'hello', command_line.command_widget.text
command_line.text = 'bye'
assert.equal 'bye', command_line.command_widget.text
it 'returns the text previously set', ->
run_as_handler ->
assert.equal command_line.text, ''
command_line.text = 'hi'
assert.equal 'hi', command_line.text
describe '.prompt', ->
it 'does not work when no running activity', ->
f = -> command_line.prompt = 'hello'
assert.raises 'no running activity', f
it 'updates the prompt displayed in the command_widget', ->
run_as_handler ->
command_line.prompt = 'hello'
assert.equal 'hello', command_line.command_widget.text
command_line.prompt = 'bye'
assert.equal 'bye', command_line.command_widget.text
it 'returns the prompt previously set', ->
run_as_handler ->
command_line.prompt = 'set'
assert.equal 'set', command_line.prompt
describe 'title', ->
it 'is hidden by default', ->
run_as_handler ->
assert.is_false command_line.header\to_gobject!.visible
it 'is shown and updated by setting .title', ->
run_as_handler ->
command_line.title = 'Nice Title'
assert.equal 'Nice Title', command_line.indic_title.label
assert.is_true command_line.header\to_gobject!.visible
it 'is hidden by setting title to empty string', ->
run_as_handler ->
command_line.title = 'Nice Title'
assert.is_true command_line.header\to_gobject!.visible
command_line.title = ''
assert.is_false command_line.header\to_gobject!.visible
it 'is restored to the one set by the current interaction', ->
run_as_handler ->
command_line.title = 'Title 0'
assert.equal 'Title 0', command_line.indic_title.label
run_as_handler ->
command_line.title = 'Title 1'
assert.equal 'Title 1', command_line.indic_title.label
assert.equal 'Title 0', command_line.indic_title.label
describe 'when using both .prompt and .text', ->
it 'the prompt is displayed before the text', ->
run_as_handler ->
command_line.prompt = 'prómpt:'
command_line.text = 'téxt'
assert.equal 'prómpt:téxt', command_line.command_widget.text
it 'preserves text when updating prompt', ->
run_as_handler ->
command_line.prompt = 'héllo:'
command_line.text = 'téxt'
assert.equal 'héllo:téxt', command_line.command_widget.text
command_line.prompt = 'hóla:'
assert.equal 'hóla:téxt', command_line.command_widget.text
it 'preserves prompt when updating téxt ', ->
run_as_handler ->
command_line.prompt = 'héllo:'
command_line.text = 'téxt '
assert.equal 'héllo:téxt ', command_line.command_widget.text
command_line.text = 'hóla'
assert.equal 'héllo:hóla', command_line.command_widget.text
context 'clear()', ->
it 'clears the text only, leaving prompt intact', ->
run_as_handler ->
command_line.prompt = 'héllo:'
command_line.text = 'téxt'
command_line\clear!
assert.equal 'héllo:', command_line.command_widget.text
describe 'when using nested interactions', ->
it 'each interaction has independent prompt and text', ->
run_as_handler ->
command_line.prompt = 'outer:'
command_line.text = '0'
assert.equal 'outer:0', command_line.command_widget.text
run_as_handler ->
command_line.prompt = 'inner:'
command_line.text = '1'
assert.equal 'outer:0inner:1', command_line.command_widget.text
command_line.prompt = 'later:'
assert.equal 'outer:0later:1', command_line.command_widget.text
assert.equal 'outer:0', command_line.command_widget.text
it '.stack_depth returns number of running activities', ->
depths = {}
table.insert depths, command_line.stack_depth
run_as_handler ->
table.insert depths, command_line.stack_depth
run_as_handler ->
table.insert depths, command_line.stack_depth
run_as_handler ->
table.insert depths, command_line.stack_depth
table.insert depths, command_line.stack_depth
table.insert depths, command_line.stack_depth
table.insert depths, command_line.stack_depth
assert.same { 0, 1, 2, 3, 2, 1, 0 }, depths
it '\\abort_all! cancels all running activities', ->
depths = {}
table.insert depths, command_line.stack_depth
run_as_handler ->
table.insert depths, command_line.stack_depth
run_as_handler ->
table.insert depths, command_line.stack_depth
run_as_handler ->
table.insert depths, command_line.stack_depth
command_line\abort_all!
table.insert depths, command_line.stack_depth
assert.same { 0, 1, 2, 3, 0 }, depths
it 'finishing any activity aborts all nested activities', ->
depths = {}
table.insert depths, command_line.stack_depth
run_as_handler ->
dispatch.launch ->
table.insert depths, command_line.stack_depth
p = dispatch.park 'command_line_test'
dispatch.launch ->
run_as_handler -> run_as_handler ->
table.insert depths, command_line.stack_depth
dispatch.resume p
dispatch.wait p
table.insert depths, command_line.stack_depth
assert.same {0, 1, 3, 1}, depths
it '\\clear_all! clears the entire command line and restores on exit', ->
texts = {}
run_as_handler ->
command_line.prompt = 'outér:'
command_line.text = '0'
run_as_handler ->
table.insert texts, command_line.command_widget.text
command_line\clear_all!
table.insert texts, command_line.command_widget.text
command_line.prompt = 'innér:'
command_line.text = '1'
table.insert texts, command_line.command_widget.text
table.insert texts, command_line.command_widget.text
assert.same { 'outér:0', '', 'innér:1', 'outér:0' }, texts
| 35.880866 | 83 | 0.599759 |
a545b0130803d40a539597c6080c6a7ecca3f827 | 87 | includer.IncludeFiles({
client: {}
server: {}
shared: {
'language_sh.lua'
}
})
| 8.7 | 23 | 0.597701 |
147b95dc570a8a13a18df0191eedccdfd1b87c82 | 1,080 | aztable = require "mooncrafts.aztable"
util = require "mooncrafts.util"
log = require "mooncrafts.log"
import string_connection_parse, string_random, to_json from util
import string_connection_parse from util
describe "mooncrafts.aztable", ->
it "create table if not exists", ->
azure_storage = os.getenv("AZURE_STORAGE")
if (azure_storage)
azure = string_connection_parse (azure_storage)
opts = {
table_name: "del1" .. util.string_random(5),
account_name: azure.AccountName,
account_key: azure.AccountKey
}
newOpts = aztable.item_list(opts)
newOpts.account_name = opts.account_name
newOpts.account_key = opts.account_key
newOpts.table_name = opts.table_name
res = aztable.request(newOpts, true)
-- print to_json(res)
-- delete table
assert.same 200, res.code
newOpts.table_name = "Tables('#{opts.table_name}')"
newOpts = aztable.table_opts(newOpts, "DELETE")
res = aztable.request(newOpts)
-- print to_json(res)
assert.same 204, res.code
| 32.727273 | 64 | 0.680556 |
d4d82661a3a2606bbb49eb9f953a4ace71106fae | 14,881 | {:cimport, :cppimport, :internalize, :eq, :neq, :ffi, :lib, :cstr, :to_cstr} = require 'test.unit.helpers'
require 'lfs'
require 'bit'
fs = cimport './src/nvim/os/os.h'
-- TODO(aktau): define these constants "better"
FAIL = 0
OK = 1
cppimport 'sys/stat.h'
describe 'fs function', ->
setup ->
lfs.mkdir 'unit-test-directory'
(io.open 'unit-test-directory/test.file', 'w').close!
(io.open 'unit-test-directory/test_2.file', 'w').close!
lfs.link 'test.file', 'unit-test-directory/test_link.file', true
-- Since the tests are executed, they are called by an executable. We use
-- that executable for several asserts.
export absolute_executable = arg[0]
-- Split absolute_executable into a directory and the actual file name for
-- later usage.
export directory, executable_name = string.match(absolute_executable, '^(.*)/(.*)$')
teardown ->
os.remove 'unit-test-directory/test.file'
os.remove 'unit-test-directory/test_2.file'
os.remove 'unit-test-directory/test_link.file'
lfs.rmdir 'unit-test-directory'
describe 'os_dirname', ->
os_dirname = (buf, len) ->
fs.os_dirname buf, len
before_each ->
export len = (string.len lfs.currentdir!) + 1
export buf = cstr len, ''
it 'returns OK and writes current directory into the buffer if it is large
enough', ->
eq OK, (os_dirname buf, len)
eq lfs.currentdir!, (ffi.string buf)
-- What kind of other failing cases are possible?
it 'returns FAIL if the buffer is too small', ->
buf = cstr (len-1), ''
eq FAIL, (os_dirname buf, (len-1))
describe 'path_full_dir_name', ->
path_full_dir_name = (directory, buffer, len) ->
directory = to_cstr directory
fs.path_full_dir_name directory, buffer, len
before_each ->
-- Create empty string buffer which will contain the resulting path.
export len = (string.len lfs.currentdir!) + 22
export buffer = cstr len, ''
it 'returns the absolute directory name of a given relative one', ->
result = path_full_dir_name '..', buffer, len
eq OK, result
old_dir = lfs.currentdir!
lfs.chdir '..'
expected = lfs.currentdir!
lfs.chdir old_dir
eq expected, (ffi.string buffer)
it 'returns the current directory name if the given string is empty', ->
eq OK, (path_full_dir_name '', buffer, len)
eq lfs.currentdir!, (ffi.string buffer)
it 'fails if the given directory does not exist', ->
eq FAIL, path_full_dir_name('does_not_exist', buffer, len)
it 'works with a normal relative dir', ->
result = path_full_dir_name('unit-test-directory', buffer, len)
eq lfs.currentdir! .. '/unit-test-directory', (ffi.string buffer)
eq OK, result
os_isdir = (name) ->
fs.os_isdir (to_cstr name)
describe 'os_isdir', ->
it 'returns false if an empty string is given', ->
eq false, (os_isdir '')
it 'returns false if a nonexisting directory is given', ->
eq false, (os_isdir 'non-existing-directory')
it 'returns false if a nonexisting absolute directory is given', ->
eq false, (os_isdir '/non-existing-directory')
it 'returns false if an existing file is given', ->
eq false, (os_isdir 'unit-test-directory/test.file')
it 'returns true if the current directory is given', ->
eq true, (os_isdir '.')
it 'returns true if the parent directory is given', ->
eq true, (os_isdir '..')
it 'returns true if an arbitrary directory is given', ->
eq true, (os_isdir 'unit-test-directory')
it 'returns true if an absolute directory is given', ->
eq true, (os_isdir directory)
describe 'os_can_exe', ->
os_can_exe = (name) ->
fs.os_can_exe (to_cstr name)
it 'returns false when given a directory', ->
eq false, (os_can_exe './unit-test-directory')
it 'returns false when given a regular file without executable bit set', ->
eq false, (os_can_exe 'unit-test-directory/test.file')
it 'returns false when the given file does not exists', ->
eq false, (os_can_exe 'does-not-exist.file')
it 'returns true when given an executable inside $PATH', ->
eq true, (os_can_exe executable_name)
it 'returns true when given an executable relative to the current dir', ->
old_dir = lfs.currentdir!
lfs.chdir directory
relative_executable = './' .. executable_name
eq true, (os_can_exe relative_executable)
lfs.chdir old_dir
describe 'file permissions', ->
os_getperm = (filename) ->
perm = fs.os_getperm (to_cstr filename)
tonumber perm
os_setperm = (filename, perm) ->
fs.os_setperm (to_cstr filename), perm
os_file_is_readonly = (filename) ->
fs.os_file_is_readonly (to_cstr filename)
os_file_is_writable = (filename) ->
fs.os_file_is_writable (to_cstr filename)
bit_set = (number, check_bit) ->
if 0 == (bit.band number, check_bit) then false else true
set_bit = (number, to_set) ->
return bit.bor number, to_set
unset_bit = (number, to_unset) ->
return bit.band number, (bit.bnot to_unset)
describe 'os_getperm', ->
it 'returns -1 when the given file does not exist', ->
eq -1, (os_getperm 'non-existing-file')
it 'returns a perm > 0 when given an existing file', ->
assert.is_true (os_getperm 'unit-test-directory') > 0
it 'returns S_IRUSR when the file is readable', ->
perm = os_getperm 'unit-test-directory'
assert.is_true (bit_set perm, ffi.C.kS_IRUSR)
describe 'os_setperm', ->
it 'can set and unset the executable bit of a file', ->
perm = os_getperm 'unit-test-directory/test.file'
perm = unset_bit perm, ffi.C.kS_IXUSR
eq OK, (os_setperm 'unit-test-directory/test.file', perm)
perm = os_getperm 'unit-test-directory/test.file'
assert.is_false (bit_set perm, ffi.C.kS_IXUSR)
perm = set_bit perm, ffi.C.kS_IXUSR
eq OK, os_setperm 'unit-test-directory/test.file', perm
perm = os_getperm 'unit-test-directory/test.file'
assert.is_true (bit_set perm, ffi.C.kS_IXUSR)
it 'fails if given file does not exist', ->
perm = ffi.C.kS_IXUSR
eq FAIL, (os_setperm 'non-existing-file', perm)
describe 'os_file_is_readonly', ->
it 'returns true if the file is readonly', ->
perm = os_getperm 'unit-test-directory/test.file'
perm_orig = perm
perm = unset_bit perm, ffi.C.kS_IWUSR
perm = unset_bit perm, ffi.C.kS_IWGRP
perm = unset_bit perm, ffi.C.kS_IWOTH
eq OK, (os_setperm 'unit-test-directory/test.file', perm)
eq true, os_file_is_readonly 'unit-test-directory/test.file'
eq OK, (os_setperm 'unit-test-directory/test.file', perm_orig)
it 'returns false if the file is writable', ->
eq false, os_file_is_readonly 'unit-test-directory/test.file'
describe 'os_file_is_writable', ->
it 'returns 0 if the file is readonly', ->
perm = os_getperm 'unit-test-directory/test.file'
perm_orig = perm
perm = unset_bit perm, ffi.C.kS_IWUSR
perm = unset_bit perm, ffi.C.kS_IWGRP
perm = unset_bit perm, ffi.C.kS_IWOTH
eq OK, (os_setperm 'unit-test-directory/test.file', perm)
eq 0, os_file_is_writable 'unit-test-directory/test.file'
eq OK, (os_setperm 'unit-test-directory/test.file', perm_orig)
it 'returns 1 if the file is writable', ->
eq 1, os_file_is_writable 'unit-test-directory/test.file'
it 'returns 2 when given a folder with rights to write into', ->
eq 2, os_file_is_writable 'unit-test-directory'
describe 'file operations', ->
setup ->
(io.open 'unit-test-directory/test_remove.file', 'w').close!
teardown ->
os.remove 'unit-test-directory/test_remove.file'
os_file_exists = (filename) ->
fs.os_file_exists (to_cstr filename)
os_rename = (path, new_path) ->
fs.os_rename (to_cstr path), (to_cstr new_path)
os_remove = (path) ->
fs.os_remove (to_cstr path)
describe 'os_file_exists', ->
it 'returns false when given a non-existing file', ->
eq false, (os_file_exists 'non-existing-file')
it 'returns true when given an existing file', ->
eq true, (os_file_exists 'unit-test-directory/test.file')
describe 'os_rename', ->
test = 'unit-test-directory/test.file'
not_exist = 'unit-test-directory/not_exist.file'
it 'can rename file if destination file does not exist', ->
eq OK, (os_rename test, not_exist)
eq false, (os_file_exists test)
eq true, (os_file_exists not_exist)
eq OK, (os_rename not_exist, test) -- restore test file
it 'fail if source file does not exist', ->
eq FAIL, (os_rename not_exist, test)
it 'can overwrite destination file if it exists', ->
other = 'unit-test-directory/other.file'
file = io.open other, 'w'
file\write 'other'
file\flush!
file\close!
eq OK, (os_rename other, test)
eq false, (os_file_exists other)
eq true, (os_file_exists test)
file = io.open test, 'r'
eq 'other', (file\read '*all')
file\close!
describe 'os_remove', ->
it 'returns non-zero when given a non-existing file', ->
neq 0, (os_remove 'non-existing-file')
it 'removes the given file and returns 0', ->
eq true, (os_file_exists 'unit-test-directory/test_remove.file')
eq 0, (os_remove 'unit-test-directory/test_remove.file')
eq false, (os_file_exists 'unit-test-directory/test_remove.file')
describe 'folder operations', ->
os_mkdir = (path, mode) ->
fs.os_mkdir (to_cstr path), mode
os_rmdir = (path) ->
fs.os_rmdir (to_cstr path)
describe 'os_mkdir', ->
it 'returns non-zero when given a already existing directory', ->
mode = ffi.C.kS_IRUSR + ffi.C.kS_IWUSR + ffi.C.kS_IXUSR
neq 0, (os_mkdir 'unit-test-directory', mode)
it 'creates a directory and returns 0', ->
mode = ffi.C.kS_IRUSR + ffi.C.kS_IWUSR + ffi.C.kS_IXUSR
eq false, (os_isdir 'unit-test-directory/new-dir')
eq 0, (os_mkdir 'unit-test-directory/new-dir', mode)
eq true, (os_isdir 'unit-test-directory/new-dir')
lfs.rmdir 'unit-test-directory/new-dir'
describe 'os_rmdir', ->
it 'returns non_zero when given a non-existing directory', ->
neq 0, (os_rmdir 'non-existing-directory')
it 'removes the given directory and returns 0', ->
lfs.mkdir 'unit-test-directory/new-dir'
eq 0, (os_rmdir 'unit-test-directory/new-dir', mode)
eq false, (os_isdir 'unit-test-directory/new-dir')
describe 'FileInfo', ->
file_info_new = () ->
file_info = ffi.new 'FileInfo[1]'
file_info[0].stat.st_ino = 0
file_info[0].stat.st_dev = 0
file_info
is_file_info_filled = (file_info) ->
file_info[0].stat.st_ino > 0 and file_info[0].stat.st_dev > 0
describe 'os_get_file_info', ->
it 'returns false if given an non-existing file', ->
file_info = file_info_new!
assert.is_false (fs.os_get_file_info '/non-existent', file_info)
it 'returns true if given an existing file and fills file_info', ->
file_info = file_info_new!
path = 'unit-test-directory/test.file'
assert.is_true (fs.os_get_file_info path, file_info)
assert.is_true (is_file_info_filled file_info)
it 'returns the file info of the linked file, not the link', ->
file_info = file_info_new!
path = 'unit-test-directory/test_link.file'
assert.is_true (fs.os_get_file_info path, file_info)
assert.is_true (is_file_info_filled file_info)
mode = tonumber file_info[0].stat.st_mode
eq ffi.C.kS_IFREG, (bit.band mode, ffi.C.kS_IFMT)
describe 'os_get_file_info_link', ->
it 'returns false if given an non-existing file', ->
file_info = file_info_new!
assert.is_false (fs.os_get_file_info_link '/non-existent', file_info)
it 'returns true if given an existing file and fills file_info', ->
file_info = file_info_new!
path = 'unit-test-directory/test.file'
assert.is_true (fs.os_get_file_info_link path, file_info)
assert.is_true (is_file_info_filled file_info)
it 'returns the file info of the link, not the linked file', ->
file_info = file_info_new!
path = 'unit-test-directory/test_link.file'
assert.is_true (fs.os_get_file_info_link path, file_info)
assert.is_true (is_file_info_filled file_info)
mode = tonumber file_info[0].stat.st_mode
eq ffi.C.kS_IFLNK, (bit.band mode, ffi.C.kS_IFMT)
describe 'os_get_file_info_fd', ->
it 'returns false if given an invalid file descriptor', ->
file_info = file_info_new!
assert.is_false (fs.os_get_file_info_fd -1, file_info)
it 'returns true if given an file descriptor and fills file_info', ->
file_info = file_info_new!
path = 'unit-test-directory/test.file'
fd = ffi.C.open path, 0
assert.is_true (fs.os_get_file_info_fd fd, file_info)
assert.is_true (is_file_info_filled file_info)
ffi.C.close fd
describe 'os_file_info_id_equal', ->
it 'returns false if file infos represent different files', ->
file_info_1 = file_info_new!
file_info_2 = file_info_new!
path_1 = 'unit-test-directory/test.file'
path_2 = 'unit-test-directory/test_2.file'
assert.is_true (fs.os_get_file_info path_1, file_info_1)
assert.is_true (fs.os_get_file_info path_2, file_info_2)
assert.is_false (fs.os_file_info_id_equal file_info_1, file_info_2)
it 'returns true if file infos represent the same file', ->
file_info_1 = file_info_new!
file_info_2 = file_info_new!
path = 'unit-test-directory/test.file'
assert.is_true (fs.os_get_file_info path, file_info_1)
assert.is_true (fs.os_get_file_info path, file_info_2)
assert.is_true (fs.os_file_info_id_equal file_info_1, file_info_2)
it 'returns true if file infos represent the same file (symlink)', ->
file_info_1 = file_info_new!
file_info_2 = file_info_new!
path_1 = 'unit-test-directory/test.file'
path_2 = 'unit-test-directory/test_link.file'
assert.is_true (fs.os_get_file_info path_1, file_info_1)
assert.is_true (fs.os_get_file_info path_2, file_info_2)
assert.is_true (fs.os_file_info_id_equal file_info_1, file_info_2)
| 37.673418 | 106 | 0.647067 |
7f7a39bfe0a39dd114a254063611b629ba324bc6 | 4,481 | import IRCClient from require 'lib.irc'
colors = {3, 4, 6, 8, 9, 10, 11, 13} -- "bright" pallet of IRC colors
hash = (input)->
out_hash = 5381
for char in input\gmatch "."
out_hash = ((out_hash << 5) + out_hash) + char\byte!
return out_hash
color = (input)-> "\003#{colors[hash(input) % #colors + 1]}#{input}\003"
patterns = {
RENAME: "%s \00309=>\003 %s \00314(\00315%s\00314)\003"
RENAME_2: "%s \00309=>\003 %s \00314(\00315%s\00314|\00315%s\00314)\003"
JOIN: "\00308[\003%s\00308]\003 \00309>\003 %s"
MODE: "\00308[\003%s\00308]\003 Mode %s by %s"
KICK: "\00308[\003%s\00308]\003 %s kicked %s"
KICK_2: "\00308[\003%s\00308]\003 %s kicked %s \00314(\00315%s\00314)\003"
PART: "\00308[\003%s\00308]\003 \00304<\003 %s"
PART_2: "\00308[\003%s\00308]\003 \00304<\003 %s \00314(\00315%s\00314)\003"
QUIT: "\00311<\003%s\00311>\003 \00304<\003"
QUIT_2: "\00311<\003%s\00311>\003 \00304<\003 \00315(\00314%s\00315)\003"
ACTION: "\00308[\003%s\00308]\003 * %s %s"
ACTION_2: "* %s %s"
PRIVMSG: "\00311<\00308[\003%s\00308]\003%s\00311>\003 %s"
PRIVMSG_2: "\00311<\003%s\00311>\003 %s"
NOTICE: "\00311-\00308[\003%s\00308]\003%s\00311-\003 %s"
NOTICE_2: "\00311-\003%s\00311-\003 %s"
INVITE: "\00308[\003%s\00308]\003 %s invited %s"
NETJOIN: "\00308[\003%s\00308]\003 \00309>\003 \00314(\00315%s\00314)\003"
NETSPLIT: "\00304<\003 \00314(\00315%s\00314)\003"
}
serve_self = (new_table)-> setmetatable(new_table, {__call: ()=>pairs(@)})
IRCClient\add_handler '372', (prefix, args)=>
@log "\00305" .. args[#args]
IRCClient\add_handler 'RENAME', (prefix, args)=>
{:nick} = prefix
unless args[3] and args[3] != ""
@log patterns.RENAME\format args[1], args[2], nick
else
@log patterns.RENAME_2\format args[1], args[2], nick, args[3]
IRCClient\add_handler 'JOIN', (prefix, args, tags, opts)=>
-- user JOINs a channel
return if opts.in_batch
channel = args[1]
@log patterns.JOIN\format channel, color(prefix.nick)
IRCClient\add_handler 'NICK', (prefix, args)=>
old = color(prefix.nick)
new = color(args[1])
@log ('%s \00309>>\003 %s')\format old, new
IRCClient\add_handler 'MODE', (prefix, args)=>
-- User or bot called /mode
channel = args[1]
if channel\sub(1,1) == "#"
@log patterns.MODE\format channel, table.concat(args, " ", 2),
color(prefix.nick)
IRCClient\add_handler 'KICK', (prefix, args)=>
channel = args[1]
nick = color(args[2])
kicker = color(prefix.nick)
if args[3]
@log patterns.KICK_2\format channel, kicker, nick, args[3]
else
@log patterns.KICK\format channel, kicker, nick
IRCClient\add_handler 'PART', (prefix, args)=>
-- User or bot parted channel, clear from lists
channel = args[1]
nick = color(prefix.nick)
if args[3]
@log patterns.PART_2\format channel, nick, args[3]
else
@log patterns.PART\format channel, nick
IRCClient\add_handler 'QUIT', (prefix, args, tags, opts)=>
return if opts.in_batch -- post-batch output processing, is not normal
nick = color(prefix.nick)
if args[1]
@log patterns.QUIT_2\format nick, args[1]
else
@log patterns.QUIT\format nick
IRCClient\add_handler 'PRIVMSG', (prefix, args)=>
{:nick} = prefix
{target, message} = args
unless target\sub(1, 1) == '#'
if message\match "^\001ACTION .-\001$"
@log patterns.ACTION_2\format color(nick),
message\match('^%S+%s+(.+).')
elseif not message\match '^\001'
@log patterns.PRIVMSG_2\format color(nick), message
else
prefix = ""
@users\get(nick)\and_then (client)->
client.channels\get(target)\and_then (channel)->
prefix = channel.statuses\entry(nick)\or_insert ""
if prefix != ""
prefix = color(prefix)
user = prefix .. color(nick)
if message\match "^\001ACTION .-\001$"
@log patterns.ACTION\format target, user, message\match('^%S+%s+(.+).')
elseif not message\match '^\001'
@log patterns.PRIVMSG\format target, user, message
IRCClient\add_handler 'NOTICE', (prefix, args)=>
return if args[2]\sub(1, 1) == '\001' -- CTCP
{:nick} = prefix
if args[1]\sub(1, 1) == '#'
prefix = ""
@users\get(nick)\and_then (client)->
client.channels\get(args[1])\and_then (channel)->
prefix = channel.statuses\entry(nick)\or_insert ""
if prefix != ""
prefix = color(prefix)
user = prefix .. color(nick)
@log patterns.NOTICE\format args[1], user, args[2]
else
@log patterns.NOTICE_2\format color(nick), args[2]
IRCClient\add_handler 'INVITE', (prefix, args)=>
nick = color(prefix.nick)
channel = args[2]
@log patterns.INVITE\format channel, nick, args[1]
| 33.440299 | 77 | 0.662129 |
9e8094d37f5fb777b38f9d46858df2e3376bb735 | 318 | export modinfo = {
type: "command"
desc: "Infinity shout"
alias: {"ishout"}
func: (Msg,Speaker) ->
tag = CreateInstance"StringValue"
Parent: Service"Lighting"
Name: "INFSHOUT"
Value: string.format("%s: %s",CharacterName, Msg)
wait(1)
tag.Parent = nil
loggit(string.format("You shouted %s",Msg))
} | 22.714286 | 52 | 0.663522 |
d39f852a8962d9a99ed319e2088bb8c573da8b3c | 1,524 | import LinkedList from "novacbn/novautils/collections/LinkedList"
-- ::makeDetachFunc(table signal, function listenerNode) -> function
-- Returns a shortcut function to detach the listener Node
--
makeDetachFunc = (signal, node) ->
return () ->
-- If not previously detached, detach the listener Node now
unless node.removed
signal\remove(node)
return false
-- Return true since previously detached from the Signal
return true
-- Signal::Signal()
-- Represents a generic Signal dispatcher
-- export
export Signal = LinkedList\extend {
-- Signal::attach(function listenerFunc) -> function
-- Attaches the listener function to the Signal, returning a shortcut function for detachment
--
attach: (listenerFunc) =>
-- Make and return a shortcut detach function
node = @push(listenerFunc)
return makeDetachFunc(self, node)
-- Signal::dispatch(any ...) -> void
-- Dispatches the vararg to all the currently attached listeners
--
dispatch: (...) =>
-- Dispatches the vararg to the attached listeners
node.value(...) for node in self\iter()
-- Signal::detach(function listenerFunc) -> void
-- Detaches the listener function from the Signal
--
detach: (listenerFunc) =>
-- Retrieve the node for the listener function, then detach it
node = @find(listenerFunc)
error("bad argument #1 to 'detach' (function not attached)") unless node
@remove(node)
} | 35.44186 | 97 | 0.662073 |
2f2b4b9d4450f49c2a82fc3d20dadd0b64e584e9 | 512 | -- Copyright 2017 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
ffi = require 'ffi'
require 'ljglibs.cdefs.gdk'
core = require 'ljglibs.core'
C = ffi.C
core.define 'GtkTargetList', {
new: () ->
ptr = C.gtk_target_list_new nil, 0
ffi.gc ptr, C.gtk_target_list_unref
add: (target, flags = 0, info = 0) =>
flags = core.parse_flags('GTK_TARGET_', flags)
C.gtk_target_list_add @, target, flags, info
}, (def, targets) ->
def.new targets
| 25.6 | 79 | 0.683594 |
96d06b120909dd56aaad0ab934621e09c800a0ff | 7,086 | describe "parser extends option", ->
parse = require('lush.parser')
describe "error checking", ->
it "rejects non-tables", ->
bads = {
"",
1,
}
for _, v in ipairs(bads)
e = assert.has_error(->
parse((-> {
B { A }
}), {extends: v}))
assert.matches("malformed_lush_spec_extends_option", e.code)
assert.not.matches("No message avaliable", e.msg)
it "rejects non-ordered lists", ->
good = parse(-> {
A { fg: "red" }
})
good_2 = parse(-> {
A { fg: "red" }
})
t = {
good: good,
good_2: good_2
}
e = assert.has_error(->
parse((-> {
B { A }
}), {extends: t}))
assert.matches("malformed_lush_spec_extends_option", e.code)
assert.not.matches("No message avaliable", e.msg)
it "rejects tables not containing parsed_lush_specs", ->
-- table but bad
e = assert.has_error(->
parse((-> {
B { A }
}), {extends: {fg: '1'}}))
assert.matches("malformed_lush_spec_extends_option", e.code)
assert.not.matches("No message avaliable", e.msg)
-- table but some good some bad
good = parse(-> {
A { fg: "red" }
})
looks_good_but_is_bad = {
A: {
fg: "red"
}
}
e = assert.has_error(->
parse((-> {
B { A }
}), {extends: {good, looks_good_but_is_bad}}))
assert.matches("malformed_lush_spec_extends_option", e.code)
assert.not.matches("No message avaliable", e.msg)
describe "behaviours", ->
it "inherits all properties of a parent spec", ->
parent_spec = -> {
A { bg: "a_bg" , fg: "a_fg" },
}
parent = parse(parent_spec)
child_spec = -> {}
child = parse(child_spec, {extends: {parent}})
assert.not_nil(child)
assert.is_not_nil(child.A)
assert.is_equal(child.A.bg, "a_bg")
assert.is_equal(child.A.fg, "a_fg")
it "can make new group from parent", ->
parent_spec = -> {
A { bg: "a_bg" , fg: "a_fg" },
}
parent = parse(parent_spec)
child_spec = -> {
B { fg: parent.A.fg, bg: "b_bg"}
}
child = parse(child_spec, {extends: {parent}})
assert.is_not_nil(child.A)
assert.is_not_nil(child.B)
assert.is_equal(child.B.fg, "a_fg")
assert.is_equal(child.B.bg, "b_bg")
it "concats extensions from first to last", ->
base = parse -> {
A { bg: "a_bg" , fg: "a_fg" },
B { bg: "b_bg", fg: "b_fg" } -- should not end up in final spec
}
base_2 = parse -> {
B { fg: "base_2_b_fg" } -- should overwrite base
}
child_spec = -> {
}
child = parse(child_spec, {extends: {base, base_2}})
assert.is_not_nil(child.A)
assert.is_not_nil(child.B)
assert.is_equal(child.A.fg, "a_fg")
assert.is_equal(child.B.fg, "base_2_b_fg")
assert.is_nil(child.B.bg) -- B was redefined, so bg should be nil
-- 2021-03-07-1420
-- no longer performs automatic lookup
--
-- it "performs lookup from last to first", ->
-- base = parse -> {
-- A { bg: "a_bg" , fg: "a_fg" },
-- B { bg: "b_bg", fg: "b_fg" } -- should not end up in final spec
-- }
-- base_2 = parse -> {
-- B { fg: "base_2_b_fg" } -- should overwrite base
-- }
-- child_spec = -> {
-- C { B }
-- }
-- child = parse(child_spec, {extends: {base, base_2}})
-- -- should prefer base_2 values
-- assert.is_equal(child.C.fg, "base_2_b_fg")
-- assert.is_nil(child.C.bg) -- B was redefined, so bg should be nil
-- -- should prefer base values
-- child = parse(child_spec, {extends: {base_2, base}})
-- assert.is_equal(child.C.fg, "b_fg")
-- assert.is_equal(child.C.bg, "b_bg")
it "can chain extends", ->
base = parse -> {
A { bg: "a_bg" , fg: "a_fg" },
}
base_2 = parse((-> {
B { bg: "b_bg", fg: base.A.fg },
C { bg: "c_bg" }
}), {extends: {base}})
base_3 = parse((-> {
D { bg: base_2.A.bg, fg: base_2.B.fg },
Z { bg: "z_bg" }
}), {extends: {base_2}})
assert.is_equal(base_3.Z.bg, "z_bg")
assert.is_equal(base_3.D.bg, "a_bg")
assert.is_equal(base_3.D.fg, "a_fg")
assert.is_equal(base_3.C.bg, "c_bg")
assert.is_equal(base_3.B.bg, "b_bg")
assert.is_equal(base_3.B.fg, "a_fg")
it "can link to an extended group", ->
parent_spec = -> {
A { bg: "a_bg" , fg: "a_fg" },
}
parent = parse(parent_spec)
child_spec = -> {
B { parent.A }
}
child = parse(child_spec, {extends: {parent}})
assert.not_nil(child)
assert.is_not_nil(child.A)
assert.is_equal(child.A.bg, "a_bg")
assert.is_equal(child.A.fg, "a_fg")
assert.is_equal(child.B.bg, "a_bg")
assert.is_equal(child.B.fg, "a_fg")
it "can group inherit from an extended group", ->
parent_spec = -> {
A { bg: "a_bg" , fg: "a_fg" },
}
parent = parse(parent_spec)
child_spec = -> {
B { parent.A, bg: "b_bg" }
}
child = parse(child_spec, {extends: {parent}})
assert.not_nil(child)
assert.is_not_nil(child.A)
assert.is_equal(child.A.bg, "a_bg")
assert.is_equal(child.A.fg, "a_fg")
assert.is_equal(child.B.bg, "b_bg")
assert.is_equal(child.B.fg, "a_fg")
it "can group inherit self from an extended group", ->
parent_spec = -> {
A { bg: "a_bg" , fg: "a_fg" },
}
parent = parse(parent_spec)
child_spec = -> {
A { parent.A, bg: "b_bg" }
}
child = parse(child_spec, {extends: {parent}})
assert.not_nil(child)
assert.is_not_nil(child.A)
assert.is_equal(child.A.bg, "b_bg")
assert.is_equal(child.A.fg, "a_fg")
it "chain link", ->
base = parse -> {
A { bg: "a_bg" , fg: "a_fg" },
}
base_2 = parse((-> {
B { base.A }
}), {extends: {base}})
base_3 = parse((-> {
C { base_2.B }
Z { base_2.A }
}), {extends: {base_2}})
assert.is_equal(base_3.A.fg, "a_fg")
assert.is_equal(base_3.A.bg, "a_bg")
assert.is_equal(base_3.B.fg, "a_fg")
assert.is_equal(base_3.B.bg, "a_bg")
assert.is_equal(base_3.C.fg, "a_fg")
assert.is_equal(base_3.C.bg, "a_bg")
assert.is_equal(base_3.Z.fg, "a_fg")
assert.is_equal(base_3.Z.bg, "a_bg")
it "can handle a complex case", ->
base = parse -> {
A { bg: "a_bg" , fg: "a_fg" },
Y { A },
Z { bg: "z_bg", fg: "z_fg" }
}
base_2 = parse((-> {
A { fg: base.A.bg },
B { bg: "arst", fg: "rsast" }
O { base.Y },
X { base.Z, fg: "x_z_fg" }
}), {extends: {base}})
assert.is_equal(base_2.O.bg, "a_bg")
assert.is_equal(base_2.X.bg, "z_bg")
assert.is_equal(base_2.X.fg, "x_z_fg")
| 27.359073 | 74 | 0.518346 |
74c60c89f839018957268501ef7778cb56a1679f | 714 |
assert = require("vimp.util.assert")
log = require("vimp.util.log")
helpers = require("vimp.testing.helpers")
UniqueTrie = require("vimp.unique_trie")
class Tester
test1: =>
helpers.unlet('foo')
vimp.nnoremap 'dlb', [[:let g:foo = 5<cr>]]
helpers.set_lines({"abcdef"})
assert.is_equal(vim.g.foo, nil)
helpers.input("0fc")
helpers.rinput('dlb')
assert.is_equal(vim.g.foo, 5)
assert.is_equal(helpers.get_line!, 'abcdef')
helpers.rinput("dl<esc>")
assert.is_equal(helpers.get_line!, 'abdef')
helpers.set_lines({"abcdef"})
helpers.input("0fc")
vimp.add_chord_cancellations('n', 'd')
helpers.rinput("dl<esc>")
assert.is_equal(helpers.get_line!, 'abcdef')
| 29.75 | 48 | 0.662465 |
2357493ad0aec865860c8e75314c397683b5dcd1 | 1,084 | import basename from require "path"
import Asset from "novacbn/gmodproj/api/Asset"
import toByteString from "novacbn/gmodproj/lib/utilities/string"
-- ::TEMPLATE_MODULE_LUA(string assetName, string byteString) -> string
-- Templates a resource asset into Lua module the parsed a byte string
TEMPLATE_MODULE_LUA = (assetName, byteString) -> "local byteTable = #{byteString}
local string_char = string.char
local table_concat = table.concat
for index, byte in ipairs(byteTable) do
byteTable[index] = string_char(byte)
end
exports['#{basename(assetName)}'] = table_concat(byteTable, '')"
-- ResourceAsset::ResourceAsset()
-- Represents a generic asset that is encoded as a byte string, useful for plaintext/binary assets that are not Lua code
export ResourceAsset = Asset\extend {
-- ResourceAsset::postTransform(string contents) -> string
-- Packages the asset as a Lua readable byte string
postTransform: (contents) =>
-- Transform the asset into a byte string and template it
return TEMPLATE_MODULE_LUA(@assetName, toByteString(contents))
} | 41.692308 | 120 | 0.752768 |
d673b78a3fc39087c6dd45b3160f489b65f23308 | 613 | -- config.moon
config = require "lapis.config"
config "development", ->
port 8080
measure_performance false
config "production", ->
port 80
num_workers 4
code_cache "on"
measure_performance true
cache_ttl 10
config "test", ->
port 8081
measure_performance true
config "db_development", ->
url "http://0.0.0.0:8530/"
name "cms"
login "root"
pass "password"
config "db_production", ->
url "http://12.12.0.6:8529/"
name "cms"
login "root"
pass "password"
-- for test purpose
config "db_test", ->
url "http://12.12.0.6:8529/"
name "cms"
login "root"
pass "password"
| 16.567568 | 31 | 0.657423 |
d7a123ce5a739a22fa92d7849e3868a9eaac1452 | 335 | tasks:
compile: => for file in wildcard "*.lua" do sh "moonc #{file}" unless file == "Alfons.moon"
make: => sh "rockbuild -m --delete #{@v}" if @v
release: => sh "rockbuild -m -t #{@v} u" if @v
clean: => for file in wildcard "*.lua" do fs.delete file
test: => sh "cat test/table.txt | tableview > test/table.html" | 55.833333 | 93 | 0.591045 |
0fdf3606bd675faa7bb4b213eb21a09ad3c35e2d | 416 | -- Copyright 2013-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
mode_reg =
name: 'haml'
extensions: 'haml'
create: -> bundle_load('haml_mode')!
howl.mode.register mode_reg
unload = -> howl.mode.unregister 'haml'
return {
info:
author: 'Copyright 2013-2015 The Howl Developers',
description: 'Haml mode',
license: 'MIT',
:unload
}
| 19.809524 | 79 | 0.692308 |
12f0be503ea0b96a4f14fae4ebbf0adae553dba0 | 13,808 | socket = require "pgmoon.socket"
import insert from table
import rshift, lshift, band from require "bit"
unpack = table.unpack or unpack
VERSION = "1.10.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
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"
new: (opts) =>
@sock, @sock_type = socket.new opts and opts.socket_type
if opts
@user = opts.user
@host = opts.host
@database = opts.database
@port = opts.port
@password = opts.password
@ssl = opts.ssl
@ssl_verify = opts.ssl_verify
@ssl_required = opts.ssl_required
@pool_name = opts.pool
@luasec_opts = {
key: opts.key
cert: opts.cert
cafile: opts.cafile
}
connect: =>
opts = if @sock_type == "nginx"
{
pool: @pool_name or "#{@host}:#{@port}:#{@database}:#{@user}"
}
ok, err = @sock\connect @host, @port, opts
return nil, err unless ok
if @sock\getreusedtimes! == 0
if @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 ...
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
else
error "don't know how to auth: #{auth_type}"
cleartext_auth: (msg) =>
assert @password, "missing password, required for connect"
@send_message MSG_TYPE.password, {
@password
NULL
}
@check_auth!
md5_auth: (msg) =>
import md5 from require "pgmoon.crypto"
salt = msg\sub 5, 8
assert @password, "missing password, required for connect"
@send_message MSG_TYPE.password, {
"md5"
md5 md5(@password .. @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 or len == 4294967295
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 @user, "missing user for connect"
assert @database, "missing database for connect"
data = {
@encode_int 196608
"user", NULL
@user, NULL
"database", NULL
@database, NULL
"application_name", NULL
"pgmoon", 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
if @sock_type == "nginx"
@sock\sslhandshake false, nil, @ssl_verify
else
@sock\sslhandshake @ssl_verify, @luasec_opts
elseif t == MSG_TYPE.error or @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 }
| 22.860927 | 82 | 0.58524 |
a35beed2d51d57f6025af3873c1b91e383d6e6cf | 1,018 | --- Script that initializes inputs and generates a bunch of Minesweeper boards
-- @module Initializer
-- Some of my comments will start with 3 dashes like the one above, these are ldoc comments that
-- describe classes, methods and fields.
-- When calling functions, parenthesis are entirely optionnal!
print "Initializing..."
-- Here we get our classes from their ModuleScripts.
gameElements = script.Parent\WaitForChild "GameElements"
Board = require gameElements\WaitForChild "Board"
MouseInputsManager = require script.Parent\WaitForChild "MouseInputsManager"
-- MouseInputsManager's Initialize method is static, it can be called directly from the class.
-- The exclamation point is how you call a parameter-less function
MouseInputsManager.Initialize!
-- Spawn our boards. Calling a class as if it were a function is how you instanciate it.
Board 12, 8, 16, Vector3.new 0, 0, -50
Board 8, 6, 8, Vector3.new 70, 0, -45
Board 20, 16, 60, Vector3.new -110, 0, -70
print "Ready!"
-- Hope you enjoyed the ride !
| 39.153846 | 96 | 0.767191 |
b961f4184be82317f0e9a4b6d605cb8f3d927fea | 4,806 |
--
-- Copyright (C) 2017-2019 DBot
-- 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.
DLib.nw.PoolBoolean('PPM2.InEditor', false)
do
import GetModel, IsDormant, GetPonyData, IsValid from FindMetaTable('Entity')
callback = ->
for _, ply in ipairs player.GetAll()
if not IsDormant(ply)
model = GetModel(ply)
ply.__ppm2_lastmodel = ply.__ppm2_lastmodel or model
if ply.__ppm2_lastmodel ~= model
data = GetPonyData(ply)
if data and data.ModelChanges
oldModel = ply.__ppm2_lastmodel
ply.__ppm2_lastmodel = model
data\ModelChanges(oldModel, model)
for _, task in ipairs PPM2.NetworkedPonyData.RenderTasks
ply = task.ent
if IsValid(ply) and not IsDormant(ply)
model = GetModel(ply)
ply.__ppm2_lastmodel = ply.__ppm2_lastmodel or model
if ply.__ppm2_lastmodel ~= model
data = GetPonyData(ply)
if data and data.ModelChanges
oldModel = ply.__ppm2_lastmodel
ply.__ppm2_lastmodel = model
data\ModelChanges(oldModel, model)
timer.Create 'PPM2.ModelWatchdog', 1, 0, ->
status, err = pcall callback
print('PPM2 Error: ' .. err) if not status
do
import GetModel, IsDormant, GetPonyData, IsValid, IsPonyCached from FindMetaTable('Entity')
hook.Add 'Think', 'PPM2.PonyDataThink', ->
for _, ply in ipairs player.GetAll()
if not IsDormant(ply) and IsPonyCached(ply)
data = GetPonyData(ply)
data\Think() if data and data.Think
for _, task in ipairs PPM2.NetworkedPonyData.RenderTasks
ply = task.ent
if IsValid(ply) and not IsDormant(ply) and IsPonyCached(ply) and task.Think
task\Think()
hook.Add 'RenderScreenspaceEffects', 'PPM2.PonyDataRenderScreenspaceEffects', ->
for _, ply in ipairs player.GetAll()
if not IsDormant(ply) and IsPonyCached(ply)
data = GetPonyData(ply)
data\RenderScreenspaceEffects() if data and data.RenderScreenspaceEffects
for _, task in ipairs PPM2.NetworkedPonyData.RenderTasks
ply = task.ent
if IsValid(ply) and not IsDormant(ply) and IsPonyCached(ply) and task.RenderScreenspaceEffects
task\RenderScreenspaceEffects()
do
catchError = (err) ->
PPM2.Message 'Slow Update Error: ', err
PPM2.Message debug.traceback()
import Alive from FindMetaTable('Player')
import IsPonyCached, IsDormant, GetPonyData from FindMetaTable('Entity')
timer.Create 'PPM2.SlowUpdate', CLIENT and 0.5 or 5, 0, ->
for _, ply in ipairs player.GetAll()
if not IsDormant(ply) and Alive(ply) and IsPonyCached(ply) and GetPonyData(ply)
data = GetPonyData(ply)
xpcall(data.SlowUpdate, catchError, data, CLIENT) if data.SlowUpdate
for _, task in ipairs PPM2.NetworkedPonyData.RenderTasks
if IsValid(task.ent) and task.ent\IsPony()
xpcall(task.SlowUpdate, catchError, task, CLIENT) if task.SlowUpdate
ENABLE_TOOLGUN = CreateConVar('ppm2_sv_ragdoll_toolgun', '0', {FCVAR_REPLICATED, FCVAR_NOTIFY}, 'Allow toolgun usage on player death ragdolls')
ENABLE_PHYSGUN = CreateConVar('ppm2_sv_ragdoll_physgun', '1', {FCVAR_REPLICATED, FCVAR_NOTIFY}, 'Allow physgun usage on player death ragdolls')
hook.Add 'CanTool', 'PPM2.DeathRagdoll', (ply = NULL, tr = {Entity: NULL}, tool = '') -> false if IsValid(tr.Entity) and tr.Entity\GetNWBool('PPM2.IsDeathRagdoll') and not ENABLE_TOOLGUN\GetBool() and tool ~= 'rope'
hook.Add 'PhysgunPickup', 'PPM2.DeathRagdoll', (ply = NULL, ent = NULL) -> false if IsValid(ent) and ent\GetNWBool('PPM2.IsDeathRagdoll') and not ENABLE_PHYSGUN\GetBool()
hook.Add 'CanProperty', 'PPM2.DeathRagdoll', (ply = NULL, mode = '', ent = NULL) -> false if IsValid(ent) and ent\GetNWBool('PPM2.IsDeathRagdoll') and not ENABLE_TOOLGUN\GetBool()
hook.Add 'CanDrive', 'PPM2.DeathRagdoll', (ply = NULL, ent = NULL) -> false if IsValid(ent) and ent\GetNWBool('PPM2.IsDeathRagdoll') and not ENABLE_TOOLGUN\GetBool()
| 48.06 | 215 | 0.74303 |
2aac4c28bc10007d0ca08efb371262b25966606e | 178 | TK = require "PackageToolkit"
M = {}
me = ...
name = "task"
members = {
"run"
"runParallel"
}
T = TK.module.submodules me, members
M[name] = () -> TK.test.self T
return M | 16.181818 | 36 | 0.595506 |
1c555055bfe76c732a4e929af2557e4d2f862b28 | 65 | print "Hello!"
double = (x) -> x * 2
export width = double(400) | 13 | 26 | 0.6 |
017e6dc3ff07c04049b5c68fd15f1f2fa77bf2b2 | 788 | -- Copyright 2012-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
mode_reg =
name: 'python'
extensions: { 'sc', 'py', 'pyw', 'pyx' }
patterns: { 'wscript$', 'SConstruct$', 'SConscript$' }
shebangs: '[/ ]python.*$'
create: -> bundle_load('python_mode')
howl.mode.register mode_reg
howl.inspection.register {
name: 'pycodestyle'
factory: -> {
cmd: 'pycodestyle <file>'
type: 'warning'
is_available: -> howl.sys.find_executable('pycodestyle'), '`pycodestyle` command not found'
}
}
unload = ->
howl.mode.unregister 'python'
howl.inspection.unregister 'pycodestyle'
return {
info:
author: 'Copyright 2015 The Howl Developers',
description: 'Python bundle',
license: 'MIT',
:unload
}
| 24.625 | 95 | 0.670051 |
37a96c5fa87332e9c1ec7efc0a334290ec1929c1 | 13,029 |
--
-- Copyright (C) 2017-2019 DBot
-- 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.
file.CreateDir('ppm2')
file.CreateDir('ppm2/backups')
file.CreateDir('ppm2/thumbnails')
for _, ffind in ipairs file.Find('ppm2/*.txt', 'DATA')
fTarget = ffind\sub(1, -5)
-- maybe joined server with old ppm2 and new clear _current was generated
if not file.Exists('ppm2/' .. fTarget .. '.dat', 'DATA')
fRead = file.Read('ppm2/' .. ffind, 'DATA')
json = util.JSONToTable(fRead)
if json
TagCompound = DLib.NBT.TagCompound()
for key, value in pairs json
switch luatype(value)
when 'string'
TagCompound\AddString(key, value)
when 'number'
TagCompound\AddFloat(key, value)
when 'boolean'
TagCompound\AddByte(key, value and 1 or 0)
when 'table'
-- assume color
TagCompound\AddByteArray(key, {value.r - 128, value.g - 128, value.b - 128, value.a - 128}) if value.r and value.g and value.b and value.a
else
error(luatype(value))
buf = DLib.BytesBuffer()
TagCompound\WriteFile(buf)
stream = file.Open('ppm2/' .. fTarget .. '.dat', 'wb', 'DATA')
buf\ToFileStream(stream)
stream\Flush()
stream\Close()
file.Delete('ppm2/' .. ffind)
class PonyDataInstance
@DATA_DIR = "ppm2/"
@DATA_DIR_BACKUP = "ppm2/backups/"
@FindFiles = =>
output = [str\sub(1, #str - 4) for _, str in ipairs file.Find(@DATA_DIR .. '*', 'DATA') when not str\find('.bak.dat')]
return output
@FindInstances = =>
output = [@(str\sub(1, #str - 4)) for _, str in ipairs file.Find(@DATA_DIR .. '*', 'DATA') when not str\find('.bak.dat')]
return output
@PONY_DATA = PPM2.PonyDataRegistry
@PONY_DATA_MAPPING = {getFunc\lower(), key for key, {:getFunc} in pairs @PONY_DATA}
@PONY_DATA_MAPPING[key] = key for key, value in pairs @PONY_DATA
for key, data in pairs @PONY_DATA
continue unless data.enum
data.enum = [arg\upper() for _, arg in ipairs data.enum]
data.enumMapping = {}
data.enumMappingBackward = {}
i = -1
for _, enumVal in ipairs data.enum
i += 1
data.enumMapping[i] = enumVal
data.enumMappingBackward[enumVal] = i
for key, {:getFunc, :fix, :enumMappingBackward, :enumMapping, :enum, :min, :max, :default} in pairs @PONY_DATA
@__base["Get#{getFunc}"] = => @dataTable[key]
@__base["GetMin#{getFunc}"] = => min if min
@__base["GetMax#{getFunc}"] = => max if max
@__base["Enum#{getFunc}"] = => enum if enum
@__base["Get#{getFunc}Types"] = => enum if enum
@["GetMin#{getFunc}"] = => min if min
@["GetMax#{getFunc}"] = => max if max
@["GetDefault#{getFunc}"] = default
@["GetEnum#{getFunc}"] = => enum if enum
@["Enum#{getFunc}"] = => enum if enum
if enumMapping
@__base["Get#{getFunc}Enum"] = => enumMapping[@dataTable[key]] or enumMapping[0] or @dataTable[key]
@__base["GetEnum#{getFunc}"] = @__base["Get#{getFunc}Enum"]
@__base["Reset#{getFunc}"] = => @["Set#{getFunc}"](@, default())
@__base["Set#{getFunc}"] = (val = defValue, ...) =>
if luatype(val) == 'string' and enumMappingBackward
newVal = enumMappingBackward[val\upper()]
val = newVal if newVal
newVal = fix(val)
oldVal = @dataTable[key]
@dataTable[key] = newVal
@ValueChanges(key, oldVal, newVal, ...)
WriteNetworkData: =>
for _, {:strName, :writeFunc, :getName, :defValue} in ipairs PPM2.NetworkedPonyData.NW_Vars
if @["Get#{getName}"]
writeFunc(@["Get#{getName}"](@))
else
writeFunc(defValue)
Copy: (fileName = @filename) =>
copyOfData = {}
for key, val in pairs @dataTable
switch luatype(val)
when 'number', 'string', 'boolean'
copyOfData[key] = val
when 'table', 'Color'
if IsColor(val)
copyOfData[key] = Color(val)
else
copyOfData[key] = Color(255, 255, 255)
newData = @@(fileName, copyOfData, false)
return newData
CreateCustomNetworkObject: (goingToNetwork = false, ply = LocalPlayer(), ...) =>
newData = PPM2.NetworkedPonyData(nil, ply)
newData\SetIsGoingToNetwork(goingToNetwork)
@ApplyDataToObject(newData, ...)
return newData
CreateNetworkObject: (goingToNetwork = true, ...) =>
newData = PPM2.NetworkedPonyData(nil, LocalPlayer())
newData\SetIsGoingToNetwork(goingToNetwork)
@ApplyDataToObject(newData, ...)
return newData
ApplyDataToObject: (target, ...) =>
for key, value in pairs @GetAsNetworked()
error("Attempt to apply data to object #{target} at unknown index #{key}!") if not target["Set#{key}"]
target["Set#{key}"](target, value, ...)
UpdateController: (...) => @ApplyDataToObject(@nwObj, ...)
CreateController: (...) => @CreateNetworkObject(false, ...)
CreateCustomController: (...) => @CreateCustomNetworkObject(false, ...)
new: (filename, data, readIfExists = true, force = false, doBackup = true) =>
@SetFilename(filename)
@NBTTagCompound = DLib.NBT.TagCompound()
@updateNWObject = true
@networkNWObject = true
@valid = @isOpen
@rawData = data
@dataTable = {k, default() for k, {:default} in pairs @@PONY_DATA}
@saveOnChange = true
if data
@SetupData(data, true)
elseif @exists and readIfExists
@ReadFromDisk(force, doBackup)
Reset: => @['Reset' .. getFunc](@) for k, {:getFunc} in pairs @@PONY_DATA
@ERR_MISSING_PARAMETER = 4
@ERR_MISSING_CONTENT = 5
GetSaveOnChange: => @saveOnChange
SaveOnChange: => @saveOnChange
SetSaveOnChange: (val = true) => @saveOnChange = val
GetValueFromNBT: (mapData, value) =>
if mapData.enum and type(value) == 'string'
mapData.fix(mapData.enumMappingBackward[value\upper()])
elseif mapData.type == 'COLOR'
if IsColor(value)
mapData.fix(Color(value))
else
mapData.fix(Color(value[1] + 128, value[2] + 128, value[3] + 128, value[4] + 128))
elseif mapData.type == 'BOOLEAN'
if type(value) == 'boolean'
mapData.fix(value)
else
mapData.fix(value == 1)
else
mapData.fix(value)
GetExtraBackupPath: => "#{@@DATA_DIR_BACKUP}#{@filename}_bak_#{os.date('%S_%M_%H-%d_%m_%Y', os.time())}.dat"
SetupData: (data = @NBTTagCompound, force = false, doBackup = false) =>
if luatype(data) == 'NBTCompound'
data = data\GetValue()
if doBackup or not force
makeBackup = false
for key, value2 in pairs(data)
key = key\lower()
map = @@PONY_DATA_MAPPING[key]
if map
mapData = @@PONY_DATA[map]
value = @GetValueFromNBT(mapData, value2)
if mapData.enum
if luatype(value) == 'string' and not mapData.enumMappingBackward[value\upper()] or luatype(value) == 'number' and not mapData.enumMapping[value]
return @@ERR_MISSING_CONTENT if not force
makeBackup = true
break
if doBackup and makeBackup and @exists
fRead = file.Read(@fpath, 'DATA')
file.Write(@GetExtraBackupPath(), fRead)
for key, value2 in pairs(data)
key = key\lower()
map = @@PONY_DATA_MAPPING[key]
continue unless map
mapData = @@PONY_DATA[map]
@dataTable[key] = @GetValueFromNBT(mapData, value2)
ValueChanges: (key, oldVal, newVal, saveNow = @exists and @saveOnChange) =>
if @nwObj and @updateNWObject
{:getFunc} = @@PONY_DATA[key]
@nwObj["Set#{getFunc}"](@nwObj, newVal, @networkNWObject)
@Save() if saveNow
SetFilename: (filename) =>
@filename = filename
@filenameFull = "#{filename}.dat"
@fpath = "#{@@DATA_DIR}#{filename}.dat"
@preview = "#{@@DATA_DIR}thumbnails/#{filename}.png"
@fpathFull = "data/#{@@DATA_DIR}#{filename}.dat"
@isOpen = @filename ~= nil
@exists = file.Exists(@fpath, 'DATA')
return @exists
SetNetworkData: (nwObj) => @nwObj = nwObj
SetPonyData: (nwObj) => @nwObj = nwObj
SetPonyDataController: (nwObj) => @nwObj = nwObj
SetPonyController: (nwObj) => @nwObj = nwObj
SetController: (nwObj) => @nwObj = nwObj
SetDataController: (nwObj) => @nwObj = nwObj
SetNetworkOnChange: (newVal = true) => @networkNWObject = newVal
SetUpdateOnChange: (newVal = true) => @updateNWObject = newVal
GetNetworkOnChange: => @networkNWObject
GetUpdateOnChange: => @updateNWObject
GetNetworkData: => @nwObj
GetPonyData: => @nwObj
GetPonyDataController: => @nwObj
GetPonyController: => @nwObj
GetController: => @nwObj
GetDataController: => @nwObj
IsValid: => @valid
Exists: => @exists
FileExists: => @exists
IsExists: => @exists
GetFileName: => @filename
GetFilename: => @filename
GetFileNameFull: => @filenameFull
GetFilenameFull: => @filenameFull
GetFilePath: => @fpath
GetFullFilePath: => @fpathFull
SerealizeValue: (valID = '') =>
map = @@PONY_DATA[valID]
return unless map
val = @dataTable[valID]
if map.enum
return DLib.NBT.TagString(map.enumMapping[val] or map.enumMapping[map.default()])
elseif map.serealize
return map.serealize(val)
else
switch map.type
when 'INT'
return DLib.NBT.TagInt(val)
when 'FLOAT'
return DLib.NBT.TagFloat(val)
when 'URL'
return DLib.NBT.TagString(val)
when 'BOOLEAN'
return DLib.NBT.TagByte(val and 1 or 0)
when 'COLOR'
return DLib.NBT.TagByteArray({val.r - 128, val.g - 128, val.b - 128, val.a - 128})
GetAsNetworked: => {getFunc, @dataTable[k] for k, {:getFunc} in pairs @@PONY_DATA}
@READ_SUCCESS = 0
@ERR_FILE_NOT_EXISTS = 1
@ERR_FILE_EMPTY = 2
@ERR_FILE_CORRUPT = 3
ReadFromDisk: (force = false, doBackup = true) =>
return @@ERR_FILE_NOT_EXISTS unless @exists
fRead = file.Read(@fpath, 'DATA')
return @@ERR_FILE_EMPTY if not fRead or fRead == ''
@NBTTagCompound\ReadFile(DLib.BytesBuffer(fRead))
return @SetupData(@NBTTagCompound, force, doBackup) or @@READ_SUCCESS
SaveAs: (path = @fpath) =>
@NBTTagCompound\AddTag(key, @SerealizeValue(key)) for key, val in pairs @dataTable
buf = DLib.BytesBuffer()
@NBTTagCompound\WriteFile(buf)
stream = file.Open(path, 'wb', 'DATA')
buf\ToFileStream(stream)
stream\Flush()
stream\Close()
return buf
SavePreview: (path = @preview) =>
buildingModel = ClientsideModel('models/ppm/ppm2_stage.mdl', RENDERGROUP_OTHER)
buildingModel\SetNoDraw(true)
buildingModel\SetModelScale(0.9)
model = ClientsideModel('models/ppm/player_default_base_new_nj.mdl')
with model
\SetNoDraw(true)
data = @CreateCustomController(model)
.__PPM2_PonyData = data
ctrl = data\GetRenderController()
if bg = data\GetBodygroupController()
bg\ApplyBodygroups()
with model\PPMBonesModifier()
\ResetBones()
hook.Call('PPM2.SetupBones', nil, model, data)
\Think(true)
\SetSequence(22)
\FrameAdvance(0)
timer.Simple 0.5, ->
renderTarget = GetRenderTarget('ppm2_save_preview_generate2', 1024, 1024, false)
renderTarget\Download()
render.PushRenderTarget(renderTarget)
--render.SuppressEngineLighting(true)
render.Clear(0, 0, 0, 255, true, true)
cam.Start3D(Vector(49.373046875, -35.021484375, 58.332901000977), Angle(0, 141, 0), 90, 0, 0, 1024, 1024)
buildingModel\DrawModel()
with model
data = .__PPM2_PonyData
ctrl = data\GetRenderController()
if textures = ctrl\GetTextureController()
textures\CompileTextures(true)
if bg = data\GetBodygroupController()
bg\ApplyBodygroups()
with model\PPMBonesModifier()
\ResetBones()
hook.Call('PPM2.SetupBones', nil, model, data)
\Think(true)
with ctrl
\DrawModels()
\HideModels(true)
\PreDraw(model, true)
\DrawModel()
ctrl\PostDraw(model, true)
cam.End3D()
data = render.Capture({
format: 'png'
x: 0
y: 0
w: 1024
h: 1024
alpha: false
})
model\Remove()
buildingModel\Remove()
file.Write(path, data)
--render.SuppressEngineLighting(false)
render.PopRenderTarget()
Save: (doBackup = true, preview = true) =>
file.Write(@GetExtraBackupPath(), file.Read(@fpath, 'DATA')) if doBackup and @exists
buf = @SaveAs(@fpath)
@SavePreview(@preview) if preview
@exists = true
return buf
PPM2.PonyDataInstance = PonyDataInstance
PPM2.MainDataInstance = nil
PPM2.GetMainData = ->
if not PPM2.MainDataInstance
PPM2.MainDataInstance = PonyDataInstance('_current', nil, true, true)
if not PPM2.MainDataInstance\FileExists()
PPM2.MainDataInstance\Save()
return PPM2.MainDataInstance
| 33.237245 | 151 | 0.681787 |
ac6c46383dc15e7f910edfc590bea382235880d2 | 10,819 |
util = require "moonscript.util"
dump = require "moonscript.dump"
transform = require "moonscript.transform"
import NameProxy, LocalName from require "moonscript.transform.names"
import Set from require "moonscript.data"
import ntype, has_value from require "moonscript.types"
statement_compilers = require "moonscript.compile.statement"
value_compilers = require "moonscript.compile.value"
import concat, insert from table
import pos_to_line, get_closest_line, trim, unpack from util
mtype = util.moon.type
indent_char = " "
local Line, DelayedLine, Lines, Block, RootBlock
-- a buffer for building up lines
class Lines
new: =>
@posmap = {}
mark_pos: (pos, line=#@) =>
@posmap[line] = pos unless @posmap[line]
-- append a line or lines to the buffer
add: (item) =>
switch mtype item
when Line
item\render self
when Block
item\render self
else -- also captures DelayedLine
@[#@ + 1] = item
@
flatten_posmap: (line_no=0, out={}) =>
posmap = @posmap
for i, l in ipairs @
switch mtype l
when "string", DelayedLine
line_no += 1
out[line_no] = posmap[i]
line_no += 1 for _ in l\gmatch"\n"
out[line_no] = posmap[i]
when Lines
_, line_no = l\flatten_posmap line_no, out
else
error "Unknown item in Lines: #{l}"
out, line_no
flatten: (indent=nil, buffer={}) =>
for i = 1, #@
l = @[i]
t = mtype l
if t == DelayedLine
l = l\render!
t = "string"
switch t
when "string"
insert buffer, indent if indent
insert buffer, l
-- insert breaks between ambiguous statements
if "string" == type @[i + 1]
lc = l\sub(-1)
if (lc == ")" or lc == "]") and @[i + 1]\sub(1,1) == "("
insert buffer, ";"
insert buffer, "\n"
when Lines
l\flatten indent and indent .. indent_char or indent_char, buffer
else
error "Unknown item in Lines: #{l}"
buffer
__tostring: =>
-- strip non-array elements
strip = (t) ->
if "table" == type t
[strip v for v in *t]
else
t
"Lines<#{util.dump(strip @)\sub 1, -2}>"
-- Buffer for building up a line
-- A plain old table holding either strings or Block objects.
-- Adding a line to a line will cause that line to be merged in.
class Line
pos: nil
append_list: (items, delim) =>
for i = 1,#items
@append items[i]
if i < #items then insert self, delim
nil
append: (first, ...) =>
if Line == mtype first
-- print "appending line to line", first.pos, first
@pos = first.pos unless @pos -- bubble pos if there isn't one
@append value for value in *first
else
insert self, first
if ...
@append ...
-- todo: try to remove concats from here
render: (buffer) =>
current = {}
add_current = ->
buffer\add concat current
buffer\mark_pos @pos
for chunk in *@
switch mtype chunk
when Block
for block_chunk in *chunk\render Lines!
if "string" == type block_chunk
insert current, block_chunk
else
add_current!
buffer\add block_chunk
current = {}
else
insert current, chunk
if current[1]
add_current!
buffer
__tostring: =>
"Line<#{util.dump(@)\sub 1, -2}>"
class DelayedLine
new: (fn) =>
@prepare = fn
prepare: ->
render: =>
@prepare!
concat @
class Block
header: "do"
footer: "end"
export_all: false
export_proper: false
value_compilers: value_compilers
__tostring: =>
h = if "string" == type @header
@header
else
unpack @header\render {}
"Block<#{h}> <- " .. tostring @parent
new: (@parent, @header, @footer) =>
@_lines = Lines!
@_names = {}
@_state = {}
@_listeners = {}
with transform
@transform = {
value: .Value\bind self
statement: .Statement\bind self
}
if @parent
@root = @parent.root
@indent = @parent.indent + 1
setmetatable @_state, { __index: @parent._state }
setmetatable @_listeners, { __index: @parent._listeners }
else
@indent = 0
set: (name, value) =>
@_state[name] = value
get: (name) =>
@_state[name]
get_current: (name) =>
rawget @_state, name
listen: (name, fn) =>
@_listeners[name] = fn
unlisten: (name) =>
@_listeners[name] = nil
send: (name, ...) =>
if fn = @_listeners[name]
fn self, ...
declare: (names) =>
undeclared = for name in *names
is_local = false
real_name = switch mtype name
when LocalName
is_local = true
name\get_name self
when NameProxy then name\get_name self
when "table"
name[1] == "ref" and name[2]
when "string"
-- TODO: don't use string literal as ref
name
continue unless is_local or real_name and not @has_name real_name, true
-- put exported names so they can be assigned to in deeper scope
@put_name real_name
continue if @name_exported real_name
real_name
undeclared
whitelist_names: (names) =>
@_name_whitelist = Set names
name_exported: (name) =>
return true if @export_all
return true if @export_proper and name\match"^%u"
put_name: (name, ...) =>
value = ...
value = true if select("#", ...) == 0
name = name\get_name self if NameProxy == mtype name
@_names[name] = value
-- Check if a name is defined in the current or any enclosing scope
-- skip_exports: ignore names that have been exported using `export`
has_name: (name, skip_exports) =>
return true if not skip_exports and @name_exported name
yes = @_names[name]
if yes == nil and @parent
if not @_name_whitelist or @_name_whitelist[name]
@parent\has_name name, true
else
yes
is_local: (node) =>
t = mtype node
return @has_name(node, false) if t == "string"
return true if t == NameProxy or t == LocalName
if t == "table"
if node[1] == "ref" or (node[1] == "chain" and #node == 2)
return @is_local node[2]
false
free_name: (prefix, dont_put) =>
prefix = prefix or "moon"
searching = true
name, i = nil, 0
while searching
name = concat {"", prefix, i}, "_"
i = i + 1
searching = @has_name name, true
@put_name name if not dont_put
name
init_free_var: (prefix, value) =>
name = @free_name prefix, true
@stm {"assign", {name}, {value}}
name
-- add a line object
add: (item) =>
@_lines\add item
item
-- todo: pass in buffer as argument
render: (buffer) =>
buffer\add @header
buffer\mark_pos @pos
if @next
buffer\add @_lines
@next\render buffer
else
-- join an empty block into a single line
if #@_lines == 0 and "string" == type buffer[#buffer]
buffer[#buffer] ..= " " .. (unpack Lines!\add @footer)
else
buffer\add @_lines
buffer\add @footer
buffer\mark_pos @pos
buffer
block: (header, footer) =>
Block self, header, footer
line: (...) =>
with Line!
\append ...
is_stm: (node) =>
statement_compilers[ntype node] != nil
is_value: (node) =>
t = ntype node
@value_compilers[t] != nil or t == "value"
-- compile name for assign
name: (node, ...) =>
if type(node) == "string"
node
else
@value node, ...
value: (node, ...) =>
node = @transform.value node
action = if type(node) != "table"
"raw_value"
else
node[1]
fn = @value_compilers[action]
unless fn
error {
"compile-error"
"Failed to find value compiler for: " .. dump.value node
node[-1]
}
out = fn self, node, ...
-- store the pos, creating a line if necessary
if type(node) == "table" and node[-1]
if type(out) == "string"
out = with Line! do \append out
out.pos = node[-1]
out
values: (values, delim) =>
delim = delim or ', '
with Line!
\append_list [@value v for v in *values], delim
stm: (node, ...) =>
return if not node -- skip blank statements
node = @transform.statement node
result = if fn = statement_compilers[ntype(node)]
fn self, node, ...
else
-- coerce value into statement
if has_value node
@stm {"assign", {"_"}, {node}}
else
@value node
if result
if type(node) == "table" and type(result) == "table" and node[-1]
result.pos = node[-1]
@add result
nil
stms: (stms, ret) =>
error "deprecated stms call, use transformer" if ret
{:current_stms, :current_stm_i} = @
@current_stms = stms
for i=1,#stms
@current_stm_i = i
@stm stms[i]
@current_stms = current_stms
@current_stm_i = current_stm_i
nil
splice: (fn) =>
lines = {"lines", @_lines}
@_lines = Lines!
@stms fn lines
class RootBlock extends Block
new: (@options) =>
@root = self
super!
__tostring: => "RootBlock<>"
root_stms: (stms) =>
unless @options.implicitly_return_root == false
stms = transform.Statement.transformers.root_stms self, stms
@stms stms
render: =>
-- print @_lines
buffer = @_lines\flatten!
buffer[#buffer] = nil if buffer[#buffer] == "\n"
table.concat buffer
format_error = (msg, pos, file_str) ->
line_message = if pos
line = pos_to_line file_str, pos
line_str, line = get_closest_line file_str, line
line_str = line_str or ""
(" [%d] >> %s")\format line, trim line_str
concat {
"Compile error: "..msg
line_message
}, "\n"
value = (value) ->
out = nil
with RootBlock!
\add \value value
out = \render!
out
tree = (tree, options={}) ->
assert tree, "missing tree"
scope = (options.scope or RootBlock) options
runner = coroutine.create ->
scope\root_stms tree
success, err = coroutine.resume runner
unless success
error_msg, error_pos = if type(err) == "table"
switch err[1]
when "user-error", "compile-error"
unpack err, 2
else
-- unknown error, bubble it
error "Unknown error thrown", util.dump error_msg
else
concat {err, debug.traceback runner}, "\n"
return nil, error_msg, error_pos or scope.last_pos
lua_code = scope\render!
posmap = scope._lines\flatten_posmap!
lua_code, posmap
-- mmmm
with data = require "moonscript.data"
for name, cls in pairs {:Line, :Lines, :DelayedLine}
data[name] = cls
{ :tree, :value, :format_error, :Block, :RootBlock }
| 22.776842 | 77 | 0.583326 |
dc3c9f303d193c7585cad31ba5ca47b6e745de61 | 2,086 | lfs = require "syscall.lfs"
remove = table.remove
is_dir = (dir) ->
return false unless type(dir) == "string"
attr = lfs.attributes dir
return false unless attr and attr.mode == "directory"
true
is_file = (path) ->
return false if is_dir path
f = io.open path, "r"
if f
f\close!
true
else
false
is_present = (path) ->
is_dir(path) or is_file(path)
dirtree = (dir, recursive) ->
assert dir and dir != "", "directory parameter is missing or empty"
assert is_dir(dir), "directory #{dir} is not a directory"
if dir\sub(-1) == "/"
dir = dir\sub 1,-2
yieldtree = (dir, recursive) ->
for entry in lfs.dir dir
if entry != "." and entry != ".."
entry = "#{dir}/#{entry}"
attr = lfs.attributes entry
coroutine.yield entry, attr
if recursive and attr.mode == "directory"
yieldtree entry, recursive
coroutine.wrap -> yieldtree dir, recursive
mkdir_p = (path) ->
path_elements = path\split "/"
local dir
if path_elements[1] == ""
remove path_elements, 1
d = remove path_elements, 1
dir = "/#{d}"
else
dir = remove path_elements, 1
lfs.mkdir dir
for p in *path_elements
dir = "#{dir}/#{p}"
lfs.mkdir dir
rm_rf = (path, attr) ->
attr = attr or lfs.attributes path
if attr and attr.mode == "directory"
for entry, attr in dirtree path, false
rm_rf entry, attr
os.remove path
else if attr
os.remove path
dir_table = (dir) ->
tbl = {}
for entry, attr in dirtree dir
path = entry\split('/')
name = path[#path]
if attr.mode == "directory"
tbl[name] = dir_table entry
else
tbl[name] = true
tbl
dir_diff = (a, b) ->
d = {}
a or= {}
b or= {}
for k,v in pairs(a)
if type(v) == "table"
d[k] = dir_diff v, b[k]
else
unless b[k]
d[k] = "DELETED"
for k,v in pairs(b)
if type(v) == "table"
d[k] = dir_diff a[k], v
else
unless a[k]
d[k] = "CREATED"
d
:dirtree, :rm_rf, :mkdir_p, :is_dir, :is_file, :is_present, :dir_table, :dir_diff
| 22.430108 | 81 | 0.582934 |
77cdd6c3ff8b87cf7280fdb12ad2bb7915c84f97 | 994 | class Layer extends Group
new: (items) ->
@_project = paper\project
-- Push it onto project.layers and set index:
@_index = @_project\layers\push(@) - 1
super\(arg)
@activate()
_remove: _remove = (notify) =>
return _remove.base.call(this, notify) if @_parent
if @_index?
@_project.activeLayer = @getNextSibling() or @getPreviousSibling() if @_project.activeLayer is this
Base.splice @_project.layers, null, @_index, 1
# Tell project we need a redraw. This is similar to _changed()
# mechanism.
@_project._needsRedraw = true
return true
false
getNextSibling:
getNextSibling = ->
(if @_parent then super\getNextSibling() else @_project.layers[@_index + 1] or nil)
getPreviousSibling:
getPreviousSibling = ->
(if @_parent then super\getPreviousSibling() else @_project.layers[@_index - 1] or nil)
isInserted:
isInserted = ->
(if @_parent then super\isInserted else @_index?)
| 30.121212 | 106 | 0.656942 |
3468d1233f62334c523c35680feaf12e0e4e050d | 114 | tasks:
f: => print @name
dof: =>
tasks.a!
tasks.b!
tasks.c!
tasks.d!
tasks.e!
tasks.f! | 12.666667 | 19 | 0.473684 |
2f07939d04f236c799c39a2f35c7500478694e66 | 1,859 |
describe "comprehension", ->
it "should double every number", ->
input = {1,2,3,4,5,6}
output_1 = [i * 2 for _, i in pairs input ]
output_2 = [i * 2 for i in *input ]
assert.same output_1, {2,4,6,8,10,12}
it "should create a slice", ->
input = {1,2,3,4,5,6}
slice_1 = [i for i in *input[1,3]]
slice_2 = [i for i in *input[,3]]
slice_3 = [i for i in *input[3,]]
slice_4 = [i for i in *input[,]]
slice_5 = [i for i in *input[,,2]]
slice_6 = [i for i in *input[2,,2]]
assert.same slice_1, {1,2,3}
assert.same slice_1, slice_2
assert.same slice_3, {3,4,5,6}
assert.same slice_4, input
assert.same slice_5, {1,3,5}
assert.same slice_6, {2,4,6}
it "should be able to assign to self", ->
input = {1,2,3,4}
output = input
output = [i * 2 for i in *output]
assert.same input, {1,2,3,4}
assert.same output, {2,4,6,8}
output = input
output = [i * 2 for _,i in ipairs input]
assert.same input, {1,2,3,4}
assert.same output, {2,4,6,8}
describe "table comprehension", ->
it "should copy table", ->
input = { 1,2,3, hello: "world", thing: true }
output = {k,v for k,v in pairs input }
assert.is_true input != output
assert.same input, output
it "should support when", ->
input = {
color: "red"
name: "fast"
width: 123
}
output = { k,v for k,v in pairs input when k != "color" }
assert.same output, { name: "fast", width: 123 }
it "should do unpack", ->
input = {4,9,16,25}
output = {i, math.sqrt i for i in *input}
assert.same output, { [4]: 2, [9]: 3, [16]: 4, [25]: 5 }
it "should use multiple return values", ->
input = { {"hello", "world"}, {"foo", "bar"} }
output = { unpack tuple for tuple in *input }
assert.same output, { foo: "bar", hello: "world" }
| 24.460526 | 61 | 0.561592 |
ea7fe40f39e6f269194787cf2cbabb66856cd4bf | 1,123 |
import P, R, S, C from require "lpeg"
cont = R("\128\191")
multibyte_character = R("\194\223") * cont +
R("\224\239") * cont * cont +
R("\240\244") * cont * cont * cont
-- This is generated by web_sanitize and copied here for convenience, includes
-- all codepoints classified as whitespace compiled into optimal pattern
whitespace = S("\13\32\10\11\12\9") +
P("\239\187\191") +
P("\194") * S("\133\160") +
P("\225") * (P("\154\128") + P("\160\142")) +
P("\226") * (P("\128") * S("\131\135\139\128\132\136\140\175\129\133\168\141\130\134\169\138\137") + P("\129") * S("\159\160")) +
P("\227\128\128")
-- direction marks by themselves are unprintable, we must see if something follows
direction_mark = P("\226\128") * S("\142\143\170\171\172\173\174") + P("\216\156")
unused_direction_mark = direction_mark * #((whitespace + direction_mark)^-1 * -1)
whitespace += unused_direction_mark
printable_character = S("\r\n\t") + R("\032\126") + multibyte_character
trim = whitespace^0 * C (whitespace^0 * (1-whitespace)^1)^0
{:multibyte_character, :printable_character, :whitespace, :direction_mark, :trim}
| 37.433333 | 131 | 0.650935 |
2ece6127a5eb996be3e5f75f2f6d5556cd314fe3 | 882 | {
aqls: {
settings: '
LET g_settings = (FOR doc IN settings LIMIT 1 RETURN doc)
LET g_redirections = (FOR doc IN redirections RETURN doc)
LET g_trads = (FOR doc IN trads RETURN ZIP([doc.key], [doc.value]))
LET g_components = (
FOR doc IN components RETURN ZIP([doc.slug], [{ _key: doc._key, _rev: doc._rev }])
)
LET g_aqls = MERGE(FOR doc IN aqls RETURN ZIP([doc.slug], [doc.aql]))
LET g_helpers = (
FOR h IN helpers
FOR p IN partials
FILTER h.partial_key == p._key
FOR a IN aqls
FILTER h.aql_key == a._key
RETURN ZIP([h.shortcut], [{ partial: p.slug, aql: a.slug }])
)
RETURN { components: g_components, settings: g_settings,
redirections: g_redirections, aqls: g_aqls,
trads: MERGE(g_trads), helpers: MERGE(g_helpers) }'
}
} | 38.347826 | 90 | 0.585034 |
c41bffe4e6c6b342e9bccd7fc28da89a0261b45b | 5,410 | assert = require "luassert"
-- This class mocks select methods from the TTS "Object" API, represented by the
-- global "self" in an object script. It contains *only* the Object-bound API
-- functions; the general API functions are exported separately (since they can
-- be called bare without having access to the Object context.) To prevent
-- cross-contamination between unit tests, only one instance of ApiContext can
-- be active at a time.
export class ApiContext
new: =>
@@instance = @
@@objects = { }
@@players = { {}, {}, {}, {}, {}, {}, {}, {}, {}, {} }
@buttons = { }
@scale = 1
@position = { 0, 0, 0 }
@rotation = { 0, 0, 0 }
@coroutines = { }
clearButtons: ->
if ApiContext.instance != nil
ApiContext.instance.buttons = { }
return true
createButton: (params) ->
assert params != nil,
"Mock API: Tried to call API.createButton with bad argument: params is nil!"
assert type(params) == "table",
"Mock API: Tried to call API.createButton with bad argument: params is not a table!"
-- The actual in-game API will throw an error if the click_function is nil
-- or an empty string, so we have to make sure that it's specified.
assert params.click_function != nil,
"Mock API: Tried to create button but no click_function was specified."
assert type(params.click_function) == "string",
"Mock API: Tried to create button but the click_function was not a string."
assert params.click_function != "",
"Mock API: Tried to create button but the click_function was an empty string."
params.index = #ApiContext.instance.buttons
ApiContext.instance.buttons[params.index + 1] = params
return true
editButton: (params) ->
assert params != nil,
"Mock API: Tried to call API.editButton with bad argument: params is nil!"
assert type(params) == "table",
"Mock API: Tried to call API.editButton with bad argument: params is not a table!"
assert params.index != nil,
"Mock API: Tried to call API.editButton with bad argument: params.index is nil!"
assert type(params.index) == "number",
"Mock API: Tried to call API.editButton with bad argument: params.index not a number!"
assert ApiContext.instance.buttons[params.index + 1] != nil,
"Mock API: Tried to call API.editButton with bad argument: there is no button with index " .. params.index .. "!"
ApiContext.instance.buttons[params.index + 1] = params
return true
getButtons: ->
newTable = { }
for key, value in pairs(ApiContext.instance.buttons)
newTable[key] = value
return newTable
removeButton: (index) ->
assert index != nil,
"Mock API: Tried to call API.removeButton with bad argument: index is nil!"
assert type(index) == "number",
"Mock API: Tried to call API.removeButton with bad argument: index not a number!"
assert ApiContext.instance.buttons[index + 1] != nil,
"Mock API: Tried to call API.removeButton with bad argument: button does not exist!"
table.remove ApiContext.instance.buttons, index + 1
return true
getScale: =>
scale = ApiContext.instance.scale
{ x: scale, y: scale, z: scale }
setPosition: (position) ->
assert position != nil,
"Tried to call API.setPosition with bad argument: position is nil!"
assert type(position) == "table",
"Tried to call API.setPosition with bad argument: position is not a table!"
assert #position <= 3,
"Tried to call API.setPosition with bad argument: too many values!"
assert type(position[1]) == "number",
"Tried to call API.setPosition with bad x value!"
assert type(position[2]) == "number",
"Tried to call API.setPosition with bad y value!"
assert type(position[3]) == "number",
"Tried to call API.setPosition with bad z value!"
ApiContext.instance.position = position
return true
setRotation: (rotation) ->
assert rotation != nil,
"Tried to call API.setRotation with bad argument: rotation is nil!"
assert type(rotation) == "table",
"Tried to call API.setRotation with bad argument: rotation is not a table!"
assert #rotation <= 3,
"Tried to call API.setRotation with bad argument: too many values!"
assert type(rotation[1]) == "number",
"Tried to call API.setRotation with bad x value!"
assert type(rotation[2]) == "number",
"Tried to call API.setRotation with bad y value!"
assert type(rotation[3]) == "number",
"Tried to call API.setRotation with bad z value!"
ApiContext.instance.rotation = rotation
return true
destruct: ->
ApiContext.instance = nil
return true
-- The following API calls are not part of the context object, because they are
-- not part of the Object API, but rather the global API. (i.e. they are not
-- called using "self")
export JSON = {
}
export Player = {
}
export Timer = {
}
export getObjectFromGUID = (guid) ->
for _, v in ipairs ApiContext.objects
if v == guid
return { }
else if (type v) == "table" and v.guid == guid
return v
nil
export getAllObjects = ->
return ApiContext.objects
export getSeatedPlayers = ->
return ApiContext.players
export startLuaCoroutine = (context, name) ->
table.insert ApiContext.instance.coroutines, { :context, :name }
-- Set up an initial instance automatically to avoid errors
ApiContext!
| 37.054795 | 119 | 0.671534 |
0c8525796e0c15a507f43e7d0617b286560b9d8b | 1,468 | import insert, sort from table
local *
Module = with {}
.sorted_pairs = (tbl) ->
-- Iterator for tables that sorts keys, storing the sorted key table within
-- the scope of the closure
sorted_keys = .sorted_key_list tbl
return sorted_iterator tbl, sorted_keys
.sorted_iterator = (tbl, sorted_keys) ->
-- errors = {}
-- if (type tbl) != "table"
-- errors[#errors + 1] = "Table argument has type #{type tbl}"
-- if (type sorted_keys) != "table"
-- errors[#errors + 1] = "Sorted key list argument has type #{type sorted_keys}"
-- if #errors > 0
-- error errors
i = 1
return () ->
if i <= #sorted_keys
key = sorted_keys[i]
val = tbl[key]
i += 1
return key, val
else
return nil
.sorted_key_list = (tbl) ->
list = [key for key, val in pairs tbl]
sort list
return list
.clone = (tbl) ->
return {key, val for key, val in pairs tbl}
.keys = (tbl) ->
i = 0
key_list = {}
for key, _val in pairs tbl
i += 1
key_list[i] = key
return key_list
.size = (tbl) ->
i = 0
for _index, _val in pairs tbl
i += 1
return i
.max = (tbl, comp=(a,b) -> a < b) ->
max = nil
max_key = nil
for key, val in pairs tbl
unless max
max = val
max_key = key
else
if comp max, val
max = val
max_key = key
return max, max_key
return Module
| 21.910448 | 86 | 0.544959 |
e90fdc53898d7890f74aa4a0eb335bf920505499 | 6,820 | [=[
Class: Command
Used to create a new command. Commands are always tied to the console, and optionally to chat as well.
]=]
class ulx.Command
@CmdMap: {}
lang = ulx.Lang -- shortcut
[=[
Function: ShortcutFn
Only available statically, meant for internal use only.
]=]
@ShortcutFn: (name, typ, default using nil) ->
@__base[name] = (val=default using nil) =>
ulx.UtilX.CheckArg "#{@@__name}.#{name}", 1, typ, val
@["_" .. name] = val
@
splitCommandNameAndArgv = (initialCommandStr, argv using nil) ->
commandStr = initialCommandStr
while #argv > 0
newCommandStr = commandStr .. " " .. argv[1]
if not @CmdMap[newCommandStr]
break
commandStr = newCommandStr
table.remove argv, 1
return commandStr, argv
[=[
Function: ConsoleRouter
This static callback function is primarily meant to act as the buffer between the Source console and ULX. *You probably should not call this directly*.
This function is called by the engine, executes the appropriate callback, and prints any errors back to the caller.
Parameters:
ply - The *player* calling the command.
commandStr - A *string* containing the first word of whatever was specified on console.
argv - A *list of strings* as parsed by the Source engine but is *ignored* in this function, since Source parses these oddly.
args - A *string* of everything but the first word of whatever was specified on console. This is used to build our own argv.
]=]
@ConsoleRouter: (ply, commandFirstWord, argv, args using nil) ->
-- Default argv doesn't parse some things correctly, so just do it ourselves
-- Examples of things that default argv chokes on...
-- MyCmd hi:there
-- MyCmd we don't like single quotes
-- MyCmd http://google.com -- though this information is LOST, so we can't fix it
argv = ulx.UtilX.SplitArgs args
commandName, argv = splitCommandNameAndArgv commandFirstWord, argv
success, argNum, msg = @.ExecutionRouter ply, commandName, argv
if not success
fullMsg = lang.GetMutatedPhrase "COMMAND_ARG_MESSAGE",
COMMANDNAME: commandName
ARGNUM: argNum
MESSAGE: msg
ulx.TSayRed ply, fullMsg
return false, fullMsg
return true
[=[
Function: ExecutionRouter
TODO
]=]
@ExecutionRouter: (ply, commandName, argv using nil) ->
cmd = @CmdMap[commandName]
if not cmd
--log.warn "ExecutionRouter received unknown command" -- TODO
return false, lang.GetMutatedPhrase "COMMAND_UNKNOWN",
COMMANDNAME: commandName
cmd\Execute ply, argv
[=[
Variables: Command Variables
All these variables are optional, with sensible defaults. *Do not set these directly*. Instead, call the setter
function of the same name without the underscore. E.G., call `Name("Billy Bob")`.
_Name - A *string* of the name of the command.
_Callback - A *function* to callback when the command is called.
_Hint - A one-line hint *string* for the command.
_Access - A *string* or *table* of the groups that get access to the command by default.
_Category - A *string* category for the command. See <Plugin.Category>.
This is normally set by the plugin, but you can override it here.
_ChatAlias - A *string* or *table* of the chat command alias(es) for the command.
_Defaults to the command parameter passed to <new()>, prefixed with the default chat prefix_.
_ConsoleAlias - A *string* or *table* of the console command alias(es) for the command.
_Defaults to the command parameter passed to <new()>_.
_Args - A *list of <Arguments>* for the command.
_Restrictions - A *list of <Restrictions>* for the command.
_Plugin - TODO
]=]
_Name: nil
_Callback: nil
_Hint: ""
_Access: {}
_Category: "unknown"
_ChatAlias: {}
_ConsoleAlias: {}
_Args: {}
_Restrictions: {}
_Plugin: {}
@.ShortcutFn "Name", "string"
@.ShortcutFn "Callback", "function"
@.ShortcutFn "Hint", "string"
@.ShortcutFn "Access", {"string", "table"}
@.ShortcutFn "Category", "string"
@.ShortcutFn "ChatAlias", {"string", "table"}
[email protected] "ConsoleAlias", {"string", "table"}
@.ShortcutFn "Args", "table"
@.ShortcutFn "Restrictions", "table"
@.ShortcutFn "Plugin", {"nil", "Plugin"}
UnregisterCommands: (using nil) =>
for alias in *@_ConsoleAlias
@@CmdMap[alias] = nil
concommand.Remove alias
ConsoleAlias: (aliases using nil) =>
ulx.UtilX.CheckArg "#{@@__name}.ConsoleAlias", 1, {"string", "table"}, aliases, 2
@UnregisterCommands!
aliases = {aliases} if type(aliases) == "string"
for alias in *aliases
@@CmdMap[alias] = self
concommand.Add alias, @@ConsoleRouter, nil, @_Hint
@_ConsoleAlias = aliases
[=[
Function: new
Creates a new command.
Parameters:
name - A *string* command name (E.G., "slap").
callback - A *function* to call when the command is invoked.
The callback gets called with the arguments specified in the <Args> variable.
plugin - TODO
]=]
new: (name, callback, plugin using nil) =>
ulx.UtilX.CheckArgs "Command", {{"string", name},
{"function", callback},
{{"nil", ulx.Plugin}, plugin}}, 3
@Name name
@Callback callback
@ChatAlias "!" .. name
@ConsoleAlias name
@Plugin plugin
[=[
Function: Execute
TODO
]=]
Execute: (ply, argvRaw using nil) =>
-- TODO, check access
argvParsed = {}
cmdArgs = @_Args
for i=1, #cmdArgs
cmdArg = cmdArgs[i]
argRaw = argvRaw[i]
argParsed = argRaw
if type(argRaw) == "string"
parsed, returned = cmdArg\Parse argRaw
if not parsed
return false, i, returned
argParsed = returned
permissible, msg = cmdArg\IsPermissible argParsed
if not permissible
return false, i, msg
argvParsed[i]=argParsed
@._Callback ply, unpack(argvParsed)
return true
[=[
with plugin\Command( "command", ulx.command ) -- Chat alias is automatically assumed, can override with .ChatAlias = ...
\Hint "Hint text"
\Access "admin"
--\Category "fun" -- Only need to specify if differing from plugin category
--\ChatAlias "command" or {"!cmd", "!command"} for multiple - if unspecified, "!command" from first line is assumed
--\ConsoleAlias "cmd" or {"cmd1", "cmd2"} for multiple
\Args{
ArgPlayer! -- help text for arguments automatically contains "player to <command name>"
ArgTime!\Optional!\min 0 -- help text "time (in minutes) to <command name>"
ArgString!\Optional!\Greedy!\RestrictToCompletes!\Completes tbl
}
\Restrictions{
RestrictToOnceEvery "1 hour"
RestrictToTime "1500-1700" --???
RestrictToAbsenceOf "%superadmin"
RestrictToPresenceOf "#user"
RestrictToCustom (ply, ...) -> if not ply\IsAlive() then return false, "you must be alive to run this command" else return true
}
]=]
| 33.431373 | 152 | 0.678739 |
b4fde1e32e4d85c548380f7bfba9205df393f888 | 37,875 | -- Copyright 2012-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
Gdk = require 'ljglibs.gdk'
Gtk = require 'ljglibs.gtk'
aullar = require 'aullar'
gobject_signal = require 'ljglibs.gobject.signal'
{:signal, :bindings, :config, :command, :clipboard, :sys, :Chunk} = howl
aullar_config = aullar.config
{:PropertyObject} = howl.util.moon
{highlight: highlights, :Searcher, :CompletionPopup} = howl.ui
{:auto_pair} = howl.editing
{
:IndicatorBar,
:Cursor,
:Selection,
:ContentBox
} = howl.ui
{:max, :min} = math
append = table.insert
_editors = setmetatable {}, __mode: 'v'
editors = -> [e for _, e in pairs _editors when e != nil]
indicators = {}
indicator_placements =
top_left: true
top_right: true
bottom_left: true
bottom_right: true
editor_config_vars = {
indentation_guides: 'indentation_guides'
line_wrapping: 'line_wrapping'
line_wrapping_navigation: 'line_wrapping_navigation'
horizontal_scrollbar: 'horizontal_scrollbar'
vertical_scrollbar: 'vertical_scrollbar'
cursor_line_highlighted: 'cursor_line_highlighted'
line_numbers: 'line_numbers'
line_padding: 'line_padding'
edge_column: 'edge_column'
}
aullar_config_vars = {
cursor_blink_interval: 'cursor_blink_interval'
scroll_speed_x: 'scroll_speed_x'
scroll_speed_y: 'scroll_speed_y'
indent: 'view_indent'
tab_width: 'view_tab_size'
font_name: 'view_font_name'
font_size: 'view_font_size'
line_wrapping_symbol: 'view_line_wrap_symbol'
}
apply_global_variable = (name, value) ->
aullar_config[name] = value
apply_variable = (name) ->
for e in *editors!
e\refresh_variable name
signal.connect 'buffer-saved', (args) ->
for e in *editors!
e\remove_popup! if e.buffer == args.buffer
signal.connect 'buffer-title-set', (args) ->
buffer = args.buffer
for e in *editors!
if buffer == e.buffer
e.indicator.title.label = buffer.title
signal.connect 'buffer-mode-set', (args) ->
buffer = args.buffer
for e in *editors!
if buffer == e.buffer
e\_set_config_settings!
class Editor extends PropertyObject
register_indicator: (id, placement = 'bottom_right', factory) ->
if not indicator_placements[placement]
error('Illegal placement "' .. placement .. '"', 2)
indicators[id] = :id, :placement, :factory
unregister_indicator: (id) ->
e\_remove_indicator id for e in *editors!
indicators[id] = nil
new: (buffer) =>
error('Missing argument #1 (buffer)', 2) if not buffer
super!
@indicator = setmetatable {}, __index: self\_create_indicator
@view = aullar.View!
listener =
on_key_press: self\_on_key_press
on_button_press: self\_on_button_press
on_button_release: self\_on_button_release
on_motion_event: self\_on_motion_event
on_focus_in: self\_on_focus
on_focus_out: self\_on_focus_lost
on_insert_at_cursor: self\_on_insert_at_cursor
on_delete_back: self\_on_delete_back
on_preedit_start: -> log.info "In pre-edit mode.."
on_preedit_change: (_, args) ->
log.info "Pre-edit: #{args.str} (Enter to submit, escape to cancel)"
on_preedit_end: -> log.info "Pre-edit mode finished"
on_scroll: self\_on_scroll
@view.listener = listener
@view.cursor.listener = {
on_pos_changed: self\_on_pos_changed
}
@selection = Selection @view
@cursor = Cursor self, @selection, drop_crumbs: true
@searcher = Searcher self
@completion_popup = CompletionPopup self
@header = IndicatorBar 'header'
content_box = ContentBox 'editor', @view\to_gobject!, {
header: @header\to_gobject!,
}
@bin = content_box\to_gobject!
@bin.can_focus = true
@_handlers = {}
append @_handlers, @bin\on_destroy self\_on_destroy
append @_handlers, @bin\on_focus_in_event -> @view\grab_focus!
@buffer = buffer
@_is_previewing = false
@has_focus = false
append _editors, self
to_gobject: => @bin
@property buffer:
get: => @_buf
set: (buffer) =>
signal.emit 'before-buffer-switch', editor: self, current_buffer: @_buf, new_buffer: buffer
prev_buffer = @_buf
@_show_buffer buffer
signal.emit 'after-buffer-switch', editor: self, current_buffer: buffer, old_buffer: prev_buffer
@property current_line: get: => @buffer.lines[@cursor.line]
@property current_context: get: => @buffer\context_at @cursor.pos
@property indentation_guides:
get: =>
show = @view.config.view_show_indentation_guides
show and 'on' or 'none'
set: (value) =>
val = switch value
when 'none' then false
when 'on' then true
else
error "Unknown value for indentation_guides: #{value}"
@view.config.view_show_indentation_guides = val
@property edge_column:
get: => @view.config.view_edge_column
set: (v) => @view.config.view_edge_column = v
@property last_edit_pos:
get: =>
pos = @view.last_edit_pos
return nil unless pos
@buffer\char_offset pos
@property line_padding:
get: => @view.config.view_line_padding
set: (v) => @view.config.view_line_padding = v
@property line_wrapping:
get: => @view.config.view_line_wrap
set: (value) =>
unless value\umatch r'^(?:none|word|character)$'
error "Unknown value for line_wrapping: #{value}", 2
@view.config.view_line_wrap = value
@property line_wrapping_navigation:
get: => @view.config.view_line_wrap_navigation
set: (value) =>
unless value\umatch r'^(?:real|visual)$'
error "Unknown value for line_wrapping_navigation: #{value}", 2
@view.config.view_line_wrap_navigation = value
@property cursor_line_highlighted:
get: => @view.config.view_highlight_current_line
set: (flag) =>
@view.config.view_highlight_current_line = flag
@property horizontal_scrollbar:
get: => @view.config.view_show_h_scrollbar
set: (flag) => @view.config.view_show_h_scrollbar = flag
@property vertical_scrollbar:
get: => @view.config.view_show_v_scrollbar
set: (flag) =>
@view.config.view_show_v_scrollbar = flag
-- @property overtype:
-- get: => @sci\get_overtype!
-- set: (flag) => @sci\set_overtype flag
@property lines_on_screen:
get: => @view.lines_showing
@property line_at_top:
get: => @view.first_visible_line
set: (nr) => @view.first_visible_line = nr
@property line_at_bottom:
get: => @view.last_visible_line
set: (nr) => @view.last_visible_line = nr
@property line_at_center:
get: => @view.middle_visible_line
set: (nr) => @view.middle_visible_line = nr
@property line_numbers:
get: => @view.config.view_show_line_numbers
set: (flag) => @view.config.view_show_line_numbers = flag
@property active_lines: get: =>
return if @selection.empty
{ @current_line }
else
@buffer.lines\for_text_range @selection.anchor, @selection.cursor
@property active_chunk: get: =>
return if @selection.empty
@buffer\chunk 1, @buffer.length
else
start, stop = @selection\range!
@buffer\chunk start, stop - 1
@property mode_at_cursor: get: => @buffer\mode_at @cursor.pos
@property config_at_cursor: get: => @buffer\config_at @cursor.pos
refresh_display: => @view\refresh_display from_line: 1, invalidate: true
grab_focus: => @view\grab_focus!
newline: =>
@buffer\as_one_undo ->
@view\insert @buffer.eol
shift_right: =>
@with_selection_preserved ->
@transform_active_lines (lines) ->
for line in *lines
line\indent!
shift_left: =>
@with_selection_preserved ->
@transform_active_lines (lines) ->
for line in *lines
if line.indentation > 0
line\unindent!
transform_active_lines: (f) =>
lines = @active_lines
return if #lines == 0
start_pos = lines[1].start_pos
end_pos = lines[#lines].end_pos
@buffer\change start_pos, end_pos, -> f lines
with_position_restored: (f) =>
line, column, indentation, top_line = @cursor.line, @cursor.column, @current_line.indentation, @line_at_top
status, ret = pcall f, self
@cursor.line = line
delta = @current_line.indentation - indentation
@cursor.column = max 1, column + delta
@line_at_top = top_line
error ret unless status
with_selection_preserved: (f) =>
if @selection.empty
return f self
start_offset, end_offset = @selection.anchor, @selection.cursor
invert = start_offset > end_offset
start_offset, end_offset = end_offset, start_offset if invert
@buffer.markers\add {
{
name: 'howl-selection'
:start_offset
:end_offset
preserve: true
}
}
status, ret = pcall f, self
markers = @buffer.markers\for_range 1, @buffer.length, name: 'howl-selection'
@buffer.markers\remove name: 'howl-selection'
marker = markers[1]
if marker
start_offset, end_offset = marker.start_offset, marker.end_offset
start_offset, end_offset = end_offset, start_offset if invert
@selection\set start_offset, end_offset
error ret unless status
preview: (buffer) =>
unless @_is_previewing
@_pre_preview_buffer = @buffer
@_pre_preview_line_at_top = @line_at_top
@_show_buffer buffer, preview: true
signal.emit 'preview-opened', {
editor: self,
current_buffer: @_pre_preview_buffer,
preview_buffer: buffer
}
cancel_preview: =>
if @_is_previewing and @_pre_preview_buffer
preview_buffer = @buffer
@_show_buffer @_pre_preview_buffer
@line_at_top = @_pre_preview_line_at_top
@_pre_preview_buffer = nil
signal.emit 'preview-closed', {
editor: self,
current_buffer: @buffer,
:preview_buffer
}
indent: => @_apply_to_line_modes 'indent'
indent_all: =>
@with_position_restored ->
@selection\select_all!
@indent!
comment: => @_apply_to_line_modes 'comment'
uncomment: => @_apply_to_line_modes 'uncomment'
toggle_comment: => @_apply_to_line_modes 'toggle_comment'
delete_line: => @buffer.lines[@cursor.line] = nil
delete_to_end_of_line: (opts = {}) =>
cur_line = @current_line
if opts.no_copy
cur_line.text = cur_line.text\usub 1, @cursor.column_index - 1
else
end_pos = cur_line.end_pos
end_pos -= 1 if cur_line.has_eol
@selection\select @cursor.pos, end_pos
@selection\cut!
copy_line: =>
clipboard.push text: @current_line.text, whole_lines: true
paste: (opts = {})=>
clip = opts.clip or clipboard.current
return unless clip
@active_chunk\delete! unless @selection.empty
if not clip.whole_lines
if opts.where == 'after'
if @cursor.at_end_of_line
@insert(' ')
else
@cursor\right!
@insert clip.text
else
line = @current_line
text = clip.text
trailing_eol = text\ends_with @buffer.eol
if opts.where == 'after'
if trailing_eol and line.next
line = line.next
else
line = @buffer.lines\insert @current_line.nr + 1, ''
if trailing_eol
text = text\sub(1, -(#@buffer.eol + 1))
elseif not trailing_eol
line = @buffer.lines\insert line.nr, ''
@cursor.pos = line.start_pos
@with_position_restored ->
@insert text
insert: (text) => @view\insert text
smart_tab: =>
if not @selection.empty
@shift_right!
return
conf = @config_at_cursor
if conf.tab_indents and @current_context.prefix.is_blank
cur_line = @current_line
next_indent = cur_line.indentation + conf.indent
next_indent -= (next_indent % conf.indent)
cur_line.indentation = next_indent
@cursor.column = next_indent + 1
else if conf.use_tabs
@view\insert '\t'
else
@view\insert string.rep(' ', conf.indent)
smart_back_tab: =>
if not @selection.empty
@shift_left!
return
conf = @config_at_cursor
if conf.tab_indents and @current_context.prefix.is_blank
cursor_col = @cursor.column
cur_line = @current_line
cur_line\unindent!
@cursor.column = min(cursor_col, cur_line.indentation + 1)
else
return if @cursor.column == 1
tab_stops = math.floor (@cursor.column - 1) / conf.tab_width
col = tab_stops * conf.tab_width + 1
col -= conf.tab_width if col == @cursor.column
@cursor.column = col
delete_back: =>
prefix = @current_context.prefix
if @selection.empty and prefix.is_blank and not prefix.is_empty
if @config_at_cursor.backspace_unindents
cur_line = @current_line
gap = cur_line.indentation - @cursor.column
cur_line\unindent!
@cursor.column = max(1, cur_line.indentation - gap)
return
@view\delete_back allow_coalescing: true
delete_back_word: =>
if @selection.empty
pos = @cursor.pos
@cursor\word_left!
@buffer\delete @cursor.pos, pos-1
else
@view\delete_back!
delete_forward: =>
if @selection.empty
unless @cursor.at_end_of_file
@buffer\delete @cursor.pos, @cursor.pos
else
@active_chunk\delete!
delete_forward_word: =>
if @selection.empty
pos = @cursor.pos
@cursor\word_right!
@buffer\delete pos, @cursor.pos-1
else
@active_chunk\delete!
join_lines: =>
@buffer\as_one_undo ->
cur_line = @current_line
next_line = cur_line.next
return unless next_line
target_column = #cur_line + 1
content_start = next_line\ufind('%S') or 1
cur_line.text ..= ' ' .. next_line.text\sub content_start, -1
@cursor.column_index = target_column
@buffer.lines[next_line.nr] = nil
@cursor.column_index = target_column
duplicate_current: =>
if @selection.empty
line = @current_line
target_line = line.nr + 1
@buffer.lines\insert target_line, line.text
@line_at_bottom = target_line if @line_at_bottom < target_line
else
{:anchor, :cursor} = @selection
@buffer\insert @selection.text, max(anchor, cursor)
@selection\set anchor, cursor
cut: =>
if @selection.empty
clipboard.push text: @current_line.text, whole_lines: true
@buffer.lines[@cursor.line] = nil
else
@selection\cut!
copy: =>
if @selection.empty
clipboard.push text: @current_line.text, whole_lines: true
else
@selection\copy!
cycle_case: =>
_capitalize = (word) ->
word\usub(1, 1).uupper .. word\usub(2).ulower
_cycle_case = (text) ->
is_lower = text.ulower == text
is_upper = text.uupper == text
if is_lower
text.uupper
elseif is_upper
text\gsub '%S+', _capitalize
else
text.ulower
if @selection.empty
curword = @current_context.word
curword.text = _cycle_case curword.text
else
anchor, cursor = @selection.anchor, @selection.cursor
@selection.text = _cycle_case @selection.text
@selection\set anchor, cursor
forward_to_match: (str) =>
pos = @current_line\ufind str, @cursor.column_index + 1, true
@cursor.column_index = pos if pos
backward_to_match: (str) =>
rev_line = @current_line.text.ureverse
cur_column = (rev_line.ulen - @cursor.column_index + 1)
pos = rev_line\ufind str, cur_column + 1, true
@cursor.column_index = (rev_line.ulen - pos) + 1 if pos
show_popup: (popup, options = {}) =>
@remove_popup!
x, y = @_get_popup_coordinates options.position
popup\show @view\to_gobject!, :x, :y
@popup = window: popup, :options
remove_popup: =>
if @popup
if @popup.options.keep_alive
@popup.window\close!
else
@popup.window\destroy!
@popup = nil
complete: =>
return if @completion_popup.active
@completion_popup\complete!
if not @completion_popup.empty
@show_popup @completion_popup, {
position: @completion_popup.position,
persistent: true,
keep_alive: true
}
undo: =>
if @buffer.can_undo
@buffer\undo!
else
log.warn "Can't undo: already at oldest stored revision"
redo: => @buffer\redo!
scroll_up: =>
@view.first_visible_line -= 1
@view.cursor\ensure_in_view!
scroll_down: =>
@view.first_visible_line += 1
@view.cursor\ensure_in_view!
range_is_visible: (start_pos, end_pos) =>
start_line = @buffer.lines\at_pos(start_pos).nr
end_line = @buffer.lines\at_pos(end_pos).nr
return start_line >= @line_at_top and end_line <= @line_at_bottom
ensure_visible: (pos) =>
return if @range_is_visible pos, pos
line = @buffer.lines\at_pos(pos).nr
if @line_at_top > line
@line_at_top = max 1, line - 2
else
@line_at_bottom = min #@buffer.lines, line + 2
get_matching_brace: (pos, start_pos=1, [email protected]) =>
byte_offset = @buffer\byte_offset
pos = @_get_matching_brace(byte_offset(pos), byte_offset(start_pos), byte_offset(end_pos))
return pos and @buffer\char_offset pos
highlight: (hl, line_nr = nil) =>
start_pos, end_pos = @buffer\resolve_span hl, line_nr
highlight = hl.highlight or 'search'
highlights.apply highlight, @buffer, start_pos, end_pos - start_pos
-- private
_show_buffer: (buffer, opts={}) =>
@selection\remove!
@remove_popup!
if @_buf
@_buf.properties.position = {
pos: @cursor.pos,
line_at_top: @line_at_top
}
@_buf\remove_view_ref @view
unless @_is_previewing
@_buf.last_shown = sys.time!
@_is_previewing = opts.preview
@_buf = buffer
@indicator.title.label = buffer.title
if buffer.activity and buffer.activity.is_running!
with @indicator.activity
\start!
\show!
elseif rawget(@indicator, 'activity')
with @indicator.activity
\stop!
\hide!
@view.buffer = buffer._buffer
@_set_config_settings!
buffer\add_view_ref!
old_pos = @cursor.pos
local line_at_top
pos = buffer.properties.position or 1
if type(pos) == 'number'
pos = max 1, min(pos, #buffer + 1)
line_at_top = buffer.properties.line_at_top
@cursor.pos = pos
else
line_at_top = pos.line_at_top
@cursor\move_to pos
if line_at_top
@line_at_top = line_at_top
else
@line_at_center = @cursor.line
if @cursor.pos != old_pos
@_on_pos_changed!
refresh_variable: (name) =>
value = @buffer.config[name]
if aullar_config_vars[name]
if @view.config[aullar_config_vars[name]] != value
@view.config[aullar_config_vars[name]] = value
elseif editor_config_vars[name]
if @[editor_config_vars[name]] != value
@[editor_config_vars[name]] = value
else
error "Invalid var #{name}"
_set_config_settings: =>
for name, _ in pairs editor_config_vars
@refresh_variable name
for name, _ in pairs aullar_config_vars
@refresh_variable name
_create_indicator: (indics, id) =>
def = indicators[id]
error 'Invalid indicator id "' .. id .. '"', 2 if not def
y, x = def.placement\match('^(%w+)_(%w+)$')
bar = y == 'top' and @header -- or @footer
if y != 'top'
print('Adding indicator to footer:' .. id)
widget = def.factory and def.factory! or nil
indic = bar\add x, id, widget
indics[id] = indic
indic
_remove_indicator: (id) =>
def = indicators[id]
return unless def
y = def.placement\match('^(%w+)_%w+$')
bar = y == 'top' and @header or @footer
bar\remove id
@indicator[id] = nil
_apply_to_line_modes: (method) =>
lines = @active_lines
mode = nil
modes = [@buffer\mode_at line.start_pos for line in *lines]
mode = modes[1]
for other_mode in *modes
if mode != other_mode
mode = @buffer.mode
break
mode[method] mode, self if mode[method]
_pos_from_coordinates: (x, y) =>
byte_offset = @view\position_from_coordinates(x, y)
if byte_offset
@buffer\char_offset byte_offset
_word_or_token_at: (pos) =>
context = @buffer\context_at pos
chunk = context.word
chunk = context.token if chunk.empty
chunk
_expand_to_word_token_boundaries: (pos1, pos2) =>
chunk1 = @_word_or_token_at pos1
chunk2 = if pos2
@_word_or_token_at pos2
else
chunk1
if pos1 <= pos2
chunk1.start_pos, chunk2.end_pos + 1
else
chunk1.end_pos + 1, chunk2.start_pos
_expand_to_line_starts: (pos1, pos2) =>
line1 = @buffer.lines\at_pos(pos1)
line2 = @buffer.lines\at_pos(pos2)
if pos1 <= pos2
line1.start_pos, @_next_line_start(line2)
else
@_next_line_start(line1), line2.start_pos
_next_line_start: (line) =>
next_line = line.next
if next_line
next_line.start_pos
else
line.end_pos
_on_destroy: =>
for h in *@_handlers
gobject_signal.disconnect h
@buffer\remove_view_ref!
@completion_popup\destroy!
@view\destroy!
@buffer.last_shown = sys.time! unless @_is_previewing
signal.emit 'editor-destroyed', editor: self
_on_key_press: (view, event) =>
@remove_popup! if event.key_name == 'escape'
if @popup
if not @popup.window.showing
@remove_popup!
else
if @popup.window.keymap
return true if bindings.dispatch(event, 'popup', { @popup.window.keymap }, @popup.window)
@remove_popup! if not @popup.options.persistent
else
@searcher\cancel!
if not bindings.is_capturing and auto_pair.handle event, @
@remove_popup!
return true
maps = { @buffer.keymap, @mode_at_cursor and @mode_at_cursor.keymap }
return true if bindings.process event, 'editor', maps, self
_on_button_press: (view, event) =>
return false if event.button == 3
if event.button == 1
@drag_press_type = event.type
@drag_press_pos = @_pos_from_coordinates(event.x, event.y)
if event.type == Gdk.GDK_2BUTTON_PRESS
group = @current_context.word
group = @current_context.token if group.empty
unless group.empty
@selection\set group.start_pos, group.end_pos + 1
true
elseif event.type == Gdk.GDK_3BUTTON_PRESS
@selection\set @current_line.start_pos, @_next_line_start(@current_line)
_on_button_release: (view, event) =>
@drag_press_type = nil
if event.button == 3 or event.button == 2
text = nil
range = nil
click_position = @_pos_from_coordinates(event.x, event.y)
start_selection, end_selection = @selection\range!
if @selection.empty or click_position >= end_selection or click_position < start_selection
context = @buffer\context_at click_position
line = context.line
if line.end_pos == click_position
text = line.text.stripped
range = line
else
start_pos, end_pos = context\_get_boundaries r'([\\.\\-_\\\\/:\\^#]*[^\\s\\p{P}]+)+'
range = Chunk @buffer, start_pos, end_pos-1
text = range.text
else
text = @selection.text.stripped
range = @selection
if event.button == 3
signal.emit 'plumb-text', editor: @, :text, :range
elseif event.button == 2
signal.emit 'execute-text', editor: @, :text, :range
_on_motion_event: (view, event) =>
if @drag_press_type == Gdk.GDK_2BUTTON_PRESS or @drag_press_type == Gdk.GDK_3BUTTON_PRESS
pos = @_pos_from_coordinates(event.x, event.y)
if pos
sel_start, sel_end = @drag_press_pos, pos
if @drag_press_type == Gdk.GDK_2BUTTON_PRESS
sel_start, sel_end = @_expand_to_word_token_boundaries sel_start, sel_end
elseif @drag_press_type == Gdk.GDK_3BUTTON_PRESS
sel_start, sel_end = @_expand_to_line_starts sel_start, sel_end
unless sel_start == sel_end
@selection\set sel_start, sel_end
true
_on_pos_changed: =>
@_update_position!
@_brace_highlight!
if @popup and @popup.window.on_pos_changed
@popup.window\on_pos_changed @cursor
signal.emit 'cursor-changed', editor: self, cursor: @cursor
mode = @mode_at_cursor
if mode.on_cursor_changed
mode\on_cursor_changed @, @cursor
_get_matching_brace: (byte_pos, start_pos, end_pos) =>
buffer = @view.buffer
return if byte_pos < 1 or byte_pos > buffer.size
auto_pairs = @buffer\mode_at(buffer\char_offset byte_pos).auto_pairs
return unless auto_pairs
cur_char = buffer\sub byte_pos, byte_pos
matching_close = auto_pairs[cur_char]
local matching_open
for k, v in pairs auto_pairs
if v == cur_char
matching_open = k
break
matching = matching_close or matching_open
return unless matching and matching != cur_char
if matching_close
return buffer\pair_match_forward(byte_pos, matching_close, end_pos)
else
return buffer\pair_match_backward(byte_pos, matching_open, start_pos)
_brace_highlight: =>
return unless @view.showing
{:buffer, :cursor} = @view
if @_brace_highlighted
buffer.markers\remove name: 'brace_highlight'
@_brace_highlighted = false
should_highlight = @config_at_cursor.matching_braces_highlighted
return unless should_highlight
auto_pairs = @mode_at_cursor.auto_pairs
return unless auto_pairs
highlight_braces = (pos1, pos2, flair) ->
buffer.markers\add {
{
name: 'brace_highlight',
:flair,
start_offset: pos1,
end_offset: pos1 + 1
},
{
name: 'brace_highlight',
:flair,
start_offset: pos2,
end_offset: pos2 + 1
},
}
@_brace_highlighted = true
pos = cursor.pos
match_pos = @_get_matching_brace pos - 1
if match_pos
highlight_braces match_pos, pos - 1, 'brace_highlight_secondary'
match_pos = @_get_matching_brace pos
if match_pos
highlight_braces match_pos, pos, 'brace_highlight'
_update_position: =>
pos = @cursor.line .. ':' .. @cursor.column
@indicator.position.label = pos
_get_popup_coordinates: ([email protected]) =>
pos = @buffer\byte_offset pos
coordinates = @view\coordinates_from_position pos
unless coordinates
pos = @buffer.lines[@line_at_top].start_pos
coordinates = @view\coordinates_from_position pos
x = coordinates.x
y = coordinates.y2 + 2
x, y
_on_focus: (args) =>
howl.app.editor = self
@has_focus = true
signal.emit 'editor-focused', editor: self
false
_on_focus_lost: (args) =>
@has_focus = false
@remove_popup!
signal.emit 'editor-defocused', editor: self
false
_on_insert_at_cursor: (_, args) =>
params = moon.copy args
params.editor = self
return if signal.emit('insert-at-cursor', params) == signal.abort
return if @mode_at_cursor.on_insert_at_cursor and @mode_at_cursor\on_insert_at_cursor(params, self)
if @popup
@popup.window\on_insert_at_cursor(self, params) if @popup.window.on_insert_at_cursor
elseif args.text.ulen == 1
config = @config_at_cursor
return unless config.complete != 'manual'
return unless #@current_context.word_prefix >= config.completion_popup_after
skip_styles = config.completion_skip_auto_within
if skip_styles
cur_style = @current_context.style
return if not cur_style
for skip_style in *skip_styles
return if cur_style\match skip_style
@complete!
true
_on_delete_back: (_, args) =>
if @popup
params = text: args.text, editor: self, at_pos: @buffer\char_offset(args.pos)
@popup.window\on_delete_back self, params if @popup.window.on_delete_back
_on_scroll: =>
return unless @popup and @popup.showing
x, y = @_get_popup_coordinates @popup.options.position
@popup.window\move_to x, y
-- Default indicators
with Editor
.register_indicator 'title', 'top_left'
.register_indicator 'position', 'bottom_right'
.register_indicator 'activity', 'top_right', -> Gtk.Spinner!
.register_indicator 'inspections', 'bottom_left'
-- Config variables
with config
.define
name: 'tab_width'
description: 'The width of a tab, in number of characters'
default: 4
type_of: 'number'
.define
name: 'use_tabs'
description: 'Whether to use tabs for indentation, and not only spaces'
default: false
type_of: 'boolean'
.define
name: 'indent'
description: 'The number of characters to use for indentation'
default: 2
type_of: 'number'
.define
name: 'tab_indents'
description: 'Whether tab indents within whitespace'
default: true
type_of: 'boolean'
.define
name: 'backspace_unindents'
description: 'Whether backspace unindents within whitespace'
default: true
type_of: 'boolean'
.define
name: 'completion_popup_after'
description: 'Show completion after this many characters'
default: 2
type_of: 'number'
.define
name: 'completion_skip_auto_within'
description: 'Do not popup auto completions when inside these styles'
default: nil
type_of: 'string_list'
options: {
{ 'string', 'Do not auto-complete within strings' },
{ 'comment', 'Do not auto-complete within comments' },
{ 'comment, string', 'Do not auto-complete within strings or comments' },
}
.define
name: 'indentation_guides'
description: 'Controls whether indentation guides are shown'
default: 'on'
options: {
{ 'none', 'No indentation guides are shown' }
{ 'on', 'Indentation guides are shown' }
}
.define
name: 'edge_column'
description: 'Shows an edge line at the specified column, if set'
default: nil
type_of: 'number'
.define
name: 'line_wrapping'
description: 'Controls how lines are wrapped if necessary'
default: 'word'
options: {
{ 'none', 'Lines are not wrapped' }
{ 'word', 'Lines are wrapped on word boundaries' }
{ 'character', 'Lines are wrapped on character boundaries' }
}
.define
name: 'line_wrapping_navigation'
description: 'Controls how wrapped lines are navigated'
default: 'visual'
options: {
{ 'real', 'Lines are navigated by real lines' }
{ 'visual', 'Lines are navigated by visual (wrapped) lines' }
}
.define
name: 'line_wrapping_symbol'
description: 'The symbol used for indicating a line wrap'
type_of: 'string'
default: '⏎'
.define
name: 'horizontal_scrollbar'
description: 'Whether horizontal scrollbars are shown'
default: true
type_of: 'boolean'
.define
name: 'vertical_scrollbar'
description: 'Whether vertical scrollbars are shown'
default: true
type_of: 'boolean'
.define
name: 'cursor_line_highlighted'
description: 'Whether the cursor line is highlighted'
default: true
type_of: 'boolean'
.define
name: 'matching_braces_highlighted'
description: 'Whether matching braces are highlighted'
default: true
type_of: 'boolean'
.define
name: 'line_numbers'
description: 'Whether line numbers are shown'
default: true
type_of: 'boolean'
.define
name: 'cursor_blink_interval'
description: 'The rate at which the cursor blinks (ms, 0 disables)'
default: 500
type_of: 'number'
.define
name: 'scroll_speed_y'
description: 'A percentage value determining the vertical mouse scrolling speed'
default: 250
type_of: 'number'
.define
name: 'scroll_speed_x'
description: 'A percentage value determining the horizontal mouse scrolling speed'
default: 250
type_of: 'number'
.define
name: 'line_padding'
description: 'Extra spacing above and below each line'
default: 0
type_of: 'number'
.define
name: 'undo_limit'
description: 'Per buffer limit of undo revisions to keep'
default: 200
type_of: 'number'
scope: 'global'
for watched_property, _ in pairs aullar_config_vars
.watch watched_property, apply_variable
for watched_property, _ in pairs editor_config_vars
.watch watched_property, apply_variable
for global_var in *{
'undo_limit'
}
.watch global_var, apply_global_variable
-- Commands
for cmd_spec in *{
{ 'newline', 'Add a new line at the current position', 'newline' }
{ 'comment', 'Comment the selection or current line', 'comment' }
{ 'uncomment', 'Uncomment the selection or current line', 'uncomment' }
{ 'toggle-comment', 'Comment or uncomment the selection or current line', 'toggle_comment' }
{ 'delete-line', 'Delete the current line', 'delete_line' }
{ 'cut-to-end-of-line', 'Cut to the end of line', 'delete_to_end_of_line' }
{ 'delete-to-end-of-line', 'Delete to the end of line', 'delete_to_end_of_line', no_copy: true }
{ 'copy-line', 'Copy the current line to the clipboard', 'copy_line' }
{ 'paste', 'Paste the contents of the clipboard at the current position', 'paste' }
{ 'smart-tab', 'Insert tab or shift selected text right', 'smart_tab' }
{ 'smart-back-tab', 'Move to previous tab stop or shifts text left', 'smart_back_tab' }
{ 'delete-back', 'Delete one character back', 'delete_back' }
{ 'delete-back-word', 'Delete one word back', 'delete_back_word' }
{ 'delete-forward', 'Delete one character forward', 'delete_forward' }
{ 'delete-forward-word', 'Delete one word forward', 'delete_forward_word' }
{ 'shift-right', 'Shift the selected lines, or the current line, right', 'shift_right' }
{ 'shift-left', 'Shift the selected lines, or the current line, left', 'shift_left' }
{ 'indent', 'Indent the selected lines, or the current line', 'indent' }
{ 'indent-all', 'Indent the entire buffer', 'indent_all' }
{ 'join-lines', 'Join the current line with the line below', 'join_lines' }
{ 'complete', 'Start completion at cursor', 'complete' }
{ 'undo', 'Undo last edit for the current editor', 'undo' }
{ 'redo', 'Redo last undo for the current editor', 'redo' }
{ 'scroll-up', 'Scroll one line up', 'scroll_up' }
{ 'scroll-down', 'Scroll one line down', 'scroll_down' }
{ 'duplicate-current', 'Duplicate the selection or current line', 'duplicate_current' }
{ 'cut', 'Cut the selection or current line to the clipboard', 'cut' }
{ 'copy', 'Copy the selection or current line to the clipboard', 'copy' }
{ 'cycle-case', 'Change case for current word or selection', 'cycle_case' }
}
args = { select 4, table.unpack cmd_spec }
command.register
name: "editor-#{cmd_spec[1]}"
description: cmd_spec[2]
handler: -> howl.app.editor[cmd_spec[3]] howl.app.editor, table.unpack args
for sel_cmd_spec in *{
{ 'select-all', 'Selects all text' }
}
command.register
name: "editor-#{sel_cmd_spec[1]}"
description: sel_cmd_spec[2]
handler: -> howl.app.editor.selection[sel_cmd_spec[1]\gsub '-', '_'] howl.app.editor.selection
-- signals
signal.register 'before-buffer-switch',
description: 'Signaled right before a buffer is set for an editor'
parameters:
editor: 'The editor for which the buffer is being set'
current_buffer: 'The current buffer for the editor'
new_buffer: 'The new buffer that will be set for the editor'
signal.register 'after-buffer-switch',
description: 'Signaled right after a buffer has been set for an editor'
parameters:
editor: 'The editor for which the buffer was set'
current_buffer: 'The new buffer that was set for the editor'
old_buffer: 'The buffer that was previously set for the editor'
signal.register 'preview-opened',
description: 'Signaled right after a preview buffer was opened in an editor'
parameters:
editor: 'The editor for which the preview was opened'
current_buffer: 'The current non-preview buffer associated with the editor'
preview_buffer: 'The new preview buffer that is open in the editor'
signal.register 'preview-closed',
description: 'Signaled right after a preview buffer has been removed for an editor'
parameters:
editor: 'The editor for which the preview was opened'
current_buffer: 'The original buffer that was restored for the editor'
preview_buffer: 'The preview buffer that was previously open in the editor'
signal.register 'editor-focused',
description: 'Signaled right after an editor has received focus'
parameters:
editor: 'The editor that received focus'
signal.register 'editor-defocused',
description: 'Signaled right after an editor has lost focus'
parameters:
editor: 'The editor that lost focus'
signal.register 'editor-destroyed',
description: 'Signaled right after an editor was destroyed'
parameters:
editor: 'The editor that is being destroyed'
signal.register 'insert-at-cursor',
description: 'Signaled right after text has been inserted into an editor at the cursor position'
parameters:
editor: 'The editor for which the text was inserted'
text: 'The inserted text'
signal.register 'cursor-changed',
description: 'Signaled right after the cursor position has changed'
parameters:
editor: 'The editor for which the text was inserted'
cursor: 'The cursor object'
signal.register 'plumb-text',
description: 'Signaled when text is right-clicked and is meant to be opened or plumbed'
parameters:
editor: 'The editor in which the signal originated'
range: 'The range which was clicked'
text: 'The stripped text'
signal.register 'execute-text',
description: 'Signaled when text is middle-clicked and is meant to be executed'
parameters:
editor: 'The editor in which the signal originated'
range: 'The range which was clicked'
text: 'The stripped text'
return Editor
| 30.011886 | 111 | 0.670284 |
1a631ec809cf93a0295e99f2df986c5b07c7c914 | 14,083 |
lapis = require "lapis"
require "spec.helpers" -- defines assert.one_of
import
mock_request
mock_action
assert_request
stub_request
from require "lapis.spec.request"
describe "lapis.spec.request", ->
describe "mock_request", ->
class App extends lapis.Application
"/hello": =>
it "should mock a request", ->
assert.same 200, (mock_request App, "/hello")
assert.has_error ->
mock_request App, "/world"
it "should mock a request with double headers", ->
mock_request App, "/hello", {
method: "POST"
headers: {
["Content-type"]: {
"hello"
"world"
}
}
}
it "should mock request with session", ->
class SessionApp extends lapis.Application
"/test-session": =>
import flatten_session from require "lapis.session"
assert.same {
color: "hello"
height: {1,2,3,4}
}, flatten_session @session
mock_request SessionApp, "/test-session", {
session: {
color: "hello"
height: {1,2,3,4}
}
}
describe "mock_action action", ->
it "should mock action", ->
assert.same "hello", mock_action lapis.Application, "/hello", {}, ->
"hello"
describe "stub_request", ->
class SomeApp extends lapis.Application
[cool_page: "/cool/:name"]: =>
it "should stub a request object", ->
req = stub_request SomeApp, "/"
assert.same "/cool/world", req\url_for "cool_page", name: "world"
describe "lapis.request", ->
describe "session", ->
class SessionApp extends lapis.Application
layout: false
"/set_session/:value": =>
@session.hello = @params.value
"/get_session": =>
@session.hello
it "should set and read session", ->
_, _, h = assert_request SessionApp, "/set_session/greetings"
status, res = assert_request SessionApp, "/get_session", prev: h
assert.same "greetings", res
describe "query params", ->
local params
class QueryApp extends lapis.Application
layout: false
"/hello": =>
params = @params
it "mocks request with query params", ->
assert.same 200, (mock_request QueryApp, "/hello?hello=world")
assert.same {hello: "world"}, params
it "mocks request with query params #bug", ->
assert.same 200, (mock_request QueryApp, "/hello?null")
-- todo: this is bug
assert.same {}, params
it "parses nested params", ->
assert.same 200, (mock_request QueryApp, "/hello?upload[1][color]=red&upload[1][height]=12m&upload[2]=hmm&upload[3][3][3]=yeah")
assert.same {
upload: {
"1": {
color: "red"
height: "12m"
}
"2": "hmm"
"3": {
"3": {
"3": "yeah"
}
}
}
}, params
it "parses params with [1] and overlapping name", ->
assert.same 200, (mock_request QueryApp, "/hello?p=a&p=x&p[1]=y")
-- due to hash table ordering this can be one or the other
assert.one_of params, {
{ p: "x" }
{ p: { ["1"]: "y" } }
}
it "parses duplicate with empty []", ->
assert.same 200, (mock_request QueryApp, "/hello?test=100&other[1]=world&thing[]=1&thing[]=2")
-- ambiguous hash table ordering means we don't know which one is written on top
assert.one_of params, {
{
test: "100"
other: { "1": "world" }
"thing[]": "1"
}
{
test: "100"
other: { "1": "world" }
"thing[]": "2"
}
}
it "parses undefined behavior", ->
assert.same 200, (mock_request QueryApp, "/hello?one[a][][]=y&two[][f][b]=x&three[q][][e]=n&four[][][]=2")
assert.same {
one: {
a: "y"
}
two: {
f: {
b: "x"
}
}
three: {
q: {
e: "n"
}
}
"four[][][]": "2"
}, params
describe "json request", ->
import json_params from require "lapis.application"
it "should parse json object body", ->
local res
class SomeApp extends lapis.Application
"/": json_params =>
res = @params.thing
assert_request SomeApp, "/", {
headers: {
"content-type": "application/json"
}
body: '{"thing": 1234}'
}
assert.same 1234, res
it "should parse json array body", ->
local res
class SomeApp extends lapis.Application
"/": json_params =>
res = @params
assert_request SomeApp, "/", {
headers: {
"content-type": "application/json"
}
body: '[1,"hello", {}]'
}
assert.same {1, "hello", {}}, res
it "should not fail on invalid json", ->
class SomeApp extends lapis.Application
"/": json_params =>
assert_request SomeApp, "/", {
headers: {
"content-type": "application/json"
}
body: 'helloworldland'
}
describe "write", ->
write = (fn, ...) ->
class A extends lapis.Application
layout: false
"/": fn
mock_request A, "/", ...
it "writes nothing, sets default content type", ->
status, body, h = write ->
assert.same 200, status
assert.same "", body
assert.same "text/html", h["Content-Type"]
it "writes status code", ->
status, body, h = write -> status: 420
assert.same 420, status
it "writes content type", ->
_, _, h = write -> content_type: "text/javascript"
assert.same "text/javascript", h["Content-Type"]
it "writes headers", ->
_, _, h = write -> {
headers: {
"X-Lapis-Cool": "zone"
"Cache-control": "nope"
}
}
assert.same "zone", h["X-Lapis-Cool"]
assert.same "nope", h["Cache-Control"]
it "does redirect", ->
status, _, h = write -> { redirect_to: "/hi" }
assert.same 302, status
assert.same "http://localhost/hi", h["Location"]
it "does permanent redirect", ->
status, _, h = write -> { redirect_to: "/loaf", status: 301 }
assert.same 301, status
assert.same "http://localhost/loaf", h["Location"]
it "writes string to buffer", ->
status, body, h = write -> "hello"
assert.same "hello", body
it "writes many things to buffer, with options", ->
status, body, h = write -> "hello", "world", status: 404
assert.same 404, status
assert.same "helloworld", body
it "writes json", ->
status, body, h = write -> json: { items: {1,2,3,4} }
assert.same [[{"items":[1,2,3,4]}]], body
assert.same "application/json", h["Content-Type"]
it "writes json with custom content-type", ->
status, body, h = write ->
json: { item: "hi" }, content_type: "application/json; charset=utf-8"
assert.same "application/json; charset=utf-8", h["Content-Type"]
assert.same [[{"item":"hi"}]], body
describe "cookies", ->
describe "read", ->
class PrintCookieApp extends lapis.Application
"/": =>
@cookies.hi
json: getmetatable(@cookies).__index
it "should return empty with no cookie header", ->
_, res = mock_request PrintCookieApp, "/", {
expect: "json"
headers: { }
}
assert.same { }, res
it "should read basic cookie", ->
_, res = mock_request PrintCookieApp, "/", {
expect: "json"
headers: {
cookie: "hello=world"
}
}
assert.same {
hello: "world"
}, res
it "should merge cookies when there are multiple headers", ->
_, res = mock_request PrintCookieApp, "/", {
expect: "json"
headers: {
cookie: {
"hello=world; one=two"
"zone=man; one=five"
"a=b"
}
}
}
assert.same {
a: "b"
one: "five"
hello: "world"
zone: "man"
}, res
describe "write", ->
class CookieApp extends lapis.Application
layout: false
"/": => @cookies.world = 34
"/many": =>
@cookies.world = 454545
@cookies.cow = "one cool ;cookie"
class CookieApp2 extends lapis.Application
layout: false
cookie_attributes: => "Path=/; Secure; Domain=.leafo.net;"
"/": => @cookies.world = 34
it "should write a cookie", ->
_, _, h = mock_request CookieApp, "/"
assert.same "world=34; Path=/; HttpOnly", h["Set-Cookie"]
it "should write multiple cookies", ->
_, _, h = mock_request CookieApp, "/many"
assert.one_of h["Set-Cookie"], {
{
'cow=one%20cool%20%3bcookie; Path=/; HttpOnly'
'world=454545; Path=/; HttpOnly'
}
{
'world=454545; Path=/; HttpOnly'
'cow=one%20cool%20%3bcookie; Path=/; HttpOnly'
}
}
it "should write a cookie with cookie attributes", ->
_, _, h = mock_request CookieApp2, "/"
assert.same "world=34; Path=/; Secure; Domain=.leafo.net;", h["Set-Cookie"]
it "should set cookie attributes with lua app", ->
app = lapis.Application!
app.cookie_attributes = =>
"Path=/; Secure; Domain=.leafo.net;"
app\get "/", =>
@cookies.world = 34
_, _, h = mock_request app, "/"
assert.same "world=34; Path=/; Secure; Domain=.leafo.net;", h["Set-Cookie"]
describe "csrf", ->
csrf = require "lapis.csrf"
it "verifies csrf token", ->
import capture_errors_json, respond_to from require "lapis.application"
class CsrfApp extends lapis.Application
"/form": capture_errors_json respond_to {
GET: =>
json: {
csrf_token: csrf.generate_token @
}
POST: =>
csrf.assert_token @
json: { success: true }
}
_, res, h = mock_request CsrfApp, "/form", {
expect: "json"
}
assert res.csrf_token, "missing csrf token"
assert h.set_cookie, "missing cookie"
_, post_res = mock_request CsrfApp, "/form", {
post: {
csrf_token: res.csrf_token
}
expect: "json"
prev: h
}
assert.same { success: true }, post_res
-- no cookie set, fails
_, post_res = mock_request CsrfApp, "/form", {
post: {
csrf_token: res.csrf_token
}
expect: "json"
}
assert.same {
errors: {
"csrf: missing token cookie"
}
}, post_res
-- no token, fails
_, post_res = mock_request CsrfApp, "/form", {
post: { }
expect: "json"
}
assert.same {
errors: {
"missing csrf token"
}
}, post_res
describe "layouts", ->
after_each = ->
package.loaded["views.another_layout"] = nil
it "renders without layout", ->
class LayoutApp extends lapis.Application
layout: "cool_layout"
"/": => "hello", layout: false
status, res = mock_request LayoutApp, "/"
assert.same "hello", res
it "renders with layout by name", ->
import Widget from require "lapis.html"
package.loaded["views.another_layout"] = class extends Widget
content: =>
text "*"
@content_for "inner"
text "^"
class LayoutApp extends lapis.Application
layout: "cool_layout"
"/": => "hello", layout: "another_layout"
status, res = mock_request LayoutApp, "/"
assert.same "*hello^", res
it "renders layout with class", ->
import Widget from require "lapis.html"
class Layout extends Widget
content: =>
text "("
@content_for "inner"
text ")"
class LayoutApp extends lapis.Application
layout: "cool_layout"
"/": =>
"hello", layout: Layout
status, res = mock_request LayoutApp, "/"
assert.same "(hello)", res
-- these seem like an application spec and not a request one
describe "before filter", ->
it "should run before filter", ->
local val
class BasicBeforeFilter extends lapis.Application
@before_filter =>
@hello = "world"
"/": =>
val = @hello
assert_request BasicBeforeFilter, "/"
assert.same "world", val
it "should run before filter with inheritance", ->
class BasicBeforeFilter extends lapis.Application
@before_filter => @hello = "world"
val = mock_action BasicBeforeFilter, =>
@hello
assert.same "world", val
it "should run before filter scoped to app with @include", ->
local base_val, parent_val
class BaseApp extends lapis.Application
@before_filter => @hello = "world"
"/base_app": => base_val = @hello or "nope"
class ParentApp extends lapis.Application
@include BaseApp
"/child_app": => parent_val = @hello or "nope"
assert_request ParentApp, "/base_app"
assert_request ParentApp, "/child_app"
assert.same "world", base_val
assert.same "nope", parent_val
it "should cancel action if before filter writes", ->
action_run = 0
class SomeApp extends lapis.Application
layout: false
@before_filter =>
if @params.value == "stop"
@write "stopped!"
"/hello/:value": => action_run += 1
assert_request SomeApp, "/hello/howdy"
assert.same action_run, 1
_, res = assert_request SomeApp, "/hello/stop"
assert.same action_run, 1
assert.same "stopped!", res
it "should create before filter for lua app", ->
app = lapis.Application!
local val
app\before_filter =>
@val = "yeah"
app\get "/", =>
val = @val
assert_request app, "/"
assert.same "yeah", val
| 25.887868 | 134 | 0.541575 |
79b83d38ab897cdd72168bb4b84227349db40577 | 2,259 | import pairs, type from _G
import lower from string
import sort from table
-- ::sortingWeights -> table
-- Represents the sorting order weights for Lua types
--
sortingWeights = {
boolean: 0,
number: 1,
string: 2,
table: 3
}
-- ::getKeys(table tbl) -> table
-- Returns all the keys within the table as an array
-- export
export getKeys = (tbl) ->
return [key for key, value in pairs(tbl)]
-- ::getSortedValues(table tbl, boolean isCaseSensitive) -> table
-- Returns all the keys within the table as an array, sorting them in the process
-- NOTE:
-- when sorting, the following rules apply
-- * if both values are booleans, false precedes true
-- * if both values are numbers, lower value precedes higher value
-- * if both values are strings, the values are alphabetized, optionally ignoring case
-- * if both values are mismatch types, the follow sorting order is applied: boolean < number < string
-- export
export getSortedValues = (tbl, isCaseSensitive) ->
values = [value for value in *tbl]
local aWeight, bWeight, aType, bType
sort(values, (a, b) ->
aType, bType = type(a), type(b)
-- If both values are the same type, use special rules, otherwise use the predetermined type weights
if aType == "string" and bType == "string"
return lower(a) < lower(b) unless isCaseSensitive
return a < b
elseif aType == "boolean" and bType == "boolean"
if aType == true and bType == false then return false
return true
elseif aType == "number" and bType == "number" then return a < b
else return sortingWeights[aType] < sortingWeights[bType]
)
return values
-- ::isArray(table tbl) -> boolean
-- Returns if the table if a sequential non-sparse array
-- export
export isArray = (tbl) ->
-- Check if the table has a first index
return false if tbl[1] == nil
-- Check if each key is a number
count = 0
for key, value in pairs(tbl)
return false unless type(key) == "number"
count += 1
-- Check if the table is sparse, using the counted keys and the calculated table length
return false unless count == #tbl
return true
| 32.271429 | 110 | 0.645861 |
bc2492c6952605f0ef4ae779e0ba4bdea36382bc | 1,932 | export world
wave = require 'wave'
waveList ={}
[[
<<<<<<< HEAD
=======
love.load= ->
world = love.physics.newWorld( 0, 0, true)
return
love.draw= ->
for i,v in ipairs(waveList)
print("main draw")
v\draw!
return
love.update= (dt)->
world\update(dt)
>>>>>>> 792fb09c6a208af33b794b9b0af90faf78a15c2b
love.keypressed= (key)->
if key == "a" then
-- new: (x, y,gap1=1, gap2=2, size=10, speed=10)=>
s = math.random(50, 150)
newWave= wave(200, 200, 400)
table.insert(waveList, newWave)
]]
Boat = require('boat')
SPAWNTIME = 5
nextspawn = 3
math.randomseed(os.time())
local boat
boxes = {}
love.load = ->
love.physics.setMeter(64)
world = love.physics.newWorld(0, 0, true)
boat = Boat!
w,h = love.window.getDimensions!
s = 3
[[
for i=1,1000
b = {}
b.body = love.physics.newBody(world, math.random(-s*w,s*w), math.random(-s*h,s*h), "dynamic")
b.shape = love.physics.newRectangleShape(30, 30)
b.fixture = love.physics.newFixture(b.body, b.shape, 1)
b.body\setMass(5)
table.insert(boxes,b)
]]
love.update = (dt) ->
boat\update(dt)
world\update(dt)
nextspawn += dt
if nextspawn > SPAWNTIME
print("Spawn")
w,h = love.window.getDimensions!
newWave= wave(math.random(w), math.random(h), 400)
table.insert(waveList, newWave)
nextspawn = 0
love.draw = ->
x,y = boat.body\getPosition!
w,h = love.window.getDimensions!
love.graphics.translate(-x+w/2,-y+h/2)
for i,v in ipairs(waveList)
v\draw!
love.graphics.setColor(200,150,0)
for i,v in ipairs(boxes)
if i%500 == 0
love.graphics.setColor(200,0,0)
love.graphics.polygon("fill", v.body\getWorldPoints(v.shape\getPoints()))
love.graphics.setColor(200,150,0)
love.graphics.setColor(255,255,255)
boat\draw!
love.graphics.origin!
return
love.keypressed = (key) ->
if key == "escape"
love.event.quit!
| 20.774194 | 97 | 0.624741 |
905ce172778f3a178dbdb85d79ffd29c3fd3e869 | 1,234 | import insert from table
import Set from require "moonscript.data"
import Block from require "moonscript.compile"
parse = require "moonscript.parse"
default_whitelist = Set {
'_G'
'_VERSION'
'assert'
'bit32'
'collectgarbage'
'coroutine'
'debug'
'dofile'
'error'
'getfenv'
'getmetatable'
'io'
'ipairs'
'load'
'loadfile'
'loadstring'
'module'
'next'
'os'
'package'
'pairs'
'pcall'
'print'
'rawequal'
'rawget'
'rawlen'
'rawset'
'require'
'select'
'setfenv'
'setmetatable'
'string'
'table'
'tonumber'
'tostring'
'type'
'unpack'
'xpcall'
"nil"
"true"
"false"
--'math'
"Dorothy"
}
class LinterBlock extends Block
new: (whitelist_globals=default_whitelist, ...) =>
super ...
@globals = {}
vc = @value_compilers
@value_compilers = setmetatable {
ref: (block, val) ->
name = val[2]
unless block\has_name(name) or whitelist_globals[name] or name\match "%."
insert @globals,name
vc.ref block, val
}, __index: vc
block: (...) =>
with super ...
.block = @block
.value_compilers = @value_compilers
LintMoonGlobals = (codes)->
tree,err = parse.string codes
return nil,err unless tree
scope = LinterBlock!
scope\stms tree
Set scope.globals
LintMoonGlobals
| 15.620253 | 77 | 0.666126 |
236cc07474b4cfb29e7764c5ed9f0767758f4ec1 | 1,633 | -- 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!
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.515625 | 79 | 0.670545 |
14619ee8df79b47881492be551f336740da7a0b9 | 1,199 | -- alfons.look
-- Gets the path for a module, specifically tailored for Alfons
import readMoon, readLua from require "alfons.file"
fs = require "filekit"
sanitize = (pattern="") -> pattern\gsub "[%(%)%.%%%+%-%*%?%[%]%^%$]", "%%%0"
dirsep, pathsep, wildcard = package.config\match "^(.)\n(.)\n(.)"
modsep = "%."
swildcard = sanitize wildcard
makeLook = (gpath=package.path) ->
-- generate lists of paths
paths = [path for path in gpath\gmatch "[^#{pathsep}]+"]
moonpaths = [path\gsub "%.lua$", ".moon" for path in gpath\gmatch "[^#{pathsep}]+"]
-- return
(name) ->
mod = name\gsub modsep, dirsep
file = false
for path in *paths
pt = path\gsub swildcard, mod
file = pt if fs.exists pt
for path in *moonpaths
pt = path\gsub swildcard, mod
file = pt if fs.exists pt
--
if file
read = (file\match "%.lua$") and readLua or readMoon
content, contentErr = read file
if content
return content
else
return nil, contentErr
else
return nil, "#{name} not found."
{ :makeLook, look: makeLook! } | 32.405405 | 85 | 0.549625 |
48b56c7d1c0737823688658678a2393d57dd3048 | 1,991 |
luasocket = do
import flatten from require "pgmoon.util"
proxy_mt = {
__index: (key) =>
sock = @sock
original = sock[key]
if type(original) == "function"
fn = (_, ...) ->
original sock, ...
@[key] = fn
fn
else
original
}
overrides = {
send: true
getreusedtimes: true
sslhandshake: true,
settimeout: true
}
{
tcp: (...) ->
socket = require "socket"
sock = socket.tcp ...
proxy = setmetatable {
:sock
send: (...) => @sock\send flatten ...
getreusedtimes: => 0
settimeout: (t) =>
if t
t = t/1000
@sock\settimeout t
sslhandshake: (verify, opts={}) =>
ssl = require "ssl"
params = {
mode: "client"
protocol: opts.ssl_version or "tlsv1"
key: opts.key
certificate: opts.cert
cafile: opts.cafile
verify: verify and "peer" or "none"
options: "all"
}
sec_sock, err = ssl.wrap @sock, params
return false, err unless sec_sock
success, err = sec_sock\dohandshake!
return false, err unless success
-- purge memoized socket closures
for k, v in pairs @
@[k] = nil unless type(v) ~= "function" or overrides[k]
@sock = sec_sock
true
}, proxy_mt
proxy
}
{
new: (socket_type) ->
if socket_type == nil
-- choose the default socket, try to use nginx, otherwise default to
-- luasocket
socket_type = if ngx and ngx.get_phase! != "init"
"nginx"
else
"luasocket"
socket = switch socket_type
when "nginx"
ngx.socket.tcp!
when "luasocket"
luasocket.tcp!
when "cqueues"
require("pgmoon.cqueues").CqueuesSocket!
else
error "unknown socket type: #{socket_type}"
socket, socket_type
}
| 22.122222 | 74 | 0.512305 |
e7fd5e52b291be895daed26a303005194f01ea6e | 1,196 | #!amulet
local *
friction = 10
delta = 32 + friction
max = vec2 512, 512
applyFriction = =>
if @ > 0
@ -= friction
@ = 0 if @ < 0
if @ < 0
@ += friction
@ = 0 if @ > 0
@
applyBoards = (win) =>
x, y = @x, @y
with win
x = .right if x < .left
x = .left if x > .right
y = .bottom if y > .top
y = .top if y < .bottom
vec2 x, y
class Player
pos: vec2 0
speed: vec2 0
new: (win) =>
@win = win
connect: (translate) =>
translate.position2d = @pos
update: (dt) =>
with @win
dx, dy = @speed.x, @speed.y
mouse = \mouse_delta! * delta
if mouse != vec2 0
dx += mouse.x
dy += mouse.y
else
dx -= delta if \key_down"left"
dx += delta if \key_down"right"
dy += delta if \key_down"up" or \key_down"rshift"
dy -= delta if \key_down"down"
dx = applyFriction dx
dy = applyFriction dy
@speed = math.clamp vec2(dx, dy), -max, max
@pos += @speed * dt
@pos = applyBoards @pos, @win
| 20.62069 | 65 | 0.442308 |
902776f247ad6d1b3c45381d2fe5ed5413eb545c | 1,059 | export ^
class OptionEntry
new: (@name = "NONAME") =>
@value = nil
options[@name] = @value
getStringValue: =>
return if @value == nil then "" else "" .. @value
action: =>
options[@name] = @value
class OptionBoolEntry extends OptionEntry
new: (name, default) =>
super(name)
@value = default
options[@name] = @value
getStringValue: =>
return if @value then "TRUE" else "FALSE"
action: =>
@value = not @value
options[@name] = @value
class OptionNumberEntry extends OptionEntry
new: (name, default, @max, @min=0) =>
super(name)
assert min <= default and default <= max, "Wrong bounds and/or default value: #{min} <= #{default} <= #{max}"
@value = default
options[@name] = @value
action: =>
@value += 1
if @value > @max
@value = @min
options[@name] = @value
class OptionExitEntry extends OptionEntry
new: =>
super("Back")
action: =>
statestack\pop()
| 23.021739 | 117 | 0.542965 |
81644e9afa5b0e2f8b86e29a10d587ac0070d750 | 4,413 | append = table.insert
line_to_rule = (line) ->
pattern = line.stripped
-- our answer status, with negation handling
status = true
if pattern\sub(1, 1) == '!'
pattern = pattern\sub(2)
status = false
-- escape pattern matching sensitive characters. we can't really use the
-- ordinary regex escape function here since we need to handle asterisks
-- ourselves below
pattern = pattern\gsub '[]\\.[+^$(){}]', (c) -> "\\#{c}"
-- normalize ignore pattern escapes
pattern = pattern\gsub '\\\\(.)', (c) -> c
if pattern\find('/', 2, true) -- non-leading separator included, sub path spec
-- handle globs correctly
pattern = pattern\gsub '%*+', (glob) ->
#glob == 1 and '[^/]*' or glob
if pattern\ends_with('/**')
pattern = "#{pattern\sub(1, -3)}.+"
if pattern\find('/**/', 1, true)
pattern = pattern\gsub('/%*%*/', '/([^/]+/)*')
if pattern\starts_with('**/')
pattern = ".*(^|/)#{pattern\sub(4)}"
else
-- remove any leading slash
if pattern\sub(1, 1) == '/'
pattern = pattern\sub(2)
pattern = "^#{pattern}"
else -- shell glob or plain
pattern = pattern\gsub '%*+', (glob) ->
#glob == 1 and '.*' or glob\gsub('%*', '\\*')
-- leading slash = anchor rest at first level
if pattern\sub(1, 1) == '/'
pattern = "^#{pattern\sub(2)}"
else -- beginning or in sub dir
pattern = "(^|/)#{pattern}"
pattern: r("#{pattern}/?$"), :status, :line
load_rules = (file) ->
content = file.contents
irrelevant = (line) -> line.is_blank or line\match '^%s*#'
lines = [l for l in content\gmatch '[^\r\n]+' when not irrelevant(l)]
[line_to_rule(l) for l in *lines]
matcher = (dir, file) ->
return nil unless file.exists
rules = load_rules(file)
f_dir = file.parent
path_mod = if dir == f_dir
nil
elseif dir\is_below(f_dir)
relative = dir\relative_to_parent(f_dir)
(p) -> "#{relative}/#{p}"
elseif f_dir\is_below(dir)
relative = f_dir\relative_to_parent(dir)
(p) -> p\gsub("^#{relative}/", '')
else
error "ignore file '#{file}' outside of matching scope '#{dir}'"
(path) ->
path = path_mod(path) if path_mod
-- we match rules in reverse order, since the last match takes precedence
for i = #rules, 1, -1
rule = rules[i]
if rule.pattern\test(path)
return rule.status and 'reject' or 'allow'
eval_matchers = (matchers, path) ->
for m in *matchers
ret = m path
if ret == 'allow'
return false
if ret == 'reject'
return true
nil
class Evaluator
new: (@dir, opts) =>
@root_matchers = {}
@matcher_cache = {}
@ignore_files = opts.ignore_files or {'.ignore', '.gitignore'}
-- add ignores for the root and parents
d = dir
while d
for f in *@ignore_files
file = d\join(f)
if file.exists
m = matcher(dir, file)
@root_matchers[#@root_matchers + 1] = m
@matcher_cache[file.parent.path] = m
d = d.parent
reject: (path) =>
sub_matchers = @_get_sub_matchers path
res = eval_matchers sub_matchers, path
return res if res != nil
res = eval_matchers @root_matchers, path
res != nil and res or false
_get_sub_matchers: (path) =>
-- get any sub-ignore files for the path
dir = path\match '(.+)/[^/]+$'
return {} unless dir
dir_matchers = @matcher_cache[dir]
return dir_matchers if dir_matchers
matchers = {}
d = dir
while d
dir_matchers = @matcher_cache[d]
if dir_matchers
if #matchers > 0
for m in *dir_matchers
append matchers, m
else
matchers = dir_matchers
break
else
for f in *@ignore_files
file = @dir\join(d, f)
m = matcher(@dir, file)
if m
append matchers, m
@matcher_cache[file.path] = m
d = d\match '(.+)/[^/]+$'
@matcher_cache[dir] = matchers
matchers
setmetatable {
evaluator: (dir, opts = {}) ->
eval = Evaluator dir, opts
(path) -> eval\reject path
}, {
-- ignore_file(file [, dir])
__call: (file, dir = nil) =>
unless file.exists
error "#{file} does not exist"
dir or= file.parent
matchers = { matcher(dir, file) }
setmetatable {
:file
:dir
}, __call: (path) =>
res = eval_matchers matchers, path
res and true or false
}
| 25.958824 | 80 | 0.575119 |
beb79d6777445b510cd6880d8bc74d6567256132 | 1,078 |
do
{a, b} = hello
{{a}, b, {c}} = hello
{ :hello, :world } = value
do
{ yes: no, thing } = world
{:a,:b,:c,:d} = yeah
{a} = one, two
{b}, c = one
{d}, e = one, two
x, {y} = one, two
xx, yy = 1, 2
{yy, xx} = {xx, yy}
{a, :b, c, :d, e, :f, g} = tbl
---
do
futurists =
sculptor: "Umberto Boccioni"
painter: "Vladimir Burliuk"
poet:
name: "F.T. Marinetti"
address: {
"Via Roma 42R"
"Bellagio, Italy 22021"
}
{poet: {:name, address: {street, city}}} = futurists
--
do
{ @world } = x
{ a.b, c.y, func!.z } = x
{ world: @world } = x
--
do
thing = {{1,2}, {3,4}}
for {x,y} in *thing
print x,y
--
do
with {a,b} = thing
print a, b
--
do
thing = nil
if {a} = thing
print a
else
print "nothing"
thang = {1,2}
if {a,b} = thang
print a,b
if {a,b} = thing
print a,b
elseif {c,d} = thang
print c,d
else
print "NO"
--
do
z = "yeah"
{a,b,c} = z
do
{a,b,c} = z
(z) ->
{a,b,c} = z
do
z = "oo"
(k) ->
{a,b,c} = z
| 10.673267 | 54 | 0.439703 |
b94fed6c972abef72f9a56d478e755701801aba7 | 352 | import Widget from require "lapis.html"
class Remove extends Widget
content: =>
form method: "POST", action: @url_for("remove2", token: @token), ->
element "table", ->
tr ->
td -> input name: "password", type: "password", size: 20
td -> p "Password (required)"
input type: "submit", value: "Remove pasta"
| 32 | 71 | 0.590909 |
bd1272e9834652039772aa88a167248298faeed8 | 1,552 | ----
-- A list class that wraps a table
-- @classmod List
import insert,concat,remove from table
class List
--- constructor passed a table `t`, which can be `nil`.
new: (t) =>
@ls = t or {}
--- append to list.
add: (item) =>
insert @ls,item
--- insert `item` at `idx`
insert: (idx,item) =>
insert @ls,idx,item
--- remove item at `idx`
remove: (idx) => remove @ls,idx
--- length of list
len: => #@ls
--- string representation
__tostring: => '['..(concat @ls,',')..']'
--- return idx of first occurence of `item`
find: (item) =>
for i = 1,#@ls
if @ls[i] == item then return i
--- remove item by value
remove_value: (item) =>
idx = self\find item
self\remove idx if idx
--- remove a list of items
remove_values: (items) =>
for item in *items do self\remove_value item
--- create a sublist of items indexed by a table `indexes`
index_by: (indexes) =>
List [@ls[idx] for idx in *indexes]
--- make a copy of this list
copy: => List [v for v in *@ls]
--- append items from the table or list `list`
extend: (list) =>
other = if list.__class == List then list.ls else list
for v in *other do self\add v
self
--- concatenate two lists, giving a new list
__concat: (l1,l2) -> l1\copy!\extend l2
--- an iterator over all items
iter: =>
i,t,n = 0,@ls,#@ls
->
i += 1
if i <= n then t[i]
return List
| 23.515152 | 62 | 0.537371 |
4b5e09d5eaa2fed44cee69175de96839b0d3a872 | 25,543 | etlua = require 'etlua'
lyaml = require 'lyaml'
stringy = require 'stringy'
import http_get from require 'lib.http_client'
import web_sanitize from require 'web_sanitize'
import aql, document_get from require 'lib.arango'
import encode_with_secret from require 'lapis.util.encoding'
import from_json, to_json, trim, unescape from require 'lapis.util'
import table_deep_merge, to_timestamp, get_nested from require 'lib.utils'
--------------------------------------------------------------------------------
splat_to_table = (splat, sep = '/') -> { k, v for k, v in splat\gmatch "#{sep}?(.-)#{sep}([^#{sep}]+)#{sep}?" }
--------------------------------------------------------------------------------
escape_pattern = (text) ->
str, _ = tostring(text)\gsub('([%[%]%(%)%+%-%*%%])', '%%%1')
str
--------------------------------------------------------------------------------
check_git_layout = (db_name, slug, key) ->
layout = { _key: key, html: "@raw_yield@yield" }
ret = ngx.location.capture("/git/#{db_name}/app/layouts/#{slug}/index.html")
if ret.status == 200
layout.found = true
layout.html = ret.body
layout._key = slug
ret = ngx.location.capture("/git/#{db_name}/app/layouts/#{slug}/settings.yml")
if ret.status == 200
page_settings = lyaml.load(ret.body)
layout.page_builder = page_settings.builder
ret = ngx.location.capture("/git/#{db_name}/app/layouts/#{slug}/vendor.js")
layout.i_js = ret.body if ret.status == 200
ret = ngx.location.capture("/git/#{db_name}/app/layouts/#{slug}/vendor.css")
layout.i_css = ret.body if ret.status == 200
ret = ngx.location.capture("/git/#{db_name}/app/layouts/#{slug}/css.css")
layout.scss = ret.body if ret.status == 200
ret = ngx.location.capture("/git/#{db_name}/app/layouts/#{slug}/js.js")
layout.javascript = ret.body if ret.status == 200
layout
--------------------------------------------------------------------------------
prepare_assets = (html, layout, params) ->
html = "@raw_yield" unless html
js_vendor_hmac = stringy.split(encode_with_secret(layout.i_js, ''), '.')[2]\gsub('/', '-')
css_vendor_hmac = stringy.split(encode_with_secret(layout.i_css, ''), '.')[2]\gsub('/', '-')
jshmac = stringy.split(encode_with_secret(layout.javascript, ''), '.')[2]\gsub('/', '-')
csshmac = stringy.split(encode_with_secret(layout.scss, ''), '.')[2]\gsub('/', '-')
html = html\gsub('@js_vendors', "/#{params.lang}/#{layout._key}/vendors/#{js_vendor_hmac}.js")
html = html\gsub('@js', "/#{params.lang}/#{layout._key}/js/#{jshmac}.js")
html = html\gsub('@css_vendors', "/#{params.lang}/#{layout._key}/vendors/#{css_vendor_hmac}.css")
html = html\gsub('@css', "/#{params.lang}/#{layout._key}/css/#{csshmac}.css")
html = html\gsub(escape_pattern('/*css*/'), escape_pattern(layout.compiled_css)) if layout.compiled_css
html
--------------------------------------------------------------------------------
prepare_headers = (html, data, params) ->
headers = "<title>#{data.item.name}</title>"
if(data.item.og_title and data.item.og_title[params.lang])
headers = "<title>#{data.item.og_title[params.lang]}</title>"
if(data.item.description and data.item.description[params.lang])
headers ..= "<meta name=\"description\" content=\"#{data.item.description[params.lang]}\" />"
if(data.item.og_title and data.item.og_title[params.lang])
headers ..= "<meta property=\"og:title\" content=\"#{data.item.og_title[params.lang]}\" />"
if(data.item.og_img and data.item.og_img[params.lang])
headers ..= "<meta property=\"og:image\" content=\"#{data.item.og_img[params.lang]}\" />"
if(data.item.og_type and data.item.og_type[params.lang])
headers ..= "<meta property=\"og:type\" content=\"#{data.item.og_type[params.lang]}\" />"
if(data.item.canonical and data.item.canonical[params.lang])
headers ..= "<link rel=\"canonical\" href=\"#{data.item.canonical[params.lang]}\" />"
headers ..= "<meta property=\"og:url\" content=\"#{data.item.canonical[params.lang]}\" />"
html = prepare_assets(html, data.layout, params)
html\gsub('@headers', headers)
--------------------------------------------------------------------------------
etlua2html = (json, partial, params, global_data) ->
template = global_data.partials[partial.item._key]
if template == nil
template = etlua.compile(partial.item.html)
global_data.partials[partial.item._key] = template
_, data = pcall(
template, {
'dataset': json, 'to_json': to_json, 'web_sanitize': web_sanitize,
'lang': params.lang, 'params': params, 'to_timestamp': to_timestamp,
'settings': from_json(global_data.settings[1].home),
'stringy': stringy
}
)
data
--------------------------------------------------------------------------------
load_document_by_slug = (db_name, slug, object, ext = 'html') ->
ret = ngx.location.capture("/git/#{db_name}/app/#{object}/#{slug}.#{ext}")
if ret.status == 200
{
item: {
html: ret.body, _key: "#{slug}",
_rev: ret.header.ETag\gsub('"', '')\gsub("-", "")
}
}
else
request = "FOR item IN #{object} FILTER item.slug == @slug RETURN { item }"
aql(db_name, request, { slug: slug })[1]
--------------------------------------------------------------------------------
load_page_by_slug = (db_name, slug, lang, uselayout = true) ->
request = "FOR item IN pages FILTER item.slug[@lang] == @slug RETURN { item }"
page = aql(db_name, request, { slug: slug, lang: lang })[1]
if page
publication = document_get(db_name, 'publications/pages_' .. page.item._key)
page.item = publication.data if publication.code == 200
ret = ngx.location.capture("/git/#{db_name}/app/pages/#{slug}_#{lang}.html")
page.item.raw_html[lang] = ret.body if ret.status == 200
if uselayout
request = 'FOR layout IN layouts FILTER layout._id == @key RETURN layout'
layout = aql(db_name, request, { key: page.item.layout_id })[1]
if layout
page.layout = layout
layout_name = layout.name
-- then override if it exists on disk
page_settings = {}
ret = ngx.location.capture("/git/#{db_name}/app/pages/#{slug}.yml")
if ret.status == 200
page_settings = lyaml.load(ret.body)
layout_name = page_settings.layout or layout_name
git_layout = check_git_layout(db_name, layout_name, page.layout._key)
page.layout = table_deep_merge(page.layout, git_layout) if git_layout.found
else
page.layout = check_git_layout(db_name, 'page') -- use the default one
else
ret = ngx.location.capture("/git/#{db_name}/app/pages/#{slug}_#{lang}.html")
if ret.status == 200
page = { item: { html: {}, raw_html: {} }, layout: { html: "@raw_yield@yield" } }
page.item.html[lang] = ""
page.item.raw_html[lang] = ret.body
page_settings = {}
ret = ngx.location.capture("/git/#{db_name}/app/pages/#{slug}.yml")
page_settings = lyaml.load(ret.body) if ret.status == 200
page = table_deep_merge(page, page_settings)
if uselayout
page.layout = check_git_layout(db_name, page_settings.layout or 'page')
page
--------------------------------------------------------------------------------
page_info = (db_name, slug, lang) ->
ret = ngx.location.capture("/git/#{db_name}/app/pages/#{slug}.yml")
if ret.status == 200
{ page: lyaml.load(ret.body), folder: {} }
else
request = "
FOR page IN pages FILTER page.slug[@lang] == @slug
LET root = (
FOR folder IN folders
FILTER folder.name == 'Root' AND folder.object_type == 'pages'
RETURN folder
)[0]
FOR folder IN folders
FILTER folder._key == (HAS(page, 'folder_key') ? page.folder_key : root._key)
LET path = (
FOR v, e IN ANY SHORTEST_PATH folder TO root GRAPH 'folderGraph'
FILTER HAS(v, 'ba_login') AND v.ba_login != ''
RETURN v
)[0]
RETURN { page: UNSET(page, 'html'), folder: path == null ? folder : path }"
aql(db_name, request, { slug: slug, lang: lang })[1]
--------------------------------------------------------------------------------
load_dataset_by_slug = (db_name, slug, object, lang, uselayout = true) ->
request = "FOR item IN datasets FILTER item.type == '#{object}' FILTER item.slug == @slug "
request ..= 'RETURN { item }'
dataset = aql(db_name, request, { slug: slug })[1]
if dataset
publication = document_get(db_name, 'publications/' .. object .. '_' .. dataset.item._key)
if publication.code ~= 404 then dataset.item = publication.data
dataset
--------------------------------------------------------------------------------
-- dynamic_page : check all {{ .* }} and load layout
dynamic_page = (db_name, data, params, global_data, history = {}, uselayout = true) ->
html = to_json(data)
if data
page_builder = (data.layout and data.layout.page_builder) or 'page'
page_partial = load_document_by_slug(db_name, page_builder, 'partials')
global_data.page_partial = page_partial
json = data.item.html.json
json = data.item.html[params['lang']].json if data.item.html[params['lang']]
if uselayout
html = prepare_headers(data.layout.html, data, params)
if(data.item.raw_html and type(data.item.raw_html[params['lang']]) == 'string')
html = html\gsub('@raw_yield', escape_pattern(data.item.raw_html[params['lang']]))
else
html = html\gsub('@raw_yield', '')
if(type(json) == 'table' and next(json) ~= nil)
html = html\gsub('@yield', escape_pattern(etlua2html(json, page_partial, params, global_data)))
else
html = etlua2html(json, page_partial, params, global_data)
html = html\gsub('@yield', '')
html = html\gsub('@raw_yield', '')
html
--------------------------------------------------------------------------------
load_redirection = (db_name, params) ->
request = '
FOR r IN redirections
FILTER r.route == @slug
LET spa = (FOR s IN spas FILTER s._id == r.spa_id RETURN s)[0]
LET layout = (FOR l IN layouts FILTER l._id == r.layout_id RETURN l)[0]
RETURN { item: r, spa_name: spa.name, layout }
'
redirection = aql(db_name, request, { slug: params.slug })[1]
if redirection ~= nil then
git_layout = check_git_layout(db_name, params.slug)
redirection.layout = table_deep_merge(
redirection.layout, check_git_layout(db_name, params.slug)
) if git_layout.found
if redirection.item.type_redirection == "spa"
html = redirection.layout.html\gsub(
'@yield',
"<div class='#{redirection.item.class}'>{{ spa | #{redirection.spa_name} }}</div>"
)
html = html\gsub('@raw_yield', '')
prepare_headers(html, redirection, params)
else nil
--------------------------------------------------------------------------------
prepare_bindvars = (splat, aql_request, locale = nil) ->
bindvar = { }
bindvar['page'] = 1 if aql_request\find('@page')
bindvar['limit'] = 20 if aql_request\find('@limit')
bindvar['lang'] = locale if locale and aql_request\find('@lang')
for k, v in pairs(splat) do
v = unescape(tostring(v))
v = tonumber(v) if v\match('^%d+$')
bindvar[k] = v if aql_request\find('@' .. k)
bindvar
--------------------------------------------------------------------------------
dynamic_replace = (db_name, html, global_data, history, params) ->
translations = global_data.trads
aqls = global_data.aqls
helpers = global_data.helpers
splat = {}
splat = splat_to_table(params.splat) if params.splat
app_settings = {}
app_settings = from_json(global_data.settings[1].home) if global_data.settings
-- {{ lang }}
html = html\gsub('{{ lang }}', params.lang)
for widget in string.gmatch(html, '{{.-}}') do
output, action, item, dataset = '', '', '', ''
args, keywords = {}, {}
widget_no_deco, _ = widget\gsub('{{ ', '')\gsub(' }}', '')
table.insert(keywords, trim(k)) for i, k in pairs(stringy.split(widget_no_deco, '|'))
action = keywords[1] if keywords[1]
item = keywords[2] if keywords[2]
dataset = keywords[3] if keywords[3]
args = splat_to_table(keywords[4], '#') if keywords[4]
-- {{ settings | key }}
-- e.g. {{ settings | chatroom_url }}
if action == 'settings' and app_settings[item]
output = app_settings[item]
-- {{ splat | key }}
-- e.g. {{ splat | salon }}
if action == 'splat' and splat[item] then output = splat[item]
-- {{ html | key | field }}
-- {{ html | key }} data will then come from params og_data.json
-- Using og_data reduce http calls
if action == 'html'
if dataset ~= ''
request = 'FOR item IN datasets FILTER item._id == @key '
request ..= 'RETURN item'
object = aql(db_name, request, { key: 'datasets/' .. item })[1]
output = etlua2html(object[dataset].json, global_data.page_partial, params, global_data)
else
if params.og_data
output = etlua2html(params.og_data[item], global_data.page_partial, params, global_data)
-- {{ page | <slug or field> (| <datatype>) }}
-- e.g. {{ page | set_a_slug_here }}
-- e.g. {{ page | slug | posts }}
if action == 'page'
if history[widget] == nil -- prevent stack level too deep
history[widget] = true
page_html = ''
if dataset == ''
page_html = dynamic_page(
db_name,
load_page_by_slug(db_name, unescape(item), params.lang, false),
params, global_data, history, false
)
else
if splat[item] then item = splat[item]
page_html = dynamic_page(
db_name,
load_dataset_by_slug(db_name, unescape(item), dataset, params.lang),
params, global_data, history, false
)
output ..= dynamic_replace(db_name, page_html, global_data, history, params)
-- {{ helper | shortcut }}
-- e.g. {{ helper | hello_world }}
-- e.g. {{ helper | hello_world | args1#true}}
if action == 'helper'
helper = helpers[item]
if helper
dataset = "##{dataset}" if dataset != ''
output = "{{ partial | #{helper.partial} | arango | req##{helper.aql}#{dataset} }}"
output = dynamic_replace(db_name, output, global_data, history, params)
else
print to_json(helpers)
print to_json(item)
output = "Helper not found !?"
-- {{ partial | slug | <dataset> | <args> }}
-- e.g. {{ partial | demo | arango | aql#FOR doc IN pages RETURN doc }}
-- params splat will be used to provide data if arango dataset
if action == 'partial'
partial = load_document_by_slug(db_name, unescape(item), 'partials', 'etlua')
if partial
db_data = { "page": 1 }
if dataset == 'arango'
-- check if it's a stored procedure
aql_request = {}
aql_options = {}
if args['req']
aql_request = aqls[args['req']]
args['aql'] = aql_request\gsub('{{ lang }}', params.lang)
aql_options = from_json(aql_request.options) if aql_request.options and aql_request.options ~= ""
-- prepare the bindvar variable with variable found in the request
-- but also on the parameters sent as args
bindvar = prepare_bindvars(table_deep_merge(splat, args), args['aql'])
-- handle conditions __IF <bindvar> __ .... __END <bindvar>__
-- @bindvar must be present in the request
for str in string.gmatch(args['aql'], '__IF (%w-)__') do
unless splat[str] then
args['aql'] = args['aql']\gsub('__IF ' .. str .. '__.-__END ' .. str .. '__', '')
else
args['aql'] = args['aql']\gsub('__IF ' .. str .. '__', '')
args['aql'] = args['aql']\gsub('__END ' .. str .. '__', '')
-- handle strs __IF_NOT <bindvar> __ .... __END_NOT <bindvar>__
for str in string.gmatch(args['aql'], '__IF_NOT (%w-)__') do
if splat[str] then
args['aql'] = args['aql']\gsub(
'__IF_NOT ' .. str .. '__.-__END_NOT ' .. str .. '__', ''
)
else
args['aql'] = args['aql']\gsub('__IF_NOT ' .. str .. '__', '')
args['aql'] = args['aql']\gsub('__END_NOT ' .. str .. '__', '')
db_data = { results: aql(db_name, args['aql'], bindvar, aql_options) }
db_data = table_deep_merge(db_data, { _params: args })
if dataset == 'rest'
db_data = from_json(http_get(args['url'], args['headers']))
if dataset == 'use_params' or args['use_params']
db_data = table_deep_merge(db_data, { _params: args })
if dataset != 'do_not_eval'
output = etlua2html(db_data, partial, params, global_data)
else
output = partial.item.html
output = dynamic_replace(db_name, output, global_data, history, params)
-- {{ riot | slug(#slug2...) | <mount> || <url> }}
-- e.g. {{ riot | demo | mount }}
-- e.g. {{ riot | demo#demo2 }}
if action == 'riot'
if history[widget] == nil -- prevent stack level too deep
history[widget] = true
data = { ids: {}, revisions: {}, names: {} }
for i, k in pairs(stringy.split(item, '#'))
component = load_document_by_slug(db_name, k, 'components', 'riot').item
table.insert(data.ids, component._key)
table.insert(data.revisions, component._rev)
table.insert(data.names, k)
output ..= "<script src='/#{params.lang}/#{table.concat(data.ids, "-")}/component/#{table.concat(data.revisions, "-")}.tag' type='riot/tag'></script>"
if dataset == 'url'
output = "/#{params.lang}/#{table.concat(data.ids, "-")}/component/#{table.concat(data.revisions, "-")}.tag"
if dataset == 'mount'
output ..= '<script>'
output ..= "document.addEventListener('DOMContentLoaded', function() { riot.mount('#{table.concat(data.names, ", ")}') });"
output ..= "document.addEventListener('turbolinks:load', function() { riot.mount('#{table.concat(data.names, ", ")}') });"
output ..= '</script>'
-- {{ riot4 | slug(#slug2...) | <mount> || <url> }}
-- e.g. {{ riot4| demo | mount }}
-- e.g. {{ riot4 | demo#demo2 }}
if action == 'riot4'
if history[widget] == nil -- prevent stack level too deep
history[widget] = true
data = { ids: {}, revisions: {}, names: {}, js: {} }
output = ''
for i, k in pairs(stringy.split(item, '#'))
name = stringy.split(k, "/")[#stringy.split(k, "/")]
component = load_document_by_slug(db_name, k, 'components', 'js').item
content = component.javascript or component.html
table.insert(data.ids, component._key)
table.insert(data.revisions, component._rev)
table.insert(data.names, k)
table.insert(data.js, content)
if dataset == 'mount'
output ..= '<script type="module">'
output ..= dynamic_replace(db_name, content, global_data, history, params)
output ..= "riot.register('#{name}', #{name});"
output ..= "riot.mount('#{name}')"
output ..='</script>'
if dataset == 'source'
output ..= dynamic_replace(db_name, content, global_data, history, params)
if dataset == 'url'
output = "/#{params.lang}/#{table.concat(data.ids, "-")}/component/#{table.concat(data.revisions, "-")}.js"
if dataset == 'tag'
output = '<script type="module">'
output ..= table.concat(data.js,"\n")
output ..='</script>'
-- {{ spa | slug }} -- display a single page application
-- e.g. {{ spa | account }}
if action == 'spa'
if history[widget] == nil -- prevent stack level too deep
history[widget] = true
spa = load_document_by_slug(db_name, item, 'spas', 'html').item
if spa
spa.js = ngx.location.capture("/git/#{db_name}/app/spas/#{item}.js").body unless spa.js
output = spa.html
output ..="<script>#{spa.js}</script>"
output = dynamic_replace(db_name, output, global_data, {}, params)
-- {{ aql | slug }} -- Run an AQL request
-- e.g. {{ aql | activate_account }}
if action == 'aql'
aql_request = load_document_by_slug(db_name, item, 'aqls', 'aql').item
if aql_request
options = {}
options = from_json(aql_request.options) if aql_request.options
aql(db_name, aql_request.aql, prepare_bindvars(splat, aql_request.aql), options)
output = " "
-- {{ tr | slug (| keys/values | multi#true) }}
-- e.g. {{ tr | my_text }}
-- e.g. with interpolation {{ tr | $(one) $(two) $(three) | one/1/two/2/three/3 }}
-- e.g. with multi {{ tr | You have $(num) items in your cart | num/5 | multi#true }}
if action == 'tr'
output = ""
unless translations[item]
aql(
db_name, 'INSERT { key: @key, value: { @lang: @key }, type: "trads" } IN trads',
{ key: item, lang: params.lang }
)
if args['multi']
aql(
db_name, 'INSERT { key: @key, value: { @lang: @value }, type: "trads" } IN trads',
{ key: item .. " :0:", value: item, lang: params.lang }
)
aql(
db_name, 'INSERT { key: @key, value: { @lang: @value }, type: "trads" } IN trads',
{ key: item .. " :1:", value: item, lang: params.lang }
)
output = item
default_lang = stringy.split(global_data.settings[1].langs, ",")[1]
if translations[item]
output = translations[item][params.lang] or translations[item][default_lang] or ""
if dataset
variables = splat_to_table(dataset)
if args['multi']
_k, v = next(variables) -- check a value
if v == "0"
output = translations[item .. " :0:"][params.lang] or translations[item .. " :0:"][default_lang] or ""
if v == "1"
output = translations[item .. " :1:"][params.lang] or translations[item .. " :1:"][default_lang] or ""
output = output\gsub("%$%((.-)%)", variables)
output = "Missing translation <em style='color:red'>#{item}</em>" if output == ''
-- {{ external | url }}
output = http_get(item) if action == 'external'
-- {{ json | url | field }}
if action == 'json'
output = from_json(http_get(item))
output = output[v] for k, v in pairs(stringy.split(dataset, "."))
-- {{ og_data | name | <default> }}
if action == 'og_data'
output = get_nested(params.og_data, item) if params.og_data
output = dataset if dataset and output == "" or output == nil
-- {{ dataset | key | field | <args> }}
-- {{ dataset | slug=demo | js }}
-- {{ dataset | slug=demo | js | only_url#js }}
if action == 'dataset'
item = stringy.split(item, '=')
request = 'FOR item IN datasets FILTER item.@field == @value RETURN item'
object = aql(db_name, request, { field: item[1], value: item[2] })[1]
if object
if args['only_url']
output = "/#{params.lang}/ds/#{object._key}/#{dataset}/#{object._rev}.#{args['only_url']}"
else
output = object[dataset]
output = dynamic_replace(db_name, output, global_data, history, params)
else output = ' '
-- {{ layout | slug | field }}
-- return from Layout's field
-- slug is layout's slug
-- fields are : js, css, js_vendor, css_vendor
if action == 'layout'
aql_request = 'FOR layout IN layouts FILTER layout.name == @slug RETURN layout'
object = aql(db_name, aql_request, { slug: item })[1]
if object
ret = ngx.location.capture("/git/#{db_name}/app/layouts/#{params.slug}/vendor.js")
object.i_js = ret.body if ret.status == 200
ret = ngx.location.capture("/git/#{db_name}/app/layouts/#{params.slug}/vendor.scss")
object.i_css = ret.body if ret.status == 200
ret = ngx.location.capture("/git/#{db_name}/app/layouts/#{params.slug}/js.js")
object.javascript = ret.body if ret.status == 200
ret = ngx.location.capture("/git/#{db_name}/app/layouts/#{params.slug}/scss.scss")
object.scss = ret.body if ret.status == 200
js_vendor_hmac = stringy.split(encode_with_secret(object.i_js, ''), '.')[2]\gsub('/', '-')
css_vendor_hmac = stringy.split(encode_with_secret(object.i_css, ''), '.')[2]\gsub('/', '-')
jshmac = stringy.split(encode_with_secret(object.javascript, ''), '.')[2]\gsub('/', '-')
csshmac = stringy.split(encode_with_secret(object.scss, ''), '.')[2]\gsub('/', '-')
output = "/#{params.lang}/#{object._key}/vendors/#{js_vendor_hmac}.js" if dataset == 'js_vendor'
output = "/#{params.lang}/#{object._key}/js/#{jshmac}.js" if dataset == 'js'
output = "/#{params.lang}/#{object._key}/vendors/#{css_vendor_hmac}.css" if dataset == 'css_vendor'
output = "/#{params.lang}/#{object._key}/css/#{csshmac}.css" if dataset == 'css'
else output = ' '
html = html\gsub(escape_pattern(widget), escape_pattern(output)) if output ~= ''
html
--------------------------------------------------------------------------------
-- expose methods
{ :splat_to_table, :load_page_by_slug, :dynamic_page, :escape_pattern
:dynamic_replace, :load_redirection, :page_info, :prepare_bindvars } | 45.289007 | 158 | 0.571859 |
d334911c684ea50a93b066ccd9604e5c57d00257 | 63 | cont => random => stop =>
r = <random
(cont r random stop)
| 15.75 | 25 | 0.571429 |
5c40b636dbdebb99f46749080bb8e181f3c9a880 | 1,894 | -- 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'
require 'ljglibs.gtk.widget'
gc_ptr = gobject.gc_ptr
C = ffi.C
jit.off true, true
core.define 'GtkEntry < GtkWidget', {
properties: {
activates_default: 'gboolean'
buffer: 'GtkEntryBuffer*'
caps_lock_warning: 'gboolean'
completion: 'GtkEntryCompletion*'
cursor_position: 'gint'
editable: 'gboolean'
has_frame: 'gboolean'
im_module: 'gchar*'
inner_border: 'GtkBorder*'
invisible_char: 'guint'
invisible_char_set: 'gboolean'
max_length: 'gint'
overwrite_mode: 'gboolean'
placeholder_text: 'gchar*'
primary_icon_activatable: 'gboolean'
primary_icon_gicon: 'GIcon*'
primary_icon_name: 'gchar*'
primary_icon_pixbuf: 'GdkPixbuf*'
primary_icon_sensitive: 'gboolean'
primary_icon_stock: 'gchar*'
primary_icon_storage_type: 'GtkImageType'
primary_icon_tooltip_markup: 'gchar*'
primary_icon_tooltip_text: 'gchar*'
progress_fraction: 'gdouble'
progress_pulse_step: 'gdouble'
scroll_offset: 'gint'
secondary_icon_activatable: 'gboolean'
secondary_icon_gicon: 'GIcon*'
secondary_icon_name: 'gchar*'
secondary_icon_pixbuf: 'GdkPixbuf*'
secondary_icon_sensitive: 'gboolean'
secondary_icon_stock: 'gchar*'
secondary_icon_storage_type: 'GtkImageType'
secondary_icon_tooltip_markup: 'gchar*'
secondary_icon_tooltip_text: 'gchar*'
selection_bound: 'gint'
shadow_type: 'GtkShadowType'
text: 'gchar*'
text_length: 'guint'
truncate_multiline: 'gboolean'
visibility: 'gboolean'
width_chars: 'gint'
xalign: 'gfloat'
}
new: ->
gc_ptr C.gtk_entry_new!
}, (spec) -> spec.new!
| 28.268657 | 79 | 0.712777 |
c5aeada84c3ca80369eb269e95c43bf731fddcd1 | 511 | export lib = require "lib"
love.graphics.setDefaultFilter "nearest", "nearest"
love.graphics.setBackgroundColor 1, 1, 1
lib.gamestate\set "game"
math.lerp = (a, b, t) -> a + (b - a) * t
math.sign = (a) ->
if a < 0
-1
elseif a > 1
1
else
0
with love
.load = -> lib.gamestate\load!
.update = (dt) -> lib.gamestate\update dt
.draw = -> lib.gamestate\draw!
.keypressed = (key) -> lib.gamestate\press key
.keyreleased = (key) -> lib.gamestate\release key | 18.925926 | 51 | 0.589041 |
0f17d7355746564ed5f89a4af5f81927c83c4cf2 | 623 |
extend = (a, ...) ->
for t in *{...}
if t
a[k] = v for k,v in pairs t
a
upper_keys = (t) ->
if t
{ type(k) == "string" and k\upper! or k, v for k,v in pairs t }
strip_numeric = (t) ->
for k,v in ipairs t
t[k] = nil
t
valid_amount = (str) ->
return true if str\match "%d+%.%d%d"
nil, "invalid amount (#{str})"
format_price = (cents, currency="USD") ->
if currency == "JPY"
tostring math.floor cents
else
dollars = math.floor cents / 100
change = "%02d"\format cents % 100
"#{dollars}.#{change}"
{ :extend, :upper_keys, :strip_numeric, :valid_amount, :format_price }
| 20.766667 | 70 | 0.569823 |
4a3573ce280250c6c2f9c835e5e63b5284f12d2b | 310 | describe "the testing environment has environment variables set up", ->
it "has the host variable", ->
assert.truthy os.getenv "OLEG_HOST"
it "has the port variable", ->
assert.truthy os.getenv "OLEG_PORT"
it "has the table name variable", ->
assert.truthy os.getenv "OLEG_TABLE"
| 38.75 | 71 | 0.677419 |
81a68884aaadc957659d80da29fda2afd50c59ce | 3,942 | -- Copyright 2012-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
Gtk = require 'ljglibs.gtk'
Window = Gtk.Window
gobject_signal = require 'ljglibs.gobject.signal'
{:PropertyObject} = howl.util.moon
{:ContentBox} = howl.ui
append = table.insert
class Popup extends PropertyObject
comfort_zone: 10
new: (@child, properties = {}) =>
error('Missing argument #1: child', 3) if not child
@_handlers = {}
@box = ContentBox 'popup', child, {
header: properties.header,
footer: properties.footer
}
properties.default_height = 150 if not properties.default_height
properties.default_width = 150 if not properties.default_width
@window = Window Window.POPUP, properties
@window.app_paintable = true
@_set_alpha!
append @_handlers, @window\on_screen_changed self\_on_screen_changed
append @_handlers, @window\on_destroy self\_on_destroy
@window\add @box\to_gobject!
@showing = false
super!
show: (widget, options = position: 'center') =>
error('Missing argument #1: widget', 2) if not widget
@window.transient_for = widget.toplevel
@window.destroy_with_parent = true
@window\realize!
@widget = widget
@showing = true
if options.x
@window.window_position = Gtk.WIN_POS_NONE
@move_to options.x, options.y
else
@center!
@window\show_all!
close: =>
@window\hide!
@showing = false
@widget = nil
destroy: =>
@window\destroy!
move_to: (x, y) =>
error('Attempt to move a closed popup', 2) if not @showing
w_x, w_y = @widget.toplevel.window\get_position!
t_x, t_y = @widget\translate_coordinates(@widget.toplevel, x, y)
x = w_x + t_x
y = w_y + t_y
@x, @y = x, y
@window\move x, y
@resize @window.allocated_width, @window.allocated_height
resize: (width, height) =>
if not @showing
@window.default_width = width
@window.default_height = height
return
screen = @widget.screen
if @x + width > (screen.width - @comfort_zone)
width = screen.width - @x - @comfort_zone
if @y + height > (screen.height - @comfort_zone)
height = screen.height - @y - @comfort_zone
@width, @height = width, height
@window\set_size_request width, height
@window\resize width, height
center: =>
error('Attempt to center a closed popup', 2) if not @showing
height = @height
width = @width
-- now, if we were to center ourselves on the widgets toplevel,
-- with our current width and height..
screen = @widget.screen
toplevel = @widget.toplevel
w_x, w_y = toplevel.window\get_position!
w_width, w_height = toplevel.allocated_width, toplevel.allocated_height
win_h_center = w_x + (w_width / 2)
win_v_center = w_y + (w_height / 2)
x = win_h_center - (width / 2)
y = win_v_center - (height / 2)
-- are we outside of the comfort zone horizontally?
if x < @comfort_zone or x + width > (screen.width - @comfort_zone)
-- pull in the stomach
min_outside_h = math.min(w_x, screen.width - (w_x + w_width))
width = (w_width + min_outside_h) - @comfort_zone
x = win_h_center - (width / 2)
-- are we outside of the comfort zone vertically?
if y < @comfort_zone or y + height > (screen.height - @comfort_zone)
-- hunch down
min_outside_v = math.min(w_y, screen.height - (w_y + w_height))
height = (w_height + min_outside_v) - @comfort_zone
y = win_v_center - (height / 2)
-- now it's all good
@resize width, height
@window\move x, y
_set_alpha: =>
screen = @window.screen
if screen.is_composited
visual = screen.rgba_visual
@window.visual = visual if visual
_on_screen_changed: =>
@_set_alpha!
_on_destroy: =>
-- disconnect signal handlers
for h in *@_handlers
gobject_signal.disconnect h
return Popup
| 27.957447 | 79 | 0.657534 |
08818c262cb0b10d3032f617f6345955318a6be5 | 6,779 | url = require "socket.url"
lapis_config = require "lapis.config"
session = require "lapis.session"
import html_writer from require "lapis.html"
import increment_perf from require "lapis.nginx.context"
import parse_cookie_string, to_json, build_url, auto_table from require "lapis.util"
import insert from table
get_time = (config) ->
if ngx
ngx.update_time!
ngx.now!
elseif config.server == "cqueues"
require("cqueues").monotime!
class Request
@__inherited: (child) =>
-- add inheritance to support methods
if support = rawget child, "support"
return if getmetatable support
setmetatable support, {
__index: @support
}
-- these are like methods but we don't put them on the request object so they
-- don't take up names that someone might use
@support: {
default_url_params: =>
parsed = { k,v for k,v in pairs @req.parsed_url }
parsed.query = nil
parsed
load_cookies: =>
@cookies = auto_table ->
cookie = @req.headers.cookie
if type(cookie) == "table"
out = {}
for str in *cookie
for k,v in pairs parse_cookie_string str
out[k] = v
out
else
parse_cookie_string cookie
load_session: =>
@session = session.lazy_session @
-- write what is in @options and @buffer into the output
-- this is called once, and done last
render: =>
if @options.skip_render
return
@@support.write_session @
@@support.write_cookies @
if @options.status
@res.status = @options.status
if @options.headers
for k,v in pairs @options.headers
@res\add_header k, v
if @options.json != nil
@res.headers["Content-Type"] = @options.content_type or "application/json"
@res.content = to_json @options.json
return
if ct = @options.content_type
@res.headers["Content-Type"] = ct
if not @res.headers["Content-Type"]
@res.headers["Content-Type"] = "text/html"
if redirect_url = @options.redirect_to
if redirect_url\match "^/"
redirect_url = @build_url redirect_url
@res\add_header "Location", redirect_url
@res.status or= 302
return
layout = if @options.layout != nil
@options.layout
else
@app.layout
@layout_opts = if layout
{ _content_for_inner: nil }
widget = @options.render
widget = @route_name if widget == true
config = lapis_config.get!
if widget
if type(widget) == "string"
widget = require "#{@app.views_prefix}.#{widget}"
start_time = if config.measure_performance
get_time config
view = widget!
@layout_opts.view_widget = view if @layout_opts
view\include_helper @
@write view
if start_time
t = get_time config
increment_perf "view_time", t - start_time
if layout
inner = @buffer
@buffer = {}
layout_cls = if type(layout) == "string"
require "#{@app.views_prefix}.#{layout}"
else
layout
start_time = if config.measure_performance
get_time config
@layout_opts._content_for_inner or= -> raw inner
layout = layout_cls @layout_opts
layout\include_helper @
layout\render @buffer
if start_time
t = get_time config
increment_perf "layout_time", t - start_time
if next @buffer
content = table.concat @buffer
@res.content = if @res.content
@res.content .. content
else
content
write_session: session.write_session
write_cookies: =>
return unless next @cookies
for k,v in pairs @cookies
cookie = "#{url.escape k}=#{url.escape v}"
if extra = @app.cookie_attributes @, k, v
cookie ..= "; " .. extra
@res\add_header "Set-Cookie", cookie
add_params: (params, name) =>
if name
@[name] = params
for k,v in pairs params
-- expand nested[param][keys]
front = k\match "^([^%[]+)%[" if type(k) == "string"
if front
curr = @params
has_nesting = false
for match in k\gmatch "%[([^%]]+)%]"
has_nesting = true
new = curr[front]
if type(new) != "table"
new = {}
curr[front] = new
curr = new
front = match
if has_nesting
curr[front] = v
else
-- couldn't parse valid nesting, just bail
@params[k] = v
else
@params[k] = v
}
new: (@app, @req, @res) =>
@buffer = {} -- output buffer
@params = {}
@options = {}
@@support.load_cookies @
@@support.load_session @
flow: (flow) =>
key = "_flow_#{flow}"
unless @[key]
@[key] = require("#{@app.flows_prefix}.#{flow}") @
@[key]
html: (fn) => html_writer fn
url_for: (first, ...) =>
if type(first) == "table"
@app.router\url_for first\url_params @, ...
else
@app.router\url_for first, ...
-- @build_url! --> http://example.com:8080
-- @build_url "hello_world" --> http://example.com:8080/hello_world
-- @build_url "hello_world?color=blue" --> http://example.com:8080/hello_world?color=blue
-- @build_url "cats", host: "leafo.net", port: 2000 --> http://leafo.net:2000/cats
-- Where example.com is the host of the request, and 8080 is current port
build_url: (path, options) =>
return path if path and (path\match("^%a+:") or path\match "^//")
parsed = @@support.default_url_params @
if path
_path, query = path\match("^(.-)%?(.*)$")
path = _path or path
parsed.query = query
parsed.path = path
scheme = parsed.scheme or "http"
if scheme == "http" and (parsed.port == "80" or parsed.port == 80)
parsed.port = nil
if scheme == "https" and (parsed.port == "443" or parsed.port == 443)
parsed.port = nil
if options
for k,v in pairs options
parsed[k] = v
build_url parsed
write: (thing, ...) =>
t = type(thing)
-- is it callable?
if t == "table"
mt = getmetatable(thing)
if mt and mt.__call
t = "function"
switch t
when "string"
insert @buffer, thing
when "table"
-- see if there are options
for k,v in pairs thing
if type(k) == "string"
@options[k] = v
else
@write v
when "function"
@write thing @buffer
when "nil"
nil -- ignore
else
error "Don't know how to write: (#{t}) #{thing}"
@write ... if ...
| 25.200743 | 91 | 0.565865 |
d19f315b35c52358b7d6238c9ad5aea833bd60d7 | 2,940 | lapis = require "lapis"
import respond_to from require "lapis.application"
import from_json, unescape from require "lapis.util"
class extends lapis.Application
'/test': respond_to {
GET: =>
{'status': 200}
}
'/health': respond_to {
GET: =>
library.response(redis.test())
}
'/flush': respond_to {
DELETE: =>
library.response(redis.flush())
}
'/orphans': respond_to {
GET: =>
library.response(redis.orphans())
DELETE: =>
library.response(redis.delete_batch_data(redis.orphans()['data']))
}
'/batch': respond_to {
before: =>
for k,v in pairs @req.params_post do
@json_body = from_json(k)
POST: =>
return library.response(status: 400, msg: "Missing json body") unless @json_body
library.response(redis.save_batch_data(@json_body, false))
PUT: =>
return library.response(status: 400, msg: "Missing json body") unless @json_body
library.response(redis.save_batch_data(@json_body, true))
DELETE: =>
return library.response(status: 400, msg: "Missing json body") unless @json_body
library.response(redis.delete_batch_data(@json_body))
}
'/frontends': respond_to {
GET: =>
library.response(redis.get_data('frontends', nil))
}
'/backends': respond_to {
GET: =>
library.response(redis.get_data('backends', nil))
}
'/:type/:name': respond_to {
GET: =>
library.response(redis.get_data(@params.type, unescape(@params.name)))
DELETE: =>
library.response(redis.delete_data(@params.type, unescape(@params.name)))
}
'/backends/:name/config/:config': respond_to {
GET: =>
library.response(redis.get_config(unescape(@params.name), unescape(@params.config)))
DELETE: =>
library.response(redis.delete_config(unescape(@params.name), unescape(@params.config)))
}
'/backends/:name/config/:config/:value': respond_to {
PUT: =>
library.response(redis.set_config(unescape(@params.name), unescape(@params.config), unescape(@params.value)))
}
'/backends/:name/:value/score/:score': respond_to {
PUT: =>
library.response(redis.save_data('backends', unescape(@params.name), unescape(@params.value), unescape(@params.score), false))
}
'/:type/:name/:value': respond_to {
POST: =>
library.response(redis.save_data(@params.type, unescape(@params.name), unescape(@params.value), 0, false))
PUT: =>
library.response(redis.save_data(@params.type, unescape(@params.name), unescape(@params.value), 0, true))
DELETE: =>
library.response(redis.delete_data(@params.type, unescape(@params.name), unescape(@params.value)))
}
| 34.588235 | 138 | 0.596939 |
0b83e96aa1cb2aa63494e1c768a5ddb7033831f2 | 1,057 | import sin, floor from math
death = {}
death.textTop = "YOU"
death.textBottom = "\nDIED"
death.height = 32
death.y = death.height
move = ->
flux.to(death, 0.48, {y: death.height + 16 })\ease("cubicin")\oncomplete(->
flux.to(death, 0.48, {y: death.height})\ease("cubicout")\oncomplete(move)
)
move!
textCentered = (s, font, y) ->
x = gameWidth / 2 - font\getWidth(s) / 2
love.graphics.setFont font
love.graphics.print(s, x, y)
text = (s, font, y) ->
love.graphics.setFont font
love.graphics.print(s, 0, y)
death.update = (dt) =>
flux.update dt
death.draw = () =>
-- draw the level
push\start!
textCentered @textTop, fontFantasy, floor(@y)
textCentered @textBottom, fontFantasy, floor(@y)
textCentered "YOUR DEPTH BEFORE DYING WAS #{depth}", fontRetro, screenHeight - 64
textCentered "PRESS ANY KEY TO CONTINUE", fontRetro, screenHeight - 48
push\finish!
death.keypressed = (key) =>
if key == "f"
push\switchFullscreen(windowedWidth, windowedHeight)
else
manager\enter states.title, false
return death | 24.581395 | 83 | 0.674551 |
fc79ca7c138f46d2186b152cd6af26943904fe2b | 14,588 | --- IRC client class
-- @classmod IRCClient
re = require "re"
socket = require 'cqueues.socket'
Logger = require 'logger'
moonscript = {
errors: require 'moonscript.errors'
}
escapers = {['s']: ' ', ['r']: '\r', ['n']: '\n', [';']: ';'}
local IRCClient, ContextTable, priority
priority = {
HIGH: 1,
DEFAULT: 2,
LOW: 3,
}
class ContextTable
-- ::TODO:: allow for multiple *and* index
get: (name, opts = {})=>
:multiple, :index, :uses_priority = opts
multiple = true if multiple == nil
uses_priority = true if uses_priority == nil
local output
output = {} if multiple
for context, items in pairs(self)
-- context
if multiple
-- add all that exist
if uses_priority
for p=priority.HIGH, priority.LOW
if items[p][name]
for element in *items[p][name]
table.insert output, element
else
if items[name]
for element in *items[name]
table.insert output, element
else
-- return the singular if it exists
if uses_priority
for p=priority.HIGH, priority.LOW
return items[p][name] if items[p][name] ~= nil
else
return items[name] if items[name] ~= nil
if multiple
output
elseif index
index\get name, :multiple, :uses_priority
remove: (name)=>
for context_name, tbl in pairs(self)
tbl[name] = nil
class IRCClient
commands: ContextTable!
hooks: ContextTable!
handlers: ContextTable!
senders: ContextTable!
__tostring: => "IRCClient"
default_config = {
prefix: "!"
}
line_pattern = re.compile [[
-- tags, command, args
line <- {|
{:tags: {| (tags sp)? |} :}
{:prefix: {| (prefix sp)? |} :}
{:command: (command / numeric) :}
{:args: {| (sp arg)* |} :} |}
tags <- '@' tag (';' tag)*
tag <- {|
{:is_client: {'+'} :}? -- check: if tag.is_client
{:vendor: {[^/]+} '/' :}?
{:key: {[^=; ]+} -> esc_tag :}
{:value: ('=' {[^; ]*} -> esc_tag) :}?
|}
prefix <- ':' (
{:nick: {[^ !]+} :} '!'
{:user: {[^ @]+} :} '@'
{:host: {[^ ]+} :} /
{:nick: {[^ ]+} :})
command <- [A-Za-z]+
numeric <- %d^+3^-4 -- at most four digits, at least three
arg <- ':' {.+} / {[^ ]+}
sp <- %s
]], esc_tag: (tag)-> tag\gsub "\\(.)", setmetatable({
[":"]: ";"
s: " "
r: "\r"
n: "\n"
}, __index: (t, k) -> k)
--- Get a tag based on search parameters (is_client IS NOT matched by key)
-- @tparam table tags Tag from IRC parser
-- @tparam table opts Options to search for (is_client: bool, key: string)
get_tag: (tags, opts)=>
:is_client, :key = opts
for tag in *tags
continue if is_client ~= nil and tag.is_client ~= is_client
if key ~= nil
continue if tag.vendor ~= nil and key ~= "#{tag.vendor}/#{tag.key}"
continue if tag.vendor == nil and key ~= tag.key
return tag
return {}
--- Generate a new IRCClient
-- @tparam string server IRC server name
-- @tparam number port IRC port number
-- @tparam table config Default configuration
new: (server, port=6697, config)=>
assert server
@config = :server, :port, :config, ssl: port == 6697
for k, v in pairs default_config
@config[k] = v
if config
for k, v in pairs config
@config[k] = v
@commands = ContextTable!
@hooks = ContextTable!
@handlers = ContextTable!
@senders = ContextTable!
@server = {}
unpack = unpack or table.unpack
get_priority = (options, fn)->
return fn and options.priority or priority.DEFAULT
handle_options: (options, fn)=>
unless fn
fn = options
options = {}
if options.async
return (...)->
args = {...}
require("queue")\wrap ->
@pcall_bare fn, unpack args
if options.wrap_iter
tmp_fn = coroutine.wrap fn
tmp_fn!
return tmp_fn
fn
assert_context: (context_table)=>
assert @context, "Missing @with_context"
return context_table[assert @context, "Missing @with_context"]
--- Change the module context for the current command
-- @tparam string context module context (typically, the name)
-- @tparam function fn code to run under context
with_context: (context, fn)=>
assert @context == nil, "Already in context: #{@context}"
@context = context
self["senders"][context] = {} -- no priority for senders, only one
for key in *{"hooks", "handlers", "commands"}
self[key][context] = [{} for p=priority.HIGH, priority.LOW]
fn self, context
@context = nil
--- Add an IRC bot command
-- @tparam string name Bot command name
-- @tparam table options [Optional] async: bool, wraps in cqueues
-- @tparam function command Function for handling command
add_command: (name, options, command)=>
final_command = command
commands = @assert_context @commands
-- `options` is passed, which fills in `command`
if command
-- is async, send typing until completed
if options.async
-- async, send @+draft/typing
final_command = (prefix, target, line, ...)=>
@vars.typing_counter = 0 if not @vars.typing_counter
@vars.typing_counter += 1
@send 'TAGMSG', target, "+draft/typing": 'active'
@pcall command, prefix, target, line, ...
@vars.typing_counter -= 1
print @vars.typing_counter
if @vars.typing_counter == 0
@send 'TAGMSG', target, "+draft/typing": 'done'
else
@send 'TAGMSG', target, "+draft/typing": 'active'
p = get_priority options, final_command
commands[p][name] = @handle_options options, final_command
--- Add a client processing hook
-- @tparam string name Name of event to hook into
-- @tparam table options [Optional] async: bool, wraps in cqueues
-- @tparam function hook Processor for hook event
add_hook: (name, options, hook)=>
hooks = @assert_context @hooks
p = get_priority options, hook
unless hooks[p][name]
hooks[p][name] = {@handle_options options, hook}
else
table.insert hooks[p][name], @handle_options(options, hook)
--- Add an IRC command handler
-- @tparam string id IRC command ID (numerics MUST be strings)
-- @tparam table options [Optional] async: bool, wraps in cqueues
-- @tparam function handler IRC command processor
add_handler: (id, options, handler)=>
handlers = @assert_context @handlers
p = get_priority options, handler
unless handlers[p][id]
handlers[p][id] = {@handle_options options, handler}
else
table.insert hooks[p][name], @handle_options(options, handler)
--- Add an IRC command sending handler, does NOT take a priority
-- @tparam string id IRC command ID ("PRIVMSG", "JOIN", etc.)
-- @tparam table options [Optional] async: bool, wraps in cqueues
-- @tparam function sender Function to handle message to be sent
add_sender: (id, options, sender)=>
senders = @assert_context @senders
senders[id] = @handle_options(options, sender)
--- Reset all modules in the IRCClient
clear_modules: ()=>
@senders = {}
@handlers = {}
@hooks = {}
@commands = {}
--- Connect to the IRC server specified in the configuration
connect: ()=>
if @socket
Logger.debug "Shutting down socket: #{tostring(@socket)}"
@socket\shutdown!
host = @config.server
port = @config.port
ssl = @config.ssl
debug_msg = ('Connecting... {host: "%s", port: "%s"}')\format host, port
@config.nick = 'Moon-Moon' if not @config.nick
@config.username = 'Mooooon' if not @config.username
@config.realname = 'Moon Moon: MoonScript IRC Bot' if not @config.realname
Logger.debug debug_msg, Logger.level.warn .. '--- Connecting...'
@socket = assert socket.connect{:host, :port}
if ssl
Logger.debug 'Starting TLS exchange...'
@socket\starttls!
Logger.debug 'Started TLS exchange'
Logger.print Logger.level.okay .. '--- Connected'
@fire_hook 'CONNECT'
nick = @config.nick
user = @config.username
real = @config.realname
pass = @config.password
Logger.print Logger.level.warn .. '--- Sending authentication data'
@send_raw 'NICK', nick
if pass and ssl
Logger.debug '*** Sending password'
@send_raw 'PASS', pass
elseif pass
Logger.print Logger.level.error .. '*** Not sending password: TLS not enabled ***'
@send_raw 'USER', user, '*', '*', real
debug_msg = ('Sent authentication data: {nickname: %s, username: %s, realname: %s}')\format nick, user, real
Logger.debug debug_msg, Logger.level.okay .. '--- Sent authentication data'
--- Disconnect from the current IRC server
disconnect: ()=>
@socket\shutdown! if @socket
@fire_hook 'DISCONNECT'
tag_escapes = {
";": ":"
" ": "s"
"\r": "r"
"\n": "n"
}
--- Serialize a value for being sent in a tag
serialize_tag_string = (key, value)->
return key if type(value) == "boolean"
return key .. "=" .. value\gsub "([: \r\n])", (value)-> "\\#{tbl[value]}"
--- Serialize client->client tags for sending to the server
-- @param tags Table of tags to serialize
serialize_tags = (tags)->
output = [serialize_tag_string(k, v) for k, v in pairs tags]
return "@#{table.concat output, ';'}"
--- Send a raw line to the currently connected IRC server
-- @param ... List of strings, concatenated using spaces
send_raw: (...)=>
output = {...}
arg_count = select("#", ...)
opts_table = select(arg_count, ...)
if type(opts_table) == "table"
-- we have tags, server accepts tags
if opts_table.tags and next(opts_table.tags) and @server.ircv3_caps["message-tags"]
table.insert output, 1, serialize_tags opts_table.tags
-- remove opts_table regardless of caps
table.remove output, #output
arg_count = #output
if output[arg_count]\find " "
output[arg_count] = ":#{output[arg_count]}"
@socket\write table.concat(output, ' ') .. '\n'
Logger.debug '==> ' .. table.concat output, ' '
--- Send a command using a builtin sender configured with @add_sender
-- @tparam string name Name of sender to use
-- @param ... List of arguments to be passed to sender
-- @see IRCClient\add_sender
send: (name, ...)=>
sender = @senders\get name, multiple: false, index: IRCClient.senders, uses_priority: false
input = sender self, ...
@socket\write input if input
date_pattern: "(%d+)-(%d+)-(%d+)T(%d+):(%d+):(%d+).(%d+)Z"
--- Parse the time of an ISO 8601 compliant string
-- @tparam string date ISO 8601 compliant YYYY-MM-DDThh:mm:ssZ date
-- @treturn number Seconds from Epoch from configured date
parse_time: (date)=>
year, month, day, hour, min, sec, mil = date\match @date_pattern
return os.time(:year, :month, :day, :hour, :min, :sec) + tonumber(mil) / 1000
--- parse an IRC command using line_pattern
parse: (line)=> line_pattern\match line
--- Activate hooks configured for the event name
-- @tparam string hook_name Name of event to "fire"
-- @treturn boolean True if no errors were encountered, false otherwise
-- @treturn table Table containing list of errors from hooks
fire_hook: (hook_name, ...)=>
Logger.debug "#{Logger.level.warn}--- Running hooks for #{hook_name}"
has_run = false
has_errors = false
errors = {}
for _, hook in pairs IRCClient.hooks\get hook_name
has_run = true unless has_run
Logger.debug Logger.level.warn .. '--- Running global hook: ' .. hook_name
ok, err = @pcall hook, ...
if not ok
has_errors = true if not has_errors
table.insert(errors, err)
for _, hook in pairs @hooks\get hook_name
has_run = true unless has_run
Logger.debug Logger.level.warn .. '--- Running hook: ' .. hook_name
ok, err = @pcall hook, ...
if not ok
has_errors = true if not has_errors
table.insert(errors, err)
Logger.debug Logger.level.error .. "*** Hook not found for #{command}" unless has_run
return has_errors, errors, has_run
process_line: (line, opts={})=>
{:tags, :prefix, :command, :args} = @parse line
opts.line = line
@process prefix, command, args, tags, opts
--- Run handlers for an unparsed command
-- @tparam table prefix Prefix argument from server (nick, user, host)
-- @tparam table args Argument list from server, including trailing
-- @tparam table tags Tags list from server
-- @tparam table opts Optional arguments, in_batch: IRCv3 batching
process: (prefix, command, args, tags, opts={})=>
{:in_batch} = opts
{:nick, :user, :host} = prefix
if opts.line
Logger.debug Logger.level.warn .. '--- | Line: ' .. opts.line
Logger.debug Logger.level.okay .. '--- |\\ Running trigger: ' .. Logger.level.warn .. command
if nick and user and host
Logger.debug "#{Logger.level.okay}--- |\\ User: #{nick}!#{user}@#{host}"
elseif nick
Logger.debug "#{Logger.level.okay}--- |\\ Nick: #{nick}"
if #args > 0
Logger.debug "#{Logger.level.okay}--- |\\ Arguments: #{table.concat args, ' '}"
has_run = false
if not in_batch and tags.batch
-- will return _, _, true if a hook run; this is necessary because
-- the protocol might send batches even if we don't support them.
return unless select(2, @fire_hook "BATCH.#{tags.batch}", prefix,
args, tags, opts)
for handler in *IRCClient.handlers\get command
has_run = true unless has_run
@pcall handler, prefix, args, tags, opts
for handler in *@handlers\get command
has_run = true unless has_run
@pcall handler, prefix, args, tags, opts
Logger.debug Logger.level.error .. "*** Handler not found for #{command}" unless has_run
--- Iterate over lines from a server and handle errors appropriately
loop: ()=>
for received_line in @socket\lines! do
@pcall @process_line, received_line, in_batch: false
--- Call a function and, when failed, print debug information
-- @tparam function fn Function to be called
-- @param ... vararg list to pass to function
pcall: (fn, ...)=>
ok, err = xpcall fn, self\log_traceback, self, ...
if not ok
Logger.debug "Arguments:"
for arg in *{...}
Logger.debug tostring arg
return ok, err
--- Call a function without self and, when failed, print debug information
-- @tparam function fn Function to be called
-- @param ... vararg list to pass to function
pcall_bare: (fn, ...)=>
ok, err = xpcall fn, self\log_traceback, ...
if not ok
Logger.debug "Arguments:"
Logger.debug tostring arg for arg in *{...}
return ok, err
--- Print a traceback using the internal logging mechanism
-- @see IRCClient\log
log_traceback: (err)=>
err = tostring err
Logger.debug moonscript.errors.rewrite_traceback debug.traceback!, err
Logger.debug "#{Logger.level.error} ---"
return err
--- Log message from IRC server (used in plugins)
-- @tparam string input Line to print, IRC color formatted
-- @see logger
log: (input)=>
for line in input\gmatch "[^\r\n]+"
Logger.print '\00311(\003' .. (@server.caps and
@server.caps['NETWORK'] or @config.server) ..
"\00311)\003 #{line}"
return {:IRCClient, :priority}
| 31.507559 | 110 | 0.655333 |
a453d26b3d8bf494de4479e9b89f4ff4fdb5f426 | 578 | System = require "lib.concord.system"
Mover = require "src.components.Mover"
Position = require "src.components.Position"
Rotation = require "src.components.Rotation"
filter = {
Mover,
Position,
Rotation
}
RotationalMovement = System filter
RotationalMovement.update = (deltaTime) =>
for _, entity in ipairs self.pool.objects
mover = entity\get Mover
position = entity\get Position
rotation = entity\get Rotation
position.x += math.sin(rotation.angle) * mover.speed * deltaTime
position.y += math.cos(rotation.angle) * mover.speed * deltaTime
RotationalMovement | 27.52381 | 66 | 0.756055 |
57841116dc1f8222f11a0b517e250bdb106cebe6 | 556 | {graphics: lg} = love
class GameOver
enter: (frm, @score) =>
draw: (prev) =>
lg.setColor 255, 255, 255
lg.print "your human side prides itself with a score of #{@score.good}", 20, 100
lg.print "your inner monster has achieved a score of #{@score.bad}", 20, 140
if @score.good > @score.bad
lg.print "you emerge victorious over your inner demons!", 30, 200
else
lg.print "evil has gotten the better of you...", 30, 200
update: (prev, dt) =>
true
keypressed: (prev, key) =>
St8.resume!
true
GameOver!
| 23.166667 | 84 | 0.622302 |
07763fa62cd4321e00b32b55cf16667df688f3cd | 8,902 | import new from require 'buffet.resty'
describe 'receiveuntil() iterator boundary cases:', ->
describe 'with trailer', ->
describe '4 char pattern', ->
index = 0
for input in *{
'deadbeef-++-deadf00d-++-trailer'
{'deadbeef', '-++-', 'deadf00d', '-++-', 'trailer'}
{'deadbee', 'f-++-', 'deadf00d-', '++-trailer'}
{'deadbee', 'f-++', '-deadf00', 'd-++', '-trailer'}
{'dead', 'beef', '-++-', 'dead', 'f00d-++-', 'trailer'}
{'d', 'eadbeef-++-de', 'ad', 'f00d', '-+', '+-', 'trai', 'le', 'r'}
}
index += 1
describe index, ->
it 'read 4 bytes', ->
bf = new input
iter = bf\receiveuntil '-++-'
for {exp_n, exp_data, exp_err, exp_partial} in *{
{1, 'dead'}
{1, 'beef'}
{1, ''}
{3, nil, nil, nil}
{1, 'dead'}
{1, 'f00d'}
{1, ''}
{3, nil, nil, nil}
{1, 'trai'}
{3, nil, 'closed', 'ler'}
{2, nil, 'closed'}
{2, nil, 'closed'}
}
n, data, err, partial = nargs iter 4
assert.are.equal exp_n, n
assert.are.equal exp_data, data
assert.are.equal exp_err, err
assert.are.equal exp_partial, partial
it 'read 3 bytes', ->
bf = new input
iter = bf\receiveuntil '-++-'
for {exp_n, exp_data, exp_err, exp_partial} in *{
{1, 'dea'}
{1, 'dbe'}
{1, 'ef'}
{3, nil, nil, nil}
{1, 'dea'}
{1, 'df0'}
{1, '0d'}
{3, nil, nil, nil}
{1, 'tra'}
{1, 'ile'}
{3, nil, 'closed', 'r'}
{2, nil, 'closed'}
{2, nil, 'closed'}
}
n, data, err, partial = nargs iter 3
assert.are.equal exp_n, n
assert.are.equal exp_data, data
assert.are.equal exp_err, err
assert.are.equal exp_partial, partial
describe '1 char pattern', ->
index = 0
for input in *{
'deadbeef-deadf00d-trailer'
{'deadbeef', '-', 'deadf00d', '-', 'trailer'}
{'deadbee', 'f-', 'deadf00d-', 'trailer'}
{'deadbee', 'f', '-deadf00', 'd-', 'trailer'}
{'dead', 'beef', '-', 'dead', 'f00d-', 'trailer'}
{'d', 'eadbeef-de', 'ad', 'f00d', '', '-', 'trai', 'le', 'r'}
}
index += 1
it index, ->
bf = new input
iter = bf\receiveuntil '-'
for {exp_n, exp_data, exp_err, exp_partial} in *{
{1, 'dead'}
{1, 'beef'}
{1, ''}
{3, nil, nil, nil}
{1, 'dead'}
{1, 'f00d'}
{1, ''}
{3, nil, nil, nil}
{1, 'trai'}
{3, nil, 'closed', 'ler'}
{2, nil, 'closed'}
{2, nil, 'closed'}
}
n, data, err, partial = nargs iter 4
assert.are.equal exp_n, n
assert.are.equal exp_data, data
assert.are.equal exp_err, err
assert.are.equal exp_partial, partial
describe 'without trailer', ->
describe '3 char pattern', ->
index = 0
for input in *{
'deadbeef***deadf00d***'
{'dea', 'dbeef*', '*', '*de', 'adf00d', '**', '*'}
{'deadbeef**', '*', 'deadf', '00d*', '**'}
{'deadbee', 'f**', '*deadf00', 'd**', '*'}
{'dead', 'beef', '***', 'dead', 'f00d***', ''}
{'d', 'eadbeef***de', 'ad', 'f00d', '**', '*'}
}
index += 1
describe index, ->
it 'read 7 bytes', ->
bf = new input
iter = bf\receiveuntil '***'
for {exp_n, exp_data, exp_err, exp_partial} in *{
{1, 'deadbee'}
{1, 'f'}
{3, nil, nil, nil}
{1, 'deadf00'}
{1, 'd'}
{3, nil, nil, nil}
{3, nil, 'closed', ''}
{2, nil, 'closed'}
{2, nil, 'closed'}
}
n, data, err, partial = nargs iter 7
assert.are.equal exp_n, n
assert.are.equal exp_data, data
assert.are.equal exp_err, err
assert.are.equal exp_partial, partial
it 'read 1 bytes', ->
bf = new input
iter = bf\receiveuntil '***'
for {exp_n, exp_data, exp_err, exp_partial} in *{
{1, 'd'}, {1, 'e'}, {1, 'a'}, {1, 'd'}
{1, 'b'}, {1, 'e'}, {1, 'e'}, {1, 'f'}
{1, ''}
{3, nil, nil, nil}
{1, 'd'}, {1, 'e'}, {1, 'a'}, {1, 'd'}
{1, 'f'}, {1, '0'}, {1, '0'}, {1, 'd'}
{1, ''}
{3, nil, nil, nil}
{3, nil, 'closed', ''}
{2, nil, 'closed'}
{2, nil, 'closed'}
}
n, data, err, partial = nargs iter 1
assert.are.equal exp_n, n
assert.are.equal exp_data, data
assert.are.equal exp_err, err
assert.are.equal exp_partial, partial
describe '1 char pattern', ->
index = 0
for input in *{
'deadbeef-deadf00d-'
{'deadbeef', '-', 'deadf00d-'}
{'deadbee', 'f-', 'deadf00d-'}
{'deadbee', 'f', '-deadf00', 'd-'}
{'dead', 'beef', '-', 'dead', 'f00d-'}
{'d', 'eadbeef-de', 'ad', 'f00d', '', '-'}
}
index += 1
it index, ->
bf = new input
iter = bf\receiveuntil '-'
for {exp_n, exp_data, exp_err, exp_partial} in *{
{1, 'dead'}
{1, 'beef'}
{1, ''}
{3, nil, nil, nil}
{1, 'dead'}
{1, 'f00d'}
{1, ''}
{3, nil, nil, nil}
{3, nil, 'closed', ''}
{2, nil, 'closed'}
{2, nil, 'closed'}
}
n, data, err, partial = nargs iter 4
assert.are.equal exp_n, n
assert.are.equal exp_data, data
assert.are.equal exp_err, err
assert.are.equal exp_partial, partial
it 'pattern longer than buffer value', ->
bf = new {'---', '-', '--', '-', '-deadf00d', '--------'}
iter = bf\receiveuntil '--------'
for {exp_n, exp_data, exp_err, exp_partial} in *{
{1, ''}
{3, nil, nil, nil}
{1, 'dead'}
{1, 'f00d'}
{1, ''}
{3, nil, nil, nil}
{3, nil, 'closed', ''}
{2, nil, 'closed'}
}
n, data, err, partial = nargs iter 4
assert.are.equal exp_n, n
assert.are.equal exp_data, data
assert.are.equal exp_err, err
assert.are.equal exp_partial, partial
| 42.390476 | 83 | 0.306223 |
10dd7d33d660e6178bcadca20787e5814b94e9c3 | 6,007 | Platform = require('main.platforms.platform')
-- Dump a list of folders in one of the paths.
-- Parse the list of folders and see if any of the names match with one of the pre-defined sets of arguments.
class Battlenet extends Platform
new: (settings) =>
super(settings)
@platformID = ENUMS.PLATFORM_IDS.BATTLENET
@platformProcess = 'Battle.net.exe'
@name = 'Blizzard Battle.net'
@cachePath = 'cache\\battlenet\\'
@battlenetPaths = [path for path in *settings\getBattlenetPaths()] or {}
@clientPath = io.joinPaths(settings\getBattlenetClientPath(), 'Battle.net.exe')
@enabled = settings\getBattlenetEnabled()
@games = {}
validate: () =>
assert(io.fileExists(@clientPath, false),
'The path to the Blizzard Battle.net client is undefined or invalid.')
hasUnprocessedPaths: () => return #@battlenetPaths > 0
hasProcessedPath: () => return io.fileExists(io.joinPaths(@cachePath, 'completed.txt'))
getCachePath: () => return @cachePath
identifyFolders: () =>
SKIN\Bang(('["#@#windowless.vbs" "#@#main\\platforms\\battlenet\\identifyFolders.bat" "%s"]')\format(@battlenetPaths[1]))
return @getWaitCommand(), '', 'OnIdentifiedBattlenetFolders'
getBanner: (title, bannerURL) =>
banner = @getBannerPath(title)
unless banner
if bannerURL
banner = io.joinPaths(@cachePath, title .. bannerURL\reverse()\match('^([^%.]+%.)')\reverse())
return banner
generateGames: (output) =>
assert(type(output) == 'string')
table.remove(@battlenetPaths, 1)
games = {}
folders = output\lower()\splitIntoLines()
assert(folders[1]\startsWith('bits:'))
bits = table.remove(folders, 1)
bits = if (bits\find('64')) ~= nil then 64 else 32
for folder in *folders
args = nil
switch folder
when 'destiny 2'
args = {
title: 'Destiny 2'
path: 'DST2'
process: 'destiny2.exe' -- No 32-bit executable
--bannerURL: ''
}
when 'diablo iii'
args = {
title: 'Diablo III'
path: 'D3'
process: if bits == 64 then 'Diablo III64.exe' else 'Diablo III.exe'
--bannerURL: ''
}
when 'hearthstone'
args = {
title: 'Hearthstone'
path: 'WTCG'
process: 'Hearthstone.exe' -- No 64-bit executable
--bannerURL: ''
}
when 'heroes of the storm'
args = {
title: 'Heroes of the Storm'
path: 'Hero'
process: if bits == 64 then 'HeroesOfTheStorm_x64.exe' else 'HeroesOfTheStorm.exe'
--bannerURL: ''
}
when 'overwatch'
args = {
title: 'Overwatch'
path: 'Pro'
process: 'Overwatch.exe' -- No 32-bit executable
--bannerURL: ''
}
when 'starcraft'
args = {
title: 'StarCraft'
path: 'S1'
process: 'StarCraft.exe' -- No 64-bit executable
--bannerURL: ''
}
when 'starcraft ii'
args = {
title: 'StarCraft II'
path: 'S2'
process: if bits == 64 then 'SC2_x64.exe' else 'SC2.exe'
--bannerURL: ''
}
when 'world of warcraft'
args = {
title: 'World of Warcraft'
path: 'WoW'
process: if bits == 64 then 'Wow-64.exe' else 'Wow.exe'
--bannerURL: ''
}
else
continue
if args.title == nil
log('Skipping Blizzard Battle.net game because the title is missing')
continue
elseif args.path == nil
log('Skipping Blizzard Battle.net game because the path is missing')
continue
args.path = ('"%s" --exec="launch %s"')\format(@clientPath, args.path)
args.banner = @getBanner(args.title, args.bannerURL)
unless args.banner
args.expectedBanner = args.title
args.platformID = @platformID
table.insert(games, args)
for args in *games
table.insert(@games, args)
if RUN_TESTS
assertionMessage = 'Blizzard Battle.net test failed!'
settings = {
getBattlenetPaths: () => return {
'Y:\\Blizzard games'
'Z:\\Games\\Battle.net'
}
getBattlenetEnabled: () => return true
getBattlenetClientPath: () => return 'C:\\Program Files\\Battle.net'
}
battlenet = Battlenet(settings)
output = 'BITS:AMD64
Diablo III
StarCraft
Overwatch
Some random game
Hearthstone
'
battlenet\generateGames(output)
games = battlenet.games
assert(#games == 4, assertionMessage)
output = 'BITS:x86
Heroes of the Storm
StarCraft II
StarCraft
Another random game
World of Warcraft
Destiny 2
'
battlenet\generateGames(output)
games = battlenet.games
assert(#games == 9, assertionMessage)
expectedGames = {
-- First library (64-bits)
{
title: 'Diablo III'
path: '"C:\\Program Files\\Battle.net\\Battle.net.exe" --exec="launch D3"'
process: 'Diablo III64.exe'
}
{
title: 'StarCraft'
path: '"C:\\Program Files\\Battle.net\\Battle.net.exe" --exec="launch S1"'
process: 'StarCraft.exe'
}
{
title: 'Overwatch'
path: '"C:\\Program Files\\Battle.net\\Battle.net.exe" --exec="launch Pro"'
process: 'Overwatch.exe'
}
{
title: 'Hearthstone'
path: '"C:\\Program Files\\Battle.net\\Battle.net.exe" --exec="launch WTCG"'
process: 'Hearthstone.exe'
}
-- Second library (32-bits)
{
title: 'Heroes of the Storm'
path: '"C:\\Program Files\\Battle.net\\Battle.net.exe" --exec="launch Hero"'
process: 'HeroesOfTheStorm.exe'
}
{
title: 'StarCraft II'
path: '"C:\\Program Files\\Battle.net\\Battle.net.exe" --exec="launch S2"'
process: 'SC2.exe'
}
{
title: 'StarCraft'
path: '"C:\\Program Files\\Battle.net\\Battle.net.exe" --exec="launch S1"'
process: 'StarCraft.exe'
}
{
title: 'World of Warcraft'
path: '"C:\\Program Files\\Battle.net\\Battle.net.exe" --exec="launch WoW"'
process: 'Wow.exe'
}
{
title: 'Destiny 2'
path: '"C:\\Program Files\\Battle.net\\Battle.net.exe" --exec="launch DST2"'
process: 'destiny2.exe'
}
}
for i, game in ipairs(games)
assert(game\getTitle() == expectedGames[i].title, assertionMessage)
assert(game\getPath() == expectedGames[i].path, assertionMessage)
assert(game\getProcess() == expectedGames[i].process, assertionMessage)
return Battlenet
| 28.334906 | 123 | 0.643915 |
41a20b6c2fff44685adfd0fd8f80db0f0e8d07e4 | 64 | pad = zb2rharxQTRobPCL5Qhy6LaWTWo7LsYJ63rVzqjDrk3hArS8T
(pad 0)
| 21.333333 | 55 | 0.875 |
00ac387e68887815cc65246b1067406b66bcb554 | 3,406 | export state = {
absolutes: {} -- *as in absolutely being drawn*
entities: {}
cam: {x: 0, y: 0, z: 0, dx: 0, dy: 0, dz: 0, pos_x: 0, pos_y: 0}
level: 1
}
export entity = require "src/things"
level = require "src/level"
-- averages vertice's given axis
export avgn = (a, n) ->
sum = 0
for v in *(a.vertices or a.model.vertices)
sum += v[n]
sum / #(a.vertices or a.model.vertices)
-- list of vertice-based entities
-- being split into two based on comparison thing
flagn = (a, n) ->
for b in *a
if state.cam.dx < 0
b.flag = state.cam.dx < avgn b, n
else
b.flag = state.cam.dx > avgn b, n
a
-- splits flagged list based on flag
splitn = (a, n) ->
flagn a, n
l, l1 = {}, {}
for b in *a
if b.flag
table.insert l, b
else
table.insert l1, b
l, l1
-- sorts vertice-based objects avg x
sortx = (a, b) ->
(avgn a, 1) < avgn b, 1
-- sorts vertice-based objects avg y
sorty = (a, b) ->
(avgn a, 2) > avgn b, 2
with state
.load = =>
level\load "res/level#{.level}.png"
for li in *.absolutes
break unless li
l, l1 = splitn li, 1
li.left = l
li.right = l1
.update = (dt) =>
for e in *.entities
e\update dt if e.update
for l in *.absolutes
break unless l
for e in *l
e\update dt if e.update
i1 = 1
for l in *.absolutes
break unless l
i = 1
for cube in *l
break unless cube
for e in *.entities
if e == cube
y = math.floor e.y / 2
unless y < 1 or y > #.absolutes
ix = 1
for a in *.absolutes[y]
break if a == cube
if (avgn cube, 1) > avgn a, 1
break
ix += 1
table.remove l, i
table.insert .absolutes[y], ix, cube
i += 1
i1 += 1
for li in *.absolutes
break unless li
l, l1 = splitn li, 1
li.left = l
li.right = l1
.cam.x = math.lerp .cam.x, .cam.dx, dt * 30
.cam.y = math.lerp .cam.y, .cam.dy, dt * 3
.cam.z = math.lerp .cam.z, .cam.dz, dt * 30
.spawn_absolute = (entity, y) =>
.absolutes[y] = {} unless .absolutes[y]
table.insert .absolutes[y], entity
.spawn = (entity) =>
table.insert .entities, entity
.draw = =>
love.graphics.push!
.cam.pos_x, .cam.pos_y = love.graphics.getWidth! / 2 - .cam.x * 10, love.graphics.getHeight! / 2 - .cam.y * 10
love.graphics.translate .cam.pos_x, .cam.pos_y
for l = #.absolutes, 1, -1
li = .absolutes[l]
break unless li.right
for e = #li.right, 1, -1
li.right[e]\draw! if li.right[e].draw
break unless li.left
for e = #li.left, 1, -1
li.left[e]\draw! if li.left[e].draw
love.graphics.pop!
.press = (key) =>
for e in *.entities
e\press key if e.press
state | 26 | 118 | 0.449794 |
08a7925ac58e1c4246eefc7121f87ba8ef6b48b0 | 68 | M = {}
M.hi = (msg) -> string.format "Hello world! %s", msg
return M | 22.666667 | 52 | 0.588235 |
8e287cc2ad80a3b8ec81cf7abba7ae92d1eefe45 | 3,074 |
import
VList
HList
Bin
Label
Group
from require "lovekit.ui"
ordinal = (num) ->
num = tonumber(num) % 10
if num > 10 and num < 20
return "th"
switch num
when 1
"st"
when 2
"nd"
when 3
"rd"
else
"th"
class Hud
time_speed: 15
days_per_month: 31
months: {"spring", "summer", "fall", "winter"}
max_time: 60*23
new: (@game) =>
@setup_time!
@setup_name!
@setup_age!
@setup_day!
@viewport = Viewport scale: GAME_CONFIG.scale
@clock = Label @\format_time
@date = Label @\format_date
@holding = Label @\format_item
@name = Label @\format_name
@group = Group {
Bin 0,0, @viewport.w, @viewport.h, @clock, 1, 1
Bin 0,0, @viewport.w, @viewport.h, @date, 0, 1
Bin 0,0, @viewport.w, @viewport.h, @holding, 1, 0
Bin 0,0, @viewport.w, @viewport.h, @name, 0, 0
}
@seq = Sequence ->
wait 2
SHARECART.Misc3 = math.floor @day % 60000
SHARECART.MapX = math.floor @time % 1000
SHARECART.MapY = math.floor @_age % 1000
again!
setup_day: =>
day = SHARECART.Misc3
unless day
day = love.math.random 0, 1023
SHARECART.Misc3 = day
@day = day
setup_time: =>
time = SHARECART.MapX
unless time
time = love.math.random 0, 1023
SHARECART.MapX = time
@time = time % @max_time
setup_name: =>
name = SHARECART.PlayerName
unless name
name = "Farmer"
SHARECART.PlayerName = name
@_name = name
setup_age: =>
age = SHARECART.MapY
unless age
age = love.math.random 18, 36
SHARECART.MapY = age
@_age = age
format_name: =>
"#{@_name\lower!} - age: #{@_age}"
format_date: =>
month = @months[math.floor(@day / @days_per_month) % #@months + 1]
day = (@day % @days_per_month) + 1
"#{month} #{day}#{ordinal day}"
format_item: =>
return "" unless @game.player
item = @game.player.holding
return "" unless item
"holding: #{item.name}"
hours_minutes: =>
t = math.floor @time
minutes = t % 60
hours = math.floor t / 60
hours, minutes
format_time: =>
hours, minutes = @hours_minutes!
minutes = 15 * math.floor minutes / 15
"#{"%.2d"\format hours}:#{"%.2d"\format minutes}"
night_progress: =>
total_minutes = 60 * 24
minutes = @time % total_minutes
start = 20 * 60 -- 20th hour
len = 9 * 60 -- 9 hours
minutes -= start
if minutes < 0
minutes += total_minutes
return 0 if minutes > len
minutes / len
night_darkness: =>
p = @night_progress!
if p < 0.1
lerp 0, 1, p/0.1
elseif p > 0.9
lerp 1, 0, (p - 0.9) / 0.1
else
1
update: (dt) =>
@time += dt * @time_speed
if @time > @max_time
@day += 1
@time -= @max_time
@group\update dt
@seq\update dt
draw: =>
@viewport\apply!
COLOR\push 0,0,0, 150
Box.draw @date
Box.draw @clock
Box.draw @holding
Box.draw @name
COLOR\pop!
@group\draw!
@viewport\pop!
{ :Hud }
| 18.630303 | 70 | 0.562785 |
401963263d1315063c052350f6fae6bf8091b88a | 15,553 | --
-- This file contains the source code of the Nomsu compiler.
--
unpack or= table.unpack
{:match, :sub, :gsub, :format, :byte, :find} = string
{:LuaCode, :Source} = require "code_obj"
require "text"
SyntaxTree = require "syntax_tree"
Files = require "files"
pretty_error = require("pretty_errors")
fail_at = (source, msg)->
local file
if SyntaxTree\is_instance(source)
file = source\get_source_file!
source = source.source
elseif type(source) == 'string'
source = Source\from_string(source)
elseif not Source\is_instance(source)
-- debug.getinfo() output:
assert(source.short_src and source.currentline)
file = Files.read(source.short_src)
assert file, "Could not find #{source.short_src}"
lines = file\lines!
start = 1
for i=1,source.currentline-1
start += #lines[i]
stop = start + #lines[source.currentline]
source = Source(source.short_src, start, stop)
if source and not file
file = Files.read(source.filename)
if not file
if NOMSU_PREFIX
path = "#{NOMSU_PREFIX}/share/nomsu/#{table.concat NOMSU_VERSION, "."}/#{source.filename}"
file = Files.read(path)
if not file
error("Can't find file: "..tostring(source.filename))
title, err_msg, hint = msg\match("([^:]*):[ \n]+(.*)[ \n]+Hint: (.*)")
if not err_msg
err_msg, hint = msg\match("(.*)[ \n]+Hint:[ \n]+(.*)")
title = "Failure"
if not err_msg
title, err_msg = msg\match("([^:]*):[ \n]+(.*)")
if not err_msg
err_msg = msg
title = "Failure"
err_str = pretty_error{
title: title,
error: err_msg, hint: hint, source: file,
start:source.start, stop:source.stop, filename:source.filename,
}
error(err_str, 0)
-- This is a bit of a hack, but this code handles arbitrarily complex
-- math expressions like 2*x + 3^2 without having to define a single
-- action for every possibility.
re = require 're'
math_expression = re.compile [[ (([*/^+-] / [0-9]+) " ")* [*/^+-] !. ]]
MAX_LINE = 80 -- For beautification purposes, try not to make lines much longer than this value
compile = (tree)=>
if tree == nil
error("No tree was passed in.")
-- Automatically upgrade trees from older versions:
if tree.version and tree.version < @NOMSU_VERSION\up_to(#tree.version) and @_1_upgraded_from_2_to
tree = @._1_upgraded_from_2_to(tree, tree.version, @NOMSU_VERSION)
switch tree.type
when "Action"
stub = tree.stub
compile_action = @COMPILE_RULES[stub]
if not compile_action and math_expression\match(stub)
lua = LuaCode\from(tree.source)
for i,tok in ipairs tree
if type(tok) == 'string'
lua\add tok
else
tok_lua = @compile(tok)
-- TODO: this is overly eager, should be less aggressive
tok_lua\parenthesize! if tok.type == "Action"
lua\add tok_lua
lua\add " " if i < #tree
return lua
if not compile_action
seen_words = {}
words = {}
for word in stub\gmatch("[^0-9 ][^ ]*")
unless seen_words[word]
seen_words[word] = true
table.insert words, word
table.sort(words)
stub2 = table.concat(words, " ")
compile_action = @COMPILE_RULES[stub2]
if compile_action
if debug.getinfo(compile_action, 'u').isvararg
stub = stub2
else compile_action = nil
if compile_action
args = [arg for arg in *tree when type(arg) != "string"]
ret = compile_action(@, tree, unpack(args))
if ret == nil
info = debug.getinfo(compile_action, "S")
filename = Source\from_string(info.source).filename
fail_at tree,
("Compile error: The compile-time action here (#{stub}) failed to return any value. "..
"Hint: Look at the implementation of (#{stub}) in #{filename}:#{info.linedefined} and make sure it's returning something.")
unless SyntaxTree\is_instance(ret)
ret.source or= tree.source
return ret
if ret != tree
return @compile(ret)
lua = LuaCode\from(tree.source)
lua\add((stub)\as_lua_id!,"(")
for argnum, arg in ipairs tree\get_args!
arg_lua = @compile(arg)
if arg.type == "Block" and #arg > 1
arg_lua = LuaCode\from(arg.source, "(function()\n ", arg_lua, "\nend)()")
if lua\trailing_line_len! + #arg_lua > MAX_LINE
lua\add(argnum > 1 and ",\n " or "\n ")
elseif argnum > 1
lua\add ", "
lua\add arg_lua
lua\add ")"
return lua
when "MethodCall"
stub = tree\get_stub!
compile_action = @COMPILE_RULES[stub]
if compile_action
args = tree\get_args!
ret = compile_action(@, tree, unpack(args))
if ret == nil
info = debug.getinfo(compile_action, "S")
filename = Source\from_string(info.source).filename
fail_at tree,
("Compile error: The compile-time method here (#{stub}) failed to return any value. "..
"Hint: Look at the implementation of (#{stub}) in #{filename}:#{info.linedefined} "..
"and make sure it's returning something.")
unless SyntaxTree\is_instance(ret)
ret.source or= tree.source
return ret
if ret != tree
return @compile(ret)
lua = LuaCode\from tree.source
target_lua = @compile tree[1]
target_text = target_lua\text!
-- TODO: this parenthesizing is maybe overly conservative
if not (target_text\match("^%(.*%)$") or target_text\match("^[_a-zA-Z][_a-zA-Z0-9.]*$") or
tree[1].type == "IndexChain")
target_lua\parenthesize!
self_lua = #tree > 2 and "_self" or target_lua
if #tree > 2
lua\add "(function(", self_lua, ")\n "
for i=2,#tree
lua\add "\n " if i > 2
if i > 2 and i == #tree
lua\add "return "
lua\add self_lua, ":"
lua\add((tree[i].stub)\as_lua_id!,"(")
for argnum, arg in ipairs tree[i]\get_args!
arg_lua = @compile(arg)
if arg.type == "Block" and #arg > 1
arg_lua = LuaCode\from(arg.source, "(function()\n ", arg_lua, "\nend)()")
if lua\trailing_line_len! + #arg_lua > MAX_LINE
lua\add(argnum > 1 and ",\n " or "\n ")
elseif argnum > 1
lua\add ", "
lua\add arg_lua
lua\add ")"
if #tree > 2
lua\add "\nend)(", target_lua, ")"
return lua
when "EscapedNomsu"
lua = LuaCode\from tree.source, "SyntaxTree{"
needs_comma, i = false, 1
as_lua = (x)->
if type(x) == 'number'
tostring(x)
elseif SyntaxTree\is_instance(x)
@compile(x)
elseif Source\is_instance(x)
tostring(x)\as_lua!
else x\as_lua!
for k,v in pairs((SyntaxTree\is_instance(tree[1]) and tree[1].type == "EscapedNomsu" and tree) or tree[1])
entry_lua = LuaCode!
if k == i
i += 1
elseif type(k) == 'string' and match(k,"[_a-zA-Z][_a-zA-Z0-9]*")
entry_lua\add(k, "= ")
else
entry_lua\add("[", as_lua(k), "]= ")
entry_lua\add as_lua(v)
if needs_comma then lua\add ","
if lua\trailing_line_len! + #(entry_lua\match("^[\n]*")) > MAX_LINE
lua\add "\n "
elseif needs_comma
lua\add " "
lua\add entry_lua
needs_comma = true
lua\add "}"
return lua
when "Block"
lua = LuaCode\from(tree.source)
for i, line in ipairs tree
if line.type == "Error"
return @compile(line)
for i, line in ipairs tree
if i > 1 then lua\add "\n"
line_lua = @compile(line)
lua\add line_lua
unless line_lua\last(1) == ";" or line_lua\last(4)\match("[^_a-zA-Z0-9]end$")
lua\add ";"
return lua
when "Text"
if #tree == 0
return LuaCode\from(tree.source, '""')
if #tree == 1 and type(tree[1]) == 'string'
return LuaCode\from(tree.source, tree[1]\as_lua!)
lua = LuaCode\from(tree.source, "Text(")
added = 0
string_buffer = ""
add_bit = (bit)->
if added > 0
if lua\trailing_line_len! + #bit > MAX_LINE
lua\add ",\n "
else
lua\add ", "
lua\add bit
added += 1
for i, bit in ipairs tree
if type(bit) == "string"
string_buffer ..= bit
continue
if string_buffer != ""
for i=1,#string_buffer,MAX_LINE
add_bit string_buffer\sub(i, i+MAX_LINE-1)\as_lua!
string_buffer = ""
bit_lua = @compile(bit)
if bit.type == "Block"
bit_lua = LuaCode\from bit.source, "a_List(function(add)",
"\n ", bit_lua,
"\nend):joined()"
add_bit bit_lua
if string_buffer != ""
for i=1,#string_buffer,MAX_LINE
add_bit string_buffer\sub(i, i+MAX_LINE-1)\as_lua!
string_buffer = ""
if added == 0
return LuaCode\from(tree.source, '""')
lua\add ")"
return lua
when "List", "Dict"
typename = "a_"..tree.type
if #tree == 0
return LuaCode\from tree.source, typename, "{}"
lua = LuaCode\from tree.source
chunks = 0
i = 1
while tree[i]
if tree[i].type == 'Block'
lua\add " + " if chunks > 0
lua\add typename, "(function(", (tree.type == 'List' and "add" or ("add, "..("add 1 =")\as_lua_id!)), ")"
body = @compile(tree[i])
body\declare_locals!
lua\add "\n ", body, "\nend)"
chunks += 1
i += 1
else
lua\add " + " if chunks > 0
sep = ''
items_lua = LuaCode\from tree[i].source
while tree[i]
if tree[i].type == "Block"
break
item_lua = @compile tree[i]
if item_lua\match("^%.[a-zA-Z_]")
item_lua = item_lua\text!\sub(2)
if tree.type == 'Dict' and tree[i].type == 'Index'
item_lua = LuaCode\from tree[i].source, item_lua, "=true"
items_lua\add sep, item_lua
if tree[i].type == "Comment"
items_lua\add "\n"
sep = ''
elseif items_lua\trailing_line_len! > MAX_LINE
sep = items_lua\last(1) == ";" and "\n " or ",\n "
else
sep = items_lua\last(1) == ";" and " " or ", "
i += 1
if items_lua\is_multiline!
lua\add LuaCode\from items_lua.source, typename, "{\n ", items_lua, "\n}"
else
lua\add LuaCode\from items_lua.source, typename, "{", items_lua, "}"
chunks += 1
return lua
when "Index"
key_lua = @compile(tree[1])
key_str = key_lua\match('^"([a-zA-Z_][a-zA-Z0-9_]*)"$')
return if key_str and key_str\is_lua_id!
LuaCode\from tree.source, ".", key_str
elseif key_lua\first(1) == "["
-- NOTE: this *must* use a space after the [ to avoid freaking out
-- Lua's parser if the inner expression is a long string. Lua
-- parses x[[[y]]] as x("[y]"), not as x["y"]
LuaCode\from tree.source, "[ ",key_lua,"]"
else
LuaCode\from tree.source, "[",key_lua,"]"
when "DictEntry"
key = tree[1]
if key.type != "Index"
key = SyntaxTree{type:"Index", source:key.source, key}
return LuaCode\from tree.source, @compile(key),"=",(tree[2] and @compile(tree[2]) or "true")
when "IndexChain"
lua = @compile(tree[1])
if lua\match("['\"}]$") or lua\match("]=*]$")
lua\parenthesize!
if lua\text! == "..."
return LuaCode\from(tree.source, "select(", @compile(tree[2][1]), ", ...)")
for i=2,#tree
key = tree[i]
-- TODO: remove this shim
if key.type != "Index"
key = SyntaxTree{type:"Index", source:key.source, key}
lua\add @compile(key)
return lua
when "Number"
number = tostring(tree[1])\gsub("_", "")
return LuaCode\from(tree.source, number)
when "Var"
if tree[1].type == "MethodCall"
return LuaCode\from(tree.source, @compile(tree[1][1]), ".", tree[1][2]\get_stub!\as_lua_id!)
return LuaCode\from(tree.source, tree\as_var!\as_lua_id!)
when "FileChunks"
error("Can't convert FileChunks to a single block of lua, since each chunk's "..
"compilation depends on the earlier chunks")
when "Comment"
return LuaCode\from(tree.source, "-- ", (tree[1]\gsub('\n', '\n-- ')))
when "Error"
err_msg = pretty_error{
title:"Parse error"
error:tree.error, hint:tree.hint, source:tree\get_source_file!
start:tree.source.start, stop:tree.source.stop, filename:tree.source.filename
}
-- Coroutine yield here?
error(err_msg)
else
error("Unknown type: #{tree.type}")
return {:compile, :fail_at}
| 41.145503 | 147 | 0.469749 |
6e792f381cc4e9fbe162e73556f7e4e9534022da | 334 | Dorothy!
TestBase = require "Dev.Test.TestBase"
Class TestBase,
run:=>
print "Fields of UnitDef:"
for k,v in pairs oUnitDef[4]
if type(k) == "string" and k\sub(1,2) ~= "__"
print k
print "\nFields of BodyDef:"
for k,v in pairs oBodyDef[4]
if type(k) == "string" and k\sub(1,2) ~= "__"
print k
| 22.266667 | 49 | 0.586826 |
a12d773c5bca65e99722bd1e035ef85863213d2d | 299 | export modinfo = {
type: "command"
desc: "Thaw"
alias: {"thaw"}
func: getDoPlayersFunction (v) ->
if v.Character
for i,s in pairs(v.Character\GetChildren())
if s\IsA"BasePart"
s.Anchored = false
s.Reflectance = 0
Output(string.format("Thawed %s",v.Name),{Colors.Green})
} | 24.916667 | 61 | 0.645485 |
efbbb5162904691a2c69946d8eb9c440ce798e26 | 15,347 | Dorothy!
SpritePanelView = require "View.Control.Item.SpritePanel"
TabButton = require "Control.Item.TabButton"
SpriteView = require "Control.Item.SpriteView"
MessageBox = require "Control.Basic.MessageBox"
import CompareTable from require "Lib.Utils"
Reference = require "Data.Reference"
-- [signals]
-- "Selected",(spriteStr)->
-- "Hide",->
-- [params]
-- x, y, width, height
Class SpritePanelView,
__init: =>
@_isSelecting = false
@selectedImages = {}
@selectedClips = {}
@viewItemChecked = (checked,item)->
if @selectedImages
@selectedImages[item.file] = if checked then true else nil
@clipItemChecked = (checked,item)->
if @selectedClips
@selectedClips[item.file] = if checked then true else nil
@selected = (item)->
@hide!
@emit "Selected",item.spriteStr
contentRect = CCRect.zero
itemRect = CCRect.zero
@scrollArea\slot "Scrolled",(delta)->
contentRect\set 0,0,@scrollArea.width,@scrollArea.height
@menu\eachChild (child)->
child.position += delta
{:positionX,:positionY,:width,:height} = child
itemRect\set positionX-width/2,positionY-height/2,width,height
child.visible = contentRect\intersectsRect itemRect -- reduce draw calls
@scrollArea\slot "ScrollStart",->
@menu.enabled = false
@scrollArea\slot "ScrollTouchEnded",->
@menu.enabled = true
@slot "Cleanup",->
oRoutine\remove @routine if @routine
@gslot "Scene.ViewSprite",->
@show!
@gslot "Scene.ClearSprite",->
@clips = nil
@images = nil
@gslot "Scene.LoadSprite",(resPath)->
@runThread ->
-- get image and clip files
images = {}
clips = {}
resPath = resPath\gsub("[\\/]*$","")
visitResource = (path)->
return unless oContent\exist path
files = oContent\getEntries path,false
sleep!
for file in *files
extension = file\match "%.([^%.\\/]*)$"
extension = extension\lower! if extension
filename = path.."/"..file
switch extension
when "png","jpg","jpeg","tiff","webp"
clipFile = filename\match("(.*)%.[^%.\\/]*$")..".clip"
table.insert images,filename unless oContent\exist clipFile
when "clip"
table.insert clips,filename
folders = oContent\getEntries path,true
for folder in *folders
if folder ~= "." and folder ~= ".."
visitResource path.."/"..folder
if #files == 0 and #folders == 2 and path ~= resPath
oContent\remove path
visitResource resPath
{:width,:height} = @scrollArea
compareClip = (a,b)->
a\match("[\\/]([^\\/]*)$") < b\match("[\\/]([^\\/]*)$")
index = 0
if @clips -- already loaded clips
clipsToAdd,clipsToDel = CompareTable @clips,clips
for clipDel in *clipsToDel
item = @clipItems[clipDel]
item.parent\removeChild item
@clipItems[clipDel] = nil
expandItems = @clipExpands[clipDel]
if expandItems
for expItem in *expandItems
expItem.parent\removeChild expItem
@clipExpands[clipDel] = nil
@playUpdateHint!
table.sort clipsToAdd,compareClip
table.sort clips,compareClip
for clipAdd in *clipsToAdd
@clipItems[clipAdd] = @_addClipTab clipAdd,index
@playUpdateHint!
index += 1
else -- first load clips
if @clipItems
@playUpdateHint!
for clip,item in pairs @clipItems
item.parent\removeChild item
expandItems = @clipExpands[clip]
if expandItems
for expItem in *expandItems
expItem.parent\removeChild expItem
@clipExpands[clip] = nil
@clipItems = {}
@clipExpands = {}
table.sort clips,compareClip
for clip in *clips
clipTab = @_addClipTab clip,index
@playUpdateHint!
index += 1
clipTab.visible = false
@clipItems[clip] = clipTab
@clips = clips
sleep!
if @images
imagesToAdd,imagesToDel = CompareTable @images,images
for imageDel in *imagesToDel
item = @imageItems[imageDel]
item.parent\removeChild item
@imageItems[imageDel] = nil
@playUpdateHint!
for imageAdd in *imagesToAdd
viewItem = SpriteView {
file: imageAdd
width: 100
height: 100
needUnload: true
}
viewItem.visible = false
viewItem.enabled = false
viewItem.isCheckMode = @_isSelecting
viewItem\slot "Checked",@viewItemChecked
viewItem\slot "Selected",@selected
@menu\addChild viewItem
@playUpdateHint!
@imageItems[imageAdd] = viewItem
viewItem.opacity = 0
viewItem\perform CCSequence {
CCDelay index*0.1
oOpacity 0.3,1
}
index += 1
else
if @imageItems
@playUpdateHint!
for _,item in pairs @imageItems
item.parent\removeChild item
@imageItems = {}
for image in *images
viewItem = SpriteView {
file: image
width: 100
height: 100
needUnload: true
}
viewItem\slot "Checked",@viewItemChecked
viewItem\slot "Selected",@selected
viewItem.visible = false
viewItem.enabled = false
viewItem.isCheckMode = @_isSelecting
@menu\addChild viewItem
@playUpdateHint!
@imageItems[image] = viewItem
viewItem.opacity = 0
viewItem\perform CCSequence {
CCDelay index*0.1
oOpacity 0.3,1
}
index += 1
@images = images
itemCount = math.floor (@panel.width-10)/110
startY = height-40
y = startY
for i,clip in ipairs @clips
i -= 1
y = startY-30-i*50
clipTab = @clipItems[clip]
clipTab.position = oVec2(width/2,y) + @scrollArea.offset
expandItems = @clipExpands[clip]
if expandItems
startY -= clipTab.deltaY
posY = y-20
for i,expItem in ipairs expandItems
i -= 1
x = 60+(i%itemCount)*110
y = posY-60-math.floor(i/itemCount)*110
expItem.position = oVec2(x,y) + @scrollArea.offset
y -= 30 if #expandItems > 0
y -= 20 if #@clips > 0
startY = y
for i,image in ipairs @images
i -= 1
x = 60+(i%itemCount)*110
y = startY-60-math.floor(i/itemCount)*110
viewItem = @imageItems[image]
viewItem.position = oVec2(x,y) + @scrollArea.offset
y -= 60 if #@images > 0
@scrollArea.viewSize = CCSize width,height-y
@addBtn.visible = false
@delBtn.visible = false
@groupBtn.visible = false
@delGroupBtn.visible = false
@modeBtn\slot "Tapped",->
return if Reference.isUpdating!
@_setCheckMode not @_isSelecting
@addBtn\slot "Tapped",->
MessageBox text:"Place Images In\n/Graphic/ folder",okOnly:true
@delBtn\slot "Tapped",->
images = [image for image,_ in pairs @selectedImages]
clips = [clip for clip,_ in pairs @selectedClips]
if #images + #clips > 0
for image in *images
if not Reference.isRemovable image
return
for clip in *clips
if not Reference.isRemovable clip
return
texFile = oCache.Clip\getTextureFile clip
texFile = texFile\gsub editor.gameFullPath,""
if #Reference.getUpRefs(texFile) > 1 and not Reference.isRemovable texFile
return
with MessageBox text:"Delete "..(#images+#clips == 1 and "item" or "items")
\slot "OK",(result)->
return unless result
with MessageBox text:"Confirm This\nDeletion"
\slot "OK",(result)->
return unless result
@runThread ->
for image in *images
sleep!
@imageItems[image].isCheckMode = false
@imageItems[image]\perform oOpacity 0.3,0
oCache.Texture\unload image
oContent\remove image
Reference.removeRef image
for clip in *clips
sleep!
@clipItems[clip].isCheckMode = false
texFile = oCache.Clip\getTextureFile clip
oCache.Clip\unload clip
oContent\remove clip
Reference.removeRef clip
oCache.Texture\unload texFile
oContent\remove texFile
Reference.removeRef texFile
sleep 0.3
editor\updateSprites!
else
MessageBox text:"No Item Selected",okOnly:true
@groupBtn\slot "Tapped",->
images = [image for image,_ in pairs @selectedImages]
if #images > 0
for image in *images
if not Reference.isRemovable image
return
ClipEditor = require "Control.Item.ClipEditor"
clipEditor = ClipEditor :images
clipEditor\slot "Grouped",(result)->
return unless result
for image in *images
@imageItems[image].isCheckMode = false
thread ->
sleep 0.3
editor\updateSprites!
else
MessageBox text:"No Sprite Selected",okOnly:true
@delGroupBtn\slot "Tapped",->
clips = [clip for clip,_ in pairs @selectedClips]
if #clips > 0
for clip in *clips
if not Reference.isRemovable clip
return
texFile = oCache.Clip\getTextureFile clip
texFile = texFile\gsub editor.gameFullPath,""
if #Reference.getUpRefs(texFile) > 1 and not Reference.isRemovable texFile
return
msgBox = MessageBox text:"Break Selected\nGroups"
msgBox\slot "OK",(result)->
return unless result
@runThread ->
for clip in *clips
sleep!
folder = editor.graphicFullPath..clip\match "[\\/]([^\\/]*)%.[^%.\\/]*$"
if oContent\exist folder
sleep!
index = 1
while oContent\exist folder..tostring index
sleep!
index += 1
folder ..= tostring index
folder ..= "/"
oContent\mkdir folder
sleep!
texFile = oCache.Clip\getTextureFile clip
oCache.Texture\unload texFile
oCache\loadAsync texFile
blendFunc = ccBlendFunc ccBlendFunc.One,ccBlendFunc.Zero
tex = oCache.Texture\load texFile
tex.antiAlias = false
names = oCache.Clip\getNames clip
for name in *names
sleep!
sp = CCSprite clip.."|"..name
sp.blendFunc = blendFunc
sp.anchor = oVec2.zero
target = CCRenderTarget sp.width,sp.height
target\beginDraw!
target\draw sp
target\endDraw!
sleep!
target\save folder..name..".png"
oCache.Clip\unload clip
oContent\remove clip
Reference.removeRef clip
oCache.Texture\unload texFile
oContent\remove texFile
Reference.removeRef texFile
@clipItems[clip].isCheckMode = false
@clipItems[clip]\perform oOpacity 0.3,0
sleep 0.3
editor\updateSprites!
else
MessageBox text:"No Group Selected",okOnly:true
@closeBtn\slot "Tapped",->
@hide!
playUpdateHint: =>
if not @hint.visible
@hint.visible = true
@hint.opacity = 1
@hint\perform @loopFade
runThread: (task)=>
oRoutine\remove @routine if @routine
@routine = thread ->
@scrollArea.touchEnabled = false
@menu\eachChild (child)->
if tolua.type child == "CCMenuItem"
child.enabled = false
@opMenu.enabled = false
task!
@hint\perform CCSequence {
oOpacity 0.3,0,oEase.OutQuad
CCHide!
}
@opMenu.enabled = true
@menu\eachChild (child)->
if tolua.type child == "CCMenuItem"
child.enabled = child.isCheckMode or not @_isSelecting
@scrollArea.touchEnabled = true
@routine = nil
_addClipTab: (clip,index)=>
clipTab = TabButton {
file: clip
width: @scrollArea.width-20
height: 40
text: clip\match "[\\/]([^\\/]*)%.[^%.\\/]*$"
}
clipTab\slot "Expanded",(expanded)->
if expanded
posY = clipTab.positionY-20
names = oCache.Clip\getNames clip
texFile = oCache.Clip\getTextureFile clip
@clipExpands[clip] = {}
newY = posY
itemCount = math.floor (@panel.width-10)/110
for i,name in ipairs names
i -= 1
spriteStr = clip.."|"..name
newX = 60+(i%itemCount)*110
newY = posY-60-math.floor(i/itemCount)*110
viewItem = SpriteView {
file: texFile
spriteStr: spriteStr
x: newX
y: newY
width: 100
height: 100
alias: #names
needUnload: i == #names-1
}
viewItem.clip = clip
viewItem\slot "Selected",@selected
@menu\addChild viewItem
table.insert @clipExpands[clip],viewItem
newY -= 50
deltaY = posY - newY
clipTab.deltaY = deltaY
@menu\eachChild (child)->
if child.clip ~= clip
child.positionY -= deltaY if child.positionY < posY
with @scrollArea.viewSize
@scrollArea.viewSize = CCSize .width,.height+deltaY
else
deltaY = clipTab.deltaY
clipTab.deltaY = 0
posY = clipTab.positionY-20-deltaY
@menu\eachChild (child)->
if child.clip ~= clip
child.positionY += deltaY if child.positionY < posY
for child in *@clipExpands[clip]
@menu\removeChild child
@clipExpands[clip] = nil
with @scrollArea.viewSize
@scrollArea.viewSize = CCSize .width,.height-deltaY
clipTab.deltaY = 0
clipTab.position += @scrollArea.offset
clipTab.enabled = false
clipTab.isCheckMode = @_isSelecting
clipTab\slot "Checked",@clipItemChecked
@menu\addChild clipTab
clipTab.opacity = 0
clipTab\perform CCSequence {
CCDelay (index or 0)*0.1
oOpacity 0.3,1
}
clipTab
_setCheckMode: (isSelecting)=>
return if isSelecting == @_isSelecting
@_isSelecting = isSelecting
@modeBtn.color = ccColor3(isSelecting and 0xff0088 or 0x00ffff)
@modeBtn.face.cascadeOpacity = not isSelecting
show = (index)-> CCSequence {
CCDelay 0.1*index
CCShow!
oScale 0,0,0
oScale 0.3,1,1,oEase.OutBack
}
hide = (index)-> CCSequence {
CCDelay 0.1*index
oScale 0.3,0,0,oEase.InBack
CCHide!
}
if isSelecting
@addBtn\perform show 0
@delBtn\perform show 1
@groupBtn\perform show 2
@delGroupBtn\perform show 3
@hint.positionX = @panel.width-(@panel.width-300)/2
else
@addBtn\perform hide 3
@delBtn\perform hide 2
@groupBtn\perform hide 1
@delGroupBtn\perform hide 0
@hint.positionX = @panel.width-(@panel.width-60)/2
@menu\eachChild (child)->
if not child.clip
child.isCheckMode = isSelecting
else
child.enabled = not isSelecting
show: =>
@perform CCSequence {
CCShow!
oOpacity 0.3,0.6,oEase.OutQuad
}
@closeBtn.scaleX = 0
@closeBtn.scaleY = 0
@closeBtn\perform oScale 0.3,1,1,oEase.OutBack
@panel.opacity = 0
@panel.scaleX = 0
@panel.scaleY = 0
@panel\perform CCSequence {
CCSpawn {
oOpacity 0.3,1,oEase.OutQuad
oScale 0.3,1,1,oEase.OutBack
}
CCCall ->
@scrollArea.touchEnabled = true
@menu.enabled = true
@opMenu.enabled = true
editor\updateSprites!
}
hide: =>
@_setCheckMode false
@scrollArea.touchEnabled = false
@menu.enabled = false
@opMenu.enabled = false
@closeBtn\perform oScale 0.3,0,0,oEase.InBack
@panel\perform CCSpawn {
oOpacity 0.3,0,oEase.OutQuad
oScale 0.3,0,0,oEase.InBack
}
@perform CCSequence {
oOpacity 0.3,0,oEase.OutQuad
CCHide!
CCCall -> @emit "Hide"
}
| 29.8 | 80 | 0.617319 |
f8149bbfb0d71080c9cf68c25c06b932c5ef78df | 30,687 | Dorothy!
ExprEditorView = require "View.Control.Trigger.ExprEditor"
ExprItem = require "Control.Trigger.ExprItem"
ExprChooser = require "Control.Trigger.ExprChooser"
PopupPanel = require "Control.Basic.PopupPanel"
MessageBox = require "Control.Basic.MessageBox"
TriggerDef = require "Data.TriggerDef"
import Path from require "Lib.Utils"
VarScope = Class
__init:(editor)=>
@editor = editor
@actionItem = nil
@localVarItem = nil
@locals = nil
@localSet = nil
@localVarFrom = nil
@localVarTo = nil
clear:=>
@actionItem = nil
@localVarItem = nil
@locals = {}
@localSet = {}
getLocalVarText:=>
if TriggerDef.CodeMode
"local "..table.concat(@locals,", ")
else
"Declare "..table.concat(@locals,", ").."."
createLocalVarItem:=>
indent = @actionItem.indent+1
localVarItem = with @editor\createExprItem @getLocalVarText!,indent
.positionY = @[email protected]/2-.height/2
children = @editor.triggerMenu.children
index = children\index(@actionItem)+1
children\removeLast!
children\insert localVarItem,index
localVarItem
refreshLocalVars:=>
if @actionItem
nextExpr = (expr)->
return unless "table" == type expr
switch expr[1]
when "SetLocal"
assignExpr = expr[2]
varType = assignExpr[1]\sub 9,-1
varName = assignExpr[2][2]
if varName ~= "InvalidName"
if not @editor.args[varName]
if not @localSet[varName]
table.insert @locals,varName
@localSet[varName] = varType
else
for i = 2,#expr
nextExpr expr[i]
@locals = {}
@localSet = {}
nextExpr @actionItem.expr
if @localVarItem
if #@locals > 0
@localVarItem.text = @getLocalVarText!
else
@localVarItem.parent\removeChild @localVarItem
@localVarItem = nil
else
if #@locals > 0
@localVarItem = @createLocalVarItem!
if @localVarFrom
@renameLocalVar @localVarFrom,@localVarTo
@localVarFrom,@localVarTo = nil,nil
renameLocalVar:(fromName,toName)=>
nextExpr = (expr)->
return false unless "table" == type expr
renamed = false
switch expr[1]
when "Action"
return false
when "LocalName"
if expr[2] == fromName
expr[2] = toName
renamed = true
for i = 2,#expr
if nextExpr expr[i]
renamed = true
renamed
children = @editor.triggerMenu.children
startIndex = children\index(@actionItem)+1
indent = @actionItem.indent
for item in *children[startIndex,]
break if item.indent == indent
if item.expr and nextExpr item.expr
item.text = tostring item.expr
Class ExprEditorView,
__init:(args)=>
@type = args.type
switch @type
when "Action"
@args = action:"UnitAction"
@extension = ".action"
when "Trigger"
@args = {}
@extension = ".trigger"
when "AINode"
@args = {}
@extension = ".node"
@exprData = nil
@filename = nil
@asyncLoad = false
@currentScope = nil
@varScopes = switch @type
when "Action"
{
Run: VarScope @
Stop: VarScope @
}
when "Trigger"
Action: VarScope @
else
{}
@newName = nil
@modified = false
@codeMode = TriggerDef.CodeMode
for child in *@editMenu.children
child.scale = oScale 0.3,1,1,oEase.OutQuad
@_selectedExprItem = nil
@changeExprItem = (button)->
@_selectedExprItem.checked = false if @_selectedExprItem
@_selectedExprItem = button.checked and button or nil
if button.checked
if @_selectedExprItem.errorInfo
@errorInfoBtn\display true
else
@errorInfoBtn\display false
@editMenu.visible = true
@editMenu.transformTarget = button
@editMenu.position = oVec2 button.width,0
{:expr,:index,:parentExpr} = @_selectedExprItem
@currentScope = @varScopes[(parentExpr or expr)[1]]
subExprItem = switch @_selectedExprItem.itemType
when "Mid","End" then true
else false
rootItem = switch expr[1]
when "Trigger","Event","Condition","Action","ConditionNode" then true
when "UnitAction","Available","Run","Stop" then true
else
if parentExpr then parentExpr[1] == "UnitAction"
else false
edit = not subExprItem
insert = if rootItem then false
elseif subExprItem then false
elseif #@triggerMenu.children >= 999 then false
elseif parentExpr then (parentExpr[1] ~= "Event")
else true
add = switch expr[1]
when "Trigger","Event" then false
when "UnitAction" then false
when "Available","Run","Stop" then true
else
if rootItem or #@triggerMenu.children >= 999 then false
elseif parentExpr then (parentExpr[1] ~= "Event")
else true
copy = add and parentExpr and parentExpr[1] ~= "Event"
del = if rootItem
false
elseif parentExpr and (switch parentExpr[1]
when "Condition","Event","Available" then #parentExpr == 2
when "ConditionNode" then #parentExpr == 3
else false)
false
else
not subExprItem
mode = switch expr[1]
when "UnitAction","Trigger","ConditionNode" then true
else false
up = not subExprItem and not rootItem and index and (switch parentExpr[1]
when "ConditionNode" then index > 3
else index > 2)
down = index and index < #parentExpr and not subExprItem and not rootItem
buttons = for v,k in pairs {:edit,:copy,:insert,:add,:del,:up,:down,:mode}
if k then v
else continue
@showEditButtons buttons
else
@errorInfoBtn\display false
@editMenu.visible = false
@editMenu.transformTarget = nil
@setupMenuScroll @triggerMenu
mode = (code,text)-> TriggerDef.CodeMode and code or text
nextExpr = (parentExpr,index,indent)->
expr = index and parentExpr[index] or parentExpr
switch expr[1]
when "Trigger"
if TriggerDef.CodeMode
@createExprItem "return",indent
@createExprItem tostring(expr),indent,expr
else
@createExprItem "Trigger",indent
@createExprItem tostring(expr),indent+1,expr
@createExprItem " ",indent
indent -= 1
for i = 4,#expr
nextExpr expr,i,indent+1
@createExprItem mode(")"," "),indent
when "Event"
with @createExprItem mode(tostring(expr),"Event"),indent,expr
.itemType = "Start"
.actionExpr = expr
for i = 2,#expr
nextExpr expr,i,indent+1
with @createExprItem mode("),"," "),indent
.itemType = "End"
indent -= 1
when "Condition"
@conditionItem = with @createExprItem mode(tostring(expr),"Condition"),indent,expr
.itemType = "Start"
.actionExpr = expr
for i = 2,#expr
nextExpr expr,i,indent+1
with @createExprItem mode("end ),"," "),indent
.itemType = "End"
when "UnitAction"
if TriggerDef.CodeMode
@createExprItem "return",indent
@createExprItem tostring(expr),indent,expr
else
@createExprItem "Unit Action",indent
@createExprItem tostring(expr),indent+1,expr
for i = 3,#expr
nextExpr expr,i,indent+1
@createExprItem mode(")"," "),indent
when "Available"
with @createExprItem mode(tostring(expr),"Available"),indent,expr
.itemType = "Start"
.actionExpr = expr
for i = 2,#expr
nextExpr expr,i,indent+1
with @createExprItem mode("end,"," "),indent
.itemType = "End"
when "Run","Stop","Action"
@currentScope = @varScopes[expr[1]]
@currentScope.actionItem = with @createExprItem mode(tostring(expr),expr[1]),indent,expr
.itemType = "Start"
.actionExpr = expr
if expr[1] == "Action"
@actionItem = @currentScope.actionItem
children = @triggerMenu.children
index = #children+1
for i = 2,#expr
nextExpr expr,i,indent+1
with @currentScope
if #.locals > 0
.localVarItem = \createLocalVarItem!
.localVarItem.lineNumber = index
moveY = .localVarItem.height
start = index+1
stop = #children
for i = start,stop
child = children[i]
child.lineNumber = i
child.positionY -= moveY
with @createExprItem mode("end"..(expr[1] == "Run" and "," or "")," "),indent
.itemType = "End"
when "ConditionNode"
if TriggerDef.CodeMode
@createExprItem "return",indent
with @createExprItem tostring(expr),indent,expr
.itemType = "Start"
.actionExpr = expr
else
@createExprItem "AI Condition Node",indent
with @createExprItem tostring(expr),indent+1,expr
.itemType = "Start"
.actionExpr = expr
indent += 1
for i = 3,#expr
nextExpr expr,i,indent+1
with @createExprItem mode("end )"," "),indent
.itemType = "End"
when "If"
with @createExprItem tostring(expr),indent,expr,parentExpr,index
.itemType = "Start"
.actionExpr = expr[3]
for i = 2,#expr[3]
nextExpr expr[3],i,indent+1
with @createExprItem mode("else","Else do."),indent,expr,parentExpr,index
.itemType = "Mid"
.actionExpr = expr[4]
for i = 2,#expr[4]
nextExpr expr[4],i,indent+1
with @createExprItem mode("end","End."),indent,expr,parentExpr,index
.itemType = "End"
when "Perform"
performExpr = expr[2]
wait = expr[3]
with @createExprItem tostring(expr),indent,expr,parentExpr,index
.itemType = "Start"
.actionExpr = performExpr[3]
for i = 2,#performExpr[3]
nextExpr performExpr[3],i,indent+1
with @createExprItem mode(")"..(wait and " )" or ""),"End."),indent,expr,parentExpr,index
.itemType = "End"
when "Sequence","Spawn"
groupExpr = expr[2]
with @createExprItem " ",indent,expr,parentExpr,index
.itemType = "Start"
.text = tostring expr
.actionExpr = groupExpr
for i = 2,#groupExpr
nextExpr groupExpr,i,indent+1
with @createExprItem " ",indent,expr,parentExpr,index
.itemType = "End"
.text = mode ")","End."
when "Loop"
with @createExprItem tostring(expr),indent,expr,parentExpr,index
.itemType = "Start"
.actionExpr = expr[6]
for i = 2,#expr[6]
nextExpr expr[6],i,indent+1
with @createExprItem mode("end )","End."),indent,expr,parentExpr,index
.itemType = "End"
when "SetLocal"
assignExpr = expr[2]
exprName = assignExpr[1]
varType = exprName\sub 9,-1
varName = assignExpr[2][2]
if varName ~= "InvalidName"
if not (@exprData[4][2].Args and @exprData[4][2].Args[varName])
with @currentScope
if not .localSet[varName]
table.insert .locals,varName
.localSet[varName] = varType
@createExprItem tostring(expr),indent,expr,parentExpr,index
else
@createExprItem tostring(expr),indent,expr,parentExpr,index
@nextExpr = (parentExpr,indent,index)=>
nextExpr parentExpr,index,indent -- param orders changed
addNewItem = (selectedExprItem,indent,parentExpr,index,delExpr=true,insertAfter=false)->
-- update triggerMenu
children = @triggerMenu.children
itemIndex = children\index selectedExprItem
startIndex = #children+1
@nextExpr parentExpr,indent,index
stopIndex = #children
-- get new items
newItems = [child for child in *children[startIndex,stopIndex]]
-- unselect item
targetItem = selectedExprItem
targetExpr = targetItem.expr
selectedExprItem.checked = false
@.changeExprItem selectedExprItem
-- remove old expr items
if delExpr
if targetExpr.MultiLine
endSearch = false
targetItems = for childItem in *children[itemIndex,]
break if endSearch
if childItem.expr == targetExpr and childItem.itemType == "End"
endSearch = true
childItem
childItem
for item in *targetItems
@triggerMenu\removeChild item
else
@triggerMenu\removeChild targetItem
elseif insertAfter
currentType = selectedExprItem.itemType
if targetExpr.MultiLine and currentType ~= "End"
switch currentType
when "Start","Mid"
itemIndex += 1
for i = itemIndex,#children
childItem = children[i]
isLineStop = switch childItem.itemType
when "End","Mid" then true
else false
if childItem.expr == targetExpr and isLineStop
itemIndex = i
break
else
itemIndex += 1
-- insert new expr items in right position
for item in *newItems
children\insert item,itemIndex
itemIndex += 1
-- separate condition exprs by comma
if not delExpr and
(((switch parentExpr[1]
when "Available","Condition","ConditionNode" then true
else false) and
selectedExprItem.expr.Type == "Boolean") or
(parentExpr[1] == "ActionGroup" and
selectedExprItem.expr.Type == "Action"))
selectedExprItem\updateText!
-- remove duplicated new exprs
for i = startIndex,stopIndex
children\removeLast!
-- refresh local variable names
@currentScope\refreshLocalVars! if @currentScope
-- update items position
offset = @offset
@offset = oVec2.zero
@viewSize = @triggerMenu\alignItems 0
@offset = offset
-- select new expr item
newItems[1].checked = true
@.changeExprItem newItems[1]
@scrollToPosY newItems[1].positionY
@notifyEdit!
@editBtn\slot "Tapped",->
selectedExprItem = @_selectedExprItem
if selectedExprItem
{:expr,:parentExpr,:index} = selectedExprItem
valueType = (expr.TypeIgnore or expr.Type == "None") and "TriggerAction" or expr.Type
with ExprChooser {
valueType:valueType
expr:expr
parentExpr:parentExpr
owner:@
}
\slot "Result",(newExpr)->
if parentExpr
parentExpr[index] = newExpr
if newExpr.Type == "Event"
@conditionItem\updateText!
@actionItem\updateText!
@updateArgs!
addNewItem selectedExprItem,selectedExprItem.indent,parentExpr,index
return
switch expr[1]
when "UnitAction","Trigger","ConditionNode"
if @newName
oldFileFullname = editor.gameFullPath..@filename
filePath = Path.getPath oldFileFullname
newFileFullname = filePath..@newName..@extension
return if oldFileFullname == newFileFullname
if oContent\exist newFileFullname
MessageBox text:"#{ @type } Name Exist!",okOnly:true
oldName = Path.getName @filename
@triggerName = oldName
emit "Scene.#{ @type }.ChangeName",oldName
elseif not Path.isValid Path.getFilename newFileFullname
MessageBox text:"Invalid Name!",okOnly:true
oldName = Path.getName @filename
@triggerName = oldName
emit "Scene.#{ @type }.ChangeName",oldName
else
oContent\saveToFile newFileFullname,TriggerDef.ToEditText @exprData
oContent\remove oldFileFullname
@filename = Path.getPath(@filename)..@newName..@extension
@newName = nil
selectedExprItem.text = tostring expr
@notifyEdit!
insertNewExpr = (after)-> ->
selectedExprItem = @_selectedExprItem
{:expr,:indent,:parentExpr,:index} = selectedExprItem
parentExpr or= expr
if after
switch selectedExprItem.itemType
when "Start","Mid"
parentExpr = selectedExprItem.actionExpr
index = #parentExpr+1
indent += 1
if index > 2
lastExpr = parentExpr[#parentExpr]
isMultiLine = lastExpr.MultiLine
children = @triggerMenu.children
startIndex = children\index(selectedExprItem)+1
for childItem in *children[startIndex,]
if childItem.expr == lastExpr and (isMultiLine == (childItem.itemType == "End"))
selectedExprItem = childItem
break
else
index += 1
else
indent += (parentExpr.MultiLine and 1 or 0)
index or= #parentExpr
valueType = switch parentExpr[1]
when "Event" then "Event"
when "Available","Condition","ConditionNode" then "Boolean"
when "ActionGroup" then "Action"
else "TriggerAction"
with ExprChooser {
valueType:valueType
parentExpr:parentExpr
owner:@
}
\slot "Result",(newExpr)->
return unless newExpr
table.insert parentExpr,index,newExpr
addNewItem selectedExprItem,indent,parentExpr,index,false,after
with @copyBtn
.copying = false
\slot "Tapped",->
.copying = not .copying
if .copying
.text = "Paste"
.color = ccColor3 0xff88cc
copyTable = (tb,target)->
for i = 1,#target
item = target[i]
if "table" == type item
item = copyTable {},item
tb[i] = item
setmetatable tb,getmetatable target
.targetExpr = copyTable {},@_selectedExprItem.expr
else
selectedExprItem = @_selectedExprItem
{:indent,:parentExpr,:index} = selectedExprItem
switch selectedExprItem.itemType
when "Start","Mid"
parentExpr = selectedExprItem.actionExpr
index = #parentExpr+1
indent += 1
else
index += 1
switch .targetExpr.Type
when "Boolean"
if not (switch parentExpr[1]
when "Condition","Available","ConditionNode" then true
else false)
.copying = true
MessageBox text:"Can Not Paste\nBoolean Item\nHere",okOnly:true
return
when "Action"
if not (switch parentExpr[1]
when "ActionGroup" then true
else false)
.copying = true
MessageBox text:"Can Not Paste\nAction Item\nHere",okOnly:true
return
else
switch parentExpr[1]
when "Condition","Available","ConditionNode","ActionGroup"
.copying = true
MessageBox text:"Can Not Paste\nTrigger Action\nHere",okOnly:true
return
.text = "Copy"
.color = ccColor3 0x00ffff
table.insert parentExpr,index,.targetExpr
addNewItem selectedExprItem,indent,parentExpr,index,false,true
.targetExpr = nil
@insertBtn\slot "Tapped",insertNewExpr false
@addBtn\slot "Tapped",insertNewExpr true
@delBtn\slot "Tapped",->
selectedExprItem = @_selectedExprItem
{:expr,:parentExpr,:index} = selectedExprItem
selectedExprItem.checked = false
@.changeExprItem selectedExprItem
table.remove parentExpr,index
children = @triggerMenu.children
startIndex = children\index(selectedExprItem)
if expr.MultiLine
isMultiLine = expr.MultiLine
searchEnd = false
delItems = for childItem in *children[startIndex,]
break if searchEnd
if childItem.expr == expr and (isMultiLine == (childItem.itemType == "End"))
searchEnd = true
childItem
for item in *delItems
@triggerMenu\removeChild item
else
@triggerMenu\removeChild selectedExprItem
if @currentScope and expr.Type == "None" or expr.TypeIgnore
@currentScope\refreshLocalVars!
offset = @offset
@offset = oVec2.zero
@viewSize = @triggerMenu\alignItems 0
@offset = offset
prevItem = children[startIndex-1]
prevItem.checked = true if prevItem.expr
@.changeExprItem prevItem
{expr:prevExpr,parentExpr:prevParent} = prevItem
if prevExpr and prevParent and
((prevExpr[1] ~= "Condition" and prevParent[1] == "Condition") or
(prevExpr[1] ~= "Available" and prevParent[1] == "Available") or
(prevExpr[1] ~= "ConditionNode" and prevParent[1] == "ConditionNode"))
prevItem\updateText!
@notifyEdit!
@upBtn\slot "Tapped",->
selectedExprItem = @_selectedExprItem
{:expr,:parentExpr,:index} = selectedExprItem
selectedExprItem.checked = false
@.changeExprItem selectedExprItem
table.remove parentExpr,index
table.insert parentExpr,index-1,expr
children = @triggerMenu.children
startIndex = children\index(selectedExprItem)
targetExpr = selectedExprItem.actionExpr or parentExpr
currentItem = selectedExprItem
prevIndex = startIndex-1
prevItem = children[prevIndex]
if prevItem.itemType == "End"
prevExpr = prevItem.expr
for i = startIndex,1,-1
item = children[i]
if item.expr == prevExpr and item.itemType == "Start"
prevIndex = i
break
if expr.MultiLine
searchEnd = false
items = for item in *children[startIndex,]
break if searchEnd
if item.expr == expr and item.itemType == "End"
searchEnd = true
currentItem = item
item
for item in *items
children\remove item
children\insert item,prevIndex
prevIndex += 1
else
children\remove selectedExprItem
children\insert selectedExprItem,prevIndex
switch targetExpr[1]
when "Condition","Available","ConditionNode","ActionGroup"
prevItem\updateText!
currentItem\updateText!
offset = @offset
@offset = oVec2.zero
@viewSize = @triggerMenu\alignItems 0
@offset = offset
selectedExprItem.checked = true
@.changeExprItem selectedExprItem
@scrollToPosY selectedExprItem.positionY
@notifyEdit!
@downBtn\slot "Tapped",->
selectedExprItem = @_selectedExprItem
{:expr,:parentExpr,:index} = selectedExprItem
selectedExprItem.checked = false
@.changeExprItem selectedExprItem
table.remove parentExpr,index
table.insert parentExpr,index+1,expr
children = @triggerMenu.children
startIndex = children\index(selectedExprItem)
targetExpr = selectedExprItem.actionExpr or parentExpr
currentItem = selectedExprItem
nextItem = children[startIndex+1]
nextIndex = startIndex+1
if expr.MultiLine
for i = startIndex,#children
childItem = children[i]
if childItem.expr == expr and childItem.itemType == "End"
currentItem = childItem
nextIndex = i+1
break
nextItem = children[nextIndex]
nextItems = if nextItem.itemType == "Start"
tmpExpr = nextItem.expr
searchEnd = false
for item in *children[nextIndex,]
break if searchEnd
if item.expr == tmpExpr and item.itemType == "End"
nextItem = item
searchEnd = true
item
else
{nextItem}
for item in *nextItems
children\remove item
children\insert item,startIndex
startIndex += 1
switch targetExpr[1]
when "Condition","Available","ConditionNode","ActionGroup"
currentItem\updateText!
nextItem\updateText!
offset = @offset
@offset = oVec2.zero
@viewSize = @triggerMenu\alignItems 0
@offset = offset
selectedExprItem.checked = true
@.changeExprItem selectedExprItem
@scrollToPosY selectedExprItem.positionY
@notifyEdit!
@modeBtn\slot "Tapped",->
thread ->
sleep 0.3
@codeMode = not @codeMode
TriggerDef.CodeMode = @codeMode
@loadExpr @exprData
@modeBtn\schedule once ->
wait -> @asyncLoad
for child in *@triggerMenu.children
if child.expr == @exprData
child.checked = true
@.changeExprItem child
break
displayButton = (button,display)->
if display
with button
.visible = true
.scaleX,.scaleY = 0,0
\perform oScale 0.3,1,1,oEase.OutQuad
elseif button.visible
button\perform CCSequence {
oScale 0.3,0,0,oEase.InBack
CCHide!
}
with @errorBtn
.visible = false
.color = ccColor3 0xff0080
\slot "Tapped",->
item = @errorBtn.errorItems[@errorBtn.currentIndex]
if item.checked
@errorBtn.currentIndex %= #@errorBtn.errorItems
@errorBtn.currentIndex += 1
item = @errorBtn.errorItems[@errorBtn.currentIndex]
if @errorBtn.currentIndex > #@errorBtn.errorItems
@errorBtn.currentIndex = 1
else
item.checked = true
@.changeExprItem item
@scrollToPosY item.positionY
@errorBtn.currentIndex %= #@errorBtn.errorItems
@errorBtn.currentIndex += 1
.display = displayButton
with @errorInfoBtn
.visible = false
.color = ccColor3 0xff0080
.display = displayButton
\slot "Tapped",->
{:width,:height} = CCDirector.winSize
panelWidth = 350
with PopupPanel {
x:width/2
y:height/2
width:panelWidth
height:300
}
.menu\addChild with CCNode!
.contentSize = CCSize panelWidth-20,40
\addChild with CCLabelTTF "Error In Line #{@_selectedExprItem.lineNumber}","Arial",24
.color = ccColor3 0x00ffff
.position = oVec2 (panelWidth-20)/2,10
.menu\addChild with ExprItem text:@_selectedExprItem.errorInfo,width:panelWidth-40
.enabled = false
.scrollArea.viewSize = .menu\alignItemsVertically!
checkReload = ->
if @codeMode ~= TriggerDef.CodeMode
@codeMode = TriggerDef.CodeMode
@loadExpr @exprData
else
@lintCode!
@slot "Entered",checkReload
@gslot "Scene.#{ @type }.ChangeName",(newName)-> @newName = newName
@gslot "Scene.#{ @type }.Open",checkReload
updateArgs:=>
if @exprData[1] == "Trigger"
eventExpr = @exprData[4][2]
@args = if eventExpr.Args
{k,v\match "^%a*" for k,v in pairs eventExpr.Args}
else {}
selectedLine:property =>
if @_selectedExprItem
@_selectedExprItem.lineNumber
else
nil,
(value)=>
item = @triggerMenu.children[value]
item.checked = true
@.changeExprItem item
notifyEdit:=>
children = @triggerMenu.children
for i = 1,#children
children[i].lineNumber = i
@modified = true
@lintCode!
emit "Scene.#{ @type }.Edited",@filename
createExprItem:(text,indent,expr,parentExpr,index)=>
children = @triggerMenu.children
lastItem = children and children.last or nil
lineNumber = children and #children+1 or 1
exprItem = with ExprItem {
:indent
:text
:expr
:parentExpr
:index
:lineNumber
width:@triggerMenu.width
}
.position = lastItem and
(lastItem.position-oVec2(0,lastItem.height/2+.height/2)) or
oVec2(@triggerMenu.width/2,@triggerMenu.height-.height/2)+@offset
\slot "Tapped",@changeExprItem if expr
@triggerMenu\addChild exprItem
{:width,:height} = @viewSize
@viewSize = CCSize width,@[email protected]+exprItem.height/2
sleep! if @asyncLoad
exprItem
loadExpr:(arg)=>
if @_selectedExprItem
@_selectedExprItem.checked = false
@.changeExprItem @_selectedExprItem
@exprData = switch type arg
when "table" then arg
when "string"
@filename = arg
TriggerDef.SetExprMeta dofile arg
@updateArgs!
@view\schedule once ->
menuEnabled = @triggerMenu.enabled
@triggerMenu.enabled = false
@triggerMenu\removeAllChildrenWithCleanup!
for _, scope in pairs @varScopes do scope\clear!
@offset = oVec2.zero
@asyncLoad = true
@nextExpr @exprData,0
@asyncLoad = false
@triggerMenu.enabled = menuEnabled
@lintCode!
if @targetLine
@selectedLine = @targetLine
@targetLine = nil
@exprData
codeMode:property => @_codeMode,
(value)=>
@_codeMode = value
@modeBtn.text = value and "Text" or "Code"
@modeBtn.color = ccColor3 value and 0xffff88 or 0xff88cc
save:=>
triggerText = TriggerDef.ToEditText @exprData
oContent\saveToFile editor.gameFullPath..@filename,triggerText
if not @isCodeHasError
codeFile = editor.gameFullPath..@filename
codeFile = Path.getPath(codeFile)..Path.getName(codeFile)..".lua"
triggerCode = TriggerDef.ToCodeText @exprData
oContent\saveToFile codeFile,triggerCode
isInAction:property => not @isInCondition and not @isInEvent
isInCondition:property =>
{:expr,:parentExpr} = @_selectedExprItem
condA = expr and switch expr[1]
when "Available","Condition","ConditionNode" then true
else false
condB = parentExpr and switch parentExpr[1]
when "Available","Condition","ConditionNode" then true
else false
not condA and condB
isInEvent:property =>
{:expr,:parentExpr} = @_selectedExprItem
switch expr[1]
when "Event" then parentExpr and parentExpr[1] == "Event"
when "Priority","Reaction","Recovery" then true
else false
getPrevLocalVars:(targetType)=>
localVars = for k,v in pairs @args
if v == targetType then k
else continue
return localVars if not @isInAction
targetExpr = @_selectedExprItem.expr
varScope = {}
varInScope = (varName)->
local result
for scope in *varScope
varType = scope[varName]
result = varType if varType
return result
nextExpr = (expr)->
return false unless "table" == type expr
switch expr[1]
when "SetLocal"
assignExpr = expr[2]
exprName = assignExpr[1]
varType = exprName\sub 9,-1
varName = assignExpr[2][2]
scope = varScope[#varScope]
if varName ~= "InvalidName"
scope[varName] = varType
when "Loop"
scope = if varInScope expr[2][2] then {} else {[expr[2][2]]:"Number"}
table.insert varScope,scope
actionExpr = expr[6]
for i = 2,#actionExpr
if nextExpr actionExpr[i]
return true -- true to stop search
table.remove varScope
when "Action"
table.insert varScope,{}
for i = 2,#expr
if nextExpr expr[i]
return true
table.remove varScope
else
for i = 2,#expr
if nextExpr expr[i]
return true
expr == targetExpr
table.insert varScope,{}
nextExpr @currentScope.actionItem.expr
for scope in *varScope
for v,k in pairs scope
if k == targetType
table.insert localVars,v
localVars
markLocalVarRename:(fromName,toName)=>
@currentScope.localVarFrom = fromName
@currentScope.localVarTo = toName
showEditButtons:(names)=>
buttonSet = {@["#{ name }Btn"],true for name in *names}
posX = @editMenu.width-35-(buttonSet[@modeBtn] and 60 or 0)
for i = #@editMenu.children,1,-1
child = @editMenu.children[i]
if buttonSet[child]
child.positionX = posX
child.visible = true
with child.face
.scaleX = 0
.scaleY = 0
\perform child.scale
posX -= 60
else
child.visible = false
triggerName:property => @exprData[2][2],
(value)=> @exprData[2][2] = value
enabled:property => @touchEnabled,
(value)=>
@touchEnabled = value
@triggerMenu.enabled = value
@editMenu.enabled = value
isCodeHasError:property => #@errorBtn.errorItems > 0
lintCode:=>
return unless @triggerMenu.children
@errorBtn.errorItems = {}
@errorBtn.currentIndex = 1
locals = {k,v for k,v in pairs @args}
globals = {expr[2][2],expr[3].Type for expr in *editor\getGlobalExpr![2,]}
lintFunc = TriggerDef.GetLintFunction locals,globals
checkError = (item)->
if item.expr
errorInfo = lintFunc item.expr,item.parentExpr,item.itemType
if errorInfo == ""
item\markError false
else
item\markError true,errorInfo
table.insert @errorBtn.errorItems,item
elseif item.itemType == "End"
lintFunc nil,nil,"End"
for item in *@triggerMenu.children
checkError item
@errorBtn\display #@errorBtn.errorItems > 0
@errorInfoBtn\display false if #@errorBtn.errorItems == 0
if @_selectedExprItem and @_selectedExprItem.errorInfo
@errorInfoBtn\display true
if @isCodeHasError
codeFile = editor.gameFullPath..@filename
codeFile = Path.getPath(codeFile)..Path.getName(codeFile)..".lua"
oContent\remove codeFile if oContent\exist codeFile
| 30.595214 | 94 | 0.666862 |
62fcf0add5c428682fd78c27d10041fcfc5329c4 | 2,393 | -- Copyright 2014-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
core = require 'ljglibs.core'
require 'ljglibs.cdefs.pango'
core.auto_loading 'pango', {
constants: {
prefix: 'PANGO_'
'ALIGN_LEFT',
'ALIGN_CENTER',
'ALIGN_RIGHT',
-- PangoEllipsizeMode
'ELLIPSIZE_NONE',
'ELLIPSIZE_START',
'ELLIPSIZE_MIDDLE',
'ELLIPSIZE_END',
-- PangoStyle
'STYLE_NORMAL',
'STYLE_OBLIQUE',
'STYLE_ITALIC',
-- PangoVariant
'VARIANT_NORMAL',
'VARIANT_SMALL_CAPS',
-- PangoWeight
'WEIGHT_THIN',
'WEIGHT_ULTRALIGHT',
'WEIGHT_LIGHT',
'WEIGHT_BOOK',
'WEIGHT_NORMAL',
'WEIGHT_MEDIUM',
'WEIGHT_SEMIBOLD',
'WEIGHT_BOLD',
'WEIGHT_ULTRABOLD',
'WEIGHT_HEAVY',
'WEIGHT_ULTRAHEAVY',
-- PangoStretch
'STRETCH_ULTRA_CONDENSED',
'STRETCH_EXTRA_CONDENSED',
'STRETCH_CONDENSED',
'STRETCH_SEMI_CONDENSED',
'STRETCH_NORMAL',
'STRETCH_SEMI_EXPANDED',
'STRETCH_EXPANDED',
'STRETCH_EXTRA_EXPANDED',
'STRETCH_ULTRA_EXPANDED'
-- PangoFontMask
'FONT_MASK_FAMILY',
'FONT_MASK_STYLE',
'FONT_MASK_VARIANT',
'FONT_MASK_WEIGHT',
'FONT_MASK_STRETCH',
'FONT_MASK_SIZE',
'FONT_MASK_GRAVITY',
-- PangoUnderline
'UNDERLINE_NONE',
'UNDERLINE_SINGLE',
'UNDERLINE_DOUBLE',
'UNDERLINE_LOW',
'UNDERLINE_ERROR',
-- PangoGravity
'GRAVITY_SOUTH',
'GRAVITY_EAST',
'GRAVITY_NORTH',
'GRAVITY_WEST',
'GRAVITY_AUTO',
-- PangoGravityHint
'GRAVITY_HINT_NATURAL',
'GRAVITY_HINT_STRONG',
'GRAVITY_HINT_LINE',
-- PangoAttributeConstants
'ATTR_INDEX_FROM_TEXT_BEGINNING',
'ATTR_INDEX_TO_TEXT_END',
-- PangoTabAlign
'TAB_LEFT'
-- PangoAttrType
'ATTR_INVALID'
'ATTR_LANGUAGE'
'ATTR_FAMILY'
'ATTR_STYLE'
'ATTR_WEIGHT'
'ATTR_VARIANT'
'ATTR_STRETCH'
'ATTR_SIZE'
'ATTR_FONT_DESC'
'ATTR_FOREGROUND'
'ATTR_BACKGROUND'
'ATTR_UNDERLINE'
'ATTR_STRIKETHROUGH'
'ATTR_RISE'
'ATTR_SHAPE'
'ATTR_SCALE'
'ATTR_FALLBACK'
'ATTR_LETTER_SPACING'
'ATTR_UNDERLINE_COLOR'
'ATTR_STRIKETHROUGH_COLOR'
'ATTR_ABSOLUTE_SIZE'
'ATTR_GRAVITY'
'ATTR_GRAVITY_HINT'
-- PangoWrapMode
'WRAP_WORD',
'WRAP_CHAR',
'WRAP_WORD_CHAR'
},
SCALE: 1024
}
| 19.77686 | 79 | 0.657752 |
bbbe267c50f892950169b90c94cdd78229546542 | 8,387 |
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) ->
ccs = for k,v in pairs t
if type(k) == "number"
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: (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, :CONTENT_FOR_PREFIX }
| 22.013123 | 102 | 0.549779 |
7a434071b1f889af074f4e4659568c28f99ac4a2 | 1,430 | -- title: game title
-- author: game developer, email, etc.
-- desc: short description
-- site: website link
-- license: MIT License (change this to your license of choice)
-- version: 0.1
-- script: moon
t=0
x=96
y=24
export TIC=->
if btn 0
y-=1
if btn 1
y+=1
if btn 2
x-=1
if btn 3
x+=1
cls 13
spr 1+(t%60)//30*2,x,y,14,3,0,0,2,2
print "HELLO WORLD!",84,84
t+=1
-- <TILES>
-- 001:eccccccccc888888caaaaaaaca888888cacccccccacc0ccccacc0ccccacc0ccc
-- 002:ccccceee8888cceeaaaa0cee888a0ceeccca0ccc0cca0c0c0cca0c0c0cca0c0c
-- 003:eccccccccc888888caaaaaaaca888888cacccccccacccccccacc0ccccacc0ccc
-- 004:ccccceee8888cceeaaaa0cee888a0ceeccca0cccccca0c0c0cca0c0c0cca0c0c
-- 017:cacccccccaaaaaaacaaacaaacaaaaccccaaaaaaac8888888cc000cccecccccec
-- 018:ccca00ccaaaa0ccecaaa0ceeaaaa0ceeaaaa0cee8888ccee000cceeecccceeee
-- 019:cacccccccaaaaaaacaaacaaacaaaaccccaaaaaaac8888888cc000cccecccccec
-- 020:ccca00ccaaaa0ccecaaa0ceeaaaa0ceeaaaa0cee8888ccee000cceeecccceeee
-- </TILES>
-- <WAVES>
-- 000:00000000ffffffff00000000ffffffff
-- 001:0123456789abcdeffedcba9876543210
-- 002:0123456789abcdef0123456789abcdef
-- </WAVES>
-- <SFX>
-- 000:000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000304000000000
-- </SFX>
-- <PALETTE>
-- 000:1a1c2c5d275db13e53ef7d57ffcd75a7f07038b76425717929366f3b5dc941a6f673eff7f4f4f494b0c2566c86333c57
-- </PALETTE>
| 26.981132 | 139 | 0.805594 |
6ca722fa3787a9e9e723f9ef1a25457babdfed68 | 30 | require "pgmoon-mashape.init"
| 15 | 29 | 0.8 |
6a1411c680a5445d2f0be10c4d410ba81442a58b | 107 | foldr = zb2rhddJhRBavTQ8iAznuNhyYHkg7bUyfp4G7i1BCnjBtyLGT
f => (foldr chr => res => (con (f chr) res) "")
| 26.75 | 57 | 0.71028 |
427501906254a3481d661f090de206a868364b66 | 1,092 | export modinfo = {
type: "command"
desc: "Clean"
alias: {"clean"}
func: (Msg,Speaker) ->
for i,s in pairs(workspace\GetChildren())
if PlayersService\GetPlayerFromCharacter(s) == nil
if not s\IsA"Terrain"
if not s\IsA"Camera"
pcall -> s.Parent = nil
b = CreateInstance"Part"
Size: Vector3.new(3000, 1, 3000)
CFrame: CFrame.new(0, 0, 0)
Name: "Base"
BrickColor: BrickColor.new("Earth green")
TopSurface: "Smooth"
BottomSurface: "Smooth"
LeftSurface: "Smooth"
RightSurface: "Smooth"
FrontSurface: "Smooth"
BackSurface: "Smooth"
Anchored: true
Locked: true
Parent: workspace
sl = CreateInstance"SpawnLocation"
Anchored: true
Locked: true
FormFactor: "Plate"
Size: Vector3.new(6, .4, 6)
CFrame: CFrame.new(0, .6, 0)
BrickColor: BrickColor.new("Really black")
TopSurface: "Smooth"
BottomSurface: "Smooth"
LeftSurface: "Smooth"
RightSurface: "Smooth"
FrontSurface: "Smooth"
BackSurface: "Smooth"
Parent: workspace
Output("Cleaned workspace",{Colors.Green})
loggit("Cleaned Workspace")
} | 26 | 53 | 0.668498 |
4cda950300e0f9319df7e4f4d4372f9a1ee4006c | 436 | M = {}
name1 = "lists"
name2 = "merge2"
TK = require("PackageToolkit")
FX = require("FunctionalX")
M.case = (input1, solution, msg="") ->
print TK.ui.dashed_line 80, '-'
print string.format "test %s.%s()", name1, name2
print msg
result = FX[name1][name2] unpack input1
print "Result: ", unpack result
assert TK.test.equal_lists result, solution
print "VERIFIED!"
print TK.ui.dashed_line 80, '-'
return M | 29.066667 | 52 | 0.646789 |
0ea54905c1d7606b3253108b185018bb4b93bdc2 | 216 | listToArray = zb2rhj3APjEyBffYfDUhef71pdkvq8N5HkixVN1hmCacPXJth
str =>
l = (len str)
(listToArray val => end =>
(for 0 l end n => list =>
i = (sub (sub l n) 1)
(val (slc str i (add i 1)) list)))
| 24 | 63 | 0.597222 |
96b12715570f1657b3ba56d52b08823c89432109 | 5,246 | -- Copyright 2012-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
import app, command, mode, interact, Buffer, Project from howl
import File from howl.io
with_vc = (f) ->
buffer = app.editor.buffer
unless buffer.file
log.error "No file associated with buffer '#{buffer}'"
return
project = Project.for_file buffer.file
unless project and project.vc
log.error "No VC found for buffer '#{buffer}'"
return
f project.vc, buffer, project
show_diff_buffer = (title, contents) ->
buffer = Buffer mode.by_name 'diff'
buffer.text = contents
buffer.title = "* Diff: #{title} *"
buffer.modified = false
buffer.can_undo = false
app\add_buffer buffer
auto_mkdir = (directory) ->
return true if directory.exists
if interact.yes_or_no prompt: "Directory #{directory} doesn't exist, create? "
directory\mkdir_p!
return true
return false
command.register
name: 'open',
description: 'Open a file'
input: -> interact.select_file allow_new: true
handler: (file) -> app\open_file file
command.register
name: 'open-recent',
description: 'Open a recently visited file'
input: ->
recent_files = {}
for buf in *app.buffers
continue unless buf.file
table.insert recent_files, {
buf.title,
buf.file.parent.short_path,
file: buf.file
}
for file_info in *app.recently_closed
table.insert recent_files, {
file_info.file.basename
file_info.file.parent.short_path
file: file_info.file
}
selected = interact.select_location
items: recent_files
columns: { {style: 'filename'}, {style: 'comment'} }
title: 'Recent files'
return selected and selected.selection.file
handler: app\open_file
command.alias 'open', 'e'
command.register
name: 'project-open',
description: 'Open a file in the current project'
input: ->
buffer = app.editor and app.editor.buffer
file = buffer and (buffer.file or buffer.directory)
if file
project = Project.get_for_file file
if project
return interact.select_file_in_project :project
else
log.warn "No file or directory associated with the current view"
return
handler: (file) ->
app\open_file file
command.register
name: 'save',
description: 'Save the current buffer to file'
handler: ->
buffer = app.editor.buffer
if not buffer.file
command.run 'save-as'
return
if buffer.modified_on_disk
overwrite = interact.yes_or_no
prompt: "Buffer '#{buffer}' has changed on disk, save anyway? "
default: false
unless overwrite
log.info "Not overwriting; buffer not saved"
return
unless auto_mkdir buffer.file.parent
log.info "Parent directory doesn't exist; buffer not saved"
return
buffer\save!
log.info ("%s: %d lines, %d bytes written")\format buffer.file.basename,
#buffer.lines, #buffer
command.alias 'save', 'w'
command.register
name: 'save-as',
description: 'Save the current buffer to a given file'
input: ->
file = interact.select_file allow_new: true
return unless file
if file.exists
unless interact.yes_or_no prompt: "File '#{file}' already exists, overwrite? "
log.info "Not overwriting; buffer not saved"
return
unless auto_mkdir file.parent
log.info "Parent directory doesn't exist; buffer not saved"
return
return file
handler: (file) ->
buffer = app.editor.buffer
buffer\save_as file
buffer.mode = mode.for_file file
log.info ("%s: %d lines, %d bytes written")\format buffer.file.basename,
#buffer.lines, #buffer
command.register
name: 'buffer-close',
description: 'Close the current buffer'
handler: ->
buffer = app.editor.buffer
app\close_buffer buffer
command.alias 'buffer-close', 'close'
command.register
name: 'vc-diff-file',
description: 'Show a diff against the VC for the current file'
handler: ->
with_vc (vc, buffer) ->
diff = vc\diff buffer.file
if diff
show_diff_buffer "[#{vc.name}] #{buffer.file.basename}", diff
else
log.info "VC: No differences found for #{buffer.file.basename}"
command.register
name: 'vc-diff',
description: 'Show a diff against the VC for the current project'
handler: ->
with_vc (vc, buffer, project) ->
diff = vc\diff!
if diff
show_diff_buffer "[#{vc.name}]: #{vc.root}", diff
else
log.info "VC: No differences found for #{project.root}"
command.register
name: 'diff-buffer-against-saved',
description: 'Show a diff against the saved file for the current buffer'
handler: ->
buffer = app.editor.buffer
unless buffer.file
log.error "No file associated with buffer '#{buffer}'"
return
File.with_tmpfile (file) ->
file.contents = buffer.text
pipe = assert io.popen "diff -u #{buffer.file} #{file}"
diff = assert pipe\read '*a'
pipe\close!
if diff and not diff.is_blank
show_diff_buffer "Compared to disk: #{buffer.file.basename}", diff
else
log.info "No unsaved modifications found for #{buffer.file.basename}"
| 28.053476 | 84 | 0.667366 |
961414d3ce95646fe53d84e1d3ef1a5789aa6367 | 622 | import Model from require "lapis.db.model"
import Users from require "models"
class ResourceScreenshots extends Model
-- Has created_at and modified_at
@timestamp: true
url_params: (reg, ...) => "resources.view_screenshot", { resource_slug: @resource, screenie_id: @id }, ...
-- get the direct url of this resource (not the page with the title and description, but the raw image data)
get_direct_url: (context) =>
res = @resource
if type(res) == "number"
res = Users\find res
context\url_for "resources.view_screenshot_image", resource_slug: res, screenie_id: @id
| 41.466667 | 113 | 0.686495 |
a3fe53fdc2fb112a93475b5f1cf6f7430b64f97f | 685 | -- 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.pango'
core = require 'ljglibs.core'
C, ffi_new, ffi_gc = ffi.C, ffi.new, ffi.gc
pc_t = ffi.typeof 'PangoColor'
core.define 'PangoColor', {
new: (r, g, b)->
color = pc_t!
if type(r) == 'string'
color\parse r
else
with color
.red = r
.green = g
.blue = b
color
parse: (spec) =>
if C.pango_color_parse(@, spec) == 0
error "Illegal color '#{spec}'", 2
meta: {
__tostring: => ffi.string C.pango_color_to_string(@)
}
}, (t, ...) -> t.new ...
| 20.147059 | 79 | 0.589781 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.