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
|
---|---|---|---|---|---|
9a6a5afda623bde4252878fd3c78df1f2e7a79e5 | 4,010 | export ^
require "states/scenes/scenestate"
require "timer"
require "states/transitions/fadetoblack"
require "states/transitions/fadefrom"
class FinderSceneState extends SceneState
new: (scene, fulltext, @clues_to_find, @startIndices, @stopIndices) =>
super(scene)
-- @timer = CigTimer() -- should be another?
@timer = MatchTimer()
-- some changes to makes it simpler
@textBox.font = love.graphics.newFont "res/font/courier-prime/Courier Prime.ttf", 23
@textBox.autoText = string.gsub(fulltext, "\n>", "\n ")
@textBox.mute = true
@clueToFind = 1 -- index of @clues_to_find
@clueAtPointer = nil -- name of the clue
@clueSelected = nil -- name of the clue
@cluesFound = {}
@foundHighlights = {}
@portraitplayer = love.graphics.newImage("res/characters/portraits/assistant.png")
@helperbox = InGameHelper("Try to find the item described by HatShade.\nClick on it before it's too late!")
-- sanity checks
assert #@clues_to_find == #@startIndices and #@startIndices == #@stopIndices,
"invalid parameters: #{#@clues_to_find} - #{#@startIndices} - #{#@stopIndices}"
for name in *@clues_to_find
assert @scene.clues[name] ~= nil, "Invalid clue name: #{name}"
update: (dt) =>
super(dt)
if @clueToFind <= #@clues_to_find
if not @timer.started and #@textBox.text >= @startIndices[@clueToFind]
-- start timer
duration = (@stopIndices[@clueToFind] - @startIndices[@clueToFind]) / @textBox.autoTypeSpeed
@timer\start(duration)
elseif @timer.started and #@textBox.text >= @stopIndices[@clueToFind]
-- stop timer
if @clues_to_find[@clueToFind] == @clueSelected
@found_clue(@clues_to_find[@clueToFind])
else
@lost_clue(@clues_to_find[@clueToFind])
@clueSelected = nil
@clueToFind += 1
else
-- highlight clue under cursor
scale, offset_x, offset_y = @getOffsetAndScale()
mx, my = love.mouse.getPosition()
img_x = math.floor((mx - offset_x) / scale)
img_y = math.floor((my - offset_y) / scale)
if (img_x >= 0 and img_y >= 0 and img_x <= @scene.spriteImg\getWidth() and img_y <= @scene.spriteImg\getHeight() )
clue = @scene\getClueAt(img_x, img_y)
if clue
@clueAtPointer = clue.name
else
@clueAtPointer = nil
else
@clueAtPointer = nil
else
statestack\push FadeToBlack(1)
found_clue: (name) =>
clue = @scene.clues[name]
table.insert(@cluesFound, name)
-- draw the found clue in green
img = clue.highlightImg
imgdata = img\getData()
foundImgData = love.image.newImageData(img\getWidth(), img\getHeight())
foundImgData\paste(imgdata, 0, 0, 0, 0, img\getWidth(), img\getHeight())
foundImgData\mapPixel( (x, y, r, g, b, a) -> g, r, b, a )
table.insert @foundHighlights, love.graphics.newImage(foundImgData)
lost_clue: (clue) =>
statestack\push FadeFrom {255, 0, 0}, 0.3
draw_clue_layer: =>
super()
for img in *@foundHighlights
love.graphics.draw(img, 0, 0)
if @clueAtPointer
love.graphics.setColor(255, 255, 255, 100)
love.graphics.draw(@scene.clues[@clueAtPointer].highlightImg, 0, 0)
love.graphics.setColor(255, 255, 255, 255)
if @clueSelected
love.graphics.setColor(255, 255, 255, 255)
love.graphics.draw(@scene.clues[@clueSelected].highlightImg, 0, 0)
mousepressed: (x, y, button) =>
switch button
when 1
@clueSelected = @clueAtPointer
| 41.340206 | 130 | 0.572319 |
cde1bd40493c48e2cc62afbeece841066daf3e65 | 1,655 | uri_patts = require 'lpeg_patterns.uri'
Incoming = require 'quest.incoming'
Outgoing = require 'quest.outgoing'
util = require 'http.util'
lpeg = require 'lpeg'
cq = require 'cqueues'
EOF = lpeg.P -1
uri_patt = uri_patts.uri * EOF
if rawget(_G, '_DEV') == true
new = Outgoing
Outgoing = (...) ->
ok, req = dbg.call new, ...
req if ok
quest = (verb, uri, headers) =>
if type(uri) ~= 'table'
uri = assert uri_patt\match(uri), 'invalid URI'
uri.port or= util.scheme_to_port[uri.scheme]
uri.version or= 1.1
req = Outgoing uri, headers
req.for = verb..' '..dbg.pretty uri
path = uri.query and uri.path..'?'..uri.query or uri.path
authority = util.to_authority uri.host, uri.port, uri.scheme
req\set ':authority', authority
req\set ':scheme', uri.scheme
req\set ':method', verb
req\set ':path', path
return req
quest = setmetatable {},
__call: quest
quest.fetch = (uri, headers) ->
quest('GET', uri, headers)\send!
local sock_mt
quest.sock = (path) ->
assert type(path) == 'string', 'socket path must be a string'
setmetatable {:path}, sock_mt
sock_request = (verb, path, headers) =>
if type(path) ~= 'string'
headers, path, verb = path, verb, 'GET'
assert type(path) == 'string', '`path` must be a string'
req = Outgoing {path: @path, version: 1.1}, headers
req.for = verb..' '..@path..'~'..path
req.queue = @queue
req\set ':authority', 'localhost'
req\set ':scheme', 'http'
req\set ':method', verb
req\set ':path', path
return req
sock_mt =
request: sock_request
fetch: (uri, headers) =>
quest.fetch @request 'GET', uri, headers
sock_mt.__index = sock_mt
return quest
| 25.461538 | 63 | 0.650151 |
0d7a0e6749b82f163e27d45e2fb42b1463d86e66 | 845 | import List from require "LunoPunk.utils.List"
class eventlistener
new: =>
@__listeners = {}
add: (type, f) =>
@__listeners[type] = List! if @__listeners[type] == nil
@__listeners[type]\push f
remove: (type, f) =>
if f == nil
@__listeners[type] = nil
return nil
l = @__listeners[type]
return nil if l == nil
for i, v in l\ipairs!
if v == f
return l\remove i
nil
dispatch: (type, ...) =>
return if @__listeners[type] == nil
for e in @__listeners[type]\pairs!
e type, ...
EventListener = eventlistener!
AddEventListener = (type, f) -> EventListener\add type, f
RemoveEventListener = (type, f) -> EventListener\remove type, f
DispatchEvent = (event, ...) -> EventListener\dispatch event\type!, ... unless event.type == nil
{ :EventListener, :AddEventListener, :RemoveEventListener, :DispatchEvent }
| 23.472222 | 96 | 0.661538 |
0349bd6e8570f670e86e9b9db140f847aa943c27 | 940 | ----------------------------------------------------------------
-- A table @{Block} that is not assigned to any variable.
-- Useful to have a table within a @{TableBlock}.
--
-- @classmod AnonymousTableBlock
-- @author Richard Voelker
-- @license MIT
----------------------------------------------------------------
local Block
if game
pluginModel = script.Parent.Parent.Parent.Parent
Block = require(pluginModel.com.blacksheepherd.code.Block)
else
Block = require "com.blacksheepherd.code.Block"
-- {{ TBSHTEMPLATE:BEGIN }}
class AnonymousTableBlock extends Block
new: =>
super!
Render: =>
buffer = ""
buffer ..= @\BeforeRender!
buffer ..= "\n"
for i, child in ipairs @_children
buffer ..= child\Render!
buffer ..= "," unless i == #@_children
buffer ..= "\n"
buffer .. @\AfterRender!
BeforeRender: => "#{@_indent}{"
AfterRender: => "#{@_indent}}"
-- {{ TBSHTEMPLATE:END }}
return AnonymousTableBlock
| 22.380952 | 64 | 0.579787 |
0eff48b1196aa62c1ef326e936e4d0260423af60 | 1,383 | ----------------------------------------------------------------
-- A @{Block} that is similar to to @{TableBlock} but assigns
-- the table to a table key instead of a local variable.
--
-- @classmod TableAssignmentBlock
-- @author Richard Voelker
-- @license MIT
----------------------------------------------------------------
local Block
if game
pluginModel = script.Parent.Parent.Parent.Parent
Block = require(pluginModel.com.blacksheepherd.code.Block)
else
Block = require "com.blacksheepherd.code.Block"
-- {{ TBSHTEMPLATE:BEGIN }}
class TableAssignmentBlock extends Block
----------------------------------------------------------------
-- Create the TableAssignmentBlock.
--
-- @tparam TableAssignmentBlock self
-- @tparam string name The name of the table variable that this
-- table is assigned to.
-- @tparam string key The key of the table to assign to.
----------------------------------------------------------------
new: (name, key) =>
super!
@_name = name
@_key = key
Render: =>
buffer = ""
buffer ..= @\BeforeRender!
buffer ..= "\n"
for i, child in ipairs @_children
buffer ..= child\Render!
buffer ..= "," unless i == #@_children
buffer ..= "\n"
buffer .. @\AfterRender!
BeforeRender: => "#{@_indent}#{@_name}[\"#{@_key}\"] = {"
AfterRender: => "#{@_indent}}"
-- {{ TBSHTEMPLATE:END }}
return TableAssignmentBlock
| 26.596154 | 65 | 0.545915 |
09763c5560ec1214b8a8cd56ac8e39827b486895 | 28,031 | config = require "lapis.config"
config.default_config.postgres = {backend: "pgmoon"}
config.reset true
db = require "lapis.db.postgres"
import Model from require "lapis.db.postgres.model"
import stub_queries, assert_queries from require "spec.helpers"
describe "lapis.db.model.relations", ->
get_queries, mock_query = stub_queries!
with old = assert_queries
assert_queries = (expected, opts) ->
old expected, get_queries!, opts
local models
before_each ->
models = {}
package.loaded.models = models
it "should make belongs_to getter", ->
mock_query "SELECT", { { id: 101 } }
models.Users = class extends Model
@primary_key: "id"
models.CoolUsers = class extends Model
@primary_key: "user_id"
class Posts extends Model
@relations: {
{"user", belongs_to: "Users"}
{"cool_user", belongs_to: "CoolUsers", key: "owner_id"}
}
post = Posts!
post.user_id = 123
post.owner_id = 99
assert post\get_user!
assert post\get_user!
post\get_cool_user!
assert_queries {
'SELECT * from "users" where "id" = 123 limit 1'
'SELECT * from "cool_users" where "user_id" = 99 limit 1'
}
it "should make belongs_to getter with inheritance", ->
mock_query "SELECT", { { id: 101 } }
models.Users = class extends Model
@primary_key: "id"
class Posts extends Model
@relations: {
{"user", belongs_to: "Users"}
}
get_user: =>
with user = super!
user.color = "green"
post = Posts!
post.user_id = 123
assert.same {
id: 101
color: "green"
}, post\get_user!
it "caches nil result from belongs_to_fetch", ->
mock_query "SELECT", {}
models.Users = class extends Model
@primary_key: "id"
class Posts extends Model
@relations: {
{"user", belongs_to: "Users"}
}
post = Posts!
post.user_id = 123
assert.same nil, post\get_user!
assert.same nil, post\get_user!
assert.same 1, #get_queries!
it "should make fetch getter", ->
called = 0
class Posts extends Model
@relations: {
{ "thing", fetch: =>
called += 1
"yes"
}
}
post = Posts!
post.user_id = 123
assert.same "yes", post\get_thing!
assert.same "yes", post\get_thing!
assert.same 1, called
assert_queries {}
it "should make a fetch with preload", ->
called = 0
class Posts extends Model
@relations: {
{ "thing"
fetch: => "yes"
preload: (objects, opts) ->
for object in *objects
continue if object.skip_me
object.thing = called
called += 1
}
}
one = Posts!
two = Posts!
two.skip_me = true
three = Posts!
four = Posts!
Posts\preload_relations {one, two, three}, "thing"
assert.same 0, one\get_thing!
assert.same nil, two\get_thing!
assert.same 1, three\get_thing!
assert.same "yes", four\get_thing!
import LOADED_KEY from require "lapis.db.model.relations"
for item in *{one, two, three}
assert.true item[LOADED_KEY].thing
assert.true four[LOADED_KEY].thing
it "should make belongs_to getters for extend syntax", ->
mock_query "SELECT", { { id: 101 } }
models.Users = class extends Model
@primary_key: "id"
m = Model\extend "the_things", {
relations: {
{"user", belongs_to: "Users"}
}
}
obj = m!
obj.user_id = 101
assert obj\get_user! == obj\get_user!
assert_queries {
'SELECT * from "users" where "id" = 101 limit 1'
}
it "should make has_one getter", ->
mock_query "SELECT", { { id: 101 } }
models.Users = class Users extends Model
@relations: {
{"user_profile", has_one: "UserProfiles"}
}
models.UserProfiles = class UserProfiles extends Model
user = Users!
user.id = 123
user\get_user_profile!
assert_queries {
'SELECT * from "user_profiles" where "user_id" = 123 limit 1'
}
it "should make has_one getter with custom key", ->
mock_query "SELECT", { { id: 101 } }
models.UserData = class extends Model
models.Users = class Users extends Model
@relations: {
{"data", has_one: "UserData", key: "owner_id"}
}
user = Users!
user.id = 123
assert user\get_data!
assert_queries {
'SELECT * from "user_data" where "owner_id" = 123 limit 1'
}
it "makes has_one getter with composite key", ->
mock_query "SELECT", { { id: 101 } }
models.UserPageData = class extends Model
models.UserPage = class extends Model
@relations: {
{"data", has_one: "UserPageData", key: {
"user_id", "page_id"
}}
}
up = models.UserPage!
up.user_id = 99
up.page_id = 234
assert up\get_data!
up2 = models.UserPage!
up2.user_id = nil
up2.page_id = 'hello'
assert up2\get_data!
assert_queries {
{
'SELECT * from "user_page_data" where "user_id" = 99 AND "page_id" = 234 limit 1'
'SELECT * from "user_page_data" where "page_id" = 234 AND "user_id" = 99 limit 1'
}
{
[[SELECT * from "user_page_data" where "user_id" IS NULL AND "page_id" = 'hello' limit 1]]
[[SELECT * from "user_page_data" where "page_id" = 'hello' AND "user_id" IS NULL limit 1]]
}
}
it "should make has_one getter key and local key", ->
mock_query "SELECT", { { id: 101, thing_email: "leafo@leafo" } }
models.Things = class extends Model
models.Users = class Users extends Model
@relations: {
{"data", has_one: "Things", local_key: "email", key: "thing_email"}
}
user = Users!
user.id = 123
user.email = "leafo@leafo"
assert user\get_data!
assert_queries {
[[SELECT * from "things" where "thing_email" = 'leafo@leafo' limit 1]]
}
it "should make has_one getter with where clause", ->
mock_query "SELECT", { { id: 101 } }
models.UserData = class extends Model
models.Users = class Users extends Model
@relations: {
{"data", has_one: "UserData", key: "owner_id", where: { state: "good"} }
}
user = Users!
user.id = 123
assert user\get_data!
assert_queries {
{
[[SELECT * from "user_data" where "owner_id" = 123 AND "state" = 'good' limit 1]]
[[SELECT * from "user_data" where "state" = 'good' AND "owner_id" = 123 limit 1]]
}
}
it "makes has_one getter with composite key with custom local names", ->
mock_query "SELECT", { { id: 101 } }
models.UserPageData = class extends Model
models.UserPage = class extends Model
@relations: {
{"data", has_one: "UserPageData", key: {
user_id: "alpha_id"
page_id: "beta_id"
}}
}
up = models.UserPage!
up.alpha_id = 99
up.beta_id = 234
assert up\get_data!
assert_queries {
{
'SELECT * from "user_page_data" where "user_id" = 99 AND "page_id" = 234 limit 1'
'SELECT * from "user_page_data" where "page_id" = 234 AND "user_id" = 99 limit 1'
}
}
it "should make has_many paginated getter", ->
mock_query "SELECT", { { id: 101 } }
models.Posts = class extends Model
models.Users = class extends Model
@relations: {
{"posts", has_many: "Posts"}
{"more_posts", has_many: "Posts", where: {color: "blue"}}
}
user = models.Users!
user.id = 1234
user\get_posts_paginated!\get_page 1
user\get_posts_paginated!\get_page 2
user\get_more_posts_paginated!\get_page 2
user\get_posts_paginated(per_page: 44)\get_page 3
assert_queries {
'SELECT * from "posts" where "user_id" = 1234 LIMIT 10 OFFSET 0'
'SELECT * from "posts" where "user_id" = 1234 LIMIT 10 OFFSET 10'
{
[[SELECT * from "posts" where "user_id" = 1234 AND "color" = 'blue' LIMIT 10 OFFSET 10]]
[[SELECT * from "posts" where "color" = 'blue' AND "user_id" = 1234 LIMIT 10 OFFSET 10]]
}
'SELECT * from "posts" where "user_id" = 1234 LIMIT 44 OFFSET 88'
}
it "should make has_many getter", ->
models.Posts = class extends Model
models.Users = class extends Model
@relations: {
{"posts", has_many: "Posts"}
{"more_posts", has_many: "Posts", where: {color: "blue"}}
{"fresh_posts", has_many: "Posts", order: "id desc"}
}
user = models.Users!
user.id = 1234
user\get_posts!
user\get_posts!
user\get_more_posts!
user\get_fresh_posts!
assert_queries {
'SELECT * from "posts" where "user_id" = 1234'
{
[[SELECT * from "posts" where "user_id" = 1234 AND "color" = 'blue']]
[[SELECT * from "posts" where "color" = 'blue' AND "user_id" = 1234]]
}
'SELECT * from "posts" where "user_id" = 1234 order by id desc'
}
it "should make has_many getter with composite key", ->
mock_query "SELECT", {
{ id: 101, user_id: 99, page_id: 234 }
{ id: 102, user_id: 99, page_id: 234 }
}
models.UserPageData = class extends Model
models.UserPage = class extends Model
@relations: {
{"data", has_many: "UserPageData", key: {
"user_id", "page_id"
}}
}
up = models.UserPage!
up.user_id = 99
up.page_id = 234
assert.same {
{ id: 101, user_id: 99, page_id: 234 }
{ id: 102, user_id: 99, page_id: 234 }
}, up\get_data!
up2 = models.UserPage!
up2.user_id = 99
up2.page_id = nil
assert up2\get_data!
assert_queries {
{
'SELECT * from "user_page_data" where "user_id" = 99 AND "page_id" = 234'
'SELECT * from "user_page_data" where "page_id" = 234 AND "user_id" = 99'
}
{
'SELECT * from "user_page_data" where "user_id" = 99 AND "page_id" IS NULL'
'SELECT * from "user_page_data" where "page_id" IS NULL AND "user_id" = 99'
}
}
it "should create relations for inheritance", ->
class Base extends Model
@relations: {
{"user", belongs_to: "Users"}
}
class Child extends Base
@relations: {
{"category", belongs_to: "Categories"}
}
assert Child.get_user, "expecting get_user"
assert Child.get_category, "expecting get_category"
assert.same nil, rawget Child, "get_user"
describe "polymorphic belongs to", ->
local Foos, Bars, Bazs, Items
before_each ->
models.Foos = class Foos extends Model
models.Bars = class Bars extends Model
@primary_key: "frog_index"
models.Bazs = class Bazs extends Model
Items = class Items extends Model
@relations: {
{"object", polymorphic_belongs_to: {
[1]: {"foo", "Foos"}
[2]: {"bar", "Bars"}
[3]: {"baz", "Bazs"}
}}
}
it "should model_for_object_type", ->
assert Foos == Items\model_for_object_type 1
assert Foos == Items\model_for_object_type "foo"
assert Bars == Items\model_for_object_type 2
assert Bars == Items\model_for_object_type "bar"
assert Bazs == Items\model_for_object_type 3
assert Bazs == Items\model_for_object_type "baz"
assert.has_error ->
Items\model_for_object_type 4
assert.has_error ->
Items\model_for_object_type "bun"
it "should object_type_for_model", ->
assert.same 1, Items\object_type_for_model Foos
assert.same 2, Items\object_type_for_model Bars
assert.same 3, Items\object_type_for_model Bazs
assert.has_error ->
Items\object_type_for_model Items
it "should object_type_for_object", ->
assert.same 1, Items\object_type_for_object Foos!
assert.same 2, Items\object_type_for_object Bars!
assert.same 3, Items\object_type_for_object Bazs
assert.has_error ->
Items\object_type_for_model {}
it "should call getter", ->
mock_query "SELECT", { { id: 101 } }
for i, {type_id, cls} in ipairs {{1, Foos}, {2, Bars}, {3, Bazs}}
item = Items\load {
object_type: type_id
object_id: i * 33
}
obj = item\get_object!
obj.__class == cls
obj2 = item\get_object!
assert.same obj, obj2
assert_queries {
'SELECT * from "foos" where "id" = 33 limit 1'
'SELECT * from "bars" where "frog_index" = 66 limit 1'
'SELECT * from "bazs" where "id" = 99 limit 1'
}
it "should call preload with empty", ->
Items\preload_objects {}
assert_queries {
}
it "should call preload", ->
k = 0
n = ->
k += 1
k
items = {
Items\load {
object_type: 1
object_id: n!
}
Items\load {
object_type: 2
object_id: n!
}
Items\load {
object_type: 1
object_id: n!
}
Items\load {
object_type: 1
object_id: n!
}
}
Items\preload_objects items
assert_queries {
'SELECT * from "foos" where "id" in (1, 3, 4)'
'SELECT * from "bars" where "frog_index" in (2)'
}
it "preloads with fields", ->
items = {
Items\load {
object_type: 1
object_id: 111
}
Items\load {
object_type: 2
object_id: 112
}
Items\load {
object_type: 3
object_id: 113
}
}
Items\preload_objects items, fields: {
bar: "a, b"
baz: "c, d"
}
assert_queries {
'SELECT * from "foos" where "id" in (111)'
'SELECT a, b from "bars" where "frog_index" in (112)'
'SELECT c, d from "bazs" where "id" in (113)'
}
it "finds relation", ->
import find_relation from require "lapis.db.model.relations"
class Posts extends Model
@relations: {
{"user", belongs_to: "Users"}
{"cool_user", belongs_to: "CoolUsers", key: "owner_id"}
}
class BetterPosts extends Posts
@relations: {
{"tags", has_many: "Tags"}
}
assert.same {"user", belongs_to: "Users"}, (find_relation Posts, "user")
assert.same nil, (find_relation Posts, "not there")
assert.same {"cool_user", belongs_to: "CoolUsers", key: "owner_id"},
(find_relation BetterPosts, "cool_user")
describe "clear_loaded_relation", ->
it "clears loaded relation cached with value", ->
mock_query "SELECT", {
{id: 777, name: "hello"}
}
models.Users = class Users extends Model
class Posts extends Model
@relations: {
{"user", belongs_to: "Users"}
}
post = Posts\load {
id: 1
user_id: 1
}
post\get_user!
post\get_user!
assert.same 1, #get_queries!
assert.not.nil post.user
post\clear_loaded_relation "user"
assert.nil post.user
post\get_user!
assert.same 2, #get_queries!
it "clears loaded relation cached with nil", ->
mock_query "SELECT", {}
models.Users = class Users extends Model
class Posts extends Model
@relations: {
{"user", belongs_to: "Users"}
}
post = Posts\load {
id: 1
user_id: 1
}
post\get_user!
post\get_user!
assert.same 1, #get_queries!
post\clear_loaded_relation "user"
post\get_user!
assert.same 2, #get_queries!
describe "preload_relations", ->
it "preloads relations that return empty", ->
mock_query "SELECT", {}
models.Dates = class Dates extends Model
models.Users = class Users extends Model
models.Tags = class Tags extends Model
class Posts extends Model
@relations: {
{"user", belongs_to: "Users"}
{"date", has_one: "Dates"}
{"tags", has_many: "Tags"}
}
post = Posts\load {
id: 888
user_id: 234
}
Posts\preload_relations {post}, "user", "date", "tags"
assert_queries {
[[SELECT * from "users" where "id" in (234)]]
[[SELECT * from "dates" where "post_id" in (888)]]
[[SELECT * from "tags" where "post_id" in (888)]]
}
import LOADED_KEY from require "lapis.db.model.relations"
assert.same {
user: true
date: true
tags: true
}, post[LOADED_KEY]
before_count = #get_queries!
post\get_user!
post\get_date!
post\get_tags!
assert.same, before_count, #get_queries!
it "preloads has_many with order and fields", ->
models.Tags = class Tags extends Model
class Posts extends Model
@relations: {
{"tags", has_many: "Tags", order: "a desc"}
}
Posts\preload_relation {Posts\load id: 123}, "tags", {
fields: "a,b"
order: "b asc"
}
assert_queries {
[[SELECT a,b from "tags" where "post_id" in (123) order by b asc]]
}
it "preloads has_many with composite key", ->
mock_query "SELECT", {
{ id: 101, user_id: 99, page_id: 234 }
{ id: 102, user_id: 99, page_id: 234 }
{ id: 103, user_id: 100, page_id: 234 }
}
models.UserPageData = class extends Model
models.UserPage = class UserPage extends Model
@relations: {
{"data", has_many: "UserPageData", key: {
"user_id", "page_id"
}}
}
user_pages = {
UserPage\load {
user_id: 99
page_id: 234
}
UserPage\load {
user_id: 100
page_id: 234
}
UserPage\load {
user_id: 100
page_id: 300
}
}
UserPage\preload_relation user_pages, "data"
assert_queries {
'SELECT * from "user_page_data" where ("user_id", "page_id") in ((99, 234), (100, 234), (100, 300))'
}
import LOADED_KEY from require "lapis.db.model.relations"
for user_page in *user_pages
assert.true user_page[LOADED_KEY].data
assert.same {
{ id: 101, user_id: 99, page_id: 234 }
{ id: 102, user_id: 99, page_id: 234 }
}, user_pages[1].data
assert.same {
{ id: 103, user_id: 100, page_id: 234 }
}, user_pages[2].data
assert.same {}, user_pages[3].data
it "preloads has_one with key and local_key", ->
mock_query "SELECT", {
{ id: 99, thing_email: "notleafo@leafo" }
{ id: 101, thing_email: "leafo@leafo" }
}
models.Things = class extends Model
models.Users = class Users extends Model
@relations: {
{"thing", has_one: "Things", local_key: "email", key: "thing_email"}
}
user = Users!
user.id = 123
user.email = "leafo@leafo"
Users\preload_relations {user}, "thing"
assert_queries {
[[SELECT * from "things" where "thing_email" in ('leafo@leafo')]]
}
assert.same {
id: 101
thing_email: "leafo@leafo"
}, user.thing
it "preloads has_one with where", ->
mock_query "SELECT", {
{ thing_id: 123, name: "whaz" }
}
models.Files = class Files extends Model
class Things extends Model
@relations: {
{"beta_file"
has_one: "Files"
where: { deleted: false }
}
}
thing = Things\load { id: 123 }
Things\preload_relations { thing }, "beta_file"
assert.same {
thing_id: 123
name: "whaz"
}, thing.beta_file
assert_queries {
[[SELECT * from "files" where "thing_id" in (123) and "deleted" = FALSE]]
}
it "preloads has_one with composite key", ->
import LOADED_KEY from require "lapis.db.model.relations"
mock_query "SELECT", {
{id: 1, user_id: 11, page_id: 101}
}
models.UserPageData = class extends Model
models.UserPage = class UserPage extends Model
@relations: {
{"data", has_one: "UserPageData", key: {
"user_id", "page_id"
}}
}
user_pages = {
UserPage\load {
user_id: 10
page_id: 100
}
UserPage\load {
user_id: 11
page_id: 101
}
}
UserPage\preload_relation user_pages, "data"
assert_queries {
[[SELECT * from "user_page_data" where ("user_id", "page_id") in ((10, 100), (11, 101))]]
}
assert.same {
{
user_id: 10
page_id: 100
[LOADED_KEY]: { data: true }
}
{
user_id: 11
page_id: 101
data: {
id: 1, user_id: 11, page_id: 101
}
[LOADED_KEY]: { data: true }
}
}, user_pages
it "preloads has_many with order and name", ->
mock_query "SELECT", {
{ primary_thing_id: 123, name: "whaz" }
}
models.Tags = class Tags extends Model
class Things extends Model
@relations: {
{"cool_tags"
has_many: "Tags"
order: "name asc"
where: { deleted: false }
key: "primary_thing_id"
}
}
thing = Things\load { id: 123 }
Things\preload_relations {thing}, "cool_tags"
assert.same {
{ primary_thing_id: 123, name: "whaz" }
}, thing.cool_tags
assert_queries {
[[SELECT * from "tags" where "primary_thing_id" in (123) and "deleted" = FALSE order by name asc]]
}
it "preloads belongs_to with correct name", ->
mock_query "SELECT", {
{ id: 1, name: "last" }
{ id: 2, name: "first" }
{ id: 3, name: "default" }
}
models.Topics = class Topics extends Model
class Categories extends Model
@relations: {
{"last_topic", belongs_to: "Topics"}
{"first_topic", belongs_to: "Topics"}
{"topic", belongs_to: "Topics"}
}
cat = Categories\load {
id: 1243
last_topic_id: 1
first_topic_id: 2
topic_id: 3
}
Categories\preload_relations {cat}, "last_topic", "first_topic", "topic"
assert.same 3, #get_queries!
assert.same {
id: 1
name: "last"
}, cat\get_last_topic!, cat.last_topic
assert.same {
id: 2
name: "first"
}, cat\get_first_topic!, cat.first_topic
assert.same {
id: 3
name: "default"
}, cat\get_topic!, cat.topic
assert.same 3, #get_queries!
it "preloads has_one with correct name", ->
mock_query "SELECT", {
{user_id: 1, name: "cool dude"}
}
models.UserData = class UserData extends Model
class Users extends Model
@relations: {
{"data", has_one: "UserData"}
}
user = Users\load id: 1
Users\preload_relations {user}, "data"
assert.same {user_id: 1, name: "cool dude"}, user.data, user\get_data!
it "finds inherited preloaders", ->
models.Users = class Users extends Model
class SimplePosts extends Model
@relations: {
{"user", belongs_to: "Users"}
}
class JointPosts extends SimplePosts
@relations: {
{"second_user", belongs_to: "Users"}
}
p = JointPosts\load {
id: 999
user_id: 1
second_user_id: 2
}
JointPosts\preload_relations {p}, "user", "second_user"
describe "has_one", ->
it "preloads when using custom keys", ->
mock_query "SELECT", {
{user_id: 100, name: "first"}
{user_id: 101, name: "second"}
}
models.UserItems = class UserItems extends Model
@primary_key: "user_id"
@relations: {
{"application", has_one: "ItemApplications", key: "user_id"}
}
new: (user_id) =>
@user_id = assert user_id, "missing user id"
models.ItemApplications = class ItemApplications extends Model
id = 1
new: (user_id) =>
@user_id = assert user_id, "missing user id"
@id = id
id += 1
ui = UserItems 100
a = assert ui\get_application!, "expected to get relation"
assert.same 100, a.user_id
ui2 = UserItems 101
UserItems\preload_relations {ui2}, "application"
a = assert ui2.application, "expected to get relation"
assert.same 101, a.user_id
assert_queries {
[[SELECT * from "item_applications" where "user_id" = 100 limit 1]]
[[SELECT * from "item_applications" where "user_id" in (101)]]
}
describe "generic preload", ->
local preload
before_each ->
import preload from require "lapis.db.model"
models.Users = class Users extends Model
@relations: {
{"tags", has_many: "Tags"}
{"user_data", has_one: "UserData"}
{"account", belongs_to: "Accounts"}
}
new: (@id) =>
assert @id, "missing id"
models.Tags = class Tags extends Model
@relations: {
{"owner", has_one: "Users"}
}
models.UserData = class UserData extends Model
@relations: {
{"images", has_many: "Images"}
}
models.Accounts = class Accounts extends Model
models.Images = class Images extends Model
it "preloads basic relations", ->
user = models.Users 10
user.account_id = 99
preload { user }, "tags", "user_data", "account"
assert_queries {
[[SELECT * from "tags" where "user_id" in (10)]]
[[SELECT * from "user_data" where "user_id" in (10)]]
[[SELECT * from "accounts" where "id" in (99)]]
}
it "preloads nested relations", ->
mock_query 'from "tags"', {
models.Tags\load {
id: 252
user_id: 10
}
models.Tags\load {
id: 311
user_id: 10
}
}
mock_query 'from "user_data"', {
models.UserData\load {
id: 32
user_id: 10
}
}
user = models.Users 10
user.account_id = 99
preload { user }, "account", {
tags: { "owner" }
user_data: {"images"}
}
assert_queries {
[[SELECT * from "accounts" where "id" in (99)]]
[[SELECT * from "images" where "user_data_id" in (32)]]
[[SELECT * from "tags" where "user_id" in (10)]]
[[SELECT * from "user_data" where "user_id" in (10)]]
[[SELECT * from "users" where "tag_id" in (252, 311)]]
}, sorted: true
it "preloads nested fetch relations", ->
models.Collections = class Collection extends Model
@relations: {
{"user",
fetch: => {}
preload: (collections) ->
for c in *collections
c.user = models.Users\load {
id: 10
}
true
}
{"things",
many: true
fetch: => {}
preload: (collections) ->
for c in *collections
c.things = {
models.Users\load {
id: 11
}
models.Users\load {
id: 12
}
}
true
}
}
new: (@id) =>
assert @id, "missing id"
collection = models.Collections 44
preload { collection }, {
user: "tags"
things: { "user_data", "tags" }
}
assert_queries {
-- TODO: homogeneous preload should be able to merge these queries
[[SELECT * from "tags" where "user_id" in (10)]]
[[SELECT * from "tags" where "user_id" in (11, 12)]]
[[SELECT * from "user_data" where "user_id" in (11, 12)]]
}, sorted: true
| 24.653474 | 108 | 0.556277 |
6e43f1321ca1e18859f380a787a7f5b59e8d8262 | 1,802 | import unpack, type from _G
import byte, char from string
import concat from table
import BYTE_MAXIMUM_VALUE, BYTE_MINIMUM_VALUE from "noomlib/io/buffer/constants"
-- table allocate(number size)
-- Returns a preallocated table
export allocate = (size) ->
return [-1 for _=1, size]
-- table bytes_from_string(string string)
-- Returns a table of bytes from a string
export bytes_from_string = (string) ->
--return {byte(string, index, #string)}
return [byte(string, index, index) for index = 1, #string]
-- table bytes_from_table(table table)
-- Returns a table of bytes from a string table
-- ```lua
-- local tbl = {"he", "l", "l", "o"}
-- local bytes = bytes_from_table(tbl) -- `{104, 101, 108, 108, 111}`
-- ```
export bytes_from_table = (table) ->
bytes = {}
for _byte in *table
if type(_byte) == "string"
for index = 1, #_byte
bytes[#bytes + 1] = byte(_byte, index, index)
elseif type(_byte) == "number"
if in_byte_range(_byte) then bytes[#bytes + 1] = _byte
else error("bad argument #1 'bytes_from_table' (expected ranged number values of 0...255 in table)")
else error("bad argument #1 to 'bytes_from_table' (expected number or string values in table)")
return bytes
-- boolean in_byte_range(number value)
-- Returns if the value is in the range of a byte, 0...255
export in_byte_range = (value) ->
return value >= BYTE_MINIMUM_VALUE and value <= BYTE_MAXIMUM_VALUE
-- string string_from_bytes(table bytes)
-- Returns a constructed string from a table of bytes
-- ```lua
-- local bytes = {104, 101, 108, 108, 111}
-- local string = string_from_bytes(bytes) -- `hello`
-- ```
export string_from_bytes = (bytes) ->
bytes = [char(byte) for byte in *bytes]
return concat(bytes) | 33.37037 | 112 | 0.666482 |
bbf54f8928531c32c912a88cb7ba5c8d2a80805c | 406 | class RedMode
new: =>
@api = bundle_load 'api'
@lexer = bundle_load 'red_lexer'
@completers = { 'in_buffer', 'api' }
comment_syntax: ';'
word_pattern: '[%w%?%-%!_~%*+/<>=]+'
auto_pairs: {
'(': ')'
'[': ']'
'{': '}'
'"': '"'
}
indentation: {
more_after: {
r'[({=\\[]\\s*(;.*|)$'
}
less_for: {
'^%s*]'
'^%s*}'
'^%s*)'
}
}
| 14.5 | 40 | 0.371921 |
477aada27de47912f6d2d85602b89a2b5dab0705 | 10,980 | api = vim.api
loop = vim.loop
Utils = require'neotags/utils'
class Neotags
new: (opts) =>
@opts = {
enable: true,
ft_conv: {
['c++']: 'cpp',
['moonscript']: 'moon',
['c#']: 'cs',
},
ft_map: {
cpp: { 'cpp', 'c' },
c: { 'c', 'cpp' },
},
hl: {
minlen: 3,
patternlength: 2048,
prefix: [[\C\<]],
suffix: [[\>]],
},
tools: {
find: nil,
},
ctags: {
run: true,
directory: vim.fn.expand('~/.vim_tags'),
verbose: false,
binary: 'ctags'
args: {
'--fields=+l',
'--c-kinds=+p',
'--c++-kinds=+p',
'--sort=no',
},
},
ignore: {
'cfg',
'conf',
'help',
'mail',
'markdown',
'nerdtree',
'nofile',
'readdir',
'qf',
'text',
'plaintext'
},
notin: {
'.*String.*',
'.*Comment.*',
'cIncluded',
'cCppOut2',
'cCppInElse2',
'cCppOutIf2',
'pythonDocTest',
'pythonDocTest2',
}
}
@languages = {}
@syntax_groups = {}
@highlighting = false
@ctags_handle = nil
@find_handle = nil
setup: (opts) =>
@opts = vim.tbl_deep_extend('force', @opts, opts) if opts
return if not @opts.enable
vim.api.nvim_create_augroup('NeotagsLua', { clear: true })
vim.api.nvim_create_autocmd(
'BufReadPost',
{
group: 'NeotagsLua',
callback: () -> require'neotags'.highlight()
}
)
vim.api.nvim_create_autocmd(
'BufWritePost',
{
group: 'NeotagsLua',
callback: () -> require'neotags'.update()
}
)
currentTagfile: () =>
path = vim.fn.getcwd()
path = path\gsub('[%.%/]', '__')
return "#{@opts.ctags.directory}/#{path}.tags"
runCtags: (files) =>
return if @ctags_handle
tagfile = @currentTagfile()
args = @opts.ctags.args
args = Utils.concat(args, { '-f', tagfile })
args = Utils.concat(args, files)
stdout = loop.new_pipe(false) if @opts.ctags.verbose
stderr = loop.new_pipe(false) if @opts.ctags.verbose
@ctags_handle = loop.spawn(
@opts.ctags.binary, {
args: args,
cwd: vim.fn.getcwd(),
stdio: {nil, stdout, stderr},
},
vim.schedule_wrap(() ->
if @opts.ctags.verbose
stdout\read_stop()
stdout\close()
stderr\read_stop()
stderr\close()
@ctags_handle\close()
@ctags_handle = nil
vim.bo.tags = tagfile
@run('highlight')
)
)
if @opts.ctags.verbose
loop.read_start(stdout, (err, data) -> print data if data)
loop.read_start(stderr, (err, data) -> print data if data)
update: () =>
return unless @opts.enable
ft = vim.bo.filetype
return if #ft == 0 or Utils.contains(@opts.ignore, ft)
@findFiles((files) -> @runCtags(files))
findFiles: (callback) =>
path = vim.fn.getcwd()
return callback({ '-R', path }) if not @opts.tools.find
return if @find_handle
stdout = loop.new_pipe(false)
stderr = loop.new_pipe(false) if @opts.ctags.verbose
files = {}
args = Utils.concat(@opts.tools.find.args, { path })
@find_handle = loop.spawn(
@opts.tools.find.binary, {
args: args,
cwd: path,
stdio: {nil, stdout, stderr},
},
vim.schedule_wrap(() ->
stdout\read_stop()
stdout\close()
if @opts.ctags.verbose
stderr\read_stop()
stderr\close()
@find_handle\close()
@find_handle = nil
callback(files)
)
)
loop.read_start(stdout, (err, data) ->
return unless data
for _, file in ipairs(Utils.explode('\n', data))
table.insert(files, file)
)
if @opts.ctags.verbose
loop.read_start(stderr, (err, data) -> print data if data)
run: (func) =>
ft = vim.bo.filetype
return if #ft == 0 or Utils.contains(@opts.ignore, ft)
co = nil
switch func
when 'highlight'
tagfile = @currentTagfile()
if vim.fn.filereadable(tagfile) == 0
@update()
elseif vim.bo.tags != tagfile
vim.bo.tags = tagfile
co = coroutine.create(() -> @highlight())
when 'clear'
co = coroutine.create(() -> @clearsyntax())
else return
return if not co
while true do
_, cmd = coroutine.resume(co)
-- vim.cmd("echo '#{cmd}'")
vim.cmd(cmd) if cmd
break if coroutine.status(co) == 'dead'
toggle: () =>
@opts.enable = not @opts.enable
@setup() if @opts.enable
@run('clear') if not @opts.enable
language: (lang, opts) =>
@languages[lang] = opts
clearsyntax: () =>
vim.api.nvim_create_augroup('NeotagsLua', { clear: true })
for _, hl in pairs(@syntax_groups)
coroutine.yield("silent! syntax clear #{hl}")
@syntax_groups = {}
makesyntax: (lang, kind, group, opts, content, added) =>
hl = "_Neotags_#{lang}_#{kind}_#{opts.group}"
matches = {}
keywords = {}
prefix = opts.prefix or @opts.hl.prefix
suffix = opts.suffix or @opts.hl.suffix
minlen = opts.minlen or @opts.hl.minlen
forbidden = {
'*',
}
for tag in *group
continue if #tag.name < minlen
continue if Utils.contains(added, tag.name)
continue if Utils.contains(forbidden, tag.name)
if not content\find(tag.name)
table.insert(added, tag.name)
continue
if (prefix == @opts.hl.prefix and suffix == @opts.hl.suffix and
opts.allow_keyword != false and not tag.name\find('.', 1, true) and
tag.name != 'contains')
table.insert(keywords, tag.name) if not Utils.contains(keywords, tag.name)
else
table.insert(matches, tag.name) if not Utils.contains(matches, tag.name)
table.insert(added, tag.name)
coroutine.yield("silent! syntax clear #{hl}")
coroutine.yield("hi def link #{hl} #{opts.group}")
table.sort(matches, (a, b) -> a < b)
merged = {}
if opts.extended_notin and opts.extend_notin == false
merged = opts.notin or @opts.notin or {}
else
a = @opts.notin or {}
b = opts.notin or {}
max = (#a > #b) and #a or #b
for i=1,max
merged[#merged+1] = a[i] if a[i]
merged[#merged+1] = b[i] if b[i]
notin = ''
notin = "containedin=ALLBUT,#{table.concat(merged, ',')}" if #merged > 0
for i = 1, #matches, @opts.hl.patternlength
current = {unpack(matches, i, i + @opts.hl.patternlength)}
str = table.concat(current, '\\|')
coroutine.yield("syntax match #{hl} /#{prefix}\\%(#{str}\\)#{suffix}/ #{notin} display")
table.sort(keywords, (a, b) -> a < b)
for i = 1, #keywords, @opts.hl.patternlength
current = {unpack(keywords, i, i + @opts.hl.patternlength)}
str = table.concat(current, ' ')
coroutine.yield("syntax keyword #{hl} #{str} #{notin}")
table.insert(@syntax_groups, hl)
highlight: () =>
return if @highlighting
ft = vim.bo.filetype
return if #ft == 0 or Utils.contains(@opts.ignore, ft)
@highlighting = true
bufnr = api.nvim_get_current_buf()
content = table.concat(api.nvim_buf_get_lines(bufnr, 0, -1, false), '\n')
tags = vim.fn.taglist('.*')
groups = {}
for tag in *tags
continue if not tag.language
continue if tag.name\match('^[a-zA-Z]{,2}$')
continue if tag.name\match('^[0-9]+$')
continue if tag.name\match('^__anon.*$')
tag.language = tag.language\lower()
tag.language = @opts.ft_conv[tag.language] if @opts.ft_conv[tag.language]
if @opts.ft_map[ft] and not Utils.contains(@opts.ft_map[ft], tag.language)
continue
if not @opts.ft_map[ft] and not ft == tag.language
continue
-- if tag.language == 'vim'
-- print require'lsp'.format_as_json(tag)
groups[tag.language] = {} if not groups[tag.language]
groups[tag.language][tag.kind] = {} if not groups[tag.language][tag.kind]
table.insert(groups[tag.language][tag.kind], tag)
langmap = @opts.ft_map[ft] or {ft}
for _, lang in pairs(langmap)
continue if not @languages[lang] or not @languages[lang].order
cl = @languages[lang]
order = cl.order
added = {}
kinds = groups[lang]
continue if not kinds
for i = 1, #order
kind = order\sub(i, i)
continue if not kinds[kind]
continue if not cl.kinds or not cl.kinds[kind]
-- print "adding #{kinds[kind]} for #{lang} in #{kind}"
@makesyntax(lang, kind, kinds[kind], cl.kinds[kind], content, added)
@highlighting = false
export neotags = Neotags! if not neotags
return {
setup: (opts) ->
path = debug.getinfo(1).source\match('@?(.*/)')
for filename in io.popen("ls #{path}/languages")\lines()
lang = filename\gsub('%.lua$', '')
neotags.language(neotags, lang, require"neotags/languages/#{lang}")
neotags.setup(neotags, opts)
highlight: () -> neotags.run(neotags, 'highlight')
update: () -> neotags.update(neotags)
toggle: () -> neotags.toggle(neotags)
language: (lang, opts) -> neotags.language(neotags, lang, opts)
}
| 30.082192 | 100 | 0.473862 |
26cf314792a560b8568cf3e9ef746b6589c7b311 | 14,193 | -- Copyright 2012-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
Gtk = require 'ljglibs.gtk'
import bindings, dispatch, interact, signal from howl
import Matcher from howl.util
import PropertyObject from howl.aux.moon
import TextWidget, NotificationWidget, IndicatorBar, StyledText from howl.ui
import highlight, markup, style, theme from howl.ui
-- used to generate a unique id for every new activity
id_counter = 0
class CommandLine extends PropertyObject
new: (@window) =>
super!
@bin = Gtk.Box Gtk.ORIENTATION_HORIZONTAL
@box = nil
@command_widget = nil
@notification_widget = nil
@header = nil
@indic_title = nil
@showing = false
@spillover = nil
@running = {}
@_command_history = {}
@aborted = {}
@next_run_queue = {}
@property current: get: => @running[#@running]
@property stack_depth: get: => #@running
_init_activity_from_factory: (activity_frame) =>
activity = activity_frame.activity_spec.factory!
if not activity
error "activity '#{activity_frame.name}' factory returned nil"
activity_frame.activity = activity
parked_handle = dispatch.park 'activity'
activity_frame.parked_handle = parked_handle
finish = (...) ->
results = table.pack ...
activity_frame.results = results
@_finish(activity_frame.activity_id, results)
dispatch.launch -> dispatch.resume parked_handle
true -- finish() is often the last function in a key handler
activity_frame.runner = ->
table.pack activity\run(finish, unpack activity_frame.args)
-- check that run didn't call finish
if @current and @current.activity_id == activity_frame.activity_id
@current.state = 'running'
@show!
bindings.cancel_capture!
if @spillover
-- allow editor to resize for correct focussing behavior
howl.timer.asap ->
@write @spillover if not @spillover.is_empty
@spillover = nil
dispatch.wait parked_handle
_init_activity_from_handler: (activity_frame) =>
if not callable activity_frame.activity_spec.handler
error "activity '#{activity_frame.name}' handler is not callable"
activity = { handler: activity_frame.activity_spec.handler }
activity_frame.activity = activity
activity_frame.runner = ->
@current.state = 'running'
results = table.pack activity.handler(unpack activity_frame.args)
if @current and @current.activity_id == activity_frame.activity_id
activity_frame.results = results
@_finish(activity_frame.activity_id, results)
run: (activity_spec, ...) =>
if not activity_spec.name or not (activity_spec.handler or activity_spec.factory)
error 'activity_spec requires "name" and one of "handler" or "factory" fields'
id_counter += 1
activity_id = id_counter
activity_frame = {
name: activity_spec.name
:activity_id
:activity_spec
args: table.pack ...
state: 'starting'
results: {}
}
if activity_spec.factory
@_init_activity_from_factory activity_frame
else
@_init_activity_from_handler activity_frame
table.insert @running, activity_frame
@_initialize! if not @box
with @current
.command_line_left_stop = @command_widget.text.ulen + 1
.command_line_widgets = { }
.command_line_prompt_len = 0
if @stack_depth == 1
@current.evade_history = activity_spec.evade_history
@history_recorded = false
else
previous = @running[@stack_depth - 1]
@current.evade_history = previous.evade_history or activity_spec.evade_history
bindings.capture -> false
ok, err = pcall activity_frame.runner
bindings.cancel_capture!
unless ok
if @current and activity_id == @current.activity_id
@_finish(activity_id)
log.error err
return
unpack activity_frame.results
run_after_finish: (f) =>
if not (@stack_depth > 0)
error 'Cannot run_after_finish - no running activity'
table.insert @next_run_queue, f
_process_run_after_finish: =>
while true
f = table.remove @next_run_queue, 1
break unless f
f!
_is_active: (activity_id) =>
for activity in *@running
if activity.activity_id == activity_id
return true
return false
_finish: (activity_id, results={}) =>
if @aborted[activity_id]
@aborted[activity_id] = nil
return
if not @current
error 'Cannot finish - no running activities'
if activity_id != @current.activity_id
if @_is_active activity_id
while @current.activity_id != activity_id
@_abort_current!
else
error "Cannot finish - invalid activity_id #{activity_id}"
@current.state = 'stopping'
if #results > 0
@record_history!
@clear!
@prompt = nil
for name, _ in pairs @_widgets
@remove_widget name
if @current.saved_command_line
@command_widget\insert @current.saved_command_line, 1
@current.saved_command_line = nil
@running[#@running] = nil
if @stack_depth > 0
@title = @title
else
@hide!
@pop_spillover!
@_process_run_after_finish!
_abort_current: =>
activity_id = @current.activity_id
handle = @current.parked_handle
@_finish activity_id
@aborted[activity_id] = true
if handle
dispatch.launch -> dispatch.resume handle
if @current and activity_id == @current.activity_id
-- hard clear, polite attempt didn't work
@running[#@running] = nil
abort_all: =>
while @current
@_abort_current!
_cursor_to_end: =>
@command_widget.cursor\eof!
_adjust_height_rows: =>
width_cols = @command_widget.width_cols
return unless width_cols > 0
max_height = math.floor howl.app.window.allocated_height * 0.5
num_lines = #@command_widget.buffer.lines
height_rows = math.ceil @command_widget.buffer.lines[num_lines].text.ulen / @command_widget.width_cols
height_rows = math.max 1, height_rows
@command_widget.height_rows = height_rows
while @command_widget.height > max_height and height_rows > 1
height_rows -= 1
@command_widget.height_rows = height_rows
record_history: =>
return if @current.evade_history or @history_recorded
@history_recorded = true
command_line = @_capture_command_line!
for frame in *@running
if frame.saved_command_line
command_line = frame.saved_command_line .. command_line
current_history = @get_history @running[1].name
last_cmd = current_history[1]
unless last_cmd == command_line or command_line\find '\n' or command_line\find '\r'
table.insert @_command_history, 1, {name: @running[1].name, cmd: command_line}
_capture_command_line: (end_pos) =>
buf = @command_widget.buffer
chunk = buf\chunk 1, (end_pos or #buf)
return StyledText chunk.text, chunk.styles
get_history: (activity_name) =>
return [item.cmd for item in *@_command_history when activity_name == item.name]
to_gobject: => @bin
_initialize: =>
@box = Gtk.Box Gtk.ORIENTATION_VERTICAL
border_box = Gtk.EventBox {
Gtk.Alignment {
top_padding: 1,
left_padding: 1,
right_padding: 3,
bottom_padding: 3,
@box
}
}
border_box.style_context\add_class 'editor'
@bin\add border_box
@command_widget = TextWidget
top_padding: 3
left_padding: 3
bottom_padding: 2
bottom_border: 1
top_border: 1
line_wrapping: 'char'
on_keypress: (event) ->
result = true
if not @handle_keypress(event)
result = false
@post_keypress!
return result
on_changed: ->
@on_update!
on_focus_lost: ->
@command_widget\focus! if @showing
on_map: ->
@_adjust_height_rows!
@command_widget.height_rows = 1
@box\pack_end @command_widget\to_gobject!, false, 0, 0
@notification_widget = NotificationWidget!
@box\pack_end @notification_widget\to_gobject!, false, 0, 0
@header = IndicatorBar 'header', 3
@indic_title = @header\add 'left', 'title'
@box\pack_start @header\to_gobject!, false, 0, 0
@property width_cols:
get: => @command_widget.width_cols
@property _activity:
get: => @current and @current.activity
@property _widgets:
get: => @current and @current.command_line_widgets
@property _left_stop:
get: => @current and @current.command_line_left_stop
@property _prompt_end:
get: => @current and @_left_stop + @current.command_line_prompt_len
@property _updating:
get: => @current and @current.command_line_updating
set: (value) =>
return unless @current
@current.command_line_updating = value
@property title:
get: => @current and @current.command_line_title
set: (text) =>
if not @current
error 'Cannot set title - no running activity', 2
@current.command_line_title = text if @current
if text == nil or text.is_empty
@header\to_gobject!\hide!
else
@header\to_gobject!\show!
@indic_title.label = tostring text
@property prompt:
get: => @current and @command_widget.text\usub @_left_stop, @_prompt_end - 1
set: (prompt='') =>
if not @current
error 'Cannot set prompt - no running activity', 2
if @_left_stop <= @_prompt_end
@command_widget\delete @_left_stop, @_prompt_end - 1
@current.command_line_prompt = prompt
@current.command_line_prompt_len = prompt.ulen
if prompt
@command_widget\insert prompt, @_left_stop, 'prompt'
@\_cursor_to_end!
@property text:
get: => @current and @command_widget.text\usub @_prompt_end
set: (text) =>
if not @current
error 'Cannot set text - no running activity', 2
@clear!
@write text
notify: (text, style='info') =>
if @notification_widget
@notification_widget\notify style, text
@notification_widget\show!
else
io.stderr\write text
clear_notification: =>
@notification_widget\hide! if @notification_widget
clear: =>
@command_widget\delete @_prompt_end, @command_widget.text.ulen
@\_cursor_to_end!
clear_all: =>
@current.saved_command_line = @_capture_command_line @_left_stop - 1
@command_widget\delete 1, @_left_stop - 1
@current.command_line_left_stop = 1
write: (text) =>
@command_widget\append text
@\_cursor_to_end!
@\on_update!
write_spillover: (text) =>
-- spillover is saved text written to whichever activity is invoked next
if @spillover
@spillover = @spillover .. text
else
@spillover = text
pop_spillover: =>
spillover = @spillover
@spillover = nil
return spillover or ''
post_keypress: =>
@enforce_left_pos!
on_update: =>
-- only call on_update() after run() ends and before finish() begins
return if not @current or @current.state != 'running'
if @_activity and @_activity.on_update and not @_updating
-- avoid recursive calls
@_updating = true
ok, err = pcall ->
@_activity\on_update @text
@_updating = false
if not ok
error err
@_adjust_height_rows!
enforce_left_pos: =>
-- don't allow cursor to go left into prompt
return if not @current
left_pos = @_prompt_end or 1
if @command_widget.cursor.pos < left_pos
@command_widget.cursor.pos = left_pos
handle_keypress: (event) =>
-- keymaps checked in order:
-- @preemptive_keymap - keys that cannot be remapped by activities
-- @_activity.keymap
-- widget.keymap for widget in @_widgets
-- @keymap
@clear_notification!
@window.status\clear!
return true if bindings.dispatch event, 'commandline', { @preemptive_keymap}, self
activity = @_activity
if activity and activity.keymap
return true if bindings.dispatch event, 'commandline', { activity.keymap }, activity
if @_widgets
for _, widget in pairs @_widgets
if widget.keymap
return true if bindings.dispatch event, 'commandline', { widget.keymap }, widget
return true if bindings.dispatch event, 'commandline', { @keymap }, self
return false
preemptive_keymap:
ctrl_shift_backspace: => @abort_all!
keymap:
binding_for:
["cursor-home"]: => @command_widget.cursor.pos = @_prompt_end
["cursor-line-end"]: => @command_widget.cursor.pos = @_prompt_end + @text.ulen
["cursor-left"]: => @command_widget.cursor\left!
["cursor-right"]: => @command_widget.cursor\right!
["editor-delete-back"]: =>
-- don't backspace into prompt
return true if @command_widget.cursor.pos <= @_prompt_end
range_start = @command_widget.selection\range!
return if range_start and range_start < @_prompt_end
@command_widget\delete_back!
@on_update!
["editor-paste"]: =>
import clipboard from howl
if clipboard.current
@write clipboard.current.text
add_widget: (name, widget) =>
error('No widget provided', 2) if not widget
@remove_widget name
@box\pack_end widget\to_gobject!, false, 0, 0
@_widgets[name] = widget
widget\show!
remove_widget: (name) =>
widget = @_widgets[name]
@box\remove widget\to_gobject! if widget
@_widgets[name] = nil
get_widget: (name) => @_widgets[name]
show: =>
return if @showing
@last_focused = @window.focus if not @last_focused
@window\remember_focus!
@_initialize! if not @box
@window.status\hide!
@bin\show_all!
@notification_widget\hide!
with @command_widget
\show!
\focus!
@title = @current and @current.command_line_title
@showing = true
hide: =>
if @showing
@bin\hide!
@showing = false
@window.status\show!
@last_focused\grab_focus! if @last_focused
@last_focused = nil
style.define_default 'prompt', 'keyword'
return CommandLine
| 27.884086 | 106 | 0.663919 |
2b5264651951cc1c9fe1b5d56f8670006df81ad5 | 322 | -- Copyright 2014-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
howl.util.lpeg_lexer ->
coffeescript = sequence {
line_start,
#any('\t', P(' ')^4),
sub_lex_match_time('coffeescript', scan_through_indented!)
}
compose 'markdown', coffeescript
| 24.769231 | 79 | 0.704969 |
8b2ce7fcd50cf10dce7f709153ab9d6be4543039 | 559 | {
whitelist_globals: {
["spiders.moon"]: {
"btn", "btnp",
"clip",
"cls",
"circ", "circb",
"elli", "ellib",
"exit",
"fget", "fset",
"font",
"key",
"keyp",
"line",
"map",
"memcpy",
"memset",
"mget", "mset",
"mouse",
"music",
"peek", "peek4",
"pix",
"pmem",
"poke", "poke4",
"print",
"rect", "rectb",
"reset",
"sfx",
"spr",
"sync",
"time",
"tstamp",
"trace",
"tri", "trib",
"textri",
}
}
}
| 14.333333 | 23 | 0.36136 |
05c95acf77e3022b6541dff8674dc4e9e571e0c6 | 5,818 | #!/usr/bin/env moon
--- Class for handling users.
-- @author ChickenNuggers
-- @classmod client
import line_pattern, hash, serialize_tag_value from require "potato.util"
import context_from_pair from require "potato.tls"
state = require "potato.state"
wire_responses = {
[401]: ":No suck nick/channel"
[402]: ":No such server"
[403]: ":No such channel"
[404]: ":Cannot send to channel"
[405]: ":You have joined too many channels"
[406]: ":There was no such nickname"
[407]: ":Duplicate recipients. No message delivered"
[409]: ":No origin specified"
[411]: ":No recipient given (%s)"
[412]: ":No text to send"
[413]: "%s :No toplevel domain specified"
[414]: ":Wildcard in the top level domain"
[421]: ":Unknown command"
[422]: ":MOTD File is missing"
[423]: "%s :No administrative info available"
[424]: ":File error performing %s on %s"
[431]: ":No nickname given"
[432]: ":Erroneous nickname"
[433]: ":Nickname is already in use"
[436]: ":Nickname collision KILL"
[441]: "%s %s :They aren't in that channel"
[442]: "%s :You're not in that channel"
[443]: "%s %s :is already in that channel"
[444]: "%s :User not logged in"
[445]: ":SUMMON has been disabled"
[446]: ":USERS has been disabled"
[451]: ":You have not registered"
[461]: "%s :Not enough parameters"
[462]: ":You may not reregister"
[463]: ":Your host isn't among the privileged"
[464]: ":Password incorrect"
[465]: ":You are banned from this server"
[467]: "%s :Channel key already set"
[471]: "%s :Cannot join channel (+l)"
[472]: "%s :is unknown mode char to me"
[473]: "%s :Cannot join channel (+i)"
[474]: "%s :Cannot join channel (+b)"
[475]: "%s :Cannot join channel (+k)"
[479]: "%s: Cannot join channel (%s)" -- CUSTOM new field ERR_NOJOINCHANNEL
[481]: ":Permission denied- You're not an IRC operator"
[482]: "%s :You're not a channel operator"
[483]: ":You can't kill a server!"
[491]: ":No O-lines for your host"
[501]: ":Unknown MODE flag (%s)" -- CUSTOM modified
[502]: ":Can't change mode for other users"
}
insert = table.insert
concat = table.concat
--- @table tag_format
-- @field vendor Optional field, contains vendor. Defaults to `default`
-- @field key Key for tag. Not optional.
-- @field value Value for tag. If left out, defaults to boolean true.
-- @field is_client Client-to-client identifier. Boolean, defaults to false
class client
--- Initiate a TLS handshake on a socket if available.
wrap_socket: (socket)->
if state.tls_ctx
-- ::TODO:: Alpn | SNI
@socket\starttls state.tls_ctx
--- Send a message to the client.
-- @tparam string prefix Name, without space. May be nick!user@host.
-- @tparam table arguments Command arguments. Will not be preceded by ':'
-- @tparam table object_tags Optional IRCv3 tags array
-- @see tag_format
send: (prefix, arguments, object_tags)->
tags = {}
if object_tags and #object_tags > 0
for tag in *object_tags
current_tag = {}
if tag.is_client
insert current_tag, "+"
if tag.vendor
insert current_tag, "#{tag.vendor}/"
insert current_tag, tag.key
if tag.value
insert current_tag, "=#{serialize_tag_value tag.value}"
insert tags, " "
if #tags != 0
@socket\write "@#{concat tags, ';'} "
@socket\write ":#{prefix} #{concat arguments, ' '}\n"
--- Send a specific numeric to a user, optionally with a custom message.
-- If a message isn't specified, one from wire_responses is used.
-- @tparam number numeric Identifier for numeric command
-- @tparam string description Description for command response
-- @tparam table tags IRCv3 tags to send with message
-- @see tag_format
numeric: (numeric, description, tags)->
if not description and @format == "wire"
description = wire_responses[numeric]
@send state.config.vhost, {numeric, description}, tags
--- Register client and establish IRCv3 capabilities.
-- @param socket Connection to client (cqueues.socket)
-- @usage for socket in server\clients!
-- loop\wrap ->
-- potato.client socket
new: (socket)=>
@socket = socket
@wrap_socket!
@format = "wire"
@channels = {}
@monitored_by = {}
{@config} = require "potato"
-- handle registration before iterating over lines
-- check for NICK command or CAP command, then USER command
line = socket\read!
data = line_pattern\match line
switch data.command
when "PASS" -- PASS <password>
if not @config.password
@received_password = hash data.arguments[1]
else
if hash data.arguments[1] != @config.password
@fatal "Incorrect password."
when "NICK" -- NICK <nickname>
"pass"
when "USER" -- USER <username> * * :<realname>
"pass"
when "CAP" -- CAP {LS,LIST,REQ,ACK,NAK,END}
"pass"
else
"pass"
-- default case, do not handle line
@loop!
--- Send an `ERROR` message and signal `QUIT` messages.
-- @tparam string message Message to send to client
fatal: (message)=>
@socket\write "ERROR: #{message}\n"
@quit message
--- Send `QUIT` to every channel the user is in; terminate connection.
-- @tparam string message Message to send to clients
quit: (message)=>
users_already_sent = {}
for channel in *@channels
channel.users[@nick] = nil
for user in *channel.users
if not users_already_sent[user]
users_already_sent[user] = true
user.socket\write "#{@prefix} QUIT :#{message}\n"
if #channel.users == 0
-- clean up
-- ::TODO:: check if channel is registered then commit to db
state.channels[channel.name] = nil
for user in *@monitored_by -- MONITOR command
user.monitors[@nick] = nil
if not users_already_sent[user]
users_already_sent[user] = true
user.socket\write "#{@prefix} QUIT :#{message}\n"
if @did_register
state.users[@nick] = nil
@socket\close! -- we don't dupe file descriptors, close also shuts down
| 34.426036 | 76 | 0.673427 |
939ad38b98bd55c32770095444508f12d8c91189 | 1,661 | [[
joli-lune
small framework for love2d
MIT License (see licence file)
]]
System = require "src.systems.system"
class Particle extends System
__tostring: => return "particle"
onCreate: (color,exp,particleType,options={}) =>
@\cron "after", exp, ->
@entity.scene\removeEntity(@entity)
@expire = exp
if type(particleType)=="string"
@entity\addSystem "Renderer",particleType,options.style or "main",options.width or 100,options.align or "left"
if color
@entity.renderer\get().tint = color
elseif tostring(particleType)=="sprite"
@entity\addSystem "Renderer",particleType,options.anim,0,0,options.flipx,options.flipy
if color
@entity.renderer\get().tint = color
else
@entity\addSystem "Renderer","circ",color,"fill",size
@render = @entity.renderer\get!
velocityx: (easing,vx1=0,vx2=vx1) =>
@position\tween @expire,{x:@position.x+love.math.random(vx1,vx2)},easing
velocityy: (easing,vy1=0,vy2=vy1) =>
@position\tween @expire,{y:@position.y+love.math.random(vy1,vy2)},easing
size: (easing,startsize,endsize) =>
if @render.rendertype == "shape"
@render.arg1 = startsize
if endsize
@\tween @expire,{arg1:endsize},easing,@render
elseif @render.rendertype=="sprite" or @render.rendertype=="text"
@position.scalex = startsize
@position.scaley = startsize
if endsize
@position\tween @expire,{scalex:endsize,scaley:endsize},easing
alpha: (easing,s,e) =>
if not @render.tint
@render.tint = {1,1,1,s}
@render.alpha = s
else
@render.tint = {@render.tint[1],@render.tint[2],@render.tint[3],s}
@render.alpha = s
if e
@\tween @expire,{alpha:e},easing,@render
return Particle | 29.140351 | 113 | 0.695364 |
8ca81a7b873111eb1748628705e321362494ae00 | 5,619 | {:delegate_to} = howl.util.table
background = '#282a36'
current = '#44475a'
selection = '#44475a'
foreground = '#f8f8f2'
comment = '#6272a4'
red = '#ff5555'
orange = '#ffb86c'
yellow = '#f1fa8c'
green = '#50fa7b'
aqua = '#8be9fd'
blue = '#8be9fd'
purple = '#bd93f9'
magenta = '#ff79c6'
grey = '#595959'
grey_darker = '#1c1d23'
grey_darkest = '#1c1d23'
grey_light = '#a6a6a6'
embedded_bg = '#484848'
border_color = '#44475a'
-- General styling for context boxes (editor, command_line)
content_box = {
background:
color: background
border:
width: 1
color: border_color
border_right:
width: 3
color: border_color
border_bottom:
width: 3
color: border_color
header:
background:
color: grey_darkest
border_bottom:
color: grey_darker
color: white
font: bold: true
padding: 1
footer:
background:
color: grey_darkest
border_top:
color: grey_darker
color: grey
font: bold: true
padding: 1
}
return {
window:
background:
color: background
status:
font: bold: true, italic: true
color: grey
info: color: grey_light
warning: color: orange
'error': color: red
:content_box
popup:
background:
color: grey_darkest
border:
color: grey
editor: delegate_to content_box, {
scrollbars:
slider:
color: magenta
indicators:
default:
color: grey_light
title:
font: bold: true
vi:
font: bold: true
caret:
color: grey_light
width: 2
current_line:
background: current
gutter:
color: comment
background:
color: grey_darkest
alpha: 0.6
}
flairs:
indentation_guide:
type: flair.PIPE,
foreground: comment,
:background,
line_width: 1
indentation_guide_1:
type: flair.PIPE,
foreground: grey_darker,
line_width: 1
indentation_guide_2:
type: flair.PIPE,
foreground: grey_darker,
line_width: 1
indentation_guide_3:
type: flair.PIPE,
foreground: grey_darker,
line_width: 1
edge_line:
type: flair.PIPE,
foreground: blue,
foreground_alpha: 0.3,
line_width: 0.5
search:
type: highlight.ROUNDED_RECTANGLE
foreground: black
foreground_alpha: 1
background: yellow
text_color: grey_darkest
height: 'text'
search_secondary:
type: flair.ROUNDED_RECTANGLE
background: yellow
text_color: grey_darkest
height: 'text'
replace_strikeout:
type: flair.ROUNDED_RECTANGLE
foreground: black
background: red
text_color: black
height: 'text'
brace_highlight:
type: flair.RECTANGLE
text_color: foreground
background: '#0064b1'
height: 'text'
brace_highlight_secondary:
type: flair.RECTANGLE
foreground: '#0064b1'
text_color: foreground
line_width: 1
height: 'text'
list_selection:
type: flair.RECTANGLE
background: current
background_alpha: 0.3
list_highlight:
type: highlight.UNDERLINE
foreground: white
text_color: white
line_width: 2
cursor:
type: flair.RECTANGLE
background: foreground
width: 2
height: 'text'
block_cursor:
type: flair.ROUNDED_RECTANGLE,
background: foreground
text_color: background
height: 'text',
min_width: 'letter'
selection:
type: highlight.ROUNDED_RECTANGLE
background: selection
background_alpha: 0.4
min_width: 'letter'
styles:
default:
color: foreground
red: color: red
green: color: green
yellow: color: yellow
blue: color: blue
magenta: color: purple
cyan: color: aqua
popup:
background: grey_darkest
color: foreground
comment:
font: italic: true
color: comment
variable:
color: yellow
label:
color: orange
font: italic: true
key:
color: blue
font: bold: true
fdecl:
color: green
font: bold: true
keyword:
color: magenta
font: bold: true
class:
color: blue
font: bold: true
type_def:
color: green
font:
bold: true
definition:
color: yellow
function:
color: blue
font: bold: true
type:
color: blue
font: italic: true
char: color: green
number: color: purple
operator: color: magenta
preproc: color: aqua
special: color: purple
tag: color: purple
member: color: red
info: color: blue
constant:
color: yellow
string:
color: yellow
regex:
color: green
background: embedded_bg
embedded:
color: blue
background: embedded_bg
-- Markup and visual styles
error:
font: italic: true
color: white
background: red
warning:
font: italic: true
color: orange
h1:
font: bold: true
color: magenta
h2:
font: bold: true
color: aqua
h3:
font: italic: true
color: purple
emphasis:
font:
bold: true
italic: true
strong: font: italic: true
link_label: color: aqua
link_url: color: comment
table:
color: blue
background: embedded_bg
underline: true
addition: color: green
deletion: color: red
change: color: yellow
}
| 17.079027 | 59 | 0.589607 |
f43fd0713ffe5d5f0f704de5686b2b3ea0f4461b | 2,269 | Atom = require 'ljglibs.gdk.atom'
GtkClipboard = require 'ljglibs.gtk.clipboard'
{:clipboard, :config} = howl
describe 'Clipboard', ->
system_cb = GtkClipboard.get(Atom.SELECTION_CLIPBOARD)
before_each -> clipboard.clear!
describe 'push(item, opts = {})', ->
context 'when <item> is a string', ->
it 'adds a clip item containing text to the clipboard', ->
clipboard.push 'hello!'
assert.equals 'hello!', clipboard.current.text
context 'when <item> is a table', ->
it 'adds the clip item as is to the clipboard', ->
clipboard.push text: 'hello!'
assert.equals 'hello!', clipboard.current.text
it 'raises an error if <item> has no .text field', ->
assert.raises 'text', -> clipboard.push {}
context 'when opts contains a ".to" field', ->
it 'pushes the item to the specified target', ->
clipboard.push 'hello!', to: 'a'
assert.is_nil clipboard.current
assert.equals 'hello!', clipboard.registers.a.text
context 'when no ".to" field is specified in opts', ->
it 'ensures the number of clips does not exceed config.clipboard_max_items', ->
config.clipboard_max_items = 5
for i = 1,6
clipboard.push "clip #{i}"
assert.equals 5, #clipboard.clips
assert.equals 'clip 6', clipboard.clips[1].text
assert.equals 'clip 2', clipboard.clips[5].text
it 'copies the clip to the system clipboard as well', ->
clipboard.push 'global!'
assert.equals 'global!', system_cb\wait_for_text!
describe 'clear()', ->
it 'clears all clips', ->
clipboard.push 'hello!'
clipboard.push 'to register!', to: 'a'
clipboard.clear!
assert.is_nil clipboard.current
assert.is_nil clipboard.registers.a
describe 'synchronize()', ->
it 'adds the clip from the system clipboard if it differs from .current', ->
system_cb\set_text 'pushed'
clipboard.synchronize!
assert.equals 'pushed', clipboard.current.text
it 'does nothing if the texts are the same', ->
clipboard.push 'pushed'
system_cb\set_text 'pushed'
clipboard.synchronize!
assert.equals 'pushed', clipboard.current.text
assert.equals 1, #clipboard.clips
| 34.907692 | 85 | 0.643896 |
f9620b8f3803049046a2f869dff7aa864b70bd46 | 272 | export modinfo = {
type: "command"
desc: "Set time of day"
alias: {"settimeofday"}
func: (Msg,Speaker) ->
light = Service"Lighting"
light.TimeOfDay = Msg
Output2(string.format("Set time of day to %s",light.TimeOfDay),{Colors.Green})
loggit("Set time of day")
} | 27.2 | 80 | 0.680147 |
3fb7b6b21fc8b6717cf2517d0d7d071fd81a359a | 223 | import Model from require "lapis.db.model"
class ResourceReports extends Model
-- Has created_at and modified_at
@timestamp: true
@relations: {
{"resource", belongs_to: "Resources", key: "resource"}
} | 27.875 | 57 | 0.686099 |
b93b7cf9c98c44ad94883cda2dfc6d2a78ee8049 | 183 | cons => nil => array =>
length = (get array "length")
(for 0 length nil i => result =>
idx = (sub (sub length i) 1)
val = (get array (nts idx))
(cons idx val result))
| 26.142857 | 34 | 0.557377 |
3df96d74d412b09cd57cfc089cfdfe4332e2a873 | 2,239 |
import insert from table
validate_functions = {
exists: (input) ->
input and input != "", "%s must be provided"
-- TODO: remove this in favor of is_file
file_exists: (input) ->
type(input) == "table" and input.filename != "" and input.content != "", "Missing file"
min_length: (input, len) ->
#tostring(input or "") >= len, "%s must be at least #{len} chars"
max_length: (input, len) ->
#tostring(input or "") <= len, "%s must be at most #{len} chars"
is_file: (input) ->
type(input) == "table" and input.filename != "" and input.content != "", "Missing file"
is_integer: (input) ->
tostring(input)\match"^%d+$", "%s must be an integer"
is_color: do
hex = "[a-fA-f0-9]"
three = "^##{hex\rep 3}$"
six = "^##{hex\rep 6}$"
(input) ->
input = tostring(input)
input\match(three) or input\match(six), "%s must be a color"
is_timestamp: (input) ->
month, day, hour, min, sec = input and input\match "^%d+%-(%d+)%-(%d+)%s+(%d+):(%d+):(%d+)$"
month != nil, "%s is not a valid timestamp"
equals: (input, value) ->
input == value, "%s must match"
one_of: (input, ...) ->
choices = {...}
for choice in *choices
return true if input == choice
false, "%s must be one of #{table.concat choices, ", "}"
type: (input, kind) ->
return true if type(input) == kind
false, "%s must be a " .. kind
}
test_input = (input, func, args) ->
fn = assert validate_functions[func], "Missing validation function #{func}"
args = {args} if type(args) != "table"
fn input, unpack args
validate = (object, validations) ->
errors = {}
for v in *validations
key = v[1]
error_msg = v[2]
input = object[key]
if v.optional
continue unless validate_functions.exists input
v.optional = nil
for fn, args in pairs v
continue unless type(fn) == "string"
success, msg = test_input input, fn, args
unless success
insert errors, (error_msg or msg)\format key
break
next(errors) and errors
assert_valid = (object, validations) ->
errors = validate object, validations
coroutine.yield "error", errors if errors
{ :validate, :assert_valid, :test_input, :validate_functions }
| 27.304878 | 96 | 0.601608 |