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
|
---|---|---|---|---|---|
ff10b4037246b410c0e43de31d7aec4bee87eebb | 6,423 | ---------------------------------------------------------------------------
-- Environment ------------------------------------------------------------
---------------------------------------------------------------------------
import format from string
import once from require 'fn'
settings = require 'hs.settings'
import run, execute from require 'shell'
{ urlParts:urlparts } = require 'hs.http'
{ new:newserver } = require 'hs.httpserver'
import dofile from require 'moonscript.base'
import javascript from require 'hs.osascript'
import compile, minify from require 'autoproxy.pac'
import map, mapk, keys, key, merge from require 'fn.table'
{ sigcheck:T, :isstring, :isboolean, :checkers } = require 'typecheck'
log = require('log').get 'autoproxy'
---------------------------------------------------------------------------
-- Implementation ---------------------------------------------------------
---------------------------------------------------------------------------
self =
_server: nil
_callback: nil
_profiles: nil
_config:
path: nil
minify: false
activenetworkservice = () ->
-- Shamelessly copied from https://apple.stackexchange.com/a/223446
result = run([[
services=$(networksetup -listnetworkserviceorder | grep 'Hardware Port')
while read line; do
sname=$(echo $line | awk -F "(, )|(: )|[)]" '{print $2}')
sdev=$(echo $line | awk -F "(, )|(: )|[)]" '{print $4}')
if [ -n "$sdev" ]; then
ifout="$(ifconfig $sdev 2>/dev/null)"
echo "$ifout" | grep 'status: active' > /dev/null 2>&1
rc="$?"
if [ "$rc" -eq 0 ]; then
currentservice="$sname"
currentdevice="$sdev"
currentmac=$(echo "$ifout" | awk '/ether/{print $2}')
fi
fi
done <<< "$(echo "$services")"
if [ -n "$currentservice" ]; then
echo $currentservice
echo $currentdevice
echo $currentmac
else
exit 1
fi]])
return result\match '(.+)\n(.+)\n(.+)' if result
networksetup = (cmd, value, service) ->
service or= activenetworkservice()
if not service
log.warn 'No active network service now. Use the last active one instead.' if log.warn
service = settings.get 'autoproxy.network-service' or 'Wi-Fi'
else
settings.set 'autoproxy.network-service', service
return if value == nil
run '/usr/bin/sudo', '/usr/sbin/networksetup', cmd, service
elseif isboolean value
execute '/usr/bin/sudo', '/usr/sbin/networksetup', cmd, service, value and 'on' or 'off'
else
execute '/usr/bin/sudo', '/usr/sbin/networksetup', cmd, service, value
makeurl = (server, path) ->
return format 'http://%s:%d/%s', server\getInterface! or '0.0.0.0', server\getPort!, path
profiles = () -> mapk @_profiles, (n, _) -> url: makeurl(@_server, n)
status = (tostr) ->
return (networksetup('-getautoproxyurl')) if tostr
url, enabled = networksetup('-getautoproxyurl')\match 'URL: (%g+)\nEnabled: (%a+)'
enabled = enabled == 'Yes'
if url == '(null)'
return nil, nil, enabled
else
if @_profiles
p = key profiles!, () => @url == url
return p, url, enabled if p
return nil, url, enabled
on = (p) ->
p or= (status!) or settings.get 'autoproxy.profile'
log.errorf 'Please specify a profile to use, candidates are: \n%s', profiles! unless p
log.info 'Switing to profile: ' .. p if log.info
networksetup '-setautoproxyurl', makeurl(@_server, p)
networksetup '-setautoproxystate', false
networksetup '-setautoproxystate', true
@._callback(p) if @_callback
settings.set 'autoproxy.profile', p
off = () ->
log.info 'Turning off...' if log.info
networksetup '-setautoproxystate', false
@._callback(nil) if @_callback
toggle = () ->
profile, _, enabled = status!
if enabled then off!
else
profile or= settings.get 'autoproxy.profile'
on profile
test = (url, host, p) ->
url = 'http://' .. url unless url\find 'http://', nil, true
host = host or urlparts(url).host
log.error 'Unable to extract host from possibly malformed URL:\n' .. url unless host
p or= (status!)
log.errorf 'Please specify a profile name to test against, candidates are:\n%s', keys @_profiles unless p
log.infof 'Testing with profile: ' .. p .. '\nURL: ' .. url .. '\nHOST: ' .. host
tester = 'function isPlainHostName(a){return !a.includes(".");}' .. @_profiles[p] .. format 'FindProxyForURL(%q,%q);', url, host
success, result, err = javascript tester
log.error 'An exception has occured: \n%s' .. err unless success
return result
load = (config, mini) ->
prsndicts = config.profiles
rsdict = config.rules
pdict = config.proxies
return map prsndicts, (prsndict) ->
pac = compile prsndict.proxies, prsndict, pdict, rsdict
return mini and minify(pac) or pac
callback = (c) -> @_callback = c
init = (options) ->
with options
@_config.minify = .minify or false
servercfg = .server or {
interface: 'localhost'
port: 8000
}
if isstring .config
@_config.path = .config -- load on start
else
@_profiles = load .config, @_config.minify
@_server = newserver!\setInterface(servercfg.interface)\setPort(servercfg.port)
start = () ->
if @_config.path
@_profiles = load dofile(@_config.path), @_config.minify
@_server\setCallback((method, path) ->
if method == 'GET'
if prof = path\match '^/(%a+)'
if resp = @_profiles[prof]
log.debugf 'Response: ' .. prof if log.debugf
return resp, 200, {}
log.debugf 'Invalid HTTP request: %s, "%s"', method, path if log.debugf
return 'Invalid Request', 400, {}
)\start!
if p = (status!) or settings.get 'autoproxy.profile'
on p
stop = () ->
off!
@_server\stop!
@_profiles = nil if @_config.path
restart = () ->
stop!
start!
checkers['autoproxy.profile'] = (v) -> isstring(v) and @_profiles and @_profiles[v]
---------------------------------------------------------------------------
-- Interface --------------------------------------------------------------
---------------------------------------------------------------------------
merge self, {
status: T '?boolean', status
on: T '?autoproxy.profile', on
test: T 'string, ?string, ?autoproxy.profile', test
callback: T 'function', once(callback)
init: T 'table', once(init)
:profiles, :start, :restart, :off, :toggle
}
| 32.770408 | 130 | 0.57045 |
81fce3f96353a94c25e46e0702e770ba25146ee8 | 353 | // Test this with `moon runIO _examples_`
do = zb2rhkLJtRQwHz9e5GjiQkBtjL2SzZZByogr1uNZFyzJGA9dX
askPowerLevel = loop@ lazy =>
| power =< (do "prompt" "What is your power level? ")
(if (gtn (stn power) 9000)
| (do "print" "No, it is not.")>
(loop 0)
| (do "print" "Ah, that's cute!")>
(do "stop"))
(askPowerLevel 0)
| 25.214286 | 55 | 0.600567 |
4ee2fb1747c7a02dcfa459c5e41458d26a482028 | 2,347 | #!/usr/bin/env moon
--- Create and manage IRC bots.
-- @script main.moon
-- @author Ryan "ChickenNuggers" <ryan@hashbang.sh>
Logger = require 'logger' -- vim:set noet sts=0 sw=3 ts=3:
cqueues = require 'cqueues'
lfs = require 'lfs'
moonscript = require "moonscript"
import IRCClient from require 'lib.irc'
wd = lfs.currentdir()
Logger.set_debug true if os.getenv 'DEBUG'
pcall -> -- use StackTracePlus if available; it's much better than builtin
debug.traceback = require("StackTracePlus").stacktrace
load_modules = (folder)->
for file in lfs.dir folder
if file\match "%.moon$"
path = "#{folder}/#{file}"
IRCClient\with_context path, assert moonscript.loadfile path
load_modules_in_plugin_folders = ->
for module_folder in *{'plugins', 'modules'}
full_path = wd .. '/' .. module_folder
load_modules full_path if lfs.attributes(full_path, 'mode') == 'directory'
load_modules_in_plugin_folders!
bots = {}
conf_home = os.getenv('XDG_CONFIG_HOME') or os.getenv('HOME') .. '/.config'
for file in lfs.dir "#{conf_home}/moonmoon"
if file\match "%.lua$"
local data
env =
bot: (name)->
return (file_data)->
file_data.name = name
file_data.file = file
data = file_data
fn = assert loadfile("#{conf_home}/moonmoon/#{file}", nil, env)
fn!
unless data and data.server
print "Missing `server` field: [#{file}]"
continue
if os.getenv 'DEBUG'
for key, value in pairs data
if type(value) == "string" then
print ("%q: %q")\format key, value
else
print ("%q: %s")\format key, value
bot = IRCClient data.server, data.port, data
table.insert(bots, bot)
queue = cqueues.new!
package.loaded["queue"] = queue -- for use in modules
for bot in *bots
queue\wrap ->
while true
local success
for i=1, 3 do -- three tries
ok, err = pcall bot.connect, bot
success = ok
if not ok
Logger.print Logger.level.error .. '*** Unable to connect: ' .. bot.config.server
Logger.debug Logger.level.error .. '*** ' .. err
else
break
if not success
Logger.print Logger.level.fatal .. '*** Not connecting anymore for: ' .. bot.config.file
return
ok, err = pcall -> bot\loop!
if not ok then
Logger.print Logger.level.error .. err
while not queue\empty!
ok, err = queue\step!
if not ok
Logger.debug "#{Logger.level.error} *** #{err}"
| 27.290698 | 92 | 0.665957 |
db8b948a22c77c79e3358a0a7c663a0e22ef86d5 | 9,316 |
-- Copyright (C) 2018-2020 DBotThePony
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
-- of the Software, and to permit persons to whom the Software is furnished to do so,
-- subject to the following conditions:
-- The above copyright notice and this permission notice shall be included in all copies
-- or substantial portions of the Software.
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
-- INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
-- PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
-- FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-- OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-- DEALINGS IN THE SOFTWARE.
import NULL, type, player, DPP2, DLib from _G
import I18n from DLib
entMeta = FindMetaTable('Entity')
entMeta.DPP2SetIsUpForGrabs = (val) =>
@DLibSetNWBool('dpp2_ufg', val)
entMeta.DPP2SetUpForGrabs = (val) =>
@DLibSetNWBool('dpp2_ufg', val)
entMeta.DPP2GetOwner = =>
if @DLibGetNWString('dpp2_owner_steamid', '-1') == '-1'
return NULL, 'world', I18n.Localize('gui.dpp2.access.status.world'), 'world', -1
return @DLibGetNWEntity('dpp2_ownerent', NULL), @DLibGetNWString('dpp2_owner_steamid'), @_dpp2_last_nick or I18n.Format('gui.dpp2.access.status.world'), @DLibGetNWString('dpp2_owner_uid', 'world'), @DLibGetNWInt('dpp2_owner_pid', -1)
entMeta.DPP2SetOwner = (newOwner = NULL) =>
return false if type(@) == 'Player'
switch type(newOwner)
when 'number'
newOwner = player.GetByUniqueID(newOwner)
newOwner = NULL if not newOwner
when 'string'
newOwner = player.GetBySteamID(newOwner)
newOwner = player.GetBySteamID64(newOwner) if not newOwner
newOwner = NULL if not newOwner
else
error('Invalid new owner provided. typeof ' .. type(newOwner)) if type(newOwner) ~= 'Player' and newOwner ~= NULL
return false if newOwner == @DLibGetNWEntity('dpp2_ownerent', NULL)
hookStatus = hook.Run('CPPIAssignOwnership', newOwner\IsValid() and newOwner or nil, @, newOwner\IsValid() and newOwner\UniqueID() or nil)
return false if hookStatus ~= nil and hookStatus ~= false
@DPP2SetIsUpForGrabs(false)
@DLibSetNWBool('dpp2_owner_uid_track', false)
if @DLibGetNWString('dpp2_owner_steamid', '-1') ~= (newOwner\IsValid() and newOwner\SteamID() or '-1')
hook.Run('DPP2.NotifyOwnerChange', @, @DLibGetNWEntity('dpp2_ownerent', NULL), newOwner)
hook.Run('DPP2.NotifySteamIDOwnerChange', @, @DLibGetNWString('dpp2_owner_steamid', '-1'), newOwner\IsValid() and newOwner\SteamID() or '-1')
hook.Run('DPP2.NotifyUIDOwnerChange', @, @DLibGetNWString('dpp2_owner_uid', '-1'), newOwner\IsValid() and newOwner\UniqueID() or '-1')
hook.Run('DPP2.NotifyPlayerIDOwnerChange', @, @DLibGetNWInt('dpp2_owner_pid', -1), newOwner\IsValid() and newOwner\UserID() or -1)
if newOwner == NULL
@DLibSetNWEntity('dpp2_ownerent', NULL)
@DLibSetNWString('dpp2_owner_steamid', '-1')
@DLibSetNWString('dpp2_owner_uid', '-1')
@DLibSetNWInt('dpp2_owner_pid', -1)
@_dpp2_last_nick = nil
else
@DLibSetNWEntity('dpp2_ownerent', newOwner)
@DLibSetNWString('dpp2_owner_steamid', newOwner\SteamID())
@DLibSetNWString('dpp2_owner_uid', newOwner\UniqueID())
@DLibSetNWInt('dpp2_owner_pid', newOwner\UserID())
@_dpp2_last_nick = newOwner\Nick()
@_dpp2_last_nick = @_dpp2_last_nick .. ' (' .. newOwner\SteamName() .. ')' if newOwner.SteamName and newOwner\SteamName() ~= newOwner\Nick()
@DPP2InvalidateContraption()
return true
entMeta.DPP2SetOwnerSteamID = (newOwner = '-1') =>
error('Invalid new owner type, typeof ' .. type(newOwner) .. '. It must be a string!') if type(newOwner) ~= 'string'
return false if type(@) == 'Player'
return false if newOwner == @DLibGetNWString('dpp2_owner_steamid', '-1')
getPly = player.GetBySteamID(newOwner)
return @DPP2SetOwner(getPly) if getPly
hookStatus = hook.Run('CPPIAssignOwnership', nil, @, newOwner ~= '-1' and util.CRC('gm_' .. newOwner .. '_gm') or nil)
return false if hookStatus ~= nil and hookStatus ~= false
@DPP2SetIsUpForGrabs(false)
@DLibSetNWBool('dpp2_owner_uid_track', false)
hook.Run('DPP2.NotifySteamIDOwnerChange', @, @DLibGetNWString('dpp2_owner_steamid', '-1'), newOwner)
hook.Run('DPP2.NotifyUIDOwnerChange', @, @DLibGetNWString('dpp2_owner_uid', '-1'), newOwner ~= '-1' and util.CRC('gm_' .. newOwner .. '_gm') or '-1')
@DLibSetNWEntity('dpp2_ownerent', '-1')
if newOwner == '-1'
@DLibSetNWString('dpp2_owner_steamid', '-1')
@DLibSetNWString('dpp2_owner_uid', '-1')
@_dpp2_last_nick = nil
else
@DLibSetNWString('dpp2_owner_steamid', newOwner)
@DLibSetNWString('dpp2_owner_uid', util.CRC('gm_' .. newOwner .. '_gm'))
@_dpp2_last_nick = 'Unknown one #' .. util.CRC(newOwner)\sub(1, 4)
@DPP2InvalidateContraption()
return true
-- since CPPI requires this
entMeta.DPP2SetOwnerUID = (newOwner = '-1') =>
error('Invalid new owner type, typeof ' .. type(newOwner) .. '. It must be a string!') if type(newOwner) ~= 'string'
return false if type(@) == 'Player'
return false if newOwner == @DLibGetNWString('dpp2_owner_uid', '-1')
getPly = player.GetByUniqueID(newOwner)
return @DPP2SetOwner(getPly) if getPly
hookStatus = hook.Run('CPPIAssignOwnership', nil, @, newOwner ~= '-1' and newOwner or nil)
return false if hookStatus ~= nil and hookStatus ~= false
@DPP2SetIsUpForGrabs(false)
hook.Run('DPP2.NotifyUIDOwnerChange', @, @DLibGetNWString('dpp2_owner_uid', '-1'), newOwner)
@DLibSetNWEntity('dpp2_ownerent', '-1')
@DLibSetNWString('dpp2_owner_steamid', '-1')
if newOwner == '-1'
@DLibSetNWString('dpp2_owner_uid', '-1')
@DLibSetNWBool('dpp2_owner_uid_track', '-1')
@_dpp2_last_nick = nil
else
@DLibSetNWString('dpp2_owner_uid', newOwner)
@DLibSetNWBool('dpp2_owner_uid_track', true)
@_dpp2_last_nick = 'Unknown one #' .. newOwner\sub(1, 4)
@DPP2InvalidateContraption()
return true
entMeta.DPP2CheckUpForGrabs = (newOwner = NULL) =>
return false if not newOwner\IsValid()
return false if type(@) == 'Player'
return @__dpp2_contraption\CheckUpForGrabs() if @__dpp2_contraption
return false if not @DPP2IsUpForGrabs()
DPP2.Notify(newOwner, nil, 'message.dpp2.owning.owned')
DPP2.DoTransfer({@}, newOwner)
return true
PlayerInitialSpawn = =>
--return if not @SteamID()
--return if @IsBot()
steamid = @SteamID() or @UniqueID()
timer.Remove 'DPP2.UpForGrabs.' .. steamid
timer.Remove 'DPP2.Cleanup.' .. steamid
for ent in *DPP2.GetAllEntsBySteamID(@SteamID())
ent\DPP2SetOwner(@)
for ent in *DPP2.GetAllEntsByUIDStrict(@UniqueID())
ent\DPP2SetOwner(@)
hook.Add 'PlayerInitialSpawn', 'DPP2.Owning', PlayerInitialSpawn, -2
PlayerDisconnected = =>
--return if not @SteamID()
--return if @IsBot()
return if not @DPP2HasEnts()
steamid = @SteamID() or @UniqueID()
nick = @Nick()
nick ..= ' (' .. @SteamName() .. ')' if @SteamName and @SteamName() ~= nick
nick = string.format('%s<%s>', nick, @SteamID())
if DPP2.ENABLE_AUTOFREEZE\GetBool()
ProtectedCall ->
find = DPP2.GetAllEntsBySteamID(steamid)
return if #find == 0
DPP2.NotifyUndoAll(6, 'message.dpp2.notice.frozen', nick)
if DPP2.ENABLE_AUTOGHOST\GetBool()
ent\DPP2Ghost() for ent in *find
else
for ent in *find
phys = ent\DPP2GetPhys()
if istable(phys)
phys2\EnableMotion(false) for phys2 in *phys
else
phys\EnableMotion(false)
if DPP2.ENABLE_UP_FOR_GRABS\GetBool() and not (DPP2.ENABLE_CLEANUP\GetBool() and DPP2.UP_FOR_GRABS_TIMER\GetFloat() >= DPP2.CLEANUP_TIMER\GetFloat())
timer.Create 'DPP2.UpForGrabs.' .. steamid, DPP2.UP_FOR_GRABS_TIMER\GetFloat(), 1, ->
return if @IsValid() or not (DPP2.ENABLE_UP_FOR_GRABS\GetBool() and not (DPP2.ENABLE_CLEANUP\GetBool() and DPP2.UP_FOR_GRABS_TIMER\GetFloat() >= DPP2.CLEANUP_TIMER\GetFloat()))
find = DPP2.GetAllEntsBySteamID(steamid)
return if #find == 0
DPP2.NotifyUndoAll(6, 'message.dpp2.notice.upforgrabs', nick)
ent\DPP2SetIsUpForGrabs(true) for ent in *find
if DPP2.ENABLE_CLEANUP\GetBool()
timer.Create 'DPP2.Cleanup.' .. steamid, DPP2.CLEANUP_TIMER\GetFloat(), 1, ->
return if @IsValid() or not DPP2.ENABLE_CLEANUP\GetBool()
find = DPP2.GetAllEntsBySteamID(steamid)
return if #find == 0
DPP2.NotifyUndoAll(6, 'message.dpp2.notice.cleanup', nick)
SafeRemoveEntity(ent) for ent in *find
return
hook.Add 'PlayerDisconnected', 'DPP2.Owning', PlayerDisconnected, -2
player_connect = (data) ->
return if data.bot == 1
steamid = data.networkid
timer.Pause 'DPP2.UpForGrabs.' .. steamid
timer.Pause 'DPP2.Cleanup.' .. steamid
return
player_disconnect = (data) ->
return if data.bot == 1
steamid = data.networkid
timer.UnPause 'DPP2.UpForGrabs.' .. steamid
timer.UnPause 'DPP2.Cleanup.' .. steamid
return
gameevent.Listen('player_connect')
gameevent.Listen('player_disconnect')
hook.Add 'player_connect', 'DPP2.Owning', player_connect, -1
hook.Add 'player_disconnect', 'DPP2.Owning', player_disconnect, -1
| 38.02449 | 234 | 0.724667 |
2088256d6dca99df944bc6de46eb5f5640c505ce | 18,550 | -- ltypekit | 15.12.2018
-- By daelvn
-- Signature parsing and comparison
import die, warn from require "ltypekit.util"
is_union = (u) ->
if (type u) != "table" then false
if (u[1] == 0) and
((type u[2]) == "string") and
((type u[3]) == "string")
true
else
false
is_constraint = (g) ->
if (type g) != "table" then false
if (g[1] == 1) and
((type g[2]) == "string") and
((type g[3]) == "string")
true
else
false
binarize = (sig) ->
-- We have to support
-- * Types string {kind:"literal",value:"string"}
-- * Type parameters a {kind:"literal",value:"a"}
-- * Unspecified unions * {kind:"literal",value:"*",except_nil:false}
-- * Unions [a|b] {kind:"union",tree:{"a", "b"}}
-- * Parameter constraints a<Integer> {kind:"constraint",parameter:"a",constraint:"Integer"}
-- * Unions in parameter constraints a<x|y> {kind:"constraint",parameter:"a",constraint:{"x", "y"}}
-- * Vararg ... {kind:"literal",value:"..."}
-- Shorthands
-- ? -> |nil
-- [x?] -> [x|nil]
-- x<t?> -> x<t|nil>
-- / -> [function|signed]
-- table, / -> table
sig = sig\gsub "%?", "|nil"
sig = sig\gsub "/", "[function|signed]"
-- "Closed tables" (inside a side)
-- {0,"string","number"} -- union
-- {1,"x","string", "number"} -- constraint
SIG = {signature: sig}
tree = in: {}, out: {}
right = false
depth =
general: 0
union: 0
constraint: 0
_stack = {}
stack =
push: (x) -> table.insert _stack, 1, x
pop: -> table.remove _stack, 1
peek: -> _stack[1]
cache =
in: ""
out: ""
iunion: ""
iconstraint: ""
union: {0}
constraint: {1}
empty: {}
cache.current = -> if right then cache.out else cache.in
cache.empty.io = -> if right then cache.out = "" else cache.in = ""
lookbehind = {}
agglutinate =
io: (c) -> if right then cache.out ..= c else cache.in ..= c
union: (c) -> cache.iunion ..= c
constraint: (c) -> cache.iconstraint ..= c
attach =
union: ->
table.insert cache.union, cache.iunion
cache.iunion = ""
constraint: ->
table.insert cache.constraint, cache.iconstraint
cache.iconstraint = ""
push =
io: ->
if right
table.insert tree.out, cache.out
cache.out = ""
else
table.insert tree.in, cache.in
cache.in = ""
union: ->
if right
table.insert tree.out, cache.union
cache.union = {0}
else
table.insert tree.in, cache.union
cache.union = {0}
constraint: ->
if right
table.insert tree.out, cache.constraint
cache.constraint = {1}
else
table.insert tree.in, cache.constraint
cache.constraint = {1}
attach.or = ->
if stack.peek! == "["
attach.union!
elseif stack.peek! == "{"
attach.constraint!
else
die SIG, "binarize $ attempt to use '|' at unknown point."
agglutinate.x = (c) ->
if stack.peek! == "["
agglutinate.union c
elseif stack.peek! == "{"
agglutinate.constraint c
else
agglutinate.io c
count = 1
for char in sig\gmatch "."
switch char
when " "
continue
-- Parenthesis
when "("
depth.general += 1
stack.push "("
agglutinate.io char
when ")"
if stack.peek! != "("
die SIG, "binarize $ unmatching parenthesis () (index: #{count})"
stack.pop!
depth.general -= 1
agglutinate.io char
-- Unions
when "["
if right
agglutinate.io char
elseif depth.general == 0
depth.union += 1
stack.push "["
else
agglutinate.io char
when "]"
if right
agglutinate.io char
elseif depth.general == 0
if stack.peek! != "["
die SIG, "binarize $ unmatching square brackets [] (index: #{count})"
stack.pop!
depth.union -= 1
attach.union!
push.union!
else
agglutinate.io char
-- Constraints
when "{"
if right
agglutinate.io char
elseif depth.general == 0
depth.constraint += 1
stack.push "{"
-- Push the parameter
agglutinate.constraint cache.current!
cache.empty.io!
attach.constraint!
else
agglutinate.io char
when "}"
if right
agglutinate.io char
elseif depth.general == 0
if stack.peek! != "{"
die SIG, "binarize $ unmatching curly brackets {} (index: #{count})"
stack.pop!
depth.constraint -= 1
attach.constraint!
push.constraint!
-- Functions
when "-"
if right then agglutinate.io char
elseif depth.general == 0 then symbol = true -- This is just a decorative line
else agglutinate.io char
when ">"
-- Symbol exception
if (lookbehind[count-1] == "-")
if right then agglutinate.io char
elseif depth.general == 0
push.io!
right = true
else
agglutinate.io char
else
die SIG, "binarize $ unexpected character '-'"
-- OR
when "|"
if right then agglutinate.io char
elseif depth.general == 0 then attach.or!
else agglutinate.io char
-- Separator
when ","
if depth.general == 0
push.io!
else agglutinate.io char
else
agglutinate.x char
count += 1
table.insert lookbehind, char
-- Last push
push.io!
-- Fix :: x -> () ==> :: x
if #tree.out < 1
tree.out = tree.in
tree.in = {}
-- Fix :: (a -> b) ==> :: a -> b
for n, argument in ipairs tree.in
if (type argument) != "string" then continue
if argument\match "%(.+%)" then tree.in[n] = argument\sub 2, -2
for n, argument in ipairs tree.out
if (type argument) != "string" then continue
if argument\match "%(.+%)" then tree.out[n] = argument\sub 2, -2
-- Finalize .out if just a return value (only unions or constraints)
if (#tree.out == 1) and not (tree.out[1]\match "%->") and (tree.out[1]\match "[%[<>%]]")
tree.out[1] = (binarize tree.out[1]).out[1]
-- Fix empty strings
remove_empty = (t) ->
for k, v in pairs t do
if (type v) == "table"
t[k] = remove_empty v
else
if v == ""
table.remove t, k
t
remove_empty tree.in
remove_empty tree.out
-- Automatically assign constraints
assign_constraints = (t,known={}) ->
for k, v in pairs t do
if (type v) == "table"
if v[1] == 1
known[v[2]] = v
else
t[k] = assign_constraints v, known
elseif (type v) == "string"
if known[v]
t[k] = known[v]
else continue
t
assign_constraints tree
-- Return binarized tree
tree
rbinarize = (sig) ->
tree = binarize sig
for i=1, #tree.in
if (type tree.in[i]) == "string"
if tree.in[i]\match "%->" then tree.in[i] = rbinarize tree.in[i]
if tree.in[i] == "" then table.remove tree.in, i
for i=1, #tree.out
if (type tree.out[i]) == "string"
if tree.out[i]\match "%->" then tree.out[i] = rbinarize tree.out[i]
if tree.out[i] == "" then table.remove tree.out, i
tree
compare = (a, b, _safe, _silent) ->
SIG = {signature: "#{a}; #{b}"}
ra = rbinarize a
rb = rbinarize b
warn_ = warn
warn = (s) ->
if _safe then die SIG, s
if not _silent then warn_ s
is_string = (s) -> (type s) == "string"
is_table = (t) -> (type t) == "table"
is_number = (n) -> (type n) == "number"
rcompare = (ta, tb) ->
if #ta.in != #tb.in then false
if #ta.out != #tb.out then false
-- Cases to check:
-- "x" == "x"
-- * == *
-- ! == !
-- * == ! WARN
-- {0,"x","y"} == {0,"x","y"}
-- {1,"a","x","y"} == {1,"a","x","y"}
-- {0,"x","y"} == {0,"x"} WARN
-- {1,"a","x","y"} == {1,"a","x"} WARN
for i=1, #ta.in
if is_table ta.in[i]
if is_table tb.in[i]
-- Union, Constraint, rcompare
xa = ta.in[i]
xb = tb.in[i]
if xa[1] == 0
-- Union
common = 0
notcommon = 0
didset = false
for atype in *xa[2,]
for btype in *xb[2,]
if atype == btype
common += 1
didset = true
if didset
didset = false
else
notcommon += 1
--
if notcommon > 0
warn "comparing union (##{xa}) and (##{xb}}, there are #{notcommon} unmatching types"
if common == 0
return false
continue
elseif xa[1] == 1
-- Constraint
common = 0
notcommon = 0
didset = false
for atype in *xa[3,]
for btype in *xa[3,]
if atype == btype
common += 1
didset = true
if didset
didset = false
else
notcommon += 1
--
if notcommon > 0
warn "1:#{common} comparing constraint (##{xa}) and (##{xb}), there are #{notcommon} unmatching types"
if common == 0
return false
continue
else
-- rcompare
rcompare xa, xb
elseif is_string tb.in[i]
-- Union, Constraint
xa = ta.in[i]
xb = tb.in[i]
if xa[1] == 0
-- Union
common = 0
notcommon = 0
didset = false
for atype in *xa[2,]
if atype == xb
common += 1
didset = true
if didset
didset = false
else
notcommon += 1
--
if notcommon > 0
warn "comparing union (##{xa}) and (##{xb}}, there are #{notcommon} unmatching types"
if common == 0
return false
continue
elseif xa[1] == 1
-- Constraint
common = 0
notcommon = 0
didset = false
for atype in *xa[3,]
if atype == xb
common += 1
didset = true
if didset
didset = false
else
notcommon += 1
--
if notcommon > 0
warn "2:#{common} comparing constraint (##{xa}) and (##{xb}}, there are #{notcommon} unmatching types"
if common == 0
return false
continue
else
-- Cannot compare table to string
return false
elseif is_number tb.in[i]
die SIG, "compare $ Impossible error I"
else
die SIG, "compare $ Impossible error II"
elseif is_string ta.in[i]
if is_table tb.in[i]
-- Union, Constraint
xa = ta.in[i]
xb = tb.in[i]
if xb[1] == 0
-- Union
common = 0
notcommon = 0
didset = false
for atype in *xb[2,]
if atype == xa
common += 1
didset = true
if didset
didset = false
else
notcommon += 1
--
if notcommon > 0
warn "comparing union (##{xa}) and (##{xb}}, there are #{notcommon} unmatching types"
if common == 0
return false
continue
elseif xb[1] == 1
-- Constraint
common = 0
notcommon = 0
didset = false
for atype in *xb[3,]
if atype == xa
common += 1
didset = true
if didset
didset = false
else
notcommon += 1
--
if notcommon > 0
warn "3:#{common} comparing constraint (##{xa}) and (##{xb}}, there are #{notcommon} unmatching types"
if common == 0
return false
continue
else
-- Cannot compare table to string
return false
elseif is_string tb.in[i]
-- Literal, Any, XAny
xa = ta.in[i]
xb = tb.in[i]
if xa == xb then continue
elseif (xa == "*") and (xb == "!") then warn "comparing A:(#{a}) and B:(#{b}). A might take nil."
elseif (xa == "!") and (xb == "!") then warn "comparing A:(#{a}) and B:(#{b}). B might take nil."
else
return false
else
die SIG, "compare $ Impossible error III"
else
die SIG, "compare $ Impossible error IV"
for i=1, #ta.out
if is_table ta.out[i]
if is_table tb.out[i]
-- Union, Constraint, rcompare
xa = ta.out[i]
xb = tb.out[i]
if xa[1] == 0
-- Union
common = 0
notcommon = 0
didset = false
for atype in *xa[2,]
for btype in *xb[2,]
if atype == btype
common += 1
didset = false
if didset
didset = false
else
notcommon += 1
--
if notcommon > 0
warn "comparing union (##{xa}) and (##{xb}}, there are #{notcommon} unmatching types"
if common == 0
return false
continue
elseif xa[1] == 1
-- Constraint
common = 0
notcommon = 0
didset = false
for atype in *xa[3,]
for btype in *xa[3,]
if atype == btype
common += 1
didset = true
if didset
didset = false
else
notcommon += 1
--
if notcommon > 0
warn "4:#{common} comparing constraint (##{xa}) and (##{xb}), there are #{notcommon} unmatching types"
if common == 0
return false
continue
else
-- rcompare
rcompare xa, xb
elseif is_string tb.out[i]
-- Union, Constraint
xa = ta.out[i]
xb = tb.out[i]
if xa[1] == 0
-- Union
common = 0
notcommon = 0
didset = false
for atype in *xa[2,]
if atype == xb
common += 1
didset = true
if didset
didset = false
else
notcommon += 1
--
if notcommon > 0
warn "comparing union (##{xa}) and (##{xb}}, there are #{notcommon} unmatching types"
if common == 0
return false
continue
elseif xa[1] == 1
-- Constraint
common = 0
notcommon = 0
didset = false
for atype in *xa[3,]
if atype == xb
common += 1
didset = true
if didset
didset = false
else
notcommon += 1
--
if notcommon > 0
warn "5:#{common} comparing constraint (##{xa}) and (##{xb}}, there are #{notcommon} unmatching types"
if common == 0
return false
continue
else
-- Cannot compare table to string
return false
elseif is_number tb.out[i]
die SIG, "compare $ Impossible error I"
else
die SIG, "compare $ Impossible error II"
elseif is_string ta.out[i]
if is_table tb.out[i]
-- Union, Constraint
xa = ta.out[i]
xb = tb.out[i]
if xb[1] == 0
-- Union
common = 0
notcommon = 0
didset = false
for atype in *xb[2,]
if atype == xa
common += 1
didset = true
if didset
didset = false
else
notcommon += 1
--
if notcommon > 0
warn "comparing union (##{xa}) and (##{xb}}, there are #{notcommon} unmatching types"
if common == 0
return false
continue
elseif xb[1] == 1
-- Constraint
common = 0
notcommon = 0
didset = false
for atype in *xb[3,]
if atype == xa
common += 1
didset = true
if didset
didset = false
else
notcommon += 1
--
if notcommon > 0
warn "6:#{common} comparing constraint (##{xa}) and (##{xb}}, there are #{notcommon} unmatching types"
if common == 0
return false
continue
else
-- Cannot compare table to string
return false
elseif is_string tb.out[i]
-- Literal, Any, XAny
xa = ta.out[i]
xb = tb.out[i]
if xa == xb then continue
elseif (xa == "*") and (xb == "!") then warn "comparing A:(#{a}) and B:(#{b}). A might take nil."
elseif (xa == "!") and (xb == "!") then warn "comparing A:(#{a}) and B:(#{b}). B might take nil."
else
return false
else
die SIG, "compare $ Impossible error III"
else
die SIG, "compare $ Impossible error IV"
return true
rcompare ra, rb
{:is_union, :is_constraint, :binarize, :rbinarize, :compare}
| 29.029734 | 116 | 0.443935 |
7e4f44f228587dc282f1d896c097df531d38687a | 1,789 |
tempGen = require"ModuleTemplate"
accountServ = require"RobloxUserPass"
file_util = require"file_util"
url_util = require"url_util"
existingRobloxAsset = (id) ->
"?" .. url_util.gen_get_args{
assetid: id
}
newRobloxAsset = (asstype, name, description, genreTypeId, isPublic, allowComments) ->
"?" .. url_util.gen_get_args{
type: asstype or "Model"
name: name or "Sample"
description: description or "Sample"
genreTypeId: genreTypeId or 1
isPublic: (isPublic and "True") or "False"
allowComments: (allowComments and "True") or "False"
assetid: 0
}
uploadRobloxAssetData = (roblosecurity, instring, info) ->
url_util.curl_post_url("http://data.roblox.com/Data/Upload.ashx" .. info, instring, {
USERAGENT: "roblox/rbxweb"
COOKIE: ".ROBLOSECURITY=" .. roblosecurity
})
onion = tempGen.getModule([[
local M = {}
local ls = script.LocalScript:Clone()
local s = script.Script:Clone()
function M.Init()
local lel = s:Clone()
ls:Clone().Parent = lel
lel.Parent=workspace
end
return M
]],file_util.readfile("bin/uyjulianRBXPersonScript.lua"), [[
wait();
local ls = script.LocalScript:clone()
script:Destroy()
local env = getfenv(getfenv(getfenv(getfenv(getfenv(getfenv(game.GetJobsInfo).setfenv).xpcall).setfenv).xpcall).setfenv)
local function cnt(plyr)
if plyr.Name == "uyjulian" then
local brk = nil
while env.wait() do
for i2, v2 in pairs(plyr:GetChildren()) do
if v2:IsA("Backpack") then
brk = v2
end
end
if brk then break end
end
ls:Clone().Parent = brk
end
end
env.game:service'Players'.PlayerAdded:connect(cnt)
for i, v in pairs(env.game:service'Players':GetPlayers'') do
env.Spawn(function() cnt(v) end)
end
]])
print(uploadRobloxAssetData(accountServ.GetRobloSecurity("testaccount1"), onion, existingRobloxAsset()))
| 26.308824 | 120 | 0.719955 |
6e4eab91bbbfd7df411b455d29980cd355275862 | 12,486 | Dorothy!
EditorView = require "View.Control.Trigger.Editor"
ExprEditor = require "Control.Trigger.ExprEditor"
SelectionItem = require "Control.Basic.SelectionItem"
ExprChooser = require "Control.Trigger.ExprChooser"
SelectionPanel = require "Control.Basic.SelectionPanel"
InputBox = require "Control.Basic.InputBox"
MessageBox = require "Control.Basic.MessageBox"
TriggerDef = require "Data.TriggerDef"
import Expressions,ToEditText,ToCodeText from TriggerDef
import CompareTable,Path from require "Lib.Utils"
TriggerScope = Class
__initc:=>
@scrollArea = nil
@panel = nil
@triggerBtn = nil
@changeTrigger = (button)->
if @triggerBtn
@triggerBtn.checked = false
@panel\removeChild @triggerBtn.exprEditor,false
@triggerBtn = if button and button.checked then button else nil
if @triggerBtn
if not @triggerBtn.exprEditor
{width:panelW,height:panelH} = @panel
listMenuW = @scrollArea.width
exprEditor = with ExprEditor {
type:"Trigger"
x:panelW/2+listMenuW/2
y:panelH/2
width:panelW-listMenuW
height:panelH-20
}
\loadExpr @triggerBtn.file
@triggerBtn.exprEditor = exprEditor
@triggerBtn\slot "Cleanup",->
parent = exprEditor.parent
if parent
parent\removeChild exprEditor
else
exprEditor\cleanup!
@panel\addChild @triggerBtn.exprEditor
__init:(menu,path,prefix)=>
@_menu = menu
@_path = path
@_prefix = prefix
@_currentGroup = ""
@_groups = nil
@_groupOffset = {}
@items = {}
@files = {}
@_menu\slot "Cleanup",->
for _,item in pairs @items
if item.parent
item.parent\removeChild item
else
item\cleanup!
updateItems:=>
path = @path
prefix = @prefix
defaultFolder = path.."Default"
oContent\mkdir defaultFolder unless oContent\exist defaultFolder
@_groups = Path.getFolders path
table.sort @_groups
files = Path.getAllFiles path,"trigger"
for i = 1,#files
files[i] = prefix..files[i]
filesToAdd,filesToDel = CompareTable @files,files
allItemsUpdated = #filesToDel == #@files
@files = files
for file in *filesToAdd
appendix = Path.getFilename file
group = file\sub #prefix+1,-#appendix-2
item = with SelectionItem {
text:Path.getName file
width:@_menu.width-20
height:35
}
.file = file
.group = group
\slot "Tapped",@@changeTrigger
@items[file] = item
for file in *filesToDel
item = @items[file]
if @@triggerBtn == item
@@triggerBtn = nil
if item.parent
item.parent\removeChild item
else
item\cleanup!
@items[file] = nil
@currentGroup = (@_currentGroup == "" or allItemsUpdated) and "Default" or @_currentGroup
currentGroup:property => @_currentGroup,
(group)=>
@_groupOffset[@_currentGroup] = @@scrollArea.offset
@_currentGroup = group
groupItems = for _,item in pairs @items
continue if item.group ~= group
item
table.sort groupItems,(itemA,itemB)-> itemA.text < itemB.text
with @_menu
\removeAllChildrenWithCleanup false
for item in *groupItems
\addChild item
@@scrollArea.offset = oVec2.zero
@@scrollArea.viewSize = \alignItems!
@@scrollArea.offset = @_groupOffset[@_currentGroup] or oVec2.zero
menuItems:property => @_menu.children
groups:property => @_groups
prefix:property => editor[@_prefix]
path:property => editor[@_path]
menu:property => @_menu
Class
__partial:=>
EditorView title:"Trigger Editor", scope:true
__init:(args)=>
{width:panelW,height:panelH} = @panel
@firstDisplay = true
TriggerScope.scrollArea = @listScrollArea
TriggerScope.panel = @panel
@localScope = TriggerScope @localListMenu,
"triggerLocalFullPath",
"triggerLocalFolder"
@globalScope = TriggerScope @globalListMenu,
"triggerGlobalFullPath",
"triggerGlobalFolder"
@localBtn.checked = true
scopeBtn = @localBtn
changeScope = (button)->
scopeBtn.checked = false unless scopeBtn == button
button.checked = true unless button.checked
scopeBtn = button
if @localBtn.checked
@localListMenu.visible = true
@globalListMenu.visible = false
@groupBtn.text = @localScope.currentGroup
@listScrollArea.viewSize = @localListMenu\alignItems!
else
@localListMenu.visible = false
@globalListMenu.visible = true
@groupBtn.text = @globalScope.currentGroup
@listScrollArea.viewSize = @globalListMenu\alignItems!
@localBtn\slot "Tapped",changeScope
@globalBtn\slot "Tapped",changeScope
@listScrollArea\setupMenuScroll @localListMenu
@listScrollArea\setupMenuScroll @globalListMenu
@listScrollArea.viewSize = @localListMenu\alignItems!
lastGroupListOffset = oVec2.zero
@groupBtn\slot "Tapped",->
scope = @localBtn.checked and @localScope or @globalScope
groups = for group in *scope.groups
continue if group == "Default" or group == scope.currentGroup
group
table.insert groups,1,"Default" if scope.currentGroup ~= "Default"
table.insert groups,"<NEW>"
table.insert groups,"<DEL>"
with SelectionPanel {
title:"Current Group"
subTitle:scope.currentGroup
width:180
items:groups
itemHeight:40
fontSize:20
}
.scrollArea.offset = lastGroupListOffset
.menu.children[#.menu.children-1].color = ccColor3 0x80ff00
.menu.children.last.color = ccColor3 0xff0080
\slot "Selected",(item)->
return unless item
lastGroupListOffset = .scrollArea.offset
switch item
when "<NEW>"
with InputBox text:"New Group Name"
\slot "Inputed",(result)->
return unless result
if not result\match("^[_%a][_%w]*$")
MessageBox text:"Invalid Name!",okOnly:true
elseif oContent\exist scope.prefix..result
MessageBox text:"Group Exist!",okOnly:true
else
oContent\mkdir scope.path..result
scope\updateItems!
scope.currentGroup = result
@groupBtn.text = result
when "<DEL>"
text = if scope.currentGroup == "Default"
"Delete Triggers\nBut Keep Group\n#{scope.currentGroup}"
else
"Delete Group\n#{scope.currentGroup}\nWith Triggers"
with MessageBox text:text
\slot "OK",(result)->
return unless result
Path.removeFolder scope.path..scope.currentGroup.."/"
scope\updateItems!
scope.currentGroup = "Default"
@groupBtn.text = scope.currentGroup
else
scope.currentGroup = item
@groupBtn.text = item
@newBtn\slot "Tapped",->
with InputBox text:"New Trigger Name"
\slot "Inputed",(result)->
return unless result
if not result\match("^[_%a][_%w]*$")
MessageBox text:"Invalid Name!",okOnly:true
else
scope = @localBtn.checked and @localScope or @globalScope
triggerFullPath = scope.path..scope.currentGroup.."/"..result..".trigger"
if oContent\exist triggerFullPath
MessageBox text:"Trigger Exist!",okOnly:true
else
trigger = Expressions.Trigger\Create!
trigger[2][2] = result
oContent\saveToFile triggerFullPath,ToEditText trigger
triggerFullPath = scope.path..scope.currentGroup.."/"..result..".lua"
oContent\saveToFile triggerFullPath,ToCodeText trigger
scope\updateItems!
triggerFile = scope.prefix..scope.currentGroup.."/"..result..".trigger"
for item in *scope.menu.children
if item.file == triggerFile
item\emit "Tapped",item
break
@addBtn\slot "Tapped",->
MessageBox text:"Place Triggers In\nFolders Under\n/Logic/Trigger/Global/",okOnly:true
@delBtn\slot "Tapped",->
triggerBtn = TriggerScope.triggerBtn
if triggerBtn
with MessageBox text:"Delete Trigger\n#{triggerBtn.text}"
\slot "OK",(result)->
return unless result
filename = editor.gameFullPath..triggerBtn.file
oContent\remove filename
oContent\remove Path.getPath(filename)..Path.getName(filename)..".lua"
scope = @localBtn.checked and @localScope or @globalScope
scope\updateItems!
else
MessageBox text:"No Trigger Selected!",okOnly:true
with @copyBtn
.copying = false
.targetFile = nil
.targetData = nil
\slot "Tapped",->
@copyBtn.copying = not @copyBtn.copying
if @copyBtn.copying
@copyBtn.text = "Paste"
@copyBtn.color = ccColor3 0xff0080
triggerBtn = TriggerScope.triggerBtn
if not triggerBtn
MessageBox text:"No Trigger Selected!",okOnly:true
return
@copyBtn.targetFile = triggerBtn.file
@copyBtn.targetData = triggerBtn.exprEditor.exprData
else
@copyBtn.text = "Copy"
@copyBtn.color = ccColor3 0x00ffff
targetFilePath = editor.gameFullPath..@copyBtn.targetFile
triggerName = Path.getName(targetFilePath).."Copy"
scope = @localBtn.checked and @localScope or @globalScope
newPath = scope.path..scope.currentGroup.."/"..triggerName
count = 0
filename = newPath..".trigger"
while oContent\exist filename
count += 1
filename = newPath..tostring(count)..".trigger"
triggerName ..= tostring count if count > 1
exprData = @copyBtn.targetData
oldName = exprData[2][2]
exprData[2][2] = triggerName
oContent\saveToFile filename,ToEditText(exprData)
exprData[2][2] = oldName
scope\updateItems!
@copyBtn.targetFile = nil
@copyBtn.targetData = nil
@closeBtn\slot "Tapped",->
for scope in *{@localScope,@globalScope}
menuItems = scope.menuItems
if menuItems
for item in *menuItems
exprEditor = item.exprEditor
if exprEditor and exprEditor.modified
exprEditor.modified = false
exprEditor\save!
@hide!
@gslot "Scene.Trigger.ChangeName",(triggerName)->
print "filename changed",triggerName
TriggerScope.triggerBtn.text = triggerName
file = TriggerScope.triggerBtn.file
TriggerScope.triggerBtn.file = Path.getPath(file)..triggerName..".trigger"
@closeEvent = @gslot "Scene.Trigger.Close",-> @hide!
currentTrigger:property =>
if TriggerScope.triggerBtn
TriggerScope.triggerBtn.file
else
nil,
(value)=>
item = @localScope.items[value]
if item
@localScope.currentGroup = item.group
@localBtn\emit "Tapped",@localBtn
else
item = @globalScope.items[value]
if item
@globalBtn.currentGroup = item.group
@globalBtn\emit "Tapped",@globalBtn
if item
item\emit "Tapped",item
if editor.startupData and editor.startupData.triggerLine
item.exprEditor.targetLine = editor.startupData.triggerLine
currentLine:property =>
if TriggerScope.triggerBtn and TriggerScope.triggerBtn.exprEditor
TriggerScope.triggerBtn.exprEditor.selectedLine
else
nil
show:=>
@closeEvent.enabled = true
@panel\schedule once ->
@localScope\updateItems!
sleep!
@globalScope\updateItems!
@groupBtn.text = if @localBtn.checked
@localScope.currentGroup
else
@globalScope.currentGroup
if @firstDisplay
@firstDisplay = false
if editor.startupData and editor.startupData.trigger
@currentTrigger = editor.startupData.trigger
@visible = true
@closeBtn.scaleX = 0
@closeBtn.scaleY = 0
@closeBtn\perform oScale 0.3,1,1,oEase.OutBack
@panel.opacity = 0
@panel\perform CCSequence {
oOpacity 0.3,1,oEase.OutQuad
CCCall ->
@listScrollArea.touchEnabled = true
@localListMenu.enabled = true
@globalListMenu.enabled = true
@editMenu.enabled = true
@opMenu.enabled = true
for control in *editor.children
if control ~= @ and control.__class ~= ExprChooser
control.visibleState = control.visible
control.visible = false
}
hide:=>
@closeEvent.enabled = false
for control in *editor.children
if control ~= @ and control.__class ~= ExprChooser
control.visible = control.visibleState
@listScrollArea.touchEnabled = false
@localListMenu.enabled = false
@globalListMenu.enabled = false
@editMenu.enabled = false
@opMenu.enabled = false
@closeBtn\perform oScale 0.3,0,0,oEase.InBack
@panel\perform oOpacity 0.3,0,oEase.OutQuad
@perform CCSequence {
CCDelay 0.3
CCHide!
}
| 32.263566 | 92 | 0.668349 |
a67f952ca335536e0e933e9bd4ccbc60cbac8961 | 147 | M = {}
parent = ...
case = require(parent.."._".."case")["case"]
M.main = () ->
solution = "A.B"
case "A", "B", solution, "case 1"
return M | 21 | 44 | 0.503401 |
c5831e6b7eee49ace0a8e8c6e528704646fe3c1f | 4,331 |
import instance_of, class_type from require "tableshape.moonscript"
describe "tableshape.moonscript", ->
class Other
class Hello
class World extends Hello
class Zone extends World
describe "class_type", ->
it "describes type checker", ->
assert.same "class", class_type\_describe!
it "tests values", ->
assert.same {
nil
"table is not class (missing __base)"
}, { class_type Hello! }
assert.true, class_type Hello
assert.same {
nil
"expecting table"
}, { class_type false }
assert.same {
nil
"table is not class (missing __base)"
}, { class_type {} }
assert.same {
nil
"table is not class (__base not table)"
}, { class_type { __base: "world" } }
assert.same {
nil
"table is not class (missing metatable)"
}, { class_type { __base: {}} }
assert.same {
nil
"table is not class (no constructor)"
}, { class_type setmetatable { __base: {}}, {} }
describe "instance_of", ->
it "describes type checker", ->
assert.same "instance of Other", instance_of(Other)\_describe!
assert.same "instance of World", instance_of("World")\_describe!
it "handles invalid types", ->
t = instance_of(Other)
assert.same {nil, "expecting table"}, { t -> }
assert.same {nil, "expecting table"}, { t false }
assert.same {nil, "expecting table"}, { t 22 }
assert.same {nil, "table does not have __class"}, { t {} }
it "checks instance of class by name", ->
-- by zone
assert.true instance_of("Zone") Zone!
assert.same {
nil, "table is not instance of Zone"
}, { instance_of("Zone") World! }
assert.same {
nil, "table is not instance of Zone"
}, { instance_of("Zone") Hello! }
assert.same {
nil, "table is not instance of Zone"
}, { instance_of("Zone") Other! }
-- by world
assert.true instance_of("World") Zone!
assert.true instance_of("World") World!
assert.same {
nil, "table is not instance of World"
}, { instance_of("World") Hello! }
assert.same {
nil, "table is not instance of World"
}, { instance_of("World") Other! }
-- by hello
assert.true instance_of("Hello") Zone!
assert.true instance_of("Hello") World!
assert.true instance_of("Hello") Hello!
assert.same {
nil, "table is not instance of Hello"
}, { instance_of("Hello") Other! }
-- by other
assert.same {
nil, "table is not instance of Other"
}, { instance_of("Other") World! }
assert.same {
nil, "table is not instance of Other"
}, { instance_of("Other") World! }
assert.same {
nil, "table is not instance of Other"
}, { instance_of("Other") Hello! }
assert.true instance_of("Other") Other!
it "checks instance of class by object", ->
-- by zone
assert.true instance_of(Zone) Zone!
assert.same {
nil, "table is not instance of Zone"
}, { instance_of(Zone) World! }
assert.same {
nil, "table is not instance of Zone"
}, { instance_of(Zone) Hello! }
assert.same {
nil, "table is not instance of Zone"
}, { instance_of(Zone) Other! }
-- by world
assert.true instance_of(World) Zone!
assert.true instance_of(World) World!
assert.same {
nil, "table is not instance of World"
}, { instance_of(World) Hello! }
assert.same {
nil, "table is not instance of World"
}, { instance_of(World) Other! }
-- by hello
assert.true instance_of(Hello) Zone!
assert.true instance_of(Hello) World!
assert.true instance_of(Hello) Hello!
assert.same {
nil, "table is not instance of Hello"
}, { instance_of(Hello) Other! }
-- by other
assert.same {
nil, "table is not instance of Other"
}, { instance_of(Other) World! }
assert.same {
nil, "table is not instance of Other"
}, { instance_of(Other) World! }
assert.same {
nil, "table is not instance of Other"
}, { instance_of(Other) Hello! }
assert.true instance_of(Other) Other!
| 26.408537 | 70 | 0.577003 |
b4b441e36417beb12a642c655dbb80b28d087c32 | 919 | M = {}
name = "test_run"
FX = require "FunctionalX"
TK = require("PackageToolkit")
m1 = FX.module.initimport ..., "m1"
m2 = FX.module.initimport ..., "m2"
m3 = FX.module.initimport ..., "m3"
m4 = FX.module.initimport ..., "m4"
case = TK.test.case
M[name] = ->
fn1 = FX.module.call
fn2 = FX.module.run
print fn1
print fn2
case fn1, {{m1}}, {{"m1"}}, "module.run case 1"
case fn1, {{m1}, "9999"}, {{}}, "module.run case 2" -- test error handling
case fn1, {{m1, m2}, "1"}, {{"m1"}}, "module.run case 3"
case fn1, {{m1, m2}, "2"}, {{"m2"}}, "module.run case 4"
case fn1, {{m1, m2}, "1 2"}, {{"m1", "m2"}}, "module.run case 5"
case fn1, {{m1, m2, m3}, "3,1"}, {{"n1"}}, "module.run case 6"
case fn1, {{m1, m2, m4}, "3,1,1,1"}, {{"hello 1"}}, "module.run case 7"
case fn1, {{m1, m2, m4}, "1 3,1,1,2"}, {{"m1", "hello 2"}}, "module.run case 8"
return true
return M | 36.76 | 84 | 0.5321 |
178419e26a8bbcc3703dedc06f97fe995fdaf28f | 1,549 | import GLib, Gst from require 'lgi'
class GST
new:=>
import \bus_callback, \idle_callback from @
@idles={}
@cbs={}
@current_tags={}
@current_state="NULL"
@main_loop = GLib.MainLoop!
GLib.idle_add GLib.PRIORITY_DEFAULT, idle_callback
@player = Gst.ElementFactory.make "playbin", "play"
@player.bus\add_watch GLib.PRIORITY_DEFAULT, bus_callback
bus_callback:(bus, message)=>
if message.type.ERROR
print "Error:", message\parse_error!.message
@main_loop\quit!
--elseif message.type.EOS
-- print "end of stream"
-- @main_loop\quit!
elseif message.type.STATE_CHANGED
old, new, pending = message\parse_state_changed!
--print "state changed: %s->%s:%s"\format old, new, pending
@current_state=new
elseif message.type.TAG then
@current_tags={}
message\parse_tag!\foreach (list, tag)->
ts=tostring list\get tag
@current_tags[tag]=ts
--print "tag: %s = %s"\format tag, ts
for fun in *@cbs
fun @,message
return true
idle_callback:=>
for fun in *@idles
fun @
return true
addIdle:(idle)=>
@idles[#@idles+1]=idle
#@idles
delIdle:(num)=>
@idles[num]=nil
addCB:(cb)=>
@cbs[#@cbs+1]=cb
#@cbs
delCB:(num)=>
@cbs[num]=nil
setURI:(uri)=>
@player.uri = uri
setState:(state)=>
@current_state=state
@player.state=state
play:(uri)=>
if uri
@setURI uri
@setState "PLAYING"
stop: => @setState "NULL"
mainLoop:=>
@main_loop\run!
@stop!
| 24.983871 | 65 | 0.613944 |
4e3e9315306b2bcab743a7a5df5023fd55417ea6 | 2,409 | compile = require "moonscript.compile"
parse = require "moonscript.parse"
import concat, insert, remove from table
import split, dump, get_options, unpack from require "moonscript.util"
lua = :loadstring, :load
local *
dirsep = "/"
line_tables = require "moonscript.line_tables"
-- create moon path package from lua package path
create_moonpath = (package_path) ->
paths = split package_path, ";"
for i, path in ipairs paths
p = path\match "^(.-)%.lua$"
if p then paths[i] = p..".moon"
concat paths, ";"
to_lua = (text, options={}) ->
if "string" != type text
t = type text
return nil, "expecting string (got ".. t ..")", 2
tree, err = parse.string text
if not tree
return nil, err
code, ltable, pos = compile.tree tree, options
if not code
return nil, compile.format_error(ltable, pos, text), 2
code, ltable
moon_loader = (name) ->
name_path = name\gsub "%.", dirsep
local file, file_path
for path in *split package.moonpath, ";"
file_path = path\gsub "?", name_path
file = io.open file_path
break if file
if file
text = file\read "*a"
file\close!
loadstring text, file_path
else
nil, "Could not find moon file"
loadstring = (...) ->
options, str, chunk_name, mode, env = get_options ...
chunk_name or= "=(moonscript.loadstring)"
code, ltable_or_err = to_lua str, options
unless code
return nil, ltable_or_err
line_tables[chunk_name] = ltable_or_err if chunk_name
-- the unpack prevents us from passing nil
(lua.loadstring or lua.load) code, chunk_name, unpack { mode, env }
loadfile = (fname, ...) ->
file, err = io.open fname
return nil, err unless file
text = assert file\read "*a"
file\close!
loadstring text, fname, ...
-- throws errros
dofile = (...) ->
f = assert loadfile ...
f!
insert_loader = (pos=2) ->
if not package.moonpath
package.moonpath = create_moonpath package.path
loaders = package.loaders or package.searchers
for loader in *loaders
return false if loader == moon_loader
insert loaders, pos, moon_loader
true
remove_loader = ->
loaders = package.loaders or package.searchers
for i, loader in ipairs loaders
if loader == moon_loader
remove loaders, i
return true
false
{
_NAME: "moonscript"
:insert_loader, :remove_loader, :to_lua, :moon_chunk, :moon_loader, :dirsep,
:dofile, :loadfile, :loadstring
}
| 22.942857 | 78 | 0.672893 |
8f0d8cd6c32c94dbed49a6ebce2a12a1965f02ba | 833 | -- non-recursive parsers
import safe_module from require "moonscript.util"
import S, P, R, C from require "lpeg"
White = S" \t\r\n"^0
plain_space = S" \t"^0
Break = P"\r"^-1 * P"\n"
Stop = Break + -1
Comment = P"--" * (1 - S"\r\n")^0 * #Stop
Space = plain_space * Comment^-1
SomeSpace = S" \t"^1 * Comment^-1
SpaceBreak = Space * Break
EmptyLine = SpaceBreak
AlphaNum = R "az", "AZ", "09", "__"
Name = C R("az", "AZ", "__") * AlphaNum^0
Num = P"0x" * R("09", "af", "AF")^1 * (S"uU"^-1 * S"lL"^2)^-1 +
R"09"^1 * (S"uU"^-1 * S"lL"^2) +
(
R"09"^1 * (P"." * R"09"^1)^-1 +
P"." * R"09"^1
) * (S"eE" * P"-"^-1 * R"09"^1)^-1
Shebang = P"#!" * P(1 - Stop)^0
safe_module "moonscript.parse.literals", {
:White, :Break, :Stop, :Comment, :Space, :SomeSpace, :SpaceBreak, :EmptyLine,
:AlphaNum, :Name, :Num, :Shebang
}
| 23.8 | 79 | 0.543818 |
153bfdb6a9ec95322d39ece1b5bdc760adde4f34 | 1,212 |
hi = [x*2 for _, x in ipairs{1,2,3,4}]
items = {1,2,3,4,5,6}
mm = [@x for @x in ipairs items]
[z for z in ipairs items when z > 4]
rad = [{a} for a in ipairs {
1,2,3,4,5,6,
} when good_number a]
[z for z in items for j in list when z > 4]
require "util"
dump = (x) -> print util.dump x
range = (count) ->
i = 0
return coroutine.wrap ->
while i < count
coroutine.yield i
i = i + 1
dump [x for x in range 10]
dump [{x, y} for x in range 5 when x > 2 for y in range 5]
things = [x + y for x in range 10 when x > 5 for y in range 10 when y > 7]
print x,y for x in ipairs{1,2,4} for y in ipairs{1,2,3} when x != 2
print "hello", x for x in items
[x for x in x]
x = [x for x in x]
print x,y for x in ipairs{1,2,4} for y in ipairs{1,2,3} when x != 2
double = [x*2 for x in *items]
print x for x in *double
cut = [x for x in *items when x > 3]
hello = [x + y for x in *items for y in *items]
print z for z in *hello
-- slice
x = {1, 2, 3, 4, 5, 6, 7}
print y for y in *x[2:-5:2]
print y for y in *x[:3]
print y for y in *x[2:]
print y for y in *x[::2]
print y for y in *x[2::2]
normal = (hello) ->
[x for x in yeah]
test = x 1,2,3,4,5
print thing for thing in *test
| 17.314286 | 74 | 0.580033 |
6433583c360d16ed523c3f62aa9778e78f271eec | 1,608 | class HitResult extends Base
new: (type, item, values) =>
@type = type
@item = item
-- Inject passed values, so we can be flexible about the HitResult
-- properties.
-- This allows the definition of getters too, e.g. for 'pixel'.
if values
values.enumerable = true
@inject values
getOptions: (options) =>
-- Use _merged property to not repeatetly call merge in recursion.
(if options and options._merged then options else Base\merge(
-- Type of item, for instanceof check: PathItem, TexItem, etc
type: null
-- Tolerance
tolerance: paper.project.options.hitTolerance or 2
-- Hit the fill of items
fill: not options
-- Hit the curves of path items, taking into account the stroke
-- width.
stroke: not options
-- Hit the part of segments that curves pass through, excluding
-- its segments (Segment--point)
segments: not options
-- Hit the parts of segments that define the curvature
handles: false
-- Only first or last segment hits on path (mutually exclusive
-- with segments: true)
ends: false
-- Hit test the center of the bounds
center: false
-- Hit test the corners and side-centers of the boudning box
bounds: false
-- Hit items that are marked as guides
guides: false
-- Only hit selected objects
selected: false
-- Mark as merged, so next time Base.merge isn't called
_merged: true
, options))
| 28.714286 | 70 | 0.610697 |
acc7aad8e346c0c2ec70baa64d6bdc8990708f49 | 17 | print "ss init"
| 8.5 | 16 | 0.647059 |
ed72b90cd0fc4ca53e6ce72a1e270cc8f9e22bf8 | 7,362 |
-- todo: splats in routes (*)
-- Cmt conditions on routes
-- pattern classes
-- :something[num] *[slug]
import insert from table
unpack = unpack or table.unpack
lpeg = require "lpeg"
import R, S, V, P from lpeg
import C, Cs, Ct, Cmt, Cg, Cb, Cc from lpeg
import encode_query_string from require "lapis.util"
reduce = (items, fn) ->
count = #items
error "reducing 0 item list" if count == 0
return items[1] if count == 1
left = fn items[1], items[2]
for i = 3, count
left = fn left, items[i]
left
class RouteParser
new: =>
@grammar = @build_grammar!
-- returns an lpeg patternt that matches route, along with table of flags
parse: (route) =>
@grammar\match route
compile_exclude: (current_p, chunks, k=1) =>
local out
for {kind, value, val_params} in *chunks[k,]
switch kind
when "literal"
if out
out += value
else
out = value
break
when "optional"
p = @route_precedence val_params
continue if current_p < p
if out
out += value
else
out = value
else
break
out
compile_chunks: (chunks, exclude=nil) =>
local patt
flags = {}
for i=#chunks,1,-1
chunk = chunks[i]
{kind, value, val_params} = chunk
flags[kind] or= 0
flags[kind] += 1
chunk_pattern = switch kind
when "splat"
inside = P 1
inside -= exclude if exclude
exclude = nil
Cg inside^1, "splat"
when "var"
char = val_params and @compile_character_class(val_params) or P 1
inside = char - "/"
inside -= exclude if exclude
exclude = nil
Cg inside^1, value
when "literal"
exclude = P value
P value
when "optional"
inner, inner_flags, inner_exclude = @compile_chunks value, exclude
for k,v in pairs inner_flags
flags[k] or= v
if inner_exclude
if exclude
exclude = inner_exclude + exclude
else
exclude = inner_exclude
inner^-1
else
error "unknown node: #{kind}"
patt = if patt
chunk_pattern * patt
else
chunk_pattern
patt, flags, exclude
-- convert character class, like %d to an lpeg pattern
compile_character_class: (chars) =>
@character_class_pattern or= Ct C("^")^-1 * (
C(P"%" * S"adw") +
(C(1) * P"-" * C(1) / (a, b) -> "#{a}#{b}") +
C(1)
)^1
negate = false
plain_chars = {}
items = @character_class_pattern\match chars
patterns = for item in *items
switch item
when "^"
negate = true
continue
when "%a"
R "az", "AZ"
when "%d"
R "09"
when "%w"
R "09", "az", "AZ"
else
if #item == 2
R item
else
table.insert plain_chars, item
continue
if next plain_chars
table.insert patterns, S table.concat plain_chars
local out
for p in *patterns
if out
out += p
else
out = p
if negate
out = 1 - out
out or P -1
build_grammar: =>
alpha = R("az", "AZ", "__")
alpha_num = alpha + R("09")
make_var = (str, char_class) -> { "var", str\sub(2), char_class }
make_splat = -> { "splat" }
make_lit = (str) -> { "literal", str }
make_optional = (children) -> { "optional", children }
splat = P"*"
var = P":" * alpha * alpha_num^0
var = C(var) * (P"[" * C((1 - P"]")^1) * P"]")^-1
@var = var
@splat = splat
chunk = var / make_var + splat / make_splat
chunk = (1 - chunk)^1 / make_lit + chunk
compile_chunks = @\compile_chunks
g = P {
"route"
optional_literal: (1 - P")" - V"chunk")^1 / make_lit
optional_route: Ct((V"chunk" + V"optional_literal")^1)
optional: P"(" * V"optional_route" * P")" / make_optional
literal: (1 - V"chunk")^1 / make_lit
chunk: var / make_var + splat / make_splat + V"optional"
route: Ct((V"chunk" + V"literal")^1)
}
g / @\compile_chunks / (p, f) -> Ct(p) * -1, f
class Router
new: =>
@routes = {}
@named_routes = {}
@parser = RouteParser!
add_route: (route, responder) =>
@p = nil
name = nil
if type(route) == "table"
name = next route
route = route[name]
-- keep existing route
unless @named_routes[name]
@named_routes[name] = route
insert @routes, { route, responder, name }
default_route: (route) =>
error "failed to find route: " .. route
route_precedence: (flags) =>
p = 0
if flags.var
p += flags.var
if flags.splat
p += 10 + (1 / flags.splat) * 10
p
build: =>
by_precedence = {}
for r in *@routes
pattern, flags = @build_route unpack r
p = @route_precedence flags
by_precedence[p] or= {}
table.insert by_precedence[p], pattern
precedences = [k for k in pairs by_precedence]
table.sort precedences
@p = nil
for p in *precedences
for pattern in *by_precedence[p]
if @p
@p += pattern
else
@p = pattern
@p or= P -1
build_route: (path, responder, name) =>
pattern, flags = @parser\parse path
pattern = pattern / (params) ->
params, responder, path, name
pattern, flags
fill_path: (path, params={}, route_name) =>
local optional_stack
replace = (s) ->
param_name = s\sub 2
if val = params[param_name]
if "table" == type val
if get_key = val.url_key
val = get_key(val, route_name, param_name) or ""
else
obj_name = val.__class and val.__class.__name or type(val)
error "Don't know how to serialize object for url: #{obj_name}"
optional_stack.hits += 1 if optional_stack
val, true
else
optional_stack.misses += 1 if optional_stack
""
patt = Cs P {
"string"
replacement: @parser.var / replace +
@parser.splat / (-> replace ":splat") +
V"optional"
optional: Cmt("(", (_, k) ->
optional_stack = {
hits: 0
misses: 0
prev: optional_stack
}
true, ""
) * Cmt Cs((V"replacement" + 1 - ")")^0) * P")", (_, k, match) ->
result = optional_stack
optional_stack = optional_stack.prev
if result.hits > 0 and result.misses == 0
true, match
else
true, ""
string: (V"replacement" + 1)^0
}
patt\match path
url_for: (name, params, query) =>
return params unless name
path = assert @named_routes[name], "Missing route named #{name}"
path = @fill_path path, params, name
if query
if type(query) == "table"
query = encode_query_string query
if query != ""
path ..= "?" .. query
path
match: (route) =>
@build! unless @p
@p\match route
resolve: (route, ...) =>
@build! unless @p
params, responder, path, name = @p\match route
if params and responder
responder params, path, name, ...
else
@default_route route, params, path, name
{ :Router, :RouteParser }
| 22.863354 | 76 | 0.537897 |
ec0ec4f9a260b243e9482b7627aa2e28a85978df | 695 |
inspect = require 'inspect'
parser = require 'src/parser'
JSON = require 'JSON'
files = {
'comma'
'demo'
'folding'
'html'
'indent'
'parentheses'
'quote'
'spaces'
'unfolding'
}
for key, value in pairs(files)
file = io.open ('cirru/' .. value .. '.cirru'), 'rb'
content = file\read "*all"
file\close()
tree = parser.pare content, ""
generated = JSON\encode tree
file = io.open ('ast/' .. value .. '.json'), 'rb'
template = file\read "*all"
file\close()
tree = JSON\decode template
template = JSON\encode tree
if generated == template
print "passed test: " .. value
else
print "failed at: " .. value
print(generated)
print(template)
| 17.820513 | 54 | 0.611511 |
e72758c1090fe41356ffbcb8e408fe9aca1ba4cf | 168 | toCharCode = zb2rhXYDewvrTT2NuGawYXLfRDxwmjkdjEqLd6CvGLSwNRKuG
char =>
n = (toCharCode char)
(or
(and (gtn n 96) (ltn n 103))
(and (gtn n 47) (ltn n 58)))
| 21 | 62 | 0.660714 |
7e5295d0bde0ed0e4811a0a6d30c3f0f18d0d60a | 1,172 | --> # libllengua
--> Library for managing conlangs
-- By daelvn
-- 19.04.2019
qualities = {
"advanced"
"advanced_tongue_root"
"alveolar"
"apical"
"aspirated"
"bidental"
"breathy_voiced"
"centralised"
"coarticulated"
"compressed"
"creaky_voiced"
"dental"
"double_long"
"ejective"
"epiglottalised"
"glottalised"
"half-long"
"ingressive"
"iotation"
"labialised"
"labiopalatalised"
"laminal"
"lateral_release"
"linguolabial"
"long"
"lowered"
"mid_centralised"
"nareal_frictative"
"nasalised"
"non_audible_release"
"non_syllabic"
"palatalised"
"pharyngealised"
"prestop"
"preaspirated"
"preglottalised"
"prelabialised"
"prelabiopalatalised"
"prenasalised"
"raised"
"retracted"
"retracted_tongue_root"
"rhotacised"
"short_consonant"
"sibilated"
"syllabic"
"tone_dipping"
"tone_extrahigh"
"tone_extralow"
"tone_falling"
"tone_high"
"tone_highfalling"
"tone_highrising"
"tone_low"
"tone_lowfalling"
"tone_lowrising"
"tone_mid"
"tone_peaking"
"tone_rising"
"uvularised"
"velarised"
"velopharyngeal"
"voiced"
"voiceless"
--
"none"
}
{ :qualities }
| 15.421053 | 33 | 0.682594 |
d76d1ecfb0f03a56a959290d643ada699ae68dd1 | 419 | [[
joli-lune
small framework for love2d
MIT License (see licence file)
]]
System = require "src.systems.system"
import graphics from love
class TiledMapLayer extends System
__tostring: => return "tiledmaplayer"
onCreate: (layer) => @layer = layer
update: (dt) => @layer\update dt
draw: =>
x,y = @position\get!
graphics.push!
graphics.translate x, y
@layer\draw!
graphics.pop!
return TiledMapLayer | 16.76 | 38 | 0.708831 |
f2ddc1ec15514527cb1a7a61f12610d618b9a2d9 | 346 | suit = require('vendor/SUIT')
Scene = require('lib/scenes/scene')
class GuiScene extends Scene
new: () =>
super()
@gui = suit.new()
update: (dt) =>
super(dt)
@gui.layout\reset(0, 0, 20, 20)
draw: () =>
super()
@gui\draw()
keypressed: (key) =>
super(key)
@gui\keypressed(key)
textinput: (text) =>
@gui\textinput(text)
| 14.416667 | 35 | 0.598266 |
8b47e52768a60a0c17811f2cccb9696ab4fa8664 | 35 | M = {}
M.main = () -> "m2"
return M | 11.666667 | 19 | 0.428571 |
a7913906c082e49127cf6a939265a5004fd91020 | 13,006 | lfs = require "lfs"
util = require "aegisub.util"
json = require "json"
PreciseTimer = require "PT.PreciseTimer"
Logger = require "l0.DependencyControl.Logger"
fileOps = require "l0.DependencyControl.FileOps"
mutex = require "BM.BadMutex"
class ConfigHandler
@handlers = {}
errors = {
jsonDecode: "JSON parse error: %s"
configCorrupted: [[An error occured while parsing the JSON config file.
A backup of the corrupted configuration has been written to '%s'.
Reload your automation scripts to generate a new configuration file.]]
badKey: "Can't %s section because the key #%d (%s) leads to a %s."
jsonRoot: "JSON root element must be an array or a hashtable, got a %s."
noFile: "No config file defined."
failedLock: "Failed to lock config file for %s: %s"
waitLockFailed: "Error waiting for existing lock to be released: %s"
forceReleaseFailed: "Failed to force-release existing lock after timeout had passed (%s)"
noLock: "#{@@__name} doesn't have a lock"
writeFailedRead: "Failed reading config file: %s."
lockTimeout: "Timeout reached while waiting for write lock."
}
traceMsgs = {
-- waitingLockPre: "Waiting %d ms before trying to get a lock..."
waitingLock: "Waiting for config file lock to be released (%d ms passed)... "
waitingLockFinished: "Lock was released after %d ms."
mergeSectionStart: "Merging own section into configuration. Own Section: %s\nConfiguration: %s"
mergeSectionResult: "Merge completed with result: %s"
fileNotFound: "Couldn't find config file '%s'."
fileCreate: "Config file '%s' doesn't exist, yet. Will write a fresh copy containing the current configuration section."
writing: "Writing config file '%s'..."
-- waitingLockTimeout: "Timeout was reached after %d seconds, force-releasing lock..."
}
new: (@file, defaults, @section, noLoad, @logger = Logger fileBaseName: @@__name) =>
@section = {@section} if "table" != type @section
@defaults = defaults and util.deep_copy(defaults) or {}
-- register all handlers for concerted writing
@setFile @file
-- set up user configuration and make defaults accessible
@userConfig = {}
@config = setmetatable {}, {
__index: (_, k) ->
if @userConfig and @userConfig[k] ~= nil
return @userConfig[k]
else return @defaults[k]
__newindex: (_, k, v) ->
@userConfig or= {}
@userConfig[k] = v
__len: (tbl) -> return 0
__ipairs: (tbl) -> error "numerically indexed config hive keys are not supported"
__pairs: (tbl) ->
merged = util.copy @defaults
merged[k] = v for k, v in pairs @userConfig
return next, merged
}
@c = @config -- shortcut
-- rig defaults in a way that writing to contained tables deep-copies the whole default
-- into the user configuration and sets the requested property there
recurse = (tbl) ->
for k,v in pairs tbl
continue if type(v)~="table" or type(k)=="string" and k\match "^__"
-- replace every table reference with an empty proxy table
-- this ensures all writes to the table get intercepted
tbl[k] = setmetatable {__key: k, __parent: tbl, __tbl: v}, {
-- make the original table the index of the proxy so that defaults can be read
__index: v
__len: (tbl) -> return #tbl.__tbl
__newindex: (tbl, k, v) ->
upKeys, parent = {}, tbl.__parent
-- trace back to defaults entry, pick up the keys along the path
while parent.__parent
tbl = parent
upKeys[#upKeys+1] = tbl.__key
parent = tbl.__parent
-- deep copy the whole defaults node into the user configuration
-- (util.deep_copy does not copy attached metatable references)
-- make sure we copy the actual table, not the proxy
@userConfig or= {}
@userConfig[tbl.__key] = util.deep_copy @defaults[tbl.__key].__tbl
-- finally perform requested write on userdata
tbl = @userConfig[tbl.__key]
for i = #upKeys-1, 1, -1
tbl = tbl[upKeys[i]]
tbl[k] = v
__pairs: (tbl) -> return next, tbl.__tbl
__ipairs: (tbl) ->
i, n, orgTbl = 0, #tbl.__tbl, tbl.__tbl
->
i += 1
return i, orgTbl[i] if i <= n
}
recurse tbl[k]
recurse @defaults
@load! unless noLoad
setFile: (path) =>
return false unless path
if @@handlers[path]
table.insert @@handlers[path], @
else @@handlers[path] = {@}
path, err = fileOps.validateFullPath path, true
return nil, err unless path
@file = path
return true
unsetFile: =>
handlers = @@handlers[@file]
if handlers and #handlers>1
@@handlers[@file] = [handler for handler in *handlers when handler != @]
else @@handlers[@file] = nil
@file = nil
return true
readFile: (file = @file, useLock = true, waitLockTime) =>
if useLock
time, err = @getLock waitLockTime
unless time
-- handle\close!
return false, errors.failedLock\format "reading", err
mode, file = fileOps.attributes file, "mode"
if mode == nil
@releaseLock! if useLock
return false, file
elseif not mode
@releaseLock! if useLock
@logger\trace traceMsgs.fileNotFound, @file
return nil
handle, err = io.open file, "r"
unless handle
@releaseLock! if useLock
return false, err
data = handle\read "*a"
success, result = pcall json.decode, data
unless success
handle\close!
-- JSON parse error usually points to a corrupted config file
-- Rename the broken file to allow generating a new one
-- so the user can continue his work
@logger\trace errors.jsonDecode, result
backup = @file .. ".corrupted"
fileOps.copy @file, backup
fileOps.remove @file, false, true
@releaseLock! if useLock
return false, errors.configCorrupted\format backup
handle\close!
@releaseLock! if useLock
if "table" != type result
return false, errors.jsonRoot\format type result
return result
load: =>
return false, errors.noFile unless @file
config, err = @readFile!
return config, err unless config
sectionExists = true
for i=1, #@section
config = config[@section[i]]
switch type config
when "table" continue
when "nil"
config, sectionExists = {}, false
break
else return false, errors.badKey\format "retrive", i, tostring(@section[i]),type config
@userConfig or= {}
@userConfig[k] = v for k,v in pairs config
return sectionExists
mergeSection: (config) =>
--@logger\trace traceMsgs.mergeSectionStart, @logger\dumpToString(@section),
-- @logger\dumpToString config
section, sectionExists = config, true
-- create missing parent sections
for i=1, #@section
childSection = section[@section[i]]
if childSection == nil
-- don't create parent sections if this section is going to be deleted
unless @userConfig
sectionExists = false
break
section[@section[i]] = {}
childSection = section[@section[i]]
elseif "table" != type childSection
return false, errors.badKey\format "update", i, tostring(@section[i]),type childSection
section = childSection if @userConfig or i < #@section
-- merge our values into our section
if @userConfig
section[k] = v for k,v in pairs @userConfig
elseif sectionExists
section[@section[#@section]] = nil
-- @logger\trace traceMsgs.mergeSectionResult, @logger\dumpToString config
return config
delete: (concertWrite, waitLockTime) =>
@userConfig = nil
return @write concertWrite, waitLockTime
write: (concertWrite, waitLockTime) =>
return false, errors.noFile unless @file
-- get a lock to avoid concurrent config file access
time, err = @getLock waitLockTime
unless time
return false, errors.failedLock\format "writing", err
-- read the config file
config, err = @readFile @file, false
if config == false
@releaseLock!
return false, errors.writeFailedRead\format err
@logger\trace traceMsgs.fileCreate, @file unless config
config or= {}
-- merge in our section
-- concerted writing allows us to update a configuration file
-- shared by multiple handlers in the lua environment
handlers = concertWrite and @@handlers[@file] or {@}
for handler in *handlers
config, err = handler\mergeSection config
unless config
@releaseLock!
return false, err
-- create JSON
success, res = pcall json.encode, config
unless success
@releaseLock!
return false, res
-- write the whole config file in one go
handle, err = io.open(@file, "w")
unless handle
@releaseLock!
return false, err
@logger\trace traceMsgs.writing, @file
handle\setvbuf "full", 10e6
handle\write res
handle\flush!
handle\close!
@releaseLock!
return true
getLock: (waitTimeout = 5000, checkInterval = 50) =>
return 0 if @hasLock
success = mutex.tryLock!
if success
@hasLock = true
return 0
timeout, timePassed = waitTimeout, 0
while not success and timeout > 0
PreciseTimer.sleep checkInterval
success = mutex.tryLock!
timeout -= checkInterval
timePassed = waitTimeout - timeout
if timePassed % (checkInterval*5) == 0
@logger\trace traceMsgs.waitingLock, timePassed
if success
@logger\trace traceMsgs.waitingLockFinished, timePassed
@hasLock = true
return timePassed
else
-- @logger\trace traceMsgs.waitingLockTimeout, waitTimeout/1000
-- success, err = @releaseLock true
-- unless success
-- return false, errors.forceReleaseFailed\format err
-- @hasLock = true
--return waitTimeout
return false, errors.lockTimeout
getSectionHandler: (section, defaults, noLoad) =>
return @@ @file, defaults, section, noLoad, @logger
releaseLock: (force) =>
if @hasLock or force
@hasLock = false
mutex.unlock!
return true
return false, errors.noLock
-- copied from Aegisub util.moon, adjusted to skip private keys
deepCopy: (tbl) =>
seen = {}
copy = (val) ->
return val if type(val) != 'table'
return seen[val] if seen[val]
seen[val] = val
{k, copy(v) for k, v in pairs val when type(k) != "string" or k\sub(1,1) != "_"}
copy tbl
import: (tbl = {}, keys, updateOnly, skipSameLengthTables) =>
tbl = tbl.userConfig if tbl.__class == @@
changesMade = false
@userConfig or= {}
keys = {key, true for key in *keys} if keys
for k,v in pairs tbl
continue if keys and not keys[k] or @userConfig[k] == v
continue if updateOnly and @c[k] == nil
-- TODO: deep-compare tables
isTable = type(v) == "table"
if isTable and skipSameLengthTables and type(@userConfig[k]) == "table" and #v == #@userConfig[k]
continue
continue if type(k) == "string" and k\sub(1,1) == "_"
@userConfig[k] = isTable and @deepCopy(v) or v
changesMade = true
return changesMade | 39.412121 | 128 | 0.556743 |
22c70d46f78d7eb49ddf0e7a04372ada64b691e8 | 5,864 | package.cpath = ";./?51.dll;./debug/?.dll;"..package.cpath
package.path = ";./socket/?.lua;"..package.path
--You can download the iup library from:
--http://sourceforge.net/projects/iup
require "iuplua"
import iup from _G
import emu, console from _G
--Using luasocket-2.0.2, you can download the socket library from:
--http://files.luaforge.net/releases/luasocket/luasocket
export socket = require('socket')
import prettyPrint, dumpPrint from require("utils")
export remExecBuilder = require('deserializeData')
export serverSocket = socket.udp()
export bindname = "*"
--export bindname = "127.0.0.1"
--export bindname = "localhost"
export bindport = 51424
export peername = "localhost"
--export peername = "127.0.0.1"
export peerport = 51425
serverSocket\setsockname(bindname, bindport)
serverSocket\settimeout(0)
serverSocket\setpeername(peername, peerport)
dumpPrint serverSocket
export queueInput=nil
export queueRcvCmd={}
export dataToSend="New command executed."
class ServerSpawn
--timer = nil
--new:(queueInput)=>
-- queueInput=queueInput
-- print "newnew"
new:()=>
print "new"
setInputQueue:(self, queue)->
queueInput=queue
print "setQueue"
--dumpPrint queueInput
addInputQueue:(self, msg)->
--print "current queue length: "..(#queueInput)
--print "new queue length: "..(#queue)
--print "new queue msg: "..tostring(msg)
--console.log msg
--dumpPrint queueInput
table.insert(queueInput, msg)
--queueInput={msg}
--print("added queueInp: "..(#queueInput))
--@run()
--print ("addedQueue: "..(#queueInput))
getSocketInfo:()->
print("Using sockname: "..bindname..":"..bindport)
print(serverSocket\getsockname())
print("Using peername: "..peername..":"..peerport)
print(serverSocket\getpeername())
cmpStartsString = (fullString,startString)->
return string.sub(fullString,1,string.len(startString))==startString
@fnTick:()->
--print("tick")
--print("tick")
@start()
--poll()
return iup.DEFAULT
@fnTock:()->
print("tock")
return iup.DEFAULT
@start:()->
--canread=nil
canread = socket.select({serverSocket}, nil, 0)
for i,inSocket in ipairs(canread) do
--iup.Close()
line, err = inSocket\receive()
if err then print "error: "..tostring(err)
rcptValue = tostring(line)
print("got: "..rcptValue)
if(rcptValue=="send") then
serverSocket\send(dataToSend)
print("done ".. rcptValue)
elseif(rcptValue~=nil and rcptValue~="nil") then
if not cmpStartsString(rcptValue,"confirm")
confirmMsg = "confirm: "..rcptValue
print("sending: "..confirmMsg)
serverSocket\send(confirmMsg)
--serverSocket\send(dataToSend);
print("added "..rcptValue)
gg = remExecBuilder(rcptValue)
table.insert(queueRcvCmd, gg)
@startTimer:()->
print("start timer")
fps = 111
timerTick = 1000/fps
timerTick=100
print("timer set at: ".. timerTick)
timer = iup.timer({time:timerTick, action_cb: @fnTock})
timer = iup.timer({time:timerTick, action_cb: @fnTick})
--timer.run="NO" --stop the timer
timer.run="YES" --start the timer
--iup.SetIdle(@fnTick) --this can be used as timer as well...
--dg = iup.dialog({title:"Timer example"})
--dg\show()
--iup.SetIdle(@fnTock)
--iup.MainLoop()
--run:()=>
-- print("inside run")
--testRun:()=>
run:()->
print "ok"
if(queueInput == nil) then print("queueInp: nil")
if(queueInput ~= nil) then
print("queueInp: "..(#queueInput))
for i, msg in ipairs(queueInput) do
print "msg to send: "..msg
--msg = io.read("*l")
--_,msg = iup.GetParam("Title", nil, "Msg to send: %s\n","")
--print socket.select({serverSocket}, nil, 0)
if msg == nil then
print("msg is null")
continue
print("SEND MSG: "..msg)
--queueInput[i]=nil
serverSocket\send(msg)
--serverSocket\sendto(msg, peername, peerport) --this may cause to crash here
--serverSocket\sendto(msg, "127.0.0.1", peerport) -- so this works
--serverSocket\sendto(msg, peername, peerport) -- so this works
print("SENDED MSG: "..msg)
--serverSocket\sendto("lol", "127.0.0.1", 51420) -- so this works
--serverSocket\sendto("lol", "127.0.0.1", 51420) -- so this works...
for i=0, #queueInput do queueInput[i]=nil --clear the queue
--queueInput= [nil for i,v in ipairs queueInput] --clear the queue
--print("queue cleared: "..(#queueInput))
--while true do
if false then
if (#queueRcvCmd > 0) then
--TODO: Send back the actual data returned.
--example:
--dataToSend= "game name: " .. gameinfo.getromname();
dataToSend = "New Command command executed with success."
for i, value in ipairs(queueRcvCmd) do
remCmd=queueRcvCmd[i]
queueRcvCmd[i]=nil
if(remCmd.multiArgs=="ping") then
print("pong")
dataToSend="pong"
else
if remCmd\isParsable() then
remCmd\parse()
--remCmd:print() -- show all the params and function used.
--else print("lib not supported")
if remCmd\isSupported() then
print("execute function...")
remCmd\exec()
--else print("function not supported")
queueRcvCmd={} --clear the queue
--emu.yield()
--emu.pause()
--@run()
--if _G.emu==nil and _G.tastudio==nil then
--print("using console mode")
--dg = iup.dialog({title:"Timer example"})
--dg\show()
--iup.MainLoop() --start a loop
testRun = ()->
queueInput={"hi"}
ServerSpawn\run()
queueInput=nil
testRun()
return {:ServerSpawn, :serverSocket}
| 27.530516 | 85 | 0.614427 |
940739550b6262c8f36402d89edb3503dbb1a487 | 6,828 | arrayLength = zb2rhj31DmWEQi2c9stdR1r8wfFboPeFCEdXNysWKikEx3QHy
arrayMap = zb2rhgW1F8GpBDCtoXjEcqDBFXNiCDaPNt1fekX2Po8uHWiEV
arrayGet = zb2rhjfCUgfysNDVs2pTuMw9Um8hRbGyYdsjKCaMTceKAGDSG
arraySlice = zb2rhiPF8JLJ2JFUKR3MGk8HvdjSSa6oAY7KmVpXzZfcD65zu
arrayAny = zb2rhgMZj9zo2uedSAd59429jtEuTVESMmwYkZesbpH8d2S92
arrayGenerate = zb2rhchsqGDzj5UBppkaEa9wm1H5n6VvVgQkHq6ryvFdKXWh8
arrayLast = zb2rhZhvZBAVJUaubWovcJQ3nY3BfqkXeSwyuQgfihH4BiAzo
arrayInit = zb2rhdmABYWjjPKYdUzzsSyt7tqhUfVHfcCWUPiBx9AEyTa8Z
strFilter = zb2rhnhgfZ8ynnFW7WtAuQvU23Z6Bt5UxYCVx8usrjt1m8VSu
strSplit = zb2rheqi4ntPSJQnoW8aCC7x9ydG5WBAM2dtDsQ9fDjkp36ek
strIndexOf = zb2rhbxRScabKQaihsvikS7VLMrqwVmG5xTiV8dhpmoycAHcV
bytesLength = zb2rhbRAVvyLUE9tCysrnWvP7guviTgXQWzcK41KocGrhnvnH
bytesConcat = zb2rhd8xzKmJPH4H4D8SABF547bcJy2P5ze7hmPEHJz2Pnp7N
bytesPad = zb2rharxQTRobPCL5Qhy6LaWTWo7LsYJ63rVzqjDrk3hArS8T
bytesFromHex = zb2rhnRAXG8KJ9FAwVTmW7qrfcMuWVJcnKNb5qSBe3sp2r9JS
bytesSlice = zb2rhg1FpG1nrxVEGvjp1gfU2tCP9sRmXXL77HjL2qnCfjUmv
bytesFromAscii = zb2rhoav2oVBSU3zQ3Yu1yZqUPcDFwLzxw2bG8NZqKWf4RVUj
u16ToBig = zb2rhYRhv5qo5sPoXSkH34uT4tRxpFDnNkc6G5BDW6pDEk3TW
bigToHex = zb2rhZFXk2vLZmHXnJ3VCsZfRXjDfSEi3o2fUT6g2iC7wecGU
hexToBig = zb2rhndxjNzRFG1YPHe8xK9S9nwGQKm3ChEBxovm8R2EC56F1
bigToNum = zb2rhhuEY9zoiu9rsJK7Mi3UGrQbRYTTyfFwiGyxdx1SP9raW
keccak256 = zb2rhkcDyioJbNcAMUAD4rBxi1pp5g5qFzAkGvQiKPu6MJcVu
isDynamic = isDynamic @ type =>
name = (get type "name")
(if (cmp name "tuple")
(arrayAny (eql 1)
(arrayMap isDynamic (get type "typs")))
dims = (get type "dims")
(arrayAny (eql 1) [
(cmp name "bytes")
(cmp name "string")
(arrayAny (eql 0) dims)
]))
type = type @ str =>
(if (cmp (slc str 0 1) "(")
types = (strSplit "," (slc str 1 (sub (len str) 1)))
{
name: "tuple"
typs: (arrayMap type types)
}
strs = (strSplit "[" (strFilter c => (sub 1 (cmp c "]")) str))
name = (get strs "0")
dims = (arrayMap (stn) (arraySlice strs 1 (arrayLength strs)))
{
name: name
dims: dims
})
encodeType = encode @ type => term =>
encodeBytes32 = hex =>
(bytesPad 1 32 "0x00" (bytesFromHex hex))
encodeAddress = hex =>
(bytesPad 0 32 "0x00" (bytesFromHex hex))
encodeUint256 = big =>
(bytesPad 0 32 "0x00" (bytesFromHex (bigToHex big)))
encodeBytes = bytes =>
length = (bytesLength bytes)
nextMul32 = (mul (add (flr (div (sub length 1) 32)) 1) 32)
lengthEncoded = (encodeUint256 (u16ToBig length))
bytesEncoded = (bytesPad 1 nextMul32 "0x00" bytes)
(bytesConcat lengthEncoded bytesEncoded)
encodeTuple = types => terms =>
size = (arrayLength types)
state = {head:"0x" tail:"0x"}
encoded = (for 0 size state i => state =>
head = (get state "head")
tail = (get state "tail")
type = (arrayGet types i)
term = (arrayGet terms i)
(if (isDynamic type)
{
head:
tailPos = (add (mul size 32) (bytesLength tail))
(bytesConcat head (encodeUint256 (u16ToBig tailPos)))
tail:
(bytesConcat tail (encode type term))
}
{
head: (bytesConcat head (encode type term))
tail: tail
}))
(bytesConcat
(get encoded "head")
(get encoded "tail"))
encodeArray = type => terms =>
name = (get type "name")
dims = (get type "dims")
lastDim = (arrayLast dims)
size = (arrayLength terms)
elementType = {
name: name
dims: (arrayInit dims)
}
tupleType = {
name: "tuple"
typs: (arrayMap term => elementType terms)
}
encodedSize = (if (eql lastDim 0) (encodeUint256 (u16ToBig size)) "0")
encodedTuple = (encode tupleType terms)
(bytesConcat
encodedSize
encodedTuple)
name = (get type "name")
(if (cmp name "tuple")
(encodeTuple (get type "typs") term)
(if (arrayLength (get type "dims"))
(encodeArray type term)
(if (cmp name "bytes32")
(encodeBytes32 term)
(if (cmp name "address")
(encodeAddress term)
(if (cmp name "uint256")
(encodeUint256 term)
(if (cmp name "bool")
(encodeUint256 term)
(if (cmp name "bytes")
(encodeBytes term)
(con "0xunsupported_type_" name))))))))
encodeCall = method => params =>
parensIndex = (strIndexOf "(" method)
methodName = (slc method 0 parensIndex)
methodType = (slc method parensIndex (len method))
sig = (bytesSlice (keccak256 (bytesFromAscii (con methodName methodType))) 0 4)
dat = (encodeType (type methodType) params)
(bytesConcat sig dat)
decodeType = type => bytes =>
decode = decode @ type => bytes => i =>
decodeUint256 = i =>
{
idx: (add i 32)
val: (hexToBig (bytesSlice bytes i (add i 32)))
}
decodeBytes32 = i =>
{
idx: (add i 32)
val: (bytesSlice bytes i (add i 32))
}
decodeAddress = i =>
{
idx: (add i 32)
val: (bytesSlice bytes 12 (add i 32))
}
decodeBytes = i =>
decodedSize = (decodeUint256 i)
size = (bigToNum (get decodedSize "val"))
j = (get decodedSize "idx")
{
idx: (add j size)
val: (bytesSlice bytes j (add j size))
}
decodeArray = type => i =>
name = (get type "name")
dims = (get type "dims")
lastDim = (arrayLast dims)
size = (if (eql lastDim 0) (bigToNum (get (decodeUint256 i) "val")) lastDim)
j = (if (eql lastDim 0) (add i 32) i)
elementType = {
name: name
dims: (arrayInit dims)
}
tupleType = {
name: "tuple"
typs: (arrayGenerate 0 size n => elementType)
}
(decode tupleType bytes j)
decodeTuple = types => i =>
size = (arrayLength types)
decodeds = (arrayGenerate 0 size n =>
type = (arrayGet types n)
j = (add i (mul n 32))
k = (if (isDynamic type) (add i (bigToNum (get (decodeUint256 j) "val"))) j)
(decode type bytes k))
{
idx: (get (arrayLast decodeds) "idx")
val: (arrayMap decoded => (get decoded "val") decodeds)
}
name = (get type "name")
result =
(if (cmp name "tuple")
(decodeTuple (get type "typs") i)
(if (arrayLength (get type "dims"))
(decodeArray type i)
(if (cmp name "bytes32")
(decodeBytes32 i)
(if (cmp name "address")
(decodeAddress i)
(if (cmp name "uint256")
(decodeUint256 i)
(if (cmp name "bool")
(decodeUint256 i)
(if (cmp name "bytes")
(decodeBytes i)
(con "unsupported_type_" name))))))))
result
(get (decode type bytes 0) "val")
(get {
encode: typeStr => (encodeType (type typeStr))
decode: typeStr => (decodeType (type typeStr))
encodeCall: encodeCall
})
| 28.214876 | 84 | 0.634446 |
48276e367f9c7526b8e8d3395167fd84183363d2 | 17,988 | import File from howl.io
describe 'File', ->
describe 'tmpfile()', ->
it 'returns a file instance pointing to an existing file', ->
file = File.tmpfile!
assert.is_true file.exists
file\delete!
describe 'with_tmpfile(f)', ->
it 'invokes <f> with the file', ->
f = spy.new (file) ->
assert.equals 'File', typeof(file)
File.with_tmpfile f
assert.spy(f).was_called(1)
it 'removes the temporary file even if <f> raises an error', ->
local tmpfile
f = (file) ->
tmpfile = file
error 'noo'
assert.raises 'noo', -> File.with_tmpfile f
assert.is_false tmpfile.exists
describe 'tmpdir()', ->
it 'returns a file instance pointing to an existing directory', ->
file = File.tmpdir!
assert.is_true file.exists
assert.is_true file.is_directory
file\delete_all!
describe 'expand_path(path)', ->
it 'expands "~" into the full path of the home directory', ->
assert.equals "#{os.getenv('HOME')}/foo.txt", (File.expand_path '~/foo.txt')
assert.equals "#{os.getenv('HOME')}/foo.txt", (File.expand_path '/blah/~/foo.txt')
it 'handles multiple "~/" by replacing the deepest one', ->
assert.equals "#{os.getenv('HOME')}/foo.txt", (File.expand_path '/a/b/~/c/~/foo.txt')
it 'does not expand "~" when part of another word', ->
assert.equals "/dir~/foo.txt", (File.expand_path '/dir~/foo.txt')
it 'does not expand trailing "~" without "/" suffix', ->
assert.equals "/dir/~", (File.expand_path '/dir/~')
describe 'new(p, cwd, opts = {})', ->
it 'accepts a string as denothing a path', ->
File '/bin/ls'
it 'accepts other files as well', ->
f = File '/bin/ls'
f2 = File f
assert.equal f, f2
context 'when <cwd> is specified', ->
it 'resolves a string <p> relative to <cwd>', ->
assert.equal '/bin/ls', File('ls', '/bin').path
it 'resolves an absolute string <p> as the absolute path', ->
assert.equal '/bin/ls', File('/bin/ls', '/home').path
it 'accepts other Files as <cwd>', ->
assert.equal '/bin/ls', File('ls', File('/bin')).path
it "accepts an optional type specifying the file's type", ->
f = File '/notherenothere', nil, type: File.TYPE_DIRECTORY
assert.is_true f.is_directory
describe '.is_absolute', ->
it 'returns true if the given path is absolute', ->
assert.is_true File.is_absolute '/bin/ls'
assert.is_true File.is_absolute 'c:\\\\bin\\ls'
it 'returns false if the given path is absolute', ->
assert.is_false File.is_absolute 'bin/ls'
assert.is_false File.is_absolute 'bin\\ls'
it '.basename returns the basename of the path', ->
assert.equal 'base.ext', File('/foo/base.ext').basename
describe '.display_name', ->
it 'is the same as the basename for files', ->
assert.equal 'base.ext', File('/foo/base.ext').display_name
it 'has a trailing separator for directories', ->
assert.equal 'bin/', File('/usr/bin').display_name
it '.extension returns the extension of the path', ->
assert.equal File('/foo/base.ext').extension, 'ext'
assert.equal File('/foo/base.ex+').extension, 'ex+'
it '.path returns the path of the file', ->
assert.equal '/foo/base.ext', File('/foo/base.ext').path
it '.uri returns an URI representing the path', ->
assert.equal File('/foo.txt').uri, 'file:///foo.txt'
it '.exists returns true if the path exists', ->
File.with_tmpfile (file) -> assert.is_true file.exists
describe '.short_path', ->
it 'returns the path with the home directory replace by "~"', ->
assert.equal '~', File(os.getenv('HOME')).short_path
file = File(os.getenv('HOME')) / 'foo.txt'
assert.equal '~/foo.txt', file.short_path
it 'does not replace a directory the home directory is a prefix of directory', ->
home_path = File(os.getenv('HOME')).path .. '-suffix'
home = File(home_path)
file = home / 'foo.txt'
assert.equal home.path, home.short_path
assert.equal file.path, file.short_path
describe 'contents', ->
it 'assigning a string writes the string to the file', ->
File.with_tmpfile (file) ->
file.contents = 'hello world'
f = io.open file.path
read_back = f\read '*all'
f\close!
assert.equal read_back, 'hello world'
it 'returns the contents of the file', ->
File.with_tmpfile (file) ->
f = io.open file.path, 'wb'
f\write 'hello world'
f\close!
assert.equal file.contents, 'hello world'
it '.parent return the parent of the file', ->
assert.equal File('/bin/ls').parent.path, '/bin'
it '.children returns a table of children', ->
with_tmpdir (dir) ->
dir\join('child1')\mkdir!
dir\join('child2')\touch!
kids = dir.children
table.sort kids, (a,b) -> a.path < b.path
assert.same [v.basename for v in *kids], { 'child1', 'child2' }
it '.children_async returns a table of children', (done) ->
howl_async ->
with_tmpdir (dir) ->
dir\join('child1')\mkdir!
dir\join('child2')\touch!
kids = dir.children_async
table.sort kids, (a,b) -> a.path < b.path
assert.same [v.basename for v in *kids], { 'child1', 'child2' }
done!
it '.file_type is a string describing the file type', ->
assert.equal 'directory', File('/bin').file_type
assert.equal 'regular', File('/bin/ls').file_type
assert.equal 'special', File('/dev/null').file_type
it '.writeable is true if the file represents a entry that can be written to', ->
with_tmpdir (dir) ->
assert.is_true dir.writeable
file = dir / 'file.txt'
assert.is_true file.writeable
file\touch!
assert.is_true file.writeable
assert.is_false File('/no/such/directory/orfile.txt').writeable
it '.readable is true if the file represents a entry that can be read', ->
with_tmpdir (dir) ->
assert.is_true dir.readable
file = dir / 'file.txt'
assert.is_false file.readable
file\touch!
assert.is_true file.readable
it '.etag is a string that can be used to check for modification', ->
File.with_tmpfile (file) ->
assert.is.not_nil file.etag
assert.equal type(file.etag), 'string'
it '.modified_at is a the unix time when the file was last modified', ->
File.with_tmpfile (file) ->
assert.is.not_nil file.modified_at
describe 'open([mode, function])', ->
context 'when <function> is nil', ->
it 'returns a Lua file handle', ->
File.with_tmpfile (file) ->
file.contents = 'first line\nsecond line\n'
fh = file\open!
assert.equal 'first line', fh\read!
assert.equal 'second line\n', fh\read '*L'
fh\close!
context 'when <function> is provided', ->
it 'it is invoked with the file handle', ->
File.with_tmpfile (file) ->
file.contents = 'first line\nsecond line\n'
local first_line
file\open 'r', (fh) ->
first_line = fh\read!
assert.equal 'first line', first_line
it 'returns the returns values of the function', ->
File.with_tmpfile (file) ->
assert.same { 'callback', nil, 'last' }, { file\open 'r', -> 'callback', nil, 'last' }
it 'closes the file automatically after invoking <function>', ->
File.with_tmpfile (file) ->
local handle
file\open 'r', (fh) -> handle = fh
assert.has_errors -> handle\read!
context 'when <function> raises an error', ->
it 'propagates that error', ->
File.with_tmpfile (file) ->
assert.raises 'kaboom', -> file\open 'r', -> error 'kaboom'
it 'still closes the file', ->
File.with_tmpfile (file) ->
local handle
pcall -> file\open 'r', (fh) ->
handle = fh
error 'kaboom'
assert.has_errors -> handle\read!
it 'read(..) is a short hand for doing a read(..) on the Lua file handle', ->
File.with_tmpfile (file) ->
file.contents = 'first line\n'
assert.same { 'first', ' line' }, { file\read 5, '*l' }
it 'join() returns a new file representing the specified child', ->
assert.equal File('/bin')\join('ls').path, '/bin/ls'
it 'relative_to_parent() returns a path relative to the specified parent', ->
parent = File '/bin'
file = File '/bin/ls'
assert.equal 'ls', file\relative_to_parent(parent)
it 'is_below(dir) returns true if the file is located beneath <dir>', ->
parent = File '/bin'
assert.is_true File('/bin/ls')\is_below parent
assert.is_true File('/bin/sub/ls')\is_below parent
assert.is_false File('/usr/bin/ls')\is_below parent
describe 'mkdir()', ->
it 'creates a directory for the path specified by the file', ->
File.with_tmpfile (file) ->
file\delete!
file\mkdir!
assert.is_true file.exists and file.is_directory
it 'raises an error if the directory could not be created', ->
assert.has_error -> File('/aksdjskjdgudfkj')\mkdir!
describe 'mkdir_p()', ->
it 'creates a directory for the path specified by the file, including parents', ->
File.with_tmpfile (file) ->
file\delete!
file = file\join 'sub/foo'
file\mkdir_p!
assert.is_true file.exists and file.is_directory
describe 'delete()', ->
it 'deletes the target file', ->
File.with_tmpfile (file) ->
file\delete!
assert.is_false file.exists
it 'raise an error if the file does not exist', ->
file = File.tmpfile!
file\delete!
assert.error -> file\delete!
it 'rm and unlink is an alias for delete', ->
assert.equal File.rm, File.delete
assert.equal File.unlink, File.delete
describe 'delete_all()', ->
context 'for a regular file', ->
it 'deletes the target file', ->
File.with_tmpfile (file) ->
file\delete_all!
assert.is_false file.exists
context 'for a directory', ->
it 'deletes the directory and all sub entries', ->
with_tmpdir (dir) ->
dir\join('child1')\mkdir!
dir\join('child1/sub_child')\touch!
dir\join('child2')\touch!
dir\delete_all!
assert.is_false dir.exists
it 'raise an error if the file does not exist', ->
File.with_tmpfile (file) ->
file\delete!
assert.error -> file\delete!
it 'rm_r is an alias for delete_all', ->
assert.equal File.rm_r, File.delete_all
describe 'touch()', ->
it 'creates the file if does not exist', ->
File.with_tmpfile (file) ->
file\delete!
file\touch!
assert.is_true file.exists
it 'raises an error if the file could not be created', ->
file = File '/no/does/not/exist'
assert.error -> file\touch!
describe 'tostring()', ->
it 'returns a string containing the path', ->
File.with_tmpfile (file) ->
to_s = file\tostring!
assert.equal 'string', typeof to_s
assert.equal to_s, file.path
describe 'find()', ->
with_populated_dir = (f) ->
with_tmpdir (dir) ->
dir\join('child1')\mkdir!
dir\join('child1/sub_dir')\mkdir!
dir\join('child1/sub_dir/deep.lua')\touch!
dir\join('child1/sub_child.txt')\touch!
dir\join('child1/sandwich.lua')\touch!
dir\join('child2')\touch!
f dir
it 'raises an error if the file is not a directory', ->
file = File '/no/does/not/exist'
assert.error -> file\find!
context 'with no parameters given', ->
it 'returns a list of all sub entries', ->
with_populated_dir (dir) ->
files = dir\find!
table.sort files, (a,b) -> a.path < b.path
normalized = [f\relative_to_parent dir for f in *files]
assert.same {
'child1',
'child1/sandwich.lua',
'child1/sub_child.txt',
'child1/sub_dir',
'child1/sub_dir/deep.lua',
'child2'
}, normalized
context 'when the sort parameter is given', ->
it 'returns a list of all sub entries in a pleasing order', ->
with_populated_dir (dir) ->
files = dir\find sort: true
normalized = [f\relative_to_parent dir for f in *files]
assert.same normalized, {
'child2',
'child1',
'child1/sandwich.lua',
'child1/sub_child.txt',
'child1/sub_dir',
'child1/sub_dir/deep.lua',
}
context 'when filter: is passed as an option', ->
it 'excludes files for which <filter(file)> returns true', ->
with_populated_dir (dir) ->
files = dir\find filter: (file) ->
file.basename != 'sandwich.lua' and file.basename != 'child1'
assert.same { 'child1', 'sandwich.lua' }, [f.basename for f in *files]
context 'when the on_enter parameter is given', ->
it 'is called once for each directory with the dir and files so far', ->
with_populated_dir (dir) ->
dirs = {}
total_files = 0
dir\find on_enter: (enter_dir, files) ->
dirs[#dirs + 1] = enter_dir
total_files = files
assert.equal 3, #dirs
assert.equal 6, #total_files
table.sort dirs
assert.same {
dir,
dir\join('child1'),
dir\join('child1')\join('sub_dir'),
}, dirs
context 'and it returns "break"', ->
it 'causes an early return', ->
with_populated_dir (dir) ->
files, cancelled = dir\find on_enter: (enter_dir, files) ->
if enter_dir.basename == 'child1'
return 'break'
assert.equal true, cancelled
table.sort files
assert.same {
dir\join('child1'),
dir\join('child2'),
}, files
describe 'find_paths(opts = {})', ->
with_populated_dir = (f) ->
with_tmpdir (dir) ->
dir\join('child1')\mkdir!
dir\join('child1/sub_dir')\mkdir!
dir\join('child1/sub_dir/deep.lua')\touch!
dir\join('child1/sub_child.txt')\touch!
dir\join('child1/sandwich.lua')\touch!
dir\join('child2')\touch!
f dir
it 'raises an error if the file is not a directory', ->
file = File '/no/does/not/exist'
assert.error -> file\find_paths!
context 'with no option specified', ->
it 'returns a list of all regular and directory sub paths', ->
with_populated_dir (dir) ->
paths = dir\find_paths!
table.sort paths
assert.same {
'child1/',
'child1/sandwich.lua',
'child1/sub_child.txt',
'child1/sub_dir/',
'child1/sub_dir/deep.lua',
'child2'
}, paths
context 'with the exclude_directories option specified', ->
it 'returns a list of all regular sub paths', ->
with_populated_dir (dir) ->
paths = dir\find_paths exclude_directories: true
table.sort paths
assert.same {
'child1/sandwich.lua',
'child1/sub_child.txt',
'child1/sub_dir/deep.lua',
'child2'
}, paths
context 'with the exclude_non_directories option specified', ->
it 'returns a list of all directory paths', ->
with_populated_dir (dir) ->
paths = dir\find_paths exclude_non_directories: true
table.sort paths
assert.same {
'child1/',
'child1/sub_dir/',
}, paths
context 'when filter: is passed as an option', ->
it 'excludes paths for which <filter(path)> returns true', ->
with_populated_dir (dir) ->
paths = dir\find_paths filter: (path) ->
not (path\ends_with('sandwich.lua') or path == 'child1/')
assert.same { 'child1/', 'child1/sandwich.lua' }, paths
context 'when the on_enter parameter is given', ->
it 'is called once for each directory with the dir and paths so far', ->
with_populated_dir (dir) ->
dirs = {}
total_files = 0
dir\find_paths on_enter: (enter_dir, files) ->
dirs[#dirs + 1] = enter_dir
total_files = files
assert.equal 3, #dirs
assert.equal 6, #total_files
table.sort dirs
assert.same {
'./',
'child1/',
'child1/sub_dir/',
}, dirs
context 'and it returns "break"', ->
it 'causes an early return', ->
with_populated_dir (dir) ->
local count
paths, cancelled = dir\find_paths on_enter: (enter_dir, cur_paths) ->
if enter_dir == 'child1/'
count = #cur_paths
return 'break'
assert.equal true, cancelled
assert.equal count, #paths
describe 'copy(dest)', ->
it 'copies the given file', ->
with_tmpdir (dir) ->
a = dir/'a.txt'
b = dir/'b.txt'
a.contents = 'hello'
a\copy b
assert.same b.contents, 'hello'
a.contents = 'hello 2'
assert.has_errors -> a\copy b
assert.same b.contents, 'hello'
a\copy b, {'COPY_OVERWRITE'}
assert.same b.contents, 'hello 2'
describe 'meta methods', ->
it '/ and .. joins the file with the specified argument', ->
file = File('/bin')
assert.equal (file / 'ls').path, '/bin/ls'
assert.equal (file .. 'ls').path, '/bin/ls'
it 'tostring returns the result of File.tostring', ->
file = File '/bin/ls'
assert.equal file\tostring!, tostring file
it '== returns true if the files point to the same path', ->
assert.equal File('/bin/ls'), File('/bin/ls')
| 34.132827 | 96 | 0.583667 |
163285bfce1084b1cf26e52ba9a784bcfbad8343 | 115 | path = "src/entities/"
player = require path .. "player"
block = require path .. "block"
{
:player
:block
}
| 11.5 | 33 | 0.608696 |
ef2e638efc460de1f1cc66bacd9fb427d7dc0ee5 | 3,282 | ffi = require "ffi"
require "ZF.img.buffer"
bmp_header = {
offset: 0
pixel_offset: 10
width: 18
height: 22
bpp: 28
compression: 30
}
-- https://github.com/max1220/lua-bitmap
class LIBBMP
version: "1.0.0"
new: (@filename = filename) =>
file = io.open @filename, "rb"
unless file
error "Can't open input file for reading: #{@filename}"
raw = file\read "*a"
assert raw and raw != "", "Can't read input file: #{@filename}"
file\close!
@raw = {}
for i = 1, #raw
@raw[i - 1] = raw\sub i, i
-- reading 8/16/32-bit little-endian integer values from a string
-- read uint8
read: (offset) =>
offset = tonumber offset
assert offset
value = @raw[math.floor offset]
assert value
return value\byte!
-- read uint16
read_word: (offset) => @read(offset + 1) * 0x100 + @read offset
-- read uint32
read_dword: (offset) => @read(offset + 3) * 0x1000000 + @read(offset + 2) * 0x10000 + @read(offset + 1) * 0x100 + @read offset
-- read int32
read_long: (offset) =>
value = @read_dword offset
if value >= 0x8000000
value = -(value - 0x80000000)
return value
decode: =>
-- check the bitmap header
unless @read_word(bmp_header.offset) == 0x4D42
error "Bitmap magic header not found"
compression = @read_dword bmp_header.compression
if compression != 0
error "Only uncompressed bitmaps supported. Is: #{compression}"
-- get bits per pixel from the bitmap header
-- this library only supports 24bpp and 32bpp pixel formats!
@bit_depth = @read_word bmp_header.bpp
unless @bit_depth == 24 or @bit_depth == 32
error "Only 24bpp/32bpp bitmaps supported. Is: #{@bit_depth}"
-- get other required info from the bitmap header
@pxOffset = @read_dword bmp_header.pixel_offset
@width = @read_long bmp_header.width
@height = @read_long bmp_header.height
-- if height is < 0, the image data is in topdown format
@topdown = true
if @height < 0
@topdown, @height = false, -@height
@getPixel = (x, y) =>
if (x < 0) or (x >= @width) or (y < 0) or (y >= @height)
error "Out of bounds"
-- calculate byte offset in data
bpp = @bit_depth / 8
lineW = math.ceil(@width / 4) * 4
index = @pxOffset + y * lineW * bpp + x * bpp
if @topdown
index = @pxOffset + (@height - y - 1) * bpp * lineW + x * bpp
b = @read index
g = @read index + 1
r = @read index + 2
a = bpp < 4 and 255 or @read index + 3
return r, g, b, a
@getData = =>
@data = ffi.new "color_RGBA[?]", @width * @height
for y = 0, @height - 1
for x = 0, @width - 1
r, g, b, a = @getPixel x, y
with @data[y * @width + x]
.r = r
.g = g
.b = b
.a = a
return @data
return @
{:LIBBMP} | 29.044248 | 130 | 0.510969 |
d006f7553b7405ef517f1abcf12c756b68edf0fb | 30,213 |
--
-- 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.
--
-- 0 eyes_updown
-- 1 eyes_rightleft
-- 2 JawOpen
-- 3 JawClose
-- 4 Smirk
-- 5 Frown
-- 6 Stretch
-- 7 Pucker
-- 8 Grin
-- 9 CatFace
-- 10 Mouth_O
-- 11 Mouth_O2
-- 12 Mouth_Full
-- 13 Tongue_Out
-- 14 Tongue_Up
-- 15 Tongue_Down
-- 16 NoEyelashes
-- 17 Eyes_Blink
-- 18 Left_Blink
-- 19 Right_Blink
-- 20 Scrunch
-- 21 FatButt
-- 22 Stomach_Out
-- 23 Stomach_In
-- 24 Throat_Bulge
-- 25 Male
-- 26 Hoof_Fluffers
-- 27 o3o
-- 28 Ear_Fluffers
-- 29 Fangs
-- 30 Claw_Teeth
-- 31 Fang_Test
-- 32 angry_eyes
-- 33 sad_eyes
-- 34 Eyes_Blink_Lower
-- 35 Male_2
-- 36 Buff_Body
-- 37 Manliest_Chin
-- 38 Lowerlid_Raise
-- 39 Happy_Eyes
-- 40 Duck
BLINK_CURVE = {0, 0.2, 0.45, 0.65, 0.9, 1, 1, 0.75, 0.55, 0.25, 0.15, 0}
BREATH_CURVE = {0, 0, 0, 0.1, 0.3, 0.55, 0.85, 1, 1, 0.85, 0.65, 0.4, 0.2, 0, 0, 0}
DISABLE_FLEXES = CreateConVar('ppm2_disable_flexes', '0', {FCVAR_ARCHIVE}, 'Disable pony flexes controllers. Saves some FPS.')
class FlexState extends PPM2.ModifierBase
@SetupModifiers: =>
@RegisterModifier('Speed', 0)
@RegisterModifier('Scale', 0)
@RegisterModifier('Weight', 0)
new: (controller, flexName = '', flexID = 0, scale = 1, speed = 1, active = true, min = 0, max = 1, useModifiers = true) =>
super()
@controller = controller
@name = flexName
@flexName = flexName
@flexID = flexID
@id = flexID
@scale = scale
@speed = speed
@originalscale = scale
@originalspeed = speed
@min = min
@max = max
@current = -1
@target = 0
@speedModify = 1
@scaleModify = 1
@modifiers = {}
@useModifiers = useModifiers
@active = active
@useLerp = true
@lerpMultiplier = 1
@activeID = "DisableFlex#{@flexName}"
controller = @controller\GetController()\GetData()
@SetIsActive(not controller['Get' .. @activeID](controller)) if controller['Get' .. @activeID]
__tostring: => "[#{@@__name}:#{@flexName}[#{@flexID}]|#{@GetData()}]"
GetFlexID: => @flexID
GetFlexName: => @flexName
SetUseLerp: (val = true) => @useLerp = val
GetUseLerp: => @useLerp
UseLerp: => @useLerp
SetLerpModify: (val = 1) => @lerpMultiplier = val
GetLerpModify: => @lerpMultiplier
LerpModify: => @lerpMultiplier
GetEntity: => @controller\GetEntity()
GetData: => @controller
GetController: => @controller
GetValue: => @current
GetRealValue: => @target
SetValue: (val = @target) =>
@current = math.Clamp(val, @min, @max) * @scale * @scaleModify
@target = @target
SetRealValue: (val = @target) => @target = math.Clamp(val, @min, @max) * @scale * @scaleModify
GetScale: => @scale
GetSpeed: => @speed
GetScaleModify: => @scaleModify
GetSpeedModify: => @speedModify
GetOriginalScale: => @originalscale
GetOriginalSpeed: => @originalspeed
SetScale: (val = @scale) => @scale = val
GetSpeed: (val = @speed) => @speed = val
SetScaleModify: (val = @scaleModify) => @scaleModify = val
GetSpeedModify: (val = @speedModify) => @speedModify = val
GetIsActive: => @active
SetIsActive: (val = true) => @active = val
AddValue: (val = 0) => @SetValue(@current + val)
AddRealValue: (val = 0) => @SetRealValue(@target + val)
Think: (ent = @GetEntity(), delta = 0) =>
return if not @active
if @useModifiers
@current = 0
@scale = @originalscale * @scaleModify
@speed = @originalspeed * @speedModify
if @useLerp
for i = 1, #@WeightModifiers
@modifiers[i] = Lerp(delta * 15 * @speed * @speedModify * @lerpMultiplier, @modifiers[i] or 0, @WeightModifiers[i])
@current += @modifiers[i]
else
@current += @WeightModifiers[i] for i = 1, #@WeightModifiers
@scale += modif for _, modif in ipairs @ScaleModifiers
@speed += modif for _, modif in ipairs @SpeedModifiers
@current = math.Clamp(@current, @min, @max) * @scale
ent\SetFlexWeight(@flexID, @current)
DataChanges: (state) =>
return if state\GetKey() ~= @activeID
@SetIsActive(not state\GetValue())
@GetController()\RebuildIterableList()
@Reset()
Reset: (resetVars = true) =>
for name, id in pairs @modifiersNames
@ResetModifiers(name)
if resetVars
@scaleModify = 1
@speedModify = 1
@scale = @originalscale * @scaleModify
@speed = @originalspeed * @speedModify
@target = 0
@current = 0
@GetEntity()\SetFlexWeight(@flexID, 0) if IsValid(@GetEntity())
PPM2.FlexState = FlexState
class FlexSequence extends PPM2.SequenceBase
new: (controller, data) =>
super(controller, data)
{
'ids': @flexIDsIterable
'numid': @numid
} = data
@flexIDS = {}
@flexStates = {}
i = 1
for _, id in ipairs data.ids
state = controller\GetFlexState(id)
num = state\GetModifierID(@name)
@["flex_#{id}"] = num
@flexIDS[id] = num
@flexStates[id] = state
@flexStates[i] = state
@flexIDS[i] = num
i += 1
@controller = controller
@Launch()
GetController: => @controller
GetModifierID: (id = '') => @flexIDS[id]
GetFlexState: (id = '') => @flexStates[id]
Think: (delta = 0) =>
return false if not IsValid(@GetEntity())
super(delta)
Stop: =>
super()
return unless @parent
@parent\GetFlexState(id)\ResetModifiers(@name) for _, id in ipairs @flexIDsIterable
SetModifierWeight: (id = '', val = 0) => @GetFlexState(id)\SetModifierWeight(@GetModifierID(id), val)
SetModifierSpeed: (id = '', val = 0) => @GetFlexState(id)\SetModifierSpeed(@GetModifierID(id), val)
SetUseLerp: (id = '', status = true) => @GetFlexState(id)\SetUseLerp(status)
GetUseLerp: (id = '') => @GetFlexState(id)\GetUseLerp()
PPM2.FlexSequence = FlexSequence
class PonyFlexController extends PPM2.ControllerChildren
@AVALIABLE_CONTROLLERS = {}
@MODELS = {'models/ppm/player_default_base_new.mdl', 'models/ppm/player_default_base_new_nj.mdl'}
@FLEX_LIST = {
{flex: 'eyes_updown', scale: 1, speed: 1, active: false}
{flex: 'eyes_rightleft', scale: 1, speed: 1, active: false}
{flex: 'JawOpen', scale: 1, speed: 1, active: true}
{flex: 'JawClose', scale: 1, speed: 1, active: true}
{flex: 'Smirk', scale: 1, speed: 1, active: true}
{flex: 'Frown', scale: 1, speed: 1, active: true}
{flex: 'Stretch', scale: 1, speed: 1, active: false}
{flex: 'Pucker', scale: 1, speed: 1, active: false}
{flex: 'Grin', scale: 1, speed: 1, active: true}
{flex: 'CatFace', scale: 1, speed: 1, active: true}
{flex: 'Mouth_O', scale: 1, speed: 1, active: true}
{flex: 'Mouth_O2', scale: 1, speed: 1, active: true}
{flex: 'Mouth_Full', scale: 1, speed: 1, active: false}
{flex: 'Tongue_Out', scale: 1, speed: 1, active: true}
{flex: 'Tongue_Up', scale: 1, speed: 1, active: true}
{flex: 'Tongue_Down', scale: 1, speed: 1, active: true}
{flex: 'NoEyelashes', scale: 1, speed: 1, active: false}
{flex: 'Eyes_Blink', scale: 1, speed: 1, active: false}
{flex: 'Left_Blink', scale: 1, speed: 1, active: true}
{flex: 'Right_Blink', scale: 1, speed: 1, active: true}
{flex: 'Scrunch', scale: 1, speed: 1, active: true}
{flex: 'FatButt', scale: 1, speed: 1, active: false}
{flex: 'Stomach_Out', scale: 1, speed: 1, active: true}
{flex: 'Stomach_In', scale: 1, speed: 1, active: true}
{flex: 'Throat_Bulge', scale: 1, speed: 1, active: true}
{flex: 'Male', scale: 1, speed: 1, active: false}
{flex: 'Hoof_Fluffers', scale: 1, speed: 1, active: false}
{flex: 'o3o', scale: 1, speed: 1, active: true}
{flex: 'Ear_Fluffers', scale: 1, speed: 1, active: false}
{flex: 'Fangs', scale: 1, speed: 1, active: false}
{flex: 'Claw_Teeth', scale: 1, speed: 1, active: false}
{flex: 'Fang_Test', scale: 1, speed: 1, active: false}
{flex: 'angry_eyes', scale: 1, speed: 1, active: true}
{flex: 'sad_eyes', scale: 1, speed: 1, active: true}
{flex: 'Eyes_Blink_Lower', scale: 1, speed: 1, active: true}
{flex: 'Male_2', scale: 1, speed: 1, active: false}
{flex: 'Buff_Body', scale: 1, speed: 1, active: false}
{flex: 'Manliest_Chin', scale: 1, speed: 1, active: false}
{flex: 'Lowerlid_Raise', scale: 1, speed: 1, active: false}
{flex: 'Happy_Eyes', scale: 1, speed: 1, active: true}
{flex: 'Duck', scale: 1, speed: 1, active: true}
}
@SEQUENCES = {
{
'name': 'anger'
'autostart': false
'repeat': false
'time': 5
'ids': {'Frown', 'Grin', 'angry_eyes', 'Scrunch'}
'reset': =>
@SetTime(math.random(15, 45) / 10)
@lastStrengthUpdate = @lastStrengthUpdate or 0
if @lastStrengthUpdate < CurTimeL()
@lastStrengthUpdate = CurTimeL() + 2
@frownStrength = math.random(40, 100) / 100
@grinStrength = math.random(15, 40) / 100
@angryStrength = math.random(30, 80) / 100
@scrunchStrength = math.random(50, 100) / 100
@SetModifierWeight(1, @frownStrength)
@SetModifierWeight(2, @grinStrength)
@SetModifierWeight(3, @angryStrength)
@SetModifierWeight(4, @scrunchStrength)
}
{
'name': 'sad'
'autostart': false
'repeat': false
'time': 5
'ids': {'Frown', 'Grin', 'sad_eyes'}
'reset': =>
@SetTime(math.random(15, 45) / 10)
@lastStrengthUpdate = @lastStrengthUpdate or 0
if @lastStrengthUpdate < CurTimeL()
@lastStrengthUpdate = CurTimeL() + 2
@frownStrength = math.random(40, 100) / 100
@grinStrength = math.random(15, 40) / 100
@angryStrength = math.random(30, 80) / 100
'func': (delta, timeOfAnim) =>
@SetModifierWeight(1, @frownStrength)
@SetModifierWeight(2, @grinStrength)
@SetModifierWeight(3, @angryStrength)
}
{
'name': 'ugh'
'autostart': false
'repeat': false
'time': 5
'ids': {'sad_eyes', 'Eyes_Blink_Lower'}
'reset': =>
@SetModifierWeight(1, math.Rand(0.27, 0.34))
@SetModifierWeight(2, math.Rand(0.3, 0.35))
@PauseSequence('eyes_blink')
@PauseSequence('eyes_idle')
}
{
'name': 'suggestive_eyes'
'autostart': false
'repeat': false
'time': 5
'ids': {'sad_eyes', 'Eyes_Blink_Lower'}
'reset': =>
@SetModifierWeight(1, 0.28)
@SetModifierWeight(2, 0.4)
@PauseSequence('eyes_blink')
@PauseSequence('eyes_idle')
}
{
'name': 'lips_lick'
'autostart': false
'repeat': false
'time': 5
'ids': {'Tongue_Out', 'Tongue_Up'}
'reset': =>
@SetModifierWeight(1, 0.9)
'func': (delta, timeOfAnim) =>
@SetModifierWeight(2, 0.75 + math.sin(CurTimeL() * 7) * 0.25)
}
{
'name': 'tongue_pullout'
'autostart': false
'repeat': false
'time': 5
'ids': {'Tongue_Out'}
'func': (delta, timeOfAnim) =>
@SetModifierWeight(1, 0.15 + math.sin(CurTimeL() * 10) * 0.1)
}
{
'name': 'tongue_pullout_twitch'
'autostart': false
'repeat': false
'time': 5
'ids': {'Tongue_Out'}
'func': (delta, timeOfAnim) =>
@SetModifierWeight(1, 0.5 + math.sin(CurTimeL() * 4) * 0.5)
}
{
'name': 'tongue_pullout_twitch_fast'
'autostart': false
'repeat': false
'time': 5
'ids': {'Tongue_Out'}
'func': (delta, timeOfAnim) =>
@SetModifierWeight(1, 0.5 + math.sin(CurTimeL() * 8) * 0.5)
}
{
'name': 'suggestive_open'
'autostart': false
'repeat': false
'time': 5
'ids': {'Pucker', 'JawOpen', 'Scrunch'}
'reset': =>
@SetModifierWeight(1, math.Rand(0.28, 0.34))
@SetModifierWeight(2, math.Rand(0.35, 0.40))
@SetModifierWeight(3, math.Rand(0.45, 0.50))
}
{
'name': 'suggestive_open_anim'
'autostart': false
'repeat': false
'time': 5
'ids': {'Pucker', 'JawOpen', 'Scrunch'}
'reset': =>
@SetModifierWeight(1, math.Rand(0.28, 0.34))
@SetModifierWeight(3, math.Rand(0.45, 0.50))
'func': (delta, timeOfAnim) =>
@SetModifierWeight(2, 0.2 + math.sin(CurTimeL() * 16) * 0.07)
}
{
'name': 'face_smirk'
'autostart': false
'repeat': false
'time': 5
'ids': {'Smirk', 'Frown'}
'reset': =>
@SetModifierWeight(1, 0.78)
@SetModifierWeight(2, 0.61)
}
{
'name': 'eyes_idle'
'autostart': true
'repeat': true
'time': 5
'ids': {'Left_Blink', 'Right_Blink'}
'func': (delta, timeOfAnim) =>
return false if @GetEntity()\GetNWBool('PPM2.IsDeathRagdoll') or (@GetEntity()\IsPlayer() and not @GetEntity()\Alive())
value = math.abs(math.sin(CurTimeL() * .5) * .15)
@SetModifierWeight(1, value)
@SetModifierWeight(2, value)
}
{
'name': 'eyes_close'
'autostart': true
'repeat': true
'time': 5
'ids': {'Left_Blink', 'Right_Blink', 'Frown'}
'func': (delta, timeOfAnim) =>
allow = true
if @GetEntity()\IsPlayer()
if @GetEntity()\Alive()
allow = false
else
if not @GetEntity()\GetNWBool('PPM2.IsDeathRagdoll')
allow = false
if not allow
@SetModifierWeight(1, 0)
@SetModifierWeight(2, 0)
@SetModifierWeight(3, 0)
return
@SetModifierWeight(1, 1)
@SetModifierWeight(2, 1)
@SetModifierWeight(3, 0.5)
}
{
'name': 'body_idle'
'autostart': true
'repeat': true
'time': 2
'ids': {'Stomach_Out'}
'func': (delta, timeOfAnim) =>
return false if @GetEntity()\GetNWBool('PPM2.IsDeathRagdoll') or (@GetEntity()\IsPlayer() and not @GetEntity()\Alive())
return if timeOfAnim < 0 or timeOfAnim > 1
@SetModifierWeight(1, math.tbezier(timeOfAnim, BREATH_CURVE) * 0.35)
}
{
'name': 'health_idle'
'autostart': true
'repeat': true
'time': 5
'ids': {'Frown', 'Left_Blink', 'Right_Blink', 'Scrunch', 'Mouth_O', 'JawOpen', 'Grin'}
'func': (delta, timeOfAnim) =>
return false if (not @GetEntity()\IsPlayer() or not @GetEntity()\Alive()) and not @GetEntity()\IsNPC() and @GetEntity().Type ~= 'nextbot'
frown = @GetModifierID(1)
frownState = @GetFlexState(1)
left, right = @GetModifierID(2), @GetModifierID(3)
leftState, rightState = @GetFlexState(2), @GetFlexState(3)
Mouth_O, Mouth_OState = @GetModifierID(4), @GetFlexState(4)
Scrunch = @GetModifierID(4)
ScrunchState = @GetFlexState(4)
hp, mhp = @GetEntity()\Health(), @GetEntity()\GetMaxHealth()
mhp = 1 if mhp == 0
div = hp / mhp
strength = math.Clamp(1.5 - div * 1.5, 0, 1)
frownState\SetModifierWeight(frown, strength)
ScrunchState\SetModifierWeight(Scrunch, strength * .5)
leftState\SetModifierWeight(left, strength * .1)
rightState\SetModifierWeight(right, strength * .1)
Mouth_OState\SetModifierWeight(Mouth_O, strength * .8)
JawOpen = @GetModifierID(6)
JawOpenState = @GetFlexState(6)
if strength > .75
JawOpenState\SetModifierWeight(JawOpen, strength * .2 + math.sin(CurTimeL() * strength * 3) * .1)
else
JawOpenState\SetModifierWeight(JawOpen, 0)
if div >= 2
@SetModifierWeight(7, .5)
else
@SetModifierWeight(7, 0)
}
{
'name': 'greeny'
'autostart': false
'repeat': false
'time': 2
'ids': {'Grin'}
'func': (delta, timeOfAnim) =>
Grin = @GetModifierID(1)
GrinState = @GetFlexState(1)
strength = .5 + math.sin(CurTimeL() * 2) * .25
GrinState\SetModifierWeight(Grin, strength)
}
{
'name': 'big_grin'
'autostart': false
'repeat': false
'time': 3
'ids': {'Grin'}
'func': (delta, timeOfAnim) =>
Grin = @GetModifierID(1)
GrinState = @GetFlexState(1)
GrinState\SetModifierWeight(Grin, 1)
}
{
'name': 'o3o'
'autostart': false
'repeat': false
'time': 3
'ids': {'o3o'}
'func': (delta, timeOfAnim) =>
@SetModifierWeight(1, 1)
}
{
'name': 'owo_alternative'
'autostart': false
'repeat': false
'time': 5
'ids': {'o3o', 'JawOpen'}
'reset': (delta, timeOfAnim) =>
@SetModifierWeight(1, math.Rand(0.8, 1))
@SetModifierWeight(2, math.Rand(0.05, 0.1))
}
{
'name': 'xd'
'autostart': false
'repeat': false
'time': 3
'ids': {'Grin', 'Left_Blink', 'Right_Blink', 'JawOpen'}
'func': (delta, timeOfAnim) =>
Grin = @GetModifierID(1)
GrinState = @GetFlexState(1)
GrinState\SetModifierWeight(Grin, .6)
Left_Blink = @GetModifierID(2)
Left_BlinkState = @GetFlexState(2)
Left_BlinkState\SetModifierWeight(Left_Blink, .9)
Right_Blink = @GetModifierID(3)
Right_BlinkState = @GetFlexState(3)
Right_BlinkState\SetModifierWeight(Right_Blink, .9)
JawOpen = @GetModifierID(4)
JawOpenState = @GetFlexState(4)
JawOpenState\SetModifierScale(JawOpen, 2)
JawOpenState\SetModifierWeight(JawOpen, (timeOfAnim % .1) * 2)
}
{
'name': 'tongue'
'autostart': false
'repeat': false
'time': 3
'ids': {'JawOpen', 'Tongue_Out'}
'func': (delta, timeOfAnim) =>
@SetModifierWeight(1, .1)
@SetModifierWeight(2, 1)
}
{
'name': 'angry_tongue'
'autostart': false
'repeat': false
'time': 6
'ids': {'Frown', 'Grin', 'angry_eyes', 'Scrunch', 'JawOpen', 'Tongue_Out'}
'reset': (delta, timeOfAnim) =>
@SetModifierWeight(1, math.random(40, 100) / 100)
@SetModifierWeight(2, math.random(15, 40) / 100)
@SetModifierWeight(3, math.random(30, 80) / 100)
@SetModifierWeight(4, math.random(50, 100) / 100)
@SetModifierWeight(5, math.random(10, 15) / 100)
@SetModifierWeight(6, math.random(80, 100) / 100)
}
{
'name': 'pffff'
'autostart': false
'repeat': false
'time': 6
'ids': {'Frown', 'Grin', 'angry_eyes', 'Scrunch', 'JawOpen', 'Tongue_Out', 'Tongue_Down', 'Tongue_Up'}
'reset': =>
@SetModifierWeight(1, math.random(40, 100) / 100)
@SetModifierWeight(2, math.random(15, 40) / 100)
@SetModifierWeight(3, math.random(30, 80) / 100)
@SetModifierWeight(4, math.random(50, 100) / 100)
@SetModifierWeight(5, math.random(10, 15) / 100)
@SetModifierWeight(6, math.random(80, 100) / 100)
'func': (delta, timeOfAnim) =>
val = math.sin(CurTimeL() * 8) * .6
if val > 0
@SetModifierWeight(7, val)
@SetModifierWeight(8, 0)
else
@SetModifierWeight(7, 0)
@SetModifierWeight(8, -val)
}
{
'name': 'cat'
'autostart': false
'repeat': false
'time': 5
'ids': {'CatFace'}
'func': (delta, timeOfAnim) =>
Grin = @GetModifierID(1)
GrinState = @GetFlexState(1)
GrinState\SetModifierWeight(Grin, 1)
}
{
'name': 'ooo'
'autostart': false
'repeat': false
'time': 2
'ids': {'Mouth_O2', 'Mouth_O'}
'func': (delta, timeOfAnim) =>
timeOfAnim *= 2
Grin = @GetModifierID(1)
GrinState = @GetFlexState(1)
GrinState\SetModifierWeight(Grin, timeOfAnim)
Grin = @GetModifierID(2)
GrinState = @GetFlexState(2)
GrinState\SetModifierWeight(Grin, timeOfAnim)
}
{
'name': 'talk'
'autostart': false
'repeat': false
'time': 2
'ids': {'JawOpen', 'Tongue_Out', 'Tongue_Up', 'Tongue_Down'}
'create': =>
@talkAnim = for i = 0, 1, 0.05
rand = math.random(1, 100) / 100
if rand <= .25
{1 * rand, 0.4 * rand, 2 * rand, 0}
elseif rand >= .25 and rand < .4
rand *= .8
{2 * rand, .6 * rand, 0, 1 * rand}
elseif rand >= .4 and rand < .75
rand *= .6
{1 * rand, 0, 1 * rand, 2 * rand}
elseif rand >= .75
rand *= .4
{1.5 * rand, 0, 1 * rand, 0}
@SetModifierSpeed(1, 2)
@SetModifierSpeed(2, 2)
@SetModifierSpeed(3, 2)
@SetModifierSpeed(4, 2)
'func': (delta, timeOfAnim) =>
JawOpen = @GetModifierID(1)
JawOpenState = @GetFlexState(1)
Tongue_OutOpen = @GetModifierID(2)
Tongue_OutOpenState = @GetFlexState(2)
Tongue_UpOpen = @GetModifierID(3)
Tongue_UpOpenState = @GetFlexState(3)
Tongue_DownOpen = @GetModifierID(4)
Tongue_DownOpenState = @GetFlexState(4)
cPos = math.floor(timeOfAnim * 20) + 1
data = @talkAnim[cPos]
return if not data
{jaw, out, up, down} = data
JawOpenState\SetModifierWeight(JawOpen, jaw)
Tongue_OutOpenState\SetModifierWeight(Tongue_OutOpen, out)
Tongue_UpOpenState\SetModifierWeight(Tongue_UpOpen, up)
Tongue_DownOpenState\SetModifierWeight(Tongue_DownOpen, down)
}
{
'name': 'talk_endless'
'autostart': false
'repeat': true
'time': 4
'ids': {'JawOpen', 'Tongue_Out', 'Tongue_Up', 'Tongue_Down'}
'create': =>
@talkAnim = for i = 0, 1, 0.05
rand = math.random(1, 100) / 100
if rand <= .25
{1 * rand, 0.4 * rand, 2 * rand, 0}
elseif rand >= .25 and rand < .4
rand *= .8
{2 * rand, .6 * rand, 0, 1 * rand}
elseif rand >= .4 and rand < .75
rand *= .6
{1 * rand, 0, 1 * rand, 2 * rand}
elseif rand >= .75
rand *= .4
{1.5 * rand, 0, 1 * rand, 0}
@SetModifierSpeed(1, 2)
@SetModifierSpeed(2, 2)
@SetModifierSpeed(3, 2)
@SetModifierSpeed(4, 2)
'func': (delta, timeOfAnim) =>
JawOpen = @GetModifierID(1)
JawOpenState = @GetFlexState(1)
Tongue_OutOpen = @GetModifierID(2)
Tongue_OutOpenState = @GetFlexState(2)
Tongue_UpOpen = @GetModifierID(3)
Tongue_UpOpenState = @GetFlexState(3)
Tongue_DownOpen = @GetModifierID(4)
Tongue_DownOpenState = @GetFlexState(4)
cPos = math.floor(timeOfAnim * 20) + 1
data = @talkAnim[cPos]
return if not data
{jaw, out, up, down} = data
volume = @GetEntity()\VoiceVolume() * 6
jaw *= volume
out *= volume
up *= volume
down *= volume
JawOpenState\SetModifierWeight(JawOpen, jaw)
Tongue_OutOpenState\SetModifierWeight(Tongue_OutOpen, out)
Tongue_UpOpenState\SetModifierWeight(Tongue_UpOpen, up)
Tongue_DownOpenState\SetModifierWeight(Tongue_DownOpen, down)
}
{
'name': 'eyes_blink'
'autostart': true
'repeat': true
'time': 7
'ids': {'Eyes_Blink_Lower'}
'create': =>
@SetUseLerp(1, false)
'reset': =>
@nextBlink = math.random(300, 600) / 1000
@nextBlinkLength = math.random(15, 30) / 800
@min, @max = @nextBlink, @nextBlink + @nextBlinkLength
'func': (delta, timeOfAnim) =>
return false if @GetEntity()\GetNWBool('PPM2.IsDeathRagdoll') or (@GetEntity()\IsPlayer() and not @GetEntity()\Alive())
if @min > timeOfAnim or @max < timeOfAnim
if @blinkHit
@blinkHit = false
@SetModifierWeight(1, 0)
return
len = (timeOfAnim - @min) / @nextBlinkLength
blink = math.tbezier(len\clamp(0, 1), BLINK_CURVE)
@SetModifierWeight(1, blink)
-- print(len, blink)
@blinkHit = true
}
{
'name': 'hurt'
'autostart': false
'repeat': false
'time': 4
'ids': {'JawOpen', 'Frown', 'Grin', 'Scrunch'}
'reset': (delta, timeOfAnim) =>
@SetModifierWeight(1, math.random(4, 16) / 100)
@SetModifierWeight(2, math.random(60, 70) / 100)
@SetModifierWeight(3, math.random(30, 40) / 100)
@SetModifierWeight(4, math.random(70, 90) / 100)
}
{
'name': 'kill_grin'
'autostart': false
'repeat': false
'time': 8
'ids': {'Smirk', 'Frown', 'Grin'}
'func': (delta, timeOfAnim) =>
@SetModifierWeight(1, .51)
@SetModifierWeight(2, .38)
@SetModifierWeight(3, .66)
}
{
'name': 'sorry'
'autostart': false
'repeat': false
'time': 8
'ids': {'Frown', 'Stretch', 'Grin', 'Scrunch', 'sad_eyes'}
'create': =>
@SetModifierWeight(1, math.random(45, 75) / 100)
@SetModifierWeight(2, math.random(45, 75) / 100)
@SetModifierWeight(3, math.random(70, 100) / 100)
@SetModifierWeight(4, math.random(7090, 100) / 100)
}
{
'name': 'scrunch'
'autostart': false
'repeat': false
'time': 6
'ids': {'Scrunch'}
'create': =>
@SetModifierWeight(1, math.random(80, 100) / 100)
}
{
'name': 'gulp'
'autostart': false
'repeat': false
'time': 2
'ids': {'Throat_Bulge', 'Frown', 'Grin'}
'create': =>
@SetModifierWeight(2, 1)
@SetModifierWeight(3, math.random(35, 55) / 100)
'func': (delta, timeOfAnim) =>
if timeOfAnim > 0.5
@SetModifierWeight(1, (1 - timeOfAnim) * 2)
else
@SetModifierWeight(1, timeOfAnim * 2)
}
{
'name': 'blahblah'
'autostart': false
'repeat': false
'time': 3
'ids': {'o3o', 'Mouth_O'}
'create': =>
@SetModifierWeight(1, 1)
@talkAnim = [math.random(50, 70) / 100 for i = 0, 1, 0.05]
'func': (delta, timeOfAnim) =>
cPos = math.floor(timeOfAnim * 20) + 1
data = @talkAnim[cPos]
return if not data
@SetModifierWeight(2, data)
}
{
'name': 'wink_left'
'autostart': false
'repeat': false
'time': 2
'ids': {'Frown', 'Stretch', 'Grin', 'Left_Blink'}
'create': =>
@SetModifierWeight(1, math.random(40, 60) / 100)
@SetModifierWeight(2, math.random(30, 50) / 100)
@SetModifierWeight(3, math.random(60, 100) / 100)
@SetModifierWeight(4, 1)
@PauseSequence('eyes_blink')
}
{
'name': 'wink_right'
'autostart': false
'repeat': false
'time': 2
'ids': {'Frown', 'Stretch', 'Grin', 'Right_Blink'}
'create': =>
@SetModifierWeight(1, math.random(40, 60) / 100)
@SetModifierWeight(2, math.random(30, 50) / 100)
@SetModifierWeight(3, math.random(60, 100) / 100)
@SetModifierWeight(4, 1)
@PauseSequence('eyes_blink')
}
{
'name': 'happy_eyes'
'autostart': false
'repeat': false
'time': 3
'ids': {'Happy_Eyes'}
'create': =>
@SetModifierWeight(1, 1)
@PauseSequence('eyes_blink')
}
{
'name': 'happy_grin'
'autostart': false
'repeat': false
'time': 3
'ids': {'Happy_Eyes', 'Grin'}
'create': =>
@SetModifierWeight(1, 1)
@SetModifierWeight(2, 1)
@PauseSequence('eyes_blink')
}
{
'name': 'duck'
'autostart': false
'repeat': false
'time': 3
'ids': {'Duck'}
'create': =>
@SetModifierWeight(1, math.random(70, 90) / 100)
}
{
'name': 'duck_insanity'
'autostart': false
'repeat': false
'time': 3
'ids': {'Duck'}
'func': (delta, timeOfAnim) =>
@SetModifierWeight(1, math.abs(math.sin(timeOfAnim * @GetTime() * 4)))
}
{
'name': 'duck_quack'
'autostart': false
'repeat': false
'time': 5
'ids': {'Duck', 'JawOpen'}
'create': =>
@talkAnim = for i = 0, 1, 0.1
rand = math.random(1, 100)
rand > 50 and 1 or 0
@SetModifierWeight(1, math.random(70, 90) / 100)
'func': (delta, timeOfAnim) =>
cPos = math.floor(timeOfAnim * 10) + 1
data = @talkAnim[cPos]
return if not data
@SetModifierWeight(2, data)
}
}
@SetupFlexesTables: =>
for i, flex in pairs @FLEX_LIST
flex.id = i - 1
flex.targetName = "target#{flex.flex}"
@FLEX_IDS = {flex.id, flex for _, flex in ipairs @FLEX_LIST}
@FLEX_TABLE = {flex.flex, flex for _, flex in ipairs @FLEX_LIST}
@SetupFlexesTables()
@NEXT_HOOK_ID = 0
@SequenceObject = FlexSequence
new: (data) =>
super(data)
@states = [FlexState(@, flex, id, scale, speed, active) for _, {:flex, :id, :scale, :speed, :active} in ipairs @@FLEX_LIST]
@statesTable = {state\GetFlexName(), state for _, state in ipairs @states}
@statesTable[state\GetFlexName()\lower()] = state for _, state in ipairs @states
@statesTable[state\GetFlexID()] = state for _, state in ipairs @states
@RebuildIterableList()
ponyData = data\GetData()
flex\SetUseLerp(ponyData\GetUseFlexLerp()) for _, flex in ipairs @states
flex\SetLerpModify(ponyData\GetFlexLerpMultiplier()) for _, flex in ipairs @states
@Hook('PlayerStartVoice', @PlayerStartVoice)
@Hook('PlayerEndVoice', @PlayerEndVoice)
@ResetSequences()
PPM2.DebugPrint('Created new flex controller for ', @GetEntity(), ' as part of ', data, '; internal ID is ', @fid)
IsValid: => @isValid
GetFlexState: (name = '') => @statesTable[name]
RebuildIterableList: =>
return false if not @isValid
@statesIterable = [state for _, state in ipairs @states when state\GetIsActive()]
DataChanges: (state) =>
return if not @isValid
flexState\DataChanges(state) for _, flexState in ipairs @states
if state\GetKey() == 'UseFlexLerp'
flex\SetUseLerp(state\GetValue()) for _, flex in ipairs @states
if state\GetKey() == 'FlexLerpMultiplier'
flex\SetLerpModify(state\GetValue()) for _, flex in ipairs @states
GetEntity: => @controller\GetEntity()
GetData: => @controller
GetController: => @controller
PlayerStartVoice: (ply = NULL) =>
return if ply ~= @GetEntity()
@StartSequence('talk_endless')
PlayerEndVoice: (ply = NULL) =>
return if ply ~= @GetEntity()
@EndSequence('talk_endless')
ResetSequences: =>
super()
state\Reset(false) for _, state in ipairs @statesIterable
Think: (ent = @GetEntity()) =>
return if DISABLE_FLEXES\GetBool()
delta = super(ent)
return if not delta
state\Think(ent, delta) for _, state in ipairs @statesIterable
return delta
do
ppm2_disable_flexes = (cvar, oldval, newval) ->
for _, ply in ipairs player.GetAll()
data = ply\GetPonyData()
continue if not data
renderer = data\GetRenderController()
continue if not renderer
flex = renderer\GetFlexController()
continue if not flex
flex\ResetSequences()
cvars.AddChangeCallback 'ppm2_disable_flexes', ppm2_disable_flexes, 'ppm2_disable_flexes'
PPM2.PonyFlexController = PonyFlexController
PPM2.GetFlexController = (model = 'models/ppm/player_default_base_new.mdl') -> PonyFlexController.AVALIABLE_CONTROLLERS[model]
| 29.390078 | 141 | 0.622778 |
cc8782787d43ae4525339d8743c6daeaa6036165 | 3,589 | -- Copyright 2014-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
ffi = require 'ffi'
bit = require 'bit'
import const_char_p, char_arr from howl.cdefs
import StyledText, ui, style, colors from howl.ui
band = bit.band
append = table.insert
backspace = 8
escape = 27
left_bracket = 91
set_graphics_op = 109
ansi_colors = {
'black',
'red',
'green',
'yellow',
'blue',
'magenta',
'cyan',
'white'
}
define_style = (name, state) ->
def = {
underline: state.underline
font: {
italic: state.italic
bold: state.bold
}
}
if state.fg
def.color = style[state.fg].color
if state.bg
def.background = style[state.bg].color
style.define name, def
style_from_state = (state) ->
name = { 'ansi' }
append name, 'bold' if state.bold
append name, 'italic' if state.italic
append name, 'underline' if state.underline
append name, state.fg if state.fg
if state.bg
append name, 'on'
append name, state.bg
name = table.concat name, '_'
define_style name, state unless style[name]
name
reset_style_state = (state) ->
with state
.italic = nil
.bold = nil
.underline = nil
.fg = nil
.bg = nil
style_state_has_any = (state) ->
state.italic or state.bold or state.underline or state.fg or state.bg
apply_graphics_value = (val, state) ->
n = tonumber val
return unless n
if n == 0
reset_style_state state
elseif n == 1
state.bold = true
elseif n == 3
state.italic = true
elseif n == 4
state.underline = true
elseif n == 22
state.bold = nil
elseif n >= 30 and n <= 37
state.fg = ansi_colors[n - 29]
elseif n == 39
state.fg = nil
elseif n >= 40 and n <= 47
state.bg = ansi_colors[n - 39]
elseif n == 49
state.bg = nil
mark_style = (from_pos, style_state, styles) ->
last = styles[#styles]
if type(last) == 'string'
styles[#styles + 1] = from_pos
if style_state_has_any style_state
styles[#styles + 1] = from_pos
append styles, style_from_state style_state
parse_sequence = (p, p_idx, style_state) ->
v = p[p_idx]
return p_idx, nil unless v == left_bracket
start_idx = p_idx
p_idx += 1
v = p[p_idx]
while v != 0 and (v < 64 or v > 126)
p_idx += 1
v = p[p_idx]
return p_idx + 1, nil if v != set_graphics_op -- unhandled, skip
vals = ffi.string p + start_idx + 1, p_idx - start_idx - 1
if #vals == 0
reset_style_state style_state
else
for v in vals\gmatch '[^;]+'
apply_graphics_value v, style_state
p_idx + 1, style_state
delete_styles_back_to = (to_idx, styles) ->
end_p = #styles
last = styles[end_p]
return if type(last) != 'number' or last < to_idx
last = to_idx
if styles[end_p - 2] >= last
for i = end_p - 2, end_p
styles[i] = nil
else
styles[end_p] = last
(text) ->
buf = char_arr(#text)
buf_idx = 0
p = const_char_p(text)
p_idx = 0
styles = {}
state = {}
while p_idx < #text
c = p[p_idx]
if c == escape
p_idx, new_style_state = parse_sequence p, p_idx + 1, state, styles
if new_style_state
state = new_style_state
mark_style buf_idx + 1, state, styles
elseif c == backspace and (buf_idx > 0)
buf_idx -= 1
while band(buf[buf_idx], 0xc0) == 0x80 -- back up continuation bytes
buf_idx -= 1
delete_styles_back_to buf_idx + 1, styles
p_idx += 1
else
buf[buf_idx] = c
buf_idx += 1
p_idx += 1
mark_style buf_idx + 1, {}, styles
StyledText ffi.string(buf, buf_idx), styles
| 21.620482 | 79 | 0.631095 |
8403700dfe29b162c0bee9828629e0b944186153 | 1,092 | util = require 'util'
json = util.json
simplehttp = util.simplehttp
urlEncode = (str, space) ->
space = space or '+'
str = str\gsub '([^%w ])', (c) ->
string.format "%%%02X", string.byte(c)
return str\gsub(' ', space)
PRIVMSG:
'^%pddg (.+)$': (source, destination, term) =>
term = urlEncode term
simplehttp "http://api.duckduckgo.com/?q=#{term}&format=json", (d) ->
data = json.decode d
out = {}
topic = data.RelatedTopics[1] if data.RelatedTopics and #data.RelatedTopics>0
if data.Heading == ''
return
table.insert out, "\002#{data.Heading}\002:"
table.insert out, data.AbstractText unless data.AbstractText == ''
table.insert out, data.Image unless data.Image == ''
table.insert out, data.AbstractURL unless data.AbstractURL == ''
table.insert out, data.Definition unless data.Definition == ''
table.insert out, data.DefinitionText unless data.DefinitionText == ''
if #out < 3
table.insert out, topic.FirstURL
table.insert out, topic.Text
say table.concat(out, ' ')
| 33.090909 | 83 | 0.621795 |
9255e9215d6b63ea22f85661d03cecbd4fb85ac1 | 396 | export class Color
new: (@red = 0, @green = 0, @blue = 0, @alpha = 255) =>
values: => @red, @green, @blue, @alpha
clone: => Color @red, @green, @blue, @alpha
-- Construct common colors, safe to mutate
@red: => Color 255
@green: => Color 0, 255
@blue: => Color 0, 0, 255
@white: => Color 255, 255, 255
@black: => Color!
__tostring: => "Color(#{@red}, #{@green}, #{@blue}, #{@alpha})" | 26.4 | 64 | 0.568182 |
41ceaae2b9fbfff62599c0459b2d69227afada5e | 2,064 | import Filter, Corpus from require 'moongrahams'
describe 'filter - calculate probabilities', ->
setup ->
export good = Corpus!
export bad = Corpus!
export filter = Filter!
teardown ->
good = nil
bad = nil
filter = nil
it '"good" has minimum probability with no bad data', ->
good\processTextLine 'good good good good good good good good good good good good good good'
filter\load good, bad
assert.are.same filter.minScore, filter.probabilities['good']
filter.minScore = 0
probability = filter\calculateTokenProbability 'good'
assert.are.same filter.minScore, probability
it 'returns a likely spam probability with all bad data', ->
bad\processTextLine 'bad bad bad bad bad bad bad bad'
filter\load good, bad
assert.are.same filter.likelySpamScore, filter.probabilities['bad']
it 'returns a certain spam probability with all bad data', ->
bad\processTextLine 'bad bad bad bad bad bad bad bad bad bad bad'
filter\load good, bad
assert.are.same filter.certainSpamScore, filter.probabilities['bad']
describe 'filter - analyze', ->
setup ->
export good = Corpus!
export bad = Corpus!
export filter = Filter!
teardown ->
good = nil
bad = nil
filter = nil
it 'scores negative for a post with negative sentiment', ->
bad\processTextLine 'bad bad bad bad bad bad'
filter\load good, bad
result = filter\analyze 'bad'
assert.is_true result.probability > 0.80
it 'scores positive for a post with positive sentiment', ->
good\processTextLine 'good good good good good'
filter\load good, bad
result = filter\analyze 'good'
assert.is_true result.probability < 0.20
it 'returns words in descending order of "interesting-ness"', ->
bad\processTextLine 'you are stupid and i hate you get out'
good\processTextLine 'you are awesome and i think you are cool'
filter.minScore = 0.11
filter.maxScore = 0.99
filter\load good, bad
result = filter\analyze 'you are the worst and i think you are stupid'
assert.are_not.equal string.find(result.words[1].word, 'stupid'), nil
| 25.8 | 94 | 0.722384 |
1d70dbdebfb9e7c6305171fb009550be32faee9b | 109 | padLeft = zb2rhhCftihvCnj8GKHxPGZ5XEVusXpAm1ppELSW3kwoUZRVG
length => bytes => (padLeft length "0x00" bytes)
| 36.333333 | 59 | 0.816514 |
38af0c9385b2e52e9169ecb1e68cf4b876c57bff | 615 | Static = (path, ...) ->
args = {...}
(p) ->
if string.sub(p.request.url_path, 1, string.len(path)) == path
-- TODO if the filename is a directory, the behavior is currently undefined
filename = '.' .. p.request.url_path
f = io.open filename, 'r'
if f == nil
p.response\status 404
return
pcall ->
mimetypes = require 'mimetypes'
p.response\set_options {'Content-Type': mimetypes.guess filename}
args[1].log\write string.format '%s - [Static] Serving %s\n', os.date('%F %T', p.utils.now!), filename if #args and args[1].log
p.response\write f\read '*a'
false
{:Static}
| 27.954545 | 130 | 0.629268 |
9f4cc489d0abfa30e7edfd62ccc7c465897cc735 | 5,606 |
ffi = require "ffi"
local lib
ffi.cdef [[
typedef void MagickWand;
typedef void PixelWand;
typedef int MagickBooleanType;
typedef int ExceptionType;
typedef int ssize_t;
typedef int CompositeOperator;
typedef int GravityType;
typedef int OrientationType;
typedef int InterlaceType;
void MagickWandGenesis();
MagickWand* NewMagickWand();
MagickWand* CloneMagickWand(const MagickWand *wand);
MagickWand* DestroyMagickWand(MagickWand*);
MagickBooleanType MagickReadImage(MagickWand*, const char*);
MagickBooleanType MagickReadImageBlob(MagickWand*, const void*, const size_t);
char* MagickGetException(const MagickWand*, ExceptionType*);
int MagickGetImageWidth(MagickWand*);
int MagickGetImageHeight(MagickWand*);
MagickBooleanType MagickAddImage(MagickWand*, const MagickWand*);
MagickBooleanType MagickAdaptiveResizeImage(MagickWand*, const size_t, const size_t);
MagickBooleanType MagickWriteImage(MagickWand*, const char*);
unsigned char* MagickGetImageBlob(MagickWand*, size_t*);
void* MagickRelinquishMemory(void*);
MagickBooleanType MagickCropImage(MagickWand*,
const size_t, const size_t, const ssize_t, const ssize_t);
MagickBooleanType MagickBlurImage(MagickWand*, const double, const double);
MagickBooleanType MagickModulateImage(MagickWand*, const double, const double, const double);
MagickBooleanType MagickBrightnessContrastImage(MagickWand*, const double, const double);
MagickBooleanType MagickSetImageFormat(MagickWand* wand, const char* format);
char* MagickGetImageFormat(MagickWand* wand);
size_t MagickGetImageCompressionQuality(MagickWand * wand);
MagickBooleanType MagickSetImageCompressionQuality(MagickWand *wand,
const size_t quality);
MagickBooleanType MagickSharpenImage(MagickWand *wand,
const double radius,const double sigma);
MagickBooleanType MagickScaleImage(MagickWand *wand,
const size_t columns,const size_t rows);
MagickBooleanType MagickRotateImage(MagickWand *wand,
const PixelWand *background,const double degrees);
MagickBooleanType MagickSetOption(MagickWand *,const char *,const char *);
char* MagickGetOption(MagickWand *,const char *);
MagickBooleanType MagickCompositeImage(MagickWand *wand,
const MagickWand *source_wand,const CompositeOperator compose,
const ssize_t x,const ssize_t y);
GravityType MagickGetImageGravity(MagickWand *wand);
MagickBooleanType MagickSetImageGravity(MagickWand *wand,
const GravityType gravity);
MagickBooleanType MagickStripImage(MagickWand *wand);
MagickBooleanType MagickGetImagePixelColor(MagickWand *wand,
const ssize_t x,const ssize_t y,PixelWand *color);
MagickWand* MagickCoalesceImages(MagickWand*);
PixelWand *NewPixelWand(void);
PixelWand *DestroyPixelWand(PixelWand *);
double PixelGetAlpha(const PixelWand *);
double PixelGetRed(const PixelWand *);
double PixelGetGreen(const PixelWand *);
double PixelGetBlue(const PixelWand *);
void PixelSetAlpha(PixelWand *wand, const double alpha);
void PixelSetRed(PixelWand *wand, const double red);
void PixelSetGreen(PixelWand *wand, const double green);
void PixelSetBlue(PixelWand *wand, const double blue);
MagickBooleanType MagickTransposeImage(MagickWand *wand);
MagickBooleanType MagickTransverseImage(MagickWand *wand);
MagickBooleanType MagickFlipImage(MagickWand *wand);
MagickBooleanType MagickFlopImage(MagickWand *wand);
char* MagickGetImageProperty(MagickWand *wand, const char *property);
MagickBooleanType MagickSetImageProperty(MagickWand *wand,
const char *property,const char *value);
OrientationType MagickGetImageOrientation(MagickWand *wand);
MagickBooleanType MagickSetImageOrientation(MagickWand *wand,
const OrientationType orientation);
InterlaceType MagickGetImageInterlaceScheme(MagickWand *wand);
MagickBooleanType MagickSetImageInterlaceScheme(MagickWand *wand,
const InterlaceType interlace_scheme);
MagickBooleanType MagickAutoOrientImage(MagickWand *wand);
MagickBooleanType MagickResetImagePage(MagickWand *wand, const char *page);
MagickBooleanType MagickSetImageDepth(MagickWand *,const unsigned long);
unsigned long MagickGetImageDepth(MagickWand *);
]]
get_flags = ->
proc = io.popen "pkg-config --cflags --libs MagickWand", "r"
flags = proc\read "*a"
get_flags = -> flags
proc\close!
flags
get_filters = ->
fname = "magick/resample.h"
prefixes = {
"/usr/include/ImageMagick"
"/usr/local/include/ImageMagick"
unpack [p for p in get_flags!\gmatch "-I([^%s]+)"]
}
for p in *prefixes
full = "#{p}/#{fname}"
if f = io.open full
content = with f\read "*a" do f\close!
filter_types = content\match "(typedef enum.-FilterTypes;)"
if filter_types
ffi.cdef filter_types
return true
false
get_filter = (name) ->
lib[name .. "Filter"]
can_resize = if get_filters!
ffi.cdef [[
MagickBooleanType MagickResizeImage(MagickWand*,
const size_t, const size_t,
const FilterTypes, const double);
]]
true
try_to_load = (...) ->
local out
for name in *{...}
if "function" == type name
name = name!
continue unless name
return out if pcall ->
out = ffi.load name
error "Failed to load ImageMagick (#{...})"
lib = try_to_load "MagickWand", ->
lname = get_flags!\match "-l(MagickWand[^%s]*)"
local suffix
if ffi.os == "OSX"
suffix = ".dylib"
elseif ffi.os == "Windows"
suffix = ".dll"
else
suffix = ".so"
lname and "lib" .. lname .. suffix
{ :lib, :can_resize, :get_filter }
| 30.139785 | 95 | 0.750981 |
0deca024c6c20a1e119554732722181131d3675b | 1,570 | -- Copyright 2016-2018 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
{:activities, :Buffer, :config, :mode, :sys} = howl
{:Process} = howl.io
bundle_load 'go_completer'
{:fmt} = bundle_load 'go_fmt'
{
auto_pairs: {
'(': ')'
'[': ']'
'{': '}'
'"': '"'
"'": "'"
"`": "`"
}
comment_syntax: '//'
completers: { 'in_buffer', 'go_completer' }
default_config:
use_tabs: true
tab_width: 4
indent: 4
inspectors_on_save: { 'golint', 'gotoolvet' }
lexer: bundle_load('go_lexer')
structure: (editor) =>
[l for l in *editor.buffer.lines when l\match('^%s*func%s') or l\match('^%s*struct%s') or l\match('^%s*type%s')]
before_save: (buffer) =>
if config.go_fmt_on_save
fmt buffer
show_doc: (editor) =>
cmd_path = config.gogetdoc_path
unless sys.find_executable cmd_path
log.warning "Command '#{cmd_path}' not found, please install for docs"
return
buffer = editor.buffer
cmd_str = string.format "#{cmd_path} -pos %s:#%d -modified -linelength 999",
buffer.file,
buffer\byte_offset(editor.cursor.pos) - 2
success, pco = pcall Process.open_pipe, cmd_str, {
stdin: string.format("%s\n%d\n%s", buffer.file, buffer.size, buffer.text)
}
unless success
log.error "Failed looking up docs: #{pco}"
return
stdout, _ = activities.run_process {title: 'running gogetdoc'}, pco
unless stdout.is_empty
buf = Buffer mode.by_name 'default'
buf.text = stdout
return buf
}
| 25.737705 | 116 | 0.622293 |
245245e33b2f33f2a3dd0b5aeffc382bfc9ebf8b | 8,664 | {:cimport, :internalize, :eq, :neq, :ffi, :lib, :cstr, :to_cstr} = require 'test.unit.helpers'
garray = cimport './src/nvim/garray.h'
-- handy constants
NULL = ffi.cast 'void*', 0
-- define a basic interface to garray. We could make it a lot nicer by
-- constructing a moonscript class wrapper around garray. It could for
-- example associate ga_clear_strings to the underlying garray cdata if the
-- garray is a string array. But for now I estimate that that kind of magic
-- might make testing less "transparant" (i.e.: the interface would become
-- quite different as to how one would use it from C.
-- accessors
ga_len = (garr) ->
garr[0].ga_len
ga_maxlen = (garr) ->
garr[0].ga_maxlen
ga_itemsize = (garr) ->
garr[0].ga_itemsize
ga_growsize = (garr) ->
garr[0].ga_growsize
ga_data = (garr) ->
garr[0].ga_data
-- derived accessors
ga_size = (garr) ->
ga_len(garr) * ga_itemsize(garr)
ga_maxsize = (garr) ->
ga_maxlen(garr) * ga_itemsize(garr)
ga_data_as_bytes = (garr) ->
ffi.cast('uint8_t *', ga_data(garr))
ga_data_as_strings = (garr) ->
ffi.cast('char **', ga_data(garr))
ga_data_as_ints = (garr) ->
ffi.cast('int *', ga_data(garr))
-- garray manipulation
ga_init = (garr, itemsize, growsize) ->
garray.ga_init(garr, itemsize, growsize)
ga_clear = (garr) ->
garray.ga_clear(garr)
ga_clear_strings = (garr) ->
assert.is_true(ga_itemsize(garr) == ffi.sizeof('char *'))
garray.ga_clear_strings(garr)
ga_grow = (garr, n) ->
garray.ga_grow(garr, n)
ga_concat = (garr, str) ->
garray.ga_concat(garr, to_cstr(str))
ga_append = (garr, b) ->
if type(b) == 'string'
garray.ga_append(garr, string.byte(b))
else
garray.ga_append(garr, b)
ga_concat_strings = (garr) ->
internalize(garray.ga_concat_strings(garr))
ga_concat_strings_sep = (garr, sep) ->
internalize(garray.ga_concat_strings_sep(garr, to_cstr(sep)))
ga_remove_duplicate_strings = (garr) ->
garray.ga_remove_duplicate_strings(garr)
-- derived manipulators
ga_set_len = (garr, len) ->
assert.is_true(len <= ga_maxlen(garr))
garr[0].ga_len = len
ga_inc_len = (garr, by) ->
ga_set_len(garr, ga_len(garr) + 1)
-- custom append functions
-- not the C ga_append, which only works for bytes
ga_append_int = (garr, it) ->
assert.is_true(ga_itemsize(garr) == ffi.sizeof('int'))
ga_grow(garr, 1)
data = ga_data_as_ints(garr)
data[ga_len(garr)] = it
ga_inc_len(garr, 1)
ga_append_string = (garr, it) ->
assert.is_true(ga_itemsize(garr) == ffi.sizeof('char *'))
-- make a non-garbage collected string and copy the lua string into it,
-- TODO(aktau): we should probably call xmalloc here, though as long as
-- xmalloc is based on malloc it should work.
mem = ffi.C.malloc(string.len(it) + 1)
ffi.copy(mem, it)
ga_grow(garr, 1)
data = ga_data_as_strings(garr)
data[ga_len(garr)] = mem
ga_inc_len(garr, 1)
ga_append_strings = (garr, ...) ->
prevlen = ga_len(garr)
len = select('#', ...)
for i = 1, len
ga_append_string(garr, select(i, ...))
eq prevlen + len, ga_len(garr)
ga_append_ints = (garr, ...) ->
prevlen = ga_len(garr)
len = select('#', ...)
for i = 1, len
ga_append_int(garr, select(i, ...))
eq prevlen + len, ga_len(garr)
-- enhanced constructors
garray_ctype = ffi.typeof('garray_T[1]')
new_garray = ->
garr = garray_ctype()
ffi.gc(garr, ga_clear)
new_string_garray = ->
garr = garray_ctype()
ga_init(garr, ffi.sizeof("char_u *"), 1)
ffi.gc(garr, ga_clear_strings)
randomByte = ->
ffi.cast('uint8_t', math.random(0, 255))
-- scramble the data in a garray
ga_scramble = (garr) ->
size, bytes = ga_size(garr), ga_data_as_bytes(garr)
for i = 0, size - 1
bytes[i] = randomByte()
describe 'garray', ->
itemsize = 14
growsize = 95
describe 'ga_init', ->
it 'initializes the values of the garray', ->
garr = new_garray()
ga_init(garr, itemsize, growsize)
eq 0, ga_len(garr)
eq 0, ga_maxlen(garr)
eq growsize, ga_growsize(garr)
eq itemsize, ga_itemsize(garr)
eq NULL, ga_data(garr)
describe 'ga_grow', ->
new_and_grow = (itemsize, growsize, req) ->
garr = new_garray()
ga_init(garr, itemsize, growsize)
eq 0, ga_size(garr) -- should be 0 at first
eq NULL, ga_data(garr) -- should be NULL
ga_grow(garr, req) -- add space for `req` items
garr
it 'grows by growsize items if num < growsize', ->
itemsize = 16
growsize = 4
grow_by = growsize - 1
garr = new_and_grow(itemsize, growsize, grow_by)
neq NULL, ga_data(garr) -- data should be a ptr to memory
eq growsize, ga_maxlen(garr) -- we requested LESS than growsize, so...
it 'grows by num items if num > growsize', ->
itemsize = 16
growsize = 4
grow_by = growsize + 1
garr = new_and_grow(itemsize, growsize, grow_by)
neq NULL, ga_data(garr) -- data should be a ptr to memory
eq grow_by, ga_maxlen(garr) -- we requested MORE than growsize, so...
it 'does not grow when nothing is requested', ->
garr = new_and_grow(16, 4, 0)
eq NULL, ga_data(garr)
eq 0, ga_maxlen(garr)
describe 'ga_clear', ->
it 'clears an already allocated array', ->
-- allocate and scramble an array
garr = garray_ctype()
ga_init(garr, itemsize, growsize)
ga_grow(garr, 4)
ga_set_len(garr, 4)
ga_scramble(garr)
-- clear it and check
ga_clear(garr)
eq NULL, ga_data(garr)
eq 0, ga_maxlen(garr)
eq 0, ga_len(garr)
describe 'ga_append', ->
it 'can append bytes', ->
-- this is the actual ga_append, the others are just emulated lua
-- versions
garr = new_garray()
ga_init(garr, ffi.sizeof("uint8_t"), 1)
ga_append(garr, 'h')
ga_append(garr, 'e')
ga_append(garr, 'l')
ga_append(garr, 'l')
ga_append(garr, 'o')
ga_append(garr, 0)
bytes = ga_data_as_bytes(garr)
eq 'hello', ffi.string(bytes)
it 'can append integers', ->
garr = new_garray()
ga_init(garr, ffi.sizeof("int"), 1)
input = {-20, 94, 867615, 90927, 86}
ga_append_ints(garr, unpack(input))
ints = ga_data_as_ints(garr)
for i = 0, #input - 1
eq input[i+1], ints[i]
it 'can append strings to a growing array of strings', ->
garr = new_string_garray()
input = {"some", "str", "\r\n\r●●●●●●,,,", "hmm", "got it"}
ga_append_strings(garr, unpack(input))
-- check that we can get the same strings out of the array
strings = ga_data_as_strings(garr)
for i = 0, #input - 1
eq input[i+1], ffi.string(strings[i])
describe 'ga_concat', ->
it 'concatenates the parameter to the growing byte array', ->
garr = new_garray()
ga_init(garr, ffi.sizeof("char"), 1)
str = "ohwell●●"
loop = 5
for i = 1, loop
ga_concat(garr, str)
-- ga_concat does NOT append the NUL in the src string to the
-- destination, you have to do that manually by calling something like
-- ga_append(gar, '\0'). I'ts always used like that in the vim
-- codebase. I feel that this is a bit of an unnecesesary
-- micro-optimization.
ga_append(garr, 0)
result = ffi.string(ga_data_as_bytes(garr))
eq string.rep(str, loop), result
test_concat_fn = (input, fn, sep) ->
garr = new_string_garray()
ga_append_strings(garr, unpack(input))
if sep == nil
eq table.concat(input, ','), fn(garr)
else
eq table.concat(input, sep), fn(garr, sep)
describe 'ga_concat_strings', ->
it 'returns an empty string when concatenating an empty array', ->
test_concat_fn({}, ga_concat_strings)
it 'can concatenate a non-empty array', ->
test_concat_fn({'oh', 'my', 'neovim'}, ga_concat_strings)
describe 'ga_concat_strings_sep', ->
it 'returns an empty string when concatenating an empty array', ->
test_concat_fn({}, ga_concat_strings_sep, '---')
it 'can concatenate a non-empty array', ->
sep = '-●●-'
test_concat_fn({'oh', 'my', 'neovim'}, ga_concat_strings_sep, sep)
describe 'ga_remove_duplicate_strings', ->
it 'sorts and removes duplicate strings', ->
garr = new_string_garray()
input = {'ccc', 'aaa', 'bbb', 'ddd●●', 'aaa', 'bbb', 'ccc', 'ccc', 'ddd●●'}
sorted_dedup_input = {'aaa', 'bbb', 'ccc', 'ddd●●'}
ga_append_strings(garr, unpack(input))
ga_remove_duplicate_strings(garr)
eq #sorted_dedup_input, ga_len(garr)
strings = ga_data_as_strings(garr)
for i = 0, #sorted_dedup_input - 1
eq sorted_dedup_input[i+1], ffi.string(strings[i])
| 31.505455 | 94 | 0.640466 |
896da7778ff8c3a74c7c652a6f344e8fab4acb65 | 3,190 |
import Router from require "lapis.router"
describe "basic route matching", ->
local r
handler = (...) -> { ... }
before_each ->
r = Router!
r\add_route "/hello", handler
r\add_route "/hello/:name", handler
r\add_route "/hello/:name/world", handler
r\add_route "/static/*", handler
r\add_route "/x/:color/:height/*", handler
r.default_route = -> "failed to find route"
it "should match static route", ->
out = r\resolve "/hello"
assert.same { {}, "/hello" }, out
it "should match param route", ->
out = r\resolve "/hello/world2323"
assert.same {
{ name: "world2323" },
"/hello/:name"
}, out
it "should match param route", ->
out = r\resolve "/hello/the-parameter/world"
assert.same {
{ name: "the-parameter" },
"/hello/:name/world"
}, out
it "should match splat", ->
out = r\resolve "/static/hello/world/343434/foo%20bar.png"
assert.same {
{ splat: 'hello/world/343434/foo%20bar.png' }
"/static/*"
}, out
it "should match all", ->
out = r\resolve "/x/greenthing/123px/ahhhhwwwhwhh.txt"
assert.same {
{
splat: 'ahhhhwwwhwhh.txt'
height: '123px'
color: 'greenthing'
}
"/x/:color/:height/*"
}, out
it "should match nothing", ->
assert.same "failed to find route", r\resolve("/what-the-heck")
it "should match nothing", ->
assert.same "failed to find route", r\resolve("/hello//world")
it "should match the catchall", ->
r = Router!
r\add_route "*", handler
assert.same {
{ splat: "hello_world" }
"*"
}, r\resolve "hello_world"
describe "named routes", ->
local r
handler = (...) -> { ... }
before_each ->
r = Router!
r\add_route { homepage: "/home" }, handler
r\add_route { profile: "/profile/:name" }, handler
r\add_route { profile_settings: "/profile/:name/settings" }, handler
r\add_route { game: "/game/:user_slug/:game_slug" }, handler
r\add_route { splatted: "/page/:slug/*" }, handler
r.default_route = -> "failed to find route"
it "should match", ->
out = r\resolve "/home"
assert.same {
{}, "/home", "homepage"
}, out
it "should generate correct url", ->
url = r\url_for "homepage"
assert.same "/home", url
it "should generate correct url", ->
url = r\url_for "profile", name: "adam"
assert.same "/profile/adam", url
it "should generate correct url", ->
url = r\url_for "game", user_slug: "leafo", game_slug: "x-moon"
assert.same "/game/leafo/x-moon", url
-- TODO: this is incorrect
it "should generate correct url", ->
url = r\url_for "splatted", slug: "cool", splat: "hello"
assert.same "/page/cool/*", url
it "should create param from object", ->
user = {
url_key: (route_name, param_name) =>
assert.same "profile_settings", route_name
assert.same "name", param_name
"adam"
}
url = r\url_for "profile_settings", name: user
assert.same "/profile/adam/settings", url
it "should not build url", ->
assert.has_error (-> r\url_for "fake_url", name: user),
"Missing route named fake_url"
| 26.583333 | 72 | 0.594357 |
d8c03153528000b916d1df3fabe3bd936435617b | 637 | with {}
.modulo_lua = (x, y) ->
-- can be used to loop through lua array, which are 1-indexed
-- e.g.
-- 1 2 3 4 5 6 7 8 9 - x
-- 1 2 0 1 2 0 1 2 0 - x % 3
-- 1 2 3 1 2 3 1 2 3 - modulo_lua(x, 3)
((x - 1) % y) + 1
.str_split = (str, pattern) ->
matches = {}
index = 1
while index <= str\len()
char = str\sub(index, index)
if char == pattern
table.insert matches, str\sub(1, index - 1)
str = str\sub(index + 1, -1)
index = 1
index += 1
table.insert matches, str
| 30.333333 | 69 | 0.425432 |
a04ac0e2915c857e4d1b7e9212837aa5e809d127 | 223 | import Widget from require "lapis.html"
class Index extends Widget
content: =>
h1 class: "header", "Hello"
div class: "body", ->
text "Welcome to my site!"
if @name
h2 "I think you are #{@name}"
| 20.272727 | 39 | 0.605381 |
e0f2f6cbb29cdbca6227c129966ce50ec7a19898 | 486 | export modinfo = {
type: "command"
desc: "UnSparkles"
alias: {"unsparkles", "nosparkles", "unsp", "nosp"}
func: getDoPlayersFunction (v) ->
if v.Character
if v.Character\FindFirstChild("Torso")
if v.Character.Torso\IsA"Part"
for i,f in pairs(v.Character.Torso\GetChildren())
if f\IsA"Sparkles"
f.Parent = nil
Output2(string.format("Removed sparkles from %s",v.Name),{Colors.Green})
loggit(string.format("Removed sparkles from %s",v.Name))
} | 34.714286 | 79 | 0.664609 |
6e075f2d2658462542eaab3a8e46ec51e533a372 | 2,906 | require "tests/init"
describe "Test Language", (using nil) ->
lang = ulx.Lang -- Save typing
red = {r:255, g:000, b:000}
green = {r:000, g:255, b:000}
blue = {r:000, g:000, b:255}
white = {r:255, g:255, b:255}
black = {r:000, g:000, b:000}
it "tests GetPhrase", (using nil) ->
slap = lang.GetPhrase "SLAP"
assert.string slap
return
it "tests GetMutatedPhrase", (using nil) ->
slap = lang.GetMutatedPhrase "SLAP",
INITIATOR: "AdminX"
TARGETS: {"Alice", "Bob"}
DAMAGE: 3
assert.equals "AdminX slapped Alice and Bob for 3 damage", slap
slap = lang.GetMutatedPhrase "SLAP",
INITIATOR: "AdminX"
TARGETS: {"Alice", "Bob", "Candy"}
DAMAGE: 0
assert.equals "AdminX slapped Alice, Bob and Candy", slap
slap = lang.GetMutatedPhrase "SLAP",
INITIATOR: "AdminX"
TARGETS: {"Doug"}
DAMAGE: nil
assert.equals "AdminX slapped Doug", slap
slap = lang.GetMutatedPhrase "SLAP_ANON",
INITIATOR: "AdminX"
TARGETS: {"Alice", "Bob"}
DAMAGE: 3
assert.equals "Alice and Bob were slapped for 3 damage", slap
slap = lang.GetMutatedPhrase "SLAP_ANON",
INITIATOR: "AdminX"
TARGETS: {"Alice", "Bob", "Candy"}
DAMAGE: 0
assert.equals "Alice, Bob and Candy were slapped", slap
slap = lang.GetMutatedPhrase "SLAP_ANON",
INITIATOR: "AdminX"
TARGETS: {"Doug"}
DAMAGE: nil
assert.equals "Doug was slapped", slap
return
it "tests GetColoredMutatedPhrase", (using nil) ->
slap = lang.GetColoredMutatedPhrase "SLAP",
INITIATOR: "AdminX"
TARGETS: {"Alice", "Bob"}
DAMAGE: 3
COLOR_DEFAULT: nil
expect = {"AdminX slapped Alice and Bob for 3 damage"}
assert.same expect, slap
slap = lang.GetColoredMutatedPhrase "SLAP",
INITIATOR: "AdminX"
TARGETS: {"Alice", "Bob"}
DAMAGE: 3
COLOR_DEFAULT: white
expect = {
white
"AdminX slapped Alice and Bob for 3 damage"
}
assert.same expect, slap
slap = lang.GetColoredMutatedPhrase "SLAP",
INITIATOR: "AdminX"
TARGETS: {"Alice", "Bob"}
DAMAGE: 3
COLOR_DEFAULT: white
COLOR_DEFAULT_REPLACED: red
expect = {
red
"AdminX"
white
" slapped "
red
"Alice and Bob for 3 damage"
}
assert.same expect, slap
slap = lang.GetColoredMutatedPhrase "SLAP",
INITIATOR: "AdminX"
TARGETS: {"Alice", "Bob"}
DAMAGE: 3
COLOR_DEFAULT: white
COLOR_DEFAULT_REPLACED: red
COLOR_INITIATOR: green
expect = {
green
"AdminX"
white
" slapped "
red
"Alice and Bob for 3 damage"
}
assert.same expect, slap
slap = lang.GetColoredMutatedPhrase "SLAP",
INITIATOR: "AdminX"
TARGETS: {"Alice", "Bob"}
DAMAGE: 3
COLOR_DEFAULT: white
COLOR_DEFAULT_REPLACED: red
COLOR_INITIATOR: green
COLOR_TARGETS: blue
COLOR_DAMAGE: black
expect = {
green
"AdminX"
white
" slapped "
blue
"Alice and Bob "
black
"for 3 damage"
}
assert.same expect, slap
return
return
| 22.353846 | 65 | 0.655884 |
df4d27f75577e6298099986ef07556c49abda682 | 808 | local *
ffi = assert require "ffi"
ffi.cdef [[
typedef int pid_t;
pid_t fork();
]]
libc = ffi.load "libc"
--------------------------------------------------------------------------------
Server = assert require "lrpc.server"
server = Server!
--------------------------------------------------------------------------------
server.callbacks.sum = (...) ->
s = 0
c = #{...}
for _, param in ipairs {...}
coroutine.yield!
s += param
s, c
server.callbacks.fact = (n) ->
f = 1
while n > 0
coroutine.yield!
f *= n
n -= 1
f
--------------------------------------------------------------------------------
pid = libc.fork!
if pid == 0
server\serve!
else
fp = io.open "server.pid", "w"
fp\write pid
fp\close!
| 15.843137 | 80 | 0.35396 |
c28eda6aa784f85863574cb2e3dc079d5f6f7260 | 842 | util = require "mooncrafts.util"
aws_region = os.getenv("AWS_DEFAULT_REGION")
aws_access_key_id = os.getenv("AWS_S3_KEY_ID")
aws_secret_access_key = os.getenv("AWS_S3_ACCESS_KEY")
aws_s3_path = os.getenv("AWS_S3_PATH") -- 'bucket-name/basepath'
base_host = os.getenv("BASE_HOST")
remote_path = os.getenv("REMOTE_PATH")
import string_split, table_clone, string_connection_parse from util
import insert from table
import upper from string
class Config
new: (newOpts={}) =>
defaultOpts = {
:remote_path
:base_host
aws: { :aws_region, :aws_access_key_id, :aws_secret_access_key, :aws_s3_path }
}
util.applyDefaults(newOpts, defaultOpts)
@__data = newOpts
get: () => table_clone(@__data, true) -- preserving config through cloning
Config
| 29.034483 | 84 | 0.680523 |
18946e2eb8f8c59bcd08b11b9cb63f716004cfc0 | 741 | with love.graphics
export gym_mansion = .newImage "res/gymmansion.png"
export productions = .newImage "res/productions.png"
export clapping = love.audio.newSource "res/sound/clapping.wav", "static"
clapping\setVolume 1.2
clapping\play!
menu =
timer: 3
loaded: false
menu.update = (dt) =>
@timer = math.max 0, @timer - dt
menu.draw = =>
with love.graphics
.setColor 1, 1, 1
.setBackgroundColor 3 - @timer, 3 - @timer, 3 - @timer
.draw gym_mansion, .getWidth! / 2 - gym_mansion\getWidth! / 2, .getHeight! / 2 - gym_mansion\getHeight! / 2 - productions\getHeight! / 2
.draw productions, .getWidth! / 2 - productions\getWidth! / 2, .getHeight! / 2 - productions\getHeight! / 2 + productions\getHeight! / 2
menu
| 29.64 | 140 | 0.684211 |
b60413780cf8f1d5bf472a235786d8291c8ca055 | 570 |
class Hello
new: (@test, @world) =>
print "creating object.."
hello: =>
print @test, @world
__tostring: => "hello world"
x = Hello 1,2
x\hello()
print x
class Simple
cool: => print "cool"
class Yikes extends Simple
new: => print "created hello"
x = Yikes()
x\cool()
class Hi
new: (arg) =>
print "init arg", arg
cool: (num) =>
print "num", num
class Simple extends Hi
new: => super "man"
cool: => super 120302
x = Simple()
x\cool()
print x.__class == Simple
class Okay
-- what is going on
something: 20323
-- yeaha
| 12.12766 | 31 | 0.6 |
427be984ba922ad04e84b45503b88a51701d316a | 22,397 | -- Copyright 2012-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
import app, activities, breadcrumbs, Buffer, command, config, bindings, bundle, interact, signal, mode, Project from howl
import ActionBuffer, JournalBuffer, ProcessBuffer, BufferPopup, StyledText from howl.ui
import Process from howl.io
serpent = require 'serpent'
get_project_root = ->
buffer = app.editor and app.editor.buffer
file = buffer.file or buffer.directory
error "No file associated with the current view" unless file
project = Project.get_for_file file
error "No project associated with #{file}" unless project
return project.root
belongs_to_project = (buffer, project_root) ->
file = buffer.file or buffer.directory
return false unless file
project = Project.for_file file
return false unless project
return project.root == project_root
get_buffer_dir = (buffer) ->
return unless buffer
buffer.file and buffer.file.parent or buffer.directory
command.register
name: 'quit',
description: 'Quit the application'
handler: -> howl.app\quit!
command.alias 'quit', 'q'
command.register
name: 'save-and-quit',
description: 'Save modified buffers and quit the application'
handler: ->
with howl.app
\quit! if \save_all!
command.alias 'save-and-quit', 'wq'
command.register
name: 'quit-without-save',
description: 'Quit the application, disregarding any modified buffers'
handler: -> howl.app\quit true
command.alias 'quit-without-save', 'q!'
command.register
name: 'run'
description: 'Run a command'
handler: command.run
command.register
name: 'new-buffer',
description: 'Opens a new buffer'
handler: ->
breadcrumbs.drop!
app.editor.buffer = howl.app\new_buffer!
command.register
name: 'switch-buffer',
description: 'Switch to another buffer'
input: (opts) ->
interact.select_buffer
prompt: opts.prompt
text: opts.text
help: opts.help
handler: (buf) ->
breadcrumbs.drop!
app.editor.buffer = buf
command.register
name: 'project-switch-buffer',
description: 'Switch to another buffer in current project'
input: (opts) ->
project_root = get_project_root!
return unless project_root
interact.select_buffer
get_buffers: -> [buf for buf in *app.buffers when belongs_to_project buf, project_root]
title: "Buffers under #{project_root}"
prompt: opts.prompt
text: opts.text
help: opts.help
handler: (buf) ->
breadcrumbs.drop!
app.editor.buffer = buf
command.register
name: 'buffer-reload',
description: 'Reload the current buffer from file'
handler: ->
buffer = app.editor.buffer
if buffer.modified
unless interact.yes_or_no prompt: 'Buffer is modified, reload anyway? '
log.info "Not reloading; buffer is untouched"
return
buffer\reload true
log.info "Buffer reloaded from file"
command.register
name: 'switch-to-last-hidden-buffer',
description: 'Switch to the last active hidden buffer'
handler: ->
for buffer in *howl.app.buffers
if not buffer.showing
breadcrumbs.drop!
app.editor.buffer = buffer
return
_G.log.error 'No hidden buffer found'
command.register
name: 'set',
description: 'Set a configuration variable'
input: (opts) ->
interact.get_variable_assignment
prompt: opts.prompt
text: opts.text
help: opts.help
handler: (result) -> result.config_value\commit!
get_input_text: (result) -> result.text
command.register
name: 'describe-key',
description: 'Show information for a key'
handler: ->
buffer = ActionBuffer!
buffer.title = 'Key watcher'
buffer\append 'Press any key to show information for it (press escape to quit)..\n\n', 'string'
editor = howl.app\add_buffer buffer
editor.cursor\eof!
bindings.capture (event, source, translations) ->
buffer.lines\delete 3, #buffer.lines
buffer\append 'Key translations (usable from bindings):\n', 'comment'
buffer\append serpent.block translations, comment: false
buffer\append '\n\nKey event:\n', 'comment'
buffer\append serpent.block event, comment: false
bound_commands = {}
for t in *translations
cmd = bindings.action_for t
cmd = '<function>' if typeof(cmd) == 'function'
bound_commands[t] = cmd
buffer\append '\n\nBound command:\n', 'comment'
buffer\append serpent.block bound_commands, comment: false
if event.key_name == 'escape'
buffer.lines[1] = '(Snooping done, close this buffer at your leisure)'
buffer\style 1, #buffer, 'comment'
buffer.modified = false
else
return false
command.register
name: 'describe-signal',
description: 'Describe a given signal'
input: interact.select_signal
handler: (signal_name) ->
def = signal.all[signal_name]
error "Unknown signal '#{signal_name}'" unless def
buffer = with ActionBuffer!
.title = "Signal: #{signal_name}"
\append "#{def.description}\n\n"
\append "Parameters:"
params = def.parameters
if not params
buffer\append "None"
else
buffer\append '\n\n'
buffer\append StyledText.for_table [ { name, desc } for name, desc in pairs params ], {
{ header: 'Name', style: 'string'},
{ header: 'Description', style: 'comment' }
}
buffer.read_only = true
buffer.modified = false
howl.app\add_buffer buffer
command.register
name: 'bundle-unload'
description: 'Unload a specified bundle'
input: interact.select_loaded_bundle
handler: (name) ->
log.info "Unloading bundle '#{name}'.."
bundle.unload name
log.info "Unloaded bundle '#{name}'"
command.register
name: 'bundle-load'
description: 'Load a specified, currently unloaded, bundle'
input: interact.select_unloaded_bundle
handler: (name) ->
log.info "Loading bundle '#{name}'.."
bundle.load_by_name name
log.info "Loaded bundle '#{name}'"
command.register
name: 'bundle-reload'
description: 'Reload a specified bundle'
input: interact.select_loaded_bundle
handler: (name) ->
log.info "Reloading bundle '#{name}'.."
bundle.unload name if _G.bundles[name]
bundle.load_by_name name
log.info "Reloaded bundle '#{name}'"
command.register
name: 'bundle-reload-current'
description: 'Reload the last active bundle (with files open)'
handler: ->
for buffer in *app.buffers
bundle_name = buffer.file and bundle.from_file(buffer.file) or nil
if bundle_name
command.bundle_reload bundle_name
return
log.warn 'Could not find any currently active bundle to reload'
matcher_find = (entry, matcher, start) ->
-- entry is result of parse_line and matcher is result of parse_query
how, positions = matcher entry.text, entry.case_text
if how
-- return start, end for the matched segment within the line
return positions[1], positions[#positions]
command.register
name: 'buffer-grep'
description: 'Show buffer lines containing fuzzy matches in real time'
input: (opts) ->
buffer = app.editor.buffer
opts.help\add_keys
['buffer-grep']: 'Switch to <command>buffer-grep-regex</>'
return interact.buffer_search
title: "Matches in #{buffer.title}"
once_per_line: true
limit: 1000
parse_query: (query) -> howl.util.Matcher.create_matcher query
parse_line: (line) -> {:line, case_text: line.text, text: line.text.ulower}
find: matcher_find
prompt: opts.prompt
text: opts.text
help: opts.help
editor: app.editor
buffer: buffer
selected_line: app.editor.current_line
cancel_for_keymap:
binding_for:
['buffer-grep']: (args) -> howl.command.run 'buffer-grep-regex ' .. args.text
handler: (result) ->
return unless result
breadcrumbs.drop!
app.editor.cursor\move_to pos: result.chunk.start_pos
command.register
name: 'buffer-grep-regex'
description: 'Show buffer lines containing regex matches in real time'
input: (opts) ->
buffer = app.editor.buffer
opts.help\add_keys
['buffer-grep']: 'Switch to <command>buffer-grep-exact</>'
['buffer-replace']: 'Switch to <command>buffer-replace-regex</>'
return interact.buffer_search
title: "Regex matches in #{buffer.title}"
once_per_line: true
limit: 1000
parse_query: (query) ->
status, query = pcall -> r query
return query if status
error 'Invalid regular expression', 0
parse_line: (line) -> line.text
find: (text, regex, start) -> regex\find text, start
prompt: opts.prompt
text: opts.text
help: opts.help
editor: app.editor
buffer: buffer
selected_line: app.editor.current_line
cancel_for_keymap:
binding_for:
['buffer-grep']: (args) -> howl.command.run 'buffer-grep-exact ' .. args.text
['buffer-replace']: (args) -> howl.command.run 'buffer-replace-regex /' .. args.text
handler: (result) ->
return unless result
breadcrumbs.drop!
app.editor.cursor\move_to pos: result.chunk.start_pos
command.register
name: 'buffer-grep-exact'
description: 'Show buffer lines containing exact matches in real time'
input: (opts)->
buffer = app.editor.buffer
opts.help\add_keys
['buffer-grep']: 'Switch to <command>buffer-grep</>'
['buffer-replace']: 'Switch to <command>buffer-replace</>'
return interact.buffer_search
title: "Exact matches in #{buffer.title}"
once_per_line: true
limit: 1000
parse_line: (line) -> line.text
find: (text, query, start) -> text\ufind query, start, true
prompt: opts.prompt
text: opts.text
help: opts.help
editor: app.editor
buffer: buffer
selected_line: app.editor.current_line
cancel_for_keymap:
binding_for:
['buffer-grep']: (args) -> howl.command.run 'buffer-grep ' .. args.text
['buffer-replace']: (args) -> howl.command.run 'buffer-replace /' .. args.text
handler: (result) ->
return unless result
breadcrumbs.drop!
app.editor.cursor\move_to pos: result.chunk.start_pos
command.register
name: 'buffer-structure'
description: 'Show the structure for the current buffer'
input: (opts) ->
buffer = app.editor.buffer
lines = buffer.mode\structure app.editor
cursor_lnr = app.editor.cursor.line
local selected_line
for line in *lines
if line.nr <= cursor_lnr
selected_line = line
if line.nr >= cursor_lnr
break
return interact.buffer_search
title: "Structure for #{buffer.title}"
once_per_line: true
editor: app.editor
buffer: buffer
parse_query: (query) -> howl.util.Matcher.create_matcher query
parse_line: (line) -> {:line, case_text: line.text, text: line.text.ulower}
find: matcher_find
prompt: opts.prompt
text: opts.text
help: opts.help
:lines
:selected_line
handler: (result) ->
return unless result
breadcrumbs.drop!
app.editor.cursor\move_to pos: result.chunk.start_pos
command.register
name: 'navigate-back'
description: 'Goes back to the last location recorded'
handler: ->
if breadcrumbs.previous
breadcrumbs.go_back!
log.info "navigate: now at #{breadcrumbs.location} of #{#breadcrumbs.trail}"
else
log.info "No previous location recorded"
command.register
name: 'navigate-forward'
description: 'Goes to the next location recorced'
handler: ->
if breadcrumbs.next
breadcrumbs.go_forward!
log.info "navigate: now at #{breadcrumbs.location} of #{#breadcrumbs.trail}"
else
log.info "No next location recorded"
command.register
name: 'navigate-go-to'
description: 'Goes to a specific location in the history'
input: (opts) ->
to_item = (crumb, i) ->
{:buffer_marker, :file} = crumb
buffer = buffer_marker and buffer_marker.buffer
project = file and Project.for_file(file)
where = if project
file\relative_to_parent(project.root)
elseif file
file.path
else
buffer.title
pos = breadcrumbs.crumb_pos crumb
{
i,
project and project.root.basename or ''
"#{where}@#{pos}"
:buffer, :file, :pos
}
crumbs = breadcrumbs.trail
items = [to_item(b, i) for i, b in ipairs crumbs]
if #items == 0
log.warn "No locations available for navigation"
return nil
interact.select_location
title: "Navigate back to.."
prompt: opts.prompt
text: opts.text
:items
selection: items[breadcrumbs.location] or items[breadcrumbs.location - 1]
columns: {
{ header: 'Position', style: 'number' },
{ header: 'Project', style: 'key' },
{ header: 'Path', style: 'string' }
}
handler: (loc) ->
return unless loc
breadcrumbs.location = loc[1]
command.register
name: 'open-journal'
description: 'Opens the Howl log journal'
handler: ->
app\add_buffer JournalBuffer!
app.editor.cursor\eof!
-----------------------------------------------------------------------
-- Howl eval commands
-----------------------------------------------------------------------
do_howl_eval = (load_f, mode_name, transform_f) ->
editor = app.editor
text = editor.selection.empty and editor.current_line.text or editor.selection.text
text = transform_f and transform_f(text) or text
f = assert load_f text
ret = { pcall f }
if ret[1]
out = ''
for i = 2, #ret
out ..= "\n#{serpent.block ret[i], comment: false}"
if editor.popup
log.info "(Eval) => #{ret[2]}"
else
buf = Buffer mode.by_name mode_name
buf.text = "-- Howl eval (#{mode_name}) =>#{out}"
editor\show_popup BufferPopup buf, scrollable: true
howl.clipboard.push out
else
log.error "(ERROR) => #{ret[2]}"
command.register
name: 'howl-lua-eval'
description: 'Eval the current line or selection as Lua'
handler: ->
do_howl_eval load, 'lua', (text) ->
unless text\match 'return%s'
text = if text\find '\n'
text\gsub "\n([^\n]+)$", "\n return %1"
else
"return #{text}"
text
command.register
name: 'howl-moon-eval'
description: 'Eval the current line or selection as Moonscript'
handler: ->
moonscript = require('moonscript')
transform = (text) ->
initial_indent = text\match '^([ \t]*)%S'
if initial_indent -- remove the initial indent from all lines if any
lines = [l\gsub("^#{initial_indent}", '') for l in text\gmatch('[^\n]+')]
text = table.concat lines, '\n'
moonscript.loadstring text
do_howl_eval transform, 'moonscript'
command.register
name: 'howl-moon-print'
description: 'Compile and show the Lua for the current buffer or selection'
handler: ->
moonscript = require('moonscript.base')
editor = app.editor
buffer = editor.buffer
title = "#{buffer.title} (compiled to Lua)"
text = buffer.text
unless editor.selection.empty
title = "#{buffer.title} (Lua - from selection)"
text = editor.selection.text
lua, err = moonscript.to_lua text
local buf
if not lua
buf = ActionBuffer!
buf\append howl.ui.markup.howl "<error>#{err}</error>"
else
buf = Buffer mode.by_name 'lua'
buf.text = lua
buf.title = title
buf.modified = false
if #buf.lines > 20
breadcrumbs.drop!
editor.buffer = buf
else
buf\insert "-- #{title}\n", 1
editor\show_popup BufferPopup buf, scrollable: true
-----------------------------------------------------------------------
-- Launch commands
-----------------------------------------------------------------------
launch_cmd = (working_directory, cmd) ->
shell = howl.sys.env.SHELL or '/bin/sh'
p = Process {
:cmd,
:shell,
read_stdout: true,
read_stderr: true,
working_directory: working_directory,
}
breadcrumbs.drop!
buffer = ProcessBuffer p
editor = app\add_buffer buffer
editor.cursor\eof!
buffer\pump!
get_project = ->
buffer = app.editor and app.editor.buffer
file = buffer.file or buffer.directory
error "No file associated with the current view" unless file
project = Project.get_for_file file
error "No project associated with #{file}" unless project
return project
command.register
name: 'project-exec',
description: 'Run an external command from within the project directory'
input: (opts) -> interact.get_external_command path: get_project_root!, prompt: opts.prompt
handler: (args) -> launch_cmd args.working_directory, args.cmd
get_input_text: (args) -> args.cmd
command.register
name: 'project-build'
description: 'Run the command in config.project_build_command from within the project directory'
handler: -> launch_cmd get_project!.root, (app.editor and app.editor.buffer.config or config).project_build_command
command.register
name: 'exec',
description: 'Run an external command'
input: (opts) -> interact.get_external_command
path: get_buffer_dir howl.app.editor.buffer
text: opts.text
handler: (args) -> launch_cmd args.working_directory, args.cmd
get_input_text: (args) -> args.cmd
command.register
name: 'save-config'
description: 'Save the current configuration'
handler: ->
config.save_config!
log.info 'Configuration saved'
config.define
name: 'project_build_command'
description: 'The command to execute when project-build is run'
default: 'make'
type_of: 'string'
-----------------------------------------------------------------------
-- File search commands
-----------------------------------------------------------------------
config.define
name: 'file_search_hit_display'
description: 'How to display file search hits in the list'
default: 'rich'
type_of: 'string'
options: -> {
{'plain', 'Display as plain unicolor strings'},
{'highlighted', 'Highlight search terms in hits'} ,
{'rich', 'Show syntax highlighted snippets with highlighted terms'},
}
file_search_hit_mt = {
__tostyled: (item) ->
text = item.text
m = mode.for_file(item.match.file)
if m and m.lexer
styles = m.lexer(text)
return StyledText text, styles
text
__tostring: (item) -> item.text
}
file_search_hit_to_location = (match, search, display_as) ->
hit_display = if display_as == 'rich'
setmetatable {text: match.message, :match}, file_search_hit_mt
else
match.message
path = match.path\truncate(50, omission_prefix: '..')
loc = {
howl.ui.markup.howl "<comment>#{path}</>:<number>#{match.line_nr}</>"
hit_display,
file: match.file,
line_nr: match.line_nr,
column: match.column
}
search = search.ulower
s, e = match.message.ulower\ufind(search, 1, true)
unless s
s, e = match.message\ufind((r(search)))
if loc.column
loc.byte_start_column = loc.column
loc.byte_end_column = loc.column + #search
elseif s
loc.start_column = s
loc.end_column = e + 1
if s and display_as != 'plain'
loc.item_highlights = {
nil,
{
{byte_start_column: s, count: e - s + 1}
}
}
loc
do_search = (search, whole_word) ->
project = get_project!
file_search = howl.file_search
matches, searcher = file_search.search project.root, search, :whole_word
unless #matches > 0
log.error "No matches found for '#{search}'"
return matches
matches = file_search.sort matches, project.root, search, app.editor.current_context
display_as = project.config.file_search_hit_display
status = "Loaded 0 out of #{#matches} locations.."
cancel = false
locations = activities.run {
title: "Loading #{#matches} locations..",
status: -> status
cancel: -> cancel = true
}, ->
return for i = 1, #matches
if i % 1000 == 0
break if cancel
status = "Loaded #{i} out of #{#matches}.."
activities.yield!
m = matches[i]
file_search_hit_to_location(m, search, display_as)
locations, searcher, project
command.register
name: 'project-file-search',
description: 'Searches files in the the current project'
input: (opts) ->
editor = app.editor
search = nil
whole_word = false
if opts.text and not opts.text.is_empty
search = opts.text
unless search or app.window.command_panel.is_active
if editor.selection.empty
search = app.editor.current_context.word.text
whole_word = true unless search.is_empty
else
search = editor.selection.text
if not search or search.is_empty
search = interact.read_text prompt: opts.prompt
if not search or search.is_empty
log.warn "No search query specified"
return
locations, searcher, project = do_search search, whole_word
if #locations > 0
interact.select_location
title: "#{#locations} matches for '#{search}' in #{project.root.short_path} (using #{searcher.name} searcher)"
items: locations
handler: (loc) ->
if loc
app\open loc
command.register
name: 'project-file-search-list',
description: 'Searches files in the the current project, listing results in a buffer'
input: (opts) ->
editor = app.editor
search = nil
whole_word = false
if opts.text and not opts.text.is_empty
search = opts.text
unless app.window.command_panel.is_active
if editor.selection.empty
search = app.editor.current_context.word.text
whole_word = true unless search.is_empty
else
search = editor.selection.text
if not search or search.is_empty
search = interact.read_text prompt: opts.prompt
if not search or search.is_empty
log.warn "No search query specified"
return
locations, searcher, project = do_search search , whole_word
if #locations > 0
matcher = howl.util.Matcher locations
list = howl.ui.List matcher
list_buf = howl.ui.ListBuffer list, {
title: "#{#locations} matches for '#{search}' in #{project.root.short_path} (using #{searcher.name} searcher)"
on_submit: (location) ->
app\open location
}
list_buf.directory = project.root
app\add_buffer list_buf
nil
handler: (loc) ->
| 29.982597 | 121 | 0.655534 |
dccba20dfbecd82969bebb4f8df09c6a7462793a | 208 | config = require("lapis.config").get!
if config.postgres
require "lapis.db.postgres.model"
elseif config.mysql
require "lapis.db.mysql.model"
else
error "You have to configure either postgres or mysql"
| 26 | 56 | 0.764423 |
c1454a77342fd9a7f5bc192ecdf089aaab51110a | 10,449 | import Router, RouteParser from require "lib.resty.router.router"
build_router = (routes) ->
handler = (ctx) -> { ctx.params, ctx.route, ctx.name }
with r = Router!
for pattern in *routes
r\add_route pattern, handler
r\set_default_route -> "failed to find route"
resolve = r.resolve
r.resolve = (self, path) ->
_, ctx, responder = resolve(self, path)
responder(ctx)
describe "Router", ->
it "matches a route", ->
router = Router!
f = ->
router\add_route "/hello", f
assert.same {{}, f, "/hello"}, {router\match "/hello"}
it "fails to match a route", ->
router = Router!
f = ->
router\add_route "/hello", f
assert.same {}, {router\match "/zone"}
describe "RouteParser.parse", ->
for {pattern, test, result} in *{
{"/:yeah", "ddd", nil}
{"/:yeah", "/okay", {yeah: "okay"}}
{"/:yeah", "/okay.com", {yeah: "okay.com"}}
-- exclude var
{":thing-:hello", "a-b", {thing: "a", hello: "b"}}
{":thing(-:hello)", {
{"a-b", {thing: "a", hello: "b"}}
{"az", {thing: "az"}}
{"i/fail", nil}
}}
-- exclude splat
{"/hi/*-:hello", "/hi/a/b/c-okay", {splat: "a/b/c", hello: "okay"}}
{"*/hello", "whoa/zone/hello", {splat: "whoa/zone"}}
{":one.*", "sure-thing.com", {splat: "com", one: "sure-thing"}}
-- splat with optional exclude from format
{"/browse/*(.:format)", {
{"/browse/things", {splat: "things"}}
{"/browse/things.zip", {splat: "things", format: "zip"}}
{"/browse/things.tar.gz", {splat: "things", format: "tar.gz"}}
}}
-- splat doesn't cancel out var
{":one(*)", "hello_world", { one: "hello_world"}}
{"/zone(/:game(/:user))", "/zone/drone/leafo",
{ game: "drone", user: "leafo"}}
{"/:game(/:user)(*)", "/drone/leafo/hi",
{ game: "drone", user: "leafo", splat: "/hi" }}
-- many optional
{"/zone(/:game(/:user)(*))", {
{"/zone", {}}
{"/zone/leafo", { game: "leafo"}}
{"/zone/leafo/beefo", { game: "leafo", user: "beefo"}}
{"/zone/drone/leafo/here", { game: "drone", user: "leafo", splat: "/here" }}
}}
-- many optional with format
{"/zone(/:game(/:user)(*))(.:format)", {
-- same as above, nothing changed
{"/zone", {}}
{"/zone/leafo", { game: "leafo"}}
{"/zone/leafo/beefo", { game: "leafo", user: "beefo"}}
{"/zone/drone/leafo/here", { game: "drone", user: "leafo", splat: "/here" }}
-- with formats
{"/zone.zip", { format: "zip"}}
{"/zone/leafo.jpeg", { game: "leafo", format: "jpeg"}}
{"/zone/leafo/beefo.moon", { game: "leafo", user: "beefo", format: "moon"}}
{"/zone/drone/leafo/here.leaf", {
game: "drone"
user: "leafo"
splat: "/here"
format: "leaf"
}}
}}
-- adjacent optionals
{"/manifest(-:version)(.:format)", {
{"/manifest", {}}
{"/manifest-first.json", { version: "first", format: "json"}}
{"/manifest.json", { format: "json"}}
{"/manifest-first", { version: "first" }}
}}
-- moonrocks workaround
-- TODO: make (-:version)(.:format) work for -5.1.zip
{"/manifest(-:a.:b)(.:format)", {
{"/manifest-5.1.json", { a: "5", b: "1", format: "json" }}
{"/manifest-5.1", { a: "5", b: "1" }}
{"/manifest.json", { format: "json" }}
}}
-- character classes
{"/:hello[%d]", {
{"/what", nil}
{"/", nil}
{"/1223", { hello: "1223"}}
{"/1", { hello: "1"}}
}}
{"/:world[%a]", {
{"/what", { world: "what"}}
{"/1223", nil}
{"/1"}
}}
{"/:lee[%w]", {
{"/what", {lee: "what"}}
{"/999", {lee: "999"}}
{"/aj23", {lee: "aj23"}}
{"/2lll__", nil}
{"/", nil}
}}
{"/:ben[a-f]", {
{"/what", nil}
{"/abf", {ben: "abf"}}
}}
{"/:andy[12fg]", {
{"/what", nil}
{"/12", {andy: "12"}}
{"/f2", {andy: "f2"}}
}}
{"/:dap[a%dd-g]", {
{"/what", nil}
{"/a3", {dap: "a3"}}
{"/9a99f", {dap: "9a99f"}}
}}
{"/:nope[^.]", {
{"/good", {nope: "good"}}
{"/", nil}
{"/one.two", nil}
}}
{"/:nope[%%%w]", {
{"/%20", {nope: "%20"}}
{"/hi%20", {nope: "hi%20"}}
{"/", nil}
}}
{"/:nope[%-ab]", {
{"/-", {nope: "-"}}
{"/--", {nope: "--"}}
{"/-ab", {nope: "-ab"}}
{"/ab-", {nope: "ab-"}}
{"/a-b", {nope: "a-b"}}
{"/", nil}
{"/%ab", nil}
{"/%20", nil}
}}
{"/:nope[%%w%-ab]", {
{"/-", {nope: "-"}}
{"/%ab", {nope: "%ab"}}
{"/%ab-", {nope: "%ab-"}}
{"/%ab-%ab-", {nope: "%ab-%ab-"}}
{"/w", {nope: "w"}}
{"/c", nil}
{"/", nil}
}}
}
do_test = (pattern, test, result) ->
it "matches `#{pattern}` with `#{test}`", ->
parser = RouteParser!
p = assert parser\compile pattern
assert.same result, (p\match test)
if type(test) == "table"
for {_test, result} in *test
do_test pattern, _test, result
else
do_test pattern, test, result
describe "with router", ->
local r
describe "basic router", ->
before_each ->
r = build_router {
"/hello"
"/hello/:name[%d]"
"/hello/:name"
"/hello/:name/world"
"/static/*"
"/x/:color/:height/*"
"/please/"
}
it "should match static route", ->
out = r\resolve "/hello"
assert.same { {}, "/hello" }, out
it "should match character class route", ->
out = r\resolve "/hello/234"
assert.same { { name: "234" }, "/hello/:name[%d]" }, out
it "should match param route", ->
out = r\resolve "/hello/world2323"
assert.same {
{ name: "world2323" },
"/hello/:name"
}, out
it "should match param route", ->
out = r\resolve "/hello/the-parameter/world"
assert.same {
{ name: "the-parameter" },
"/hello/:name/world"
}, out
it "should match splat", ->
out = r\resolve "/static/hello/world/343434/foo%20bar.png"
assert.same {
{ splat: 'hello/world/343434/foo%20bar.png' }
"/static/*"
}, out
it "should match all", ->
out = r\resolve "/x/greenthing/123px/ahhhhwwwhwhh.txt"
assert.same {
{
splat: 'ahhhhwwwhwhh.txt'
height: '123px'
color: 'greenthing'
}
"/x/:color/:height/*"
}, out
it "should match nothing", ->
assert.same "failed to find route", r\resolve("/what-the-heck")
it "should match nothing", ->
assert.same "failed to find route", r\resolve("/hello//world")
it "should match trailing exactly", ->
assert.same {
{}
"/please/"
}, r\resolve("/please/")
assert.same "failed to find route", r\resolve("/please")
it "should match the catchall", ->
r = build_router {"*"}
assert.same {
{ splat: "hello_world" }
"*"
}, r\resolve "hello_world"
describe "named routes", ->
local r
before_each ->
r = build_router {
{ homepage: "/home" }
{ profile: "/profile/:name" }
{ profile_settings: "/profile/:name/settings" }
{ game: "/game/:user_slug/:game_slug" }
{ splatted: "/page/:slug/*" }
{ optional: "/page(.:format)" }
}
it "should match", ->
out = r\resolve "/home"
assert.same {
{}, "/home", "homepage"
}, out
describe "optional parts", ->
local r
describe "basic router", ->
before_each ->
r = build_router {
"/test(/:game)"
"/zone(/:game(/:user)(*))"
"/test/me"
}
it "matches without optional", ->
out = r\resolve "/test/yeah"
assert.same { {game: "yeah"}, "/test(/:game)" }, out
it "matches with optional part", ->
out = r\resolve "/test/ozone"
assert.same { {game: "ozone"}, "/test(/:game)" }, out
it "fails to find", ->
out = r\resolve "/test/ozone/"
assert.same "failed to find route", out
it "lets literal route take precedence", ->
out = r\resolve "/test/me"
assert.same { {}, "/test/me" }, out
describe "route precedence", ->
local r
before_each ->
r = build_router {
"/*"
"/:slug"
"/hello"
}
it "matches literal route first", ->
out = r\resolve "/hello"
assert.same { {}, "/hello" }, out
it "matches var route second", ->
out = r\resolve "/world"
assert.same { {slug: "world"}, "/:slug" }, out
it "matches slug last", ->
out = r\resolve "/whoa/zone"
assert.same { { splat: "whoa/zone" }, "/*" }, out
it "preserves declare order among routes with same precedence", ->
r = build_router {
"/*"
"/:slug1"
"/:slug2"
"/:slug3"
"/:slug4"
"/:slug5"
"/hello"
}
out = r\resolve "/hey"
assert.same { { slug1: "hey" }, "/:slug1" }, out
it "more specific takes precedence", ->
pending "todo"
r = build_router {
"/test/:game"
"/test/:game-world"
}
out = r\resolve "/test/hello-world"
assert.same { { game: "hello" }, "/test/:game-world" }, out
it "non-optional takes precedence", ->
pending "todo"
r = build_router {
"/test(/:game)"
"/test/:game"
}
out = r\resolve "/test/thing"
assert.same { { game: "thing" }, "/test/:game" }, out
it "precedence with unnamed routes", ->
r = build_router {
{ something: "/*" }
"/foo"
"/bar/*"
}
out = r\resolve "/bar/baz/1"
assert.same { { splat: "baz/1" }, "/bar/*" }, out
out = r\resolve "/qux/foo"
assert.same { { splat: "qux/foo" }, "/*", "something" }, out
describe "sort routes", ->
sort_routes = (rs) ->
router = build_router rs
tuples = for r in *router.routes
pattern, flags = router\build_route unpack r
p = router\route_precedence flags
-- print r[1], p
{r[1], p}
table.sort tuples, (a,b) ->
a[2] < b[2]
[t[1] for t in *tuples]
it "basic set", ->
assert.same {
"/hello"
"/:slug1/two"
"/*"
}, sort_routes {
"/*"
"/:slug1/two"
"/hello"
}
it "number of slugs affects match", ->
assert.same {
"/hello"
"/:slug1/two"
"/:slug1/:slug2"
"/*/hi/*"
"/*"
}, sort_routes {
"/*"
"/*/hi/*"
"/:slug1/:slug2"
"/:slug1/two"
"/hello"
}
| 24.470726 | 82 | 0.480907 |
962e03406b78541f7f88cfe00d784a9c8a821c39 | 2,549 | -- Copyright 2014-2015 The Howl Developers
-- License: MIT (see LICENSE)
dispatch = howl.dispatch
describe 'dispatch', ->
describe 'launch(f, ...)', ->
it 'invokes <f> in a coroutine with the specified arguments', ->
f = spy.new ->
_, is_main = coroutine.running!
assert.is_false is_main
dispatch.launch f, 1, nil, 'three'
assert.spy(f).was_called_with 1, nil, 'three'
context 'when <f> starts correctly', ->
it 'returns true and the coroutine status', ->
status, co_status = dispatch.launch -> nil
assert.is_true status
assert.equals 'dead', co_status
context 'when <f> errors upon start', ->
it 'returns false and the error message', ->
status, err = dispatch.launch -> error 'foo'
assert.is_false status
assert.equals 'foo', err
describe 'wait()', ->
it 'yields until resumed using resume() on the parked handle', ->
handle = dispatch.park 'test'
done = false
dispatch.launch ->
dispatch.wait handle
done = true
assert.is_false done
dispatch.resume handle
assert.is_true done
it 'returns any parameters passed to resume()', ->
handle = dispatch.park 'test'
local res
dispatch.launch ->
res = { dispatch.wait handle }
dispatch.resume handle, 1, nil, 'three', nil
assert.same { 1, nil, 'three', nil }, res
it 'raises an error when resumed with resume_with_error()', ->
handle = dispatch.park 'test'
local err
dispatch.launch ->
status, err = pcall dispatch.wait, handle
assert.is_false status
dispatch.resume_with_error handle, 'blargh!'
assert.includes err, 'blargh!'
describe 'resume()', ->
it 'propagates any error occurring during resuming', ->
handle = dispatch.park 'test'
dispatch.launch ->
dispatch.wait handle
error 'boom'
assert.raises 'boom', -> dispatch.resume handle
context 'when nothing is yet waiting on the parking', ->
it 'blocks until released by a wait', (done) ->
howl_async ->
handle = dispatch.park 'out-of-order'
launched, status = dispatch.launch -> dispatch.resume handle, 'resume-now!'
assert.is_true launched
assert.equals "suspended", status
launched, status = dispatch.launch ->
assert.equals 'resume-now!', dispatch.wait handle
done!
assert.is_true launched
assert.equals "dead", status
| 29.639535 | 85 | 0.612397 |
e5220fbce313381326a00037d01dcd202a2354e1 | 1,972 | stypes = require "stypes"
tokenise = (program) ->
tokens = {}
expr = {}
token = ""
inChar = false
inString = false
for c in program\gmatch "."
if inString
if c == '"' and token[#token] != '\\'
token = "#{token}#{c}"
inString = false
else
token = "#{token}#{c}"
elseif inChar
if c == "'" and token[#token] != '\\'
token = "#{token}#{c}"
inChar = false
else
token = "#{token}#{c}"
else
if c == '"'
inString = true
token = "#{token}#{c}"
elseif c == "'"
inChar = true
token = "#{token}#{c}"
elseif c == " "
expr[#expr + 1] = token
token = ""
elseif c == "\n"
tokens[#tokens + 1] = expr
expr = {}
else
token = "#{token}#{c}"
if #token > 0
expr[#expr + 1] = token
token = ""
if #expr > 0
tokens[#tokens + 1] = expr
expr = {}
tokens
parse = (tokens) ->
ast = {}
errors = {}
for _, expr in pairs tokens
new_expr = {}
for pos, sym in pairs expr
if pos == 1
new_expr[#new_expr + 1] = stypes.Label(sym)
elseif pos == 2
new_expr[#new_expr + 1] = stypes.Function(sym)
elseif stypes.isnumber(sym)
new_expr[#new_expr + 1] = stypes.Number(sym)
elseif stypes.isfloat(sym)
new_expr[#new_expr + 1] = stypes.Float(sym)
elseif stypes.isrational(sym)
new_expr[#new_expr + 1] = stypes.Rational(sym)
elseif stypes.ischar(sym)
new_expr[#new_expr + 1] = stypes.Character(sym)
elseif stypes.isstring(sym)
new_expr[#new_expr + 1] = stypes.String(sym)
-- TODO: else error
ast[#ast + 1] = new_expr
ast
dump_tokens = (tokens) ->
for line, expr in pairs tokens
msg = "["
for _, sym in pairs expr
msg = "#{msg} #{sym},"
msg = "#{msg\sub(1, #msg - 1)} ]"
print msg
dump_tokens tokenise "10 print \"Hello, World!\" \n20 print 'a"
| 25.282051 | 63 | 0.511156 |
c82b106152585a143dadf2cb6c01b0b0ed6a1ece | 4,456 | -- Copyright 2012-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
import app, config, interact, Project from howl
import File from howl.io
import icon from howl.ui
import Matcher from howl.util
append = table.insert
config.define
name: 'buffer_icons'
description: 'Whether buffer icons are displayed'
scope: 'global'
type_of: 'boolean'
default: true
icon.define_default 'buffer', 'font-awesome-square'
icon.define_default 'buffer-modified', 'font-awesome-pencil-square-o'
icon.define_default 'buffer-modified-on-disk', 'font-awesome-clone'
icon.define_default 'process-success', 'font-awesome-check-circle'
icon.define_default 'process-running', 'font-awesome-play-circle'
icon.define_default 'process-failure', 'font-awesome-exclamation-circle'
buffer_dir = (buffer) ->
if buffer.file
return buffer.file.parent.short_path
elseif buffer.directory
return buffer.directory.short_path
return '(none)'
buffer_status_text = (buffer) ->
stat = if buffer.modified then '*' else ''
stat ..= '[modified on disk]' if buffer.modified_on_disk
stat
buffer_status_icon = (buffer) ->
local name
if typeof(buffer) == 'ProcessBuffer'
if buffer.process.exited
name = buffer.process.successful and 'process-success' or 'process-failure'
else
name = 'process-running'
else
if buffer.modified_on_disk
name = 'buffer-modified-on-disk'
elseif buffer.modified
name = 'buffer-modified'
else
name = 'buffer'
return icon.get(name, 'operator')
make_title = (buffer, opts={}) ->
file = buffer.file
title = file.basename
if opts.parents
parent = file.parent
for _ = 1, opts.parents
if parent
title = "#{parent.basename}#{File.separator}#{title}"
parent = parent.parent
else
break
if opts.project
project = Project.for_file file
if project
title = "#{title} [#{project.root.basename}]"
return title
has_duplicates = (list) ->
set = {}
for item in *list
return true if set[item]
set[item] = true
return false
get_buffer_list = (buffers) ->
basenames = {}
enhanced_titles = {}
for buf in *buffers
continue unless buf.file and buf.file.basename == buf.title
basenames[buf.file.basename] or= {}
append basenames[buf.file.basename], buf
for _, buffer_group in pairs(basenames)
continue if #buffer_group == 1
options_list = {
{ project: true }
{ project: false, parents: 1 }
{ project: true, parents: 1 }
{ project: false, parents: 2 }
{ project: true, parents: 2 }
}
titles = nil
for options in *options_list
titles = [make_title buffer, options for buffer in *buffer_group]
break if not has_duplicates titles
for i=1,#buffer_group
enhanced_titles[buffer_group[i]] = titles[i]
title = (buffer) -> enhanced_titles[buffer] or buffer.title
if config.buffer_icons
return [{buffer_status_icon(buffer), title(buffer), buffer_dir(buffer), :buffer} for buffer in *buffers]
else
return [{title(buffer), buffer_status_text(buffer), buffer_dir(buffer), :buffer} for buffer in *buffers]
buffer_matcher = (get_buffers) ->
(text) ->
buffers = get_buffers!
matcher = Matcher get_buffer_list buffers
return matcher(text)
interact.register
name: 'select_buffer'
description: 'Selection list for buffers'
handler: (opts={}) ->
opts = moon.copy opts
local columns
if config.buffer_icons
columns = {
{},
{style: 'string'}
{style: 'comment'}
}
else
columns = {
{style: 'string'}
{style: 'operator'}
{style: 'comment'}
}
current_selection = nil
with opts
.title or= 'Buffers'
.matcher = buffer_matcher opts.get_buffers or -> app.buffers
.columns = columns
.on_change = (selection, text, items) ->
current_selection = selection
command_line = howl.app.window.command_line
command_line\add_keymap {
binding_for:
['buffer-close']: =>
if current_selection and current_selection.buffer
app\close_buffer current_selection.buffer
command_line\refresh!
}
command_line\add_help
key_for: 'buffer-close'
action: 'Close the currently selected buffer'
result = interact.select_location opts
if result
return result.selection.buffer
| 27.506173 | 108 | 0.670557 |
f3f7f2aafb907521d312b8f273fdb5e93d3a6714 | 340 | import mode from howl
curly_mode = {
indentation: {
more_after: {
'[[{(]%s*$',
}
less_for: {
'^%s*[]})]',
}
}
code_blocks:
multiline: {
{ '{%s*$', '^%s*}', '}'}
{ '%[%s*$', '^%s*%]', ']'}
{ '%(%s*$', '^%s*%)', ')'}
}
}
mode.register name: 'curly_mode', create: -> curly_mode
| 14.166667 | 55 | 0.373529 |
765c75478da3a7ecf5b57b393a298afcd0dc2386 | 3,843 | -- Copyright 2018 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
{:clean, :is_valid} = require 'howl.util.utf8'
{:get_monotonic_time} = require 'ljglibs.glib'
ffi = require 'ffi'
C = ffi.C
to_hex_string = (s) ->
parts = {}
for i = 1, #s
parts[#parts + 1] = '\\x' .. string.format('%02x', s\byte(i))
table.concat parts, ' '
describe 'utf8', ->
describe 'clean(s)', ->
glib_make_valid = (s) ->
ptr = C.g_utf8_make_valid(s, #s)
s = ffi.string ptr
C.g_free(ptr)
s
utf8_clean = (s) ->
r, size = clean s
ffi.string r, size
assert_clean = (s, expected) ->
rs = utf8_clean s
unless rs == expected
assert.equal to_hex_string(expected), to_hex_string(rs)
it 'returns a clean string as is', ->
assert_clean '123456789', '123456789'
assert_clean "åäöƏ⏱🌨", "åäöƏ⏱🌨"
it 'cleans up incorrect dual sequences', ->
assert_clean '|\xc3\x24|', '|�$|'
assert_clean '|\xc3\x24\xc3\x61|', '|�$�a|'
assert_clean '|\xc3\x24X\xc3\x61|', '|�$X�a|'
it 'cleans up incorrect three-byte sequences', ->
-- -- incorrect at second seq byte
assert_clean '|\xe1\x24|', '|�$|'
-- incorrect at third seq byte
assert_clean '|\xe1\x80\x24|', '|��$|'
it 'cleans up incorrect four-byte sequences', ->
-- incorrect at second seq byte
assert_clean '|\xf0\x24|', '|�$|'
-- incorrect at third seq byte
assert_clean '|\xf0\x80\x24|', '|��$|'
-- incorrect at fourth seq byte
assert_clean '|\xf0\x80\x80\x24|', '|���$|'
it 'cleans up stray continuation bytes', ->
assert_clean '|\x80|', '|�|'
assert_clean '|\x80\x80|', '|��|'
assert_clean '\x80|', '�|'
assert_clean '|\x80', '|�'
assert_clean '\xc2\xa9\xa9', '©�'
it 'cleans up illegal bytes', ->
for b = 192, 193
assert_clean "|#{string.char(b)}|", '|�|'
for b = 245, 255
assert_clean "|#{string.char(b)}|", '|�|'
it 'cleans up broken utf8 at the end', ->
assert_clean '\x8d\xc7\xe0', '���'
it 'handles sequence starts within sequences', ->
assert_clean '\xc7\xe0\x60\x28\x8c', '��`(�'
it 'handles illegal values in sequences', ->
assert_clean '\xc4\xf7\x61\xb9', '��a�'
-- below are some comparison runs with the builtin glib variants useful
-- for performance testing
if false
time = (title, f) ->
start = get_monotonic_time!
f!
done = get_monotonic_time!
elapsed = (done - start) / 1000000
print "'#{title}': #{elapsed} elapsed"
it 'performance', ->
valid = string.rep 'abcdefghijklmnopqrstuvxyzABCDEFGHIJKLMNOPQRSTUVXYZ', 1000
for i = 1, 100
C.g_utf8_validate valid, #valid, nil
time 'g_utf8_validate', ->
for i = 1, 1000
C.g_utf8_validate valid, #valid, nil
for i = 1, 100
is_valid valid
time 'own is_valid', ->
for i = 1, 1000
is_valid valid
for i = 1, 100
glib_make_valid(valid)
time 'g_utf8_make_valid CLEAN', ->
for i = 1, 1000
ptr = C.g_utf8_make_valid(valid, #valid)
C.g_free(ptr)
for i = 1, 100
clean valid
time 'own clean CLEAN', ->
for i = 1, 1000
clean valid
broken = string.rep 'ab⏱🌨\xc3\x24hiåäömn\xe1\x80\x24opq\xf0\x24', 1000
for i = 1, 100
glib_make_valid(broken)
time 'g_utf8_make_valid BROKEN', ->
for i = 1, 1000
ptr = C.g_utf8_make_valid(broken, #broken)
C.g_free(ptr)
for i = 1, 100
clean broken
time 'own clean BROKEN', ->
for i = 1, 1000
clean broken
| 27.647482 | 85 | 0.550612 |
b11e4b5849320f8aa36b232cb22d470831ada4cb | 1,231 | lines = (file) ->
assert (love.filesystem.isFile file), "#{file} doesn't exist!"
[line for line in love.filesystem.lines file]
split = (inp, sep="%s") ->
[t for t in string.gmatch inp, "([^#{sep}]+)"]
class
new: (file, @r=100, @g=100, @b=0, s=1) =>
@vertices = {}
@faces = {}
for i, v in ipairs lines file
if "v " == string.sub v, 1, 2
v_line = split (v\sub 3), " "
table.insert @vertices, [(s * tonumber a) for a in *v_line]
if "f " == string.sub v, 1, 2
v_line = split (v\sub 3), " "
table.insert @faces, [(tonumber a) for a in *v_line]
@width, @height = 0, 0
for v in *@vertices
@width = v[1] if v[1] > @width
@height = v[2] if v[2] > @height
move: (...) =>
d = {...}
for v in *@vertices
for i = 1, #d
v[i] += d[i]
draw: =>
love.graphics.push!
love.graphics.translate 0, 0
for p in *@faces
love.graphics.setColor @r, @g, @b
reald.graphics.triangle fov or 250, "fill", @vertices[p[1]], @vertices[p[2]], @vertices[p[3]]
love.graphics.pop!
| 27.977273 | 105 | 0.463851 |
c59bd47741c3244f2b6c2ab0195816b15e8044e8 | 10,778 | -- Copyright 2018 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
{:file_search} = howl
{:File, :Process} = howl.io
describe 'file_search', ->
local searchers, tmp_dir, config, searcher
setup ->
searchers = {name, def for name, def in pairs file_search.searchers}
for name in pairs searchers
file_search.unregister_searcher name
tmp_dir = File.tmpdir!
config = howl.config.for_file tmp_dir
teardown ->
for name in pairs file_search.searchers
file_search.unregister_searcher name
for _, def in pairs searchers
file_search.register_searcher def
tmp_dir\delete_all!
before_each ->
searcher = {
name: 'test'
description: 'test'
handler: -> {}
}
describe 'register_searcher(def)', ->
it 'raises an error for missing attributes', ->
assert.raises "name", ->
file_search.register_searcher description: 'desc', handler: ->
assert.raises "description", ->
file_search.register_searcher name: 'name', handler: ->
assert.raises "handler", ->
file_search.register_searcher name: 'test', description: 'desc'
describe 'search(directory, term, opts)', ->
before_each ->
file_search.register_searcher searcher
config.file_searcher = 'test'
context '(when the searcher returns matches directly)', ->
it 'returns matches from the specified searcher', ->
matches = {
{ path: 'urk.txt', file: tmp_dir\join('urk'), line_nr: 1, message: 'foo'}
}
searcher.handler = -> matches
res = file_search.search tmp_dir, 'foo'
assert.same matches, res
it 'raises an error if the searcher omits required match fields', ->
matches = {}
searcher.handler = -> matches
matches[1] = { line_nr: 1, message: 'foo' }
assert.raises 'path', -> file_search.search tmp_dir, 'foo'
matches[1] = { path: 'urk.txt', message: 'foo' }
assert.raises 'line_nr', -> file_search.search tmp_dir, 'foo'
matches[1] = { path: 'urk.txt', line_nr: 1 }
assert.raises 'message', -> file_search.search tmp_dir, 'foo'
it 'sets .file from path if not provided', ->
searcher.handler = -> { { path: 'urk.txt', line_nr: 1, message: 'foo'} }
res = file_search.search tmp_dir, 'foo'
assert.equal tmp_dir\join('urk.txt'), res[1].file
context '(when the searcher returns a process object)', ->
it "returns matches from the process' output", (done) ->
howl_async ->
searcher.handler = -> Process.open_pipe 'echo "file.ext:10: foo"'
res = file_search.search tmp_dir, 'foo'
assert.same {
{message: 'foo', path: 'file.ext', line_nr: 10, file: tmp_dir\join('file.ext')}
}, res
done!
context '(when the searcher returns a string)', ->
it 'returns matches from running the string as a command', (done) ->
howl_async ->
searcher.handler = -> 'echo "file.ext:10: foo"'
res = file_search.search tmp_dir, 'foo'
assert.same {
{message: 'foo', path: 'file.ext', line_nr: 10, file: tmp_dir\join('file.ext')}
}, res
done!
context '(when a search process exits with an exit code of 1)', ->
it 'return zero matches', (done) ->
howl_async ->
searcher.handler = -> 'exit 1'
res = file_search.search tmp_dir, 'foo'
assert.same {}, res
done!
context '(selecting the searcher)', ->
it 'raises an error if the specified searcher is not available', ->
searcher.is_available = -> false
assert.raises 'unavailable', -> file_search.search tmp_dir, 'foo'
it 'allows passing an explicit searcher using an explicit `searcher` table', ->
my_searcher = {
name: 'custom',
description: 'pass-directly',
handler: -> {
{ line_nr: 1, file: tmp_dir\join('my'), path: 'my', message: 'custom' }
}
}
res = file_search.search tmp_dir, 'foo', searcher: my_searcher
assert.same my_searcher.handler!, res
it 'allows passing an explicit searcher using an explicit `searcher` string', ->
my_searcher = {
name: 'my_searcher',
description: 'pass-directly',
handler: -> {
{ line_nr: 1, file: tmp_dir\join('my'), path: 'my', message: 'custom' }
}
}
file_search.register_searcher my_searcher
res = file_search.search tmp_dir, 'foo', searcher: 'my_searcher'
assert.same my_searcher.handler!, res
it 'returns matches and the used searcher', ->
matches = {}
searcher.handler = -> matches
_, used_searcher = file_search.search tmp_dir, 'foo'
assert.equal searcher, used_searcher
describe 'sort(matches, context)', ->
match = (message, path, line_nr = 1) ->
{:message, :path, :line_nr, file: tmp_dir\join(path)}
messages = (matches) -> [m.message for m in *matches]
it 'prefers standalone matches to substring matches', ->
sorted = file_search.sort {
match('a fool', 'sub1')
match('bar foo zed', 'alone')
match('food for thought', 'sub2')
}, tmp_dir, 'foo'
assert.equal 'alone', sorted[1].path
it "prefers matches where the term is included in the match's base name", ->
sorted = file_search.sort {
match('notbase', 'foo/zed.moon')
match('base', 'bar/foo.moon')
}, tmp_dir, 'foo'
assert.same {'base', 'notbase'}, messages(sorted)
it 'penalizes matches in test files', ->
sorted = file_search.sort {
match('spec', 'foo/zed_spec.moon')
match('test', 'foo/zed_test.moon')
match('specd', 'foo/zed-spec.moon')
match('testd', 'foo/zed-test.moon')
match('testp', 'foo/test_test.moon')
match('base', 'foo/zed.moon')
}, tmp_dir, 'foo'
assert.same 'base', messages(sorted)[1]
it 'groups matches by path for same-score matches', ->
sorted = file_search.sort {
match('foo', 'one.moon')
match('foo', 'two.moon')
match('bar', 'one.moon')
match('bar', 'two.moon')
}, tmp_dir, 'xxx'
assert.equal sorted[1].path, sorted[2].path
-- and it follows that 3 4 are equal
it 'always orders matches in the same file by line nr', ->
sorted = file_search.sort {
match('3', 'file.moon', 3)
match('1', 'file.moon', 1)
match('2', 'file.moon', 2)
}, tmp_dir, 'xxx'
assert.same {'1', '2', '3'}, messages(sorted)
context 'when context is provided', ->
local buffer
before_each ->
buffer = howl.Buffer!
it 'prefers matches close to the current context directory', ->
buffer.file = tmp_dir\join 'first/second/file.txt'
sorted = file_search.sort {
match('twoup', 'twoup.txt') -- distance 3
match('samedir', 'first/second/samedir.txt') -- distance 1
match('same', 'first/second/file.txt') -- distance 0
match('oneup', 'first/oneup.txt') -- distance 2
match('diffroot', 'other/otro/annan.txt') --distance 5
}, tmp_dir, 'foo', buffer\context_at(1)
assert.same {'same', 'samedir', 'oneup', 'twoup', 'diffroot'}, messages(sorted)
it 'prefers matches in files sharing the same name cluster', ->
buffer.file = tmp_dir\join 'foo.moon'
sorted = file_search.sort {
match('notsame', 'food.moon')
match('spec', 'foo_spec.moon')
match('other', 'angry/fools.moon')
}, tmp_dir, 'foo', buffer\context_at(1)
assert.same {'spec', 'notsame', 'other'}, messages(sorted)
buffer.file = tmp_dir\join 'foo_spec.moon'
sorted = file_search.sort {
match('notsame', 'food.moon')
match('main', 'foo.moon')
match('other', 'angry/fools.moon')
}, tmp_dir, 'search', buffer\context_at(1)
assert.same {'main', 'notsame', 'other'}, messages(sorted)
describe 'the native searcher', ->
local search
setup ->
search = searchers.native.handler
it 'handles multiple matches in a file correctly', ->
hit = tmp_dir\join('hit.txt')
hit.contents = ([[
food
snafoo
bafoon
]]).stripped
res = search tmp_dir, 'foo'
assert.same {
{path: 'hit.txt', line_nr: 1, column: 1, message: 'food'},
{path: 'hit.txt', line_nr: 2, column: 4, message: 'snafoo'},
{path: 'hit.txt', line_nr: 3, column: 3, message: 'bafoon'},
}, res
it 'handles a match at the end of a file, preceeding an empty line', ->
hit = tmp_dir\join('hit.txt')
hit.contents = 'foo\n'
res = search tmp_dir, 'foo'
assert.same {
{path: 'hit.txt', line_nr: 1, column: 1, message: 'foo'},
}, res
it 'is case insensitive', ->
hit = tmp_dir\join('hit.txt')
hit.contents = 'foo\nFOO'
res = search tmp_dir, 'fOo'
assert.same {
{path: 'hit.txt', line_nr: 1, column: 1, message: 'foo'},
{path: 'hit.txt', line_nr: 2, column: 1, message: 'FOO'},
}, res
it 'only reports the first match for a given line', ->
hit = tmp_dir\join('hit.txt')
hit.contents = 'in barbary there is a bar\n'
res = search tmp_dir, 'bar'
assert.same {
{
path: 'hit.txt',
line_nr: 1,
column: 4,
message: 'in barbary there is a bar'
},
}, res
it 'limits messages to the given max_message_length option', ->
hit = tmp_dir\join('hit.txt')
hit.contents = string.rep 'x', 100
res = search tmp_dir, 'x', max_message_length: 50
assert.equals 50, #res[1].message
it 'handles binary files without issue', ->
ffi = require('ffi')
bin = tmp_dir\join('bin')
data = ffi.new 'char[1024]'
for i = 0, 1023
data[i] = math.random(255)
bin.contents = ffi.string(data, 1024)
res = search tmp_dir, 'notlikely'
-- the assertion here is not super important - we mostly want to
-- check that we didn't crash here (as for instance GRegex would
-- for binary content without the RAW flag)
assert.equals 0, #res
context 'when the whole_word option is set', ->
it 'only finds whole words', ->
hit = tmp_dir\join('hit.txt')
hit.contents = ([[
bar
fubar
barred
barbary
in a bar
]]).stripped
res = search tmp_dir, 'bar', whole_word: true
assert.same {
{path: 'hit.txt', line_nr: 1, column: 1, message: 'bar'},
{path: 'hit.txt', line_nr: 5, column: 6, message: 'in a bar'},
}, res
| 34.767742 | 91 | 0.586194 |
663d0ae5ab266d004be1be682e5031aab2f24244 | 1,933 | Player = struct
x: "number"
y: "number"
real_x: "number"
real_y: "number"
speed: "number"
move_padding: "number"
key_buffer: "table"
key_limit: "number"
Player\impl
update: (dt) =>
@real_x = math.lerp @real_x, @x * SIZE, dt * @speed
@real_y = math.lerp @real_y, @y * SIZE, dt * @speed
game.camera.x = math.lerp game.camera.x, (math.floor @real_x * game.camera.zoom + SIZE), dt * game.camera.zoom
game.camera.y = math.lerp game.camera.y, (math.floor @real_y * game.camera.zoom + SIZE), dt * game.camera.zoom
for i, v in ipairs @key_buffer
if i < @key_limit
key = table.remove @key_buffer, 1
dx, dy = @key_to_direction key
@move dx, dy
with love.keyboard
if (@real_x - @x * SIZE)^2 + (@real_y - @y * SIZE)^2 < @move_padding^2
dx = 0
dy = 0
if .isDown "right"
dx = 1
if .isDown "left"
dx = -1
if .isDown "down"
dy = 1
if .isDown "up"
dy = -1
@move dx, dy
draw: =>
with love.graphics
.setColor 0, 1, 1
.rectangle "fill", @real_x, @real_y, SIZE, SIZE
.setColor 0, 0.8, 0.8
.rectangle "line", @real_x, @real_y, SIZE, SIZE
keypressed: (key) =>
keys = {
left: true
right: true
up: true
down: true
}
if keys[key]
table.insert @key_buffer, key
key_to_direction: (key) =>
dx = 0
dy = 0
switch direction
when "right"
dx = 1
when "left"
dx = -1
when "down"
dy = 1
when "up"
dy = -1
dx, dy
move: (dx, dy) =>
if game.world.level\vacant @x + dx, @y + dy
@x += dx
@y += dy
unless dx + dy == 0
game.world.level\set @x, @y, game.world.level.registry.NULL
game.world.level\set @x, @y, game.world.level.registry.PLAYER
{
:Player
} | 21.241758 | 114 | 0.515779 |
20d2fb65f6f174ceb7b492d1fff0ce8cf2232905 | 576 | System = require "lib.concord.system"
Position = require "src.components.Position"
Bounds = require "src.components.Bounds"
filter = {
Position,
Bounds
}
ScreenWrap = System filter
ScreenWrap.update = (deltaTime) =>
for _, entity in ipairs self.pool.objects
position = entity\get Position
bounds = entity\get Bounds
if position.x > bounds.right
position.x = bounds.left
if position.x < bounds.left
position.x = bounds.right
if position.y > bounds.bottom
position.y = bounds.top
if position.y < bounds.top
position.y = bounds.bottom
ScreenWrap
| 20.571429 | 44 | 0.723958 |
222ec302abc610e03124e5e897be14956f2745f6 | 5,052 | -- Copyright 2014-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
gio = require 'ljglibs.gio'
ffi = require 'ffi'
require 'ljglibs.cdefs.gio'
require 'ljglibs.gio.file_info'
require 'ljglibs.gio.file_input_stream'
require 'ljglibs.gio.file_output_stream'
core = require 'ljglibs.core'
glib = require 'ljglibs.glib'
callbacks = require 'ljglibs.callbacks'
import gc_ptr from require 'ljglibs.gobject'
{:g_string, :catch_error, :get_error} = glib
{:async_ready_callback} = gio
{:C, cast: ffi_cast} = ffi
goffset = ffi.typeof('goffset')
info_t = ffi.typeof 'GFileInfo *'
to_i = (o) -> ffi_cast info_t, o
core.define 'GFileEnumerator', {
next_file: => gc_ptr catch_error C.g_file_enumerator_next_file, @, nil
close: => catch_error C.g_file_enumerator_close, @, nil
get_child: (info) => C.g_file_enumerator_get_child @, info
next_files_async: (num_files, priority = glib.PRIORITY_DEFAULT, callback) =>
local handle
handler = (source, res) ->
callbacks.unregister handle
status, ret, err_code = get_error C.g_file_enumerator_next_files_finish, @, res
if not status
callback false, ret, err_code
else
ret\consume!
infos = [gc_ptr(to_i(i)) for i in *ret.elements]
callback true, infos
handle = callbacks.register handler, 'next-files-async'
C.g_file_enumerator_next_files_async @, num_files, priority, nil, async_ready_callback, callbacks.cast_arg(handle.id)
close_async: (priority = glib.PRIORITY_DEFAULT, callback) =>
local handle
handler = (source, res) ->
callbacks.unregister handle
status, ret, err_code = get_error C.g_file_enumerator_close_finish, @, res
if not status
callback false, ret, err_code
else
callback true
handle = callbacks.register handler, 'enumerator-close-async'
C.g_file_enumerator_close_async @, priority, nil, async_ready_callback, callbacks.cast_arg(handle.id)
}
core.define 'GFile', {
constants: {
prefix: 'G_FILE_'
'QUERY_INFO_NONE',
'QUERY_INFO_NOFOLLOW_SYMLINKS',
'COPY_NONE',
'COPY_OVERWRITE',
'COPY_BACKUP',
'COPY_NOFOLLOW_SYMLINKS',
'COPY_ALL_METADATA',
'COPY_NO_FALLBACK_FOR_MOVE',
'COPY_TARGET_DEFAULT_PERMS',
}
new_for_path: (p) -> gc_ptr C.g_file_new_for_path p
new_for_commandline_arg_and_cwd: (p, cwd) ->
assert glib.check_version 2, 36, 0
gc_ptr C.g_file_new_for_commandline_arg_and_cwd p, cwd
get_relative_path: (parent, descendant) ->
g_string C.g_file_get_relative_path parent, descendant
properties: {
path: => g_string C.g_file_get_path @
uri: => g_string C.g_file_get_uri @
exists: => C.g_file_query_exists(@, nil) != 0
parent: => gc_ptr C.g_file_get_parent @
basename: => g_string C.g_file_get_basename @
}
has_parent: (parent = nil) => C.g_file_has_parent(@, parent) != 0
query_info: (attributes, flags) =>
gc_ptr catch_error C.g_file_query_info, @, attributes, flags, nil
load_contents: =>
buf = ffi.new 'char *[1]'
catch_error C.g_file_load_contents, @, nil, buf, nil, nil
g_string buf[0]
get_child: (name) => gc_ptr C.g_file_get_child @, name
enumerate_children: (attributes, flags = @QUERY_INFO_NONE) =>
gc_ptr catch_error C.g_file_enumerate_children, @, attributes, flags, nil
enumerate_children_async: (attributes, flags = @QUERY_INFO_NONE, priority = glib.PRIORITY_DEFAULT, callback) =>
local handle
handler = (source, res) ->
callbacks.unregister handle
status, ret, err_code = get_error C.g_file_enumerate_children_finish, @, res
if not status
callback false, ret, err_code
else
callback true, ret
handle = callbacks.register handler, 'enumerate-children-async'
C.g_file_enumerate_children_async @, attributes, flags, priority, nil, async_ready_callback, callbacks.cast_arg(handle.id)
copy: (dest, flags, cancellable, progress_callback) =>
local handler, cb_handle, cb_cast, cb_data
copy_flags = core.parse_flags 'G_FILE_', flags
if progress_callback
handler = (current_bytes, total_bytes) ->
current_bytes = tonumber ffi.cast(goffset, current_bytes)
total_bytes = tonumber ffi.cast(goffset, total_bytes)
progress_callback @, current_bytes, total_bytes
cb_handle = callbacks.register handler, 'file-copy-progress'
cb_cast = ffi.cast('GFileProgressCallback', callbacks.void3)
cb_data = callbacks.cast_arg(cb_handle.id)
catch_error(C.g_file_copy, @, dest, copy_flags, cancellable, cb_cast, cb_data) != 0
make_directory: => catch_error(C.g_file_make_directory, @, nil) != 0
make_directory_with_parents: => catch_error(C.g_file_make_directory_with_parents, @, nil) != 0
delete: => catch_error(C.g_file_delete, @, nil) != 0
read: => gc_ptr catch_error(C.g_file_read, @, nil)
append_to: => gc_ptr catch_error(C.g_file_append_to, @, 0, nil)
meta: {
__tostring: (f) -> f.path or f.uri
}
}, (def, p) -> def.new_for_path p
| 33.68 | 126 | 0.70863 |
d20824315e172136fddf775e022f3b581af1d877 | 3,076 | -- base.moon
package.path ..= ""
export __ = require("moses")
export sf = sf or (string.format)
export lfs = require("lfs")
cl = lfs.currentdir()
export expand_path = (path) ->
abs_path = cl.."/"..path
package.path ..= sf ";%s/?.lua",abs_path
-------------------------------------------------------------------------------
-- Utilities
--
__genOrderedIndex = ( t ) ->
orderedIndex = {}
for key in pairs(t)
table.insert( orderedIndex, key )
table.sort( orderedIndex )
return orderedIndex
orderedNext = (t, state) ->
if state == nil
-- the first time, generate the index
t.__orderedIndex = __genOrderedIndex( t )
key = t.__orderedIndex[1]
return key, t[key]
key = nil
for i = 1,table.getn(t.__orderedIndex)
if t.__orderedIndex[i] == state
key = t.__orderedIndex[i+1]
if key
return key, t[key]
t.__orderedIndex = nil
return
export orderedPairs = (t) ->
return orderedNext, t, nil
-- _G["orderedPairs"] = orderedPairs
-- string.trim
export trim = (s) ->
return (s\gsub("^%s*(.-)%s*$", "%1"))
-- string.split
export split = (str, pat) ->
t = {}
fpat = "(.-)" .. pat
last_end = 1
s, e, cap = str\find(fpat, 1)
while s
if s != 1 or cap != ""
table.insert(t,trim(cap))
last_end = e+1
s, e, cap = str\find(fpat, last_end)
if last_end <= #str
cap = str\sub(last_end)
table.insert(t,trim(cap))
return t
-- string split... to array (table)
export split_spc = (ln) ->
vars = {}
if not string.match(ln, "^#")
for item in string.gmatch(ln,"%S+")
-- vars[]
vars[#vars+1] = item
return vars
-- string split... to array (table) pure
export split_space = (ln) ->
vars = {}
for item in string.gmatch(ln,"%S+")
-- vars[]
vars[#vars+1] = item
return vars
-- scan dir.
export scandir = (directory) ->
if unexpected_condition then error()
i, t, popen = 0, {}, io.popen
for filename in popen('ls -a '..directory)\lines()
i = i + 1
t[i] = filename
return t
--
-- array
--
export push_head = (q,v) -> table.insert(q,1,v)
export push_tail = (q,v) -> q[#q+1]=v
export pop_head = (q) ->
item=nil
if (#q>0)
item = q[1]
table.remove(q,1)
return item
export pop_tail = (q) ->
item=nil
if (#q>0)
item= q[#q]
table.remove(q,#q)
return item
--
-- files
--
-- _G["file_exist"] = (fname) ->
export file_exist = (fname) ->
f = io.open(fname,"r")
if (f!=nil)
f\close()
return true
return false
export get_file_ext = (fname) ->
va = split(fname,"[.]")
return va[#va]
export load_pages = (fpath,subpath) ->
skip=0
fpath = fpath.."/"..subpath
subpath2,fn = subpath.."."
for fn in lfs.dir(fpath)
f1 = fn\sub(1,1)
if ((fn==".") or (fn=="..") or (f1=="."))
skip = skip + 1
else
fname = fpath.."/"..fn
attr = lfs.attributes(fname)
mode = attr.mode
ext = fn\sub(-4)
if (ext==".lua")
va = fn\sub(1,(#fn-4))
require(subpath2..va)
elseif (ext=="moon")
va = fn\sub(1,(#fn-5))
-- require(subpath2..va)
| 20.506667 | 79 | 0.552016 |
4709fb9d5858629dd41fbe84b9958aa7c55ca496 | 321 | -- needed lib
template = require "resty.template"
-- our view is homepage, but included into layout
view = template.new "homepage.html", "layout.html"
-- we set title of page, and also those from homepage
view.title = "Testing lua-resty-template"
view.message = "Hello, World!"
-- let's go displaying result
view\render!
| 32.1 | 53 | 0.738318 |
2a822e6e15c718bf9441e9466745662e1d610a51 | 425 | Entity = require "lib.concord.entity"
Vector = require "src.Vector"
Position = require "src.components.Position"
Mover = require "src.components.Mover"
Sprite = require "src.components.Sprite"
Bounds = require "src.components.Bounds"
Bullet = Entity!
speed = 512
Bullet\give Position,
0, -- X
0 -- Y
Bullet\give Sprite,
"res/Lasers/laserBlue08.png"
Bullet\give Mover,
speed,
Vector speed,
0
Bullet\give Bounds
Bullet | 19.318182 | 44 | 0.743529 |
f0f18c0e3316568e1c89a904667a32866849f67c | 1,515 | export script_name = "All Characters To"
export script_description = "Converts all characters to uppercase, lowercase or capitalized."
export script_author = "Zeref"
export script_version = "1.0.3"
-- LIB
zf = require "ZF.main"
unicode.to_capitalized = (text, i = 1) ->
concat, done = "", false
for char, ci in unicode.chars text
a = tonumber char
b = zf.util\isBlank char
if not done and not a and not b
done = true
unless ci == 1 and i > 1
char = unicode.to_upper_case char
elseif char == "."
done = false
concat ..= char
return concat
splitMap = (text, fn) ->
concat = ""
with zf.tags\splitTextByTags text\gsub("\\N", "%[@%]")\gsub("\\h", "%[#%]"), false
for i = 1, #.text
concat ..= .tags[i] .. fn .text[i], i
return concat\gsub("%[@%]", "\\N")\gsub("%[#%]", "\\h")\gsub "{%s*}", ""
main = (fn) ->
(subs, selected) ->
for sel in *selected
l = subs[sel]
unless zf.util\isShape l.text\gsub "%b{}", ""
l.text = splitMap l.text, fn
subs[sel] = l
aegisub.set_undo_point script_name
aegisub.register_macro "#{script_name} / Upper-case", script_description, main unicode.to_upper_case
aegisub.register_macro "#{script_name} / Lower-case", script_description, main unicode.to_lower_case
aegisub.register_macro "#{script_name} / Capitalized", script_description, main unicode.to_capitalized | 37.875 | 102 | 0.588119 |
c31bde74f4fdf86a52f7ec7f030f6054aaf6179a | 4,641 | export *
----------------------------------
-- Layers that implement a loss. Currently these
-- are the layers that can initiate a '\backward!' pass.
-- In the future we probably want a more flexible system
-- that can accomodate multiple losses to do multi-task
-- learning, and stuff like that. But for now, one of the
-- layers in this file must be the final layer in a Net.
----------------------------------
class SoftmaxLayer
----------------------------------
-- This is a classifier, with 'N' discrete classes
-- from 1 to 'N'. It gets it stream of 'N' incoming
-- numbers and computes the softmax function.
----------------------------------
new: (opt) =>
@num_inputs = opt["in_sx"] * opt["in_sy"] * opt["in_depth"]
@out_depth = @num_inputs
@out_sx = 1
@out_sy = 1
@layer_type = "softmax"
forward: (V, is_training) =>
@in_act = V
A = Vol 1, 1, @out_depth, 0
-- mac activation
as = V.w
max_act = V.w[1]
for i = 1, @out_depth
if as[i] > max_act
max_act = as[i]
-- compute exponentials (carefully not to blow up)
@exps = util.zeros @out_depth
esum = 0
for i = 1, @out_depth
e = math.exp as[i] - max_act
esum += e
@exps[i] = e
-- normalize and output to sum to one
for i = 1, @out_depth
@exps[i] /= esum
A.w[i] = @exps[i]
@es = es
@out_act = A
@out_act
backward: (y) =>
-- compute and accumulate gradient w.r.t. weights and bias of this layer
x = @in_act
x.dw = util.zeros #x.w
for i = 1, @out_depth
indicator = 0
if i == y
indicator = 1
mul = -(indicator - @exps[i])
x.dw[i] = mul
-math.log @exps[y]
get_params_and_grads: =>
{}
to_JSON: =>
{
["out_depth"]: @out_depth,
["out_sx"]: @out_sx,
["out_sy"]: @out_sy,
["layer_type"]: @layer_type,
["num_inputs"]: @num_inputs,
}
from_JSON: (json) =>
@out_depth = json["out_depth"]
@out_sx = json["out_sx"]
@out_sy = json["out_sy"]
@layer_type = json["layer_type"]
@num_inputs = json["num_inputs"]
class RegressionLayer
----------------------------------
-- Implements an 'L2' regression cost layer,
-- so penalizes 'sum_i(||x_i - y_i||^2)', where 'x' is its input
-- and 'y' is the user-provided array of supervising values.
----------------------------------
new: (opt) =>
@num_inputs = opt["in_sx"] * opt["in_sy"] * opt["in_depth"]
@out_sx = 1
@out_sy = 1
@out_depth = @num_inputs
@layer_type = "regression"
forward: (V, is_training) =>
@in_act = V
@out_act = V
V
backward: (y) =>
----------------------------------
-- 'y' is a list of size 'num_inputs'
-- compute and accumulate gradient w.r.t. weights and bias
-- - of this layer.
----------------------------------
x = @in_act
x.dw = util.zeros #x.w
loss = 0
if y["dim"] == nil and y["val"] == nil
for i = 1, @out_depth
dy = x.w[i] - y[i]
x.dw[i] = dy
loss += 2 * dy^2
else
i = y["dim"]
y_i = y["val"]
dy = x.w[i] - y_i
x.dw[i] = dy
loss += 2 * dy^2
loss
get_params_and_grads: =>
{}
to_JSON: =>
{
["out_depth"]: @out_depth,
["out_sx"]: @out_sx,
["out_sy"]: @out_sy,
["layer_type"]: @layer_type,
["num_inputs"]: @num_inputs,
}
from_JSON: (json) =>
@out_depth = json["out_depth"]
@out_sx = json["out_sx"]
@out_sy = json["out_sy"]
@layer_type = json["layer_type"]
@num_inputs = json["num_inputs"]
class SVMLayer
new: (opt) =>
@num_inputs = opt["in_sx"] * opt["in_sy"] * opt["in_depth"]
@out_depth = opt["out_depth"]
@out_sx = 1
@out_sy = 1
@layer_type = "svm"
forward: (V, is_training) =>
@in_act = V
@out_act = V
V
backward: (V) =>
-- compute and accumulate gradient w.r.t. weights and bias of this layer
x = @in_act
x.dw = util.zeros #x.w
y_score = x.w[y]
margin = 1
loss = 0
for i = 1, @out_depth
if -y_score + x.w[i] + margin > 0
-- 'hinge loss'
x.dw[i] += 1
x.dw[y] -= 1
loss += -y_score + x.w[i] + margin
loss
get_params_and_grads: =>
{}
to_JSON: =>
{
["out_depth"]: @out_depth,
["out_sx"]: @out_sx,
["out_sy"]: @out_sy,
["layer_type"]: @layer_type,
["num_inputs"]: @num_inputs,
}
from_JSON: (json) =>
@out_depth = json["out_depth"]
@out_sx = json["out_sx"]
@out_sy = json["out_sy"]
@layer_type = json["layer_type"]
@num_inputs = json["num_inputs"]
| 23.678571 | 76 | 0.516268 |
caea6e9d8deb4a86b447c351ee7e6295984a31ca | 1,565 | -- include using:
-- @include "widgets.utils"
class WidgetUtils
output_errors: =>
if @errors and #@errors > 0
div class: "alert alert-danger", role: "alert", ->
ul -> for err in *@errors do li err
write_csrf_input: =>
input type: "hidden", name: "csrf_token", value: @csrf_token, ["aria-hidden"]: "true"
write_pagination_nav: (url, pages, current_page, post, get={}) =>
old_get = get.page
nav -> ul class: "pagination", ->
get.page = current_page - 1
-- This is the left arrow
li class: "page-item", -> a class: "page-link", ["aria-label"]: "Previous", href: @url_for(url, post, get), ->
span ["aria-hidden"]: "true", -> raw "«"
span class: "sr-only", "Previous"
for page = math.max(1, current_page-5), math.min(pages-1, current_page+4)
active_class = "page-item " .. (if current_page == page then "active" else "")
get.page = page
li class: active_class, -> a class: "page-link", href: @url_for(url, post, get), page
li class: "page-item disabled", -> span class: "page-link", "..."
get.page = pages
active_class = "page-item " .. (if current_page == pages then "active" else "")
li class: active_class, -> a class: "page-link", href: @url_for(url, post, get), pages
get.page = current_page + 1
-- This is the right arrow
li class: "page-item", -> a class: "page-link", ["aria-label"]: "Next", href: @url_for(url, post, get), ->
span ["aria-hidden"]: "true", -> raw "»"
span class: "sr-only", "Next"
get.page = old_get | 38.170732 | 114 | 0.602556 |
64518866c3ffa581ede2f1ff2fef43839b18c001 | 544 | astronomy = require "astronomy"
cqueues = require "cqueues"
Logger = require "logger"
Logger.print "Test: astronomy.attach"
base_table = {}
astronomy\attach coroutine.create ->
cqueues.sleep 0.005
for i=1, 2 do
table.insert base_table, 'A'
cqueues.sleep 0.01
astronomy\attach coroutine.create ->
for i=1, 2 do
table.insert base_table, 'B'
cqueues.sleep 0.01
assert astronomy\loop!
result_table = {
'B'
'A'
'B'
'A'
}
for k, v in pairs base_table
Logger.print "#{v} == #{result_table[k]}"
assert v == result_table[k]
| 17 | 42 | 0.685662 |
68e836cb0059e6f2d190845c9282af6dabcc300a | 428 | import print from _G
-- ::DEPRECATION_FEATURE_KEYS -> table
-- Represents the features that were already deprecated
--
DEPRECATION_FEATURE_KEYS = {}
-- ::deprecate(string featureKey, string text) -> void
-- Prints the deprecation text once per feature key
-- export
export deprecate = (featureKey, text) ->
unless DEPRECATION_FEATURE_KEYS[featureKey]
print(text)
DEPRECATION_FEATURE_KEYS[featureKey] = true | 30.571429 | 55 | 0.742991 |
c819839c76fcf0517636a0d9f24343d2f3273fe9 | 25,556 |
-- 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 = 'Your DirectX™ level is too low. At least 9.0 is required. If you use 8.1 for framerate,\nyou either have the most ancient videocard or have bad drivers.\nBecause framerate in gmod can only be low because of other addons which create pointless high CPU load.\nYes, this message will appear several times to annoy you. Because WHY THE FK YOU THEN REPORT ABOUT MISSING TEXTURES???'
gui.ppm2.dxlevel.toolow = 'DirectX™ level is too low for PPM/2'
gui.ppm2.editor.eyes.separate = 'Use separated settings for eyes'
gui.ppm2.editor.eyes.url = 'Eye URL texture'
gui.ppm2.editor.eyes.url_desc = 'When uring eye URL texture; options below have no effect'
gui.ppm2.editor.eyes.lightwarp_desc = 'Lightwarp has effect only on EyeRefract eyes'
gui.ppm2.editor.eyes.lightwarp = "Lightwarp"
gui.ppm2.editor.eyes.desc1 = "Lightwarp texture URL input\nIt must be 256x16!"
gui.ppm2.editor.eyes.desc2 = "Glossiness strength\nThis parameters adjucts strength of real time reflections on eye\nTo see changes, set ppm2_cl_reflections convar to 1\nOther players would see reflections only with ppm2_cl_reflections set to 1\n0 - is matted; 1 - is mirror"
for _, {tprefix, prefix} in ipairs {{'def', ''}, {'left', 'Left '}, {'right', 'Right '}}
gui.ppm2.editor.eyes[tprefix].lightwarp.shader = "#{prefix}Use EyeRefract shader"
gui.ppm2.editor.eyes[tprefix].lightwarp.cornera = "#{prefix}Use Eye Cornera diffuse"
gui.ppm2.editor.eyes[tprefix].lightwarp.glossiness = "#{prefix}Glossiness"
gui.ppm2.editor.eyes[tprefix].type = "#{prefix}Eye type"
gui.ppm2.editor.eyes[tprefix].reflection_type = "#{prefix}Eye reflection type"
gui.ppm2.editor.eyes[tprefix].lines = "#{prefix}Eye lines"
gui.ppm2.editor.eyes[tprefix].derp = "#{prefix}Derp eye"
gui.ppm2.editor.eyes[tprefix].derp_strength = "#{prefix}Derp eye strength"
gui.ppm2.editor.eyes[tprefix].iris_size = "#{prefix}Eye size"
gui.ppm2.editor.eyes[tprefix].points_inside = "#{prefix}Eye lines points inside"
gui.ppm2.editor.eyes[tprefix].width = "#{prefix}Eye width"
gui.ppm2.editor.eyes[tprefix].height = "#{prefix}Eye height"
gui.ppm2.editor.eyes[tprefix].pupil.width = "#{prefix}Pupil width"
gui.ppm2.editor.eyes[tprefix].pupil.height = "#{prefix}Pupil height"
gui.ppm2.editor.eyes[tprefix].pupil.size = "#{prefix}Pupil size"
gui.ppm2.editor.eyes[tprefix].pupil.shift_x = "#{prefix}Pupil Shift X"
gui.ppm2.editor.eyes[tprefix].pupil.shift_y = "#{prefix}Pupil Shift Y"
gui.ppm2.editor.eyes[tprefix].pupil.rotation = "#{prefix}Eye rotation"
gui.ppm2.editor.eyes[tprefix].background = "#{prefix}Eye background"
gui.ppm2.editor.eyes[tprefix].pupil_size = "#{prefix}Pupil"
gui.ppm2.editor.eyes[tprefix].top_iris = "#{prefix}Top eye iris"
gui.ppm2.editor.eyes[tprefix].bottom_iris = "#{prefix}Bottom eye iris"
gui.ppm2.editor.eyes[tprefix].line1 = "#{prefix}Eye line 1"
gui.ppm2.editor.eyes[tprefix].line2 = "#{prefix}Eye line 2"
gui.ppm2.editor.eyes[tprefix].reflection = "#{prefix}Eye reflection effect"
gui.ppm2.editor.eyes[tprefix].effect = "#{prefix}Eye 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 (unsaved changes!)'
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\nData value: %q'
gui.ppm2.editor.generic.url = '%s\n\nLink goes to: %s'
gui.ppm2.editor.generic.url_field = 'URL Field'
gui.ppm2.editor.generic.spoiler = 'Mysterious spoiler'
gui.ppm2.editor.generic.restart.needed = 'Editor restart required'
gui.ppm2.editor.generic.restart.text = 'You should restart editor for applying change.\nRestart now?\nUnsaved data will lost!'
gui.ppm2.editor.generic.fullbright = 'Fullbright'
gui.ppm2.editor.generic.wtf = 'For some reason, your player has no NetworkedPonyData - Nothing to edit!\nTry ppm2_reload in your console and try to open editor again'
gui.ppm2.editor.io.random = 'Randomize!'
gui.ppm2.editor.io.newfile.title = 'New File'
gui.ppm2.editor.io.newfile.confirm = 'Really want to create a new file?'
gui.ppm2.editor.io.newfile.toptext = 'Reset'
gui.ppm2.editor.io.delete.confirm = 'Do you really want to delete that file?\nIt will be gone forever!\n(a long time!)'
gui.ppm2.editor.io.delete.title = 'Really Delete?'
gui.ppm2.editor.io.filename = 'Filename'
gui.ppm2.editor.io.hint = 'Open file by double click'
gui.ppm2.editor.io.reload = 'Reload file list'
gui.ppm2.editor.io.failed = 'Failed to import.'
gui.ppm2.editor.io.warn.oldfile = '!!! It may or may not work. You will be squished.'
gui.ppm2.editor.io.warn.text = "Currently, you did not stated your changes.\nDo you really want to open another file?"
gui.ppm2.editor.io.warn.header = 'Unsaved changes!'
gui.ppm2.editor.io.save.button = 'Save'
gui.ppm2.editor.io.save.text = 'Enter file name without ppm2/ and .dat\nTip: to save as autoload, type "_current" (without quotes)'
gui.ppm2.editor.io.wear = 'Apply changes (wear)'
gui.ppm2.editor.seq.standing = 'Standing'
gui.ppm2.editor.seq.move = 'Moving'
gui.ppm2.editor.seq.walk = 'Walking'
gui.ppm2.editor.seq.sit = 'Sit'
gui.ppm2.editor.seq.swim = 'Swim'
gui.ppm2.editor.seq.run = 'Run'
gui.ppm2.editor.seq.duckwalk = 'Crouch walk'
gui.ppm2.editor.seq.duck = 'Crouch'
gui.ppm2.editor.seq.jump = 'Jump'
gui.ppm2.editor.misc.race = 'Race'
gui.ppm2.editor.misc.weight = 'Weight'
gui.ppm2.editor.misc.size = 'Pony Size'
gui.ppm2.editor.misc.hide_weapons = 'Should hide weapons'
gui.ppm2.editor.misc.chest = 'Male chest buff'
gui.ppm2.editor.misc.gender = 'Gender'
gui.ppm2.editor.misc.wings = 'Wings Type'
gui.ppm2.editor.misc.flexes = 'Flexes controls'
gui.ppm2.editor.misc.no_flexes2 = 'No flexes on new model'
gui.ppm2.editor.misc.no_flexes_desc = 'You can disable separately any flex state controller\nSo these flexes can be modified with third-party addons (like PAC3)'
gui.ppm2.editor.misc.hide_pac3 = 'Hide entitites when using PAC3 entity'
gui.ppm2.editor.misc.hide_mane = 'Hide mane when using PAC3 entity'
gui.ppm2.editor.misc.hide_tail = 'Hide tail when using PAC3 entity'
gui.ppm2.editor.misc.hide_socks = 'Hide socks when using PAC3 entity'
gui.ppm2.editor.tabs.main = 'General'
gui.ppm2.editor.tabs.files = 'Files'
gui.ppm2.editor.tabs.old_files = 'Old Files'
gui.ppm2.editor.tabs.cutiemark = 'Cutiemark'
gui.ppm2.editor.tabs.head = 'Head anatomy'
gui.ppm2.editor.tabs.eyes = 'Eyes'
gui.ppm2.editor.tabs.face = 'Face'
gui.ppm2.editor.tabs.mouth = 'Mouth'
gui.ppm2.editor.tabs.left_eye = 'Left Eye'
gui.ppm2.editor.tabs.right_eye = 'Right Eye'
gui.ppm2.editor.tabs.mane_horn = 'Mane and Horn'
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 Separated Details'
gui.ppm2.editor.tabs.ears = 'Ears'
gui.ppm2.editor.tabs.horn = 'Horn'
gui.ppm2.editor.tabs.back = 'Back'
gui.ppm2.editor.tabs.wings = 'Wings'
gui.ppm2.editor.tabs.left = 'Left'
gui.ppm2.editor.tabs.right = 'Right'
gui.ppm2.editor.tabs.neck = 'Neck'
gui.ppm2.editor.tabs.body = 'Pony body'
gui.ppm2.editor.tabs.tattoos = 'Tattoos'
gui.ppm2.editor.tabs.tail = 'Tail'
gui.ppm2.editor.tabs.hooves = 'Hooves anatomy'
gui.ppm2.editor.tabs.bottom_hoof = 'Bottom hoof'
gui.ppm2.editor.tabs.legs = 'Legs'
gui.ppm2.editor.tabs.socks = 'Socks'
gui.ppm2.editor.tabs.newsocks = 'New Socks'
gui.ppm2.editor.tabs.about = 'About'
gui.ppm2.editor.tabs.clothes = 'Clothes'
gui.ppm2.editor.old_tabs.mane_tail = 'Mane and tail'
gui.ppm2.editor.old_tabs.wings_and_horn_details = 'Wings and horn details'
gui.ppm2.editor.old_tabs.wings_and_horn = 'Wings and horn'
gui.ppm2.editor.old_tabs.body_details = 'Body details'
gui.ppm2.editor.old_tabs.mane_tail_detals = 'Mane and tail URL details'
gui.ppm2.editor.cutiemark.display = 'Display cutiemark'
gui.ppm2.editor.cutiemark.type = 'Cutiemark type'
gui.ppm2.editor.cutiemark.size = 'Cutiemark size'
gui.ppm2.editor.cutiemark.color = 'Cutiemark color'
gui.ppm2.editor.cutiemark.input = 'Cutiemark URL image input field\nShould be PNG or JPEG (works same as\nPAC3 URL texture)'
gui.ppm2.editor.face.eyelashes = 'Eyelashes'
gui.ppm2.editor.face.eyelashes_color = 'Eyelashes Color'
gui.ppm2.editor.face.eyelashes_phong = 'Eyelashes phong parameters'
gui.ppm2.editor.face.eyebrows_color = 'Eyebrows Color'
gui.ppm2.editor.face.new_muzzle = 'Use new muzzle for male model'
gui.ppm2.editor.face.nose = 'Nose Color'
gui.ppm2.editor.face.lips = 'Lips Color'
gui.ppm2.editor.face.eyelashes_separate_phong = 'Separate Eyelashes Phong'
gui.ppm2.editor.face.eyebrows_glow = 'Glowing eyebrows'
gui.ppm2.editor.face.eyebrows_glow_strength = 'Eyebrows glow strength'
gui.ppm2.editor.face.inherit.lips = 'Inherit Lips Color from body'
gui.ppm2.editor.face.inherit.nose = 'Inherit Nose Color from body'
gui.ppm2.editor.mouth.fangs = 'Fangs'
gui.ppm2.editor.mouth.alt_fangs = 'Alternative Fangs'
gui.ppm2.editor.mouth.claw = 'Claw teeth'
gui.ppm2.editor.mouth.teeth = 'Teeth color'
gui.ppm2.editor.mouth.teeth_phong = 'Teeth phong parameters'
gui.ppm2.editor.mouth.mouth = 'Mouth color'
gui.ppm2.editor.mouth.mouth_phong = 'Mouth phong parameters'
gui.ppm2.editor.mouth.tongue = 'Tongue color'
gui.ppm2.editor.mouth.tongue_phong = 'Tongue phong parameters'
gui.ppm2.editor.mane.type = 'Mane Type'
gui.ppm2.editor.mane.phong = 'Separate mane phong settings from body'
gui.ppm2.editor.mane.mane_phong = 'Mane phong parameters'
gui.ppm2.editor.mane.phong_sep = 'Separate upper and lower mane colors'
gui.ppm2.editor.mane.up.phong = 'Upper Mane Phong Settings'
gui.ppm2.editor.mane.down.type = 'Lower Mane Type'
gui.ppm2.editor.mane.down.phong = 'Lower Mane Phong Settings'
gui.ppm2.editor.mane.newnotice = 'Next options have effect only on new model'
for i = 1, 2
gui.ppm2.editor.mane['color' .. i] = "Mane color #{i}"
gui.ppm2.editor.mane.up['color' .. i] = "Upper mane color #{i}"
gui.ppm2.editor.mane.down['color' .. i] = "Lower mane color #{i}"
for i = 1, 6
gui.ppm2.editor.mane['detail_color' .. i] = "Mane detail color #{i}"
gui.ppm2.editor.mane.up['detail_color' .. i] = "Upper mane color #{i}"
gui.ppm2.editor.mane.down['detail_color' .. i] = "Lower mane color #{i}"
gui.ppm2.editor.url_mane['desc' .. i] = "Mane URL Detail #{i} input field"
gui.ppm2.editor.url_mane['color' .. i] = "Mane URL detail color #{i}"
gui.ppm2.editor.url_tail['desc' .. i] = "Tail URL Detail #{i} input field"
gui.ppm2.editor.url_tail['color' .. i] = "Tail URL detail color #{i}"
gui.ppm2.editor.url_mane.sep.up['desc' .. i] = "Upper mane URL Detail #{i} input field"
gui.ppm2.editor.url_mane.sep.up['color' .. i] = "Upper Mane URL detail color #{i}"
gui.ppm2.editor.url_mane.sep.down['desc' .. i] = "Lower mane URL Detail #{i} input field"
gui.ppm2.editor.url_mane.sep.down['color' .. i] = "Lower Mane URL detail color #{i}"
gui.ppm2.editor.ears.bat = 'Bat pony ears'
gui.ppm2.editor.ears.size = 'Ears size'
gui.ppm2.editor.clothes.head = 'Head clothes'
gui.ppm2.editor.clothes.eye = 'Eye(s) clothes'
gui.ppm2.editor.clothes.neck = 'Neck clothes'
gui.ppm2.editor.clothes.body = 'Body clothes'
gui.ppm2.editor.clothes_col.help = 'Some of color pickers may not for some clothes'
gui.ppm2.editor.clothes_col.head_use = 'Custom head clothes color'
gui.ppm2.editor.clothes_col.eye_use = 'Custom eye(s) clothes color'
gui.ppm2.editor.clothes_col.neck_use = 'Custom neck clothes color'
gui.ppm2.editor.clothes_col.body_use = 'Custom body clothes color'
for {internal, publicName} in *{{'head', 'Head'}, {'neck', 'Neck'}, {'body', 'Body'}, {'eye', 'Eye'}}
for i = 1, PPM2.MAX_CLOTHES_COLORS
gui.ppm2.editor.clothes[internal .. '_url' .. i] = string.format('%s clothes URL material %d', publicName, i)
for i = 1, PPM2.MAX_CLOTHES_COLORS
gui.ppm2.editor.clothes_col["head_#{i}"] = 'Head clothes color №' .. i
gui.ppm2.editor.clothes_col["eye_#{i}"] = 'Eye(s) clothes color №' .. i
gui.ppm2.editor.clothes_col["neck_#{i}"] = 'Neck clothes color №' .. i
gui.ppm2.editor.clothes_col["body_#{i}"] = 'Body clothes color №' .. i
gui.ppm2.editor.horn.detail_color = 'Horn detail color'
gui.ppm2.editor.horn.glowing_detail = 'Glowing Horn Detail'
gui.ppm2.editor.horn.glow_strength = 'Horn Glow Strength'
gui.ppm2.editor.horn.separate_color = 'Separate horn color from body'
gui.ppm2.editor.horn.color = 'Horn color'
gui.ppm2.editor.horn.horn_phong = 'Horn phong parameters'
gui.ppm2.editor.horn.magic = 'Horn magic color'
gui.ppm2.editor.horn.separate_magic_color = 'Separate magic color from eye color'
gui.ppm2.editor.horn.separate = 'Separate horn color from body'
gui.ppm2.editor.horn.separate_phong = 'Separate horn phong settings from body'
gui.ppm2.editor.horn.use_new = 'Use new horn'
gui.ppm2.editor.horn.new_type = 'New horn type'
for i = 1, 3
gui.ppm2.editor.horn.detail['desc' .. i] = "Horn URL detail #{i}"
gui.ppm2.editor.horn.detail['color' .. i] = "URL Detail color #{i}"
gui.ppm2.editor.wings.separate_color = 'Separate wings color from body'
gui.ppm2.editor.wings.color = 'Wings color'
gui.ppm2.editor.wings.wings_phong = 'Wings phong parameters'
gui.ppm2.editor.wings.separate = 'Separate wings color from body'
gui.ppm2.editor.wings.separate_phong = 'Separate wings phong settings from body'
gui.ppm2.editor.wings.bat_color = 'Bat Wings color'
gui.ppm2.editor.wings.bat_skin_color = 'Bat Wings skin color'
gui.ppm2.editor.wings.bat_skin_phong = 'Bat wings skin phong parameters'
gui.ppm2.editor.wings.normal = 'Normal wings'
gui.ppm2.editor.wings.bat = 'Bat wings'
gui.ppm2.editor.wings.bat_skin = 'Bat wings skin'
gui.ppm2.editor.wings.left.size = 'Left wing size'
gui.ppm2.editor.wings.left.fwd = 'Left Wing Forward'
gui.ppm2.editor.wings.left.up = 'Left Wing Up'
gui.ppm2.editor.wings.left.inside = 'Left Wing Inside'
gui.ppm2.editor.wings.right.size = 'Right wing size'
gui.ppm2.editor.wings.right.fwd = 'Right Wing Forward'
gui.ppm2.editor.wings.right.up = 'Right Wing Up'
gui.ppm2.editor.wings.right.inside = 'Right Wing Inside'
for i = 1, 3
gui.ppm2.editor.wings.details.def['detail' .. i] = "Wings URL detail #{i}"
gui.ppm2.editor.wings.details.def['color' .. i] = "URL Detail color #{i}"
gui.ppm2.editor.wings.details.bat['detail' .. i] = "Bat wing URL detail #{i}"
gui.ppm2.editor.wings.details.bat['color' .. i] = "Bat wing URL Detail color #{i}"
gui.ppm2.editor.wings.details.batskin['detail' .. i] = "Bat wing skin URL detail #{i}"
gui.ppm2.editor.wings.details.batskin['color' .. i] = "Bat wing skin URL Detail color #{i}"
gui.ppm2.editor.neck.height = 'Neck height'
gui.ppm2.editor.body.suit = 'Bodysuit'
gui.ppm2.editor.body.color = 'Body color'
gui.ppm2.editor.body.body_phong = 'Body phong parameters'
gui.ppm2.editor.body.spine_length = 'Spine length'
gui.ppm2.editor.body.url_desc = 'Body detail URL image input fields\nShould be PNG or JPEG (works same as\nPAC3 URL texture)'
gui.ppm2.editor.body.disable_hoofsteps = 'Disable hoofsteps'
gui.ppm2.editor.body.disable_wander_sounds = 'Disable wander sounds'
gui.ppm2.editor.body.disable_new_step_sounds = 'Disable custom step sounds'
gui.ppm2.editor.body.disable_jump_sound = 'Disable jump sound'
gui.ppm2.editor.body.disable_falldown_sound = 'Disable falldown sound'
gui.ppm2.editor.body.call_playerfootstep = 'Call PlayerFootstep on each sound'
gui.ppm2.editor.body.call_playerfootstep_desc = 'Call PlayerFootstep hook on each actual sound you hear.\nUsing this option will allow other addons installed to rely on PPM2\'s immersion\nwhich listen PlayerFootstep hook. This should be disabled only when you get unreliable result from other addons\nor your FPS drop to low values since one of addons installed is badly coded.'
for i = 1, PPM2.MAX_BODY_DETAILS
gui.ppm2.editor.body.detail['desc' .. i] = "Detail #{i}"
gui.ppm2.editor.body.detail['color' .. i] = "Detail color #{i}"
gui.ppm2.editor.body.detail['glow' .. i] = "Detail #{i} is glowing"
gui.ppm2.editor.body.detail['glow_strength' .. i] = "Detail #{i} glow strength"
gui.ppm2.editor.body.detail.url['desc' .. i] = "Detail #{i}"
gui.ppm2.editor.body.detail.url['color' .. i] = "Detail color #{i}"
gui.ppm2.editor.tattoo.edit_keyboard = 'Edit using keyboard'
gui.ppm2.editor.tattoo.type = 'Type'
gui.ppm2.editor.tattoo.over = 'Tattoo over body details'
gui.ppm2.editor.tattoo.glow = 'Tattoo is glowing'
gui.ppm2.editor.tattoo.glow_strength = 'Tattoo glow strength'
gui.ppm2.editor.tattoo.color = 'Color of Tattoo'
gui.ppm2.editor.tattoo.tweak.rotate = 'Rotation'
gui.ppm2.editor.tattoo.tweak.x = 'X Position'
gui.ppm2.editor.tattoo.tweak.y = 'Y Position'
gui.ppm2.editor.tattoo.tweak.width = 'Width Scale'
gui.ppm2.editor.tattoo.tweak.height = 'Height Scale'
for i = 1, PPM2.MAX_TATTOOS
gui.ppm2.editor.tattoo['layer' .. i] = "Tattoo layer #{i}"
gui.ppm2.editor.tail.type = 'Tail type'
gui.ppm2.editor.tail.size = 'Tail size'
gui.ppm2.editor.tail.tail_phong = 'Tail phong parameters'
gui.ppm2.editor.tail.separate = 'Separate tail phong settings from body'
for i = 1, 2
gui.ppm2.editor.tail['color' .. i] = 'Tail color ' .. i
for i = 1, 6
gui.ppm2.editor.tail['detail' .. i] = "Tail detail color #{i}"
gui.ppm2.editor.tail.url['detail' .. i] = "Tail URL detail #{i}"
gui.ppm2.editor.tail.url['color' .. i] = "Tail URL detail #{i}"
gui.ppm2.editor.hoof.fluffers = 'Hoof Fluffers'
gui.ppm2.editor.legs.height = 'Legs height'
gui.ppm2.editor.legs.socks.simple = 'Socks (simple texture)'
gui.ppm2.editor.legs.socks.model = 'Socks (as model)'
gui.ppm2.editor.legs.socks.color = 'Socks model color'
gui.ppm2.editor.legs.socks.socks_phong = 'Socks phong parameters'
gui.ppm2.editor.legs.socks.texture = 'Socks Texture'
gui.ppm2.editor.legs.socks.url_texture = 'Socks URL texture'
for i = 1, 6
gui.ppm2.editor.legs.socks['color' .. i] = 'Socks detail color ' .. i
gui.ppm2.editor.legs.newsocks.model = 'Socks (as new model)'
for i = 1, 3
gui.ppm2.editor.legs.newsocks['color' .. i] = 'New Socks color ' .. i
gui.ppm2.editor.legs.newsocks.url = 'New Socks URL texture'
-- shared editor stuffs
gui.ppm2.editor.tattoo.help = "To exit edit mode, press Escape or click anywhere with mouse
To move tatto use WASD
To Scale higher/lower use Up/Down arrows
To Scale wider/smaller use Right/Left arrows
To rotate left/right use Q/E"
gui.ppm2.editor.reset_value = 'Reset %s'
gui.ppm2.editor.phong.info = 'More info about Phong on wiki'
gui.ppm2.editor.phong.exponent = 'Phong Exponent - how strong reflective property\nof pony skin is\nSet near zero to get robotic looking of your\npony skin'
gui.ppm2.editor.phong.exponent_text = 'Phong Exponent'
gui.ppm2.editor.phong.boost.title = 'Phong Boost - multiplies specular map reflections'
gui.ppm2.editor.phong.boost.boost = 'Phong Boost'
gui.ppm2.editor.phong.tint.title = 'Tint color - what colors does reflect specular map\nWhite - Reflects all colors\n(In white room - white specular map)'
gui.ppm2.editor.phong.tint.tint = 'Tint color'
gui.ppm2.editor.phong.frensel.front.title = 'Phong Front - Fresnel 0 degree reflection angle multiplier'
gui.ppm2.editor.phong.frensel.front.front = 'Phong Front'
gui.ppm2.editor.phong.frensel.middle.title = 'Phong Middle - Fresnel 45 degree reflection angle multiplier'
gui.ppm2.editor.phong.frensel.middle.front = 'Phong Middle'
gui.ppm2.editor.phong.frensel.sliding.title = 'Phong Sliding - Fresnel 90 degree reflection angle multiplier'
gui.ppm2.editor.phong.frensel.sliding.front = 'Phong Sliding'
gui.ppm2.editor.phong.lightwarp = 'Lightwarp'
gui.ppm2.editor.phong.url_lightwarp = 'Lightwarp texture URL input\nIt must be 256x16!'
gui.ppm2.editor.phong.bumpmap = 'Bumpmap URL input'
gui.ppm2.editor.info.discord = "Join DBot's Discord!"
gui.ppm2.editor.info.ponyscape = "PPM/2 is a Ponyscape project"
gui.ppm2.editor.info.creator = "PPM/2 were created and being developed by DBot"
gui.ppm2.editor.info.newmodels = "New models were created by Durpy"
gui.ppm2.editor.info.cppmmodels = "CPPM Models (including pony hands) belong to UnkN', 'http://steamcommunity.com/profiles/76561198084938735"
gui.ppm2.editor.info.oldmodels = "Old models belong to Scentus and others"
gui.ppm2.editor.info.bugs = "Found a bug? Report here!"
gui.ppm2.editor.info.sources = "You can find sources here"
gui.ppm2.editor.info.githubsources = "Or on GitHub mirror"
gui.ppm2.editor.info.thanks = "Special thanks to everypony who criticized,\nhelped and tested PPM/2!"
-- other stuff
info.ppm2.fly.pegasus = 'You need to be a Pegasus or an Alicorn to fly!'
info.ppm2.fly.cannot = 'You can not %s right now.'
gui.ppm2.emotes.sad = 'Sad'
gui.ppm2.emotes.wild = 'Wild'
gui.ppm2.emotes.grin = 'Grin'
gui.ppm2.emotes.angry = 'Angry'
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 = 'Lips lick'
gui.ppm2.emotes.scrunch = 'Scrunch'
gui.ppm2.emotes.sorry = 'Sorry'
gui.ppm2.emotes.wink = 'Wink'
gui.ppm2.emotes.right_wink = 'Right Wink'
gui.ppm2.emotes.licking = 'Licking'
gui.ppm2.emotes.suggestive_lips = 'Suggestive Lips lick'
gui.ppm2.emotes.suggestive_no_tongue = 'Suggestive w/o tongue'
gui.ppm2.emotes.gulp = 'Gulp'
gui.ppm2.emotes.blah = 'Blah blah blah'
gui.ppm2.emotes.happi = 'Happi'
gui.ppm2.emotes.happi_grin = 'Happi grin'
gui.ppm2.emotes.duck = 'DUCK'
gui.ppm2.emotes.ducks = 'DUCK INSANITY'
gui.ppm2.emotes.quack = 'QUACKS'
gui.ppm2.emotes.suggestive = 'Suggestive w/ tongue'
message.ppm2.emotes.invalid = 'No such emotion with ID: %s'
gui.ppm2.editor.intro.text = "Welcome to my new... Robosurgeon for Ponies! It allows you to....\n" ..
"hmmm... become a pony, and yes, this process is IRREVERSIBLE! But don't need worry,\n" ..
"you won't loose any of your brain cells before, in, and after then operation, because it performs operation very gently...\n\n" ..
"Actually i have no idea, you biological being! His mechanical hands will envelop you in the most tight hugs you ever get!\n" ..
"And, please, don't die in process, because this would cause VOID OF YOUR LIFE WARRANTY... and you will not be a pony!\n" ..
"----\n\n\n" ..
"Caution: Do not disassemble Robosurgeon.\nDo not put your hands/hooves into moving parts of Robosurgeon.\n" ..
"Do not poweroff it while it operates.\nDo not try to resist it's actions.\n" ..
"Always be gently with Robosurgeon\n" ..
"Never slap Robosurgeon onto his interface.\n" ..
"DBot's DLibCo take no responsibility for any harm caused by wrong usage of Robosurgeon.\n" ..
"Warranty is voided if user die.\n" ..
"No refunds."
gui.ppm2.editor.intro.title = 'Welcome here, Human!'
gui.ppm2.editor.intro.okay = "Ok, i will never read this license anyway"
message.ppm2.debug.race_condition = 'Received NetworkedPonyData before entity were created on client! Waiting...'
gui.ppm2.spawnmenu.newmodel = 'Spawn new model'
gui.ppm2.spawnmenu.newmodelnj = 'Spawn new nj model'
gui.ppm2.spawnmenu.oldmodel = 'Spawn old model'
gui.ppm2.spawnmenu.oldmodelnj = 'Spawn old nj model'
gui.ppm2.spawnmenu.cppmmodel = 'Spawn CPPM model'
gui.ppm2.spawnmenu.cppmmodelnj = 'Spawn CPPM nj model'
gui.ppm2.spawnmenu.cleanup = 'Cleanup unused models'
gui.ppm2.spawnmenu.reload = 'Reload local data'
gui.ppm2.spawnmenu.require = 'Require data from server'
gui.ppm2.spawnmenu.drawhooves = 'Draw hooves as hands'
gui.ppm2.spawnmenu.nohoofsounds = 'No hoofsounds'
gui.ppm2.spawnmenu.noflexes = 'Disable flexes (emotes)'
gui.ppm2.spawnmenu.advancedmode = 'Enable PPM2 editor advanced mode'
gui.ppm2.spawnmenu.reflections = 'Enable real time eyes reflections'
gui.ppm2.spawnmenu.reflections_drawdist = 'Reflections draw distance'
gui.ppm2.spawnmenu.reflections_renderdist = 'Reflections render distance'
gui.ppm2.spawnmenu.doublejump = 'Double jump activate flight'
gui.ppm2.spawnmenu.vm_magic = 'ViewModel unicorn alignment'
tip.ppm2.in_editor = 'In PPM/2 Editor'
tip.ppm2.camera = "%s's PPM/2 Camera"
message.ppm2.queue_notify = '%i textures are queued to be rendered'
gui.ppm2.editor.body.bump = 'Bumpmap strength'
gui.ppm2.editor.body.detail.first = 'Render detail first-wise'
gui.ppm2.editor.size.pony = 'Collision height of pony: %s'
gui.ppm2.editor.size.pony2 = 'Visual height of pony: ~%s'
gui.ppm2.editor.size.pony_width = 'Collision width of pony: %s'
gui.ppm2.editor.size.back = 'Length of spine: ~%s'
gui.ppm2.editor.size.neck = 'Length of neck: ~%s'
| 51.112 | 412 | 0.746439 |
cf27718bc14603047f4c2f2e4a177a0b87522b41 | 2,032 | listToArray = zb2rhj3APjEyBffYfDUhef71pdkvq8N5HkixVN1hmCacPXJth
bigNor = zb2rhmDFWSSNMJAE7vNzAkaP1bKj4q89SFQqW4N1pybSWwqFy
aList => bList =>
md = (pow 2 16)
a = (listToArray aList)
b = (listToArray bList)
al = (get a "length")
bl = (get b "length")
ini = {car:0 res:c=>n=>n}
res = (for 0 (add al bl) ini i => state =>
car = (get state "car")
res = (get state "res")
sum = (for 0 bl 0 j => sum =>
n = (sub i j)
m = (sub (sub bl j) 1)
x = (if (ltn n 0) 0 (if (ltn n al) (get a (nts n)) 0))
y = (get b (nts j))
(add (mul x y) sum))
tot = (add sum car)
{
car: (flr (div tot md))
res: c => n => (res c (c (mod tot md) n))
})
(bigNor (get res "res"))
// algorithm:
//
// a = 23958233
// b = 5830
// c = a * b
//
// 00023958233000
// 0385 0 + 0 + 0 + 0 = 0
// 0385 0 + 9 + 0 + 0 = 9
// 0385 0 + 9 + 24 + 0 = 3 ~3
// 0385 0 + 6 + 24 + 15 = 8 ~4
// 0385 0 + 24 + 16 + 15 = 9 ~5
// 0385 0 + 15 + 64 + 10 = 4 ~9
// 0385 0 + 27 + 40 + 40 = 6 ~11
// 0385 0 + 9 + 72 + 25 = 7 ~11
// 0385 0 + 6 + 24 + 45 = 6 ~8
// 0385 0 + 0 + 16 + 15 = 9 ~3
// 0385 0 + 0 + 0 + 10 = 3 ~1
//
// c = 139676498390
//
// Slower version:
// f = a => b =>
// md = (pow 2 16)
// (
// c => n => (a c (b (h => (c 0)) n))
// a => as => state =>
// car0 = (get state "car")
// res0 = (get state "res")
// aas0 = (get state "aas")
// aas1 = c => n => (c a aas0)
// prod = (add car0 (b y => ys => a => (a x => xs => (add (mul x y) (ys xs)) 0) a => 0 aas1))
// car1 = (flr (div prod md))
// res1 = c => n => (res0 c (c (mod prod md) n))
// (as {car:car1 res:res1 aas:aas1})
// state =>
// car = (get state "car")
// res = (get state "res")
// (if car (c => n => (c car (res c n))) res)
// {car:0 res:c=>n=>n aas:c=>n=>n})
| 30.328358 | 99 | 0.413386 |
0020cc9268d288c4da0a0d233e1457983a877c4c | 10,541 | [=[
File: Arguments
This file defines argument types to be used in TODO.
]=]
[=[
Class: Arg
The base argument class. This class is not really meant to be used in practice and is basically a pass through itself,
but <Arg> lays down some important shared functionality for the other argument classes.
]=]
class ulx.Arg
--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
@
[=[
Function: Deserialize
Parameters:
str - A serialized *string* generated by <Serialize>.
Returns:
An instantiation of *<Arg>*. For the derived classes, it returns the appopriate class instantiation with the
restrictions set according to what the serialized string contained.
]=]
@Deserialize: (str using nil) ->
ulx.Arg!
[=[
Variables: Arg 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 `Default(myDefaultValue)`.
_Default - A value of *any type*. If an argument is optional and unspecified, this value is used.
_Optional - A *boolean* of whether or not this argument is optional.
_Hint - A *string* (usually a word or two) used in help output to give users a general idea of what the argument is for.
_Help - A *string* used in longer help output to describe the argument.
]=]
_Default: nil
_Optional: false
_Hint: "arg"
_Help: "An arbitrary argument"
@ShortcutFn "Default"
@ShortcutFn "Optional", "boolean", true
@ShortcutFn "Hint", "string"
@ShortcutFn "Help", "string"
[=[
Function: UsageShort
Parameters:
str - An optional *string* to add the help into. _Defaults to ""_.
Returns:
A short, one-line help *string* for using the argument.
]=]
UsageShort: (str = "" using nil) =>
str ..= ", " if @_Optional and #str > 0
str ..= "default #{@_Default}" if @_Optional
str = ": " .. str if @_Hint and #str > 0
str = tostring(@_Hint) .. str if @_Hint
str = "<" .. str .. ">"
str = "[" .. str .. "]" if @_Optional
str
[=[
Function: UsageLong
Similar to <UsageShort>, but has no length restrictions on the returned text.
Parameters:
str - An optional *string* to add the help into. _Defaults to ""_.
Returns:
A full *string* help for using the argument.
]=]
UsageLong: (str = "" using nil) =>
str ..= "Type: #{@@__name}"
str ..= "\nDefault: #{@_Default} (used if argument is unspecified)" if @_Optional
str ..= "\nHint: #{@_Hint}" if @_Hint
str ..= "\nHelp: #{@_Help}" if @_Help
str
[=[
Function: Completes
Parameters:
str - The *string* input for the command so far.
Returns:
A *list of strings* to be used as command autocomplete suggestions.
]=]
Completes: (str using nil) =>
{@UsageShort!}
[=[
Function: IsValid
"Valid" for <Arg> is any object that is not nil, or nil if the argument is optional.
Parameters:
obj - A value of *any type*.
Returns:
A *boolean* on whether the passed object is valid for this argument type.
]=]
IsValid: (obj using nil) =>
obj ~= nil or @_Optional
[=[
Function: Parse
Parameters:
obj - A value of *any type*.
Returns:
1 - A *boolean*. True if the argument was parsed, false otherwise.
2 - The parsed value of *any type* or a translated *string* explaining why it couldn't be parsed.
For <Arg>, this function simply returns what was passed or the default value if it's passed nil.
]=]
Parse: (obj using nil) =>
if obj == nil and @_Optional
return @_Default
obj
[=[
Function: IsPermissible
Parameters:
obj - A value of *any type*. For other argument classes, you pass only a parsed object of the appropriate type.
Under most circumstances, you'll be passing the output from <Parse> into this function.
Returns:
A *boolean* stating whether the passed object meets the restrictions specified by the class configuration.
If it returns false, a *string* explaining why it is not permissible is passed as the second return value.
]=]
IsPermissible: (obj using nil) =>
true
[=[
Function: Serialize
Returns:
A serialized *string* version of the restrictions in this class to be used by <Deserialzie>. Since ULX is only
concerned about saving restrictions created by a user for various commands, nothing is saved by this base class.
]=]
Serialize: (using nil) =>
""
[=[
Class: ArgNum
The argument class used for any numeric data.
Passes:
A *number* value, defaulting to _0_.
]=]
class ulx.ArgNum extends ulx.Arg
-- Values from parent that we want to override the defaults for
_Default: 0
_Hint: "number"
_Help: "A number argument"
@ShortcutFn "Default", {"number", "nil"}
lang = ulx.Lang -- shortcut
[=[
Variables: ArgNum Variables
All these variables are optional, with sensible defaults. See <Arg.Arg Variables> above for an important note.
_Min - A *number or nil* specifying the minimum value for the argument.
_Max - A *number or nil* specifying the maximum value for the argument.
_Round - A *number or nil* specifying the digit to round to, as passed to <UtilX.Round>.
_Hint - A *string* (usually a word or two) used in help output to give users a general idea of what the argument is for.
]=]
_Min: nil
_Max: nil
_Round: nil
@ShortcutFn "Min", {"number", "nil"}
@ShortcutFn "Max", {"number", "nil"}
@ShortcutFn "Round", {"number", "nil"}
[=[
Function: UsageShort
See <Arg.UsageShort>.
]=]
UsageShort: (str = "" using nil) =>
if @_Min and @_Min == @_Max
str ..= tostring @_Min
else
str ..= @_Min .. "<=" if @_Min
str ..= "x"
str ..= "<=" .. @_Max if @_Max
super\UsageShort str
[=[
Function: UsageLong
See <Arg.UsageLong>.
]=]
UsageLong: (str = "" using nil) =>
str = super\UsageLong(str)
str ..= "\nMin: #{@_Min}" if @_Min
str ..= "\nMax: #{@_Max}" if @_Max
str ..= "\nRound: #{@_Round}" if @_Round
str
[=[
Function: IsValid
See <Arg.IsValid>. For <ArgNum>, "valid" is anything that passes tonumber().
]=]
IsValid: (obj using nil) =>
if obj == nil and @_Optional
return true
tonumber(obj) ~= nil
[=[
Function: Parse
See <Arg.Parse>.
Returns:
1 - A *boolean*. True if the argument was parsed, false otherwise.
2 - The parsed and rounded *number* or a translated *string* explaining why it couldn't be parsed.
]=]
Parse: (obj using nil) =>
local num
if obj ~= nil
num = tonumber obj
if num == nil
return false, lang.GetMutatedPhrase "ARG_CANNOT_PARSE",
TYPE: lang.GetPhrase "NUMBER"
GIVEN: tostring obj
elseif @_Optional
num = @_Default
num = ulx.UtilX.Round num, @_Round if num and @_Round
return true, num
[=[
Function: IsPermissible
See <Arg.IsPermissible>. For <ArgNum>, checks the bounds of the number.
Parameters:
num - A *number* or *nil*.
]=]
IsPermissible: (num using nil) =>
data =
TYPE: lang.GetPhrase "NUMBER"
GIVEN: tostring num
MIN: @_Min
MAX: @_Max
if num == nil
return false, lang.GetMutatedPhrase("ARG_NOT_SPECIFIED", data) if not @_Optional
return true
return false, lang.GetMutatedPhrase("ARG_INCORRECT_TYPE", data) if type(num) ~= "number"
return false, lang.GetMutatedPhrase("ARGNUM_BELOW_MIN", data) if @_Min and num < @_Min
return false, lang.GetMutatedPhrase("ARGNUM_ABOVE_MAX", data) if @_Max and num > @_Max
return true
[=[
Function: Serialize
See <Arg.Serialize>.
Returns:
A *string* in the format "min_num:max_num".
]=]
Serialize: (using nil) =>
str = ""
str ..= tostring(@_Min) if @_Min
str ..= ":" if @_Min or @_Max
str ..= tostring(@_Max) if @_Max
str
[=[
Function: Deserialize
See <Arg.Deserialize>.
]=]
@Deserialize: (str using nil) ->
splitPt = str\find ":"
local min, max
if splitPt
min = tonumber(str\sub(1, splitPt-1))
max = tonumber(str\sub(splitPt+1))
else -- Assume they want it restricted to one value
min = tonumber(str)
max = min
ulx.ArgNum!\Min(min)\Max(max)
[=[
Class: ArgTime
The argument class used for a timespan using natural language.
Passes:
A *number* of seconds, defaulting to _0_.
]=]
class ulx.ArgTime extends ulx.ArgNum
[=[
Variables: ArgNum Variables
All these variables are optional, with sensible defaults.
Min - A *number, string, or nil* specifying the minimum value for the argument.
Max - A *number, string, or nil* specifying the maximum value for the argument.
]=]
Min: nil
Max: nil
[=[
Class: ArgString
The argument class used for string arguments.
Passes:
A *string* value, defaulting to _0_.
]=]
class ulx.ArgString extends ulx.Arg
[=[
Variables: ArgString Variables
All these variables are optional, with sensible defaults.
Default - A *string*, defaults to _""_. If an argument is optional and unspecified, this value is used.
RestrictToCompletes - A *boolean*, defaults to _false_.
If true, the argument passed will /always/ be one of the arguments from the <Completes> table.
Completes - A *list of strings or nil* of auto-completes (suggestions) for the argument.
]=]
Default: ""
RestrictToCompletes: false
Completes: nil
[=[
Class: ArgPlayerID
The argument class used for SteamID arguments.
Passes:
A *table of strings or players* (between one and <MaximumTargets> items).
Each item is either a valid SteamID or a connected player.
]=]
class ulx.ArgPlayerID extends ulx.Arg
[=[
Variables: ArgPlayerID Variables
All these variables are optional, with sensible defaults.
Default - A *string*, defaults to _"^"_ (keyword for the player calling the command).
If an argument is optional and unspecified, this value is used.
RestrictTarget - A *string or nil* specifying the players this argument is allowed to target.
This is passed to <TODO.GetUser()>. Nil indicates no restriction.
MaximumTargets - A *number*, defaulting to _1_, specifying the maximum number of players this argument can target.
PassPlayerIfActive - A *boolean*. If true, will pass the player object if they are connected.
]=]
Default: "^"
RestrictTarget: nil
MaximumTargets: 1
PassPlayerIfActive: false
[=[
Class: ArgPlayerActive
The argument class used for player arguments.
Passes:
A *table of players* (between one and <MaximumTargets> items).
]=]
class ulx.ArgPlayerActive extends ulx.ArgPlayerID
| 26.484925 | 123 | 0.677545 |
dfde78471716417eabdc5922e25774d0f755f908 | 865 | insert: append, :concat = table
to_func = (callable) ->
(...) -> callable ...
coro = (func, ...) ->
coroutine.wrap(to_func(func)) ...
to_coro = (func) ->
(...) -> coro(func, ...)
read = (fd, count = 4096) -> ->
bytes, err = fd\read nil, count
return "", err if err
return nil if #bytes == 0
bytes
NEWLINE = string.byte '\n'
readline = (fd) ->
line = {}
getline = ->
for bytes, err in read(fd)
coroutine.yield nil, err if err
for i=1, #bytes
if bytes\byte(i) == NEWLINE
coroutine.yield concat(line, '')
line = {}
continue
append line, bytes\sub(i,i)
coroutine.wrap -> getline!
{
is_callable: (thing) ->
t = type thing
return true if t == 'function'
mt = getmetatable thing
return true if mt and mt.__call
false
:to_func
:to_coro
:read
:readline
}
| 19.222222 | 42 | 0.554913 |
a37bbe9d8752be0a16e816990129263386681ba4 | 877 | import Application from require 'ice.application'
import UpdateCommand from require 'ice.commands.update'
import BuildCommand from require 'ice.commands.build'
import VStudioCommand from require 'ice.commands.vstudio'
import RunCommand from require 'tools.run'
import NatvisCommand from require 'tools.natvis'
import CodeStyleCommand from require 'tools.codestyle'
class IceShard extends Application
@name: 'IceShard'
@description: 'IceShard engine project tool.'
@commands: {
'build': BuildCommand
'update': UpdateCommand
'vstudio': VStudioCommand
'run': RunCommand
'natvis': NatvisCommand
'codestyle': CodeStyleCommand
}
-- Plain call to the application
execute: (args) =>
print "#{@@name} project tool - v0.1-alpha"
print ' For more options see the -h,--help output.'
{ :IceShard }
| 31.321429 | 59 | 0.701254 |
b62b8a7796f8e553cca6834db7172ad3e45f4d7b | 724 | -- Copyright 2012-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
import interact, signal from howl
get_signals_list = ->
signals = {}
for name, def in pairs signal.all
table.insert signals, { name, def.description\match('[^\n.]*'), :name }
table.sort signals, (a, b) -> a[1] < b[1]
return signals
interact.register
name: 'select_signal'
description: 'Selection list for signals'
handler: (opts={}) ->
opts = moon.copy opts
with opts
.title or= 'Signals'
.items = get_signals_list!
.columns = { { style: 'string' }, { style: 'comment' } }
selected = interact.select opts
if selected
return selected.name
| 26.814815 | 79 | 0.654696 |
d682907dc35436d858c671e8a67ea339e969de47 | 1,839 | -- Copyright 2014-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
Atom = require 'ljglibs.gdk.atom'
GtkClipboard = require 'ljglibs.gtk.clipboard'
TargetEntry = require 'ljglibs.gtk.target_entry'
{:PropertyTable} = howl.util
ffi = require 'ffi'
{:config} = howl
config.define {
name: 'clipboard_max_items',
description: 'The maximum number of anynomous clips to keep in the clipboard',
type_of: 'number',
default: 50,
scope: 'global'
}
clips = {}
registers = {}
system_clipboard = GtkClipboard.get(Atom.SELECTION_CLIPBOARD)
system_primary = GtkClipboard.get(Atom.SELECTION_PRIMARY)
sync_counter = ffi.new 'uint64_t'
UTF8_TARGET = TargetEntry('UTF8_STRING')
primary = PropertyTable {
clear: -> system_primary\clear!
text:
set: (v) =>
if callable(v)
system_primary\set UTF8_TARGET, 1, v
else
system_primary.text = v
get: => system_primary.text
}
local Clipboard
Clipboard = {
push: (item, opts = {}) ->
item = { text: item } if type(item) == 'string'
error('Missing required field "text"', 2) unless item.text
if opts.to
registers[opts.to] = item
else
table.insert clips, 1, item
clips[config.clipboard_max_items + 1] = nil
system_clipboard.text = item.text
system_clipboard\set_can_store nil, 0
sync_counter += 1
store: ->
system_clipboard\store!
clear: ->
clips = {}
registers = {}
synchronize: ->
sync_id = sync_counter
system_clipboard\request_text (_, text) ->
if sync_id == sync_counter and text
cur = clips[1]
if not cur or cur.text != text
Clipboard.push text
current: get: ->
clips[1]
clips: get: -> clips
registers: get: -> registers
primary: get: -> primary
}
PropertyTable Clipboard
| 23.278481 | 80 | 0.666667 |
7ae70bf0a76c9489ab27cfc6339137634c1b78d7 | 2,335 | log = require "mooncrafts.log"
util = require "mooncrafts.util"
crypto = require "mooncrafts.crypto"
url = require "mooncrafts.url"
import string_split, url_escape, query_string_encode, table_sort_keys, url_build from util
import sort, concat from table
url_parse = url.parse
url_default_port = url.default_port
escape_uri = url_escape
unescape_uri = ngx and ngx.unescape_uri or util.url_unescape
encode_base64 = ngx and ngx.encode_base64 or crypto.base64_encode
digest_hmac_sha1 = ngx and ngx.hmac_sha1 or (key, str) -> crypto.hmac(key, str, crypto.sha1).digest()
digest_md5 = ngx and ngx.md5 or (str) -> crypto.md5(str).hex()
normalizeParameters = (parameters, body, query) ->
items = { query_string_encode(parameters, "&") }
string_split(body, "&", items) if body
string_split(query, "&", items) if query
sort(items)
concat(items, "&")
calculateBaseString = (body, method, query, base_uri, parameters) ->
escape_uri(method) .. "&" .. escape_uri(base_uri) .. "&" .. escape_uri(normalizeParameters(parameters, body, query))
secret = (oauth) -> unescape_uri(oauth["consumersecret"]) .. "&" .. unescape_uri(oauth["tokensecret"] or "")
sign = (body, method, query, base_uri, oauth, parameters) ->
oauth.stringToSign = calculateBaseString(body, method, query, base_uri, parameters)
encode_base64(digest_hmac_sha1(secret(oauth), oauth.stringToSign))
create_signature = (opts, oauth) ->
-- parse url for query string
parts = url_parse(opts.url)
parts.port = nil if (url_default_port(parts.scheme) == parts.port)
base_uri = url_build(parts, false)
-- allow for unit testing by passing in timestamp
timestamp = oauth['timestamp'] or os.time()
parameters = {
oauth_consumer_key: oauth["consumerkey"],
oauth_signature_method: "HMAC-SHA1",
oauth_timestamp: timestamp,
oauth_nonce: digest_md5(timestamp .. ""),
oauth_version: oauth["version"] or "1.0"
}
parameters["oauth_token"] = oauth["accesstoken"] if oauth["accesstoken"]
parameters["oauth_callback"] = unescape_uri(oauth["callback"]) if oauth["callback"]
parameters["oauth_signature"] = sign(opts["body"], opts["method"] or 'GET', parts.query, base_uri, oauth, parameters)
"OAuth " .. query_string_encode(parameters, ",", "\"")
{ :create_signature }
| 38.916667 | 119 | 0.70364 |
a568470e6b7a3081b04c19e122fc5a98ee9b85b1 | 147 | geo3x3 = require "geo3x3"
print geo3x3.encode 35.65858, 139.745433, 14
pos = geo3x3.decode "E9139659937288"
print pos[1], pos[2], pos[3], pos[4]
| 21 | 44 | 0.707483 |
ff5ca745a14672a9580dbddda940f796ddab3d8a | 178 | class
new: (@x, @y, @w, @h) =>
draw: =>
with lg
.setColor 255, 100, 100
.draw game.sprites.block[0], @x, @y
apply: (thing) =>
game.load!
nil, nil
| 14.833333 | 41 | 0.483146 |
71c18abc3069d4710c7e12fa06faec287a3ae445 | 471 | --- Fuzy Logic
-- (c) buckle2000 2016
math = require "math"
{
and_: (x, y) ->
x * y
or_: (x, y) ->
-x * y + x + y
not_: (x) ->
1 - x
proximity_linear: (center, error_) ->
assert error_ > 0
(x) -> math.max(0, 1 - math.abs(x - center) / error_)
proximity_normal: (mean, std) ->
error("Not implemented.")
proximity_sigmoid: (center, multiple) ->
assert multiple > 0
(x) -> 2 / (1 + math.exp(math.abs(x - center) / multiple))
} | 20.478261 | 62 | 0.539278 |
a3820a7e47e6e86e7e4a710e2f322fcb80d33094 | 35 | {
DEBUG: true
GLOBALS: true
} | 8.75 | 15 | 0.571429 |
6a13cfd2fe1b551ee9181e2bee5a1ef024dc4359 | 638 | formatters = {}
formatter_names = {}
register = (fmt) ->
formatters[fmt.name] = fmt
table.insert formatter_names, {fmt.name, fmt.description}
unregister = (fmt) ->
formatters[fmt.name] = nil
table.remove formatter_names, {fmt.name, fmt.description}
by_name = (name) ->
formatters[name]
by_mode = (mode) ->
by_name howl.config.get "formatter", "", "mode:"..mode.name
select = ->
result = howl.interact.select
items: formatter_names
columns: {
{style: "string"}
{style: "comment"}
}
return unless result
by_name result.selection
{
:register
:unregister
:by_name
:by_mode
:select
}
| 17.722222 | 61 | 0.655172 |
4af6aa0d05d39d67bb875c038cc4a3aeae40e809 | 1,003 |
import build from require "moonscript.types"
import unpack from require "moonscript.util"
-- always declares as local
class LocalName
new: (@name) => self[1] = "temp_name"
get_name: => @name
-- creates a unique name when used
class NameProxy
new: (@prefix) =>
self[1] = "temp_name"
get_name: (scope, dont_put=true) =>
if not @name
@name = scope\free_name @prefix, dont_put
@name
chain: (...) =>
items = { base: @, ... }
for k,v in ipairs items
items[k] = if type(v) == "string"
{"dot", v}
else
v
build.chain items
index: (key) =>
if type(key) == "string"
key = {"ref", key}
build.chain {
base: self, {"index", key}
}
__tostring: =>
if @name
("name<%s>")\format @name
else
("name<prefix(%s)>")\format @prefix
is_name_proxy = (v) ->
return false unless type(v) == "table"
switch v.__class
when LocalName, NameProxy
true
{ :NameProxy, :LocalName, :is_name_proxy }
| 19.288462 | 47 | 0.576271 |
193a4b5ebd7c34778d65d68a99d2a115c9116e22 | 5,149 |
util = require "moonscript.util"
data = require "moonscript.data"
import ntype from require "moonscript.types"
import user_error from require "moonscript.errors"
import concat, insert from table
import unpack from util
table_delim = ","
string_chars = {
"\r": "\\r"
"\n": "\\n"
}
{
scoped: (node) =>
{_, before, value, after} = node
before and before\call @
with @value value
after and after\call @
-- list of values separated by binary operators
exp: (node) =>
_comp = (i, value) ->
if i % 2 == 1 and value == "!="
value = "~="
@value value
with @line!
\append_list [_comp i,v for i,v in ipairs node when i > 1], " "
-- list of expressions separated by commas
explist: (node) =>
with @line!
\append_list [@value v for v in *node[2,]], ", "
parens: (node) =>
@line "(", @value(node[2]), ")"
string: (node) =>
_, delim, inner = unpack node
end_delim = delim\gsub "%[", "]"
if delim == "'" or delim == '"'
inner = inner\gsub "[\r\n]", string_chars
delim..inner..end_delim
chain: (node) =>
callee = node[2]
callee_type = ntype callee
item_offset = 3
if callee_type == "dot" or callee_type == "colon" or callee_type == "index"
callee = @get "scope_var"
unless callee
user_error "Short-dot syntax must be called within a with block"
item_offset = 2
-- TODO: don't use string literals as ref
if callee_type == "ref" and callee[2] == "super" or callee == "super"
if sup = @get "super"
return @value sup self, node
chain_item = (node) ->
t, arg = unpack node
if t == "call"
-- print arg, util.dump arg
"(", @values(arg), ")"
elseif t == "index"
"[", @value(arg), "]"
elseif t == "dot"
".", tostring arg
elseif t == "colon"
":", tostring arg
elseif t == "colon_stub"
user_error "Uncalled colon stub"
else
error "Unknown chain action: #{t}"
if (callee_type == "self" or callee_type == "self_class") and node[3] and ntype(node[3]) == "call"
callee[1] = callee_type.."_colon"
callee_value = @value callee
callee_value = @line "(", callee_value, ")" if ntype(callee) == "exp"
actions = with @line!
\append chain_item action for action in *node[item_offset,]
@line callee_value, actions
fndef: (node) =>
_, args, whitelist, arrow, block = unpack node
default_args = {}
self_args = {}
arg_names = for arg in *args
name, default_value = unpack arg
name = if type(name) == "string"
name
else
if name[1] == "self" or name[1] == "self_class"
insert self_args, name
name[2]
insert default_args, arg if default_value
name
if arrow == "fat"
insert arg_names, 1, "self"
with @block!
if #whitelist > 0
\whitelist_names whitelist
\put_name name for name in *arg_names
for default in *default_args
name, value = unpack default
name = name[2] if type(name) == "table"
\stm {
'if', {'exp', {"ref", name}, '==', 'nil'}, {
{'assign', {name}, {value}}
}
}
self_arg_values = [arg[2] for arg in *self_args]
\stm {"assign", self_args, self_arg_values} if #self_args > 0
\stms block
-- inject more args if the block manipulated arguments
-- only varargs bubbling does this currently
if #args > #arg_names -- will only work for simple adjustments
arg_names = [arg[1] for arg in *args]
.header = "function("..concat(arg_names, ", ")..")"
table: (node) =>
_, items = unpack node
with @block "{", "}"
format_line = (tuple) ->
if #tuple == 2
key, value = unpack tuple
-- escape keys that are lua keywords
if ntype(key) == "key_literal" and data.lua_keywords[key[2]]
key = {"string", '"', key[2]}
assign = if ntype(key) == "key_literal"
key[2]
else
@line "[", \value(key), "]"
out = @line assign, " = ", \value(value)
out
else
@line \value tuple[1]
if items
count = #items
for i, tuple in ipairs items
line = format_line tuple
line\append table_delim unless count == i
\add line
minus: (node) =>
@line "-", @value node[2]
temp_name: (node, ...) =>
node\get_name self, ...
number: (node) =>
node[2]
length: (node) =>
@line "#", @value node[2]
not: (node) =>
@line "not ", @value node[2]
self: (node) =>
"self."..@name node[2]
self_class: (node) =>
"self.__class."..@name node[2]
self_colon: (node) =>
"self:"..@name node[2]
self_class_colon: (node) =>
"self.__class:"..@name node[2]
-- a variable reference
ref: (value) =>
if sup = value[2] == "super" and @get "super"
return @value sup @
tostring value[2]
-- catch all pure string values
raw_value: (value) =>
if value == "..."
@send "varargs"
tostring value
}
| 24.754808 | 102 | 0.550204 |
7ec8a7538234eb6cc5d777151ba380531e311f80 | 467 |
current = ->
return "nginx" if ngx
"xavante"
make_static_handler = (root) ->
=>
import req, res from @
req.relpath = @params.splat
if current! == "xavante"
handler = xavante.filehandler root
handler req, res, root
layout: false
serve_from_static = (root="static") ->
handler = make_static_handler root
=>
@params.splat = @req.relpath
handler @
{ :make_server, :make_static_handler, :serve_from_static, :current }
| 17.961538 | 68 | 0.646681 |
6579126a62712af337b67cc05075bdc7c8afae1b | 526 | import config_for, load_config_from from require "moonpick.config"
import lint from require "moonpick"
local convert_issue
main = (file_path) ->
config_file = config_for file_path
config = if config_file
load_config_from config_file, file_path
else
nil
source = io.stdin\read "*a"
issues = lint source, config
formatted_issues = [convert_issue issue for issue in *issues]
for line in *formatted_issues
print line
convert_issue = (issue) ->
"#{issue.line}:#{issue.pos}:#{issue.msg}"
{ :main }
| 21.916667 | 66 | 0.722433 |
ff96d7ba4b43e906a298d632daaf4f619eb20333 | 3,700 | ---------------------------------------------------------------------------
-- Environment ------------------------------------------------------------
---------------------------------------------------------------------------
import sort from table
import max, min from math
{ sigcheck:T } = require 'typecheck'
---------------------------------------------------------------------------
-- Implementation ---------------------------------------------------------
---------------------------------------------------------------------------
move = (top, left, sframe, frame) ->
x = if left > 1 then frame.x - left
elseif left > 0 then sframe.x + sframe.w * (1 - left)
elseif left == 0 then frame.x
elseif left >= -1 then sframe.x - sframe.w * left - frame.w
else frame.x - left
y = if top > 1 then frame.y - top
elseif top > 0 then sframe.y + sframe.h * (1 - top)
elseif top == 0 then frame.y
elseif top >= -1 then sframe.y - sframe.h * top - frame.h
else frame.y - top
return { :x, :y }
extend = (top, left, sframe, frame) ->
x, w = if left > 1
frame.x - left, frame.w + left
elseif left > 0
fx = sframe.x + sframe.w * (1 - left)
fx, frame.w + frame.x - fx
elseif left == 0
frame.x, frame.w
elseif left >= -1
fx = sframe.x - sframe.w * left - frame.w
fx, frame.w + fx - frame.x
else frame.x - left
y, h = if left > 1
frame.y - left, frame.h + left
elseif left > 0
fy = sframe.y + sframe.h * (1 - left)
fy, frame.h + frame.y - fy
elseif left == 0
frame.y, frame.h
elseif left >= -1
fy = sframe.y - sframe.h * left - frame.h
fy, frame.h + fy - frame.y
else frame.y - left
return { :x, :y }, { :w, :h }
center = (sframe, frame) ->
w, h = frame.w, frame.h
x = sframe.x + sframe.w / 2 - w / 2
y = sframe.y + sframe.h / 2 - h / 2
return { :x, :y }
maximize = (sframe) -> sframe, sframe
normalized = (x, y, w, h, sframe) ->
w = sframe.w * w
h = sframe.h * h
x = sframe.x + sframe.w * x
y = sframe.y + sframe.h * y
return { :x, :y }, { :w, :h }
snap = (grids, sframe, frame) ->
results, glen = {}, #grids
for i = 1, glen, 4
gtopleft, gsize = normalized grids[i], grids[i + 1], grids[i + 2], grids[i + 3], sframe
-- calculate intersection area
fx, fy, gx, gy, fw, fh, gw, gh = frame.x, frame.y, gtopleft.x, gtopleft.y, frame.w, frame.h, gsize.w, gsize.h
ix, iy = max(fx, gx), max(fy, gy)
ix2, iy2 = min(fx + fw, gx + gw), min(fy + fh, gy + gh)
iarea = (ix2 >= ix and iy2 >= iy) and (ix2 - ix) * (iy2 - iy) or 0
-- calc ratios
fratio = iarea / (fw * fh)
gratio = iarea / (gw * gh)
-- almost fit, use next grid frame
if fratio >= 0.9 and gratio >= 0.9
if i == glen - 3 -- last
return results[1][2], results[1][3]
return normalized grids[i + 4], grids[i + 5], grids[i + 6], grids[i + 7], sframe
results[(i - 1) / 4 + 1] = { i, gtopleft, gsize, fratio, gratio }
sort results, (r1, r2) ->
fr1, fr2 = r1[4], r2[4]
return fr1 > fr2 if fr1 != fr2
sfr1, sfr2 = r1[5], r2[5]
return sfr1 > sfr2 if sfr1 != sfr2
return r1[1] < r2[1]
return results[1][2], results[1][3]
---------------------------------------------------------------------------
-- Interface --------------------------------------------------------------
---------------------------------------------------------------------------
{
move: T 'number, number, table, table', move
extend: T 'number, number, table, table', extend
center: T 'table, table', center
maximize: T 'table', maximize
normalized: T 'number, number, number, number, table, table' , normalized
snap: T 'table, table, table', snap
}
| 32.173913 | 113 | 0.466486 |
8943dd8dc0749d9da2043d5e5bdebbd33bbb4c57 | 5,175 |
import setup_db, teardown_db from require "spec_postgres.helpers"
import drop_tables, truncate_tables from require "lapis.spec.db"
db = require "lapis.db.postgres"
import Model, enum from require "lapis.db.postgres.model"
import types, create_table from require "lapis.db.postgres.schema"
class Users extends Model
@create_table: =>
drop_tables @
create_table @table_name!, {
{"id", types.serial}
{"name", types.text}
"PRIMARY KEY (id)"
}
@truncate: =>
truncate_tables @
class Posts extends Model
@timestamp: true
@create_table: =>
drop_tables @
create_table @table_name!, {
{"id", types.serial}
{"user_id", types.foreign_key null: true}
{"title", types.text null: false}
{"body", types.text null: false}
{"created_at", types.time}
{"updated_at", types.time}
"PRIMARY KEY (id)"
}
@truncate: =>
truncate_tables @
class Likes extends Model
@primary_key: {"user_id", "post_id"}
@timestamp: true
@relations: {
{"user", belongs_to: "Users"}
{"post", belongs_to: "Posts"}
}
@create_table: =>
drop_tables @
create_table @table_name!, {
{"user_id", types.foreign_key}
{"post_id", types.foreign_key}
{"count", types.integer default: 1}
{"created_at", types.time}
{"updated_at", types.time}
"PRIMARY KEY (user_id, post_id)"
}
@truncate: =>
truncate_tables @
class HasArrays extends Model
@create_table: =>
drop_tables @
create_table @table_name!, {
{"id", types.serial}
{"tags", types.text array: true}
"PRIMARY KEY (id)"
}
describe "model", ->
setup ->
setup_db!
teardown ->
teardown_db!
describe "core model", ->
build = require "spec.core_model_specs"
build { :Users, :Posts, :Likes }
it "should get columns of model", ->
Users\create_table!
assert.same {
{
data_type: "integer"
column_name: "id"
}
{
data_type: "text"
column_name: "name"
}
}, Users\columns!
it "should fail to create without required types", ->
Posts\create_table!
assert.has_error ->
Posts\create {}
describe "returning", ->
it "should create with returning", ->
Likes\create_table!
like = Likes\create {
user_id: db.raw "1 + 1"
post_id: db.raw "2 * 2"
count: 1
}
assert.same 1, like.count
assert.same 2, like.user_id
assert.same 4, like.post_id
it "should create with returning all", ->
Likes\create_table!
like = Likes\create {
user_id: 9
post_id: db.raw "2 * 2"
}, returning: "*"
assert.same 1, like.count
assert.same 9, like.user_id
assert.same 4, like.post_id
it "should create with returning specified column", ->
Likes\create_table!
like = Likes\create {
user_id: 2
post_id: db.raw "9 * 2"
}, returning: {"count"}
assert.same 1, like.count
assert.same 2, like.user_id
assert.same 18, like.post_id
it "should create with returning null", ->
Posts\create_table!
post = Posts\create {
title: db.raw "'hi'"
body: "okay!"
user_id: db.raw "(case when false then 1234 else null end)"
}
assert.same "hi", post.title
assert.same "okay!", post.body
assert.falsy post.user_id
it "should update with returning", ->
Likes\create_table!
like = Likes\create {
user_id: 1
post_id: 2
count: 1
}
like\update {
count: db.raw "1 + 1"
post_id: 123
user_id: db.raw "(select user_id from likes where count = 1 limit 1)"
}
assert.same 2, like.count
assert.same 123, like.post_id
assert.same 1, like.user_id
it "should update with returning null", ->
Posts\create_table!
post = Posts\create {
title: "hi"
body: "quality writing"
user_id: 1343
}
post\update user_id: db.raw "(case when false then 1234 else null end)"
assert.same nil, post.user_id
describe "arrays", ->
before_each ->
HasArrays\create_table!
it "inserts a new row", ->
res = HasArrays\create {
tags: db.array {"hello", "world"}
}
assert.same {
id: 1
tags: {"hello", "world"}
}, res
it "fetches rows with arrays", ->
db.query "insert into #{db.escape_identifier HasArrays\table_name!}
(tags) values ('{one,two,three}')"
db.query "insert into #{db.escape_identifier HasArrays\table_name!}
(tags) values ('{food,hat}')"
assert.same {
{id: 1, tags: {"one", "two", "three"}}
{id: 2, tags: {"food", "hat"}}
}, HasArrays\select "order by id asc"
it "updates model with array", ->
res = HasArrays\create {
tags: db.array {"hello", "world"}
}
res\update tags: db.array {"yeah"}
assert.same {"yeah"}, unpack(HasArrays\select!).tags
table.insert res.tags, "okay"
res\update "tags"
assert.same {"yeah", "okay"}, unpack(HasArrays\select!).tags
| 23.958333 | 77 | 0.585121 |
a1be1fe84de5f43897f4fafd1a9c8e28b0534a45 | 154 | parent = ...
case = (require parent..".case")["case"]
M = {}
M.test_batch_format = ->
case "p%s", {1,2,3}, {"p1","p2","p3"}
return true
return M | 19.25 | 41 | 0.532468 |
70a8b059bd086aa1cb9469ba67620b40b757529f | 21,726 |
import Postgres from require "pgmoon"
unpack = table.unpack or unpack
HOST = "127.0.0.1"
PORT = "9999"
USER = "postgres"
DB = "pgmoon_test"
psql = ->
os.execute "psql -h '#{HOST}' -p '#{PORT}' -U '#{USER}'"
describe "pgmoon with server", ->
setup ->
os.execute "spec/postgres.sh start"
teardown ->
os.execute "spec/postgres.sh stop"
for socket_type in *{"luasocket", "cqueues"}
describe "socket(#{socket_type})", ->
local pg
setup ->
assert 0 == os.execute "dropdb -h '#{HOST}' -p '#{PORT}' --if-exists -U '#{USER}' '#{DB}'"
assert 0 == os.execute "createdb -h '#{HOST}' -p '#{PORT}' -U '#{USER}' '#{DB}'"
pg = Postgres {
database: DB
user: USER
host: HOST
port: PORT
:socket_type
}
assert pg\connect!
teardown ->
pg\disconnect!
it "creates and drop table", ->
res = assert pg\query [[
create table hello_world (
id serial not null,
name text,
count integer not null default 0,
primary key (id)
)
]]
assert.same true, res
res = assert pg\query [[
drop table hello_world
]]
assert.same true, res
it "settimeout()", ->
timeout_pg = Postgres {
host: "10.0.0.1"
:socket_type
}
timeout_pg\settimeout 1000
ok, err = timeout_pg\connect!
assert.is_nil ok
errors = {
"timeout": true
"Connection timed out": true
}
assert.true errors[err]
it "tries to connect with SSL", ->
-- we expect a server with ssl = off
ssl_pg = Postgres {
database: DB
user: USER
host: HOST
port: PORT
ssl: true
:socket_type
}
finally ->
ssl_pg\disconnect!
assert ssl_pg\connect!
it "requires SSL", ->
ssl_pg = Postgres {
database: DB
user: USER
host: HOST
port: PORT
ssl: true
ssl_required: true
:socket_type
}
status, err = ssl_pg\connect!
assert.falsy status
assert.same [[the server does not support SSL connections]], err
describe "with table", ->
before_each ->
assert pg\query [[
create table hello_world (
id serial not null,
name text,
count integer not null default 0,
flag boolean default TRUE,
primary key (id)
)
]]
after_each ->
assert pg\query [[
drop table hello_world
]]
it "inserts a row", ->
res = assert pg\query [[
insert into "hello_world" ("name", "count") values ('hi', 100)
]]
assert.same { affected_rows: 1 }, res
it "inserts a row with return value", ->
res = assert pg\query [[
insert into "hello_world" ("name", "count") values ('hi', 100) returning "id"
]]
assert.same {
affected_rows: 1
{ id: 1 }
}, res
it "selects from empty table", ->
res = assert pg\query [[select * from hello_world limit 2]]
assert.same {}, res
it "selects count as a number", ->
res = assert pg\query [[select count(*) from hello_world]]
assert.same {
{ count: 0 }
}, res
it "deletes nothing", ->
res = assert pg\query [[delete from hello_world]]
assert.same { affected_rows: 0 }, res
it "update no rows", ->
res = assert pg\query [[update "hello_world" SET "name" = 'blahblah']]
assert.same { affected_rows: 0 }, res
describe "with rows", ->
before_each ->
for i=1,10
assert pg\query [[
insert into "hello_world" ("name", "count")
values (']] .. "thing_#{i}" .. [[', ]] .. i .. [[)
]]
it "select some rows", ->
res = assert pg\query [[ select * from hello_world ]]
assert.same "table", type(res)
assert.same 10, #res
it "update rows", ->
res = assert pg\query [[
update "hello_world" SET "name" = 'blahblah'
]]
assert.same { affected_rows: 10 }, res
assert.same "blahblah",
unpack((pg\query "select name from hello_world limit 1")).name
it "delete a row", ->
res = assert pg\query [[
delete from "hello_world" where id = 1
]]
assert.same { affected_rows: 1 }, res
assert.same nil,
unpack((pg\query "select * from hello_world where id = 1")) or nil
it "truncate table", ->
res = assert pg\query "truncate hello_world"
assert.same true, res
it "make many select queries", ->
for i=1,20
assert pg\query [[update "hello_world" SET "name" = 'blahblah' where id = ]] .. i
assert pg\query [[ select * from hello_world ]]
-- single call, multiple queries
describe "multi-queries #multi", ->
it "gets two results", ->
res, num_queries = assert pg\query [[
select id, flag from hello_world order by id asc limit 2;
select id, flag from hello_world order by id asc limit 2 offset 2;
]]
assert.same 2, num_queries
assert.same {
{
{ id: 1, flag: true }
{ id: 2, flag: true }
}
{
{ id: 3, flag: true }
{ id: 4, flag: true }
}
}, res
it "gets three results", ->
res, num_queries = assert pg\query [[
select id, flag from hello_world order by id asc limit 2;
select id, flag from hello_world order by id asc limit 2 offset 2;
select id, flag from hello_world order by id asc limit 2 offset 4;
]]
assert.same 3, num_queries
assert.same {
{
{ id: 1, flag: true }
{ id: 2, flag: true }
}
{
{ id: 3, flag: true }
{ id: 4, flag: true }
}
{
{ id: 5, flag: true }
{ id: 6, flag: true }
}
}, res
it "does multiple updates", ->
res, num_queries = assert pg\query [[
update hello_world set flag = false where id = 3;
update hello_world set flag = true;
]]
assert.same 2, num_queries
assert.same {
{ affected_rows: 1 }
{ affected_rows: 10 }
}, res
it "does mix update and select", ->
res, num_queries = assert pg\query [[
update hello_world set flag = false where id = 3;
select id, flag from hello_world where id = 3
]]
assert.same 2, num_queries
assert.same {
{ affected_rows: 1 }
{
{ id: 3, flag: false }
}
}, res
it "returns partial result on error", ->
res, err, partial, num_queries = pg\query [[
select id, flag from hello_world order by id asc limit 1;
select id, flag from jello_world limit 1;
]]
assert.same {
err: [[ERROR: relation "jello_world" does not exist (112)]]
num_queries: 1
partial: {
{ id: 1, flag: true }
}
}, { :res, :err, :partial, :num_queries }
it "deserializes types correctly", ->
assert pg\query [[
create table types_test (
id serial not null,
name text default 'hello',
subname varchar default 'world',
count integer default 100,
flag boolean default false,
count2 double precision default 1.2,
bytes bytea default E'\\x68656c6c6f5c20776f726c6427',
config json default '{"hello": "world", "arr": [1,2,3], "nested": {"foo": "bar"}}',
bconfig jsonb default '{"hello": "world", "arr": [1,2,3], "nested": {"foo": "bar"}}',
uuids uuid[] default ARRAY['00000000-0000-0000-0000-000000000000']::uuid[],
primary key (id)
)
]]
assert pg\query [[
insert into types_test (name) values ('hello')
]]
res = assert pg\query [[
select * from types_test order by id asc limit 1
]]
assert.same {
{
id: 1
name: "hello"
subname: "world"
count: 100
flag: false
count2: 1.2
bytes: 'hello\\ world\''
config: { hello: "world", arr: {1,2,3}, nested: {foo: "bar"} }
bconfig: { hello: "world", arr: {1,2,3}, nested: {foo: "bar"} }
uuids: {'00000000-0000-0000-0000-000000000000'}
}
}, res
assert pg\query [[
drop table types_test
]]
describe "custom deserializer", ->
it "deserializes big integer to string", ->
assert pg\query [[
create table bigint_test (
id serial not null,
largenum bigint default 9223372036854775807,
primary key (id)
)
]]
assert pg\query [[
insert into bigint_test (largenum) values (default)
]]
pg\set_type_oid 20, "bignumber"
pg.type_deserializers.bignumber = (val) => val
row = unpack pg\query "select * from bigint_test"
assert.same {
id: 1
largenum: "9223372036854775807"
}, row
describe "hstore", ->
import encode_hstore, decode_hstore from require "pgmoon.hstore"
describe "encoding", ->
it "encodes hstore type", ->
t = { foo: "bar" }
enc = encode_hstore t
assert.same [['"foo"=>"bar"']], enc
it "encodes multiple pairs", ->
t = { foo: "bar", abc: "123" }
enc = encode_hstore t
results = {'\'"foo"=>"bar", "abc"=>"123"\'', '\'"abc"=>"123", "foo"=>"bar"\''}
assert(enc == results[1] or enc == results[2])
it "escapes", ->
t = { foo: "bar's" }
enc = encode_hstore t
assert.same [['"foo"=>"bar''s"']], enc
describe "decoding", ->
it "decodes hstore into a table", ->
s = '"foo"=>"bar"'
dec = decode_hstore s
assert.same {foo: 'bar'}, dec
it "decodes hstore with multiple parts", ->
s = '"foo"=>"bar", "1-a"=>"anything at all"'
assert.same {
foo: "bar"
"1-a": "anything at all"
}, decode_hstore s
it "decodes hstore with embedded quote", ->
assert.same {
hello: 'wo"rld'
}, decode_hstore [["hello"=>"wo\"rld"]]
describe "serializing", ->
before_each ->
assert pg\query [[
CREATE EXTENSION hstore;
create table hstore_test (
id serial primary key,
h hstore
)
]]
pg\setup_hstore!
after_each ->
assert pg\query [[
DROP TABLE hstore_test;
DROP EXTENSION hstore;
]]
it "serializes correctly", ->
assert pg\query "INSERT INTO hstore_test (h) VALUES (#{encode_hstore {foo: 'bar'}});"
res = assert pg\query "SELECT * FROM hstore_test;"
assert.same {foo: 'bar'}, res[1].h
it "serializes NULL as string", ->
assert pg\query "INSERT INTO hstore_test (h) VALUES (#{encode_hstore {foo: 'NULL'}});"
res = assert pg\query "SELECT * FROM hstore_test;"
assert.same 'NULL', res[1].h.foo
it "serializes multiple pairs", ->
assert pg\query "INSERT INTO hstore_test (h) VALUES (#{encode_hstore {abc: '123', foo: 'bar'}});"
res = assert pg\query "SELECT * FROM hstore_test;"
assert.same {abc: '123', foo: 'bar'}, res[1].h
describe "json", ->
import encode_json, decode_json from require "pgmoon.json"
it "encodes json type", ->
t = { hello: "world" }
enc = encode_json t
assert.same [['{"hello":"world"}']], enc
t = { foo: "some 'string'" }
enc = encode_json t
assert.same [['{"foo":"some ''string''"}']], enc
it "encodes json type with custom escaping", ->
escape = (v) ->
"`#{v}`"
t = { hello: "world" }
enc = encode_json t, escape
assert.same [[`{"hello":"world"}`]], enc
it "serialize correctly", ->
assert pg\query [[
create table json_test (
id serial not null,
config json,
primary key (id)
)
]]
assert pg\query "insert into json_test (config) values (#{encode_json {foo: "some 'string'"}})"
res = assert pg\query [[select * from json_test where id = 1]]
assert.same { foo: "some 'string'" }, res[1].config
assert pg\query "insert into json_test (config) values (#{encode_json {foo: "some \"string\""}})"
res = assert pg\query [[select * from json_test where id = 2]]
assert.same { foo: "some \"string\"" }, res[1].config
assert pg\query [[
drop table json_test
]]
describe "arrays", ->
import decode_array, encode_array from require "pgmoon.arrays"
it "converts table to array", ->
import PostgresArray from require "pgmoon.arrays"
array = PostgresArray {1,2,3}
assert.same {1,2,3}, array
assert PostgresArray.__base == getmetatable array
it "encodes array value", ->
assert.same "ARRAY[1,2,3]", encode_array {1,2,3}
assert.same "ARRAY['hello','world']", encode_array {"hello", "world"}
assert.same "ARRAY[[4,5],[6,7]]", encode_array {{4,5}, {6,7}}
it "decodes empty array value", ->
assert.same {}, decode_array "{}"
import PostgresArray from require "pgmoon.arrays"
assert PostgresArray.__base == getmetatable decode_array "{}"
it "decodes numeric array", ->
assert.same {1}, decode_array "{1}", tonumber
assert.same {1, 3}, decode_array "{1,3}", tonumber
assert.same {5.3}, decode_array "{5.3}", tonumber
assert.same {1.2, 1.4}, decode_array "{1.2,1.4}", tonumber
it "decodes multi-dimensional numeric array", ->
assert.same {{1}}, decode_array "{{1}}", tonumber
assert.same {{1,2,3},{4,5,6}}, decode_array "{{1,2,3},{4,5,6}}", tonumber
it "decodes literal array", ->
assert.same {"hello"}, decode_array "{hello}"
assert.same {"hello", "world"}, decode_array "{hello,world}"
it "decodes multi-dimensional literal array", ->
assert.same {{"hello"}}, decode_array "{{hello}}"
assert.same {{"hello", "world"}, {"foo", "bar"}},
decode_array "{{hello,world},{foo,bar}}"
it "decodes string array", ->
assert.same {"hello world"}, decode_array [[{"hello world"}]]
it "decodes multi-dimensional string array", ->
assert.same {{"hello world"}, {"yes"}},
decode_array [[{{"hello world"},{"yes"}}]]
it "decodes string escape sequences", ->
assert.same {[[hello \ " yeah]]}, decode_array [[{"hello \\ \" yeah"}]]
it "fails to decode invalid array syntax", ->
assert.has_error ->
decode_array [[{1, 2, 3}]]
it "decodes literal starting with numbers array", ->
assert.same {"1one"}, decode_array "{1one}"
assert.same {"1one", "2two"}, decode_array "{1one,2two}"
it "decodes json array result", ->
res = pg\query "select array(select row_to_json(t) from (values (1,'hello'), (2, 'world')) as t(id, name)) as items"
assert.same {
{
items: {
{ id: 1, name: "hello" }
{ id: 2, name: "world" }
}
}
}, res
it "decodes jsonb array result", ->
assert.same {
{
items: {
{ id: 442, name: "itch" }
{ id: 99, name: "zone" }
}
}
}, pg\query "select array(select row_to_json(t)::jsonb from (values (442,'itch'), (99, 'zone')) as t(id, name)) as items"
describe "with table", ->
before_each ->
pg\query "drop table if exists arrays_test"
it "loads integer arrays from table", ->
assert pg\query "create table arrays_test (
a integer[],
b int2[],
c int8[],
d numeric[],
e float4[],
f float8[]
)"
num_cols = 6
assert pg\query "insert into arrays_test
values (#{"'{1,2,3}',"\rep(num_cols)\sub 1, -2})"
assert pg\query "insert into arrays_test
values (#{"'{9,5,1}',"\rep(num_cols)\sub 1, -2})"
assert.same {
{
a: {1,2,3}
b: {1,2,3}
c: {1,2,3}
d: {1,2,3}
e: {1,2,3}
f: {1,2,3}
}
{
a: {9,5,1}
b: {9,5,1}
c: {9,5,1}
d: {9,5,1}
e: {9,5,1}
f: {9,5,1}
}
}, (pg\query "select * from arrays_test")
it "loads string arrays from table", ->
assert pg\query "create table arrays_test (
a text[],
b varchar[],
c char(3)[]
)"
num_cols = 3
assert pg\query "insert into arrays_test
values (#{"'{one,two}',"\rep(num_cols)\sub 1, -2})"
assert pg\query "insert into arrays_test
values (#{"'{1,2,3}',"\rep(num_cols)\sub 1, -2})"
assert.same {
{
a: {"one", "two"}
b: {"one", "two"}
c: {"one", "two"}
}
{
a: {"1", "2", "3"}
b: {"1", "2", "3"}
c: {"1 ", "2 ", "3 "}
}
}, (pg\query "select * from arrays_test")
it "loads string arrays from table", ->
assert pg\query "create table arrays_test (ids boolean[])"
assert pg\query "insert into arrays_test (ids) values ('{t,f}')"
assert pg\query "insert into arrays_test (ids) values ('{{t,t},{t,f},{f,f}}')"
assert.same {
{ ids: {true, false} }
{ ids: {
{true, true}
{true, false}
{false, false}
} }
}, (pg\query "select * from arrays_test")
it "converts null", ->
pg.convert_null = true
res = assert pg\query "select null the_null"
assert pg.NULL == res[1].the_null
it "converts to custom null", ->
pg.convert_null = true
n = {"hello"}
pg.NULL = n
res = assert pg\query "select null the_null"
assert n == res[1].the_null
it "encodes bytea type", ->
n = { { bytea: "encoded' string\\" } }
enc = pg\encode_bytea n[1].bytea
res = assert pg\query "select #{enc}::bytea"
assert.same n, res
it "returns error message", ->
status, err = pg\query "select * from blahlbhabhabh"
assert.falsy status
assert.same [[ERROR: relation "blahlbhabhabh" does not exist (15)]], err
it "allows a query after getting an error", ->
status, err = pg\query "select * from blahlbhabhabh"
assert.falsy status
res = pg\query "select 1"
assert.truthy res
it "errors when connecting with invalid server", ->
pg2 = Postgres {
database: "doesnotexist"
user: USER
host: HOST
port: PORT
:socket_type
}
status, err = pg2\connect!
assert.falsy status
assert.same [[FATAL: database "doesnotexist" does not exist]], err
describe "pgmoon without server", ->
escape_ident = {
{ "dad", '"dad"' }
{ "select", '"select"' }
{ 'love"fish', '"love""fish"' }
}
escape_literal = {
{ 3434, "3434" }
{ 34.342, "34.342" }
{ "cat's soft fur", "'cat''s soft fur'" }
{ true, "TRUE" }
}
local pg
before_each ->
pg = Postgres!
for {ident, expected} in *escape_ident
it "escapes identifier '#{ident}'", ->
assert.same expected, pg\escape_identifier ident
for {lit, expected} in *escape_literal
it "escapes literal '#{lit}'", ->
assert.same expected, pg\escape_literal lit
| 30.948718 | 131 | 0.47648 |
013c8dc3d746ad918e22766a841fab59654ad475 | 2,159 | export script_name = 'Selegator'
export script_description = 'Select/navigate in the subtitle grid'
aegisub.register_macro script_name..'/Current style/select all', script_description, (subs, sel, act) ->
lookforstyle = subs[act].style
if #sel>1
[i for i in *sel when subs[i].style==lookforstyle]
else
[k for k,s in ipairs subs when s.style==lookforstyle]
aegisub.register_macro script_name..'/Current style/previous', '', (subs, sel, act) ->
lookforstyle = subs[act].style
for i = act-1,1,-1
return if subs[i].class!='dialogue'
if subs[i].style==lookforstyle
return {i}
aegisub.register_macro script_name..'/Current style/next', '', (subs, sel, act) ->
lookforstyle = subs[act].style
for i = act+1,#subs
if subs[i].style==lookforstyle
return {i}
aegisub.register_macro script_name..'/Current style/first in block', '', (subs, sel, act) ->
lookforstyle = subs[act].style
for i = act-1,1,-1
if subs[i].class!='dialogue' or subs[i].style!=lookforstyle
return {i+1}
aegisub.register_macro script_name..'/Current style/last in block', '', (subs, sel, act) ->
lookforstyle = subs[act].style
for i = act+1,#subs
if subs[i].style!=lookforstyle
return {i-1}
{#subs}
aegisub.register_macro script_name..'/Current style/select block', '', (subs, sel, act) ->
lookforstyle = subs[act].style
first, last = act, #subs
for i = act-1,1,-1
if subs[i].class!='dialogue' or subs[i].style!=lookforstyle
first = i + 1
break
for i = act+1,#subs
if subs[i].class!='dialogue' or subs[i].style!=lookforstyle
last = i - 1
break
[i for i=first,last]
aegisub.register_macro script_name..'/Select till start',
'Unlike built-in Shift-Home, it preserves the active line',
(subs, sel, act) -> [i for i = 1,act when subs[i].class=='dialogue']
aegisub.register_macro script_name..'/Select till end',
'Unlike built-in Shift-End, it preserves the active line',
(subs, sel, act) -> [i for i = act,#subs when subs[i].class=='dialogue']
| 37.877193 | 104 | 0.629458 |
888ed8eed63404348a8158be7dd8101a7bb12fa2 | 3,969 | import signal from howl
describe 'signal', ->
describe '.register(name, options)', ->
it 'raises an error if mandatory fields are missing', ->
assert.raises 'description', -> signal.register 'foo'
it '.all contains all registered signals', ->
signal.register 'foo', description: 'bar'
assert.same description: 'bar', signal.all.foo
describe '.unregister(name)', ->
it 'unregisters the specified signal', ->
signal.register 'frob', description: 'bar'
signal.unregister 'frob'
assert.is_nil signal.all.frob
context 'trying to use a non-registered signal', ->
it 'emit raises an error', ->
assert.raises 'none', -> signal.emit 'none'
it 'connect raises an error', ->
assert.raises 'none', -> signal.connect 'none', -> true
context 'with a registered signal', ->
before_each -> signal.register 'foo', description: 'bar'
after_each -> signal.unregister 'foo'
it 'allows name based signals to be broadcasted to any number of handlers', ->
handler1 = spy.new -> nil
handler2 = spy.new -> nil
signal.connect 'foo', handler1
signal.connect 'foo', handler2
signal.emit 'foo'
assert.spy(handler1).was_called!
assert.spy(handler2).was_called!
it 'allows connecting handlers before existing handlers', ->
value = nil
signal.connect 'foo', -> value = 'first'
signal.connect 'foo', (-> value = 'second'), 1
signal.emit 'foo'
assert.equal value, 'first'
it 'allows disconnecting handlers', ->
handler = spy.new -> true
signal.connect 'foo', handler
signal.disconnect 'foo', handler
signal.emit 'foo'
assert.spy(handler).was.not_called!
describe '.emit', ->
it 'raises an error when called with more than two parameters', ->
assert.raises 'parameter', -> signal.emit 'foo', {}, 2
it 'raises an error when the second parameter is not a table', ->
assert.raises 'table', -> signal.emit 'foo', 2
context 'when a handler returns true', ->
it 'skips invoking subsequent handlers', ->
handler2 = spy.new -> true
signal.connect 'foo', -> true
signal.connect 'foo', handler2
signal.emit 'foo'
assert.spy(handler2).was.not_called!
it 'returns true', ->
signal.connect 'foo', -> true
assert.is_true signal.emit 'foo'
context 'when a handler raises an error', ->
it 'logs an error message', ->
signal.connect 'foo', -> error 'BOOM'
signal.emit 'foo'
assert.match log.last_error.message, 'BOOM'
it 'continues processing subsequent handlers', ->
handler2 = spy.new -> true
signal.connect 'foo', -> error 'BOOM'
signal.connect 'foo', handler2
signal.emit 'foo'
assert.spy(handler2).was_called!
it 'returns false if no handlers returned true', ->
assert.is_false signal.emit 'foo'
signal.connect 'foo', -> 'this is fortunately not true'
assert.is_false signal.emit 'foo'
it 'invokes all handlers in their own coroutines', ->
coros = {}
coro_register = ->
co, main = coroutine.running!
coros[co] = true unless main
handler1 = spy.new coro_register
handler2 = spy.new coro_register
signal.connect 'foo', handler1
signal.connect 'foo', handler2
signal.emit 'foo'
assert.equal 2, #[v for _, v in pairs coros]
context 'when a handler yields', ->
it 'continues on invoking subsequent handlers', ->
handler2 = spy.new -> true
signal.connect 'foo', -> coroutine.yield false
signal.connect 'foo', handler2
signal.emit 'foo'
assert.spy(handler2).was_called!
it 'returns false', ->
signal.connect 'foo', -> coroutine.yield true
assert.is_false signal.emit 'foo'
| 35.123894 | 82 | 0.608718 |
e289402a91369800e108a25601391f818824d7d1 | 878 | html = require "lapis.html"
config = (require "lapis.config").get!
appname=config.appname or "l0g1n.de"
class MainLayout extends html.Widget
@include "views.mixin.header"
@include "views.mixin.favicon"
content: =>
html_5 ->
head ->
meta charset:"utf-8"
meta name:"viewport", content:"width=device-width, initial-scale=1"
link rel:"stylesheet", href:"/static/css/pure-min.css"
link rel:"stylesheet", href:"/static/css/main_layout.less.css"
script src:"/static/js/jquery.min.js"
title (@title and @title.." - "..appname) or (@has_content_for("title") and @content_for("title").." - "..appname) or appname
@mixFavicon!
body class:"route-"..@route_name..(type(@body_classes)=="string" and " "..@body_classes or ""),->
@mixin_header!
div class:"content",->
@content_for "inner"
| 39.909091 | 133 | 0.629841 |
857d97f714e5070ba8516bb7c905a75288aa5846 | 1,118 | Texture = sauce3.java.require "com.badlogic.gdx.graphics.Texture"
Constants = require "sauce3.wrappers"
class
new: (path, format = "rgba8", f_type) =>
file = sauce3.File path, f_type
@texture = sauce3.java.new Texture, file.file, Constants.formats[format], false
@texture\setFilter Constants.filters["linear"], Constants.filters["linear"]
get_dimensions: =>
@get_width!, @get_height!
get_filter: =>
min_filter = @texture\getMinFilter!
mag_filter = @texture\getMagFilter!
Constants.filter_codes[min_filter], Constants.filter_codes[mag_filter]
get_format: =>
texture_data = @texture\getTextureData!
format = texture_data\getFormat!
Constants.format_codes[format]
get_width: =>
@texture\getWidth!
get_height: =>
@texture\getHeight!
get_wrap: =>
Constants.wraps[@texture\getUWrap!], Constants.wraps[@texture\getVWrap!]
set_filter: (min, mag) =>
@texture\setFilter Constants.filters[min], Constants.filters[mag]
set_wrap: (h, v) =>
@texture\setWrap Constants.wraps[h], Constants.wraps[v]
dispose: =>
@texture\dispose!
| 26 | 83 | 0.69678 |
5f4cd9dbfdf9d692c9e87d5cbbd85a14be99fb6b | 1,345 |
import validate from require "lapis.validate"
o = {
age: ""
name: "abc"
height: "12234234"
}
tests = {
{
{
{ "age", exists: true }
{ "name", exists: true }
{ "rupture", exists: true, "CUSTOM MESSAGE COOL" }
}
{ "age must be provided", "CUSTOM MESSAGE COOL" }
}
{
{
{ "name", exists: true, min_length: 4 }
{ "age", min_length: 4 }
{ "height", max_length: 5 }
}
{
"name must be at least 4 chars"
"age must be at least 4 chars"
"height must be at most 5 chars"
}
}
{
{
{ "height", is_integer: true }
{ "name", is_integer: true }
{ "age", is_integer: true }
}
{
"name must be an integer"
"age must be an integer"
}
}
{
{
{ "height", min_length: 4 }
}
nil
}
{
{
{ "age", optional: true, max_length: 2 }
{ "name", optional: true, max_length: 2 }
}
{
"name must be at most 2 chars"
}
}
{
{
{ "name", one_of: {"cruise", "control" } }
}
{
"name must be one of cruise, control"
}
}
{
{
{ "name", one_of: {"bcd", "abc" } }
}
}
}
describe "lapis.validate", ->
for {input, output} in *tests
it "should match", ->
errors = validate o, input
assert.same errors, output
| 14.944444 | 56 | 0.475093 |
12b3df4694c56f4fdd6920aa187c6202a98cb384 | 1,085 | signals = assert require "hump.signal"
import bind_methods from assert require "moon"
--------------------------------------------------------------------------------
class Sounds
load: =>
with love.audio
@["cue-hits-ball"] = .newSource "resources/cue-hits-ball.wav", "static"
@["white-hit"] = .newSource "resources/white-hit.wav", "static"
@["ball-hits-ball"] = .newSource "resources/ball-hits-ball.wav", "static"
@["ball-touches-border"] = .newSource "resources/ball-touches-border.wav", "static"
@["ball-in-hole"] = .newSource "resources/ball-in-hole.wav", "static"
signals.register "shoot", -> @\shot!
signals.register "ball-in-hole", -> @\score!
signals.register "collision", (...) -> @\collision ...
shot: => @["cue-hits-ball"]\play!
score: => @["ball-in-hole"]\play!
collision: (coltype) =>
sound = @[coltype] or @["ball-hits-ball"]
sound\play!
--------------------------------------------------------------------------------
bind_methods Sounds!
| 37.413793 | 95 | 0.499539 |
625033209e1bd07ef3fe7e11d8420705d62547d7 | 8,783 | import pairs, type from _G
import lower from string
import Object from require "core"
import readFileSync from require "fs"
import basename, dirname, extname from require "path"
import decode from "novacbn/properties/exports"
import VirtualFileSystem from "novacbn/luvit-extras/vfs"
import FileSystemAdapter from "novacbn/luvit-extras/adapters/FileSystemAdapter"
fsx = dependency "novacbn/luvit-extras/fs"
import Theme from "novacbn/lunarbook/api/Theme"
import PluginManager from "novacbn/lunarbook/api/PluginManager"
import ALLOWED_FRAGMENT_TYPES, BOOK_HOME, BUILD_DIRS from "novacbn/lunarbook/lib/constants"
import extractSections, extractTitle from "novacbn/lunarbook/lib/utilities"
import endswith, slugify from "novacbn/lunarbook/lib/utilities/string"
import isdirSync, isfileSync, join from "novacbn/lunarbook/lib/utilities/vfs"
import LunarConfig from "novacbn/lunarbook/schemas/LunarConfig"
-- ::ProcessedFragment(string render, string link, string title, table sections) -> ProcessedFragments
-- Represents a book fragment that's been processed
--
ProcessedFragment = (render, link, title, sections) -> {
-- ProcessedFragment::link -> string
-- Represents the canonical URL link of the fragment
--
link: link
-- ProcessedFragment::render -> string
-- Represents the rendered layout of the fragment
--
render: render
-- ProcessedFragment::title -> string
-- Represents the extracted title of the fragment
--
title: title
-- ProcessedFragment::sections -> table
-- Represents the extract header sections of the fragment
--
sections: sections
}
-- Book::Book()
-- Represents a LunarBook build
-- export
export Book = with Object\extend()
-- Book::cache -> table
-- Represents a lookup table of previously-processed fragments
--
.cache = nil
-- Book::configuration -> table
-- Represents the configuration of the current book
--
.configuration = nil
-- Book::layoutEnvironment -> table
-- Represents the environment of for LunarViz Layouts
--
.layoutEnvironment = nil
-- Book::plugins -> PluginManager
-- Represents the plugins loaded for this book
--
.plugins = nil
-- Book::styleEnvironment -> table
-- Represents the environment of for LunarViz Styles
--
.styleEnvironment = nil
-- Book::theme -> Theme
-- Represents the theme of the LunarBook
--
.theme = nil
-- Book::vfs -> VirtualFileSystem
-- Represents the VirtualFileSystem used for the book
--
.vfs = nil
-- Book::initialize(string bookDirectory, string buildDirectory, string themeDirectory) -> void
-- Constructor for Book
--
.initialize = (bookDirectory, buildDirectory, themeDirectory) =>
error("bad argument #1 to 'initialize' (expected string)") unless type(bookDirectory) == "string"
error("bad argument #2 to 'initialize' (expected string)") unless type(buildDirectory) == "string"
local configuration
if fsx.isfileSync(BOOK_HOME.configuration)
contents = readFileSync(BOOK_HOME.configuration)
configuration = decode(contents, propertiesEncoder: "moonscript")
@configuration, err = LunarConfig\transform(configuration)
error("bad dispatch to 'initialize' (malformed book config)\n#{err}") if err
@cache = {}
@plugins = PluginManager\new()
@theme = Theme\new(themeDirectory, @configuration.theme)
@vfs = VirtualFileSystem\new()
@vfs\mount("book", FileSystemAdapter\new(bookDirectory))
@vfs\mount("build", FileSystemAdapter\new(buildDirectory))
-- Create the missing asset directories if needed
@vfs\mkdirSync(BUILD_DIRS.assets) unless isdirSync(@vfs, BUILD_DIRS.assets)
@vfs\mkdirSync(BUILD_DIRS.fragments) unless isdirSync(@vfs, BUILD_DIRS.fragments)
@vfs\mkdirSync(BUILD_DIRS.scripts) unless isdirSync(@vfs, BUILD_DIRS.scripts)
@vfs\mkdirSync(BUILD_DIRS.styles) unless isdirSync(@vfs, BUILD_DIRS.styles)
@initializePlugins()
@initializeAssets()
-- Book::initializeAssets() -> void
-- Collects the assets required by the style and pushes them to the environment
--
.initializeAssets = () =>
for asset in *@theme\getIncludedAssets()
@vfs\writeFileSync(join(BUILD_DIRS.assets, asset.name), asset.contents)
@theme.configuration.environment.scripts = ["assets/"..asset.name for asset in *@theme\getIncludedAssets() when endswith(lower(asset.name), ".js")]
@theme.configuration.environment.styles = ["assets/"..asset.name for asset in *@theme\getIncludedAssets() when endswith(lower(asset.name), ".css")]
-- Book::initializePlugins() -> void
-- Initializes the user-supplied plugins
--
.initializePlugins = () =>
@plugins\processConfiguration(@configuration.plugins)
@transformers = @plugins\configureTransformers()
@layoutEnvironment = @plugins\configureLayoutEnvironment()\clone()
@styleEnvironment = @plugins\configureStyleEnvironment()\clone()
-- Book::createFragment(string file, table fragments) -> void
-- Creates the fragment in the build directory
--
.createFragment = (file, fragments) =>
fragment = @processFragment(file)
layout = @theme\render("Index", true, @layoutEnvironment, fragment: fragment.render, link: fragment.link, navigation: fragments)
link = join(BUILD_DIRS.fragments, fragment.link)
@vfs\mkdirSync(link) unless isdirSync(@vfs, link)
@vfs\writeFileSync(join(link, "index.html"), fragment.render)
@vfs\mkdirSync(BUILD_DIRS.scheme..fragment.link) unless isdirSync(@vfs, BUILD_DIRS.scheme..fragment.link)
@vfs\writeFileSync(BUILD_DIRS.scheme..join(fragment.link, "index.html"), layout)
-- Book::processBook() -> void
-- Processes the directory of the LunarBook
--
.processBook = () =>
-- Start processing the book from the base directory
@processDirectory("")
-- Write any memory-cached assets to disk
@vfs\writeFileSync(join(BUILD_DIRS.fragments, fragment.link..".html"), fragment.render) for fragment in *@cache
--@vfs\writeFileSync(join(BUILD_DIRS.scripts, "lunarbook.components.js", @theme\getComputedScript())
@vfs\writeFileSync(join(BUILD_DIRS.styles, "lunarbook.components.css"), @theme\getComputedStyle(true, @styleEnvironment))
-- Book::processDirectory(string directory) -> void
-- Processes the directory of the book
--
.processDirectory = (directory) =>
entries = @vfs\readdirSync("book://"..directory)
directories = [entry for entry in *entries when isdirSync(@vfs, "book://"..join(directory, entry))]
files = [entry for entry in *entries when isfileSync(@vfs, "book://"..join(directory, entry)) and ALLOWED_FRAGMENT_TYPES[lower(extname(entry))]]
fragments = [@processFragment(join(directory, fragment)) for fragment in *files]
if #directories > 0 or #files > 0
@vfs\mkdirSync("build://#{directory}") unless isdirSync(@vfs, "build://#{directory}")
@vfs\mkdirSync(join(BUILD_DIRS.fragments, directory)) unless isdirSync(@vfs, join(BUILD_DIRS.fragments, directory))
@processDirectory(join(directory, entry)) for entry in *directories
@createFragment(join(directory, entry), #fragments > 1 and fragments) for entry in *files
--@createNavigation(directory, files) if #files > 1
-- Book::processFragment(string file) -> table
-- Processes the LunarBook fragment for metadata
--
.processFragment = (file) =>
unless @cache[file]
-- Load the fragment from disk and then have the theme process and render it
contents = @vfs\readFileSync("book://"..file)
contents = @transformers\processFragment(file, false, contents)
layout = @theme\render("Fragment", true, @layoutEnvironment, fragment: contents)
-- Slugify and use the title of the fragment as the link
-- Or, if the link is an index file, use the base directory
link = dirname(file)
link = "" if link == "."
title = extractTitle(layout)
unless basename(file, extname(file)) == "index"
link = join(link, slugify(title))
error("bad argument #1 to 'processFragment' (missing or malformed title)") unless #link > 0
sections = [{title: section, slug: slugify(section)} for section in *extractSections(layout)]
@cache[file] = ProcessedFragment(layout, link, title, sections)
return @cache[file] | 43.480198 | 158 | 0.675282 |
9c3191c92e57d580376c4e7f29e6c15499fe542d | 1,658 | -- title: Bunnymark in MoonScript
-- author: Rob Loach
-- desc: Benchmarking tool to see how many bunnies can fly around the screen, using MoonScript.
-- input: gamepad
-- script: moon
-- version: 1.1.0
screenWidth = 240
screenHeight = 136
toolbarHeight = 6
t = 0
class Bunny
@width: 26
@height: 32
new: =>
@x = math.random(0, screenWidth - @@width)
@y = math.random(0, screenHeight - @@height)
@speedX = math.random(-100, 100) / 60
@speedY = math.random(-100, 100) / 60
@sprite = 1
draw: () =>
spr(@sprite, @x, @y, 1, 1, 0, 0, 4, 4)
update: () =>
@x += @speedX
@y += @speedY
if @x + @@width > screenWidth
@x = screenWidth - @@width
@speedX *= -1
if @x < 0
@x = 0
@speedX *= -1
if @y + @@height > screenHeight
@y = screenHeight - @@height
@speedY *= -1
if @y < toolbarHeight
@y = toolbarHeight
@speedY *= -1
class FPS
new: =>
@value = 0
@frames = 0
@lastTime = 0
getValue: () =>
if time() - @lastTime <= 1000
@frames += 1
else
@value = @frames
@frames = 0
@lastTime = time()
return @value
fps = FPS!
bunnies = {}
table.insert(bunnies, Bunny!)
export TIC=->
-- music
if t == 0 then
music(0)
if t == 6*64*2.375 then
music(1)
t = t + 1
-- Input
if btn(0)
for i = 1, 5
table.insert(bunnies, Bunny!)
elseif btn(1)
for i = 1, 5
table.remove(bunnies, 1)
-- Update
for i, item in pairs bunnies
item\update!
-- Draw
cls(15)
for i, item in pairs bunnies
item\draw!
rect(0, 0, screenWidth, toolbarHeight, 0)
print("Bunnies: " .. #bunnies, 1, 0, 11, false, 1, false)
print("FPS: " .. fps\getValue!, screenWidth / 2, 0, 11, false, 1, false)
| 18.21978 | 95 | 0.587455 |
d3616c47eabaff9fabd9632ac64702838e03b79a | 2,606 |
--
-- 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.
export PPM2
PPM2 = PPM2 or {}
shared = (filein) ->
AddCSLuaFile('ppm2/' .. filein) if SERVER
include('ppm2/' .. filein)
server = (filein) -> include('ppm2/' .. filein) if SERVER
client = (filein) ->
AddCSLuaFile('ppm2/' .. filein) if SERVER
include('ppm2/' .. filein) if CLIENT
shared('common/modifier_base.lua')
shared('common/sequence_base.lua')
shared('common/sequence_holder.lua')
shared('common/controller_children.lua')
shared('common/registry.lua')
shared('common/functions.lua')
shared('common/bodygroup_controller.lua')
shared('common/weight_controller.lua')
shared('common/pony_expressions_controller.lua')
shared('common/emotes.lua')
shared('common/flex_controller.lua')
shared('common/registry_data.lua')
shared('common/ponydata.lua')
shared('common/bones_modifier.lua')
shared('common/ponyfly.lua')
shared('common/size_controller.lua')
shared('common/hooks.lua')
shared('common/hoofsteps.lua')
client('client/data_instance.lua')
client('client/materials_registry.lua')
client('client/texture_controller.lua')
client('client/new_texture_controller.lua')
client('client/hooks.lua')
client('client/functions.lua')
client('client/render_controller.lua')
client('client/emotes.lua')
client('client/player_menu.lua')
client('client/editor.lua')
client('client/editor3.lua')
client('client/rag_edit.lua')
client('client/render.lua')
server('server/misc.lua')
server('server/hooks.lua')
server('server/emotes.lua')
server('server/hitgroups.lua')
server('server/rag_edit.lua')
return nil
| 34.746667 | 92 | 0.764006 |
b774a21b9d5fb6b064fbbe83a9424cc24f3d9a00 | 500 | Gtk = require 'ljglibs.gtk'
describe 'Container', ->
local container
before_each -> container = Gtk.Box!
describe '.children', ->
it 'is a table of all children', ->
child1 = Gtk.Box!
child2 = Gtk.Box!
container\add child1
container\add child2
assert.same { child1, child2 }, container.children
it 'retains type information when possible', ->
child1 = Gtk.Box!
container\add child1
assert.equal 'GtkBox', container.children[1].__type
| 25 | 57 | 0.644 |