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
|
---|---|---|---|---|---|
f75528890e0b2331e4ad6c4d6c75cae005a90071 | 2,007 | import Model, enum from require "lapis.db.model"
import create_table, types, add_column from require "lapis.db.schema"
Users = require "lazuli.modules.user_management.models.users"
class ACL_Entries extends Model
matchUser: (user)=>
if user
if type(user)=="number"
user=Users\find user
return nil, "user not found" unless user
switch @target_type
when @@target_types.user
if user and @target_id == user.id
return @policy
when @@target_types.include, @@target_types.include_inverted
switch @target_id
when @@special_targets.include_everyone
return @policy
when @@special_targets.include_logged_in
return @policy if user
else
ACLs = require "models.acls"
list=ACLs\find @target_id
return nil, "include "..tostring(@target_id).." not found" unless list
ret=list\matchUser user, false
return nil, err if ret == nil and err
if type(ret)=="boolean"
return not ret if @target_type == @@target_types.include_inverted
return ret
@relations: {
{"acl", belongs_to: "ACLs"}
--{"target_user", belongs_to: "Users"}
--{"target_include", belongs_to: "ACLs"}
}
@get_relation_model: (name)=> switch name
when "Users"
require "lazuli.modules.user_management.models.users"
when "ACLs"
require "models.acls"
@target_types: enum {
include: 1
include_inverted: 2
user: 3
}
@special_targets: enum {
include_everyone: -1
include_logged_in: -2
}
@migrations: {
->
create_table "acl_entries", {
{"id", types.serial}
{"acl_id", types.integer}
{"position", types.integer default: 0}
{"policy", types.boolean}
{"target_type", types.integer}
{"target_id", types.integer null: true}
"PRIMARY KEY (id)"
}
}
| 29.086957 | 82 | 0.592427 |
a084e50db9444cdb7f7a6ebae0bbd8ba2526c43a | 1,229 |
-- inspect = require('inspect')
size = (list) ->
count = 0
for key, value in pairs list
count += 1
count
concat = (listA, listB) ->
resultList = {}
sizeA = size listA
for key, value in pairs listA
resultList[key] = value
for key, value in pairs listB
resultList[key + sizeA] = value
resultList
append = (list, item) ->
concat list, {item}
init = (list) ->
sizeX = size list
if sizeX < 1
error "call init upon empty table"
resultList = {}
for key, value in pairs list
if key < sizeX
resultList[key] = value
resultList
tail = (list) ->
resultList = {}
for key, value in pairs list
if key > 1
resultList[key - 1] = value
resultList
isArray = (list) ->
if type(list) != 'table'
return false
for key, value in pairs list
if (type key) != 'number'
return false
return true
map = (list, fn) ->
resultList = {}
for key, value in pairs list
resultList[key] = fn value, key
resultList
-- print inspect(concat {1,2,{3}}, {4,{5,6}})
-- print inspect(append {1,2,{3}}, 4)
-- print inspect(append {1,2,{3}}, {4})
-- print inspect(init {1,2,3})
-- print inspect(init {})
return {:size, :concat, :append, :init, :isArray, :tail, :map}
| 20.483333 | 62 | 0.606998 |
19d7b1f0a771b61dcb1edb62d83df6d334ba502b | 93 | export class Animation
new: (@name, @frames, @framerate, @looped = true, @callback = nil) => | 46.5 | 70 | 0.677419 |
3f27e26014166db93c120b7852c1174d93eb7023 | 181 | export modinfo = {
type: "command"
desc: "Set a player's character to nil"
alias: {"nil"}
func: getDoPlayersFunction (v) ->
pcall -> v.Character\Remove!
v.Character = nil
} | 22.625 | 40 | 0.662983 |
d31abd5c1a9f94529f76b8a40f07235520d0705a | 3,865 | import escape_pattern, parse_content_disposition, build_url from require "lapis.util"
import run_after_dispatch from require "lapis.nginx.context"
lapis_config = require "lapis.config"
flatten_params = (t) ->
{k, type(v) == "table" and v[#v] or v for k,v in pairs t}
parse_multipart = ->
out = {}
upload = require "resty.upload"
input, err = upload\new 8192
return nil, err unless input
input\set_timeout 1000 -- 1 sec
current = { content: {} }
while true
t, res, err = input\read!
switch t
when "body"
table.insert current.content, res
when "header"
unless type(res) == "table"
return nil, err or "failed to read upload header"
name, value = unpack res
if name\lower! == "content-disposition"
if params = parse_content_disposition value
for tuple in *params
current[tuple[1]] = tuple[2]
else
current[name\lower!] = value
when "part_end"
current.content = table.concat current.content
if current.name
if current["content-type"] -- a file
out[current.name] = current
else
out[current.name] = current.content
current = { content: {} }
when "eof"
break
else
return nil, err or "failed to read upload"
out
ngx_req = {
-- deprecated fields
referer: -> ngx.var.http_referer or ""
cmd_mth: -> ngx.var.request_method
cmd_url: -> ngx.var.request_uri
relpath: (t) -> t.parsed_url.path
srv: -> ngx.var.server_addr
built_url: (t) -> build_url t.parsed_url
--
headers: -> ngx.req.get_headers!
method: -> ngx.var.request_method
scheme: -> ngx.var.scheme
port: -> ngx.var.server_port
server_addr: -> ngx.var.server_addr
remote_addr: -> ngx.var.remote_addr
request_uri: -> ngx.var.request_uri
read_body_as_string: ->
=>
ngx.req.read_body!
ngx.req.get_body_data!
parsed_url: (t) ->
uri = ngx.var.request_uri
pos = uri\find("?")
uri = pos and uri\sub(1, pos-1) or uri
host_header = ngx.var.http_host
{
scheme: ngx.var.scheme
path: uri
host: ngx.var.host
port: host_header and host_header\match ":(%d+)$"
query: ngx.var.args
}
params_post: (t) ->
content_type = t.headers["content-type"] or ""
content_type = "" unless type(content_type) == "string"
content_type = content_type\lower!
params = if content_type\match escape_pattern "multipart/form-data"
parse_multipart!
elseif content_type\match escape_pattern "application/x-www-form-urlencoded"
ngx.req.read_body!
args = if max = lapis_config.get!.max_request_args
ngx.req.get_post_args max
else
ngx.req.get_post_args!
if args
flatten_params args
params or {}
params_get: ->
args = if max = lapis_config.get!.max_request_args
ngx.req.get_uri_args max
else
ngx.req.get_uri_args!
if args
flatten_params args
else
{}
}
lazy_tbl = (tbl, index) ->
setmetatable tbl, {
__index: (key) =>
fn = index[key]
if fn
with res = fn @
@[key] = res
}
build_request = (unlazy=false) ->
with t = lazy_tbl {}, ngx_req
if unlazy
for k in pairs ngx_req
t[k]
build_response = ->
{
req: build_request!
add_header: (k, v) =>
old = @headers[k]
switch type old
when "nil"
@headers[k] = v
when "table"
old[#old + 1] = v
@headers[k] = old
else
@headers[k] = {old, v}
headers: ngx.header
}
dispatch = (app) ->
res = build_response!
app\dispatch res.req, res
ngx.status = res.status if res.status
ngx.print res.content if res.content
run_after_dispatch!
res
{ :build_request, :build_response, :dispatch }
| 23.283133 | 85 | 0.606727 |
9cc4ea78d273ca9582e5fc29e758f18cad3c6da8 | 774 | class Point
new: (@position) =>
set_position: (@position) =>
----------------------------------
-- moves point by given deltas
----------------------------------
translate: (delta) =>
@position += delta
----------------------------------
-- projecting point one dimension down
----------------------------------
projection_n1: (a) =>
prime = {}
for i, v in ipairs @pos.content
l = a + @pos.content[#@pos.content]
if i < #@pos.content
prime[i] = a * v / l
Vector prime
----------------------------------
-- getting projection in given plane
----------------------------------
get_n: (n, pos=@pos, a) =>
if #pos.content <= n
return pos
else
@get_n n, (@projection_n1 pos, a), a
| 24.1875 | 42 | 0.401809 |
2fe99e351c4797a62a9bbf23fe9cf08b23ed5de5 | 7,196 | ---------------------------------------------------------------------------
-- Environment ------------------------------------------------------------
---------------------------------------------------------------------------
import execute from os
{ log:mlog, :floor } = math
menubars = require 'menubars'
import run from require 'shell'
import format, find from string
import next, ipairs, pairs from _G
log = require('log').get 'menubars'
{ sigcheck:T } = require 'typecheck'
import allVolumes from require 'hs.fs.volume'
{ new:StyledText } = require 'hs.styledtext'
import partial, partialr, once from require 'fn'
import sort, keys, join, filterk from require 'fn.table'
import launchOrFocusByBundleID from require 'hs.application'
---------------------------------------------------------------------------
-- Implementation ---------------------------------------------------------
---------------------------------------------------------------------------
NO_DATA_MENU = {{
title: 'No Data'
disabled: true
}}
PARAGON_NTFS_ITEM =
title: 'Open Paragon NTFS...'
fn: partial launchOrFocusByBundleID, 'com.paragon-software.ntfs.fsapp'
DISK_UTILITY_ITEM =
title: 'Open Disk Utility...'
fn: partial launchOrFocusByBundleID, 'com.apple.DiskUtility'
menuItem = nil
CAPACITY_UNITS = { 'bytes', 'kb', 'MB', 'GB', 'TB', 'PB' }
makeCapacityDesc = (bytes) ->
pow = floor mlog(bytes) / mlog(1000)
return format '%.3f' .. CAPACITY_UNITS[pow + 1], bytes / (1000 ^ pow)
makeUsageDesc = (total, available, showTotal) ->
used = total - available
usage = used / total * 100
capacity = makeCapacityDesc(showTotal and total or used)
return format '%.1f%%, %s', usage, capacity
diskutil = (op, path) ->
output = run 'diskutil', op, path
log.infof 'diskutil %s "%s": "%s"', op, path, output if log.infof
ejectDiskImages = (volumes) ->
for p, v in pairs volumes
diskutil 'eject', p if v.NSURLVolumeIsLocalKey and v.NSURLVolumeIsReadOnlyKey
makeVolumeItem = (path, volume, removing) ->
name = StyledText volume.NSURLVolumeLocalizedNameKey, {
font: { name: 'HelveticaNeue-Medium', size: 14 }
}
usage = makeUsageDesc volume.NSURLVolumeTotalCapacityKey, volume.NSURLVolumeAvailableCapacityKey
return if volume.NSURLVolumeIsInternalKey then {
title: format '%s (%s)', name, usage
fn: partial execute, format('open %q', path)
} elseif removing then {
title: format 'โ %s (%s)', name, usage
fn: partial diskutil, 'unmount', path
} else {
title: format '%s (%s)', name, usage
fn: (mods) ->
if mods and mods['alt'] then execute format('open %q', path)
else diskutil 'unmount', path
}
makeDetailedVolumeItem = (path, volume, flat) ->
name = StyledText volume.NSURLVolumeLocalizedNameKey, {
font: { name: 'HelveticaNeue-Medium', size: 14 }
}
total = volume.NSURLVolumeTotalCapacityKey
available = volume.NSURLVolumeAvailableCapacityKey
internal = volume.NSURLVolumeIsInternalKey
ejectable = volume.NSURLVolumeIsEjectableKey
usage = 'Usage: ' .. makeUsageDesc(total, available, false)
capacity = 'Capacity: ' .. makeCapacityDesc(total)
fs = 'File System: ' .. volume.NSURLVolumeLocalizedFormatDescriptionKey
removal = partial diskutil, (ejectable and 'eject' or 'unmount'), path
action = (mods) ->
if mods and mods['alt'] then removal!
else execute format('open %q', path)
return if flat then {
{ title: name, fn: action }
{ title: usage, disabled: true, indent: 1 }
{ title: capacity, disabled: true, indent: 1 }
{ title: fs, disabled: true, indent: 1 }
} else {
{
title: name, fn: action, menu: {
{ title: 'Open', fn: partial execute, format('open %q', path) }
{ title: ejectable and 'Eject' or 'Unmount', fn: removal, disabled: internal }
{ title: '-' }
{ title: usage, disabled: true }
{ title: capacity, disabled: true }
{ title: fs, disabled: true }
}
}
}
addVolumeItems = (volumes, menu, maker) ->
paths = keys volumes
-- sort by capacity.
sort paths, (l, r) ->
volumes[l].NSURLVolumeTotalCapacityKey > volumes[r].NSURLVolumeTotalCapacityKey
for _, p in ipairs paths
v = volumes[p]
item = maker p, v
if item.title -- is list of items
menu[#menu + 1] = item
else
join menu, item
addUtilityCommands = (volumes, menu) ->
local hasDiskImages, hasNTFSVolumes
for _, v in pairs volumes
if v.NSURLVolumeIsLocalKey and v.NSURLVolumeIsReadOnlyKey
hasDiskImages = true
if find v.NSURLVolumeLocalizedFormatDescriptionKey, 'Windows NT Filesystem'
hasNTFSVolumes = true
break if hasDiskImages and hasNTFSVolumes
menu[#menu + 1] = title: '-'
menu[#menu + 1] = {
title: 'Eject All Disk Images',
fn: partial ejectDiskImages, volumes
} if hasDiskImages
menu[#menu + 1] = DISK_UTILITY_ITEM
menu[#menu + 1] = PARAGON_NTFS_ITEM if hasNTFSVolumes
makeMenu = (showInternalVolumes, showUtilityCommands, modifiers) ->
volumes = allVolumes!
maker = partialr makeVolumeItem, modifiers and modifiers['alt']
return NO_DATA_MENU unless next volumes
externals = {}
internals = filterk volumes, (p, v) ->
return true if v.NSURLVolumeIsInternalKey
externals[p] = v
menu = {}
if showInternalVolumes
addVolumeItems internals, menu, maker
if next(externals) -- has external volumes
menu[#menu + 1] = title: '-'
addVolumeItems externals, menu, maker
elseif next externals
addVolumeItems externals, menu, maker
else
menu[#menu + 1] = { title: 'No External Volumes', disabled: true }
addUtilityCommands volumes, menu if showUtilityCommands
return menu
makeDetailedMenu = (showInternalVolumes, showUtilityCommands, modifiers) ->
volumes = allVolumes!
maker = partialr makeDetailedVolumeItem, modifiers and modifiers['alt']
return NO_DATA_MENU unless next volumes
externals = {}
internals = filterk volumes, (p, v) ->
return true if v.NSURLVolumeIsInternalKey
externals[p] = v
menu = {}
if showInternalVolumes
menu[#menu + 1] = { title: 'Internal', disabled: true }
addVolumeItems internals, menu, maker
if next(externals) -- has external volumes
menu[#menu + 1] = title: '-'
menu[#menu + 1] = { title: 'External & Disk Images', disabled: true }
addVolumeItems externals, menu, maker
elseif next externals
addVolumeItems externals, menu, maker
else
menu[#menu + 1] = { title: 'No External Volumes', disabled: true }
addUtilityCommands volumes, menu if showUtilityCommands
return menu
init = (options) ->
with options
icon = .icon or menubars._defaultIcon
detailed = .showVolumeDetails == true
showCommands = .showUtilityCommands != false
showInternals = .showInternalVolumes != false
menu = partial detailed and makeDetailedMenu or makeMenu, showInternals, showCommands
menuItem = menubars.new icon, .title, menu
---------------------------------------------------------------------------
-- Interface --------------------------------------------------------------
---------------------------------------------------------------------------
{
init: T 'table', once(init)
}
| 34.430622 | 98 | 0.626042 |
f31dcd544e181d558c34c55c0e62a580c6480293 | 660 | export modinfo = {
type: "command"
desc: "Private base"
alias: {"pb"}
func: (Msg,Speaker) ->
CreateInstance"Model"{
Parent: workspace
CreateInstance"Part"
Name: "PB"
Anchored: true
Locked: true
BrickColor: BrickColor.new("Bright green")
Size: Vector3.new(50,1,50)
CFrame: CFrame.new(0,1000,0)
CreateInstance"Part"
Locked: true
Anchored: true
CanCollide: false
Transparency: 1
CFrame: CFrame.new(0,1010,0)
}
LocalPlayer.Character.Torso.CFrame = CFrame.new(0,1020,0)
Output2("Private base created",{Color3.new(math.random(),math.random(),math.random())},Speaker)
loggit("Private base created")
} | 26.4 | 97 | 0.672727 |
a36668d0ae8c159675aecd79e15d3cc7e91e516a | 4,144 | Dorothy!
SelectionPanel = require "Control.Basic.SelectionPanel"
PickPanelView = require "View.Control.Operation.PickPanel"
PointControl = require "Control.Edit.PointControl"
import Round from require "Lib.Utils"
-- [params]
-- width, height
Class PickPanelView,
__init:=>
@editorType = nil
@itemType = nil
@pickedItem = nil
@pointControl = nil
itemString = ->
if tolua.type(@pickedItem) == "oVec2"
string.format "%d,%d",@pickedItem.x,@pickedItem.y
else
tostring @pickedItem
pickFunction = (editorType)->
(args)->
{itemType,currentItem} = args
if itemType == "Point"
@pointControl = with PointControl!
\show currentItem,if editor.currentData
editor\getItem editor.currentData
else
nil
\slot "PosChanged",(pos)->
@pickedItem = Round pos
@label.text = itemString!
@parent\addChild @pointControl,-1
else
itemName = currentItem\match "^[^%.]*"
item = editor.items[itemName]
itemData = item and editor\getData(item) or nil
emit "Scene.ViewPanel.Pick",itemData
@selectEvent.enabled = true
@editorType = editorType
@itemType = itemType
@pickedItem = currentItem
@visible = true
@title.text = itemType
@label.text = itemString!
@showButton!
with @panel
.scaleX,.scaleY = 0,0
\perform oScale 0.3,1,1,oEase.OutBack
@gslot "Scene.Trigger.Picking",pickFunction "Trigger"
@gslot "Scene.Action.Picking",pickFunction "Action"
@gslot "Scene.AINode.Picking",pickFunction "AINode"
@selectEvent = @gslot "Scene.ViewPanel.Select",(itemData)->
if @itemType ~= "Point"
@pickedItem = nil
@label.text = ""
if itemData and @itemType
switch @itemType
when "Sensor"
if itemData.itemType == "Body"
bodyGroup = editor\getItem itemData
sensors = {}
bodyGroup.data\each (name,item)->
if tolua.type(item) == "oBody" and item.sensor
table.insert sensors,name
if #sensors > 0
with SelectionPanel {
title:"Select Sensor"
width:150
items:sensors
itemHeight:40
fontSize:20
}
\slot "Selected",(item)->
return unless item
@pickedItem = itemData.name.."."..item
@label.text = itemString!
@showButton!
when "Slice"
if itemData.itemType == "Body"
bodyGroup = editor\getItem itemData
slices = {}
bodyGroup.data\each (name,item)->
if tolua.type(item) == "oBody" and not item.sensor
table.insert slices,name
if #slices > 0
with SelectionPanel {
title:"Select Slice"
width:150
items:slices
itemHeight:40
fontSize:20
}
\slot "Selected",(item)->
return unless item
@pickedItem = itemData.name.."."..item
@label.text = itemString!
@showButton!
when "Point"
isBody = itemData.itemType == "Body"
offset = isBody and itemData.position or oVec2.zero
with @pointControl
\show @pickedItem,editor\getItem(itemData),offset
if isBody
\schedule ->
.offset = itemData.position
.targetPos = @pickedItem+.offset
.circle.position = .targetPos
else
\unschedule!
when itemData.itemType
@pickedItem = itemData.name
@label.text = itemString!
@showButton!
@selectEvent.enabled = false
@pickBtn\slot "Tapped",->
emit "Scene.#{ @editorType }.Picked",@pickedItem
emit "Scene.#{ @editorType }.Open"
if @visible and not @scheduled
if @pointControl
@pointControl.parent\removeChild @pointControl
@pointControl = nil
@selectEvent.enabled = false
@panel\perform oScale 0.3,0,0,oEase.InBack
@pickBtn\perform oScale 0.3,0,0,oEase.InBack
@schedule once ->
sleep 0.3
@visible = false
showButton:=>
with @pickBtn
.scaleX,.scaleY = 0,0
\perform oScale 0.3,1,1,oEase.OutBack
| 29.81295 | 62 | 0.598214 |
344f8b6367662e96ed0ed44ef56375be4d0adff5 | 3,074 | dbi = require 'DBI'
require'logging.console'
log = logging.console()
conn = false
schemas = {[[
CREATE TABLE IF NOT EXISTS log (
time timestamp DEFAULT now(),
nick text,
channel text,
message text,
type text
);]],
[[CREATE INDEX idx_time ON log(time);]],
[[CREATE INDEX idx_channel ON log(channel);]]
}
connect = ->
conn, err = DBI.Connect('PostgreSQL', ivar2.config.dbname, ivar2.config.dbuser, ivar2.config.dbpass, ivar2.config.dbhost, ivar2.config.dbport)
unless conn
log\error "Unable to connect to DB: #{err}"
return
conn\autocommit(true)
--for s in *schemas
-- a,b = DBI.Do(conn, s)
dbh = ->
connect! unless conn
-- Check if connection is alive
alive = conn\ping!
connect! unless alive
success, err = DBI.Do(conn, 'SELECT NOW()')
unless success
log\error "SQL Connection :#{err}"
connect!
return conn
dblog = (type, source, destination, arg) =>
nick = source.nick
if type == 'PRIVMSG'
-- action
if arg\sub(1,1) == '\001' and arg\sub(-1) == '\001'
arg = arg\sub(9, -2)
type = 'ACTION'
unless arg
arg = ''
insert = dbh!\prepare('INSERT INTO log(nick,channel,message,type) values(?,?,?,?)')
stmt, err = insert\execute(nick, destination, arg, type)
unless stmt
log\error err
history = (source, destination, nr) ->
nr = tonumber(nr) or 1
stmt = dbh!\prepare [[
SELECT
*
FROM log
WHERE channel=?
AND (type = 'PRIVMSG' OR type = 'ACTION')
ORDER BY time
DESC LIMIT ?
]]
stmt\execute destination, nr
out = {}
for row in stmt\rows(true) -- true for column names
out[#out+1] = row
if #out == 1
return out[1].message
return out
lastlog = (source, destination, arg) ->
nr = tonumber(nr) or 1
arg = '%'..arg..'%'
stmt = dbh!\prepare [[
SELECT
*
FROM log
WHERE channel=?
AND (type = 'PRIVMSG' OR type = 'ACTION')
AND message LIKE ?
ORDER BY time DESC
LIMIT 20
]]
stmt\execute destination, arg
out = {}
for row in stmt\rows(true) -- true for column names
out[#out+1] = row
if #out == 1
return out[1].message
return out
return {
PRIVMSG: {
(s, d, a) =>
dblog @, 'PRIVMSG', s, d, a
'%plast$': (source, destination) =>
say history(source,destination,1)
'%plastlog (.+)$': (source, destination, arg) =>
out = {}
for k,v in *lastlog(source, destination, arg)
table.insert out, string.format('<%s> %s', k.nick, k.message)
say table.concat(out, ' ')
}
NOTICE: {
(s, d, a) =>
dblog @, 'NOTICE', s, d, a
}
JOIN: {
(s, d, a) =>
dblog @, 'JOIN', s, d, a
}
PART: {
(s, d, a) =>
dblog @, 'PART', s, d, a
}
KICK: {
(s, d, a) =>
dblog @, 'KICK', s, d, a
}
MODE: {
(s, d, a) =>
dblog @, 'MODE', s, d, a
}
TOPIC: {
(s, d, a) =>
dblog @, 'TOPIC', s, d, a
}
NICK: {
(s, d, a) =>
dblog @, 'NICK', s, d, a
}
QUIT: {
(s, d, a) =>
dblog @, 'QUIT', s, d, a
}
}
| 20.493333 | 144 | 0.544242 |
c816eba89d91114aa6899f4cad4269e2e15c510e | 4,990 | import concat from table
import char from string
import floor, tointeger from math
import zsplit, map, insgen, prerr, undecimal from require'opeth.common.utils'
import hexdecode, hextobin, adjustdigit, bintoint, hextoint, hextochar, bintohex, inttobin from undecimal
op_list = require'opeth.common.oplist' "abc", "abx", "asbx", "ab"
string = string
string.zsplit = zsplit
-- TODO: now only supported signed 64bit float
f2ieee = (flt) ->
if flt == 0 then return "0"\rep 64
bias = 1023
abs_flt = math.abs flt
e, m = math.modf abs_flt
while e == 0
abs_flt *= 2
bias -= 1
e, m = math.modf abs_flt
while e > 9.223372e18
e /= 2
bias += 1
mb = ""
pa = (inttobin e)\match"0*1(.*)" or ""
e = #pa + bias
for b in pa\gmatch"."
if #mb == 52 then break
mb ..= b
eb = adjustdigit (hextobin "%x"\format e)\match"0*(.*)", 11
for i = -1, -(52 - #mb), -1
p = 2^i
if m - p >= 0
m -= p
mb ..= "1"
if m == 0
while #mb < 52 do mb ..= "0"
break
else mb ..= "0"
(flt < 0 and "1" or "0") .. eb .. mb
-- Writer class
-- interface to write to file
-- {{{
class Writer
new: (cont) =>
typ = type cont
@cont = switch typ
when "userdata" then cont
when "string" then assert io.open(cont, "w+b"), "Writer.new #1: failed to open file `#{cont}'"
when "nil" then {block: "", write: ((a) => @block ..= a), flush: (=>), close: (=>), seek: (=>), read: (=>)}
else error "Writer.new receives only the type of string or file (got `#{typ}')"
@size = 0
__shl: (v) =>
@size += #v
with @ do @cont\write v
__len: => @size
close: =>
@cont\flush!
@cont\close!
show: =>
pos = @cont\seek "cur"
@cont\seek "set"
with @cont\read "*a"
@cont\seek "set", pos
-- }}}
-- write (re) encoded data to file
-- {{{
local adjust_endianness
regx = (i) -> hextobin "%x"\format i
writeint = (wt, int, dig = 8) -> map (=> wt << hextochar @), adjust_endianness (adjustdigit ("%x"\format int), dig)\zsplit 2
write_fnblock = (wt, fnblock, has_debug) ->
import chunkname, line, params, vararg, regnum, instruction, constant, upvalue, prototype, debug from fnblock
-- chunkname
-- {{{
if has_debug or #chunkname > 0
has_debug = true
wt << char #chunkname + 1
map (=> wt << @), chunkname\zsplit!
else wt << "\0"
-- }}}
-- parameters
-- {{{
map (=> writeint wt, (hextoint @)), {line.defined, line.lastdefined}
map (=> wt << hextochar @), {
params
vararg
regnum
}
-- }}}
-- instruction
-- {{{
writeint wt, #instruction
for i = 1, #instruction
{RA, RB, RC, :op} = instruction[i]
a = adjustdigit (regx RA), 8
rbc = if RC
concat map (=> adjustdigit (regx if @ < 0 then 2^8 - 1 - @ else @), 9), {RB, RC}
else adjustdigit (regx if op_list[op][2] == "asbx" then RB +2^17-1 else RB), 18
bins = rbc ..a..(adjustdigit (regx (op_list[op].idx - 1)), 6)
assert #bins == 32
map (=> wt << hextochar @), adjust_endianness (concat map (=> bintohex @), bins\zsplit 4)\zsplit 2
-- }}}
-- constant
-- {{{
writeint wt, #constant
for i = 1, #constant do with constant[i]
wt << char .type
switch .type
when 0x1 then wt << char .val
when 0x3
wt << c for c in *(adjust_endianness [("0x"..(bintohex cxa) .. (bintohex cxb))\char! for cxa, cxb in (f2ieee .val)\gmatch "(....)(....)"])
when 0x13 then writeint wt, .val, 16
when 0x4, 0x14
if #.val > 0xff
wt << char 0xff
writeint wt, #.val + 1, 16
else writeint wt, #.val + 1, 2
wt << .val
-- }}}
-- upvalue
-- {{{
writeint wt, #upvalue
map (=> wt << char @), adjust_endianness {upvalue[i].reg, upvalue[i].instack} for i = 1, #upvalue
-- }}}
-- prototype
-- {{{
writeint wt, #prototype
write_fnblock wt, prototype[i], has_debug for i = 1, #prototype
-- }}}
-- debug
-- {{{
-- {:linenum, :opline, :varnum, :varinfo, :upvnum, :upvinfo} = debug
import linenum, opline, varnum, varinfo, upvnum, upvinfo from debug
writeint wt, (has_debug and linenum or 0)
if has_debug then for i = 1, #(opline or "")
writeint wt, opline[i]
writeint wt, (has_debug and varnum or 0)
if has_debug then for i = 1, #(varinfo or "")
with varinfo[i]
writeint wt, #.varname+1, 2
wt << .varname
writeint wt, .life.begin
writeint wt, .life.end
writeint wt, (has_debug and upvnum or 0)
if has_debug then for i = 1, #(upvinfo or "")
writeint wt, #upvinfo[i]+1, 2
wt << upvinfo[i]
-- }}}
write = (wt, vmformat) ->
import header, fnblock from vmformat
adjust_endianness = header.endian < 1 and (=> @) or (xs) -> [xs[i] for i = #xs, 1, -1]
with header
map (=> wt << @), {
.hsig
(hextochar tointeger .version * 10)
(char .format)
.luac_data
}
with .size
map (=> wt << (char @)), {
.int
.size_t
.instruction
.lua_integer
.lua_number
}
map (=> wt << @), {
(concat adjust_endianness (((char 0x00)\rep 6) .. char 0x56, 0x78)\zsplit!)
.luac_num
.has_debug
}
write_fnblock wt, fnblock
wt
-- }}}
Writer.__base.write = write
:Writer, :write
| 22.995392 | 142 | 0.591383 |
bb4ddab80ec8e7b6ddb9b54c8b04c939113ebda9 | 2,532 |
_G.arg = {}
require"busted.runner"!
xml_lib = require "dist/xml" -- you need to build XML first
assert\register "assertion", "one_of", (state, arguments) ->
if not type(arguments[1]) == "table" or #arguments ~= 2
return false
for value in *arguments[2]
if value == arguments[1]
return true
return false
describe "xml building", ->
describe "name", ->
it "xml with a string as name", ->
xml = xml_lib.XML (E) -> E "Test"
assert.are.equal xml, "<Test/>"
it "xml with a number as name", ->
assert.has_error -> xml_lib.XML (E) -> E 1, "argument #1 must be string, not number"
describe "keyword arguments", ->
it "xml with strings as key/value", ->
xml = xml_lib.XML (E) -> E "Test", {test: "test"}
assert.are.equal xml, '<Test test="test"/>'
it "xml with a number as key", ->
assert.has_error ->
xml_lib.XML (E) -> E "Test", {"test"},
"XML keys must be string, not number"
it "xml with a number as value", ->
xml = xml_lib.XML (E) -> E "Test", {number: 1}
assert.are.equal xml, '<Test number="1"/>'
it "xml with a list as value", ->
xml = xml_lib.XML (E) -> E "Test", {test: {"abc", "def"}}
assert.are.equal xml, '<Test test=["abc", "def"]/>'
it "xml with multiple arguments", ->
xml = xml_lib.XML (E) -> E "Test", {testA: "test", testB: "test"}
assert.is.one_of xml, {'<Test testA="test" testB="test"/>', '<Test testB="test" testA="test"/>'}
describe "sub functions / elements", ->
it "xml no sub elements", ->
xml = xml_lib.XML (E) -> E "Test", {}, -> nil
assert.are.equal xml, '<Test></Test>'
it "xml sub elements", ->
xml = xml_lib.XML (E) -> E "Test", {}, -> E "Test"
assert.are.equal xml, '<Test><Test/></Test>'
it "xml sub elements (16)", ->
dept = 0
elem = (E) ->
dept += 1
if dept < 16
E "Test_#{dept}", {}, -> elem E
xml = xml_lib.XML (E) -> elem E
assert.are.equal xml, '<Test_1><Test_2><Test_3><Test_4><Test_5><Test_6><Test_7><Test_8><Test_9><Test_10><Test_11><Test_12><Test_13><Test_14><Test_15></Test_15></Test_14></Test_13></Test_12></Test_11></Test_10></Test_9></Test_8></Test_7></Test_6></Test_5></Test_4></Test_3></Test_2></Test_1>'
| 41.508197 | 303 | 0.515798 |
2d66336df8946c8a3035a2657a5e481089504d56 | 167 | [[local lapis = require("lapis")
local app = lapis.Application()
app:get("/", function()
return "Welcome to Lapis " .. require("lapis.version")
end)
return app
]]
| 16.7 | 56 | 0.664671 |
70143d8cfe9321609a275daa2115b8416f881c6c | 2,463 | db = require "lapis.db.postgres"
import BaseModel, Enum, enum from require "lapis.db.base_model"
class Model extends BaseModel
@db: db
-- create from table of values, return loaded object
@create: (values, opts) =>
if @constraints
for key in pairs @constraints
if err = @_check_constraint key, values and values[key], values
return nil, err
values._timestamp = true if @timestamp
local returning, return_all
if opts and opts.returning
if opts.returning == "*"
return_all = true
returning = { db.raw "*" }
else
returning = { @primary_keys! }
for field in *opts.returning
table.insert returning, field
unless return_all
for k, v in pairs values
if db.is_raw v
returning or= {@primary_keys!}
table.insert returning, k
res = if returning
db.insert @table_name!, values, unpack returning
else
db.insert @table_name!, values, @primary_keys!
if res
if returning and not return_all
for k in *returning
values[k] = res[1][k]
for k,v in pairs res[1]
values[k] = v
@load values
else
nil, "Failed to create #{@__name}"
-- thing\update "col1", "col2", "col3"
-- thing\update {
-- "col1", "col2"
-- col3: "Hello"
-- }
update: (first, ...) =>
cond = @_primary_cond!
columns = if type(first) == "table"
for k,v in pairs first
if type(k) == "number"
v
else
@[k] = v
k
else
{first, ...}
return nil, "nothing to update" if next(columns) == nil
if @@constraints
for _, column in pairs columns
if err = @@_check_constraint column, @[column], @
return nil, err
values = { col, @[col] for col in *columns }
-- update options
nargs = select "#", ...
last = nargs > 0 and select nargs, ...
opts = if type(last) == "table" then last
if @@timestamp and not (opts and opts.timestamp == false)
values._timestamp = true
local returning
for k, v in pairs values
if db.is_raw v
returning or= {}
table.insert returning, k
if returning
with res = db.update @@table_name!, values, cond, unpack returning
if update = unpack res
for k in *returning
@[k] = update[k]
else
db.update @@table_name!, values, cond
{ :Model, :Enum, :enum }
| 24.147059 | 72 | 0.573285 |
900d565b0e2f7d2a2bad9bbdca1655570692eef1 | 8,330 | -- Copyright 2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
Markers = require 'aullar.markers'
describe 'markers', ->
local markers, listener
before_each ->
listener = {
on_markers_added: spy.new -> nil
on_markers_removed: spy.new -> nil
}
markers = Markers listener
names = (ms) ->
n = [m.name for m in *ms]
table.sort n
n
describe 'add(markers)', ->
it 'raises an error if <data.name> is missing', ->
assert.raises 'name', -> markers\add { {start_offset: 1, end_offset: 2} }
it 'raises an error if <data.start_offset> is missing', ->
assert.raises 'start_offset', -> markers\add { {name: 'test', end_offset: 2} }
it 'raises an error if <data.end_offset> is missing', ->
assert.raises 'end_offset', -> markers\add { {name: 'test', start_offset: 2} }
it 'adds the specified marker for the designated span', ->
data = name: 'test', my_key: 'my_val', start_offset: 2, end_offset: 4
markers\add { data }
assert.same {}, markers\at(1)
assert.same {data}, markers\at(2)
assert.same {data}, markers\at(3)
assert.same {}, markers\at(4)
it 'notifies the listener', ->
mks = { {name: 'test', start_offset: 2, end_offset: 4} }
markers\add mks
assert.spy(listener.on_markers_added).was_called_with listener, mks
describe 'for_range(start_offset, end_offset [, selector])', ->
it 'returns all markers that intersects with the specified span', ->
markers\add { {name: 'test1', start_offset: 2, end_offset: 5} }
markers\add { {name: 'test2', start_offset: 4, end_offset: 6} }
assert.same {'test1'}, names(markers\for_range(1, 4))
assert.same {'test1', 'test2'}, names(markers\for_range(1, 5))
assert.same {'test1', 'test2'}, names(markers\for_range(4, 5))
assert.same {'test2'}, names(markers\for_range(5, 5))
assert.same {'test2'}, names(markers\for_range(5, 10))
assert.same {'test1', 'test2'}, names(markers\for_range(1, 30))
describe 'when <selector> is specified', ->
it 'only returns markers with fields matching selector', ->
markers\add { {name: 'test1', start_offset: 2, end_offset: 5, foo: 'bar'} }
markers\add { {name: 'test2', start_offset: 4, end_offset: 6, frob: 'nic'} }
assert.same {}, markers\for_range(1, 6, foo: 'other')
describe 'find(selector)', ->
it 'finds all markers matching the selector', ->
markers\add { {name: 'test1', start_offset: 1, end_offset: 2} }
markers\add { {name: 'test2', start_offset: 1, end_offset: 2} }
assert.same {
{name: 'test1', start_offset: 1, end_offset: 2}
}, markers\find name: 'test1'
assert.same {
{name: 'test2', start_offset: 1, end_offset: 2}
}, markers\find name: 'test2'
assert.same {}, markers\find foo: 'bar'
it 'markers can overlap', ->
markers\add { {name: 'test1', start_offset: 2, end_offset: 4} }
markers\add { {name: 'test2', start_offset: 3, end_offset: 4} }
assert.equals 1, #markers\at(2)
assert.equals 2, #markers\at(3)
assert.same {'test1', 'test2'}, names(markers\at(3))
describe 'remove(selector)', ->
it 'removes all markers matching the selector', ->
markers\add { {name: 'test1', start_offset: 2, end_offset: 3, foo: 'bar'} }
markers\add { {name: 'test2', start_offset: 5, end_offset: 6, foo: 'frob'} }
markers\remove foo: 'frob'
assert.same {'test1'}, names(markers\for_range(1, 7))
markers\remove!
assert.same {}, markers\for_range(1, 7)
it 'notifies the listener', ->
markers\add { {name: 'test1', start_offset: 2, end_offset: 3, foo: 'bar'} }
markers\add { {name: 'test2', start_offset: 5, end_offset: 6, foo: 'frob'} }
markers\remove foo: 'frob'
assert.spy(listener.on_markers_removed).was_called_with listener, {
{ name: 'test2', start_offset: 5, end_offset: 6, foo: 'frob' }
}
describe 'remove_for_range(start_offset, end_offset [, selector])', ->
it 'removes all markers within the range', ->
markers\add { {name: 'test1', start_offset: 2, end_offset: 3} }
markers\add { {name: 'test2', start_offset: 5, end_offset: 6} }
markers\remove_for_range 1, 4
assert.same {}, markers\at(2)
markers\remove_for_range 4, 10
assert.same {}, markers\at(5)
it 'notifies the listener', ->
markers\add { {name: 'test1', start_offset: 2, end_offset: 3} }
markers\add { {name: 'test2', start_offset: 5, end_offset: 6} }
markers\remove_for_range 1, 4
assert.spy(listener.on_markers_removed).was_called_with listener, {
{ name: 'test1', start_offset: 2, end_offset: 3 }
}
describe 'when <selector> is specified', ->
it 'only removes markers matching the selector', ->
markers\add { {name: 'test1', start_offset: 2, end_offset: 3, foo: 'bar'} }
markers\add { {name: 'test2', start_offset: 5, end_offset: 6, foo: 'frob'} }
markers\remove_for_range 1, 7, foo: 'frob'
assert.same {'test1'}, names(markers\for_range(1, 7))
describe 'expand(offset, count)', ->
it 'bumps all markers below or at <offset> by <count> positions', ->
markers\add { {name: 'test1', start_offset: 3, end_offset: 4} }
markers\expand 2, 3
assert.same {}, markers\at(3)
assert.same {
name: 'test1',
start_offset: 6,
end_offset: 7
}, markers\at(6)[1]
markers\expand 2, 1
assert.same {}, markers\at(6)
assert.same {
name: 'test1',
start_offset: 7,
end_offset: 8
}, markers\at(7)[1]
it 'expands enclosing markers by <count> positions', ->
markers\add { {name: 'test1', start_offset: 2, end_offset: 4} }
markers\expand 3, 2
assert.same {
name: 'test1',
start_offset: 2,
end_offset: 6
}, markers\at(2)[1]
-- but this is outside
markers\expand 6, 2
assert.equals 6, markers\at(2)[1].end_offset
-- and inside by one
markers\expand 5, 1
assert.equals 7, markers\at(2)[1].end_offset
describe 'shrink(offset, count)', ->
it 'moves all markers above the end offset down by <count> positions', ->
markers\add { {name: 'test1', start_offset: 5, end_offset: 10} }
markers\shrink 4, 1
assert.same {}, markers\at(9)
assert.same {
name: 'test1',
start_offset: 4,
end_offset: 9
}, markers\at(4)[1]
markers\shrink 1, 1
assert.same {}, markers\at(8)
assert.same {
name: 'test1',
start_offset: 3,
end_offset: 8
}, markers\at(3)[1]
it 'shrinks enclosing markers by <count> positions', ->
markers\add { {name: 'test1', start_offset: 2, end_offset: 8} }
markers\shrink 2, 2
assert.same {
name: 'test1',
start_offset: 2,
end_offset: 6
}, markers\at(2)[1]
-- but this is outside
markers\shrink 6, 2
assert.equals 6, markers\at(2)[1].end_offset
-- and inside by one
markers\shrink 5, 1
assert.equals 5, markers\at(2)[1].end_offset
context 'for partially affected markers', ->
it 'removes markers with marker.preserve = false', ->
markers\add { {name: 'test1', start_offset: 2, end_offset: 4} }
markers\add { {name: 'test2', start_offset: 5, end_offset: 10} }
markers\shrink 8, 3
assert.same { {name: 'test1', start_offset: 2, end_offset: 4} }, markers\for_range 1, 100
markers\shrink 1, 3
assert.same {}, markers\for_range 1, 100
it 'trims markers with marker.preserve = true', ->
markers\add { {name: 'test1', start_offset: 2, end_offset: 4, preserve: true} }
markers\add { {name: 'test2', start_offset: 5, end_offset: 10, preserve: true} }
-- trim end
markers\shrink 8, 3
assert.same { {name: 'test2', start_offset: 5, end_offset: 8, preserve: true} }, markers\at(5)
-- trim start
markers\shrink 4, 2
assert.same { {name: 'test2', start_offset: 4, end_offset: 6, preserve: true} }, markers\at(4)
assert.same { {name: 'test1', start_offset: 2, end_offset: 4, preserve: true} }, markers\at(2)
| 37.692308 | 102 | 0.607923 |
018d1c8cc89d3bc485853b8ef1faafe1129b589e | 106 |
version = "0.3.2"
{
version: version,
print_version: ->
print "MoonScript version #{version}"
}
| 11.777778 | 41 | 0.622642 |
8c7781238f15463ea7e30c318c895fe7dee33ff5 | 1,368 | -- Copyright 2012-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
interactions = {} -- registry
register = (spec) ->
for field in *{'name', 'description'}
error 'Missing field for command: "' .. field .. '"' if not spec[field]
if not (spec.factory or spec.handler) or (spec.factory and spec.handler)
error 'One of "factory" or "handler" required'
interactions[spec.name] = moon.copy spec
unregister = (name) ->
interactions[name] = nil
sequence = (order, def) ->
for name in *order
error "#{name} not found in def" unless def[name]
state = {}
pos = 1
local current
while true
def.update state if def.update
prev = current
current = order[pos]
if current
result = def[current](state, prev)
return nil unless result
if result.back
pos -= 1
state[order[pos]] = nil
else
state[current] = result
pos += 1
continue
else
if def.finish
return def.finish state
return state
get = (name) -> interactions[name]
return setmetatable {:register, :unregister, :get, :sequence}, {
__index: (interaction_name) =>
spec = get(interaction_name)
return if not spec
(...) -> howl.app.window.command_line\run spec, ...
}
| 24.872727 | 79 | 0.605994 |
77a5853c2ffa5242163ef1fe6cab5a15c63b0deb | 2,419 | import Widget from require "lapis.html"
i18n = require "i18n"
class MTASettingsAccount extends Widget
@include "widgets.utils"
category: "account"
content: =>
div class: "card", ->
div class: "card-header", i18n "settings.changepass_title"
div class: "card-block", -> form action: @url_for("settings.change_password"), method: "POST", ->
@write_csrf_input!
div class: "form-group row", ->
label class: "col-sm-2", i18n "settings.old_pass"
div class: "col-sm-10", ->
input type: "password", class: "form-control", name: "settingsOldPassword", required: true
div class: "form-group row", ->
label class: "col-sm-2", i18n "settings.new_pass"
div class: "col-sm-10", ->
input type: "password", class: "form-control", name: "settingsNewPassword", required: true
div class: "form-group row", ->
label class: "col-sm-2", i18n "settings.confirm_new_pass"
div class: "col-sm-10", ->
input type: "password", class: "form-control", name: "settingsNewPasswordConfirm", required: true
div class: "form-group row", ->
div class: "col-sm-offset-2 col-sm-10", ->
button type: "submit", class: "btn btn-secondary", i18n "settings.changepass_button"
div class: "card", ->
div class: "card-header", i18n "settings.rename_title"
div class: "card-block", -> form action: @url_for("settings.rename_account"), method: "POST", ->
@write_csrf_input!
p i18n "settings.rename_info"
div class: "form-group row", ->
label class: "col-sm-2", i18n "settings.username"
div class: "col-sm-10", ->
input type: "text", class: "form-control", name: "settingsNewUsername", value: @active_user.username, required: true
div class: "form-group row", ->
div class: "col-sm-offset-2 col-sm-10", ->
button type: "submit", class: "btn btn-secondary", onclick: "return confirm(\"#{i18n 'settings.rename_confirm'}\")", i18n "settings.rename_button"
div class: "card", ->
div class: "card-header bg-danger", "Delete account"
div class: "card-block", ->
p i18n "settings.delete_info"
form action: @url_for("settings.delete_account"), method: "POST", ->
@write_csrf_input!
button class: "btn btn-primary btn-danger", type: "submit", onclick: "return confirm(\"#{i18n 'settings.delete_confirm'}\")", i18n "settings.delete_button"
| 43.196429 | 161 | 0.642001 |
a32462e3152a78dbf20d968389678868b0007155 | 6,390 |
cjson = require"cjson"
ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-=[];',./!@#$%^&*()_+{}|:\"<>?\\`~ "
DEFAULT_FONT = "12px sans-serif"
-- disable invalid functions
os.remove = -> error "os.remove is disabled"
os.rename = -> error "os.rename is disabled"
os.execute = -> error "os.execute is disabled"
os.exit = -> error "os.exit is disabled"
io.tmpfile = -> error "io.tmpfile is disabled"
post_message = (o) ->
o = cjson.encode o if type(o) == "table"
nacl.post_message o
printer = (channel="std_out") ->
(...) ->
args = {...}
str = table.concat [tostring s for s in *args], "\t"
post_message { channel, str }
async_print = printer"std_out"
async_err = printer"std_err"
msg_id = 0
msg_responses = {}
request_response = (msg) ->
id = msg_id
msg_id += 1
post_message { "request", id, msg }
while true
msg = coroutine.yield!
if msg == "response" and msg_responses[id]
return with msg_responses[id]
msg_responses[id] = nil
safe_resume = (co, ...) ->
success, error_msg = coroutine.resume co, ...
if not success
async_err debug.traceback co, error_msg
nacl.set_game_thread nil
false
else
true
async_require = (module_name) ->
mod = package.loaded[module_name]
return mod if mod
loader = if package.preload[module_name]
package.preload[module_name]
else
msg = request_response { "require", module_name }
status, code = unpack msg
return async_err code if status == "error"
assert loadstring code, module_name
setfenv loader, getfenv 2
mod = loader module_name
mod = true if mod == nil
package.loaded[module_name] = mod
mod
nacl.lib = {
core: nacl
prefetch: (files) ->
tuples = {}
add_files = (list, t="text") ->
for k, file_or_list in pairs list
if type(file_or_list) == "table"
add_files file_or_list, k
else
table.insert tuples, { t, file_or_list }
add_files files
return if #tuples == 0
status, msg = unpack request_response { "prefetch", tuples }
error "prefetch: " .. msg if status != "success"
track_event: (category, action, label=nil, value=nil, interactive=true) ->
post_message { "track_event", { category, action, label, value, interactive } }
}
async_scope = nil
nacl_package_seeall = (mod) ->
setmetatable mod, __index: async_scope
module = module
-- scope of the game thread
async_scope = setmetatable {
print: async_print
require: async_require
nacl: nacl.lib
-- make it so module creates tables in async_scope instead of _G
module: (...) ->
_G = _G
setfenv 0, async_scope
out = { module ... }
setfenv 0, _G
unpack out
package: setmetatable {
seeall: nacl_package_seeall
}, __index: package
}, {
__index: _G
}
game_thread = nil -- to prevent it from being garbage collected
nacl.show_error = async_err -- used by C to send errors to client
nacl.handle_message = (msg) ->
error "unknown msg: " .. tostring(msg) if type(msg) != "string"
print ">>", msg\sub 1, 120
msg = cjson.decode msg
switch msg[1]
-- create a new execution thread
-- throws out the old one
when "execute"
fn, err = loadstring msg[2], "execute"
if not fn
async_err err
else
setfenv fn, async_scope
run = -> aroma.run fn
game_thread = coroutine.create run
nacl.set_game_thread game_thread
safe_resume game_thread
when "response"
_, id, data = unpack msg
msg_responses[id] = data
safe_resume game_thread, "response"
else
error "Don't know how to handle message: " .. (msg[1] or msg)
img_cache = {}
image_data_from_url = (url) ->
msg = request_response { "image", url }
status, bytes, width, height = unpack msg
if status == "success"
nacl.image_data_from_byte_string bytes, width, height
else
error bytes
class AudioSource
new: (@source_id, @url) =>
msg: (...) => post_message { "audio", @source_id, ... }
play: => @msg "play"
stop: => @msg "stop"
rewind: => @msg "rewind"
setVolume: (vol) => -- TODO
setLooping: (should_loop) => @msg "set_looping", should_loop
__tostring: => "HTMLAudioSource<" .. @url .. ">"
nacl.init = {
graphics: =>
old_new_image = @newImage
@newImage = (url, ...) ->
return old_new_image url, ... if type(url) != "string"
return img_cache[url] if img_cache[url]
img_data = image_data_from_url url
img = old_new_image img_data
img_cache[url] = img
img
old_new_image_font = @newImageFont
@newImageFont = (url, letters) ->
image_data = if type(url) == "string"
aroma.image.newImageData url
else
url
old_new_image_font image_data, letters
@newFont = (font_str, alphabet=ALPHABET) ->
glyphs = request_response { "font", font_str, alphabet }
cache = aroma.font.newGlyphCache!
for g in *glyphs
letter, data_string, w, h = unpack g
data = nacl.image_data_from_byte_string data_string, w, h
cache\add_glyph letter\byte!, data
cache\to_font!
aroma.boot = ->
if not self.getFont!
self.setFont self.newFont DEFAULT_FONT
audio: =>
@newSource = (url, kind="static") ->
msg = request_response { "audio", url, kind }
status, source_id, err_msg = unpack msg
if status == "success"
AudioSource source_id, url
else
error error_msg
image: =>
old_new_image_data = @newImageData
@newImageData = (...) ->
args = {...}
old_new_image_data ... if type(args[1]) != "string"
image_data_from_url args[1]
}
functions_to_reset = {"draw", "update", "keypressed", "keyreleased", "focus", "load"}
default_modules = { name, true for name in pairs package.loaded }
nacl.init_all = (aroma) ->
aroma.run = (setup_fn) ->
-- unload any modules
for key in pairs package.loaded
package.loaded[key] = nil unless default_modules[name]
blank = ->
aroma[key] = blank for key in *functions_to_reset
aroma.graphics.reset!
aroma.boot!
setup_fn!
while true -- listen for game messages
msg = {coroutine.yield!}
if aroma[msg[1]]
name = table.remove msg, 1
aroma[name] unpack msg
-- else
-- print "unknown message"
-- print unpack msg
| 25.870445 | 110 | 0.632238 |
d39375b10c71a203615580acb06cb53abd202afd | 909 | export modinfo = {
type: "command"
desc: "Try ID"
alias: {"try"}
func: (Msg,Speaker) ->
GetCharacterAsset = (id) ->
return string.format("%sAsset/CharacterFetch.ashx?userId=%s&placeId=0",RobloxWebsite, id)
for i = 1, #Msg
if string.sub(Msg, i, i) == ConfigSystem("Get", "Blet")
search = GetPlayers(string.sub(Msg, 1, i - 1))
for _,v in pairs(search)
if v.Character
if v.Character\FindFirstChild("Humanoid")
v.Character.Humanoid.Health = 0
alr = GetPlayers(string.sub(Msg, i+1))
if #alr == 0
if string.lower(string.sub(Msg, i+1)) == "normal"
v.CharacterAppearance = GetCharacterAsset(v.userId)
else
v.CharacterAppearance = GetCharacterAsset(string.sub(Msg, i+1))
else
for i,s in pairs(alr)
v.CharacterAppearance = GetCharacterAsset(s.userId)
Output("Changed player's identity",{Colors.Green})
} | 36.36 | 92 | 0.633663 |
ba09a9b34650bbc8738a2ce91a566632685bb137 | 198 | fizzbuzz = (i) ->
if i % 3 == 0 and i % 5 == 0
print "FizzBuzz"
else if i % 3 == 0
print "Fizz"
else if i % 5 == 0
print "Buzz"
else
print i
for num = 1, 100
fizzbuzz num
| 15.230769 | 30 | 0.505051 |
b61f2a4a704d90e066a1306b9a879fb66e69ed2d | 115 | Component = require "lib.concord.component"
Rotation = Component (entity, angle) ->
entity.angle = angle
Rotation | 23 | 43 | 0.756522 |
286b47b26ef0ac8dee6a5f9f60745560c711f50a | 3,105 |
require('vimp')
assert = require("vimp.util.assert")
log = require("vimp.util.log")
helpers = require("vimp.testing.helpers")
TestKeys = '<F4>'
TestKeys2 = '<F5>'
class Tester
test_nnoremap: =>
helpers.unlet('foo')
vimp.nnoremap { 'expr' }, TestKeys, -> [[:let g:foo = 5<cr>]]
assert.is_equal(vim.g.foo, nil)
helpers.rinput(TestKeys)
assert.is_equal(vim.g.foo, 5)
test_inoremap: =>
vimp.inoremap { 'expr' }, TestKeys, -> 'foo'
helpers.rinput("i#{TestKeys}")
assert.is_equal(helpers.get_line!, 'foo')
test_xnoremap: =>
vimp.xnoremap { 'expr' }, TestKeys, -> 'cfoo'
helpers.input("istart middle end<esc>")
assert.is_equal(helpers.get_line!, 'start middle end')
helpers.input("Fmviw")
helpers.rinput(TestKeys)
assert.is_equal(helpers.get_line!, 'start foo end')
test_snoremap: =>
vimp.snoremap { 'expr' }, TestKeys, -> 'foo'
helpers.input("istart mid end<esc>")
assert.is_equal(helpers.get_line!, 'start mid end')
helpers.input("Fmgh<right><right>")
helpers.rinput(TestKeys)
assert.is_equal(helpers.get_line!, 'start foo end')
test_cnoremap: =>
vimp.cnoremap { 'expr' }, TestKeys, -> 'foo'
helpers.unlet('foo')
helpers.rinput(":let g:foo='#{TestKeys}'<cr>")
assert.is_equal(vim.g.foo, 'foo')
test_onoremap: =>
vimp.onoremap { 'expr' }, TestKeys, -> 'aw'
helpers.input("istart mid end<esc>Fm")
helpers.rinput("d#{TestKeys}")
assert.is_equal(helpers.get_line!, 'start end')
-- Skip this one because it's tricky to test
-- Test it manually instead
-- test_tnoremap: =>
test_nmap: =>
vimp.nnoremap TestKeys2, 'diw'
vimp.nmap {'expr'}, TestKeys, -> TestKeys2
helpers.set_lines({'foo bar qux'})
helpers.input("0w")
helpers.rinput("#{TestKeys}")
assert.is_equal(helpers.get_line!, 'foo qux')
test_imap: =>
vimp.inoremap TestKeys2, 'qux'
vimp.imap {'expr'}, TestKeys, -> TestKeys2
helpers.set_lines({'foo bar'})
helpers.input("0w")
helpers.rinput("i#{TestKeys}<esc>")
assert.is_equal(helpers.get_line!, 'foo quxbar')
test_xmap: =>
vimp.xnoremap TestKeys2, 'cfoo'
vimp.xmap {'expr'}, TestKeys, -> TestKeys2
helpers.set_lines({'qux bar'})
helpers.input('0wviw')
helpers.rinput(TestKeys)
assert.is_equal(helpers.get_line!, 'qux foo')
test_smap: =>
vimp.snoremap TestKeys2, 'foo'
vimp.smap {'expr'}, TestKeys, -> TestKeys2
helpers.input("istart mid end<esc>")
assert.is_equal(helpers.get_line!, 'start mid end')
helpers.input("Fmgh<right><right>")
helpers.rinput(TestKeys)
assert.is_equal(helpers.get_line!, 'start foo end')
test_cmap: =>
vimp.cnoremap TestKeys2, 'foo'
vimp.cmap {'expr'}, TestKeys, -> TestKeys2
helpers.unlet('foo')
helpers.rinput(":let g:foo='#{TestKeys}'<cr>")
assert.is_equal(vim.g.foo, 'foo')
test_omap: =>
vimp.onoremap TestKeys2, 'iw'
vimp.omap {'expr'}, TestKeys, -> TestKeys2
helpers.input("istart mid end<esc>Fm")
helpers.rinput("d#{TestKeys}")
assert.is_equal(helpers.get_line!, 'start end')
| 30.441176 | 65 | 0.646377 |
1bf1e1fe0e4c388b613d0770a1ae3fe1adc01c84 | 9,477 |
import render_html, Widget from require "lapis.html"
render_widget = (w) ->
buffer = {}
w buffer
table.concat buffer
describe "lapis.html", ->
it "should render html", ->
output = render_html ->
b "what is going on?"
div ->
pre class: "cool", -> span "hello world"
text capture -> div "this is captured"
link rel: "icon" -- , type: "image/png", href: "dad"-- can't have multiple because of hash ordering
raw "<div>raw test</div>"
text "<div>raw test</div>"
html_5 ->
div "what is going on there?"
assert.same [[<b>what is going on?</b><div><pre class="cool"><span>hello world</span></pre></div><div>this is captured</div><link rel="icon"/><div>raw test</div><div>raw test</div><!DOCTYPE HTML><html lang="en"><div>what is going on there?</div></html>]], output
it "should render html class table syntax", ->
output = render_html ->
div class: {"hello", "world", cool: true, notcool: false}
div class: {}
div class: {ok: "fool"}
div class: {cool: nil}
assert.same '<div class="hello world cool"></div><div></div><div class="ok"></div><div></div>', output
it "should render more html", ->
output = render_html ->
element "leaf", {"hello"}, "world"
element "leaf", "one", "two", "three"
element "leaf", {hello: "world", "a"}, { no: "show", "b", "c" }
leaf {"hello"}, "world"
leaf "one", "two", "three"
leaf {hello: "world", "a"}, { no: "show", "b", "c" }
assert.same [[<leaf>helloworld</leaf><leaf>onetwothree</leaf><leaf hello="world">abc</leaf><leaf>helloworld</leaf><leaf>onetwothree</leaf><leaf hello="world">abc</leaf>]], output
-- attributes are unordered so we don't check output (for now)
it "should render multiple attributes", ->
render_html ->
link rel: "icon", type: "image/png", href: "dad"
pre id: "hello", class: "things", style: [[border: image("http://leafo.net")]]
it "should boolean attributes", ->
output = render_html ->
span required: true
div required: false
assert.same [[<span required></span><div></div>]], output
it "should capture", ->
-- we have to do it this way because in plain Lua 5.1, upvalues can't be
-- joined, we only have a copy of the value.
capture_result = {}
output = render_html ->
text "hello"
capture_result.value = capture ->
div "This is the capture"
text "world"
assert.same "helloworld", output
assert.same "<div>This is the capture</div>", capture_result.value
it "should capture into joined upvalue", ->
-- skip on lua 5.1
if _VERSION == "Lua 5.1" and not _G.jit
pending "joined upvalues not available in Lua 5.1, skipping test"
return
capture_result = {}
output = render_html ->
text "hello"
capture_result.value = capture ->
div "This is the capture"
text "world"
assert.same "helloworld", output
assert.same "<div>This is the capture</div>", capture_result.value
it "should render the widget", ->
class TestWidget extends Widget
content: =>
div class: "hello", @message
raw @inner
input = render_widget TestWidget message: "Hello World!", inner: -> b "Stay Safe"
assert.same input, [[<div class="hello">Hello World!</div><b>Stay Safe</b>]]
it "should render widget with inheritance", ->
class BaseWidget extends Widget
value: 100
another_value: => 200
content: =>
div class: "base_widget", ->
@inner!
inner: => error "implement me"
class TestWidget extends BaseWidget
inner: =>
text "Widget speaking, value: #{@value}, another_value: #{@another_value!}"
input = render_widget TestWidget!
assert.same input, [[<div class="base_widget">Widget speaking, value: 100, another_value: 200</div>]]
it "should include widget helper", ->
class Test extends Widget
content: =>
div "What's up! #{@hello!}"
w = Test!
w\include_helper {
id: 10
hello: => "id: #{@id}"
}
input = render_widget w
assert.same input, [[<div>What's up! id: 10</div>]]
it "helper should pass to sub widget", ->
class Fancy extends Widget
content: =>
text @cool_message!
text @thing
class Test extends Widget
content: =>
first ->
widget Fancy @
second ->
widget Fancy!
w = Test thing: "THING"
w\include_helper {
cool_message: =>
"so-cool"
}
assert.same [[<first>so-coolTHING</first><second>so-cool</second>]],
render_widget w
it "helpers should resolve correctly ", ->
class Base extends Widget
one: 1
two: 2
three: 3
class Sub extends Base
two: 20
three: 30
four: 40
content: =>
text @one
text @two
text @three
text @four
text @five
w = Sub!
w\include_helper {
one: 100
two: 200
four: 400
five: 500
}
buff = {}
w\render buff
assert.same {"1", "20", "30", "40", "500"}, buff
it "should include methods from mixin", ->
class TestMixin
thing: ->
div class: "the_thing", ->
text "hello world"
class SomeWidget extends Widget
@include TestMixin
content: =>
div class: "outer", ->
@thing!
assert.same [[<div class="outer"><div class="the_thing">hello world</div></div>]],
render_widget SomeWidget!
it "should set layout opt", ->
class TheWidget extends Widget
content: =>
@content_for "title", -> div "hello world"
@content_for "another", "yeah"
widget = TheWidget!
helper = { layout_opts: {} }
widget\include_helper helper
out = render_widget widget
assert.same { _content_for_another: "yeah", _content_for_title: "<div>hello world</div>" }, helper.layout_opts
it "should render content for", ->
class TheLayout extends Widget
content: =>
assert @has_content_for("title"), "should have title content_for"
assert @has_content_for("inner"), "should have inner content_for"
assert @has_content_for("footer"), "should have footer content_for"
assert not @has_content_for("hello"), "should not have hello content for"
div class: "title", ->
@content_for "title"
@content_for "inner"
@content_for "footer"
class TheWidget extends Widget
content: =>
@content_for "title", -> div "hello world"
@content_for "footer", "The's footer"
div "what the heck?"
layout_opts = {}
inner = {}
view = TheWidget!
view\include_helper { :layout_opts }
view inner
layout_opts._content_for_inner = -> raw inner
assert.same [[<div class="title"><div>hello world</div></div><div>what the heck?</div>The's footer]], render_widget TheLayout layout_opts
it "should append multiple content for", ->
class TheLayout extends Widget
content: =>
element "content-for", ->
@content_for "things"
class TheWidget extends Widget
content: =>
@content_for "things", -> div "hello world"
@content_for "things", "dual world"
layout_opts = {}
inner = {}
view = TheWidget!
view\include_helper { :layout_opts }
view inner
assert.same [[<content-for><div>hello world</div>dual world</content-for>]], render_widget TheLayout layout_opts
it "should instantiate widget class when passed to widget helper", ->
class SomeWidget extends Widget
content: =>
@color = "blue"
-- assert.Not.same @, SomeWidget
text "hello!"
render_html ->
widget SomeWidget
assert.same nil, SomeWidget.color
it "should render widget inside of capture", ->
capture_result = {}
class InnerInner extends Widget
content: =>
out = capture ->
span "yeah"
raw out
class Inner extends Widget
content: =>
dt "hello"
widget InnerInner
dt "world"
class Outer extends Widget
content: =>
capture_result.value = capture ->
div "before"
widget Inner!
div "after"
assert.same [[]], render_widget Outer!
assert.same [[<div>before</div><dt>hello</dt><span>yeah</span><dt>world</dt><div>after</div>]], capture_result.value
describe "widget.render_to_file", ->
class Inner extends Widget
content: =>
dt class: "cool", "hello"
p ->
strong "The world #{@t}"
@m!
dt "world"
m: =>
raw "is & here"
it "renders to string by filename", ->
time = os.time!
Inner({
t: time
})\render_to_file "widget_out.html"
written = assert(io.open("widget_out.html"))\read "*a"
assert.same [[<dt class="cool">hello</dt><p><strong>The world ]] .. time .. [[</strong>is & here</p><dt>world</dt>]], written
it "writes to file interface", ->
written = {}
fake_file = {
write: (content) =>
table.insert written, content
}
time = os.time!
Inner({
t: time
})\render_to_file fake_file
assert.same [[<dt class="cool">hello</dt><p><strong>The world ]] .. time .. [[</strong>is & here</p><dt>world</dt>]], table.concat(written)
| 27.077143 | 290 | 0.590271 |
8a5e657b0dc8e375dca715f3c8bcefbace645f48 | 2,842 | -- "moon.all".fold()
--Copyright (C) 2017 by Leaf Corcoran
--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.
fold = (items, fn)->
len = #items
if len > 1
accum = fn items[1], items[2]
for i=3,len
accum = fn accum, items[i]
accum
else
items[1]
-- END LICENSE --
-- combine(...)
--Copyright 2018 Aric Hasting
--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.
combine = (...) ->
args = {...}
-- Nil if there are no arguments
if #args == 0
return
-- Return first value if only one argument
if #args == 1
args[1]
-- Fold all table key/values into the previous
return fold args, (a, b) ->
if type(b) == "table"
for key, val in pairs b
a[key] = val
else
table.insert(a, b)
a
concat = (...) ->
args = {...}
return fold args, (a, b) ->
for i = 1, #b
a[#a + 1] = b[i]
a
{:combine, :concat}
| 54.653846 | 462 | 0.727305 |
4fd85606f6871a42cead2e760d68c00b18d24497 | 863 | Secs = require('vendor/secs/lib/secs')
class MapLayer extends Secs
new: (map, @name, index) =>
super()
layers = map\getTiledLayers()
exists = false
-- Support using an existing layer
for l, layer in ipairs layers
if _.isString(@name) and layer.name == @name
exists = true
index = l
if _.isString(index) and layer.name == index
index = l
-- Default to adding to the top
if not _.isNumber(index) then index = #layers + 1
-- Create STI layer, and store properties here
layer = nil
if exists then
layer = map.tiled\convertToCustomLayer(index)
@name = layer.name
else
layer = map.tiled\addCustomLayer(@name, index)
@type = layer.type
@visible = layer.visible
@opacity = layer.opacity
@properties = layer.properties
-- Replace original layer with this instance
layers[index] = @
layers[@name] = @
| 22.710526 | 51 | 0.672074 |
bb52426370c1480c72522463a98fb1668590d6ca | 2,208 | class Gradient extends Base
new: (stops, radial) =>
-- Define this Gradient's unique id.
@_id = Gradient._id = (Gradient._id or 0) + 1
stops = radial = nil if stops and @_set(stops)
@setStops stops or ["white", "black"] if !@_stops
-- Support old string type argument and new radial boolean.
@setRadial typeof radial is "string" and radial is "radial" or radial or false if !@_radial?
_serialize: (options, dictionary) =>
dictionary.add @, ->
Base\serialize [@_stops, @_radial], options, true, dictionary
_changed: =>
-- Loop through the gradient-colors that use this gradient and notify
-- them, so they can notify the items they belong to.
i = 0
l = @_owners and @_owners.length
while i < l
@_owners[i]\_changed()
i++
_addOwner: (color) =>
@_owners = [] if !@_owners
@_owners\push color
_removeOwner: (color) =>
index = (if @_owners then @_owners\indexOf(color) else -1)
if !(index is -1)
@_owners\splice index, 1
delete @_owners if @_owners.length is 0
clone: =>
stops = []
i = 0
l = @_stops.length
while i < l
stops[i] = @_stops[i]\clone()
i++
Gradient(stops)
getStops: =>
@_stops
setStops: (stops) =>
-- If this gradient already contains stops, first remove
-- this gradient as their owner.
if @stops
i = 0
l = @_stops.length
while i < l
delete @_stops[i]._owner
i++
assert(stops.length < 2)
@_stops = GradientStop\readAll(stops, 0, false, true) -- clone
-- Now reassign ramp points if they were not specified.
i = 0
l = @_stops.length
while i < l
stop = @_stops[i]
stop._owner = this
stop\setRampPoint i / (l - 1) if stop._defaultRamp
i++
@_changed()
getRadial: =>
@_radial
setRadial: (radial) =>
@_radial = radial
@_changed()
equals: (gradient) =>
if gradient and gradient.__class is Gradient and @_stops.length is gradient._stops.length
i = 0
l = @_stops.length
while i < l
return false if !@_stops[i]\equals(gradient._stops[i])
i++
return true
false
| 23 | 96 | 0.593297 |
e59e312f9d777f1143138522859d27c6197f9152 | 148 | ltypekit_sign = require "ltypekit.sign"
ltypekit_sign.signature = ltypekit_sign.sign
ltypekit_sign.VERSION = "5.0"
return ltypekit_sign
| 29.6 | 49 | 0.756757 |
2b0cb771e3350267042785470b621adcd3c00323 | 541 | binser = require('benchmarks.binser')
binser.deserialize(binser.serialize({}))
{
description: 'binser'
serialize:
largeNumArray: binser.serialize
largeU32Array: binser.serialize
smallNumArray: binser.serialize
smallU8Array: binser.serialize
simpleTable: binser.serialize
deepTable: binser.serialize
deserialize:
largeNumArray: binser.deserialize
largeU32Array: binser.deserialize
smallNumArray: binser.deserialize
smallU8Array: binser.deserialize
simpleTable: binser.deserialize
deepTable: binser.deserialize
}
| 23.521739 | 40 | 0.798521 |
54ff4622edacfd664a60fc26812f3d52429a67d3 | 22 | require "base58.init"
| 11 | 21 | 0.772727 |
cb2365c0248b2b5e67d9d10eca817669917612e7 | 21,451 |
-- 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 DPP2 from _G
import Menus from DPP2
import i18n from DLib
DPP2.CL_ENABLE_PROPERTIES = DPP2.CreateClientConVar('cl_properties', '1', DPP2.TYPE_BOOL)
DPP2.CL_ENABLE_PROPERTIES_REGULAR = DPP2.CreateClientConVar('cl_properties_regular', '1', DPP2.TYPE_BOOL)
DPP2.CL_ENABLE_PROPERTIES_ADMIN = DPP2.CreateClientConVar('cl_properties_admin', '1', DPP2.TYPE_BOOL)
DPP2.CL_ENABLE_PROPERTIES_RESTRICTIONS = DPP2.CreateClientConVar('cl_properties_restrictions', '1', DPP2.TYPE_BOOL)
lockmodes = {
DPP2.PhysgunProtection
DPP2.DriveProtection
DPP2.ToolgunProtection
DPP2.DamageProtection
DPP2.PickupProtection
DPP2.UseProtection
DPP2.VehicleProtection
DPP2.GravgunProtection
}
properties.Add('dpp2_cleanup', {
MenuLabel: 'gui.dpp2.property.cleanup'
Order: 1655
MenuIcon: Menus.Icons.CleanupMenu
Filter: (ent = NULL, ply = LocalPlayer()) => ent\DPP2IsOwned() and DPP2.cmd_perm_watchdog\HasPermission('dpp2_cleanup')
MenuOpen: (option, ent = NULL, tr, ply = LocalPlayer()) =>
with menu = option\AddSubMenu()
menu\AddOption('gui.dpp2.menus.remove2', -> RunConsoleCommand('dpp2_cleanup', ent\DPP2GetOwnerPID()))\SetIcon(Menus.Icons.Confirm)
Action: (ent = NULL, tr, ply = LocalPlayer()) =>
})
properties.Add('dpp2_cleanupnpcs', {
MenuLabel: 'gui.dpp2.property.cleanupnpcs'
Order: 1656
MenuIcon: Menus.Icons.CleanupMenu
Filter: (ent = NULL, ply = LocalPlayer()) => ent\IsNPC() and ent\DPP2IsOwned() and DPP2.cmd_perm_watchdog\HasPermission('dpp2_cleanupnpcs')
MenuOpen: (option, ent = NULL, tr, ply = LocalPlayer()) =>
with menu = option\AddSubMenu()
menu\AddOption('gui.dpp2.menus.remove2', -> RunConsoleCommand('dpp2_cleanupnpcs', ent\DPP2GetOwnerPID()))\SetIcon(Menus.Icons.Confirm)
Action: (ent = NULL, tr, ply = LocalPlayer()) =>
})
properties.Add('dpp2_cleanupvehicles', {
MenuLabel: 'gui.dpp2.property.cleanupvehicles'
Order: 1657
MenuIcon: Menus.Icons.CleanupMenu
Filter: (ent = NULL, ply = LocalPlayer()) => ent\IsVehicle() and ent\DPP2IsOwned() and DPP2.cmd_perm_watchdog\HasPermission('dpp2_cleanupvehicles')
MenuOpen: (option, ent = NULL, tr, ply = LocalPlayer()) =>
with menu = option\AddSubMenu()
menu\AddOption('gui.dpp2.menus.remove2', -> RunConsoleCommand('dpp2_cleanupvehicles', ent\DPP2GetOwnerPID()))\SetIcon(Menus.Icons.Confirm)
Action: (ent = NULL, tr, ply = LocalPlayer()) =>
})
ban_durations = {
30
60
3 * 60
5 * 60
10 * 60
30 * 60
1 * 60 * 60
2 * 60 * 60
3 * 60 * 60
6 * 60 * 60
12 * 60 * 60
1 * 24 * 60 * 60
3 * 24 * 60 * 60
7 * 24 * 60 * 60
}
properties.Add('dpp2_ban', {
MenuLabel: 'gui.dpp2.property.banning'
Order: 1658
MenuIcon: Menus.Icons.LockTool
Filter: (ent = NULL, ply = LocalPlayer()) => (ent\DPP2IsOwned() and IsValid(ent\DPP2GetOwner()) and not ent\DPP2GetOwner()\IsBot() or ent\IsPlayer() and not ent\IsBot()) and (DPP2.cmd_perm_watchdog\HasPermission('dpp2_ban') or DPP2.cmd_perm_watchdog\HasPermission('dpp2_unban'))
MenuOpen: (option, ent = NULL, tr, ply = LocalPlayer()) =>
getply = ent\IsPlayer() and ent or ent\DPP2GetOwner()
pid = getply\UserID()
with menu = option\AddSubMenu()
if getply\DPP2IsBanned() and DPP2.cmd_perm_watchdog\HasPermission('dpp2_unban')
menu\AddOption('command.dpp2.unban.do_unban', -> RunConsoleCommand('dpp2_unban', pid))\SetIcon(Menus.Icons.UnLockTool)
if DPP2.cmd_perm_watchdog\HasPermission('dpp2_ban')
menu\AddOption('command.dpp2.indefinitely', -> RunConsoleCommand('dpp2_permanent_ban', pid))
for time in *ban_durations
menu\AddOption(DLib.I18n.FormatTime(time), -> RunConsoleCommand('dpp2_ban', pid, time))
Action: (ent = NULL, tr, ply = LocalPlayer()) =>
})
properties.Add('dpp2_lock_self', {
MenuLabel: 'gui.dpp2.property.lock_self.top'
Order: 401
MenuIcon: Menus.Icons.LockTool
Filter: (ent = NULL, ply = LocalPlayer()) =>
return false if not DPP2.CL_ENABLE_PROPERTIES\GetBool()
return false if not DPP2.CL_ENABLE_PROPERTIES_REGULAR\GetBool()
@MenuIcon = Menus.Icons.LockTool
return false if not ent\IsValid()
-- return false if hook.Run('CanProperty', ply, 'dpp2_lock_self', ent) == false
return false if ent\IsNPC() or ent\IsPlayer() or type(ent) == 'NextBot'
for object in *lockmodes
if not object\IsLockedSelf(ply, ent) and DPP2.cmd_perm_watchdog\HasPermission('dpp2_' .. object.lock_self_name)
return true
return false
MenuOpen: (option, ent = NULL, tr, ply = LocalPlayer()) =>
with menu = option\AddSubMenu()
for object in *lockmodes
if not object\IsLockedSelf(ply, ent) and DPP2.cmd_perm_watchdog\HasPermission('dpp2_' .. object.lock_self_name)
menu\AddOption('gui.dpp2.property.lock_self.' .. object.identifier, -> RunConsoleCommand('dpp2_' .. object.lock_self_name, ent\EntIndex()))\SetIcon(Menus.Icons.LockTool)
Action: (ent = NULL, tr, ply = LocalPlayer()) =>
for object in *lockmodes
if not object\IsLockedSelf(ply, ent) and DPP2.cmd_perm_watchdog\HasPermission('dpp2_' .. object.lock_self_name)
RunConsoleCommand('dpp2_' .. object.lock_self_name, ent\EntIndex())
})
properties.Add('dpp2_unlock_self', {
MenuLabel: 'gui.dpp2.property.unlock_self.top'
Order: 402
MenuIcon: Menus.Icons.UnLockTool
Filter: (ent = NULL, ply = LocalPlayer()) =>
return false if not DPP2.CL_ENABLE_PROPERTIES\GetBool()
return false if not DPP2.CL_ENABLE_PROPERTIES_REGULAR\GetBool()
@MenuIcon = Menus.Icons.UnLockTool
return false if not ent\IsValid()
-- return false if hook.Run('CanProperty', ply, 'dpp2_unlock_self', ent) == false
return false if ent\IsNPC() or ent\IsPlayer() or type(ent) == 'NextBot'
for object in *lockmodes
if object\IsLockedSelf(ply, ent)
return true
return false
MenuOpen: (option, ent = NULL, tr, ply = LocalPlayer()) =>
with menu = option\AddSubMenu()
for object in *lockmodes
if object\IsLockedSelf(ply, ent)
menu\AddOption('gui.dpp2.property.unlock_self.' .. object.identifier, -> RunConsoleCommand('dpp2_' .. object.unlock_self_name, ent\EntIndex()))\SetIcon(Menus.Icons.UnLockTool)
Action: (ent = NULL, tr, ply = LocalPlayer()) =>
for object in *lockmodes
if object\IsLockedSelf(ply, ent)
RunConsoleCommand('dpp2_' .. object.unlock_self_name, ent\EntIndex())
})
properties.Add('dpp2_lock_others', {
MenuLabel: 'gui.dpp2.property.lock_others.top'
Order: 403
MenuIcon: Menus.Icons.LockTool
Filter: (ent = NULL, ply = LocalPlayer()) =>
return false if not DPP2.CL_ENABLE_PROPERTIES\GetBool()
return false if not DPP2.CL_ENABLE_PROPERTIES_REGULAR\GetBool()
@MenuIcon = Menus.Icons.LockTool
return false if not ent\IsValid() or ent\DPP2GetOwner() ~= ply
-- return false if hook.Run('CanProperty', ply, 'dpp2_lock_others', ent) == false
return false if ent\IsNPC() or ent\IsPlayer() or type(ent) == 'NextBot'
for object in *lockmodes
if not object\IsLockedOthers(ent) and DPP2.cmd_perm_watchdog\HasPermission('dpp2_' .. object.lock_others_name)
return true
return false
MenuOpen: (option, ent = NULL, tr, ply = LocalPlayer()) =>
with menu = option\AddSubMenu()
for object in *lockmodes
if not object\IsLockedOthers(ent) and DPP2.cmd_perm_watchdog\HasPermission('dpp2_' .. object.lock_others_name)
menu\AddOption('gui.dpp2.property.lock_others.' .. object.identifier, -> RunConsoleCommand('dpp2_' .. object.lock_others_name, ent\EntIndex()))\SetIcon(Menus.Icons.LockTool)
Action: (ent = NULL, tr, ply = LocalPlayer()) =>
for object in *lockmodes
if not object\IsLockedOthers(ent) and DPP2.cmd_perm_watchdog\HasPermission('dpp2_' .. object.lock_others_name)
RunConsoleCommand('dpp2_' .. object.lock_others_name, ent\EntIndex())
})
properties.Add('dpp2_unlock_others', {
MenuLabel: 'gui.dpp2.property.unlock_others.top'
Order: 404
MenuIcon: Menus.Icons.LockTool
Filter: (ent = NULL, ply = LocalPlayer()) =>
return false if not DPP2.CL_ENABLE_PROPERTIES\GetBool()
return false if not DPP2.CL_ENABLE_PROPERTIES_REGULAR\GetBool()
@MenuIcon = Menus.Icons.LockTool
return false if not ent\IsValid()
-- return false if hook.Run('CanProperty', ply, 'dpp2_unlock_others', ent) == false
return false if ent\IsNPC() or ent\IsPlayer() or type(ent) == 'NextBot'
for object in *lockmodes
if object\IsLockedOthers(ent)
return true
return false
MenuOpen: (option, ent = NULL, tr, ply = LocalPlayer()) =>
with menu = option\AddSubMenu()
for object in *lockmodes
if object\IsLockedOthers(ent) and (ent\DPP2GetOwner() == ply or object.camiwatchdog\HasPermission(object.otherPermString))
menu\AddOption('gui.dpp2.property.unlock_others.' .. object.identifier, -> RunConsoleCommand('dpp2_' .. object.unlock_others_name, ent\EntIndex()))\SetIcon(Menus.Icons.LockTool)
Action: (ent = NULL, tr, ply = LocalPlayer()) =>
for object in *lockmodes
if object\IsLockedOthers(ent) and (ent\DPP2GetOwner() == ply or object.camiwatchdog\HasPermission(object.otherPermString))
RunConsoleCommand('dpp2_' .. object.unlock_others_name, ent\EntIndex())
})
do
SENT = '0'
VEHICLE = '1'
NPC = '2'
WEAPON = '3'
PROP = '4'
properties.Add('dpp2_arm_creator', {
MenuLabel: 'gui.dpp2.property.arm_creator'
Order: 878
MenuIcon: Menus.Icons.Wrench2
CreatorType: 0
-- CreatorArg: 'none'
CreatorName: ''
Filter: (ent = NULL, ply = LocalPlayer()) =>
return false if not DPP2.CL_ENABLE_PROPERTIES\GetBool()
return false if not DPP2.CL_ENABLE_PROPERTIES_REGULAR\GetBool()
@MenuIcon = Menus.Icons.Wrench2
return false if not ent\IsValid()
return false if not IsValid(ply\GetWeapon('gmod_tool'))
-- return false if hook.Run('CanProperty', ply, 'dpp2_arm_creator', ent) == false
return false if ent\IsPlayer() or ent\GetClass()\startsWith('prop_door') or ent\GetClass()\startsWith('func_') or ent\GetClass()\startsWith('prop_dynamic')
gtype = type(ent)
if gtype == 'Weapon'
@CreatorName = ent\GetClass()
@CreatorArg = nil
@CreatorType = WEAPON
elseif gtype == 'NPC'
@CreatorName = ent\GetClass()
@CreatorArg = IsValid(ent\GetActiveWeapon()) and ent\GetActiveWeapon()\GetClass() or 'none'
@CreatorType = NPC
elseif gtype == 'Vehicle'
@CreatorArg = nil
@CreatorType = VEHICLE
@CreatorName = ent.VehicleName or ent\GetPrintNameDLib() or 'Jeep'
elseif gtype == 'Entity'
gclass = ent\GetClass()
if gclass == 'prop_physics'
@CreatorArg = nil
@CreatorType = PROP
@CreatorName = ent\GetModel()
elseif gclass == 'prop_effect'
@CreatorArg = nil
@CreatorType = PROP
@CreatorName = ent\GetChildren()[1] and ent\GetChildren()[1]\GetModel() or ent\GetModel() -- ???
else
@CreatorArg = nil
@CreatorType = SENT
@CreatorName = ent\GetClass()
return true
Action: (ent = NULL, tr, ply = LocalPlayer()) =>
RunConsoleCommand('gmod_toolmode', 'creator')
RunConsoleCommand('creator_type', @CreatorType)
RunConsoleCommand('creator_arg', @CreatorArg) if @CreatorArg
RunConsoleCommand('creator_name', @CreatorName)
input.SelectWeapon(ply\GetWeapon('gmod_tool'))
})
properties.Add('dpp2_copymodel', {
MenuLabel: 'gui.dpp2.property.copymodel'
Order: 1650
MenuIcon: Menus.Icons.Copy
Filter: (ent = NULL, ply = LocalPlayer()) =>
return false if not DPP2.CL_ENABLE_PROPERTIES\GetBool()
return false if not DPP2.CL_ENABLE_PROPERTIES_REGULAR\GetBool()
@MenuIcon = Menus.Icons.Copy
return false if not ent\IsValid()
return false if not ent\GetModel() or ent\GetModel()\trim() == ''
return true
Action: (ent = NULL) =>
gmodel = ent\GetModel()
if ent\GetClass() == 'prop_effect'
gmodel = ent\GetChildren()[1] and ent\GetChildren()[1]\GetModel() or ent\GetModel() -- ???
SetClipboardText(gmodel)
})
properties.Add('dpp2_copyclassname', {
MenuLabel: 'gui.dpp2.property.copyclassname'
Order: 1651
MenuIcon: Menus.Icons.Copy
Filter: (ent = NULL, ply = LocalPlayer()) =>
return false if not DPP2.CL_ENABLE_PROPERTIES\GetBool()
return false if not DPP2.CL_ENABLE_PROPERTIES_REGULAR\GetBool()
@MenuIcon = Menus.Icons.Copy
return false if not ent\IsValid()
return false if not ent\GetClass() or ent\GetClass()\trim() == ''
return true
Action: (ent = NULL) =>
SetClipboardText(ent\GetClass())
})
properties.Add('dpp2_copyangles', {
MenuLabel: 'gui.dpp2.property.copyangles'
Order: 1652
MenuIcon: Menus.Icons.Angle
Filter: (ent = NULL, ply = LocalPlayer()) =>
return false if not DPP2.CL_ENABLE_PROPERTIES\GetBool()
return false if not DPP2.CL_ENABLE_PROPERTIES_REGULAR\GetBool()
@MenuIcon = Menus.Icons.Angle
return ent\IsValid()
Action: (ent = NULL) =>
ang = ent\GetAngles()
SetClipboardText(string.format('Angle(%.2f, %.2f, %.2f)', ang.p, ang.y, ang.r))
})
properties.Add('dpp2_copyvector', {
MenuLabel: 'gui.dpp2.property.copyvector'
Order: 1653
MenuIcon: Menus.Icons.Vector
Filter: (ent = NULL, ply = LocalPlayer()) =>
return false if not DPP2.CL_ENABLE_PROPERTIES\GetBool()
return false if not DPP2.CL_ENABLE_PROPERTIES_REGULAR\GetBool()
return ent\IsValid()
Action: (ent = NULL) =>
vec = ent\GetPos()
SetClipboardText(string.format('Vector(%.2f, %.2f, %.2f)', vec.p, vec.y, vec.r))
})
restrictions = {
DPP2.PhysgunProtection.RestrictionList
DPP2.DriveProtection.RestrictionList
DPP2.PickupProtection.RestrictionList
DPP2.UseProtection.RestrictionList
DPP2.VehicleProtection.RestrictionList
DPP2.GravgunProtection.RestrictionList
DPP2.ToolgunProtection.RestrictionList
DPP2.DamageProtection.RestrictionList
DPP2.SpawnRestrictions
}
blacklists = {
DPP2.PhysgunProtection.Blacklist
DPP2.DriveProtection.Blacklist
DPP2.PickupProtection.Blacklist
DPP2.UseProtection.Blacklist
DPP2.VehicleProtection.Blacklist
DPP2.GravgunProtection.Blacklist
DPP2.ToolgunProtection.Blacklist
DPP2.DamageProtection.Blacklist
'a'
DPP2.PhysgunProtection.Exclusions
DPP2.DriveProtection.Exclusions
DPP2.PickupProtection.Exclusions
DPP2.UseProtection.Exclusions
DPP2.VehicleProtection.Exclusions
DPP2.GravgunProtection.Exclusions
DPP2.ToolgunProtection.Exclusions
DPP2.DamageProtection.Exclusions
}
modelstuff = {
DPP2.ModelBlacklist
DPP2.ModelExclusions
DPP2.ModelRestrictions
DPP2.PerModelLimits
}
properties.Add('dpp2_copyvector', {
MenuLabel: 'gui.dpp2.property.restrictions'
Order: 1680
MenuIcon: Menus.Icons.Restrict
Filter: (ent = NULL, ply = LocalPlayer()) =>
return false if not DPP2.CL_ENABLE_PROPERTIES\GetBool()
return false if not DPP2.CL_ENABLE_PROPERTIES_RESTRICTIONS\GetBool()
return false if not ent\IsValid()
classname = ent\GetClass()
if model = ent\GetModel()
for object in *modelstuff
if object\Has(model)
return true if DPP2.cmd_perm_watchdog\HasPermission('dpp2_' .. object.remove_command_identifier)
else
return true if DPP2.cmd_perm_watchdog\HasPermission('dpp2_' .. object.add_command_identifier)
for object in *blacklists
if not isstring(object)
if object\Has(classname)
return true if DPP2.cmd_perm_watchdog\HasPermission('dpp2_' .. object.remove_command_identifier)
else
return true if DPP2.cmd_perm_watchdog\HasPermission('dpp2_' .. object.add_command_identifier)
for object in *restrictions
if object\Has(classname)
return true if DPP2.cmd_perm_watchdog\HasPermission('dpp2_' .. object.remove_command_identifier)
else
return true if DPP2.cmd_perm_watchdog\HasPermission('dpp2_' .. object.add_command_identifier)
do
object = DPP2.PerEntityLimits
if object\Has(classname)
return true if DPP2.cmd_perm_watchdog\HasPermission('dpp2_' .. object.remove_command_identifier)
else
return true if DPP2.cmd_perm_watchdog\HasPermission('dpp2_' .. object.add_command_identifier)
return false
Action: (ent = NULL) =>
MenuOpen: (option, ent, tr) =>
classname = ent\GetClass()
with menu = option\AddSubMenu()
addrestriction = (object, classname) ->
if object\Has(classname)
if DPP2.cmd_perm_watchdog\HasPermission('dpp2_' .. object.add_command_identifier)
\AddOption('gui.dpp2.menu.edit_in_' .. object.identifier .. '_restrictions', (-> object\OpenMenu(classname)))\SetIcon(Menus.Icons.Add)
if DPP2.cmd_perm_watchdog\HasPermission('dpp2_' .. object.remove_command_identifier)
submenu, button = \AddSubMenu('gui.dpp2.menu.remove_from_' .. object.identifier .. '_restrictions')
button\SetIcon(Menus.Icons.Remove)
submenu\AddOption('gui.dpp2.menus.remove2', (-> RunConsoleCommand('dpp2_' .. object.remove_command_identifier, classname)))\SetIcon(Menus.Icons.Remove)
elseif DPP2.cmd_perm_watchdog\HasPermission('dpp2_' .. object.add_command_identifier)
\AddOption('gui.dpp2.menu.add_to_' .. object.identifier .. '_restrictions', (-> object\OpenMenu(classname)))\SetIcon(Menus.Icons.Add)
model = ent\GetModel()
if ent\GetClass() == 'prop_effect'
model = ent\GetChildren()[1] and ent\GetChildren()[1]\GetModel() or ent\GetModel() -- ???
if model
if DPP2.ModelBlacklist\Has(model)
if DPP2.cmd_perm_watchdog\HasPermission('dpp2_' .. DPP2.ModelBlacklist.remove_command_identifier)
submenu, button = \AddSubMenu('gui.dpp2.menu.remove_from_model_blacklist')
button\SetIcon(Menus.Icons.Remove)
submenu\AddOption('gui.dpp2.menus.remove2', (-> RunConsoleCommand('dpp2_' .. DPP2.ModelBlacklist.remove_command_identifier, model)))\SetIcon(Menus.Icons.Remove)
elseif DPP2.cmd_perm_watchdog\HasPermission('dpp2_' .. DPP2.ModelBlacklist.add_command_identifier)
\AddOption('gui.dpp2.menu.add_to_model_blacklist', (-> RunConsoleCommand('dpp2_' .. DPP2.ModelBlacklist.add_command_identifier, model)))\SetIcon(Menus.Icons.AddPlain)
if DPP2.ModelExclusions\Has(model)
if DPP2.cmd_perm_watchdog\HasPermission('dpp2_' .. DPP2.ModelExclusions.remove_command_identifier)
submenu, button = \AddSubMenu('gui.dpp2.menu.remove_from_model_exclist')
button\SetIcon(Menus.Icons.Remove)
submenu\AddOption('gui.dpp2.menus.remove2', (-> RunConsoleCommand('dpp2_' .. DPP2.ModelExclusions.remove_command_identifier, model)))\SetIcon(Menus.Icons.Remove)
elseif DPP2.cmd_perm_watchdog\HasPermission('dpp2_' .. DPP2.ModelExclusions.add_command_identifier)
\AddOption('gui.dpp2.menu.add_to_model_exclist', (-> RunConsoleCommand('dpp2_' .. DPP2.ModelExclusions.add_command_identifier, model)))\SetIcon(Menus.Icons.AddPlain)
if DPP2.PerModelLimits\Has(model)
if DPP2.cmd_perm_watchdog\HasPermission('dpp2_' .. DPP2.PerModelLimits.add_command_identifier)
edit = -> DPP2.PerModelLimits\OpenMenu(model)
\AddOption('gui.dpp2.menu.edit_in_' .. DPP2.PerModelLimits.identifier .. '_limits', edit)\SetIcon(Menus.Icons.Edit)
if DPP2.cmd_perm_watchdog\HasPermission('dpp2_' .. DPP2.PerModelLimits.remove_command_identifier)
remove = -> RunConsoleCommand('dpp2_' .. DPP2.PerModelLimits.remove_command_identifier, model, entry.group) for entry in *DPP2.PerModelLimits\GetByClass(model)
submenu, button = \AddSubMenu('gui.dpp2.menu.remove_from_' .. DPP2.PerModelLimits.identifier .. '_limits')
button\SetIcon(Menus.Icons.Remove)
submenu\AddOption('gui.dpp2.menus.remove2', remove)\SetIcon(Menus.Icons.Remove)
else
if DPP2.cmd_perm_watchdog\HasPermission('dpp2_' .. DPP2.PerModelLimits.add_command_identifier)
add = -> DPP2.PerModelLimits\OpenMenu(model)
\AddOption('gui.dpp2.menu.add_to_' .. DPP2.PerModelLimits.identifier .. '_limits', add)\SetIcon(Menus.Icons.Add)
addrestriction(DPP2.ModelRestrictions, model)
\AddSpacer()
for object in *blacklists
if isstring(object)
\AddSpacer()
else
if object\Has(classname)
if DPP2.cmd_perm_watchdog\HasPermission('dpp2_' .. object.remove_command_identifier)
submenu, button = \AddSubMenu('gui.dpp2.menu.remove_from_' .. object.identifier .. '_' .. object.__class.REGULAR_NAME)
button\SetIcon(Menus.Icons.Remove)
submenu\AddOption('gui.dpp2.menus.remove2', (-> RunConsoleCommand('dpp2_' .. object.remove_command_identifier, classname)))\SetIcon(Menus.Icons.Remove)
elseif DPP2.cmd_perm_watchdog\HasPermission('dpp2_' .. object.add_command_identifier)
\AddOption('gui.dpp2.menu.add_to_' .. object.identifier .. '_' .. object.__class.REGULAR_NAME, (-> RunConsoleCommand('dpp2_' .. object.add_command_identifier, classname)))\SetIcon(Menus.Icons.AddPlain)
\AddSpacer()
for object in *restrictions
addrestriction(object, classname)
})
| 40.020522 | 279 | 0.736935 |
654771bf848513749dd3ee3cb4d34b0e0b5281fa | 4,832 |
module "moonscript.compile", package.seeall
util = require "moonscript.util"
data = require "moonscript.data"
require "moonscript.compile.format"
import ntype from require "moonscript.types"
import concat, insert from table
export value_compile
table_append = (name, len, value) ->
{
{"update", len, "+=", 1}
{"assign", {
{"chain", name, {"index", len}} }, { value }}
}
value_compile =
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], " "
update: (node) =>
_, name = unpack node
@stm node
@name name
explist: (node) =>
with @line!
\append_list [@value v for v in *node[2:]], ", "
parens: (node) =>
@line "(", @value(node[2]), ")"
string: (node) =>
_, delim, inner, delim_end = unpack node
delim..inner..(delim_end or delim)
with: (node) =>
with @block "(function()", "end)()"
\stm node, default_return
if: (node) =>
with @block "(function()", "end)()"
\stm node, default_return
-- todo: convert to transformation
comprehension: (node) =>
_, exp, iter = unpack node
with @block!
tmp_name = \init_free_var "accum", {"table"}
len_name = \init_free_var "len", 0
action = (value) ->
table_append tmp_name, len_name, value
\stm node, action
\stm {"return", tmp_name}
.header, .footer = if .has_varargs
"(function(...)", "end)(...)"
else
"(function()", "end)()"
chain: (node) =>
callee = node[2]
if callee == -1
callee = @get "scope_var"
if not callee then user_error "Short-dot syntax must be called within a with block"
sup = @get "super"
if callee == "super" and sup
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"
".", arg
elseif t == "colon"
":", arg, chain_item(node[3])
elseif t == "colon_stub"
user_error "Uncalled colon stub"
else
error "Unknown chain action: "..t
if ntype(callee) == "self" and node[3] and ntype(node[3]) == "call"
callee[1] = "self_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[3:]
@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"
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', 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
\ret_stms block
if #args > #arg_names -- will only work for simple adjustments
arg_names = for arg in *args
arg[1]
.header = "function("..concat(arg_names, ", ")..")"
table: (node) =>
_, items = unpack node
with @block "{", "}"
.delim = ","
format_line = (tuple) ->
if #tuple == 2
key, value = unpack tuple
if type(key) == "string" and data.lua_keywords[key]
key = {"string", '"', key}
assign = if type(key) != "string"
@line "[", \value(key), "]"
else
key
\set "current_block", key
out = @line assign, " = ", \value(value)
\set "current_block", nil
out
else
@line \value tuple[1]
if items
\add format_line line for line in *items
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."..@value node[2]
self_colon: (node) =>
"self:"..@value node[2]
raw_value: (value) =>
if value == "..."
@has_varargs = true
tostring value
| 23.230769 | 89 | 0.534147 |
36bb47d0ec7312577ea1c7dd706da64c830f2e55 | 2,389 | ----------------------------------
-- rotate point around x-axis
----------------------------------
rotate_x: (y, z, a_x, c_y, c_z) =>
cos_x = math.cos a_x
sin_x = math.sin a_x
_z = z - c_z
_y = y - c_y
y1 = _y * cos_x - _z * sin_x
z1 = _z * cos_x - _y * sin_x
y1 + c_y, z1 + c_z
----------------------------------
-- rotate point around y-axis
----------------------------------
rotate_y: (x, z, a_y, c_x, c_z) =>
cos_y = math.cos a_y
sin_y = math.sin a_y
_z = z - c_z
_x = x - c_x
x1 = _x * cos_y - _z * sin_y
z1 = _z * cos_y - _x * sin_y
x1 + c_x, z1 + c_z
----------------------------------
-- rotate point around z-axis
----------------------------------
rotate_z: (x, y, a_z, c_x, c_y) =>
cos_z = math.cos a_z
sin_z = math.sin a_z
_x = x - c_x
_y = y - c_y
x1 = _x * cos_z - _y * sin_z
y1 = _y * cos_z - _x * sin_z
x1 + c_x, y1 + c_y
----------------------------------
-- sort on by z-position
----------------------------------
z_sort: (point_t) =>
table.sort point_t, (A, B) -> A.z > B.z
(focal, vp_x, vp_y) ->
project = (x, y, z) ->
scale = focal / (focal + z)
new_x = vp_x + x * scale
new_y = vp_y + y * scale
new_x, new_y, scale
----------------------------------
-- maps 2D circle rendering to 3D projection
----------------------------------
circle = (mode, x, y, z, radius, segments) ->
x, y, scale = project x, y, z
love.graphics.circle mode, x, y, radius * scale, segments
----------------------------------
-- maps 2D line rendering to 3D projection
----------------------------------
line = (width, style, x1, y1, z1, x2, y2, z2) ->
x1, y1 = project x1, y1, z1
x2, y2 = project x2, y2, z2
love.graphics.setLine width, style
love.graphics.line x1, y1, x2, y2
----------------------------------
-- maps 2D image rendering to 3D projection
----------------------------------
draw = (drawable, x, y, z, r, sx, sy, ox, oy, is_scale) ->
x, y, scale = project x, y, z
if is_scale
love.graphics.draw drawable, x, y, r, sx * scale, sy * scale, ox, oy
else
love.graphics.draw drawable, x, y, r, sx, sy, ox, oy
----------------------------------
-- wrapper table
----------------------------------
{
graphics: {
:circle
:line
:draw
}
:rotate_x
:rotate_y
:rotate_z
:z_sort
}
| 22.971154 | 74 | 0.426957 |
ff7750903d332918d11bda30e21a9270a419ce53 | 254 | -- This is a comment.
fizzbuzz = (i) ->
if (i % 3 == 0 and i % 5 == 0)
print "FizzBuzz"
else if (i % 3 == 0)
print "Fizz"
else if (i % 5 == 0)
print "Buzz"
else
print i
for num = 1, 100
fizzbuzz num
| 15.875 | 34 | 0.448819 |
d5dec3bc82c8e8a3e3fa308e90fca219bb7b7496 | 2,424 |
-- signed sessions
json = require "cjson"
import encode_base64, decode_base64, hmac_sha1 from require "lapis.util.encoding"
config = require"lapis.config".get!
import insert from table
import setmetatable, getmetatable, rawset, rawget from _G
hmac = (str, secret) ->
encode_base64 hmac_sha1 secret, str
encode_session = (tbl, secret=config.secret) ->
s = encode_base64 json.encode tbl
if secret
s ..= "\n--#{hmac s, secret}"
s
get_session = (r, secret=config.secret) ->
cookie = r.cookies[config.session_name]
return nil, "no cookie" unless cookie
real_cookie, sig = cookie\match "^(.*)\n%-%-(.*)$"
if real_cookie
return nil, "rejecting signed session" unless secret
unless sig == hmac real_cookie, secret
return nil, "invalid secret"
cookie = real_cookie
elseif secret
return nil, "missing secret"
success, session = pcall ->
json.decode (decode_base64 cookie)
unless success
return nil, "invalid session serialization"
session
-- r.session should be a `lazy_session`
write_session = (r) ->
current = r.session
return nil, "missing session object" unless current
mt = getmetatable current
return nil, "session object not lazy session" unless mt
-- abort unless session has been changed
return nil, "session unchanged" unless next(current) != nil or mt[1]
s = {} -- the flattened session object
-- triggers auto_table to load the current session if it hasn't yet
current[s]
-- copy old session
if index = mt.__index
for k,v in pairs index
s[k] = v
-- copy new values
for k,v in pairs current
s[k] = v
-- copy an deleted values
for name in *mt
s[name] = nil if rawget(current, name) == nil
r.cookies[config.session_name] = mt.encode_session s
true
lazy_session = do
__newindex = (key, val) =>
-- we mark what new fields have been written by adding them to the array
-- slots of the metatable in order to detect and write removed fields
insert getmetatable(@), key
rawset @, key, val
__index = (key) =>
mt = getmetatable @
s = mt.get_session(mt.req) or {}
mt.__index = s
s[key]
(req, opts) ->
setmetatable {}, {
:__index, :__newindex, :req
get_session: opts and opts.get_session or get_session
encode_session: opts and opts.encode_session or encode_session
}
{ :get_session, :write_session, :encode_session, :lazy_session }
| 24.484848 | 81 | 0.681518 |
338f6345cad38304cbeb26c2bc3dfc451670a30c | 1,502 | package.path = "./modules/?.lua;" .. package.path
file_util = require"file_util"
ast_util = require"ast_util"
JSON = require"JSON"
bson = require"bson"
configtable = JSON\decode(file_util.readfile(arg[1]))
outtable = {}
for i1, v1 in pairs(configtable)
curVariable = ""
if v1["type"] == "number"
curVariable = ast_util.obj_to_ast(v1.value)
elseif v1["type"] == "string"
curVariable = ast_util.obj_to_ast(v1.value)
elseif v1["type"] == "BrickColor"
curVariable = ast_util.new_ast_node("Call", ast_util.new_ast_node("Index", ast_util.new_ast_node("Id", "BrickColor"), ast_util.new_ast_node("String", "new")), ast_util.new_ast_node("String", v1.value))
elseif v1["type"] == "Color3"
curVariable = ast_util.new_ast_node("Call", ast_util.new_ast_node("Index", ast_util.new_ast_node("Id", "Color3"), ast_util.new_ast_node("String", "new")), ast_util.new_ast_node("Number", v1.value[1]), ast_util.new_ast_node("Number", v1.value[2]), ast_util.new_ast_node("Number", v1.value[3]))
elseif v1["type"] == "boolean"
curVariable = ast_util.obj_to_ast(v1.value)
elseif v1["type"] == "table"
curVariable = ast_util.obj_to_ast(v1.value)
elseif v1["type"] == "instance"
curVariable = ast_util.new_ast_node("Nil")
else
error("unknown type")
table.insert(outtable, ast_util.new_ast_node("Call", ast_util.new_ast_node("Id", "ConfigSystem"), ast_util.new_ast_node("String", "Set"), ast_util.new_ast_node("String", i1), curVariable))
file_util.writefile(arg[2], ast_util.ast_to_code(outtable))
| 46.9375 | 294 | 0.725033 |
3ceaf8afcc18ac87a3fb6802a4d2c81953ad744d | 8,156 | import command, interact, config, app, signal, Project from howl
import Process from howl.io
import ActionBuffer from howl.ui
-- forward delcaration
local FileManager
extensions=bundle_load 'extensions'
-- config variables
local showtype, typemode, showhidden
showtype_default=false
typemode_default='extension'
showhidden_default=true
config.define
name: 'files_showtype'
description: "Whether or not the file manager will display the filetypes"
scope: 'global'
type_of: 'boolean'
config.define
name: 'files_typemode'
description: "How the file manager will detect the filetype"
scope: 'global'
options: {'command', 'extension', 'smart'}
config.define
name: 'files_showhidden'
description: "Whether or not the file manager will display hidden files"
scope: 'global'
type_of: 'boolean'
config.watch 'files_showtype', (key, val) ->
showtype=val
showtype=showtype_default if val==nil
FileManager.updateall!
config.watch 'files_typemode', (key, val) ->
typemode=val
typemode=typemode_default if val==nil
FileManager.updateall!
config.watch 'files_showhidden', (key, val) ->
showhidden=val
showhidden=showhidden_default if val==nil
FileManager.updateall!
showtype=config.files_showtype
typemode=config.files_typemode
showhidden=config.files_showhidden
showtype=showtype_default if showtype==nil
typemode=typemode_default if typemode==nil
showhidden=showhidden_default if showhidden==nil
-- main code
getinfo= (file) ->
filetype=''
if file.is_directory
filetype="Directory"
elseif showtype
if typemode=='extension'
filetype=extensions[file.extension] if file.extension
elseif typemode=='command'
filetype=(Process.execute {'file', '-b', file})\gsub '\n', ''
elseif typemode=='smart'
filetype=rawget extensions, file.extension
filetype=(Process.execute {'file', '-b', file})\gsub '\n', '' unless filetype
{
:file
name: file.display_name
directory: file.is_directory
hidden: file.is_hidden
symlink: file.is_link
type: filetype
}
class FileManager
@dispatch_key= (evt) ->
if evt.event.alt or evt.event.meta or evt.event.control or evt.event.super
return
if evt.source=='editor' and evt.parameters[1] and evt.parameters[1].buffer and evt.parameters[1].buffer.data.filemanager
return evt.parameters[1].buffer.data.filemanager\keyevent evt.event
return false
@closeall= () ->
for buf in *app.buffers
app\close_buffer buf if buf.data.filemanager
@updateall= () ->
for buf in *app.buffers
buf.data.filemanager\update! if buf.data.filemanager
@keys=
e:
info: "edit file"
action: 'edit'
o:
info: "open with..."
action: 'open'
d:
info: "delete file"
action: 'delete'
t:
info: "create file"
action: 'create'
m:
info: "Create directory"
action: 'mkdir'
h:
info: "Show/hide hidden"
action: 'toggle_hidden'
r:
info: "Refresh"
action: 'refresh'
return:
info: "navigate into"
action: 'navigate'
escape:
info: "exit"
action: 'exit'
backspace:
info: "goto parent"
action: 'navigate_parent'
up:
info: "move up"
action: 'up'
down:
info: "move down"
action: 'down'
new: (@dir) =>
-- create the buffer and associate it with this object and an editor
@buffer=ActionBuffer!
@buffer.data.filemanager=@
app\add_buffer @buffer, true
-- initial render
@reload!
update: () =>
line=@cursor.line if @cursor
@updatefiles!
@render!
@updatecurrent!
@cursor.line=line if line
reload: () =>
@updatefiles!
@render!
@editor.line_at_top=1
@cursor.line=@firstline
@updatecurrent!
updatefiles: () =>
-- load all files
@files=[getinfo file for file in *@dir.children when showhidden or not file.is_hidden]
-- sort them first by directory, then by name
table.sort @files, (a, b) ->
if a.directory and not b.directory
return true
if b.directory and not a.directory
return false
return a.name<b.name
-- get the max len of the longest filename
@maxfilenamelen=0
for file in *@files
if #file.name>@maxfilenamelen
@maxfilenamelen=#file.name
updatecurrent: () =>
@current=@files[@cursor.line-@firstline+1]
render: () =>
-- load editor/cursor info
@editor=app\editor_for_buffer @buffer
@cursor=@editor.cursor
-- set the editor as writable
@buffer.read_only=false
-- display header
@firstline=3
@buffer.title="Files: #{@dir}"
@buffer.text=""
if parent=@dir.parent
@buffer\append parent.short_path, 'comment'
if parent.short_path!='/'
@buffer\append '/', 'comment'
@buffer\append @dir.basename, 'label'
@buffer\append '\n'
do
keys=[k for k in pairs @@keys]
table.sort keys, (a, b) ->
return #a<#b if #a!=#b
return a<b
for k in *keys
@buffer\append k, 'label'
@buffer\append ': ', 'comment'
@buffer\append @@keys[k].info
@buffer\append '\n'
@firstline+=1
-- display files
for file in *@files
@buffer\append '\n'
if file.hidden
@buffer\append file.name, 'comment'
elseif file.directory
@buffer\append file.name, 'keyword'
else
@buffer\append file.name, 'emphasis'
if file.symlink
@buffer\append '@', 'label'
@buffer\append string.rep ' ', @maxfilenamelen-#file.name+1
@buffer\append file.type, 'comment'
if #@files==0
@buffer\append '\n'
@buffer\append '(empty)', 'comment'
-- validate buffer
@buffer.read_only=true
@buffer.modified=false
@cursor.column=1
keyevent: (evt) =>
@updatecurrent!
if key=(@@keys[evt.key_name] or @@keys[evt.character])
@['action_'..key.action] @ -- call @action_<something> as a method; evil hack
return signal.abort
action_edit: () =>
if @current and not @current.directory
app\open_file @current.file
action_navigate: () =>
if @current.directory and not @current.symlink
@dir=@current.file
@reload!
action_navigate_parent: () =>
if parent=@dir.parent
@dir=parent
@reload!
action_exit: () =>
app\close_buffer @buffer
action_create: () =>
filename=interact.read_text
title: "New filename"
return unless filename
(@dir/filename)\touch!
@update!
action_mkdir: () =>
filename=interact.read_text
title: "Directory name"
return unless filename
(@dir/filename)\mkdir!
@update!
action_delete: () =>
local confirmation
if @current.directory
confirmation=interact.yes_or_no
title: "Recursively delete directory #{@current.file}"
else
confirmation=interact.yes_or_no
title: "Delete file #{@current.file}"
if confirmation
@current.file\rm_r!
@update!
action_open: () =>
if @current
Process
cmd: {'xdg-open', @current.file.basename}
read_stdout: false
read_stderr: false
write_stdin: false
working_directory: @dir
action_toggle_hidden: () =>
config.files_showhidden=not config.files_showhidden
action_refresh: () =>
@update!
action_up: () =>
@cursor.line-=1 if @cursor.line>@firstline
action_down: () =>
@cursor.line+=1
-- commands
command.register
name: 'files'
description: "opens a file manager"
input: interact.select_directory
handler: FileManager
command.register
name: 'files-here'
description: "opens a file manager in the directory of the current buffer"
handler: ->
dir=app.editor.buffer.directory
FileManager dir if dir
command.register
name: 'files-project'
description: "Opens a file manager in the current project"
handler: ->
proj=Project.for_file app.editor.buffer.file
FileManager proj.root
command.register
name: 'files-closeall'
description: "closes all file managers"
handler: FileManager.closeall
command.register
name: 'files-updatell'
description: "refreshes all file managers"
handler: FileManager.updateall
-- signal handlers
signal.connect 'key-press', FileManager.dispatch_key, 1
-- unloading process
unload= ->
command.unregister 'files'
command.unregister 'files-here'
command.unregister 'files-project'
command.unregister 'files-closeall'
command.unregister 'files-updateall'
signal.disconnect 'key-press', FileManager.dispatch_key
FileManager.closeall!
-- module definition
{
info:
author: "Codinget"
description: "A file manager for Howl"
license: 'MIT'
:unload
}
| 23.302857 | 123 | 0.703409 |
f176f75ed8d587c0ab55c7924752fb36b16c19ef | 848 | import Graphic from require "LunoPunk.Graphic"
import Scene from require "LunoPunk.Scene"
import Draw from require "LunoPunk.utils.Draw"
import Image from require "LunoPunk.graphics.Image"
import Point from require "LunoPunk.geometry.Point"
import Entity from require "LunoPunk.Entity"
class MainScene extends Scene
begin: =>
@img = Image "scenes/front.png"
@img.originX = @img\width!/2
@img.originY = @img\height!/2
@point = Point 400, 100
@camera = Point 0, 0
print "MainScene begin"
update: =>
super!
@img.angle += 1
render: =>
Draw.circle 200, 100, 50, 0x123456
Draw.rect 300, 100, 50, 50, 0x654321
Draw.text "Hello MainScene", 300, 300
@img\render @point, @camera
g = Graphic!
g.visable = true
e = Entity 25, 25, g
e\setHitbox 25, 25, 50, 50
Draw.hitbox e, true, 0xFF00FF
-- e\render!
{ :MainScene }
| 24.941176 | 51 | 0.695755 |
ca02bc1fd02a52872d4698089271ffb25d7a40b8 | 11,205 |
-- 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.
data = {
"XQAAAQAO6QEAAAAAAAB7n8SEw387KgN0RmBHLQWvW9L46KCk3wDGdXcdDGKQwIto09cy0yk+",
"Y9qvJVX4sqhyPZ/CH+39wb9LNbRo2VzOi5olAubjTkvIMBHd+exhf7usSkAYONg7Yzo93QG7",
"g7XwM3jc0V0oP0F++mXJOkI1O0VBDZ5b5pAFNnuzNiHChrG+xeVoZIgraMxjPqM+VZQxV+mS",
"BlKzrUeNWaDKwedixktKC9X7yxg8qFx9Wd8Kad39Oti2zQXhkSIRg6iPywJW8AKAdDROMHQv",
"Kn1gUpkZiK1v4+2wYpZyIG25cNXDF7TNh3PF4+u+KQgxrZmAo0MjPp/afwe2agvojYm2jE14",
"F0FgHa1jKUZnB9siUfktaaU43A1fl+4Vl6AP4px1Fvyns6yn8TJYqgx4uk7eBuR2k+PEN0F+",
"vYFQzJEsN/2Y/4dldOdFvT8D9aefHZXsXpOpjKv6DQ7ewJW06YPIF87NQMpDyCD1ZTlRdkAe",
"hRV3hpPWsw79i/R8D0zzqUPcPoOkH9jkzj/h0suoGyse9SjhZQz198ahiAQ5sbJ2ccG59yjR",
"A+BOX0Jy3kvMnOUG7piGvsQ8/Qao9t8hje673fBNF4Zk6DYBxirgLBluT1B5AB/ubs/Jstng",
"Dt3OI8guQjzwntnYRsMGMCyHssL4ysFOJ96wsUoaZuDAUcnREmFMfrrnReTd7nbEEEmmK/fX",
"QjTfmA6vdD7xLIGRRlVJFo3H4o3LBgbPONAZujKKTebR1ckSHy6PYmd1vnacggq1wGajtHOo",
"PQxPyUl3DgLgRwLakorlsXiLp3zdJ0PTLEaGZgzqE4MSb/Uid3ZIV1bosRtVo7zxfS32SgXg",
"tCosI6+TtUbPpwaCP2kQ0I9bGn+Xw8fG7leWGn5kM3dQsvBjqJTWyxISxQQj8L6753xAjGMS",
"926rL8WdayB2ZEf17UO35FSYLWGtch/pVV72Etd9oAe37VkU4YQtxBde0wOSM4eQbZu4UlvK",
"/CVcmf2goNfCVy8Ib04X1/eS2ft4tXNG59mG5nWNDPUtsr9W+VZADtJ8HqODnS8NU5sJ06Du",
"7vTsGbMN98ByOp2RMadw0U8ADsb8uQLhbAreDEc1zqHKXVmR2/RHQQ37QhGOS/a3HW+zwDNp",
"iRJnLVNYkbDX7AYMU9SG3X86Dl7fSUmqMZ3PyAN0GwvZ9GJa1toXsrMR847LC93VGfjJ8KpK",
"uSyVz4gfZFThOq8Qc9CABAWMhp/VKQLYKv6wwbb8JOEPqCs1iUbNTkcj5o2kACqwfW3mC96K",
"446mTQPsJF0v6lOW0iBxg9KFYdI8Rxi6f1CP9f+vPr7ka2sQfOuYilb3ovmcRqc6esbXm93H",
"Fw1J2L9F/jGeJnFvoOlMvC6uTtoY1FYlarzcsrnmsZRPhSoVoKJtLqaANu8H8ZluBGWtyFcK",
"ZrhY5cq7BI5jspFsYWGgPNhRAgGnorTjeWN1LiDi8/LqtojHQzc3diG1Vgi3SS57BiwhTjOq",
"GgM0VBwdVcvktNAuhRheKfTT+/bbtIGW8hM3tbkUt1h4OB7oJGAEcmKv5fFoHhxQI5GNaXv6",
"XtM5FmSj2x2raXFiOos9MRouPy3kzSsczPk8gPEKxOsM1/4z0kmJeR5HBsGkRVDlFXEKBvZS",
"18qSD2MThFIhHj6C7lnuI15Rs3zxiHbF6ogKxFxQDlVMmSHL7+O5xCWT6FEpBl7/s9u8H+51",
"vcww1vveoX7Fj9aOKJzi3oWoKIuBu1lmopaOHene6rKc3IYquevdANMllETeWKZDvtxj3aQu",
"QffggHtkKqM8qP0Oi0MfXUZjVh9378QDaoPf4E/ASPMHc8SVguSmqqs4Q75k0VP0o6637tmU",
"rvi4tPhmw8ow4fdTkLTphRkJpgKh81QqlPPC0MEanDryZfUQHQn25O4cDDs5aqMxTRhIrGWt",
"BpS4Ta4mEvaF9MTB4++62DMPqJdwnFBUOuP8b5+98HJZFvKQ0VJY4q9lEc8yJNdjegXvH2s2",
"rIA6E4ZPAnkKair++NreWu2pp8NwhXdBzeeKlqKrtq0XqvRtPQanljmLwjfJ3ILQIXXd56D0",
"EiJJqAln9DbYt7I91NSZ9dMWzFYpkgjLRxJImeT6RQRPBhDAzCUta1caljqroXFHgNJZNxym",
"MbdemfXz4s1sqB/6KxgaUja6YEX+N59IoPRr7b/+90OiW9NwsCzSEpzBEP5gysOUE3lrH3Bb",
"bWOm0F2klbZ6b74E9OYf6i5gjW74BxHYl5JxXKW8upq92pk/YOSeaxHB8czQRdFBi4p8JSht",
"C7dcfDLh8Odl+GRpLLW0pzbsoMYBRX7onvf6DHJ6A3hZw/O3EqgYLsjwYQWpRMWfEM17a+4x",
"JV0AhvRYsykntJ9aznvhB0VibJd5QtQ/8UyUUkx3QbksK1y+ePyehxhGJ09ohs4LmGPT0vEs",
"DQQl0vU5y/wDNZhITwUjihZET5SCs+TAXJ2FVpLkEQ7QwRSCJTIb9Za2lBa3HmUA0N04PMPz",
"gwpmeqX3Gqwm14nnu+pW3/2Y0fmnpv2hlWqyltE1gGcDdQPnjoawMTJ496U+N/daQCnn+lwb",
"xqGCVgt6sVY5MMjXN5PYe9DIqEgNjcgU6IShmNxw1XNg8Nwh/oCaAeu6etHUgxFZ5rOtaKC2",
"uvP0II3pkfQ8xcKo8kyr/Poe5PXIG3MvB/EwjJg79w871VMmz+Mv1PICOqh1aa+vp4Ck8EwG",
"6S2NTKEtXfHiJv2AwuVuUONZ3Ca/Yw5U9MAh0Go08D8m4s64wXajqgVkSwaPwdI/xrxV4ijo",
"1YvkYpOQfulgY7mIceWfyA38I8j3WA56JxlPEKEGmRU0YyUNW5WpRbeLz3lhYkUzzuQH49+R",
"9wQMsMX57CnnNB7RYFfxv7FzXWaP7Kpme9iih5D8My+/2z+NWkNZyfaoBpDKJq74XciMCdcy",
"zFcGGglrcSdh5cIomY2/0h1WFyLmGh2N+8U1pUYTdyVGY7PmgoLnBQ1njGHBMS7uouK5DNqt",
"mZP3Cp/OroFXzWaatvJ2P44FeEfY6hRI9DR7zrSLu5DoQhj1+QhvRutLO+hjcX7oihg3eBR0",
"u3XxJo4aJVFUFyxClsW8014B8xP8Tg83YnCKtwloR5avsnAraYl8xNvw46kha2yoy2k9nAP0",
"px+pPCRBPL/5fUNWd+unsHWL0RFhSgrJQXA1DW2XjB34OHNkmlo2otgUxI//yXldCT4wc8Wo",
"7FJ4ycZWthJK0j3iUWYllb5dOcH8BMh866yshQCMXkcYIgtRXFfXBgGV/f/X1FCAWkhfMsAX",
"FMKW6uGTOAHdW3XRt0qMOd6fzMFdii3r60w6UyUo6S4dc3dc4nqjx6E7Pi65YfUCFy/bhemk",
"Rra3QxHSPDEr6zfDkzSxtyYzX1eyynDPD5C5MBUmoaoF+fGCk7tLzGpQlx6XQBeI3qhJtPtv",
"0MDs8bRJs+Mif8dyHeQ4zfr3lz8gt4RZTMIw+Xb8lVTRFy9e9zNs/P33VSu2mBXkyGDPGCeh",
"tax2SXHz0LVlhL4/sG6Wlx25c+89GQgdEFKw17lpcijTqvF3ypSHow3p1PJRz7SnXliNGuGx",
"5T5Scn5Gc5CpHY1DdmiV789XiO26IWYdVytbcSmRM4WxkDTu8miN7xFmuqB6fF0Iukb+32A+",
"ZgT8F8iYJbzaEFRGE1FBZp8EKjV1+RYnrtpVDp660x9VWs9xbkxTmQ3kOwO42O/1EmcYlwIf",
"Y91pcUMv1X+54UwneGHNuKcLWTFYjvdOE7E7rkarmbLgAgUBTCoDEpU/uZ6XVJH/Popvko82",
"Gezg1etYBYmlek/sV9+YL/12ABLyl5rC4RIjTWeud6Gfa5X+v/lrcvFNKpWuH7gaGoyhHecj",
"P5hdn4RKd/wrxfJwBCn4vCWSovSxWNiapP0kYcEu1xPxiGAyWv2WfnQNmzsECDEV5cGsZF+1",
"2VMNPXoIHa247XGd2IbroBkNXNsQQieWJZxtSZCv8B7oN+PJuw0JxaL5XtCgs/iUO8Or7rAA",
"6vNV1T8Qjkw0YxyKpqCSXHvjeZn/Hr9TqvI73ZVvHTVkMw5xMTU13mJfo6J6hGEX/MleeSY4",
"2EQdMsFlvNK96iy7dBKPFc547FaE7Ht5CyeSH2o60n1Ds7ywoOhZJUvqKAOeUCXnFZqK5XMY",
"ukOxWHP0Mlufa06Lq6MpT+/4u19FEXyLahlU9lzsM7s18BGP25lfbJGAU3qyDqDmTnnBuv+V",
"E7Q/BoQfcUeQ4kB/isLSI7t/bt9yX+j9+qggqk/lFlHlEbJ2LG9OgjAWFNeNOOeqrf131u36",
"vBX4P0GHNCAsKjP9z6cwieG9I9cw/96eUO8/PnyjM65XQZI8oQrvkoJ5QvwAbEi20AloLaVw",
"i5+88FMC+WhUUGT9M/Lz/bwdKET3gH8YUd9wTxa6PZe3iEQ/sFIRTv0ZpnrA+Znf0rIAfGWb",
"WtQfk2uT1hCzpKLOrouqFNHepCxwXXrsc6t1q9Oy2XSs5n+Yey0zmu+po6zGk/eHbLjpdNeS",
"RqvyEOodqn2FxxEUwzGxOpxxKEiB2YhFHNYvjypuIxamjh81p6/oustPAtf6f3dQ4DwRjg1I",
"JIdlATJLga7zBKfzV2rz5KtSvKGY3zc45u3VRTl48A7SpWnsUQ6T4K6eWlrwqb/j4ZMSsD7v",
"pup8t5DWp2lKoGu8ZtrX1GUOaY5kEhTrqQY1DJOeinq+8iNtODyoPRwRDI8N015BGoo7ulWP",
"ljV2oSLung+61UbO8rkI0c+uKb9GUaIB1rZ3jd8yb5KV0lDHIh7M1xKnYpmWNUTnQLclos1d",
"s5AK4JwwP4MyrC37X5bPg9jkJH8m2jpTISy+AnG0APiz2xGtHe14kj4rpttg+Jn4S4KwBJty",
"6HubcxUDIdSkuOB6d1djcHRPgw20eznih5RCyd6/QQz8wfbZcf4wrJ739TTHl/NB6mLl9vkI",
"KvGSB2Rhf4Cz69fILB+s6TSmkFvq9SxmUWjTXRNC4vzfkQjcuSrMLK1IRXJLNJuFaVZI5yLu",
"IWSjOVg+K2aStBPz/RnxVkd0xuS3awPSkRnxKaq4GhnEJ+ZaxWR76PQt3vS5a4Z1/hdunGLC",
"iWUS1Qiue9Bagzrb1rADKSniA0nLw7XxSeYwSJsJ6Gee0+C+lxcga24KwKSUYoqQ6XtuTd6U",
"v+MZwFGuGQnb84myKSUtALgLoc5dKdDVllH4kMlZSkLgZ6iPsiWADYyfoLPEz46cENU/EaoJ",
"F8rRzctDLWr/iBwrTFLRIHd2fBzXvnNKJG0qXIhTxq6H2CAI5k5kSQaxVRjeJ0ejLB+EoXGN",
"+nMQaZyxhUm3ggtm1v4tvVRKvc/tvYY+5caAqAwZtGNVNg0VBnhPkPneWylZKOL8HLXoaDMb",
"xjtEyGfLC47x6y5Go50MX2sG8ZD6aVBDb+gX8wa/jzsFR6XOI3r5VhDBdPbhwSd6XlMpH/95",
"05ysScqNtDv52aeb1fXCxYSrAFEpTRvRiXwsFWts2I0fgg+u18pV74VO3XIv4azgyiWjzwsm",
"gAEQyLpce4KI+H+JYJ4lG28YthNEnE+8SBGjGFkjeSmTy1uWxSoXXqJD25Ny+crvbzH/KhvI",
"KO8oSFvptQBTCbu1OWda3j6P2B1BZPR+G7toWF82o7YhLP1HLafdiIZ6x1Hz35ZBHr9FReFD",
"tDcrSwuHxlQlCJJE7R1Ds0V6khk4aczldz2aRCsDEkA6rM6Ofp5hqRNvtj8RPs71eWN/lASF",
"3AZGkPuo6mtD5iJQ7Y6ZUL+5Q/RIf7Jvl61hu2qVmv5ibmNpPm1ThR98T7CO3MQrp32N/z6X",
"ywV9Gm0CbUhYzHms9v4BeZo7FzVLYcXcjDH2w4lkpniqTvsk9/nirL3Riw6ppaj0vIaoUf0J",
"Vp3J60TXImbJz1V/HKvBYHUkHR16kk9UoQa37RT7bHDshpzsnhn2cg6oGqQZpxBtBJcM5JXv",
"ZVOWs20UpiZJHWuQIqcg4GB3u3SWJcB1k9DEWHury2bYPl9YvfHT+mqOR1lAQf6YKSkuz4Zb",
"Ywom6DXL18o2Tg0TgLsNNO409qthDIzhZlYgBh5ugk+gAu8x4dTRUUd7qUrFB5VsKEojXPoh",
"fP3Qb0tfudTezNb8TdmnMZGHEjW0nXDev0nCMNpQGbj1ZIp1y4ji7JH9mWBQBH0va+pDIBCT",
"8cxjoWDpEdVO57mClBTyevxLtty53AGW6X2g9sAOsvAZFAaQtWsu5txrDlHJ9WDg6dgBad4l",
"AzmevpMBLZsvuCike82RDbQw3FMsXpSZj0ORf87cZq11sVcnzxvBMNMym9xIi3oQshqhv4rp",
"oLJAjSpFa9BEr8uzPBkP+dTwWwO9FhY2S2MkoBnNl7HJOBaOwPRtTszGiLaS6Z17jObloRpV",
"Cmy1JpXTkg7UnZBfsCRNBqyLI6oNKlVpSruTh/yrpM8ELRCZQWuG6sQ/UzBUN0gzxbtXGB3S",
"szP86pXQfS2X9CVQDldxg4MVd9EzmGackbCHDWEu89veEMZUEHGPiDEJeNTBSpEniXwcxMFH",
"HSJuv87fGrJm2N51Uj09vraeYdOpr/VQYgGzpK+FT5aW5nKT1RcYfvy6J18lRvyUnKWSLiUI",
"UM1Ft/I8fqWY5mxZnHnPKupCoBUmgPP9z0GkfVY77MQx0fUiPNJREA9ACILwTXtQSDnY6bOA",
"OUmmCiOEg6NfFXJZCo9GREOHqOR/soK1SkS95pl4lO5N5UfLa+nPxS7DCp1zNSo8+hXB4Zmc",
"fTWXY7you7Enz2GU7MihTYeHzt4dvjewGz0M0fEve84C9l7vcv6AWMOfk1+cDyXfrGyxQyZX",
"7W+7sSSCav1HDeS3cO8CXUGeFnDW7BV1qWONanW2+TbALwc+OIey1NvS9oW1DoVik3Uo8TbP",
"fiyHbheK1kLd1+nGctSLumGq1DmgPhYbEFBRSY7x+fDMkaFt4DRBsUQ3ms3bpLmqiKFGPwiD",
"6Ckk90Y75dHBEGLFcnw+FQ88yOpCHwPQ2SgQmOqb6OpupJd3UGcc8MvJEilGTGJIdvDWWkia",
"5N2c0JkNiQV5o9jcuutlf71rLb4GtwixuyP4vjMp9HaDFszrl5R/F30uHKxL31xAxl64f9ZQ",
"bPWoYjeDbeW/4ohrF98kG9dBfq0RMqSHK5xYtr0GKBG2qzbr3IP7VsNJPUSrT30INb/v2auD",
"qZt1pJeUB4l06Ezz4cx3YaNk7mzYHJr5eHVq+Qzr7xVB0Q2FGu1b9lVqgdArXA9roIJHmgAI",
"aK8osGzLWFAR4a4vf2lxEOVzEX1ZZeFvAdzn0x6+XiakwP2DyC0Geco3pelSSPCf7W1W9Ngo",
"nULE8UmUrltY8dza3pYecOXtFMCkwwcW/Oc7mwbjLoXSas9Q8v7hCNcx5Pd7Zm/+NhKExi4P",
"t4YRAiq/S9LE6dQ4OPhXhVP5sCePdK3dEogJlaqBevxJpylo7X9jjFQemM2xdSOvIALjJslA",
"Aq4y9QCyXeEdAI/usLsWDRp2z4KpPW8WafM84QOB6fYgfkR1MbLDhYOZ9emlH1ZMHZxwth+l",
"1JAJFjkIJMT3WeNBogHR/0KWT44z6euFiar4s6DnreCDCrTzSrXoagaLJG4j1ELFhxK3qIXZ",
"uzHyMNuTC3bZmGEZiMumVIYYAi99K9vJh8cGrR2JcJBaeeW4Cnr7G7l2Grfe+3nx0+uz37XK",
"XyLdTSStI1P4OW4xDIyOosqUK2jZ7XjAWd5MKMIHqCJu8iesGF8tzeTcqnZLv8H47KxxwQi0",
"T23ae0VmGBSho49lTDeJRCczA3EmCUKzSOvmz+0lqaKnQ0uYz7kFW2nXGoS0/JvkATLdWGue",
"heMtFvb4/u0ASQNxLCbeYX96y6JjRYd9D5PtPsPQoHmWaQ9DeNu65sytGZ/46xXdFjxnhFhZ",
"sXjfL16q7MIR73Orxz+vbK9EX1A4RdkkycY10Se9V4LYewqErmwlhS+TxY+9vftCizx6B6to",
"+4NlAImOOhZs8zIwkhqVfBL0QWz9I1g/pOHoHRKhp9zx+X3it8/XDKKGR0aeIRFkLzpno7vv",
"iCgCbNz6q9IUgh1bBlFstIcB+RwNBxkpIVHVZgCpkYIBRa3zSkGSQzEljAkT+WjN5/KvcYYQ",
"ClvnIM2GhiINDWznn1CNbMFQKD2PL6eaPWsMuPM3wECmsQZGUJUDtin/5+H4kkyUe8mlASVc",
"Ev2mYBJiUXC90eN8zQwQGEBub15O9Btizu6OH/UeqoBBMIFzF/dkGykg2Pl2M2CxtmJgJ5o+",
"X92EHdy2uT44b0iZx4so/ltWUQ5vtzKe6rxh25cE55RZ2XeENuohVGrdV2xwqBIXAa7lGbcV",
"xZrnzJGTO3uz00RFACzNaR8lbkwU8j+X5DsmI1gt0GGvTBmr58oG/DqT2gV8hmiu36WPpcNo",
"gCnbKxGyVfMxsmWZ/1CObqyVpRnO4l75EsYJUKl0Bk+1InJAqOWQLwOvC25t/2tK3cseXIa8",
"gBpyZx0jWBLiJyPaZt5KpIYMiDhtKk1tqod1iOYPxVp/EQCBR4rHPTZRa2cx6oy7PZZZtkT8",
"LQUmpv4CBqKLALsTSawsZevxhD5tmbFayRPQmggkN7o6XZg/m7S4xoaYC1b91o6lhviuN5Yl",
"gfsKaTE9FDV9FwmlSlBYols916l26P8ERlXhgl+wmB4VchzcO2UUU4eDsuadwhVB9wiLJ+Rl",
"dFc7GuVhMDEMgYWlgc2RGS3UxsihwSuLwAhEAdkjVXIR+yEKmJwwyasBUIRyoZJ+Mf1MFbJY",
"KxsMZw+sD31xKIIsFmA0LcyX7/Zv2Hz2t1usMAW/dJs4V00z4JZ9Gp/vODIxdOCx7Sy1o4V1",
"e0c6/W+PU30Wk+7JS47hN3yZl9K6m7kFLKHwu7xrYER9PwcG1dQUsSIKpBoRq2KtfSZzTYMI",
"mVjYwXYqMi3Pc2Cbu6H8r7nP4Yo4QGCFF6zW6R6lpcECk24ozRFXPIHesxpGqaQqQVd3/KEJ",
"0mVSNkgGeJpaz1HNdqEWsS2igzhqLYMqRWrUNK8yePzAsfS61TKRxtW3QzL6BQLl4EcUuvol",
"1parmEqp8S9Vae15/Wd7Y2PBSgFLeIHrSlu3/Fv7EUXwwjWti4ZPoSUffRwu04Dzh/4DRipC",
"T5aGb+IOTVRW6P7bcFLkQuVNZOfQOL28a76WmxSudTXzeFe/k9P0ikRI2P8lFw6gu4/CK/gC",
"VLGrvvGR6wwYjasgyV1Pj/fWM4PEIxPxcF5XSNswEigBfvzDaDc1jHxUc2u6QT3QnUaV3dAB",
"quQ3Nzbvtbz5cVZ/bF5g+hObfubrFFsyoosEmA==",
}
return DLib.GON.Deserialize(DLib.BytesBuffer(util.Decompress(util.Base64Decode(table.concat(data, '\n')))))
| 72.290323 | 107 | 0.893619 |
07455262be1da486a8898e941a46ab91a935d7a2 | 121 | TK = require("PackageToolkit")
parent = "appIoLua"
members = {
"_text"
}
return TK.module.submodules parent, members
| 17.285714 | 43 | 0.710744 |
3cc91fc975d9cca05fe6b5d21f3e9b38b20a7402 | 824 | -- Copyright 2013-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
howl.aux.lpeg_lexer ->
comment = capture 'comment', span('#', eol)
directive = capture 'preproc', span('---', eol)
delimiter = capture('special', '...') * eol
operator = capture 'operator', S'-:&*?!(){}[]'
key = capture('key', alpha * (alnum + S'-_')^0) * #(space^0 * ':' * space^1)
dq_string = capture 'string', span('"', '"', '\\')
sq_string = capture 'string', span("'", "'")
string = any{ dq_string, sq_string }
number = B(space^1) * capture('number', digit * (digit + '.')^0) * #space^1
block_scalars = capture 'string', S'>|' * scan_through_indented!
any {
string,
directive,
delimiter,
comment,
key,
number,
block_scalars,
operator,
}
| 30.518519 | 79 | 0.597087 |
8d7e9ed8bcd282527791e28c53a6c06f3b474e46 | 365 | make = (frames, s=1, loop=false, f=util.lerp, current=0) ->
anim = {
:frames
:s
:loop
:current
:f
}
with anim
.update = (dt) =>
@current = @.f @current, #@frames, dt * @s
if (math.floor @current + 0.5) == #@frames
@current = 0 if @loop
.get_current = =>
@frames[math.floor @current]
anim
{
:make
} | 15.869565 | 59 | 0.49863 |
aca1f61bc09c36916367e5669916490645273226 | 4,427 | import
getmetatable, pairs, rawget,
setmetatable, type from _G
import bind from "novacbn/novautils/utilities"
import clone, keysMeta from "novacbn/novautils/table"
-- Object::Object()
-- Represents a simple generic inheritable OOP object
-- export
export Object = {
-- Object::new(table objectClass, any ...) -> table
-- Makes a new instance of an Object class
-- static
new: (objectClass, ...) ->
-- Make a new table that inherits the parent object
newInstance = setmetatable({}, objectClass)
-- If any assigned Decorator instances, call the '__initialized' metaevent
metaKeys = keysMeta(objectClass)
for key, value in pairs(metaKeys)
if type(value) == "table" and isInstance(Decorator, value)
value\__initialized(newInstance, key)
-- Call the constructor, if available, then return the new Object instance
newInstance\constructor(...) if newInstance.constructor
return newInstance
-- Object::extend(table parentClass, table objectMembers) -> table
-- Makes the provided table extend the parent Object class
-- static
extend: (parentClass, objectMembers) ->
-- Extend the parent Object class
objectMembers.__index = objectMembers
setmetatable(objectMembers, parentClass)
-- Loop Decorators to call assignment metaevents
for key, value in pairs(objectMembers)
if type(value) == "table" and isInstance(Decorator, value)
value\__assigned(objectMembers, key)
-- Call the extension metaevent if the parent Object class contains it
parentClass\__extended(objectMembers) if parentClass.__extended
return objectMembers
}
Object.__index = Object
-- ::isInstance(table parentObject, table targetObject) -> boolean
-- Returns if the target object is an instance of the parent object
-- export
export isInstance = (parentObject, targetObject) ->
if rawget(targetObject, "__index") ~= targetObject
return hasInherited(parentObject, targetObject)
return false
-- ::hasInherited(table parentObject, table targetObject) -> boolean
-- Returns if the target object inherited from the parent object
-- export
export hasInherited = (parentObject, targetObject) ->
metaTable = targetObject
while metaTable
return true if metaTable == parentObject
metaTable = getmetatable(metaTable)
return false
-- Decorator::Decorator()
-- Inheritable generic object that allows for enhancing of Object members
-- export
export Decorator = Object\extend {
-- Decorator::__call(any ...) -> table
-- Metaevent called to shortcut inherited Decorator initialization
-- metaevent
__call: (...) => self.new(self, ...)
-- Decorator::__assigned(table objectClass, string memberName) -> void
-- Metaevent called whenever assigned to a Object class
-- metaevent
__assigned: (objectClass, memberName) =>
-- Decorator::__initialized(table objectInstance, string memberName) -> void
-- Metaevent called whenever a Object class is initialized with this Decorator as a member
-- metaevent
__initialized: (objectInstance, memberName) =>
}
-- Default::Default()
-- Quality of life object for assigning default values on Object initialization
-- export
export Default = Decorator\extend {
-- Default::constructor(any defaultValue, any ...) -> void
-- Constructor for default
--
constructor: (defaultValue, ...) =>
switch type(defaultValue)
when "table"
-- Construct the default value if Object, clone the default value if plain table
if hasInherited(Object, defaultValue) then @generator = bind(defaultValue.new, defaultValue, ...)
else @generator = bind(clone, defaultValue)
when "function"
-- Bind into a generator if function type
@generator = bind(defaultValue, ...)
-- Store value for later lookups
@defaultValue = defaultValue
-- Default::__initialized(table newObject, string memberName) -> void
-- Metaevent for hooking into an object right before constructor call
-- metaevent
__initialized: (newObject, memberName) =>
-- If generator provided, generate new value, or use the static value
newObject[memberName] = @generator and @generator() or @defaultValue
} | 38.163793 | 113 | 0.683759 |
b01a86877993c8b011d7449e79268f6b948d38c4 | 1,936 | import DEBUG from require "typekit.config"
import inspect, log from (require "typekit.debug") DEBUG
import compare from require "typekit.parser.compare"
parser = require "typekit.parser"
signatures = {
--"fa :: Cl a => a -> b -> c"
--"fb :: {a:b} -> {b:a}"
--"fc :: [a] -> [b]"
--"fd :: Eq Ord a, Ord a => Maybe a -> Boolean"
--"a :: a"
--"b :: a -> b"
--"c :: a -> b -> c"
--"d :: (a -> b) -> c"
--"e :: a -> b -> c -> d -> e"
--"f :: ((a -> b) -> c) -> (d -> e)"
"g :: b -> (a -> b) -> Maybe a -> b"
}
import getlr from parser
NAMES = false
if NAMES
for i, sig in ipairs signatures
import nameFor from parser
n, sig = nameFor sig
log "parser.test.nameFor", "#{inspect n} :: #{sig}"
CONSTRAINTS = false
if CONSTRAINTS
for i, sig in ipairs signatures
import constraintsFor from parser
cl, sig = constraintsFor sig
log "parser.test.constraintsFor", "#{inspect cl} => #{sig}" if #cl > 0
BINARIZE = false
if BINARIZE
for i, sig in ipairs signatures
import binarize from parser
S = binarize sig
l, r = getlr S
log "parser.test.binarize", "#{l} >> #{r}"
log "parser.test.binarize #name", "#{S.name}"
log "parser.test.binarize #constraints", "#{inspect S.constl}"
REBINARIZE = false
if REBINARIZE
for i, sig in ipairs signatures
import rebinarize from parser
S = rebinarize sig
l, r = getlr S
log "parser.test.rebinarize", "#{inspect l} >> #{inspect r}"
SUBSIGN = false
if SUBSIGN
import rebinarize from parser
S = rebinarize "Eq a => (Ord a => a -> a) -> a"
log "parser.test.rebinarize #subsign", inspect S
COMPARE = true
if COMPARE
import rebinarize from parser
Sa = rebinarize ">>= :: Monad m => a -> m b"
Sb = rebinarize ">>=' :: Monad Maybe => a -> Maybe b"
--log "parser.test.rebinarize", inspect Sa
log "parser.test.compare", inspect {compare Sa, Sb} | 28.895522 | 74 | 0.579029 |
76db4907159e02fa2499f86657ea1738267d4234 | 990 | -- Copyright 2013-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
is_header = (line) ->
return true if line\match('^%#+%s')
next = line.next
return next and next\match('^[-=]+%s*$')
{
lexer: bundle_load('markdown_lexer')
word_pattern: r'\\b\\w[\\w\\d_-]+\\b'
default_config:
cursor_line_highlighted: false
auto_pairs: {
'(': ')'
'[': ']'
'{': '}'
'"': '"'
}
code_blocks:
multiline: {
{ r'```(\\w+)?\\s*$', '^```', '```'}
}
is_paragraph_break: (line) ->
return true if line.is_blank or is_header line
prev = line.previous
return true if prev and (is_header(prev) or prev\match('^```'))
line\umatch r'^(?:[\\s-*[]|```)'
line_is_reflowable: (line) =>
no_break = { '^```', '^%s*#', '^%s*|' }
for p in *no_break
return false if line\find p
true
structure: (editor) =>
[l for l in *editor.buffer.lines when is_header(l)]
}
| 22.5 | 79 | 0.551515 |
d4c1cdc91fcc154cdbe61bb37ad6a76c4705b47e | 2,423 | require "assets"
require "settings"
require "knight"
-- Local variables
{:cell_size, :white_color, :black_color, :rows, :columns, :font_size} = Settings
white_modulo = 0 -- Either 0 or 1, shows which color will have the top left cell
-- Generates a table of positions in chess order
gen_lattice = (mod) ->
[{x, y} for x = 0, (columns - 1) for y = 0, (rows - 1) when (x + y) % 2 == mod]
-- Sets drawing color from settings
set_graphics_color = (color) ->
love.graphics.setColor(color["red"], color["green"], color["blue"])
-- Draws a chess cell
draw_chess_cell = (index_x, index_y, size) ->
love.graphics.rectangle("fill", index_x * size, index_y * size, size, size)
-- Draws both white and black cells
draw_cells = ->
-- Draw white cells
set_graphics_color(white_color)
for pos in *gen_lattice(white_modulo)
draw_chess_cell(pos[1], pos[2], cell_size)
-- Draw black cells
set_graphics_color(black_color)
for pos in *gen_lattice(1 - white_modulo)
draw_chess_cell(pos[1], pos[2], cell_size)
-- Draws cues - numbers on the first column and letters on the first row
draw_cues = ->
-- Draw letters
col_index = (white_modulo + rows) % 2
for i = 0, (columns - 1)
set_graphics_color(if col_index == 0 then white_color else black_color)
col_index = 1 - col_index
love.graphics.print(string.char(97 + i),
math.floor((i + 1) * cell_size - font_size / 1.5),
math.floor(rows * cell_size - font_size * 1.2))
-- Draw numbers
col_index = (white_modulo + 1) % 2
for i = 0, (rows - 1)
set_graphics_color(if col_index == 0 then white_color else black_color)
col_index = 1 - col_index
love.graphics.print(tostring(rows - i), 0,
i * cell_size)
draw_piece = (piece) ->
{pos_x, pos_y} = piece\get_pos()
img = Assets.images[piece\get_image()]
love.graphics.draw(img, pos_x * cell_size, pos_y * cell_size, 0,
cell_size / img\getWidth())
local knight
love.load = ->
Assets.load_all()
love.graphics.setNewFont(font_size)
knight = Knight()
-- The main draw function
cnt = 0
cnt_y = 0
love.draw = ->
draw_cells()
draw_cues()
love.graphics.setColor(1, 1, 1)
knight\set_pos(math.floor(cnt / 10), cnt_y)
cnt += 1
if cnt == columns * 10
cnt = 0
cnt_y += 1
cnt_y %= rows
draw_piece(knight)
| 26.922222 | 83 | 0.634338 |
ad0103c1015b23931fa9564c620e397e6c6eb219 | 748 | --- Class that represents a mine (i.e. activating it will make the player loose)
-- @classmod Mine
Tile = require script.Parent\WaitForChild "Tile"
-- A mine is a Tile, but with different 'Reveal' and 'ToggleFlag' methods
class Mine extends Tile
-- Note that there's no 'new' method in this class. But since there's one in our parent class
-- Tile, that one will be called.
--- Reveal the mine, ending the game
Reveal: =>
@Label.Text = "X"
@Part.BrickColor = BrickColor.new "Bright red"
@Board\EndGame!
--- Toggle the flag on this mine
ToggleFlag: =>
super! -- This will call Tile.ToggleFlag
if @Flagged then @Board.CorrectlyFlaggedMines += 1
else @Board.CorrectlyFlaggedMines -= 1
@Board\CheckVictory!
| 31.166667 | 95 | 0.69385 |
eb020fbb76a885f4900a6f7f04b64774d5b53b3b | 9,613 | -- Copyright 2012-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
GFile = require 'ljglibs.gio.file'
GFileInfo = require 'ljglibs.gio.file_info'
glib = require 'ljglibs.glib'
{:park, :resume, :resume_with_error, :wait} = howl.dispatch
import PropertyObject from howl.util.moon
append = table.insert
file_types = {
[tonumber GFileInfo.TYPE_DIRECTORY]: 'directory',
[tonumber GFileInfo.TYPE_SYMBOLIC_LINK]: 'symlink',
[tonumber GFileInfo.TYPE_SPECIAL]: 'special',
[tonumber GFileInfo.TYPE_REGULAR]: 'regular',
[tonumber GFileInfo.TYPE_MOUNTABLE]: 'mountable',
[tonumber GFileInfo.TYPE_UNKNOWN]: 'unknown',
}
class File extends PropertyObject
TYPE_DIRECTORY: GFileInfo.TYPE_DIRECTORY
TYPE_SYMBOLIC_LINK: GFileInfo.TYPE_SYMBOLIC_LINK
TYPE_SPECIAL: GFileInfo.TYPE_SPECIAL
TYPE_REGULAR: GFileInfo.TYPE_REGULAR
TYPE_MOUNTABLE: GFileInfo.TYPE_MOUNTABLE
TYPE_UNKNOWN: GFileInfo.TYPE_UNKNOWN
@async: false
tmpfile: ->
file = File assert os.tmpname!
file.touch if not file.exists
file
tmpdir: ->
with File os.tmpname!
\delete! if .exists
\mkdir!
with_tmpfile: (f) ->
file = File.tmpfile!
result = { pcall f, file }
file\delete_all! if file.exists
if result[1]
table.unpack result, 2
else
error result[2]
is_absolute: (path) ->
(path\match('^/') or path\match('^%a:\\\\')) != nil
expand_path: (path) ->
expanded_home = File.home_dir.path .. File.separator
res = path\gsub ".+#{File.separator}~#{File.separator}", expanded_home
res\gsub "^~#{File.separator}", expanded_home
separator: jit.os == 'Windows' and '\\' or '/'
new: (target, cwd, opts) =>
error "missing parameter #1 for File()", 3 unless target
t = typeof target
if t == 'File'
@gfile = target.gfile
@path = target.path
else
if t == 'string'
if cwd and not self.is_absolute target
target = GFile(tostring cwd)\get_child(target).path
@gfile = GFile tostring target
else
@gfile = target
@path = @gfile.path
if opts
@_ft = opts.type
super!
@property basename: get: => @gfile.basename
@property display_name: get: =>
base = @basename
@is_directory and "#{base}#{File.separator}" or base
@property extension: get: => @basename\match('%.([^.]+)$')
@property uri: get: => @gfile.uri
@property is_directory: get: => @_has_file_type GFileInfo.TYPE_DIRECTORY
@property is_link: get: => @_has_file_type GFileInfo.TYPE_SYMBOLIC_LINK
@property is_special: get: => @_has_file_type GFileInfo.TYPE_SPECIAL
@property is_regular: get: => @_has_file_type GFileInfo.TYPE_REGULAR
@property is_mountable: get: => @_has_file_type GFileInfo.TYPE_MOUNTABLE
@property is_hidden: get: => @exists and @_info!.is_hidden
@property is_backup: get: => @exists and @_info!.is_backup
@property size: get: => @_info!.size
@property exists: get: => @gfile.exists
@property readable: get: => @exists and @_info('access')\get_attribute_boolean 'access::can-read'
@property etag: get: => @exists and @_info('etag').etag
@property modified_at: get: => @exists and @_info('time')\get_attribute_uint64 'time::modified'
@property short_path: get: =>
return "~" if @path == File.home_dir.path
@path\gsub "^#{File.home_dir.path}#{File.separator}", '~/'
@property root_dir:
get: =>
file = @
while file.parent
file = file.parent
return file
@property writeable: get: =>
if @exists
return @_info('access')\get_attribute_boolean 'access::can-write'
else
return @parent.exists and @parent.writeable
@property file_type: get: => file_types[tonumber @_file_type]
@property contents:
get: => @gfile\load_contents!
set: (contents) =>
with @_assert io.open @path, 'wb'
\write tostring contents
\close!
@property parent:
get: =>
parent = @gfile.parent
return if parent then File(parent) else nil
@property children:
get: =>
File.async and @children_async or @children_sync
@property children_sync:
get: =>
files = {}
enum = @gfile\enumerate_children 'standard::name,standard::type', GFile.QUERY_INFO_NONE
while true
info = enum\next_file!
unless info
enum\close!
return files
append files, File(enum\get_child(info), nil, type: info.filetype)
@property children_async:
get: =>
handle = park 'enumerate-children-async'
@gfile\enumerate_children_async 'standard::name,standard::type', nil, nil, (status, ret, err_code) ->
if status
resume handle, ret
else
resume_with_error handle, "#{ret} (#{err_code})"
enum = wait handle
files = {}
while true
info = enum\next_file!
unless info
enum\close!
return files
append files, File(enum\get_child(info), nil, type: info.filetype)
open: (mode = 'r', func) =>
fh = assert io.open @path, mode
if func
ret = table.pack pcall func, fh
fh\close!
error ret[2] unless ret[1]
return table.unpack ret, 2, ret.n
fh
read: (...) =>
args = {...}
@open 'r', (fh) -> fh\read table.unpack args
join: (...) =>
root = @gfile
root = root\get_child(tostring child) for child in *{...}
File root
relative_to_parent: (parent) =>
parent.gfile\get_relative_path @gfile
is_below: (dir) => @relative_to_parent(dir) != nil
mkdir: => @gfile\make_directory!
mkdir_p: => @gfile\make_directory_with_parents!
delete: => @gfile\delete!
delete_all: =>
if @is_directory
entries = @find!
entry\delete! for entry in *entries when not entry.is_directory
directories = [f for f in *entries when f.is_directory]
table.sort directories, (a,b) -> a.path > b.path
dir\delete! for dir in *directories
@delete!
touch: => @contents = '' if not @exists
find: (options = {}) =>
error "Can't invoke find on a non-directory", 1 if not @is_directory
filters = {}
if options.filter then append filters, options.filter
filter = (entry) -> for f in *filters do return true if f entry
files = {}
directories = {}
dir = self
on_enter = options.on_enter
while dir
if on_enter and 'break' == on_enter(dir, files)
return files, true
ok, children = pcall -> dir.children
unless ok
dir = table.remove directories
append(files, dir) if dir
continue
if options.sort then table.sort children, (a,b) -> a.basename < b.basename
for entry in *children
continue if filter entry
if entry.is_directory
append directories, 1, entry
else
append files, entry
dir = table.remove directories
append(files, dir) if dir
files, false
find_paths: (opts = {}) =>
separator = File.separator
exclude_directories = opts.exclude_directories
exclude_non_directories = opts.exclude_non_directories
get_children = if File.async then
(dir) ->
handle = park 'enumerate-children-async'
dir\enumerate_children_async 'standard::name,standard::type', nil, nil, (status, ret, err_code) ->
if status
resume handle, ret
else
resume handle, nil
wait handle
else
(dir) ->
dir\enumerate_children 'standard::name,standard::type', GFile.QUERY_INFO_NONE
filter = opts.filter
on_enter = opts.on_enter
scan_dir = (dir, base, list = {}) ->
enum = get_children dir
return unless enum
while true
info = enum\next_file!
unless info
enum\close!
break
if info.filetype == GFileInfo.TYPE_DIRECTORY
f = enum\get_child info
path = "#{base}#{info.name}#{separator}"
continue if filter and filter(path)
if on_enter and 'break' == on_enter(path, list)
return true
append list, path unless exclude_directories
scan_dir f, path, list
else
path = "#{base}#{info.name}"
continue if filter and filter(path)
append list, path unless exclude_non_directories
error "Can't invoke find on a non-directory", 1 if not @is_directory
paths = {}
if on_enter and 'break' == on_enter(".#{separator}", paths)
return paths, true
partial = scan_dir GFile(@path), '', paths
paths, partial
copy: (dest, flags) =>
@gfile\copy File(dest).gfile, flags, nil, nil
tostring: => tostring @path or @uri
_info: (namespace = 'standard') =>
@gfile\query_info "#{namespace}::*", GFile.QUERY_INFO_NONE
@property _file_type: get: =>
@_ft or= @_info!.filetype
@_ft
_has_file_type: (t) =>
return @_ft == t if @_ft != nil
return false unless @exists
@_ft = @_info!.filetype
@_ft == t
@meta {
__tostring: => @tostring!
__div: (op) => @join op
__concat: (op1, op2) ->
if op1.__class == File
op1\join(op2)
else
tostring(op1) .. tostring(op2)
__eq: (op1, op2) -> op1\tostring! == op2\tostring!
__lt: (op1, op2) -> op1\tostring! < op2\tostring!
__le: (op1, op2) -> op1\tostring! <= op2\tostring!
}
_assert: (...) =>
status, msg = ...
error @tostring! .. ': ' .. msg, 3 if not status
...
File.home_dir = File glib.get_home_dir!
File.__base.rm = File.delete
File.__base.unlink = File.delete
File.__base.rm_r = File.delete_all
return File
| 27.783237 | 108 | 0.62998 |
f2cb3abfd364a0dd895ba52fc3e4d818917063a7 | 349 | import lib from require "magick.wand.lib"
lib.MagickWandGenesis!
import Image from require "magick.wand.image"
import make_thumb from require "magick.thumb"
load_image = Image\load
{
VERSION: require "magick.version"
mode: "image_magick"
:Image
:load_image
thumb: make_thumb load_image
load_image_from_blob: Image\load_from_blob
}
| 17.45 | 45 | 0.770774 |
c961ad4f4050c15fc164b4e33899497b7683f0a9 | 780 | concat = table.concat
pattern_escapes = {
"(": "%(",
")": "%)",
".": "%.",
"%": "%%",
"+": "%+",
"-": "%-",
"*": "%*",
"?": "%?",
"[": "%[",
"]": "%]",
"^": "%^",
"$": "%$",
"\0": "%z"
}
escape_pattern = (str) -> str\gsub(".", pattern_escapes)
export *
trim = (str) ->
t = str\match "^%s*()"
t > #str and "" or str\match(".*%S", t)
string.split = (str, delim) ->
return {} if str == ""
str ..= delim
delim = escape_pattern(delim)
[m for m in str\gmatch("(.-)"..delim)]
string.trim = (str) ->
stripped = {}
lines = str\split "\n"
for line in *lines
trimmed = trim line
empty = trimmed\match "^%s*$"
unless empty
stripped[#stripped + 1] = trimmed
concat stripped, " "
tr = (s) -> s\trim!
moon = require 'moon'
| 16.956522 | 56 | 0.451282 |
98c4f5a48ed9f3624d0528316e4920982a95dc58 | 14,952 |
module "moonscript.transform", package.seeall
types = require "moonscript.types"
util = require "moonscript.util"
data = require "moonscript.data"
import reversed from util
import ntype, build, smart_node, is_slice from types
import insert from table
export Statement, Value, NameProxy, LocalName, Run
-- always declares as local
class LocalName
new: (@name) => self[1] = "temp_name"
get_name: => @name
class NameProxy
new: (@prefix) =>
self[1] = "temp_name"
get_name: (scope) =>
if not @name
@name = scope\free_name @prefix, true
@name
chain: (...) =>
items = {...} -- todo: fix ... propagation
items = for i in *items
if type(i) == "string"
{"dot", i}
else
i
build.chain {
base: self
unpack items
}
index: (key) =>
build.chain {
base: self, {"index", key}
}
__tostring: =>
if @name
("name<%s>")\format @name
else
("name<prefix(%s)>")\format @prefix
class Run
new: (@fn) =>
self[1] = "run"
call: (state) =>
self.fn state
-- transform the last stm is a list of stms
-- will puke on group
apply_to_last = (stms, fn) ->
-- find last (real) exp
last_exp_id = 0
for i = #stms, 1, -1
stm = stms[i]
if stm and util.moon.type(stm) != Run
last_exp_id = i
break
return for i, stm in ipairs stms
if i == last_exp_id
fn stm
else
stm
-- is a body a sindle expression/statement
is_singular = (body) ->
return false if #body != 1
if "group" == ntype body
is_singular body[2]
else
true
constructor_name = "new"
class Transformer
new: (@transformers, @scope) =>
@seen_nodes = {}
transform: (scope, node, ...) =>
-- print scope, node, ...
return node if @seen_nodes[node]
@seen_nodes[node] = true
while true
transformer = @transformers[ntype node]
res = if transformer
transformer(scope, node, ...) or node
else
node
return node if res == node
node = res
__call: (node, ...) =>
@transform @scope, node, ...
instance: (scope) =>
Transformer @transformers, scope
can_transform: (node) =>
@transformers[ntype node] != nil
construct_comprehension = (inner, clauses) ->
current_stms = inner
for _, clause in reversed clauses
t = clause[1]
current_stms = if t == "for"
_, names, iter = unpack clause
{"foreach", names, iter, current_stms}
elseif t == "when"
_, cond = unpack clause
{"if", cond, current_stms}
else
error "Unknown comprehension clause: "..t
current_stms = {current_stms}
current_stms[1]
Statement = Transformer {
assign: (node) =>
_, names, values = unpack node
-- bubble cascading assigns
if #values == 1 and types.cascading[ntype values[1]]
values[1] = @transform.statement values[1], (stm) ->
t = ntype stm
if types.is_value stm
{"assign", names, {stm}}
else
stm
build.group {
{"declare", names}
values[1]
}
else
node
export: (node) =>
-- assign values if they are included
if #node > 2
if node[2] == "class"
cls = smart_node node[3]
build.group {
{"export", {cls.name}}
cls
}
else
build.group {
node
build.assign {
names: node[2]
values: node[3]
}
}
else
nil
update: (node) =>
_, name, op, exp = unpack node
op_final = op\match "^(.+)=$"
error "Unknown op: "..op if not op_final
build.assign_one name, {"exp", name, op_final, exp}
import: (node) =>
_, names, source = unpack node
stubs = for name in *names
if type(name) == "table"
name
else
{"dot", name}
real_names = for name in *names
type(name) == "table" and name[2] or name
if type(source) == "string"
build.assign {
names: real_names
values: [build.chain { base: source, stub} for stub in *stubs]
}
else
source_name = NameProxy "table"
build.group {
{"declare", real_names}
build["do"] {
build.assign_one source_name, source
build.assign {
names: real_names
values: [build.chain { base: source_name, stub} for stub in *stubs]
}
}
}
comprehension: (node, action) =>
_, exp, clauses = unpack node
action = action or (exp) -> {exp}
construct_comprehension action(exp), clauses
-- handle cascading return decorator
if: (node, ret) =>
if ret
smart_node node
-- mutate all the bodies
node['then'] = apply_to_last node['then'], ret
for i = 4, #node
case = node[i]
body_idx = #node[i]
case[body_idx] = apply_to_last case[body_idx], ret
node
with: (node, ret) =>
_, exp, block = unpack node
scope_name = NameProxy "with"
build["do"] {
build.assign_one scope_name, exp
Run => @set "scope_var", scope_name
build.group block
if ret
ret scope_name
}
foreach: (node) =>
smart_node node
if ntype(node.iter) == "unpack"
list = node.iter[2]
index_name = NameProxy "index"
list_name = NameProxy "list"
slice_var = nil
bounds = if is_slice list
slice = list[#list]
table.remove list
table.remove slice, 1
slice[2] = if slice[2] and slice[2] != ""
max_tmp_name = NameProxy "max"
slice_var = build.assign_one max_tmp_name, slice[2]
{"exp", max_tmp_name, "<", 0
"and", {"length", list_name}, "+", max_tmp_name
"or", max_tmp_name }
else
{"length", list_name}
slice
else
{1, {"length", list_name}}
build.group {
build.assign_one list_name, list
slice_var
build["for"] {
name: index_name
bounds: bounds
body: {
{"assign", node.names, {list_name\index index_name}}
build.group node.body
}
}
}
switch: (node, ret) =>
_, exp, conds = unpack node
exp_name = NameProxy "exp"
-- convert switch conds into if statment conds
convert_cond = (cond) ->
t, case_exp, body = unpack cond
out = {}
insert out, t == "case" and "elseif" or "else"
if t != "else"
insert out, {"exp", case_exp, "==", exp_name} if t != "else"
else
body = case_exp
if ret
body = apply_to_last body, ret
insert out, body
out
first = true
if_stm = {"if"}
for cond in *conds
if_cond = convert_cond cond
if first
first = false
insert if_stm, if_cond[2]
insert if_stm, if_cond[3]
else
insert if_stm, if_cond
build.group {
build.assign_one exp_name, exp
if_stm
}
class: (node) =>
_, name, parent_val, body = unpack node
-- split apart properties and statements
statements = {}
properties = {}
for item in *body
switch item[1]
when "stm"
insert statements, item[2]
when "props"
for tuple in *item[2,]
if ntype(tuple[1]) == "self"
insert statements, build.assign_one unpack tuple
else
insert properties, tuple
-- find constructor
constructor = nil
properties = for tuple in *properties
if tuple[1] == constructor_name
constructor = tuple[2]
nil
else
tuple
parent_cls_name = NameProxy "parent"
base_name = NameProxy "base"
self_name = NameProxy "self"
cls_name = NameProxy "class"
if not constructor
constructor = build.fndef {
args: {{"..."}}
arrow: "fat"
body: {
build["if"] {
cond: parent_cls_name
then: {
build.chain { base: "super", {"call", {"..."}} }
}
}
}
}
else
smart_node constructor
constructor.arrow = "fat"
cls = build.table {
{"__init", constructor}
{"__base", base_name}
{"__name", {"string", '"', name}} -- "quote the string"
{"__parent", parent_cls_name}
}
-- look up a name in the class object
class_lookup = build["if"] {
cond: {"exp", "val", "==", "nil", "and", parent_cls_name}
then: {
parent_cls_name\index"name"
}
}
insert class_lookup, {"else", {"val"}}
cls_mt = build.table {
{"__index", build.fndef {
args: {{"cls"}, {"name"}}
body: {
build.assign_one LocalName"val", build.chain {
base: "rawget", {"call", {base_name, "name"}}
}
class_lookup
}
}}
{"__call", build.fndef {
args: {{"cls"}, {"..."}}
body: {
build.assign_one self_name, build.chain {
base: "setmetatable"
{"call", {"{}", base_name}}
}
build.chain {
base: "cls.__init"
{"call", {self_name, "..."}}
}
self_name
}
}}
}
cls = build.chain {
base: "setmetatable"
{"call", {cls, cls_mt}}
}
value = nil
with build
value = .block_exp {
Run =>
@set "super", (block, chain) ->
if chain
slice = [item for item in *chain[3,]]
new_chain = {"chain", parent_cls_name}
head = slice[1]
if head == nil
return parent_cls_name
switch head[1]
-- calling super, inject calling name and self into chain
when "call"
calling_name = block\get"current_block"
slice[1] = {"call", {"self", unpack head[2]}}
act = if ntype(calling_name) != "value" then "index" else "dot"
insert new_chain, {act, calling_name}
-- colon call on super, replace class with self as first arg
when "colon"
call = head[3]
insert new_chain, {"dot", head[2]}
slice[1] = { "call", { "self", unpack call[2] } }
insert new_chain, item for item in *slice
new_chain
else
parent_cls_name
.assign_one parent_cls_name, parent_val == "" and "nil" or parent_val
.assign_one base_name, {"table", properties}
.assign_one base_name\chain"__index", base_name
build["if"] {
cond: parent_cls_name
then: {
.chain {
base: "setmetatable"
{"call", {
base_name,
.chain { base: parent_cls_name, {"dot", "__base"}}
}}
}
}
}
.assign_one cls_name, cls
.assign_one base_name\chain"__class", cls_name
.group if #statements > 0 {
.assign_one LocalName"self", cls_name
.group statements
} else {}
cls_name
}
value = .group {
.declare names: {name}
.assign {
names: {name}
values: {value}
}
}
value
}
class Accumulator
body_idx: { for: 4, while: 3, foreach: 4 }
new: =>
@accum_name = NameProxy "accum"
@value_name = NameProxy "value"
@len_name = NameProxy "len"
-- wraps node and mutates body
convert: (node) =>
index = @body_idx[ntype node]
node[index] = @mutate_body node[index]
@wrap node
-- wrap the node into a block_exp
wrap: (node) =>
build.block_exp {
build.assign_one @accum_name, build.table!
build.assign_one @len_name, 0
node
@accum_name
}
-- mutates the body of a loop construct to save last value into accumulator
-- can optionally skip nil results
mutate_body: (body, skip_nil=true) =>
val = if not skip_nil and is_singular body
with body[1]
body = {}
else
body = apply_to_last body, (n) ->
build.assign_one @value_name, n
@value_name
update = {
{"update", @len_name, "+=", 1}
build.assign_one @accum_name\index(@len_name), val
}
if skip_nil
table.insert body, build["if"] {
cond: {"exp", @value_name, "!=", "nil"}
then: update
}
else
table.insert body, build.group update
body
default_accumulator = (node) =>
Accumulator!\convert node
implicitly_return = (scope) ->
is_top = true
fn = (stm) ->
t = ntype stm
if types.manual_return[t] or not types.is_value stm
-- remove blank return statement
if is_top and t == "return" and stm[2] == ""
nil
else
stm
elseif types.cascading[t]
is_top = false
scope.transform.statement stm, fn
else
if t == "comprehension" and not types.comprehension_has_value stm
stm
else
{"return", stm}
fn
Value = Transformer {
for: default_accumulator
while: default_accumulator
foreach: default_accumulator
comprehension: (node) =>
a = Accumulator!
node = @transform.statement node, (exp) ->
a\mutate_body {exp}, false
a\wrap node
tblcomprehension: (node) =>
_, key_exp, value_exp, clauses = unpack node
accum = NameProxy "tbl"
dest = build.chain { base: accum, {"index", key_exp} }
inner = build.assign_one dest, value_exp
build.block_exp {
build.assign_one accum, build.table!
construct_comprehension {inner}, clauses
accum
}
fndef: (node) =>
smart_node node
node.body = apply_to_last node.body, implicitly_return self
node
if: (node) => build.block_exp { node }
with: (node) => build.block_exp { node }
switch: (node) =>
build.block_exp { node }
-- pull out colon chain
chain: (node) =>
stub = node[#node]
if type(stub) == "table" and stub[1] == "colon_stub"
table.remove node, #node
base_name = NameProxy "base"
fn_name = NameProxy "fn"
is_super = node[2] == "super"
@transform.value build.block_exp {
build.assign {
names: {base_name}
values: {node}
}
build.assign {
names: {fn_name}
values: {
build.chain { base: base_name, {"dot", stub[2]} }
}
}
build.fndef {
args: {{"..."}}
body: {
build.chain {
base: fn_name, {"call", {is_super and "self" or base_name, "..."}}
}
}
}
}
block_exp: (node) =>
_, body = unpack node
fn = nil
arg_list = {}
insert body, Run =>
if @has_varargs
insert arg_list, "..."
insert fn.args, {"..."}
fn = smart_node build.fndef body: body
build.chain { base: {"parens", fn}, {"call", arg_list} }
}
| 23.620853 | 81 | 0.536918 |
97213e92e59ea5333f68d60727b0aee376c42f99 | 5,393 | -- Copyright 2015-2016 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
Gtk = require 'ljglibs.gtk'
gobject_signal = require 'ljglibs.gobject.signal'
Background = require 'ljglibs.aux.background'
ffi = require 'ffi'
{:signal} = howl
{:theme} = howl.ui
{:PropertyObject} = howl.util.moon
append = table.insert
ffi_cast = ffi.cast
{:max} = math
allocations_differ = (a1, a2) ->
a1.x != a2.x or a1.y != a2.y or a1.width != a2.width or a1.height != a2.height
get_bg_conf = (theme_conf = {}, additional) ->
bg_conf = {}
if theme_conf.background
for k, v in pairs theme_conf.background
bg_conf[k] = v
for k, v in pairs theme_conf
bg_conf[k] = v if k\match '^border'
if additional
for k, v in pairs additional
bg_conf[k] = v
bg_conf
class ContentBox extends PropertyObject
new: (@name, @content_widget, opts = {})=>
@opts = opts
@_handlers = {}
@main = background: Background "#{name}_bg", 0, 0
if opts.header
@header = @_create_bar opts.header, opts.header_background, @main, "header"
if opts.footer
@footer = @_create_bar opts.footer, opts.footer_background, @main, "footer"
main_widget = Gtk.Box Gtk.ORIENTATION_VERTICAL
if @header
main_widget\pack_start @header.widget, false, false, 0
main_widget\pack_start content_widget, true, true, 0
if @footer
main_widget\pack_start @footer.widget, false, false, 0
@main.widget = main_widget
@e_box = Gtk.EventBox {
hexpand: true,
vexpand: false,
main_widget
}
@e_box.app_paintable = true
@e_box.visible_window = false
append @_handlers, @e_box\on_size_allocate self\_on_size_allocate
append @_handlers, @e_box\on_destroy self\_on_destroy
append @_handlers, @e_box\on_draw self\_draw
@_theme_changed = self\_on_theme_changed
signal.connect 'theme-changed', @_theme_changed
@_on_theme_changed theme: theme.current
to_gobject: => @e_box
_prepare_background: (bg, cr) =>
if @header and @header.background and @header.widget.visible
cr\save!
@header.background\draw cr, preserve: true
cr\restore!
if @footer and @footer.background and @footer.widget.visible
cr\save!
cr\translate 0, bg.height - @footer.background.height - bg.padding_bottom - bg.padding_top
@footer.background\draw cr, preserve: true
cr\restore!
_draw: (_, cr) =>
cr\save!
clip = cr.clip_extents
bg = @main.background
bg\draw cr, should_clip: true, :clip
cr\translate bg.padding_left, bg.padding_top
gobject_signal.emit_by_name @main.widget, 'draw', cr
cr\restore!
true
_on_theme_changed: (opts) =>
def = opts.theme[@name] or opts.theme.content_box or {}
bg_conf = get_bg_conf def, prepare: self\_prepare_background
main_bg = @main.background
main_bg\reconfigure bg_conf
with @main.widget
.margin_top = main_bg.padding_top
.margin_right = main_bg.padding_right
.margin_bottom = main_bg.padding_bottom
.margin_left = main_bg.padding_left
corner_padding = main_bg.border_radius
reconfigure_bar = (bar) ->
bg = bar.background
bar_conf = def[bar.name] or {}
bar_bg_conf = get_bg_conf bar_conf
bg\reconfigure bar_bg_conf
bar_padding = bar_conf.padding or 0
with bar.widget
.margin_top = bg.padding_top + max(bar_conf.padding_top or 0, bar_padding)
.margin_right = max(bg.padding_right, corner_padding, main_bg.padding_right) + max(bar_conf.padding_right or 0, bar_padding)
.margin_bottom = bg.padding_bottom + max(bar_conf.padding_bottom or 0, bar_padding)
.margin_left = max(bg.padding_left, corner_padding, main_bg.padding_left) + max(bar_conf.padding_left or 0, bar_padding)
reconfigure_bar @header if @header
reconfigure_bar @footer if @footer
_on_destroy: =>
-- disconnect signal handlers
for h in *@_handlers
gobject_signal.disconnect h
signal.disconnect 'theme-changed', @_theme_changed
_create_bar: (widget, background_configuration, parent, name) =>
bg = Background "#{@name}_#{name}", 0, 0
bar = :name, :widget, background: bg
append @_handlers, bar.widget\on_size_allocate self\_on_bar_size_allocate, bar
bar
_on_size_allocate: (_, allocation) =>
allocation = ffi_cast('GdkRectangle *', allocation)
@_height = allocation.height
return if @_allocation and not allocations_differ(@_allocation, allocation)
with allocation
@_allocation = x: .x, y: .y, width: .width, height: .height
@main.background\resize allocation.width, allocation.height
w_adjustment = @main.background.padding_left + @main.background.padding_right
if @header and @header.background
@header.background\resize allocation.width - w_adjustment, nil
if @footer and @footer.background
@footer.background\resize allocation.width - w_adjustment, nil
_on_bar_size_allocate: (_, allocation, bar) =>
allocation = ffi_cast('GdkRectangle *', allocation)
-- return if bar.allocation and not allocations_differ(bar.allocation, allocation)
w = bar.widget
height_adjust = w.margin_top + w.margin_bottom
bar.background\resize nil, allocation.height + height_adjust
with allocation
bar.allocation = x: .x, y: .y, width: .width, height: .height
| 31.723529 | 132 | 0.697015 |
10413dd866e00ae702601b80506dcb3765805451 | 1,148 | import config, mode from howl
with config
.define
name: 'clang_completion'
description: 'Whether or not to use Clang for C/C++ completion'
default: false
type_of: 'boolean'
.define
name: 'clang_diagnostics'
description: 'Whether or not to show diagnostic messages when running Clang'
default: false
type_of: 'boolean'
.define
name: 'clang_arguments'
description: 'A list of arguments to pass to Clang'
default: {}
type_of: 'string_list'
.define
name: 'clang_placeholders'
description: 'Whether or not to insert placeholder text after a Clang completion'
default: true
type_of: 'boolean'
.define
name: 'clang_ignored_extensions'
description: 'File extensions that should be ignored, even if they use the C mode'
default: {'l', 'y', 'dasc'}
type_of: 'string_list'
completer = bundle_load 'clang_completer'
c = mode.by_name 'c'
c.completers = { completer, 'in_buffer' }
c.on_completion_accepted = (completion, context) =>
@completer or= completer!
@completer\finish_completion completion, context
{
info: bundle_load('aisu').meta
unload: () ->
}
| 25.511111 | 86 | 0.695993 |
33d5bd14945fde4a2354d55fd868280ac238b3d2 | 6,589 | utils = require("utils")
bz_handle = require("bz_handle")
net = require("net")
rx = require("rx")
tiny = require("tiny")
bztiny = require("bztiny")
bzcomponents = require("bzcomp")
bzsystems = require("bzsystems")
Module = require("module")
event = require("event")
import Subject from rx
import namespace, OdfFile, getMeta, getFullName from utils
import EcsWorld, requireAny, requireAll, Component, getComponentOdfs from bztiny
import BzNetworkSystem, BzPlayerSystem, BzPositionSystem from bzsystems
import BzHandleComponent,
BzBuildingComponent,
BzVehicleComponent,
BzPlayerComponent,
BzPersonComponent,
BzRecyclerComponent,
BzFactoryComponent,
BzConstructorComponent,
BzArmoryComponent,
BzHowitzerComponent,
BzWalkerComponent,
BzConstructorComponent,
BzWingmanComponent,
BzGuntowerComponent,
BzScavengerComponent,
BzTugComponent,
BzMinelayerComponent,
BzTurretComponent
BzHangarComponent,
BzSupplydepotComponent,
BzSiloComponent,
BzCommtowerComponent,
BzPortalComponent,
BzPowerplantComponent,
BzSignComponent,
BzArtifactComponent,
BzStructureComponent,
BzAnimstructureComponent,
BzBarracksComponent,
PositionComponent,
BzLocalComponent,
BzRemoteComponent from bzcomponents
import EventDispatcher, Event from event
USE_HANDLE_COMPONENT = true
USE_PLAYER_COMPONENT = true
USE_VEHICLE_COMPONENT = true
classname_components = {
"recycler": BzRecyclerComponent,
"factory": BzFactoryComponent,
"armory": BzArmoryComponent,
"wingman": BzWingmanComponent,
"constructionrig": BzConstructorComponent,
"howitzer": BzHowitzerComponent,
"scavenger": BzScavengerComponent,
"tug": BzTugComponent,
"turret": BzGuntowerComponent,
"walker": BzWalkerComponent,
"turrettank": BzTurretComponent,
"minelayer": BzMinelayerComponent,
"repairdepot": BzHangarComponent,
"supplydepot": BzSupplydepotComponent,
"silo": BzSiloComponent,
"commtower": BzCommtowerComponent,
"portal": BzPortalComponent,
"powerplant": BzPowerplantComponent,
"sign": BzSignComponent,
"artifact": BzArtifactComponent,
"i76building": BzStructureComponent,
"i76building2": BzStructureComponent,
"animbuilding": BzAnimstructureComponent
}
misc_components = {
[BzBuildingComponent]: IsBuilding,
[BzVehicleComponent]: IsCraft,
[BzPersonComponent]: IsPerson
}
class EcsModule extends Module
new: (...) =>
super(...)
@hmap = {}
@world = EcsWorld()
@handlesToProcess = {}
@dispatcher = EventDispatcher()
@addSystem(BzPositionSystem()\createSystem())
@addSystem(BzPlayerSystem()\createSystem())
--todo: network system is broken
--if IsNetGame()
-- @world\addSystem(BzNetworkSystem()\createSystem())
getDispatcher: () =>
@dispatcher
start: () =>
super\start()
for i in AllObjects()
@_regHandle(i)
_setMiscComponents: (entity, handle) =>
className = GetClassLabel(handle)
classComponent = classname_components[className]
if classComponent
classComponent\addEntity(entity)
for miscComponent, filter in pairs(misc_components)
if filter(handle)
miscComponent\addEntity(entity)
_loadComponentsFromOdf: (entity, handle) =>
odf = GetOdf(handle)
file = OdfFile(odf)
for component, _ in pairs(getComponentOdfs())
cMeta = getMeta(component, "ecs.fromfile")
header = cMeta.header
use = file\getBool(header, header, false)
if use
comp = component\addEntity(entity)
file\getFields(header, cMeta.fields, comp)
addSystem: (system) =>
@world\addSystem(system)
system.getEntityByHandle = @\getEntityByHandle
system.registerHandle = @\_regHandle
@dispatcher\dispatch(Event("ECS_ADD_SYSTEM",@,nil, system))
-- moves components from old handle to new handle
-- should be called after new handle is created
replaceHandle: (old, new) =>
@handlesToProcess[new] = nil
eid = @getEntityId(old)
entity = @getEntity(eid)
handleComponent = BzHandleComponent\getComponent(entity)
handleComponent.handle = new
-- was not called early, remove entity that was created
if @getEntityId(new) ~= nil
neid = @getEntityId(new)
@world\removeEntity(neid)
@hmap[old] = nil
@hmap[new] = eid
RemoveObject(old)
_regHandle: (handle) =>
@handlesToProcess[handle] = nil
if not @hmap[handle]
eid, e = @world\createEntity()
c1 = BzHandleComponent\addEntity(e)
c1.handle = handle
c2 = PositionComponent\addEntity(e)
c2.position = GetPosition(handle)
if IsNetGame()
if IsLocal(handle)
BzLocalComponent\addEntity(e)
if IsRemote(handle)
BzRemoteComponent\addEntity(e)
else
BzLocalComponent\addEntity(e)
@hmap[handle] = eid
@_loadComponentsFromOdf(e, handle)
@_setMiscComponents(e, handle)
@dispatcher\dispatch(Event("ECS_REG_HANDLE",@,nil,handle, eid, e))
_unregHandle: (handle) =>
eid = @hmap[handle]
if eid
entity = @world\getTinyEntity(eid)
if entity
handleComponent = BzHandleComponent\getComponent(entity)
if handleComponent and handleComponent.removeOnDeath then
@world\removeEntity(eid)
@dispatcher\dispatch(Event("ECS_UNREG_HANDLE",@,nil,handle, eid, entity))
@hmap[handle] = nil
getWorld: () =>
@world
update: (dtime) =>
super\update(dtime)
for i, v in pairs(@handlesToProcess)
@_regHandle(i)
@handlesToProcess[i] = nil
@world\update(dtime)
@world\refresh()
createObject: (handle) =>
@handlesToProcess[handle] = true
addObject: (handle) =>
super\addObject(handle)
@handlesToProcess[handle] = true
deleteObject: (handle) =>
super\deleteObject(handle)
@_unregHandle(handle)
getEntityByHandle: (handle) =>
id = @getEntityId(handle)
if id ~= nil
return @getEntity(id)
getEntityId: (handle) =>
return @hmap[handle]
getEntity: (id) =>
return @world\getTinyEntity(id)
save: () =>
data = {
ecs: @world\save(),
handles: @hmap
}
return data
load: (data) =>
@world\load(data.ecs)
@hmap = data.handles
namespace("core.ecs", EcsModule)
return {
EntityComponentSystemModule: EcsModule
}
| 25.440154 | 82 | 0.667021 |
658d8867319887ba6d9fc994670fa31540bb6428 | 2,872 |
lua = { :debug, :type }
import getfenv, setfenv, dump from require "moonscript.util"
local *
p = (...) ->
print dump ...
is_object = (value) -> -- is a moonscript object
lua.type(value) == "table" and value.__class
type = (value) -> -- class aware type
base_type = lua.type value
if base_type == "table"
cls = value.__class
return cls if cls
base_type
debug = setmetatable {
upvalue: (fn, k, v) ->
upvalues = {}
i = 1
while true
name = lua.debug.getupvalue(fn, i)
break if name == nil
upvalues[name] = i
i += 1
if not upvalues[k]
error "Failed to find upvalue: " .. tostring k
if not v
_, value = lua.debug.getupvalue fn, upvalues[k]
value
else
lua.debug.setupvalue fn, upvalues[k], v
}, __index: lua.debug
-- run a function with scope injected before its function environment
run_with_scope = (fn, scope, ...) ->
old_env = getfenv fn
env = setmetatable {}, {
__index: (name) =>
val = scope[name]
if val != nil
val
else
old_env[name]
}
setfenv fn, env
fn ...
-- wrap obj such that calls to methods do not need a reference to self
bind_methods = (obj) ->
setmetatable {}, {
__index: (name) =>
val = obj[name]
if val and lua.type(val) == "function"
bound = (...) -> val obj, ...
self[name] = bound
bound
else
val
}
-- use a function to provide default values to table
-- optionally specify a starting table
-- fibanocci table:
-- t = defaultbl {[0]: 0, [1]: 1}, (i) -> self[i - 1] + self[i - 2]
defaultbl = (t, fn) ->
if not fn
fn = t
t = {}
setmetatable t, {
__index: (name) =>
val = fn self, name
rawset self, name, val
val
}
-- chain together tables by __index metatables
extend = (...) ->
tbls = {...}
return if #tbls < 2
for i = 1, #tbls - 1
a = tbls[i]
b = tbls[i + 1]
setmetatable a, __index: b
tbls[1]
-- shallow copy
copy = =>
{key,val for key,val in pairs self}
-- mixin class properties into self, call new
mixin = (cls, ...) =>
for key, val in pairs cls.__base
self[key] = val if not key\match"^__"
cls.__init self, ...
-- mixin methods from an object into self
mixin_object = (object, methods) =>
for name in *methods
self[name] = (parent, ...) ->
object[name](object, ...)
-- mixin table values into self
mixin_table = (tbl, keys) =>
if keys
for key in *keys
self[key] = tbl[key]
else
for key, val in pairs tbl
self[key] = val
fold = (items, fn)->
len = #items
if len > 1
accum = fn items[1], items[2]
for i=3,len
accum = fn accum, items[i]
accum
else
items[1]
{
:dump, :p, :is_object, :type, :debug, :run_with_scope, :bind_methods,
:defaultbl, :extend, :copy, :mixin, :mixin_object, :mixin_table, :fold
}
| 21.432836 | 72 | 0.578691 |
0ff8f64dd0505dc5341331b53feb5057b2d6de13 | 712 | import drop_column, create_table, types, add_column from require "lapis.db.schema"
{
user_management_000001: =>
create_table "lazuli_modules_user_management_users", {
{"id", types.serial}
{"username", types.varchar}
{"pwHMACs1", types.varchar}
"PRIMARY KEY (id)"
}
user_management_yubicloud_000001: =>
create_table "lazuli_modules_user_management_yubicloud", {
{"id", types.serial}
{"user_id", types.integer}
{"idstr", types.varchar}
"PRIMARY KEY (id)"
}
user_management_000002: =>
drop_column "lazuli_modules_user_management_users", "pwHMACs1"
add_column "lazuli_modules_user_management_users", "pwHash", types.varchar null: true
}
| 32.363636 | 89 | 0.698034 |
041ca53c6d68eca11b1dc5edc17fd98ee891aba9 | 5,864 | -- typekit.type.data
-- Datatypes for typekit
-- By daelvn
-- This is in fact the third implementation of this concept.
-- The others were overengineered and certainly too complex.
-- Notes:
-- data Maybe a = Nothing | Just a
-- # Translates to #
-- Type "Maybe a", -- this shows up in signatures
-- Nothing: ""
-- Just: "a"
-- # Object structure #
-- Maybe {a} -- Just a
-- Maybe { } -- Nothing
--
-- data Person = Person {
-- name :: String
-- age :: Int
-- }
-- # Translates to #
-- Type "Person",
-- Person:
-- ""
-- name: "String"
-- age: "Int"
-- # Constructors #
-- Person :: String -> Int -> Person
-- name :: Person -> Int
-- age :: Person -> String
-- # Application #
-- Person "Dael" 16
-- Person R{ name: "Dael", age: 16 }
--
-- data State s a = State { runState :: s -> (s, a) }
-- # Translates to #
-- Type "State s' a'",
-- State: ""
-- runState: "s' -> Pair s' a'"
-- # Object structure #
-- State {s', a'}
-- runState :: s' -> Pair s' a'
import DEBUG from require "typekit.config"
import inspect, log from (require "typekit.debug") DEBUG
import addReference from require "typekit.global"
import Type, typeof from require "typekit.type"
import typeError from require "typekit.type.error"
import sign from require "typekit.sign"
import curry,
metatype,
metakind,
metaparent,
getPair,
isLower,
isUpper from require "typekit.commons"
--unpack or= table.unpack
-- Parses an annotation
-- Annotations are like "signatures" for types themselves
-- ex. "Either a b", "Maybe a"
parseAnnotation = (ann) -> [word for word in ann\gmatch "%S+"]
-- Builds a signature from a series of types
-- {String, Number, String} -> "String -> Number -> String"
buildSignature = (name, t) -> "#{name} :: #{table.concat t, " -> "}"
-- Creates a new constructor
Constructor = (name, parent, definition) ->
this = {:definition, :parent, :name, record: {}, rorder: {}}
-- check if we have records
if "Table" == typeof definition
this.annotation = parseAnnotation definition[1]
table.remove definition, 1
for rec in *definition
-- get record information & signature
record, sig = getPair rec
recf = sign "#{record} :: #{parent.name} -> #{sig}"
-- get position & add record
lat = #this.annotation+1
this.rorder[record] = lat
this.annotation[lat] = sig
-- function & add reference
addReference record, parent.record[record]
parent.record[record] = recf (x) -> x[lat]
else
this.annotation = parseAnnotation definition
-- validate variables
for var in *this.annotation
log "type.data.Constructor #var", var
if (isLower var) and (not parent.variablel[var])
typeError "No variable '#{var}' in type annotation"
-- build signature
ann = [v for v in *this.annotation]
log "type.data.Constructor #ann", inspect ann
-- @IMPL if we take no arguments, return object directly
if #ann == 0
log "type.data.Constructor #direct", "Direct constructor -> #{this.name}"
return (metaparent parent) (metatype parent.name) (metakind this.name) setmetatable {}, __tostring: this.name
-- keep building signature
table.insert ann, parent.name
for v in *this.annotation do ann[#ann] ..= " #{v}"
log "type.data.Constructor #ann", inspect ann
this.signature = buildSignature this.name, ann
log "type.data.Constructor #sig", inspect this.signature
Ct = sign this.signature
Ctf = Ct curry ((...) ->
log "Ct #got", inspect {...}
return (metaparent parent) (metatype parent.name) (metakind this.name) setmetatable {...}, __tostring: this.name
), #this.annotation
--
return (metatype "Function") (metakind "Constructor") setmetatable this, __call: (x) => switch typeof x
when "Record"
argl = {}
for record, val in pairs x
log "type.data.Constructor #record", "Calling with record syntax, #{this.rorder[record]} is #{inspect val}"
argl[this.rorder[record]] = val
log "type.data.Constructor #record", "Arguments are #{inspect argl}"
fn = Ctf
for arg in *argl do fn = fn arg
return fn
else
return Ctf x
-- Creates a new type
_TSyn = Type
Type = (__annotation, definition) ->
-- typechecking
if "String" != typeof __annotation
typeError "Expected String as argument #1 to Type"
if "String" == typeof definition
return _TSyn __annotation, definition
elseif "Table" != typeof definition
typeError "Expected Table/String as argument #2 to Type"
--
this = {:__annotation, :definition}
-- validate name & typevars
this.annotation = parseAnnotation __annotation
unless isUpper this.annotation[1]
typeError "Type name '#{this.annotation[1]}' must begin with uppercase"
for i=2, #this.annotation do unless isLower this.annotation[i]
typeError "Type variable '#{this.annotation[i]}' must begin with lowercase"
this.name = this.annotation[1]
-- expects
this.expects = #this.annotation - 1
-- variables
this.variables = {i-1, this.annotation[i] for i=2, #this.annotation}
this.variablel = {v, k for k, v in pairs this.variables}
--
this.constructor = {}
this.record = {}
for name, def in pairs definition
if isUpper name -- constructor
this.constructor[name] = Constructor name, this, def
addReference name, this.constructor[name]
else typeError "'#{name}' must begin with uppercase character"
--
addReference this.name, this
return (metatype "Type") (metakind this.name) setmetatable this, __tostring: this.name
-- Passing record syntax to constructors
Record = (t) -> (metatype "Record") t
{
:Type, :Constructor, :Record
} | 35.113772 | 116 | 0.63148 |
a52dd594a527dec329ab8572fee10a1d17dd1174 | 2,200 | import Widget from require "lapis.html"
db = require "lapis.db"
i18n = require "i18n"
class MTASettingsProfile extends Widget
@include "widgets.utils"
category: "profile"
content: =>
div class: "card", ->
div class: "card-header", i18n "settings.profile"
div class: "card-block", ->
form method: "POST", ->
@write_csrf_input!
div class: "form-group row", ->
label class: "col-sm-2", -> abbr title: i18n("settings.privacy_note"), i18n "settings.privacy"
div class: "col-sm-10", ->
div class: "radio", -> label ->
input type: "radio", name: "settingsPrivacy", value: "1", checked: @data.privacy_mode == 1
raw " "
text i18n "settings.public"
div class: "radio", -> label ->
input type: "radio", name: "settingsPrivacy", value: "2", checked: @data.privacy_mode == 2
raw " "
text i18n "settings.following_only"
div class: "form-group row", ->
label class: "col-sm-2", i18n "users.cakeday"
div class: "col-sm-10", ->
input type: "date", class: "form-control", name: "settingsDate", value: (@data.birthday == db.NULL) and "" or @data.birthday
div class: "form-group row", ->
label class: "col-sm-2", i18n "users.gang"
div class: "col-sm-10", ->
input type: "text", class: "form-control", name: "settingsGang", maxlength: 255, value: (@data.gang == db.NULL) and "" or @data.gang
div class: "form-group row", ->
label class: "col-sm-2", i18n "users.location"
div class: "col-sm-10", ->
input type: "text", class: "form-control", name: "settingsLocation", maxlength: 255, value: (@data.location == db.NULL) and "" or @data.location
div class: "form-group row", ->
label class: "col-sm-2", i18n "users.website"
div class: "col-sm-10", ->
input type: "text", class: "form-control", name: "settingsWebsite", maxlength: 255, value: (@data.website == db.NULL) and "" or @data.website
div class: "form-group row", ->
div class: "col-sm-offset-2 col-sm-10", ->
button type: "submit", class: "btn btn-secondary", i18n "settings.update_section" | 44.897959 | 152 | 0.594091 |
c910b85fb9e150b22888e7386b3f8873263a28df | 163 | export modinfo = {
type: "command"
desc: "Rejoin the game"
alias: {"rjg"}
func: (Msg,Speaker) ->
Service("TeleportService")\Teleport(game.PlaceId, Speaker)
} | 23.285714 | 60 | 0.680982 |
03732d625c2934eedd36ceb27a860d473c94af65 | 288 | import std, perform from require 'mae'
import with_std_io, with_io_log, log from std
with_std_io ->
with_io_log ->
perform log.Info '%s', "Some info message"
perform log.Warn '%s %d', "Some warning message with a number", 5
perform log.Error "An error message with %d errors", 2
| 28.8 | 67 | 0.71875 |
6f652ef6275e00c001b9b5f5b303ba3e5131f7e9 | 2,000 | -- alfons 4.2
-- Task execution with Lua and MoonScript
-- By daelvn
import VERSION from require "alfons.version"
import style from require "ansikit.style"
fs = require "filekit"
unpack or= table.unpack
printerr = (t) -> io.stderr\write t .. "\n"
-- utils
prints = (...) -> printerr unpack [style arg for arg in *{...}]
printError = (text) -> printerr style "%{red}#{text}"
errors = (code, msg) ->
printerr style "%{red}#{msg}"
os.exit code
-- introduction
prints "%{bold blue}Alfons #{VERSION}"
-- get arguments
import getopt from require "alfons.getopt"
args = getopt {...}
-- optionally accept a custom file
FILE = do
if args.f then args.f
elseif args.file then args.file
elseif fs.exists "Alfons.lua" then "Alfons.lua"
elseif fs.exists "Alfons.moon" then "Alfons.moon"
elseif fs.exists "Alfons.tl" then "Alfons.tl"
else errors 1, "No Taskfile found."
-- Also accept a custom language
LANGUAGE = do
if FILE\match "moon$" then "moon"
elseif FILE\match "lua$" then "lua"
elseif FILE\match "tl$" then "teal"
elseif args.type then args.type
else errors 1, "Cannot resolve format for Taskfile."
printerr "Using #{FILE} (#{LANGUAGE})"
-- Load string
import readMoon, readLua, readTeal from require "alfons.file"
content, contentErr = switch LANGUAGE
when "moon" then readMoon FILE
when "lua" then readLua FILE
when "teal" then readTeal FILE
else errors 1, "Cannot resolve format '#{LANGUAGE}' for Taskfile."
unless content then errors 1, contentErr
-- Run the taskfile
import runString from require "alfons.init"
alfons, alfonsErr = runString content, nil, true, 0, {}, {}, true
unless alfons then errors 1, alfonsErr
env = alfons ...
-- run tasks, and teardown after each of them
for command in *args.commands
env.tasks[command] args[command]
(rawget env.tasks, "teardown") if rawget env.tasks, "teardown"
-- finalize
env.finalize! | 31.746032 | 73 | 0.664 |
a035e0af10e5cdf37de136ad0362bfef594cd407 | 70 | select = (list) ->
list[math.random(1, #list)]
return {:select}
| 11.666667 | 31 | 0.585714 |
35c3aae3ca6c1e0f8faf64c0e23ba75183ccf49f | 475 | export modinfo = {
type: "command"
desc: "Unparalyze player"
alias: {"Unpara"}
func: getDoPlayersFunction (v) ->
v.Character.Humanoid.Jump = false
v.Character.Humanoid.PlatformStand = false
v.Character.Humanoid.Sit = false
if v.Character\FindFirstChild("Torso")
v.Character.Torso.CFrame = CFrame.new(v.Character.Torso.Position) + Vector3.new(0,5,0)
v.Character.Torso.Velocity = Vector3.new()
Output(string.format("Unparalyzed %s",v.Name),{Colors.Green})
} | 36.538462 | 89 | 0.726316 |
e1ff1fa6b2b93fc98dac8a680df6b04086cbce4e | 490 | -- Copyright 2012-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
import interact from howl
import BufferExplorer from howl.explorers
interact.register
name: 'select_buffer'
description: ''
handler: (opts={}) ->
interact.explore
prompt: opts.prompt
text: opts.text
help: opts.help
path: {BufferExplorer -> howl.app.buffers}
editor: opts.editor
transform_result: (item) -> item.buffer
| 25.789474 | 79 | 0.697959 |
b384c8fa7e588b597653178023398911a9ed527c | 4,633 | -- Copyright 2014-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
--
-- This supports more efficient mappings of character (code points) <->
-- byte offsets for gap buffer contents, by caching offsets and thus
-- making scans shorter
ffi = require 'ffi'
bit = require 'bit'
require 'ljglibs.cdefs.glib'
tonumber, max, abs = tonumber, math.max, math.abs
C = ffi.C
band = bit.band
ffi.cdef [[
struct ao_mapping {
size_t c_offset;
size_t b_offset;
}
]]
NR_MAPPINGS = 20
IDX_LAST = NR_MAPPINGS - 1
MIN_SPAN_CHARS = 1000
MIN_SPAN_BYTES = 1500
zero_mapping = ffi.new 'struct ao_mapping'
mapping_for_char = (mappings, char_offset) ->
m = zero_mapping
idx = 0
for i = 0, IDX_LAST
idx = i
nm = mappings[i]
break if nm.c_offset == 0 or nm.c_offset > char_offset
m = nm
m
mapping_for_byte = (mappings, byte_offset) ->
m = zero_mapping
idx = 0
for i = 0, IDX_LAST
idx = i
nm = mappings[i]
break if nm.c_offset == 0 or nm.b_offset > byte_offset
m = nm
m
update_for = (mappings, char_offset, byte_offset) ->
idx = 0
for i = 0, IDX_LAST
nm = mappings[i]
return nm if nm.c_offset == char_offset -- already present
break if nm.c_offset == 0
break if nm.c_offset > char_offset
idx = i + 1
if idx == NR_MAPPINGS -- rebalancing time
idx = NR_MAPPINGS / 2
for i = idx + 1, IDX_LAST
mappings[i].c_offset = 0
m = mappings[idx]
m.c_offset = char_offset
m.b_offset = byte_offset
m
gb_char_offset = (gb, start_offset, end_offset) ->
idx = start_offset
idx += gb.gap_size if idx >= gb.gap_start
b_end = end_offset > gb.gap_start and (end_offset + gb.gap_size) or end_offset
c_offset = 0
p = gb.array
while idx < b_end
if idx >= gb.gap_start and idx < gb.gap_end
idx += gb.gap_size
idx = idx + 1
while p[idx] != 0 and band(p[idx], 0xc0) == 0x80 -- continuation byte
idx = idx + 1
c_offset += 1
c_offset
gb_byte_offset = (gb, start_offset, char_offset) ->
idx = start_offset
idx += gb.gap_size if idx >= gb.gap_start
p = gb.array
while char_offset > 0
if idx >= gb.gap_start and idx < gb.gap_end
idx += gb.gap_size
idx += 1
char_offset -= 1
while p[idx] != 0 and band(p[idx], 0xc0) == 0x80 -- continuation byte
idx += 1
delta = idx >= gb.gap_end and gb.gap_size or 0
(idx - start_offset) - delta
Offsets = {
char_offset: (gb, byte_offset) =>
m = mapping_for_byte @mappings, byte_offset
-- should we create a new mapping, closer this offset?
if (byte_offset - m.b_offset) > MIN_SPAN_BYTES and
(gb.size - byte_offset) > MIN_SPAN_BYTES
m_b_offset = byte_offset - (byte_offset % MIN_SPAN_BYTES)
-- position may be in the middle of a sequence here, so back up as needed
while m_b_offset > 0 and band(gb\get_ptr(m_b_offset, 1)[0], 0xc0) == 0x80
m_b_offset -= 1
c_offset = m.c_offset + gb_char_offset(gb, m.b_offset, m_b_offset)
m = update_for @mappings, c_offset, m_b_offset
tonumber m.c_offset + gb_char_offset(gb, m.b_offset, byte_offset)
byte_offset: (gb, char_offset) =>
m = mapping_for_char(@mappings, char_offset), char_offset
-- should we create a new mapping, closer this offset?
if char_offset - m.c_offset > MIN_SPAN_CHARS
m_c_offset = char_offset - (char_offset % MIN_SPAN_CHARS)
b_offset = m.b_offset + gb_byte_offset(gb, m.b_offset, m_c_offset - m.c_offset)
m = update_for(@mappings, m_c_offset, b_offset)
tonumber m.b_offset + gb_byte_offset(gb, m.b_offset, char_offset - m.c_offset)
adjust_for_insert: (byte_offset, bytes, characters) =>
mappings = @mappings
for i = 0, IDX_LAST
m = mappings[i]
if m.c_offset != 0 and m.b_offset > byte_offset
m.b_offset += bytes
m.c_offset += characters
adjust_for_delete: (byte_offset, bytes, characters) =>
mappings = @mappings
for i = 0, IDX_LAST
m = mappings[i]
if m.c_offset != 0 and m.b_offset > byte_offset
-- update the mapping if we can
if m.b_offset > bytes
m.b_offset -= bytes
m.c_offset -= characters
else
-- but if the result would wrap around we give up
-- and invalidate all subsequent mapping
@invalidate_from m.b_offset
break
invalidate_from: (byte_offset) =>
mappings = @mappings
for i = 0, IDX_LAST
nm = mappings[i]
nm.c_offset = 0 if nm.b_offset > byte_offset
}
-> setmetatable { mappings: ffi.new "struct ao_mapping[#{NR_MAPPINGS}]" }, __index: Offsets
| 27.577381 | 91 | 0.654651 |
e1d926cfdb2ed3cf48e301a231cde11edf7d3a73 | 2,344 | AddCSLuaFile!
Moonpanel.Canvas.Entities = {}
class Moonpanel.Canvas.Entities.BaseEntity
SetSocket: (@__socket) =>
GetSocket: => @__socket
GetCanvas: => @__socket\GetCanvas!
PostPopulatePathNodes: =>
PopulatePathNodes: =>
CleanUpPathNodes: =>
ImportData: =>
ExportData: =>
CanClick: =>
GetSocketType: => @__class.SocketType
IsBase: => @__class.__name == "BaseEntity"
class Moonpanel.Canvas.Entities.BaseIntersection extends Moonpanel.Canvas.Entities.BaseEntity
@SocketType = Moonpanel.Canvas.SocketType.Intersection
SetPathNode: (@__pathNode) =>
GetPathNode: => @__pathNode
ExportData: =>
className = @__class.__name
if className ~= "BaseIntersection"
{ Type: className }
IsBase: => @__class.__name == "BaseIntersection"
class Moonpanel.Canvas.Entities.BaseCell extends Moonpanel.Canvas.Entities.BaseEntity
@SocketType = Moonpanel.Canvas.SocketType.Cell
ExportData: =>
className = @__class.__name
if className ~= "BaseCell"
{ Type: className }
IsBase: => @__class.__name == "BaseCell"
class Moonpanel.Canvas.Entities.BasePath extends Moonpanel.Canvas.Entities.BaseEntity
@SocketType = Moonpanel.Canvas.SocketType.Path
ExportData: =>
className = @__class.__name
if className ~= "BasePath"
{ Type: className }
IsHorizontal: => @__socket\IsHorizontal!
PopulatePathNodes: =>
socket = @GetSocket!
local intA, intB
if @IsHorizontal!
intA = socket\GetLeft!
intB = socket\GetRight!
else
intA = socket\GetAbove!
intB = socket\GetBelow!
if intA and intB
nodeA = intA\GetPathNode!
nodeB = intB\GetPathNode!
table.insert nodeA.neighbors, nodeB
table.insert nodeB.neighbors, nodeA
@__link =
nodeA: nodeB
nodeB: nodeA
CleanUpPathNodes: =>
if @__link
for node, otherNode in pairs @__link
for i, neighbor in ipairs node.neighbors
if node == neighbor
table.remove node.neighbors, i
break
IsBase: => @__class.__name == "BasePath"
include "entities/sh_intersections.lua"
| 26.337079 | 93 | 0.612201 |
24c7a4397e1e86e717145f744805f357532c3ded | 425 | import readnumber, ls from require 'mon.util'
(args={}) ->
import name from args
unless name
name = (ls '/sys/class/backlight')[1]
return {} unless name
{
level:
value: ->
curr = readnumber "/sys/class/backlight/#{name}/brightness"
max = readnumber "/sys/class/backlight/#{name}/max_brightness"
math.floor curr/max*100 + .5
name: "Backlight - #{name} - Level"
min: 0
max: 100
unit: '%'
}
| 22.368421 | 66 | 0.628235 |
c9cdf61c16179fcfa84224a3169cf5b8ecaa723b | 961 | BlobWriter, BlobReader = require('BlobWriter'), require('BlobReader')
writer, reader = BlobWriter!, BlobReader('')
reader\reset(writer\table({})\tostring!)\table!
{
description: 'Blob'
serialize:
largeNumArray: (data) -> writer\clear!\array('number', data)\tostring!
largeU32Array: (data) -> writer\clear!\array('u32', data)\tostring!
smallNumArray: (data) -> writer\clear!\array('number', data)\tostring!
smallU8Array: (data) -> writer\clear!\array('u8', data)\tostring!
simpleTable: (data) -> writer\clear!\table(data)\tostring!
deepTable: (data) -> writer\clear!\table(data)\tostring!
deserialize:
largeNumArray: (data) -> reader\reset(data)\array('number')
largeU32Array: (data) -> reader\reset(data)\array('u32')
smallNumArray: (data) -> reader\reset(data)\array('number')
smallU8Array: (data) -> reader\reset(data)\array('u8')
simpleTable: (data) -> reader\reset(data)\table!
deepTable: (data) -> reader\reset(data)\table!
}
| 40.041667 | 72 | 0.695109 |
4c3492ac3a1dd88103e3caae4d9ef16231c2a259 | 522 | [[
joli-lune
small framework for love2d
MIT License (see licence file)
]]
class State
new: (game, name, options) =>
@_name = name
@game = game
@assets = game.assets
@settings = game.settings
@input = game.input
@nextState = options.next or {}
-- callbacks
onEnter: =>
onExit: =>
update: (dt) =>
draw: =>
-- end callbacks
next: (nextStateNum=1, ...) =>
if #@nextState == 0
print "Warning, no next state specified from", @_name
return
@game\stateActivation @nextState[1], ...
return State | 16.83871 | 56 | 0.639847 |
a7729757dd6688337c93d622f1af89a0d04f0a44 | 2,727 | class CropPage extends Page
new: (callback, region) =>
@pointA = VideoPoint!
@pointB = VideoPoint!
@keybinds =
"1": self\setPointA
"2": self\setPointB
"r": self\reset
"ESC": self\cancel
"ENTER": self\finish
self\reset!
@callback = callback
-- If we have a region, set point A and B from it
if region and region\is_valid!
@pointA.x = region.x
@pointA.y = region.y
@pointB.x = region.x + region.w
@pointB.y = region.y + region.h
reset: =>
dimensions = get_video_dimensions!
{x: xa, y: ya} = dimensions.top_left
@pointA\set_from_screen(xa, ya)
{x: xb, y: yb} = dimensions.bottom_right
@pointB\set_from_screen(xb, yb)
if @visible
self\draw!
setPointA: =>
posX, posY = mp.get_mouse_pos()
@pointA\set_from_screen(posX, posY)
if @visible
-- No need to clear, as we draw the entire OSD (also it causes flickering)
self\draw!
setPointB: =>
posX, posY = mp.get_mouse_pos()
@pointB\set_from_screen(posX, posY)
if @visible
self\draw!
cancel: =>
self\hide!
self.callback(false, nil)
finish: =>
region = Region!
region\set_from_points(@pointA, @pointB)
self\hide!
self.callback(true, region)
draw_box: (ass) =>
region = Region!
region\set_from_points(@pointA\to_screen!, @pointB\to_screen!)
d = get_video_dimensions!
ass\new_event()
ass\append("{\\an7}")
ass\pos(0, 0)
ass\append('{\\bord0}')
ass\append('{\\shad0}')
ass\append('{\\c&H000000&}')
ass\append('{\\alpha&H77}')
-- Draw a black layer over the uncropped area
ass\draw_start()
ass\rect_cw(d.top_left.x, d.top_left.y, region.x, region.y + region.h) -- Top left uncropped area
ass\rect_cw(region.x, d.top_left.y, d.bottom_right.x, region.y) -- Top right uncropped area
ass\rect_cw(d.top_left.x, region.y + region.h, region.x + region.w, d.bottom_right.y) -- Bottom left uncropped area
ass\rect_cw(region.x + region.w, region.y, d.bottom_right.x, d.bottom_right.y) -- Bottom right uncropped area
ass\draw_stop()
draw: =>
window = {}
window.w, window.h = mp.get_osd_size()
ass = assdraw.ass_new()
self\draw_box(ass)
ass\new_event()
self\setup_text(ass)
ass\append("#{bold('Crop:')}\\N")
ass\append("#{bold('1:')} change point A (#{@pointA.x}, #{@pointA.y})\\N")
ass\append("#{bold('2:')} change point B (#{@pointB.x}, #{@pointB.y})\\N")
ass\append("#{bold('r:')} reset to whole screen\\N")
ass\append("#{bold('ESC:')} cancel crop\\N")
width, height = math.abs(@pointA.x - @pointB.x), math.abs(@pointA.y - @pointB.y)
ass\append("#{bold('ENTER:')} confirm crop (#{width}x#{height})\\N")
mp.set_osd_ass(window.w, window.h, ass.text)
| 30.988636 | 118 | 0.63293 |
da13ff5fa575eb8d3666e0989ac71093be35e93c | 11,831 | get_active_tracks = ->
accepted =
video: true
audio: not mp.get_property_bool("mute")
sub: mp.get_property_bool("sub-visibility")
active =
video: {}
audio: {}
sub: {}
for _, track in ipairs mp.get_property_native("track-list")
if track["selected"] and accepted[track["type"]]
count = #active[track["type"]]
active[track["type"]][count + 1] = track
return active
filter_tracks_supported_by_format = (active_tracks, format) ->
has_video_codec = format.videoCodec != ""
has_audio_codec = format.audioCodec != ""
supported =
video: has_video_codec and active_tracks["video"] or {}
audio: has_audio_codec and active_tracks["audio"] or {}
sub: has_video_codec and active_tracks["sub"] or {}
return supported
append_track = (out, track) ->
external_flag =
"audio": "audio-file"
"sub": "sub-file"
internal_flag =
"video": "vid"
"audio": "aid"
"sub": "sid"
-- The external tracks rely on the behavior that, when using
-- audio-file/sub-file only once, the track is selected by default.
-- Also, for some reason, ytdl-hook produces external tracks with absurdly long
-- filenames; this breaks our command line. Try to keep it sane, under 2048 characters.
if track['external'] and string.len(track['external-filename']) <= 2048
append(out, {
"--#{external_flag[track['type']]}=#{track['external-filename']}"
})
else
append(out, {
"--#{internal_flag[track['type']]}=#{track['id']}"
})
append_audio_tracks = (out, tracks) ->
-- Some additional logic is needed for audio tracks because it seems
-- multiple active audio tracks are a thing? We probably only can reliably
-- use internal tracks for this so, well, we keep track of them and see if
-- more than one is active.
internal_tracks = {}
for track in *tracks
if track['external']
-- For external tracks, just do the same thing.
append_track(out, track)
else
append(internal_tracks, { track })
if #internal_tracks > 1
-- We have multiple audio tracks, so we use a lavfi-complex
-- filter to mix them.
filter_string = ""
for track in *internal_tracks
filter_string = filter_string .. "[aid#{track['id']}]"
filter_string = filter_string .. "amix[ao]"
append(out, {
"--lavfi-complex=#{filter_string}"
})
else if #internal_tracks == 1
append_track(out, internal_tracks[1])
get_scale_filters = ->
if options.scale_height > 0
return {"lavfi-scale=-2:#{options.scale_height}"}
return {}
get_fps_filters = ->
if options.fps > 0
return {"fps=#{options.fps}"}
return {}
append_property = (out, property_name, option_name) ->
option_name = option_name or property_name
prop = mp.get_property(property_name)
if prop and prop != ""
append(out, {"--#{option_name}=#{prop}"})
-- Reads a mpv "list option" property and set the corresponding command line flags (as specified on the manual)
-- option_prefix is optional, will be set to property_name if empty
append_list_options = (out, property_name, option_prefix) ->
option_prefix = option_prefix or property_name
prop = mp.get_property_native(property_name)
if prop
for value in *prop
append(out, {"--#{option_prefix}-append=#{value}"})
-- Get the current playback options, trying to match how the video is being played.
get_playback_options = ->
ret = {}
append_property(ret, "sub-ass-override")
append_property(ret, "sub-ass-force-style")
append_property(ret, "sub-ass-vsfilter-aspect-compat")
append_property(ret, "sub-auto")
append_property(ret, "sub-delay")
append_property(ret, "video-rotate")
append_property(ret, "ytdl-format")
return ret
get_speed_flags = ->
ret = {}
speed = mp.get_property_native("speed")
if speed != 1
append(ret, {
"--vf-add=setpts=PTS/#{speed}",
"--af-add=atempo=#{speed}",
"--sub-speed=1/#{speed}"
})
return ret
get_metadata_flags = ->
title = mp.get_property("filename/no-ext")
return {"--oset-metadata=title=%#{string.len(title)}%#{title}"}
apply_current_filters = (filters) ->
vf = mp.get_property_native("vf")
msg.verbose("apply_current_filters: got #{#vf} currently applied.")
for filter in *vf
msg.verbose("apply_current_filters: filter name: #{filter['name']}")
-- This might seem like a redundant check (if not filter["enabled"] would achieve the same result),
-- but the enabled field isn't guaranteed to exist... and if it's nil, "not filter['enabled']"
-- would achieve a different outcome.
if filter["enabled"] == false
continue
str = filter["name"]
params = filter["params"] or {}
for k, v in pairs params
str = str .. ":#{k}=%#{string.len(v)}%#{v}"
append(filters, {str})
get_video_filters = (format, region) ->
filters = {}
append(filters, format\getPreFilters!)
if options.apply_current_filters
apply_current_filters(filters)
if region and region\is_valid!
append(filters, {"lavfi-crop=#{region.w}:#{region.h}:#{region.x}:#{region.y}"})
append(filters, get_scale_filters!)
append(filters, get_fps_filters!)
append(filters, format\getPostFilters!)
return filters
get_video_encode_flags = (format, region) ->
flags = {}
append(flags, get_playback_options!)
filters = get_video_filters(format, region)
for f in *filters
append(flags, {
"--vf-add=#{f}"
})
append(flags, get_speed_flags!)
return flags
calculate_bitrate = (active_tracks, format, length) ->
if format.videoCodec == ""
-- Allocate everything to the audio, not a lot we can do here
return nil, options.target_filesize * 8 / length
video_kilobits = options.target_filesize * 8
audio_kilobits = nil
has_audio_track = #active_tracks["audio"] > 0
if options.strict_filesize_constraint and has_audio_track
-- We only care about audio bitrate on strict encodes
audio_kilobits = length * options.strict_audio_bitrate
video_kilobits -= audio_kilobits
video_bitrate = math.floor(video_kilobits / length)
audio_bitrate = audio_kilobits and math.floor(audio_kilobits / length) or nil
return video_bitrate, audio_bitrate
find_path = (startTime, endTime) ->
path = mp.get_property('path')
if not path
return nil, nil, nil, nil, nil
is_stream = not file_exists(path)
is_temporary = false
if is_stream
if mp.get_property('file-format') == 'hls'
-- Attempt to dump the stream cache into a temporary file
path = utils.join_path(parse_directory('~'), 'cache_dump.ts')
mp.command_native({
'dump_cache',
seconds_to_time_string(startTime, false, true),
seconds_to_time_string(endTime + 5, false, true),
path
})
endTime = endTime - startTime
startTime = 0
is_temporary = true
return path, is_stream, is_temporary, startTime, endTime
encode = (region, startTime, endTime) ->
format = formats[options.output_format]
originalStartTime = startTime
originalEndTime = endTime
path, is_temporary, is_stream, startTime, endTime = find_path(startTime, endTime)
if not path
message("No file is being played")
return
command = {
"mpv", path,
"--start=" .. seconds_to_time_string(startTime, false, true),
"--end=" .. seconds_to_time_string(endTime, false, true),
-- When loop-file=inf, the encode won't end. Set this to override.
"--loop-file=no",
-- Same thing with --pause
"--no-pause"
}
append(command, format\getCodecFlags!)
active_tracks = get_active_tracks!
supported_active_tracks = filter_tracks_supported_by_format(active_tracks, format)
for track_type, tracks in pairs supported_active_tracks
if track_type == "audio"
append_audio_tracks(command, tracks)
else
for track in *tracks
append_track(command, track)
for track_type, tracks in pairs supported_active_tracks
if #tracks > 0
continue
switch track_type
when "video"
append(command, {"--vid=no"})
when "audio"
append(command, {"--aid=no"})
when "sub"
append(command, {"--sid=no"})
if format.videoCodec != ""
-- All those are only valid for video codecs.
append(command, get_video_encode_flags(format, region))
append(command, format\getFlags!)
if options.write_filename_on_metadata
append(command, get_metadata_flags!)
if format.acceptsBitrate
if options.target_filesize > 0
length = endTime - startTime
video_bitrate, audio_bitrate = calculate_bitrate(supported_active_tracks, format, length)
if video_bitrate
append(command, {
"--ovcopts-add=b=#{video_bitrate}k",
})
if audio_bitrate
append(command, {
"--oacopts-add=b=#{audio_bitrate}k"
})
if options.strict_filesize_constraint
type = format.videoCodec != "" and "ovc" or "oac"
append(command, {
"--#{type}opts-add=minrate=#{bitrate}k",
"--#{type}opts-add=maxrate=#{bitrate}k",
})
else
type = format.videoCodec != "" and "ovc" or "oac"
-- set video bitrate to 0. This might enable constant quality, or some
-- other encoding modes, depending on the codec.
append(command, {
"--#{type}opts-add=b=0"
})
-- split the user-passed settings on whitespace
for token in string.gmatch(options.additional_flags, "[^%s]+") do
command[#command + 1] = token
if not options.strict_filesize_constraint
for token in string.gmatch(options.non_strict_additional_flags, "[^%s]+") do
command[#command + 1] = token
-- Also add CRF here, as it used to be a part of the non-strict flags.
-- This might change in the future, I don't know.
if options.crf >= 0
append(command, {
"--ovcopts-add=crf=#{options.crf}"
})
dir = ""
if is_stream
dir = parse_directory("~")
else
dir, _ = utils.split_path(path)
if options.output_directory != ""
dir = parse_directory(options.output_directory)
formatted_filename = format_filename(originalStartTime, originalEndTime, format)
out_path = utils.join_path(dir, formatted_filename)
append(command, {"--o=#{out_path}"})
-- Do the first pass now, as it won't require the output path. I don't think this works on streams.
-- Also this will ignore run_detached, at least for the first pass.
if options.twopass and format.supportsTwopass and not is_stream
-- copy the commandline
first_pass_cmdline = [arg for arg in *command]
append(first_pass_cmdline, {
"--ovcopts-add=flags=+pass1"
})
message("Starting first pass...")
msg.verbose("First-pass command line: ", table.concat(first_pass_cmdline, " "))
res = run_subprocess({args: first_pass_cmdline, cancellable: false})
if not res
message("First pass failed! Check the logs for details.")
return
-- set the second pass flag on the final encode command
append(command, {
"--ovcopts-add=flags=+pass2"
})
if format.videoCodec == "libvpx"
-- We need to patch the pass log file before running the second pass.
msg.verbose("Patching libvpx pass log file...")
vp8_patch_logfile(get_pass_logfile_path(out_path), endTime - startTime)
msg.info("Encoding to", out_path)
msg.verbose("Command line:", table.concat(command, " "))
if options.run_detached
message("Started encode, process was detached.")
utils.subprocess_detached({args: command})
else
res = false
if not should_display_progress!
message("Started encode...")
res = run_subprocess({args: command, cancellable: false})
else
ewp = EncodeWithProgress(startTime, endTime)
res = ewp\startEncode(command)
if res
message("Encoded successfully! Saved to\\N#{bold(out_path)}")
else
message("Encode failed! Check the logs for details.")
-- Clean up pass log file.
os.remove(get_pass_logfile_path(out_path))
if is_temporary
os.remove(path)
| 31.718499 | 112 | 0.682783 |
c69e0d564ca99a0192442efb27b3a9d98522e836 | 1,691 | -- Copyright 2012-2018 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
{:PropertyObject} = howl.util.moon
{:TextWidget} = howl.ui
{:floor} = math
{:tostring} = _G
class ListWidget extends PropertyObject
new: (@list, opts = {}) =>
super!
@partial = false
@opts = moon.copy opts
@opts.on_resized = -> list.selection = list.selection
@text_widget = TextWidget @opts
@text_widget.visible_rows = 15
list\insert @text_widget.buffer
list.max_rows = @text_widget.visible_rows
list\on_refresh self\_on_refresh
@property showing: get: => @text_widget.showing
@property height: get: => @text_widget.height
@property width: get: => @text_widget.width
@property max_height_request:
set: (height) =>
default_line_height = @text_widget.view\text_dimensions('M').height
@list.max_rows = floor(height / default_line_height)
@list\draw!
keymap:
binding_for:
['cursor-up']: => @list\select_prev!
['cursor-down']: => @list\select_next!
['cursor-page-up']: => @list\prev_page!
['cursor-page-down']: => @list\next_page!
to_gobject: => @text_widget\to_gobject!
show: =>
return if @showing
@text_widget\show!
@list\draw!
hide: => @text_widget\hide!
_on_refresh: =>
if @text_widget.showing
@_adjust_height!
@_adjust_width!
@text_widget.view.first_visible_line = 1
_adjust_height: =>
shown_rows = @list.rows_shown
if @opts.never_shrink
@list.min_rows = shown_rows
@text_widget.visible_rows = shown_rows
_adjust_width: =>
if @opts.auto_fit_width
@text_widget\adjust_width_to_fit!
| 26.015385 | 79 | 0.6712 |
e062633fdba35f786f081c240b040cb93795dcc8 | 24 | require "lapis.db.model" | 24 | 24 | 0.791667 |
750c6220d076883602065ed31c99dd4b034a139c | 1,172 | import concat from table
setfenv or= (env) =>
i = 1
while true
if name = debug.getupvalue @, i
if name == "_ENV"
debug.upvaluejoin @, i, (-> env), 1
break
else break
i += 1
@
local H
html = =>
switch type @
when "table" concat[html(v) for v in *@]
when "function"
env = setmetatable {}, H
setfenv(@, env)!
concat [tostring(i) for i in *env]
else tostring @
mt = {
__tostring: =>
k = @k
k = k\sub(2) if k\sub(1, 1) == "_"
content = concat [tostring(i) for i in *@]
if k == "text" then content
else
attrs = @attrs and (
concat [type(_v) == "boolean" and (_v and " #{_k}" or "") or " #{_k}=\"#{_v}\"" for _k, _v in pairs @attrs]
) or ''
if #@ == 0 then "<#{k}#{attrs}/>"
else "<#{k}#{attrs}>#{content}</#{k}>"
__call: (...) =>
for i = 1, select "#", ...
item = select i, ...
if type(item) == "table"
@attrs = item
else
@[#@+1] = html item
}
H = __index: (k) =>
return _G[k] if _G[k] and k ~= "table"
k = "table" if k == "htable"
v = setmetatable {:k}, mt
@[#@+1] = v
v
setmetatable H, H
:html
| 21.309091 | 115 | 0.480375 |
b78fe0d2323c31254c7204cc152024e4381d006b | 276 | local sprite
with tiny
sprite = .processingSystem!
sprite.filter = .requireAll "x", "y", "sprite"
sprite.process = (e, dt) =>
with e
love.graphics.setColor 255, 255, 255
love.graphics.draw .sprite, .x, .y, (.rotation or 0), (.sx or 1), .sy or 1
sprite
| 21.230769 | 78 | 0.623188 |
3968110238a1f5f2b6ce90d8c8cc9044a73f65f1 | 6,630 | Revisions = require 'aullar.revisions'
Buffer = require 'aullar.buffer'
describe 'Revisions', ->
local revisions, buffer
before_each ->
revisions = Revisions!
buffer = Buffer!
describe 'push(type, offset, text, meta)', ->
it 'adds revisions with the correct parameters', ->
revisions\push 'inserted', 3, 'foo'
assert.same {
type: 'inserted',
offset: 3,
text: 'foo',
meta: {}
}, revisions[1]
revisions\push 'deleted', 3, 'f', foo: 1
assert.same {
type: 'deleted',
offset: 3,
text: 'f',
meta: { foo: 1 }
}, revisions[2]
it 'returns the added revision', ->
rev = revisions\push 'inserted', 3, 'foo'
assert.same {
type: 'inserted',
offset: 3,
text: 'foo',
meta: {}
}, rev
describe 'adjacent edits', ->
it 'merges subsequent inserts', ->
revisions\push 'inserted', 2, 'foo'
revisions\push 'inserted', 5, 'ba'
assert.equal 1, #revisions
assert.same {
type: 'inserted',
offset: 2,
text: 'fooba',
meta: {}
}, revisions.last
it 'merges preceeding deletes', ->
-- 123456
revisions\push 'deleted', 4, '4'
revisions\push 'deleted', 3, '3'
revisions\push 'deleted', 2, '2'
assert.equal 1, #revisions
assert.same {
type: 'deleted',
offset: 2,
text: '234',
meta: {}
}, revisions.last
it 'merges deletes at the same offset', ->
-- 123456
revisions\push 'deleted', 4, '4'
revisions\push 'deleted', 4, '5'
revisions\push 'deleted', 4, '6'
assert.equal 1, #revisions
assert.same {
type: 'deleted',
offset: 4,
text: '456',
meta: {}
}, revisions.last
-- it 'never merges blank insert revisions', ->
-- revisions\push 'inserted', 1, 'x'
-- revisions\push 'inserted', 2, ' '
-- assert.equal 2, #revisions
-- revisions\push 'inserted', 3, '\n'
-- assert.equal 3, #revisions
it 'raises an error if the type is unknown', ->
assert.raises 'foo', -> revisions\push 'foo', 3, 'bar'
describe 'pop(buffer)', ->
it 'undos the stored revisions, in reverse order', ->
-- starting with '123456789'
revisions\push 'deleted', 9, '9' -- and we've deleted '9' at 9
revisions\push 'inserted', 4, 'xxx' -- and inserted 'xxx' at 3
buffer.text = '123xxx45678' -- this is what it looks like
revisions\pop buffer -- pop the insert
assert.equal '12345678', buffer.text
revisions\pop buffer -- pop the delete
assert.equal '123456789', buffer.text
it 'returns earliest undo revision', ->
revisions\push 'deleted', 9, '9'
buffer.text = '12345678' -- this is what it looks like
assert.same {
type: 'deleted',
offset: 9,
text: '9',
meta: {}
}, revisions\pop(buffer)
describe 'forward(buffer)', ->
it 'does nothing when there are no revisions to apply', ->
buffer.text = '12345'
revisions\forward buffer
assert.equal '12345', buffer.text
revisions\push 'deleted', 2, 'x'
revisions\forward buffer
assert.equal '12345', buffer.text
describe 'with previously popped revisions available', ->
it 'applies the last popped revision', ->
buffer.text = '12x3'
revisions\push 'inserted', 3, 'x'
revisions\pop buffer
assert.equal '123', buffer.text
revisions\forward buffer
assert.equal '12x3', buffer.text
describe 'clear()', ->
it 'removes all previous revisions', ->
revisions\push 'deleted', 9, '9' -- and we've deleted '9' at 9
revisions\push 'inserted', 4, 'xxx' -- and inserted 'xxx' at 3
revisions\clear!
assert.equal 0, #revisions
it '# returns the number of revisions', ->
assert.equal 0, #revisions
revisions\push 'inserted', 3, 'foo'
assert.equal 1, #revisions
describe 'grouped undos', ->
it 'start_group() groups revisions together until end_group()', ->
-- starting with '123456789'
revisions\push 'deleted', 9, '9'
revisions\start_group!
revisions\push 'inserted', 4, 'x'
revisions\push 'inserted', 2, 'y'
revisions\end_group!
buffer.text = '1y23x45678' -- this is what it looks like
-- let's pop the grouped revisions
assert.same { -- the last pop'ed revision should be returned
type: 'inserted',
offset: 4,
text: 'x',
group: 1,
meta: {}
}, revisions\pop(buffer)
assert.equal '12345678', buffer.text -- and both should be undone
assert.equal 1, #revisions -- with one single revision left
-- let's forward the grouped revisions
assert.same { -- the last forwarded revision should be returned
type: 'inserted',
offset: 2,
text: 'y',
group: 1,
meta: {}
}, revisions\forward(buffer)
assert.equal '1y23x45678', buffer.text -- and both should be reapplied
assert.equal 3, #revisions -- with three revisions left again
it 'does not merge grouped revisions into non-group revisions', ->
revisions\push 'inserted', 3, 'f'
revisions\start_group!
revisions\push 'inserted', 4, 'u'
assert.equal 2, #revisions
it 'treats nested groups as one big group', ->
buffer.text = ' '
revisions\start_group!
revisions\push 'deleted', 1, 'x'
revisions\start_group!
revisions\push 'deleted', 2, 'x'
revisions\end_group!
revisions\push 'deleted', 3, 'x'
revisions\end_group!
revisions\pop buffer
assert.equal 'x x x', buffer.text
it 'separates adjacent undo groups', ->
buffer.text = ' '
revisions\start_group!
revisions\push 'deleted', 1, 'x'
revisions\end_group!
revisions\start_group!
revisions\push 'deleted', 2, 'x'
revisions\end_group!
revisions\pop buffer
assert.equal ' x', buffer.text
describe 'over-arching concerns', ->
it 'push resets the ability to forward again', ->
buffer.text = ' '
revisions\push 'deleted', 1, 'x'
revisions\push 'deleted', 2, 'x'
revisions\push 'deleted', 3, 'x'
revisions\pop buffer
revisions\pop buffer
assert.equals ' x x', buffer.text
revisions\push 'inserted', 1, 'X'
revisions\forward buffer -- should be a no-op
assert.equals ' x x', buffer.text
| 30.981308 | 76 | 0.579035 |
11d85936915e2eac72b2ff4f785cd80ba6d7d314 | 2,647 |
import compile, render, Parser from require "etlua"
describe "etlua", ->
describe "Parser", ->
cases = {
{
"hello world"
"hello world"
}
{
"one surf-zone two"
"one <%= var %> two"
{var: "surf-zone"}
}
{
"a ((1))((2))((3)) b"
"a <% for i=1,3 do %>((<%= i %>))<% end %> b"
}
{
"y%>u"
[[<%= "y%>u" %>]]
}
{
"y%>u"
[[<%- "y%>u" %>]]
}
{
[[
This is my message to you
This is my message to 4
hello 1
hello 2
hello 3
hello 4
hello 5
hello 6
hello 7
hello 8
hello 9
hello 10
message: yeah
This is my message to oh yeah %>"]]
[[
This is my message to <%= "you" %>
This is my message to <%= 4 %>
<% if things then %>
I love things
<% end %>
<% for i=1,10 do%>
hello <%= i -%>
<% end %>
message: <%= visitor %>
This is my message to <%= [=[oh yeah %>"]=] %>]]
{
visitor: "yeah"
}
}
{
"hello"
"<%= 'hello' -%>
"
}
-- should have access to _G
{
""
"<% assert(true) %>"
{ hello: "world" }
}
}
for case in *cases
it "should render template", ->
assert.same case[1], render unpack case, 2
it "should error on unclosed tag", ->
assert.has_error ->
assert render "hello <%= world"
it "should fail on bad interpolate tag", ->
assert.has_error ->
assert render "hello <%= if hello then print(nil) end%>"
it "should fail on bad code tag", ->
assert.has_error ->
assert render [[
what is going on
hello <% howdy doody %>
there is nothing left
]]
it "should use existing buffer", ->
fn = compile "hello<%= 'yeah' %>"
buff = {"first"}
out = fn {}, buff, #buff
assert.same "firsthelloyeah", out
it "should compile readme example", ->
parser = Parser!
first_fn = parser\load parser\compile_to_lua "Hello "
second_fn = parser\load parser\compile_to_lua "World"
buffer = {}
parser\run first_fn, nil, buffer, #buffer
parser\run second_fn, nil, buffer, #buffer
assert.same "Hello World", table.concat buffer
describe "Parser.in_string", ->
cases = {
{ "hello world", false }
{ "hello 'world", true }
{ [[hello "hello \" world]], true }
{ "hello [=[ wor'ld ]=]dad", false }
}
for {str, expected} in *cases
it "should detect if in string", ->
assert.same expected, Parser.in_string { :str }, 1
| 19.181159 | 64 | 0.487722 |
a39791a5ec20a46794823deaebd3b2a2a44f4150 | 1,036 |
ltn12 = require "ltn12"
http = require "socket.http"
https = require "ssl.https"
local *
string_source = ltn12.source.string
table_sink = ltn12.sink.table
table_concat = table.concat
make_request = (opts) ->
return https.request(opts) if opts.url\find "https:"
http.request(opts)
--request {
-- method = string,
-- url = string,
-- headers = header-table,
-- body = string
--}
--response {
-- body = <response body>,
-- code = <http status code>,
-- headers = <table of headers>,
-- status = <the http status message>,
-- err = <nil or error message>
--}
request = (opts) ->
opts = { url: opts, method: 'GET' } if type(opts) == 'string'
opts.source = string_source(opts.body)
result = {}
opts.sink = table_sink(result)
one, code, headers, status = make_request opts
body = table_concat(result)
message = #body > 0 and body or "unknown error"
return {:code, :headers, :status, err: message} unless one
{ :code, :headers, :status, :body }
{ :request }
| 22.521739 | 70 | 0.622587 |
444545672bc7cf1d0997587d873e5648127f0ae8 | 198 | export modinfo = {
type: "command"
desc: "Parent cba"
alias: {"pcba"}
func: ->
CreateInstance"StringValue"
Parent: workspace
Name: "CBA Attachment"
Value: "script.Parent=Workspace"
} | 18 | 35 | 0.671717 |
681786eb1a5c7c2d4c105f18213bcd1fe357074c | 8,027 | -- Copyright (c) 2012, Thomas Goyne <plorkyeran@aegisub.org>
--
-- Permission to use, copy, modify, and distribute this software for any
-- purpose with or without fee is hereby granted, provided that the above
-- copyright notice and this permission notice appear in all copies.
--
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
error = error
next = next
select = select
type = type
bit = require 'bit'
ffi = require 'ffi'
ffi_util = require 'aegisub.ffi'
check = require 'aegisub.argcheck'
ffi.cdef[[
typedef struct agi_re_flag {
const char *name;
int value;
} agi_re_flag;
]]
regex_flag = ffi.typeof 'agi_re_flag'
-- Get the boost::eegex binding
regex = require 'aegisub.__re_impl'
-- Wrappers to convert returned values from C types to Lua types
search = (re, str, start) ->
return unless start <= str\len()
res = regex.search re, str, str\len(), start
return unless res != nil
first, last = res[0], res[1]
ffi.C.free res
first, last
replace = (re, replacement, str, max_count) ->
ffi_util.string regex.replace re, replacement, str, str\len(), max_count
match = (re, str, start) ->
assert start <= str\len()
m = regex.match re, str, str\len(), start
return unless m != nil
ffi.gc m, regex.match_free
get_match = (m, idx) ->
res = regex.get_match m, idx
return unless res != nil
res[0], res[1] -- Result buffer is owned by match so no need to free
err_buff = ffi.new 'char *[1]'
compile = (pattern, flags) ->
err_buff[0] = nil
re = regex.compile pattern, flags, err_buff
if err_buff[0] != nil
return ffi.string err_buff[0]
ffi.gc re, regex.regex_free
-- Return the first n elements from ...
select_first = (n, a, ...) ->
if n == 0 then return
a, select_first n - 1, ...
-- Bitwise-or together regex flags passed as arguments to a function
process_flags = (...) ->
flags = 0
for i = 1, select '#', ...
v = select i, ...
if not ffi.istype regex_flag, v
error 'Flags must follow all non-flag arguments', 3
flags = bit.bor flags, v.value
flags
-- Extract the flags from ..., bitwise OR them together, and move them to the
-- front of ...
unpack_args = (...) ->
flags_start = nil
for i = 1, select '#', ...
v = select i, ...
if ffi.istype regex_flag, v
flags_start = i
break
return 0, ... unless flags_start
process_flags(select flags_start, ...), select_first flags_start - 1, ...
-- Replace a match with the value returned from func when passed the match
replace_match = (match, func, str, last, acc) ->
-- Copy everything between the last match and this match
if last < match.last
acc[#acc + 1] = str\sub last, match.first - 1
repl = func match.str, match.first, match.last
-- If it didn't return a string just leave the old value
acc[#acc + 1] = if type(repl) == 'string' then repl else match.str
match.first, match.last + 1
-- Replace all matches from a single iteration of the regexp
do_single_replace_fun = (re, func, str, acc, pos) ->
matches = re\match str, pos
-- No more matches so just return what's left of the input
return pos unless matches
-- If there's only one match then there's no capturing groups and we need
-- to pass the entire match to the replace function, but if there's
-- multiple then we want to skip the full match and only pass the capturing
-- groups.
start = if #matches == 1 then 1 else 2
last = pos
local first
for i = start, #matches
first, last = replace_match matches[i], func, str, last, acc
-- Always eat at least one character from the input or we'll just make the
-- same match max_count times
if first == last
acc[#acc + 1] = str\sub last, last
last += 1
return last, matches[1].first <= str\len()
do_replace_fun = (re, func, str, max) ->
acc = {}
pos = 1
local i
for i = 1, max do
pos, more = do_single_replace_fun re, func, str, acc, pos
unless more
max = i
break
table.concat(acc, '') .. str\sub pos
-- Compiled regular expression type protoype
class RegEx
-- Verify that a valid value was passed for self
_check_self: =>
unless @__class == RegEx
error 're method called with invalid self. You probably used . when : is needed.', 3
new: (@_regex, @_level) =>
gsplit: check'RegEx string ?boolean ?number' (str, skip_empty, max_split) =>
if not max_split or max_split <= 0 then max_split = str\len()
start = 0
prev = 1
do_split = () ->
if not str or str\len() == 0 then return
local first, last
if max_split > 0
first, last = search @_regex, str, start
if not first or first > str\len()
ret = str\sub prev, str\len()
str = nil
return if skip_empty and ret\len() == 0 then nil else ret
ret = str\sub prev, first - 1
prev = last + 1
start = if start >= last then start + 1 else last
if skip_empty and ret\len() == 0
do_split()
else
max_split -= 1
ret
do_split
split: check'RegEx string ?boolean ?number' (str, skip_empty, max_split) =>
[v for v in @gsplit str, skip_empty, max_split]
gfind: check'RegEx string' (str) =>
start = 0
->
first, last = search(@_regex, str, start)
return unless first
start = if last > start then last else start + 1
str\sub(first, last), first, last
find: check'RegEx string' (str) =>
ret = [str: s, first: f, last: l for s, f, l in @gfind(str)]
next(ret) and ret
sub: check'RegEx string string|function ?number' (str, repl, max_count) =>
max_count = str\len() + 1 if not max_count or max_count == 0
if type(repl) == 'function'
do_replace_fun @, repl, str, max_count
elseif type(repl) == 'string'
replace @_regex, repl, str, max_count
gmatch: check'RegEx string ?number' (str, start) =>
start = if start then start - 1 else 0
m = match @_regex, str, start
i = 0
->
return unless m
first, last = get_match m, i
return unless first
i += 1
{
str: str\sub first + start, last + start
first: first + start
last: last + start
}
match: check'RegEx string ?number' (str, start) =>
ret = [v for v in @gmatch str, start]
-- Return nil rather than a empty table so that if re.match(...) works
return nil if next(ret) == nil
ret
-- Create a regex object from a pattern, flags, and error depth
real_compile = (pattern, level, flags, stored_level) ->
if pattern == ''
error 'Regular expression must not be empty', level + 1
re = compile pattern, flags
if type(re) == 'string'
error regex, level + 1
RegEx re, stored_level or level + 1
-- Compile a pattern then invoke a method on it
invoke = (str, pattern, fn, flags, ...) ->
compiled_regex = real_compile(pattern, 3, flags)
compiled_regex[fn](compiled_regex, str, ...)
-- Generate a static version of a method with arg type checking
gen_wrapper = (impl_name) -> check'string string ...' (str, pattern, ...) ->
invoke str, pattern, impl_name, unpack_args ...
-- And now at last the actual public API
do
re = {
compile: check'string ...' (pattern, ...) ->
real_compile pattern, 2, process_flags(...), 2
split: gen_wrapper 'split'
gsplit: gen_wrapper 'gsplit'
find: gen_wrapper 'find'
gfind: gen_wrapper 'gfind'
match: gen_wrapper 'match'
gmatch: gen_wrapper 'gmatch'
sub: gen_wrapper 'sub'
}
i = 0
flags = regex.get_flags()
while flags[i].name != nil
re[ffi.string flags[i].name] = flags[i]
i += 1
re
| 29.511029 | 90 | 0.648063 |
b930afe7d03a3bb798718ff96797a4e7b9ced0c4 | 226 | love.conf= (t) ->
t.version = "0.10.0"
t.identity = "billiard"
with t.window
.title = "Billiard"
.icon = "images/billiard.png"
.width = 800
.height = 542
.fullscreen = false
| 22.6 | 37 | 0.50885 |
ea8183528d3ef2066ea977ec16efffc0c2a328f4 | 309 | import config from require "lapis.config"
config "development", ->
postgresql_url "postgres://benchmarkdbuser:benchmarkdbpass@127.0.0.1/hello_world"
config "production", ->
port 80
num_workers 4
lua_code_cache "on"
postgresql_url "postgres://benchmarkdbuser:benchmarkdbpass@127.0.0.1/hello_world"
| 28.090909 | 83 | 0.773463 |
c78670aff88c0a03a001d76529c91f99bf560765 | 177 | tasks:
always: =>
load "graph-proof.d"
load "graph-proof.e"
a: => print @name
doa: =>
tasks.a!
tasks.b!
tasks.c!
tasks.d!
tasks.e!
tasks.f! | 14.75 | 24 | 0.508475 |
35cc3b9b603685b40d33e55198cda74a07563ed9 | 1,993 | -- Copyright 2013-2015 The Howl Developers
-- License: MIT (see LICENSE.md)
import style from howl.ui
style.define 'css_selector', 'keyword'
style.define 'css_property', 'key'
style.define 'css_unit', 'type'
style.define 'css_color', 'string'
style.define 'css_at', 'preproc'
style.define 'css_pseudo', 'class'
howl.aux.lpeg_lexer ->
blank = capture 'whitespace', S(' \t')^1
operator = capture 'operator', S'>{},():'
name = alpha * (alnum + S'_-')^0
comment = capture 'comment', span('/*', '*/')
unit = capture 'css_unit', any('%', 'in', 'cm', 'mm', 'em', 'ex', 'pt', 'pc', 'px')
integer = S'+-'^-1 * digit^1
real = S'+-'^-1 * digit^0 * P'.'^-1 * digit^1
num = capture('number', (integer + real)) * unit^-1
color = capture 'css_color', P'#' * R('af', 'AF', '09')^0
dq_string = capture 'string', span('"', '"', '\\')
sq_string = capture 'string', span("'", "'", '\\')
string = any(dq_string, sq_string)
property = capture('css_property', (alpha + '-')^1) * blank^0 * capture('operator', ':')
value_identifier = any(S'-:.', alpha)^1
named_parameter = capture('key', name) * blank^0 * capture('operator', S'*^='^1)
func_value = any(alpha, S'-:.')^1 * '(' * complement(')')^1 * ')'
decl_value = any {
comment,
num,
color,
blank,
named_parameter,
func_value,
value_identifier,
string,
capture('operator', S'!'),
complement(S' \t;{},')^1,
}
declaration = property * space^0 * (decl_value^0 + blank) * any {
capture('operator', ';'),
space^0 * capture('operator', '}'),
eol,
}
at_rule = capture('css_at', P'@' * name) * (blank * dq_string)^-1
pseudo = capture 'css_pseudo', P':' * name
attr_spec = capture('operator', '[') * any(named_parameter, blank, dq_string, capture('key', name))^0 * capture('operator', ']')
selector = capture('css_selector', any(S'.#'^-1 * name, P'*'))
any {
comment,
pseudo,
declaration,
at_rule,
attr_spec,
selector,
operator,
}
| 28.884058 | 130 | 0.581535 |
ac7bf2c408d1a966c2892b2a6dad0a1177ec5b8e | 133 | Gamestate = require "lib.gamestate"
game = require "states.game"
love.load = ->
Gamestate.registerEvents!
Gamestate.switch game
| 19 | 35 | 0.744361 |
772fc6027d6988d5ecba0cbf548bf4335bf6f84e | 2,224 | html = require "lapis.html"
config = (require "lapis.config").get!
appname=config.appname or "KinkyEureka"
import staticUrl from require "utils"
class Favicon extends html.Widget
content: =>
link rel:"apple-touch-icon", sizes:"57x57", href: staticUrl"/favicon/apple-touch-icon-57x57.png"
link rel:"apple-touch-icon", sizes:"60x60", href: staticUrl"/favicon/apple-touch-icon-60x60.png"
link rel:"apple-touch-icon", sizes:"72x72", href: staticUrl"/favicon/apple-touch-icon-72x72.png"
link rel:"apple-touch-icon", sizes:"76x76", href: staticUrl"/favicon/apple-touch-icon-76x76.png"
link rel:"apple-touch-icon", sizes:"114x114", href: staticUrl"/favicon/apple-touch-icon-114x114.png"
link rel:"apple-touch-icon", sizes:"120x120", href: staticUrl"/favicon/apple-touch-icon-120x120.png"
link rel:"apple-touch-icon", sizes:"144x144", href: staticUrl"/favicon/apple-touch-icon-144x144.png"
link rel:"apple-touch-icon", sizes:"152x152", href: staticUrl"/favicon/apple-touch-icon-152x152.png"
link rel:"apple-touch-icon", sizes:"180x180", href: staticUrl"/favicon/apple-touch-icon-180x180.png"
link rel:"icon", type:"image/png", href: staticUrl"/favicon/favicon-32x32.png", sizes:"32x32"
link rel:"icon", type:"image/png", href: staticUrl"/favicon/android-chrome-192x192.png", sizes:"192x192"
link rel:"icon", type:"image/png", href: staticUrl"/favicon/favicon-96x96.png", sizes:"96x96"
link rel:"icon", type:"image/png", href: staticUrl"/favicon/favicon-16x16.png", sizes:"16x16"
link rel:"manifest", href: staticUrl"/favicon/manifest.json"
link rel:"mask-icon", href: staticUrl"/favicon/safari-pinned-tab.svg", color:"#171010"
link rel:"shortcut icon", href: staticUrl"/favicon/favicon.ico"
meta name:"apple-mobile-web-app-title", content:appname
meta name:"application-name", content:appname
meta name:"msapplication-TileColor", content:"#000000"
meta name:"msapplication-TileImage", content: staticUrl"/favicon/mstile-144x144.png"
meta name:"msapplication-config", content: staticUrl"/favicon/browserconfig.xml"
meta name:"theme-color", content:"#171010"
| 58.526316 | 108 | 0.69964 |
d1ddee93ff5a0f6db80f6eb05e22dda4418e481c | 721 | ----------------------------------------------------------------
-- Holds a string value and is used by the Compiler to print
-- out literal string text without having quotes in the output.
--
-- @classmod LiteralString
-- @author Richard Voelker
-- @license MIT
----------------------------------------------------------------
-- {{ TBSHTEMPLATE:BEGIN }}
class LiteralString
----------------------------------------------------------------
-- Create a new LiteralString.
--
-- @tparam LiteralString self
-- @tparam string s The string to output.
----------------------------------------------------------------
new: (s) =>
@_string = s
__tostring: => @_string
-- {{ TBSHTEMPLATE:END }}
return LiteralString
| 28.84 | 65 | 0.445215 |
91d092db7467e7b3a23799156d517796afb27074 | 1,385 | check_fuel = ->
print "Checking fuel..."
if turtle.getFuelLevel! < 500
print "Fuel low, refueling..."
turtle.suckUp!
turtle.refuel!
print("Fuel level: ", turtle.getFuelLevel!)
dump = ->
print "Dumping saplings..."
for i=1,16
turtle.select i
turtle.drop!
diorite = ->
success, data = turtle.inspectDown()
if (data.name == "minecraft:stone") and (data.metadata == 3)
return true
andesite = ->
success, data = turtle.inspectDown()
if (data.name == "minecraft:stone") and (data.metadata == 5)
return true
granite = ->
success, data = turtle.inspectDown()
if (data.name == "minecraft:stone") and (data.metadata == 1)
return true
-- (MAIN FUNCTION)
search = ->
--success, data = turtle.inspectDown()
unless diorite! or andesite! or granite!
turtle.suck!
turtle.forward!
--Detect DIORITE and turn RIGHT
if diorite!
turtle.turnRight!
turtle.forward!
--Detect ANDESITE and turn LEFT
if andesite!
turtle.turnLeft!
turtle.forward!
--Detect GRANITE and perform station actions
if granite!
turtle.turnRight!
turtle.up!
turtle.up!
dump!
check_fuel!
turtle.down!
turtle.down!
turtle.forward!
running = true
while running
search! | 21.307692 | 64 | 0.588448 |
c33b3a5980c6ebadc4b2f9f611e30ce024b14529 | 2,262 | -- Copyright 2012-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
import Chunk from howl
import PropertyObject from howl.util.moon
import style from howl.ui
class Context extends PropertyObject
new: (@buffer, @pos) =>
super!
@property word: get: =>
return @_word if @_word
start_pos, end_pos = @_get_word_boundaries!
@_word = Chunk @buffer, start_pos, end_pos - 1
@_word
@property token: get: =>
suffix = @suffix
prefix = @prefix
first = suffix[1]
start_pos, end_pos = @pos, @pos - 1
pfx_p, sfx_p = if first\match '%p' -- punctuation
'%p+$', '^%p+'
elseif first\match '%w' -- word
'%w+$', '^%w+'
elseif first\match '%S' -- non-blank
'%S+$', '^%S+'
if pfx_p
i = prefix\ufind pfx_p
start_pos = @pos - (#prefix - i + 1) if i
if sfx_p
_, i = suffix\ufind sfx_p
end_pos = @pos + i - 1 if i
Chunk(@buffer, start_pos, end_pos)
@property line: get: =>
@_line or= @buffer.lines\at_pos @pos
@_line
@property word_prefix: get: => @word.text\usub 1, @pos - @word.start_pos
@property word_suffix: get: => @word.text\usub (@pos - @word.start_pos) + 1
@property prefix: get: => @line\usub 1, (@pos - @line.start_pos)
@property suffix: get: => @line\usub (@pos - @line.start_pos) + 1
@property next_char: get: => @suffix[1]
@property prev_char: get: => @prefix[-1]
@property style: get: => style.at_pos @buffer, @pos
@meta {
__eq: (a, b) ->
t = typeof a
t == 'Context' and t == typeof(b) and a.buffer.id == b.buffer.id and a.pos == b.pos
__tostring: => "Context<#{tostring @buffer}@#{@pos}>"
}
_get_word_boundaries: =>
return @_get_boundaries @buffer\mode_at(@pos).word_pattern
_get_boundaries: (pattern) =>
line_text = @line.text
line_start_pos = @line.start_pos
line_pos = @pos - line_start_pos + 1
start_pos = 1
while start_pos <= line_pos
start_pos, end_pos = line_text\ufind pattern, start_pos
break unless start_pos
if start_pos <= line_pos and end_pos >= line_pos - 1
return @line.start_pos + start_pos - 1, @line.start_pos + end_pos
start_pos = end_pos + 1
return @pos, @pos
| 28.632911 | 89 | 0.62069 |
3fca1005694963403321cfc52bb3b0b501e92456 | 3,056 | -- title: Let's build a house
-- author: congusbongus
-- desc: Arrange helpers to pass building materials and build a house
-- script: moon
x=11
y=5
SW=240
SH=136
TW=16
TH=16
class Cursor
new:(x,y)=>
@counter=0
@delay=10
@x=x
@y=y
@lastx=x
@lasty=y
move:(dx,dy)=>
if dx==0 and dy==0
@counter = 0
return
if @counter > 0
@counter -= 1
return
moved = false
@lastx = @x
@lasty = @y
if dy<0 and @y>0
@y -= 1
moved = true
else if dy>0 and @y < SH/TH-1
@y += 1
moved = true
if dx<0 and @x>0
@x-=1
moved = true
else if dx>0 and @x < SW/TW-1
@x+=1
moved = true
if moved
@counter = @delay
draw:=>
d = @counter/@delay
d = d*d
x = (@x - (@x-@lastx)*d)*TW
y = (@y - (@y-@lasty)*d)*TH
spr(384,x,y,0,1,0,0,2,2)
cursor=Cursor(11,5)
class Map
new:=>
draw:=>
-- Draw a grid
for x=0,SW,TW
line(x,0,x,SH,8)
for y=0,SH,TH do
line(0,y,SW,y,8)
map=Map()
export TIC=->
dx = 0
dy = 0
if btn(0)
dy = -1
else if btn(1)
dy = 1
if btn(2)
dx = -1
else if btn(3)
dx = 1
cursor\move(dx, dy)
cls(13)
map\draw!
cursor\draw!
print("HELLO WORLD!",84,84)
-- <SPRITES>
-- 000:0000000b000000bb00000bbb0000bbbb000bbbbb00bbbbbb0bbbbbbbbbbbbbbb
-- 001:b0000000bb000000bbb00000bbbb0000bbbbb000bbbbbb00bbbbbbb0bbbbbbbb
-- 016:0000bbbb0000bbbb0000bbbb0000bbbb0000bbbb0000bbbb0000bbbb0000bbbb
-- 017:bbbb0000bbbb0000bbbb0000bbbb0000bbbb0000bbbb0000bbbb0000bbbb0000
-- 032:00000000000000000000000000000000bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
-- 033:b0000000bb000000bbb00000bbbb0000bbbbb000bbbbbb00bbbbbbb0bbbbbbbb
-- 048:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb00000000000000000000000000000000
-- 049:bbbbbbbbbbbbbbb0bbbbbb00bbbbb000bbbb0000bbb00000bb000000b0000000
-- 064:0000bbbb0000bbbb0000bbbb0000bbbb0000bbbb0000bbbb0000bbbb0000bbbb
-- 065:bbbb0000bbbb0000bbbb0000bbbb0000bbbb0000bbbb0000bbbb0000bbbb0000
-- 080:bbbbbbbb0bbbbbbb00bbbbbb000bbbbb0000bbbb00000bbb000000bb0000000b
-- 081:bbbbbbbbbbbbbbb0bbbbbb00bbbbb000bbbb0000bbb00000bb000000b0000000
-- 096:0000000b000000bb00000bbb0000bbbb000bbbbb00bbbbbb0bbbbbbbbbbbbbbb
-- 097:00000000000000000000000000000000bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
-- 112:bbbbbbbb0bbbbbbb00bbbbbb000bbbbb0000bbbb00000bbb000000bb0000000b
-- 113:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb00000000000000000000000000000000
-- 128:0077770007ffff707ff777007f7000007f7000007f7000000700000000000000
-- 129:0077770007ffff7000777ff7000007f7000007f7000007f70000007000000000
-- 144:00000000070000007f7000007f7000007f7000007ff7770007ffff7000777700
-- 145:0000000000000070000007f7000007f7000007f700777ff707ffff7000777700
-- </SPRITES>
-- <WAVES>
-- 000:00000000ffffffff00000000ffffffff
-- 001:0123456789abcdeffedcba9876543210
-- 002:0123456789abcdef0123456789abcdef
-- </WAVES>
-- <SFX>
-- 000:000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000304000000000
-- </SFX>
-- <PALETTE>
-- 000:140c1c44243430346d4e4a4e854c30346524d04648757161597dced27d2c8595a16daa2cd2aa996dc2cadad45edeeed6
-- </PALETTE>
| 24.253968 | 139 | 0.768652 |
9ed8b905ed777b54aa281558a1c090437d5d47f1 | 4,520 | -- index.moon
lapis = require "lapis"
import Widget from require "lapis.html"
util = require "lapis.util"
class extends Widget
content: =>
div class:"landing1",style:"background-image: linear-gradient(-190deg, #101010 1%, #777777 100%) !important;",->
div class:"container hero",->
div class:"row",->
div class:"col-md-6 left",->
h1 "Build the best software tools & services with us"
ul ->
li "Mobile & Web Apps",->
span id:"tools",""
li "Discover new tools and services"
p "Left"
div class:"col-md-6 right",->
-- ๋ฐ๋ฒจ๋ฆฌ์ด
div class:"col-md-12 hero-tool flex_con_c",->
div class:"col-md-3",->
img class:"img-responsive img-round", src:"/img/bbl3_80.png"
div class:"col-md-8",->
h3 "Babelier"
p class:"text-gray","Collective Translation Community"
div class:"col-md-1",->
-- button class:"btn btn-sm btn-transparent borderless",type:"submit",value:"Contact Us",->
-- i class:"glyphicon glyphicon-share-alt"
a href:"http://www.babelier.com",->
i class:"glyphicon glyphicon-share-alt"
-- ๊ณตํธ๋ ์ด๋
div class:"col-md-12 hero-tool flex_con_c",->
div class:"col-md-3",->
img class:"img-responsive img-round", src:"/img/gong_72_48.png"
img class:"img-responsive img-round", src:"/img/trader_78_44.png"
div class:"col-md-8",->
h3 "Gong Trader"
p class:"text-gray","The Social Trading Platform"
div class:"col-md-1",->
a href:"http://www.gongtrader.com",->
i class:"glyphicon glyphicon-share-alt"
-- ์ฝ์ค์ฝค Open API
div class:"col-md-12 hero-tool flex_con_c",->
div class:"col-md-3",->
img class:"img-responsive img-round", src:"/img/logo_koscom.png"
div class:"col-md-8",->
h3 "Financial Open API"
p class:"text-gray","Financial Information Open API via HTTP/WebSockets"
div class:"col-md-1",->
a href:"http://www.koscom.com",->
i class:"glyphicon glyphicon-share-alt"
-- div class:"landing1",style:"background-image: linear-gradient(-190deg, #101010 1%, #777777 100%) !important;",->
div class:"landing1",style:"background-color: #fff !important;",->
div class:"container white_hero",->
div class:"row text-center",->
-- h1 "True Open-Source Solutions"
div class:"col-md-6 left",style:"padding: 48px;",->
img class:"img-responsive img-rect", src:"/img/ss_tools.jpg"
div class:"col-md-6 right",->
h1 "All the best software tools and cloud infrastructure services in one studio"
-- Contact
div class:"landing1",style:"background-image: url('/img/black_tile_01.jpg');",->
div class:"container hero",->
div class:"row",->
h1 "Contact Us"
div class:"col-md-6",id:"contact",->
h3 class:"text-gray","Send Message"
-- br!
form action:"http://mailthis.to/sangmin.lna@gmail.com",method:"post",->
div ->
label for:"email", "Your Email:"
br!
input type:"email",name:"email",id:"name",placeholder:"youraddress@yourdomain.com",style:"width:100%;color: black;"
br!
div ->
label for:"message","Message:"
br!
textarea rows:"12",name:"message",style:"width:100%;color: black;",placeholder:"write your messages"
div ->
-- button type:"submit",value:"Contact Us"
-- input type:"submit",value:"Contact Us"
button class:"btn btn-default btn-sm btn-transparent borderless",type:"submit",value:"Contact Us",->
i class:"glyphicon glyphicon-envelope",
" Contact Us"
div class:"col-md-6",id:"about",->
h3 class:"text-gray","About Us"
div ->
p "๊ณต์คํ๋์ค๋ ๋ค์ํ ๋ชจ๋ฐ์ผ / ์น ์๋น์ค๋ค์ ๊ฐ๋ฐํ๊ณ ์์ต๋๋ค."
-- Carousel
div class:"landing1",style:"background-color: #fff !important;",->
div class:"container white_hero",->
div class:"row",->
div class:"col-md-12",->
h1 "Carousel"
| 43.461538 | 131 | 0.531858 |
c7ff88485830d0fbf4cb3b9c6d96ec3fe05d3872 | 507 | config = (require "lapis.config").get!
appname=config.appname or "nonchip.de"
class MixinFavicon
mixFavicon: ()-> --http://realfavicongenerator.net/
raw [[
<link rel="icon" type="image/gif" href="/static/favicon.gif" sizes="16x16">
<link rel="shortcut icon" href="/static/favicon.gif">
<meta name="apple-mobile-web-app-title" content="]]..appname..[[">
<meta name="application-name" content="]]..appname..[[">
<meta name="theme-color" content="#000000">
]]
| 42.25 | 83 | 0.629191 |
bef8be576ac41aebd736a1fce86ee1805d59801f | 9,646 | -- Copyright 2014-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
flair = require 'aullar.flair'
callbacks = require 'ljglibs.callbacks'
cast_arg = callbacks.cast_arg
ffi = require 'ffi'
C = ffi.C
flair.define_default 'cursor', {
type: flair.RECTANGLE,
background: '#000000',
width: 1.5,
height: 'text'
}
flair.define_default 'block_cursor', {
type: flair.RECTANGLE,
foreground: '#c3c3c3',
background: '#000000',
background_alpha: 0.5,
min_width: 5,
height: 'text'
text_color: '#dddddd'
}
flair.define_default 'inactive_cursor', {
type: flair.RECTANGLE,
foreground: '#cc3333',
min_width: 5,
line_width: 1,
height: 'text',
}
{:max, :min, :abs} = math
{:define_class} = require 'aullar.util'
timer_callback = ffi.cast 'GSourceFunc', callbacks.bool1
is_showing_line = (view, line) ->
line >= view.first_visible_line and line <= view.last_visible_line
pos_is_in_line = (pos, line) ->
pos >= line.start_offset and (pos <= line.end_offset or not line.has_eol)
Cursor = {
new: (@view, @selection) =>
@width = 1.5
@show_when_inactive = true
@_blink_interval = 500
@_line = 1
@_column = 1
@_pos = 1
@_active = false
@_showing = true
@_sticky_x = nil
@_style = 'line'
@_flair = 'cursor'
properties: {
display_line: => @view.display_lines[@line]
buffer_line: => @view.buffer\get_line @line
style: {
get: => @_style
set: (style) =>
return if style == @_style
if style == 'block'
@_flair = 'block_cursor'
elseif style == 'line'
@_flair = 'cursor'
else
error 'Invalid style ' .. style, 2
@_style = style
@_refresh_current_line!
}
blink_interval: {
get: => @_blink_interval
set: (interval) =>
@_disable_blink!
@_blink_interval = interval
@_showing = true
@_enable_blink! if interval > 0
}
line: {
get: => @_line
set: (line) => @move_to :line
}
column: {
get: => (@pos - @buffer_line.start_offset) + 1
set: (column) => @move_to pos: @buffer_line.start_offset + column - 1
}
pos: {
get: => @_pos
set: (pos) => @move_to :pos
}
active: {
get: => @_active
set: (active) =>
return if active == @_active
if active
@_flair = @_prev_flair if @_prev_flair
@_enable_blink!
@_showing = true
else
@_disable_blink!
if @show_when_inactive
@_prev_flair = @_flair
@_flair = 'inactive_cursor'
@_showing = true
else
@_prev_flair = @_flair
@_showing = false
@_active = active
@_refresh_current_line!
}
in_view: =>
@line >= @view.first_visible_line and @line <= @view.last_visible_line
}
ensure_in_view: =>
return if @in_view
new_line = if @line < @view.first_visible_line
@view.first_visible_line
else
@view.last_visible_line
@move_to line: new_line
remember_column: =>
cur_rect = @display_line.layout\index_to_pos @column - 1
@_sticky_x = cur_rect.x
in_line: (line) =>
pos_is_in_line @_pos, line
move_to: (opts) =>
pos = opts.pos
if opts.line
line_nr = max(1, min(opts.line, @view.buffer.nr_lines))
b_line = @view.buffer\get_line line_nr
if b_line
pos = b_line.start_offset
pos += (opts.column - 1) if opts.column
if pos
pos = max min(@view.buffer.size + 1, pos), 1
else
error("Illegal argument #1 to Cursor.move_to (pos: #{opts.pos}, line: #{opts.line}, column: #{opts.column})", 2)
return if pos == @_pos
extend_selection = opts.extend or @selection.persistent
if not extend_selection and not @selection.is_empty
@selection\clear!
old_line = @buffer_line
unless old_line -- old pos/line is gone
@_pos = @view.buffer.size + 1
@_line = @view.buffer.nr_lines
old_line = @view.buffer\get_line(@_line)
-- are we moving to another line?
if not pos_is_in_line(pos, old_line) or not is_showing_line @view, old_line.nr
dest_line = @view.buffer\get_line_at_offset pos
@_line = dest_line.nr
if is_showing_line @view, dest_line.nr
if abs(dest_line.nr - old_line.nr) == 1 -- moving to an adjacent line, do one refresh
@view\refresh_display min(dest_line.start_offset, old_line.start_offset), max(dest_line.end_offset, old_line.end_offset)
else -- separated lines, refresh each line separately
@view\refresh_display old_line.start_offset, old_line.end_offset
@view\refresh_display dest_line.start_offset, dest_line.end_offset
else -- scroll
if dest_line.nr < @view.first_visible_line
@view.first_visible_line = dest_line.nr
else
@view.last_visible_line = dest_line.nr
-- adjust for the remembered column if appropriate
if @_sticky_x and (opts.line and not opts.column)
inside, index = @display_line.layout\xy_to_index @_sticky_x, 1
index = @display_line.size if not inside and index > 0 -- move to the ending new line
pos = dest_line.start_offset + index
else -- staying on same line, refresh it
@view\refresh_display old_line.start_offset, old_line.end_offset
if extend_selection
@selection\extend @_pos, pos
@_pos = pos
@_force_show = true
@_showing = true
if not opts.line or not @_sticky_x
@remember_column!
-- finally, do we need to scroll horizontally to show the new position?
rect = @display_line.layout\index_to_pos @column - 1
col_pos = rect.x / 1024
char_width = rect.width / 1024
x_pos = col_pos - @view.base_x + @view.edit_area_x + @width
if @view.width and x_pos + char_width > @view.width -- scroll to the right
@view.base_x = col_pos - @view.edit_area_width + char_width + @width
elseif x_pos < @view.edit_area_x -- scroll to the left
@view.base_x = col_pos
-- alert listener if set
if @listener and @listener.on_pos_changed
@listener.on_pos_changed @listener, self
start_of_file: (opts = {}) =>
@move_to pos: 1, extend: opts.extend
end_of_file: (opts = {}) =>
@move_to pos: @view.buffer.size + 1, extend: opts.extend
forward: (opts = {}) =>
return if @_pos > @view.buffer.size
line_start = @buffer_line.start_offset
z_col = (@_pos - line_start)
new_index, new_trailing = @display_line.layout\move_cursor_visually true, z_col, 0, 1
new_index = @display_line.size if new_trailing > 0
if new_index > @display_line.size
@move_to pos: @pos + 1, extend: opts.extend
else
@move_to pos: line_start + new_index, extend: opts.extend
backward: (opts = {}) =>
return if @_pos == 1
line_start = @buffer_line.start_offset
z_col = (@_pos - line_start)
new_index = @display_line.layout\move_cursor_visually true, z_col, 0, -1
@move_to pos: line_start + new_index, extend: opts.extend
up: (opts = {}) =>
prev = @line - 1
if prev >= 1
@move_to line: prev, extend: opts.extend
down: (opts = {}) =>
next = @line + 1
if next <= @view.buffer.nr_lines
@move_to line: next, extend: opts.extend
page_up: (opts = {}) =>
if @view.first_visible_line == 1
@start_of_file opts
return
first_visible = max(@view.first_visible_line - @view.lines_showing, 1)
cursor_line_offset = max(@line - @view.first_visible_line, 0)
@view.first_visible_line = first_visible
@move_to line: first_visible + cursor_line_offset, extend: opts.extend
page_down: (opts = {}) =>
if @view.last_visible_line == @view.buffer.nr_lines
@end_of_file opts
return
cursor_line_offset = max(@line - @view.first_visible_line, 0)
first_visible = min(@view.last_visible_line, @view.buffer.nr_lines - (@view.lines_showing - 1))
@view.first_visible_line = first_visible
@move_to line: first_visible + cursor_line_offset, extend: opts.extend
start_of_line: (opts = {}) =>
@move_to pos: @buffer_line.start_offset, extend: opts.extend
end_of_line: (opts = {}) =>
@move_to pos: @buffer_line.start_offset + @buffer_line.size, extend: opts.extend
draw: (x, base_y, cr, display_line) =>
return unless @_showing and (@active or @show_when_inactive)
start_offset = @column
end_offset, new_trailing = display_line.layout\move_cursor_visually true, start_offset - 1, 0, 1
if new_trailing > 0 or end_offset > display_line.size + 1
end_offset = display_line.size + 1
else
end_offset += 1
flair.draw @_flair, display_line, start_offset, end_offset, x, base_y, cr
_blink: =>
return false if not @active
if @_force_show
@_force_show = false
return true
@_showing = not @_showing
@_refresh_current_line!
true
_get_line: (nr) =>
@view.buffer\get_line nr
_enable_blink: =>
return if @_blink_cb_handle
jit.off true, true
@_blink_cb_handle = callbacks.register self._blink, "cursor-blink", @
@blink_cb_id = C.g_timeout_add_full C.G_PRIORITY_LOW, @blink_interval, timer_callback, cast_arg(@_blink_cb_handle.id), nil
_disable_blink: =>
if @_blink_cb_handle
callbacks.unregister @_blink_cb_handle
@_blink_cb_handle = nil
-- todo unregister source? will be auto-cancelled by callbacks module though
_refresh_current_line: =>
cur_line = @buffer_line
@view\refresh_display cur_line.start_offset, cur_line.end_offset
}
define_class Cursor
| 29.230303 | 130 | 0.647937 |
e4dd7796eb05814e648a041d7c09bebbb071b9f1 | 2,357 | db = require "lapis.db.mysql"
import BaseModel, Enum, enum from require "lapis.db.base_model"
import preload from require "lapis.db.model.relations"
class Model extends BaseModel
@db: db
@columns: =>
columns = @db.query "
SHOW COLUMNS FROM #{@db.escape_identifier @table_name!}
"
columns = [c for c in *columns] -- strip extra data from query
@columns = -> columns
columns
-- create from table of values, return loaded object
@create: (values, opts) =>
if @constraints
for key in pairs @constraints
if err = @_check_constraint key, values and values[key], values
return nil, err
if @timestamp
time = @db.format_date!
values.created_at or= time
values.updated_at or= time
res = db.insert @table_name!, values, @primary_keys!
if res
-- FIXME this code works only if mysql backend is
-- either luasql (field res.last_auto_id) or
-- lua-resty-mysql (field res.insert_id) and
new_id = res.last_auto_id or res.insert_id
if not values[@primary_key] and new_id and new_id != 0
values[@primary_key] = new_id
@load values
else
nil, "Failed to create #{@__name}"
@find_all: (...) =>
res = BaseModel.find_all @, ...
if res[1]
-- strip out extra data from query
[r for r in *res]
else
res
-- thing\update "col1", "col2", "col3"
-- thing\update {
-- "col1", "col2"
-- col3: "Hello"
-- }
update: (first, ...) =>
cond = @_primary_cond!
columns = if type(first) == "table"
for k,v in pairs first
if type(k) == "number"
v
else
@[k] = v
k
else
{first, ...}
return nil, "nothing to update" if next(columns) == nil
if @@constraints
for _, column in pairs columns
if err = @@_check_constraint column, @[column], @
return nil, err
values = { col, @[col] for col in *columns }
-- update options
nargs = select "#", ...
last = nargs > 0 and select nargs, ...
opts = if type(last) == "table" then last
if @@timestamp and not (opts and opts.timestamp == false)
time = @@db.format_date!
values.updated_at or= time
res = db.update @@table_name!, values, cond
(res.affected_rows or 0) > 0, res
{ :Model, :Enum, :enum, :preload }
| 25.901099 | 71 | 0.591854 |
3027a600345ca9af58a37f7fc9b154f96226c6e6 | 16,210 | -- Copyright 2016-2017 Nils Nordman <nino@nordman.org>
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
moonpick = require 'moonpick'
describe 'moonpick', ->
clean = (code) ->
initial_indent = code\match '^([ \t]*)%S'
code = code\gsub '\n\n', "\n#{initial_indent}\n"
lines = [l\gsub("^#{initial_indent}", '') for l in code\gmatch('[^\n]+')]
code = table.concat lines, '\n'
code = code\match '^%s*(.-)%s*$'
code .. '\n'
lint = (code, opts) ->
inspections = assert moonpick.lint code, opts
res = {}
for i in *inspections
{:line, :msg} = i
res[#res + 1] = :line, :msg
res
describe 'unused variables', ->
it 'detects unused variables', ->
code = 'used = 2\nfoo = 2\nused'
res = lint code, {}
assert.same {
{line: 2, msg: 'declared but unused - `foo`'}
}, res
it 'handles multiple assignments', ->
code = 'a, b = 1, 2\na'
res = lint code, {}
assert.same {
{line: 1, msg: 'declared but unused - `b`'}
}, res
it 'does not report variable used in a different scope', ->
code = clean [[
a = 1
->
a + 1
]]
res = lint code, {}
assert.same {}, res
it 'detects function scoped, unused variables', ->
code = clean [[
x = -> a = 1
y = -> a = 1
x + y
]]
res = lint code, {}
assert.same {
{line: 1, msg: 'declared but unused - `a`'}
{line: 2, msg: 'declared but unused - `a`'}
}, res
it 'detects control flow scoped, unused variables', ->
code = clean [[
if _G.foo
x = 2
elseif _G.zed
x = 1
else
x = 1
unless _G.bar
x = 3
x
]]
res = lint code, {}
assert.same {
{line: 2, msg: 'declared but unused - `x`'}
{line: 4, msg: 'declared but unused - `x`'}
{line: 6, msg: 'declared but unused - `x`'}
{line: 8, msg: 'declared but unused - `x`'}
{line: 9, msg: 'accessing global - `x`'}
}, res
it 'detects unused variables in with statements', ->
code = clean [[
with _G.foo
x = 1
with _G.bar
x = 2
x = 3
x
]]
res = lint code, {}
assert.same {
{line: 2, msg: 'declared but unused - `x`'}
{line: 4, msg: 'declared but unused - `x`'}
}, res
it 'detects while scoped unused variables', ->
code = clean [[
while true
x = 1
break
]]
res = lint code, {}
assert.same {
{line: 2, msg: 'declared but unused - `x`'}
}, res
it 'accounts for implicit returns', ->
code = clean [[
x = 1
->
y = 1
y
x
]]
res = lint code, {}
assert.same {}, res
it 'handles inline with variable assignment statements', ->
code = clean [[
with foo = 2
foo += 3
]]
res = lint code, {}
assert.same {}, res
it 'detects unused function parameters if requested', ->
code = '(foo) -> 2'
res = lint code, report_params: true
assert.same {
{line: 1, msg: 'declared but unused - `foo`'}
}, res
it 'detects usages in parameter lists', ->
code = clean [[
x = 1
(v = x)->
v
]]
res = lint code
assert.same {}, res
it 'does not complain about varargs', ->
code = clean [[
(...) ->
...
]]
res = lint code, {}
assert.same {}, res
it 'respects a given whitelist_params', ->
code = clean '(x) -> 1'
res = lint code, { whitelist_params: {'x'} }
assert.same {}, res
it 'respects a given whitelist_loop_variables', ->
code = clean 'for x in *{1,2}\n _G.other = 1'
res = lint code, { whitelist_loop_variables: {'x'} }
assert.same {}, res
it 'does not complain about @variables in methods', ->
code = clean [[
class Foo
new: (@bar) =>
other: (@zed) =>
Foo
]]
res = lint code
assert.same {}, res
it 'detects unused class definitions', ->
code = clean [[
class Foo extends _G.Bar
new: =>
{}
]]
res = lint code, {}
assert.same {
{line: 1, msg: 'declared but unused - `Foo`'}
}, res
it 'detects implicit returns of class definitions', ->
code = clean [[
class Foo
new: =>
]]
res = lint code, {}
assert.same {
}, res
it 'detects dotted assignment references', ->
code = clean [[
(arg) ->
arg.foo = .zed
]]
res = lint code
assert.same {}, res
it 'handles local declarations', ->
code = clean [[
local x, y
->
x = 2
y = 1
y + x
]]
res = lint code
assert.same {}, res
it 'handles export declarations', ->
code = clean [[
export foo
->
foo = 2
y = 1
export zed = ->
y + 2
]]
res = lint code
assert.same {}, res
it 'handles wildcard export declarations', ->
code = clean [[
x = 1
export *
y = 2
]]
res = lint code
assert.same {
{line: 1, msg: 'declared but unused - `x`'}
}, res
it 'detects indexing references', ->
code = clean [[
(foo) ->
_G[foo] = 2
]]
res = lint code
assert.same {}, res
it 'detects unused imports', ->
code = clean [[
import foo from _G.bar
import \func from _G.thing
]]
res = lint code
assert.same {
{line: 1, msg: 'declared but unused - `foo`'}
{line: 2, msg: 'declared but unused - `func`'}
}, res
it 'detects usages in import source lists', ->
code = clean [[
ffi = require 'ffi'
import C from ffi
C
]]
res = lint code
assert.same {}, res
it 'detects unused destructured variables', ->
code = clean [[
{:foo} = _G.bar
{bar: other} = _G.zed
{frob} = {1,2}
{numbers: {first}} = _G.frob
{props: {color: my_col}} = _G.what
]]
res = lint code, {}
assert.same {
{line: 1, msg: 'declared but unused - `foo`'}
{line: 2, msg: 'declared but unused - `other`'}
{line: 3, msg: 'declared but unused - `frob`'}
{line: 4, msg: 'declared but unused - `first`'}
{line: 5, msg: 'declared but unused - `my_col`'}
}, res
code = '{:foo, :bar} = _G.bar'
res = lint code, {}
assert.equal 2, #res
it 'detects unused variables in ordinary loops', ->
code = clean [[
for foo = 1,10
_G.other!
for foo = 1,10
_G.other foo
]]
res = lint code, {}
assert.same {
{line: 1, msg: 'declared but unused - `foo`'}
}, res
it 'detects unused variables in for each loops', ->
code = clean [[
for foo in *{2, 3}
_G.other!
]]
res = lint code, {}
assert.same {
{line: 1, msg: 'declared but unused - `foo`'}
}, res
it 'detects unused destructured variables in for each loops', ->
code = clean [[
for {foo} in *{2, 3}
_G.other!
for {:bar} in *{2, 3}
_G.other!
for {bar: zed} in *{2, 3}
_G.other!
]]
res = lint code
assert.same {
{line: 1, msg: 'declared but unused - `foo`'}
{line: 4, msg: 'declared but unused - `bar`'}
{line: 7, msg: 'declared but unused - `zed`'}
}, res
it 'does not warn for used vars in decorated statements', ->
code = clean [[
_G[a] = nil for a in *_G.list
]]
res = lint code, {}
assert.same {}, res
it 'detects variable usages correctly in comprehensions', ->
code = clean [[
[x * 2 for x in *_G.foo]
]]
res = lint code, {}
assert.same {}, res
it 'detects variable usages correctly in for comprehensions', ->
code = clean [[
[tostring(l) for l = 1, 100]
]]
res = lint code
assert.same {}, res
it 'detects variable usages correctly in comprehensions 2', ->
code = clean [[
[name for name in pairs _G.foo]
]]
res = lint code
assert.same {}, res
it 'detects variable usages correctly in hash comprehensions', ->
code = clean [[
{k, _G.foo[k] for k in *{1,2}}
]]
res = lint code
assert.same {}, res
describe 'undeclared access', ->
it 'detected undeclared accesses', ->
code = 'foo!'
res = lint code, {}
assert.same {
{line: 1, msg: 'accessing global - `foo`'}
}, res
it 'detected undeclared accesses for chained expressions', ->
code = 'foo.x'
res = lint code, {}
assert.same {
{line: 1, msg: 'accessing global - `foo`'}
}, res
it 'reports each undeclared usage separately', ->
code = clean [[
x 1
x 2
]]
res = lint code, {}
assert.same {
{line: 1, msg: 'accessing global - `x`'}
{line: 2, msg: 'accessing global - `x`'}
}, res
it 'includes built-ins in the global whitelist', ->
code = clean [[
x = tostring(_G.foo)
y = table.concat {}, '\n'
x + y
]]
res = lint code
assert.same {}, res
it 'allows access to self and super in methods', ->
code = clean [[
class Foo
meth: =>
self.bar!
super!
]]
res = lint code
assert.same {}, res
it 'allows access to self in methods and sub scopes thereof', ->
code = clean [[
class Foo
meth: =>
if true
self.bar!
]]
res = lint code
assert.same {}, res
it 'disallows access to self in functions', ->
code = clean [[
->
self.bar!
]]
res = lint code
assert.same {
{line: 2, msg: 'accessing global - `self`'}
}, res
it 'handles variabled assigned with statement modifiers correctly', ->
code = clean [[
x = _G.foo if true
x
]]
res = lint code
assert.same {}, res
code = clean [[
x = _G.foo unless false
x
]]
res = lint code
assert.same {}, res
it 'handles variabled assigned with statement modifiers correctly', ->
code = clean [[
x or= _G.foo
y or= _G.bar\zed!
x + y
]]
res = lint code
assert.same {}, res
it 'handles variables assigned with destructuring correctly', ->
code = clean [[
{foo, bar} = _G.zed
foo + bar
]]
res = lint code
assert.same {}, res
it 'detects class parent references', ->
code = clean [[
import Base from _G
class I extends Base
]]
res = lint code
assert.same {}, res
it 'handles non-prefixed member access', ->
code = clean [[
class Foo
bar: (@x = 'zed') =>
x
]]
res = lint code
assert.same {}, res
it 'handles loop modified statements', ->
code = clean [[
_G.foo[t] = true for t in pairs {}
t! for t in *{}
_G.foo += i for i = 1, 10
]]
res = lint code
assert.same {}, res
it 'handles "with" statement assignments', ->
code = clean [[
with x = 2
.y + 2
]]
res = lint code
assert.same {}, res
it 'handles while scoped unused variables', ->
code = clean [[
while true
x = 1
if x
break
x
]]
res = lint code, {}
assert.same {
{line: 5, msg: 'accessing global - `x`'}
}, res
describe 'format_inspections(inspections)', ->
it 'returns a string representation of inspections', ->
code = clean [[
{:foo} = _G.bar
{bar: other} = _G.zed
]]
inspections = assert moonpick.lint code, {}
assert.same clean([[
line 1: declared but unused - `foo`
===================================
> {:foo} = _G.bar
line 2: declared but unused - `other`
=====================================
> {bar: other} = _G.zed
]]), moonpick.format_inspections(inspections)
describe 'shadowing warnings', ->
it 'detects shadowing outer variables in for each', ->
code = clean [[
x = 2
for x in *{1,2}
_G.other x
x
]]
res = lint code, {}
assert.same {
{line: 2, msg: 'shadowing outer variable - `x`'}
}, res
it 'detects shadowing using local statements', ->
code = clean [[
x = 2
->
local x
x = 2
x * 2
x
]]
res = lint code, {}
assert.same {
{line: 3, msg: 'shadowing outer variable - `x`'}
}, res
it 'understand lexical scoping', ->
code = clean [[
for x in *{1,2}
_G.other x
x = 2 -- defined after previous declaration
x
]]
res = lint code, {}
assert.same {}, res
it 'rvalue declaration values generally does not shadow lvalues', ->
code = clean [[
x = { -- assignment lvalue target
f: (x) -> -- this is part of the rvalue
}
x
]]
res = lint code, {}
assert.same {}, res
it 'implicitly local lvalue declarations are recognized (i.e. fndefs)', ->
code = clean [[
f = (x) -> x + f(x + 1)
f
]]
res = lint code, {}
assert.same {}, res
it 'does not complain about foreach comprehension vars shadowing target', ->
code = clean [[
for x in *[x for x in *_G.foo when x != 'bar' ]
x!
]]
res = lint code, {}
assert.same {}, res
it 'handles scope shadowing and unused variables correctly', ->
code = clean [[
(a) ->
[ { a, b } for a, b in pairs {} ]
]]
res = lint code, report_params: true
assert.same {
{line: 1, msg: 'declared but unused - `a`'},
{line: 2, msg: 'shadowing outer variable - `a`'}
}, res
it 'handles shadowing with decorated statements correctly', ->
code = clean [[
x = 1
(arg) -> x! for x in *arg
]]
res = lint code, {}
assert.same {
{line: 1, msg: 'declared but unused - `x`'},
{line: 2, msg: 'shadowing outer variable - `x`'}
}, res
describe 'unwanted reassignments', ->
it 'detects overwriting function definitions', ->
code = clean [[
x = () ->
x = 2
x
]]
res = lint code
assert.same {
{line: 2, msg: 'reassigning function variable - `x`'}
}, res
context '(top level reassignments)', ->
it 'detects reassigning top level variable from within functions', ->
code = clean [[
x = 1
{:y} = require 'bar'
->
x = 2
y = 3
x + y
]]
res = lint code, report_top_level_reassignments: true
assert.same {
{line: 4, msg: 'reassigning top level variable within function - `x`'}
{line: 5, msg: 'reassigning top level variable within function - `y`'}
}, res
it 'allows reassigning non top level variables', ->
code = clean [[
->
x = 1
->
x = 2
x
]]
res = lint code, report_top_level_reassignments: true
assert.same {}, res
it 'allows reassigning unitialized top level variables', ->
code = clean [[
local x
export y
_, z = 1
->
x = 1
y = 2
x + y + z
]]
res = lint code, report_top_level_reassignments: true
assert.same {}, res
| 24.635258 | 80 | 0.475941 |
81d5870f6895b2ec11c74c890405e87baf1488d1 | 40 | (require "lapis.util").autoload "models" | 40 | 40 | 0.75 |
79fd6925d9fa884e57474e862b7671551d70b40f | 4,163 | build = () ->
contents = '[SlotBackground]
Meter=Image
SolidColor=0,0,0,1
X=([WindowBackground:X] + 2)
Y=([WindowBackground:Y] + #TitleBarHeight#)
W=([WindowBackground:W] - 3)
H=([WindowBackground:H] - #TitleBarHeight# - #ButtonHeight#)
MouseScrollUpAction=[!CommandMeasure "Script" "ScrollSlots(-1)"]
MouseScrollDownAction=[!CommandMeasure "Script" "ScrollSlots(1)"]
DynamicVariables=1
'
-- Scrollbar
contents ..= '
[ScrollBarBackground]
Meter=Image
SolidColor=#ScrollbarBackgroundColor#
X=([WindowBackground:X] + [WindowBackground:W] - #ScrollBarWidth#)
Y=([SlotBackground:Y])
W=#ScrollBarWidth#
H=([SlotBackground:H])
DynamicVariables=1
[ScrollBar]
Meter=Image
SolidColor=#ScrollbarColor#
X=([ScrollBarBackground:X] + 1)
Y=([ScrollBarBackground:Y] + 1)
W=([ScrollBarBackground:W] - 1)
H=([ScrollBarBackground:H] - 2)
DynamicVariables=1
'
-- FolderPath
contents ..= '
[FolderPathInput]
Measure=Plugin
Plugin=InputText
SolidColor=#WindowBackgroundColor#
X=0
Y=0
W=0
H=0
DefaultValue=
StringAlign=Left
StringStyle=Bold
FontSize=16
DynamicVariables=1'
for i = 1, STATE.NUM_SLOTS
contents ..= ('Command%d=[!CommandMeasure "Script" "EditFolderPath(%d, \'$UserInput$;\')"]\n')\format(i, i)
contents ..= '\n'
-- FolderPathSpinner
contents ..= '
[FolderPathSpinnerInput]
Measure=Plugin
Plugin=InputText
SolidColor=#WindowBackgroundColor#
X=0
Y=0
W=0
H=0
DefaultValue=
StringAlign=Left
StringStyle=Bold
FontSize=16
DynamicVariables=1'
for i = 1, STATE.NUM_SLOTS
contents ..= ('Command%d=[!CommandMeasure "Script" "EditFolderPathSpinner(%d, \'$UserInput$;\')"]\n')\format(i, i)
contents ..= '\n'
-- Integer
contents ..= '
[IntegerInput]
Measure=Plugin
Plugin=InputText
SolidColor=#WindowBackgroundColor#
X=0
Y=0
W=0
H=0
DefaultValue=
InputNumber=1
StringAlign=Left
StringStyle=Bold
FontSize=16
DynamicVariables=1
'
for i = 1, STATE.NUM_SLOTS
contents ..= ('Command%d=[!CommandMeasure "Script" "EditInteger(%d, \'$UserInput$\')"]\n')\format(i, i)
contents ..= '\n'
-- String
contents ..= '
[StringInput]
Measure=Plugin
Plugin=InputText
SolidColor=#WindowBackgroundColor#
X=0
Y=0
W=0
H=0
DefaultValue=
StringAlign=Left
StringStyle=Bold
FontSize=16
DynamicVariables=1'
for i = 1, STATE.NUM_SLOTS
contents ..= ('Command%d=[!CommandMeasure "Script" "EditString(%d, \'$UserInput$;\')"]\n')\format(i, i)
contents ..= '\n'
Settings = require('settings.types')
args = {
title: ''
tooltip: ''
}
settings = [Setting(args) for key, Setting in pairs(Settings)]
for i = 1, STATE.NUM_SLOTS
contents ..= table.concat({
-- Bounding box
('[Slot%dBoundingBox]')\format(i)
'Meter=Image'
'SolidColor=0,0,0,1'
'X=([SlotBackground:X])'
('Y=([SlotBackground:Y] + %d * [SlotBackground:H] / %d)')\format(i - 1, STATE.NUM_SLOTS)
'W=([SlotBackground:W] - #ScrollBarWidth# - 2)'
('H=([SlotBackground:H] / %d)')\format(STATE.NUM_SLOTS)
'DynamicVariables=1'
('Group=Slot%d')\format(i)
''
-- Tooltip
('[Slot%dToolTip]')\format(i)
'Meter=Image'
'ImageName=#@#settings\\gfx\\tooltip.png'
'SolidColor=0,0,0,1'
('X=([Slot%dBoundingBox:X] + 2)')\format(i)
('Y=([Slot%dBoundingBox:Y] + 8)')\format(i)
'W=16'
'H=16'
('ToolTipText=Slot %d')\format(i)
('Group=Slot%d')\format(i)
''
-- Title
('[Slot%dTitle]')\format(i)
'Meter=String'
('Text=Slot %d')\format(i)
'StringAlign=LeftCenter'
'SolidColor=0,0,0,1'
'X=2R'
'Y=8r'
'FontSize=16'
'AntiAlias=1'
'StringStyle=Bold'
('W=([Slot%dBoundingBox:W] - 24)')\format(i)
'H=32'
'ClipString=1'
'DynamicVariables=1'
('Group=Slot%d')\format(i)
'\n'
}, '\n')
-- Each type of setting
for setting in *settings
contents ..= setting\getInc(i)
if i < STATE.NUM_SLOTS
i += 1
contents ..= table.concat({
-- Separator
('[Slot%dSeparator]')\format(i)
'Meter=Image'
'SolidColor=#SlotSeparatorColor#'
'X=([WindowBackground:X] + 2)'
('Y=([Slot%dBoundingBox:Y] + [Slot%dBoundingBox:H] - 1)')\format(i - 1, i - 1)
('W=([Slot%dBoundingBox:W])')\format(i - 1)
'H=2'
'DynamicVariables=1'
('Group=Slot%d')\format(i)
'\n'
}, '\n')
return contents
return build
| 22.625 | 116 | 0.663464 |
4abb565dcf3ef857346a3a14db7ece519de4b4e5 | 5,706 | -- Copyright 2014-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
ffi = require 'ffi'
C, ffi_copy, ffi_fill, ffi_gc, ffi_cast = ffi.C, ffi.copy, ffi.fill, ffi.gc, ffi.cast
{:min} = math
{:define_class} = require 'aullar.util'
ffi.cdef [[
void *calloc(size_t nmemb, size_t size);
void free(void *ptr);
void *memmove(void *dest, const void *src, size_t n);
]]
GAP_SIZE = 100
define_class {
new: (@type, size, opts = {}) =>
@default_gap_size = opts.gap_size or GAP_SIZE
@type_size = ffi.sizeof type
@arr_ptr = ffi.typeof "const #{type} *"
@new_arr = (arr_size) ->
ffi_gc(ffi_cast("#{@type} *", C.g_malloc0(arr_size * @type_size)), C.g_free)
@set opts.initial, size
properties: {
gap_size: => (@gap_end - @gap_start)
}
get_ptr: (offset, size) =>
if offset < 0 or offset > (@size - 1) or (offset + size) > @size or size < 0
error "GapBuffer.get_ptr(): Illegal range: offset=#{offset}, size=#{size} for buffer of size #{@size}", 2
if offset >= @gap_start -- post gap ptr
@array + @gap_size + offset, false
elseif offset + size <= @gap_start -- pre gap ptr
@array + offset, false
else -- ephemeral copy pointer
if size == @size
@compact!
@get_ptr(offset, size), true
else
arr = self.new_arr(size + 1)
pregap_size = @gap_start - offset
postgap_size = size - pregap_size
ffi_copy arr, @array + offset, pregap_size * @type_size
ffi_copy arr + pregap_size, @array + @gap_end, postgap_size * @type_size
arr[size] = 0
arr, false
move_gap_to: (offset) =>
if offset < 0 or offset > @size
error "GapBuffer#move_gap_to: Illegal offset #{offset} (size #{@size})", 2
delta = offset - @gap_start
return if delta == 0
if delta < 0 -- offset < gap start, move stuff up
dest = @array + @gap_end + delta
src = @array + offset
C.memmove dest, src, (-delta) * @type_size
else -- offset > gap start, move stuff down
C.memmove @array + @gap_start, @array + @gap_end, delta * @type_size
gap_size = @gap_size
@gap_start = offset
@gap_end = offset + gap_size
ffi_fill @array + @gap_start, @gap_size * @type_size
extend_gap_at: (offset, gap_size) =>
if offset < 0 or offset > @size
error "GapBuffer#extend_gap_at: Illegal offset #{offset} (size #{@size})", 2
arr_size = @size + gap_size
arr = self.new_arr arr_size
src_ptr = @array
dest_ptr = arr
-- chunk up to gap start or offset
count = min(tonumber(@gap_start), tonumber(offset))
ffi_copy dest_ptr, src_ptr, count * @type_size
-- fill from current post gap if the new gap is above the old
if @gap_start < offset
src_ptr = @array + @gap_end
dest_ptr += count
count = offset - count
ffi_copy dest_ptr, src_ptr, count * @type_size
-- now at dest post gap
src_ptr += count
dest_ptr = arr + offset + gap_size
if @gap_start > offset -- fill remainder from pre gap
count = @gap_start - offset
ffi_copy dest_ptr, src_ptr, count * @type_size
src_ptr = @array + @gap_end
dest_ptr += count
elseif @gap_start == offset
src_ptr = @array + @gap_end
-- the rest
count = (arr + arr_size) - dest_ptr
if count > 0
ffi_copy dest_ptr, src_ptr, count * @type_size
@array = arr
@gap_start = offset
@gap_end = offset + gap_size
compact: =>
@move_gap_to @size
insert: (offset, data, size = #data) =>
return if size == 0
if offset < 0 or offset > @size
error "GapBuffer#insert: Illegal offset #{offset} (size #{@size})", 2
if size <= @gap_size
@move_gap_to offset
else
@extend_gap_at offset, size + @default_gap_size
if data
ffi_copy @array + @gap_start, self.arr_ptr(data), size * @type_size
else
ffi_fill @array + @gap_start, size * @type_size
@size += size
@gap_start += size
delete: (offset, count) =>
return if count == 0 or offset >= @size
if offset == @gap_end - @gap_size -- adjust gap end forward
ffi_fill @array + @gap_end, count * @type_size -- zero fill
@gap_end += count
else
if offset + count == @gap_start -- adjust gap start backwards
@gap_start -= count
else
@move_gap_to offset + count
@gap_start -= count
ffi_fill @array + @gap_start, count * @type_size -- zero fill
@size -= count
replace: (offset, count, replacement, replacement_size = #replacement) =>
@delete offset, count
@insert offset, replacement, replacement_size
fill: (start_offset, end_offset, val) =>
if start_offset < 0 or start_offset >= @size or end_offset >= @size
error "GapBuffer#fill(#{start_offset}, #{end_offset}): Illegal offsets (size #{@size})", 2
arr = @array
i = start_offset
offset = start_offset
offset += @gap_size if offset >= @gap_start
while i <= end_offset
if offset >= @gap_start and offset < @gap_end -- entering into gap
offset += @gap_size
arr[offset] = val
i += 1
offset += 1
set: (data, size = #data) =>
arr_size = size + @default_gap_size
if @array and @size + @gap_size >= arr_size
arr_size = @size + @gap_size
ffi_fill @array, size * @type_size
else
-- allocate new array
@array = self.new_arr(arr_size + 1) -- + 1 = with one final zero
@array[arr_size] = 0 -- which we set here
if data
ffi_copy @array, data, size * @type_size
@size = size
@gap_start = size
@gap_end = arr_size
ffi_fill @array + @gap_start, @gap_size * @type_size
}
| 30.190476 | 111 | 0.618822 |
dda125c95acba67c2247fcf0e0b1a0bdcb155754 | 341 | export modinfo = {
type: "function"
id: "getRecursiveChildren"
func: (FirstObject) ->
AllObjects = {}
tbl = {}
table.insert(tbl, FirstObject)
while #tbl ~= 0
qemu = {}
for i, v in pairs(tbl)
for i1, v1 in pairs(v\children!)
table.insert(qemu, v1)
table.insert(AllObjects, v)
tbl = qemu
return AllObjects
}
| 20.058824 | 36 | 0.624633 |
f8e2b19c06faa658235870e4ab874b8ec3db7806 | 4,001 | import highlight from howl.ui
import app, mode, Buffer from howl
moon = require 'moon'
class ControlCompleter
complete: (context) =>
candidates = {}
for name, _ in pairs aisu.packages
table.insert candidates, name
compls = howl.util.Matcher(candidates) context.word_prefix
compls.authoritive = true
compls
ControlMode =
default_config:
cursor_line_highlighted: false
line_wrapping: 'character'
complete: 'manual'
keymap: {}
completers: { ControlCompleter, 'in_buffer' }
with highlight
.define 'aisu-error',
type: .ROUNDED_RECTANGLE
background: 'red'
background_alpha: 0.5
.define 'aisu-warning',
type: .ROUNDED_RECTANGLE
background: 'purple'
background_alpha: 0.5
.define 'aisu-prompt',
type: .ROUNDED_RECTANGLE
background: 'gray'
background_alpha: 0.5
.define 'aisu-header',
type: .ROUNDED_RECTANGLE
background: '#043927'
background_alpha: 0.5
.define 'aisu-info'
type: .ROUNDED_RECTANGLE
background: '#7ec0ee'
background_alpha: 0.5
class ControlBuffer extends Buffer
new: (hook) =>
super {}
@hook = @safe_coroutine hook
@read_only = true
@title = 'Aisu'
@mode = mode.by_name 'aisu-control'
@allow_appends = false
@prompt_begins = nil
@_buffer.insert = aisu.bind @\_aullar_override, @_buffer\insert
@_buffer.delete = aisu.bind @\_aullar_override, @_buffer\delete
@writeln 'Aisu Console', 'aisu-header'
@resume!
-- Workaround for https://github.com/howl-editor/howl/issues/363
meta = getmetatable @
meta.__properties = moon.copy Buffer.__properties
meta.__properties.modified =
get: -> false
set: ->
-- https://github.com/howl-editor/howl/issues/363
-- @property modified:
-- get: -> false
-- set: ->
_aullar_override: (orig_func, buf, offset, ...) =>
return if not @allow_appends
if @prompt_begins
return unless offset > @prompt_begins
buf.read_only = false
status, err = pcall orig_func, offset, ...
buf.read_only = true
if status
@update_prompt!
else
error err
open_prompt: =>
@allow_appends = true
@prompt_begins = @length
@mode.keymap.enter = @\close_prompt
@update_prompt!
update_prompt: =>
return unless @prompt_begins
highlight.remove_all 'aisu-prompt', @
highlight.apply 'aisu-prompt', @, @prompt_begins, @length-@prompt_begins+1
close_prompt: =>
return if not @prompt_begins
@allow_appends = false
text = @sub @prompt_begins+1
@prompt_begins = nil
@writeln!
@mode.config.complete = 'manual'
@resume text.stripped
resume: (...) =>
if coroutine.status(@hook) != 'dead'
@call coroutine.resume, @hook, @, ...
call: (f, ...) =>
errfunc = (err) ->
@writeln "FATAL ERROR: #{err}", 'aisu-error'
@writeln debug.traceback!, 'aisu-error'
status, err = xpcall f, errfunc, ...
error err if not status
safe_coroutine: (f) => coroutine.create (...) -> @call f, ...
_force_append: (...) =>
allow_appends = @allow_appends
@allow_appends = true
result, err = pcall @append, @, ...
@allow_appends = allow_appends
app.editor.cursor\eof!
error err unless result
write: (text, flair) =>
pos = @length
pos = 1 if pos == 0
@_force_append text
highlight.apply flair, @, pos, @length - pos if flair
writeln: (text, flair) => @write "#{text or ''}\n", flair
info: (text) => @writeln text, 'aisu-info'
warn: (text) => @writeln "WARNING: #{text}", 'aisu-warning'
error: (text) => @writeln "ERROR: #{text}", 'aisu-error'
ask: (text, flair) =>
yn = nil
while yn == nil
@write text, flair
@open_prompt!
ans = aisu.yield!
if ans == 'y'
yn = true
elseif ans == 'n'
yn = false
else
@error "Invalid answer: #{ans}"
return yn
aisu.ControlBuffer = ControlBuffer
mode.register
name: 'aisu-control'
create: -> ControlMode
| 24.850932 | 78 | 0.633342 |