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
27f3010b64ee35cef241222cb67d27f05b1ac40b
333
local json do ok, dkjson = pcall require, "dkjson" json = if ok then dkjson else require "cjson" local yaml do lyaml = require "lyaml" yaml = encode: lyaml.dump decode: lyaml.load local toml do _toml = require "toml" _toml.strict = false toml = encode: _toml.encode decode: _toml.parse return {:json, :yaml, :toml}
15.136364
46
0.693694
c2937ab3fbbe1037ee89a232a75a39023c5affec
3,819
-- Copyright 2012-2015 The Howl Developers -- License: MIT (see LICENSE.md at the top-level directory of the distribution) import interact from howl import highlight from howl.ui import Matcher from howl.util append = table.insert line_match_highlighter = (editor, explain) -> local buffer (selection, text, items) -> if buffer highlight.remove_all 'search', buffer highlight.remove_all 'search_secondary', buffer return unless selection buffer = editor.buffer line = buffer.lines[selection.line_nr] local segments if text and not text.is_empty segments = explain text, line.text if segments start_pos = line.start_pos ranges = [{start_pos + s[1] - 1, s[2]} for s in *segments] highlight.apply 'search', buffer, ranges else highlight.apply 'search', buffer, line.start_pos, line.end_pos - line.start_pos -- highlight nearby secondary matches if #items > 0 and not text.is_empty local idx for i, item in ipairs items continue unless item.buffer == buffer if item.line_nr >= editor.line_at_top - 5 idx = i break if idx ranges = {} for i = idx, #items continue unless items[i].buffer == buffer nr = items[i].line_nr if nr > editor.line_at_bottom + 5 break if nr == selection.line_nr continue line = buffer.lines[nr] start_pos = line.start_pos segments = explain text, line.text if segments for segment in *segments ranges[#ranges + 1] = { start_pos + segment[1] - 1, segment[2] } highlight.apply 'search_secondary', buffer, ranges create_matcher = (line_items, find) -> mt = { __call: (query) => return moon.copy(line_items) unless query return [item for item in *line_items when find query, item[2].text] } return setmetatable {explain: (query, text) -> find query, text}, mt interact.register name: 'select_line' description: 'Selection for buffer lines' handler: (opts) -> opts = moon.copy opts lines = opts.lines opts.lines = nil unless lines error '"lines" field required', 2 if opts.matcher or opts.items or opts.on_change error '"matcher", "items" or "on_change" not allowed', 2 editor = opts.editor or howl.app.editor line_items = {} largest_nr = 0 for line in *lines append line_items, {tostring(line.nr), line.chunk, buffer: line.buffer, line_nr: line.nr, :line} largest_nr = math.max(largest_nr, line.nr) selected_line = opts.selected_line if selected_line for item in *line_items if item.line_nr == selected_line.nr and item.buffer == selected_line.buffer opts.selection = item break opts.selected_line = nil local matcher if opts.find matcher = create_matcher(line_items, opts.find) else matcher = Matcher line_items, preserve_order: true opts.items = line_items opts.on_change = line_match_highlighter(editor, matcher.explain) opts.force_preview = true opts.columns = { {align: 'right', style: 'comment', min_width: tostring(largest_nr).ulen}, {} } result = interact.select_location opts if result line = result.selection.line column = 1 if result.text and not result.text.is_empty segments = matcher.explain result.text, line.text column = segments and segments[1][1] or 1 return { :line text: result.text :column } else highlight.remove_all 'search', editor.buffer highlight.remove_all 'search_secondary', editor.buffer return -- howl.interact.select_line lines: howl.app.editor.buffer.lines
29.152672
102
0.641791
676d6f5a1bc2836987d68d99d2a2aaa8ac5c0155
626
{ define_class: (base, meta = {}) -> props = base.properties or {} orig_index = meta.__index meta.__index = (o, k) -> m = base[k] return m if m p = props[k] if p p = p.get if type(p) == 'table' p and p o elseif orig_index orig_index o, k meta.__newindex = (o, k, ...) -> p = props[k] p = p.set if p if p p o, ... else rawset o, k, ... setmetatable {}, { __call: (t, ...) -> o = setmetatable {}, meta if base.new base.new o, ... o __index: meta.__index } }
18.411765
39
0.434505
460b834952fff39566f078492f4d79a3cf4c4889
889
describe "transform.branch", -> run = require("shipwright.builder").run branch = require("shipwright.transform.branch") -- passing spies to run seems to break because it messes with the #len -- value (sets it to 0) t = { double: spy.new(->) square: spy.new(->) } square = (v) -> v = v[1] * v[1] t.square(v) return {v} double = (v) -> v = v[1] * 2 t.double(v) return {v} it "branch once", -> value = run({3}, {branch, double, square}) assert.spy(t.double).was.called_with(3*2) assert.spy(t.square).was.called_with(6*6) it "branch once", -> s = spy.new(-> return {}) value = run({3}, {branch, square}, {branch, double}, (v) -> s(v) return v) assert.spy(t.double).was.called_with(3*2) assert.spy(t.square).was.called_with(3*3) assert.spy(s).was.called_with({3})
22.225
72
0.559055
d280b5ba17534f45db993ac6c1f032ace28b2788
189
import Model from require "lapis.db.model" class ResourceAdmins extends Model -- Has created_at and modified_at @timestamp: true @primary_key: { "resource", "user" }
27
43
0.677249
0f999ac94b106d15b836bc7ab8372ee43ac59574
79
export class Wall extends Entity new: (x, y) => super x, y, sprites.wall
19.75
32
0.64557
67b18365056547ae749e7798352b51db4a90e16e
191
-- ::Enum(table fieldNames) -> table -- Makes a table of enumerable incremental keys -- export export Enum = (fieldNames) -> return {fieldNames[index], index - 1 for index=1, #fieldNames}
38.2
66
0.701571
91e0770cf6613a743a8c34829c4972e66c3a1b04
337
lapis = require "lapis" oleg = require "lib/oleg" class CacheBro extends lapis.Application [olegview: "/cache/:table/:key"]: => @value, @err = oleg.get @params.table, @params.key @title = "Cache view: " .. @params.table .. " -> " .. @params.key if @err ~= nil return render: "error", status: 404 render: true
24.071429
69
0.608309
c08985d221eaeb3b587f9594dd8aa5dc629be42e
237
Dorothy! AISettingView = require "View.Control.Unit.AISetting" import Struct from require "Lib.Utils" --MessageBox = require "Control.Basic.MessageBox" Class AISettingView, __init:=> @instinctPanel.itemSource = Struct.Array!
26.333333
54
0.755274
7dd31fab11e308af5ce065dbd3020e0dd2409f8f
779
export modinfo = { type: "function" id: "GetPlayers" func: (str) -> Rtn = {} plyr = PlayersService\GetPlayers! if str == "all" for _,v in pairs plyr table.insert Rtn,v elseif str == "others" for _,v in pairs plyr if v ~= LocalPlayer table.insert Rtn,v elseif str == "random" table.insert Rtn,plyr[math.random(1,#plyr)] elseif str == "me" table.insert Rtn,LocalPlayer elseif str == "vetrans" for _,v in pairs plyr if v.AccountAge > 365 table.insert Rtn,v elseif str == "nonvetrans" or str == "notvetrans" for _,v in pairs plyr if v.AccountAge < 365 table.insert Rtn,v else for _,v in pairs plyr if string.sub(string.lower(v.Name),1,#str) == string.lower(str) table.insert Rtn,v return Rtn }
24.34375
67
0.630295
b22134ab6acb0e76e23847e6306afd68a2beaaba
5,060
get_env_switch = (name) -> val = tostring os.getenv name switch val\lower! when '1', 'true', 't', 'yes', 'y' return true when '0', 'false', 'f', 'no', 'nil', 'n' return false else error "Unknown value for environment variable #{name}: #{val}" DEBUG = get_env_switch 'PRA_PDC_CLASS_DEBUG' DO_MD = get_env_switch 'PRA_PDC_CLASS_DO_MD' if FORMAT\match'markdown' or FORMAT\match'gfm' and not DO_MD -- a minimal no-op filter return { { Pandoc: -> nil } } _assert = (msg, val, lvl=0) -> if DEBUG assert val, msg elseif val return val else error msg, lvl+2 pdc = _assert "Couldn't find pandoc library. Are you running this as a Pandoc Lua filter?", pandoc ptext = _assert "Couldn't find the pandoc.text library", pdc.text stringy = => tostring @ or "" reverse_array = => n = tonumber(@n) or #@ [@[i] for i=n,1,-1] -- Syntactic sugar for HTML opening/closing tags hopen = (tag) -> pdc.RawInline 'html', "<#{tag}>" hclose = (tag) -> pdc.RawInline 'html', "</#{tag}>" -- "Wrap" an inline element in a LaTeX command. -- Arguments: -- 1. The element -- 2. The command 'begin', optionally just a string -- of letters for the command name -- 3. The 'close' of the command, by default '}' -- Returns: a Span element containing the wrapped element latex_command (elem, cmd, post='}') -> cmd = stringy cmd post = stringy post if cmd\match '^%a+$' cmd = "\\#{cmd}{" pdc.Span { pdc.RawInline('latex',cmd), elem, pdc.RawInline('latex', post), } inline2span = => switch @tag when 'Span', nil return @ else switch type @content when 'table' return pdc.Span @content else return pdc.Span {@} -- Create a closure which "wraps" its argument -- (an inline element) in a "canned" LaTeX command: -- ltc(command, close='}') ltc = (cmd, post) -> => latex_command inline2span(@), cmd, post ncc = (pre,post=pre) -> pre = "\\NoCaseChange{" .. stringy(pre) post = stringy(post) .. '}' return ltc pre, post -- "Wrap" an inline element in one or two strings, -- "removing" any "style" on the element -- Arguments: -- 1. The element -- 2. The string before the element -- 3. The string after the element, by default same as #2 string_wrap = (elem, pre, post=pre) -> return pdc.Span { pdc.Str(stringy pre), inline2span(elem), pdc.Str(stringy post), } -- Returns a closure with a canned string_wrap strw = (pre, post) -> => string_wrap inline2span(@), pre, post -- Filter to turn all Str elements uppercase uc_str = Str: => pdc.Str ptext.upper @text -- Usage: -- html_inline(elem, 'u') -- > `<u>...</u>` -- DWIM: -- html_inline(elem, 'u class="double"') -- Explicit closing tag: -- html_inline(elem, 'u class="double"', 'u') html_inline (elem, open, close) -> if nil == close close = open\match '^%a+' return pdc.Span { hopen(open), elem, hclose(close), } -- Filter to turn (sequences of) uppercase letters in Str elements into SmallCaps. -- Limitation: only works on ASCII letters (use `.sc` otherwise). -- For (Xe)LaTeX we use a command `textusc` which should be defined like this: -- -- \newcommand{\textusc}[1]{% -- {\addfontfeature{Letters=UppercaseSmallCaps}{#1}} -- } pdc_usc = { Str: => rv = {} for lc, uc in @text\gmatch '(%U*)(%u*)' if #lc > 0 rv[#rv+1] = pdc.Str lc if #uc > 0 uc = ptext.lower uc rv[#rv+1] = pdc.SmallCaps pdc.Str uc return rv } inline_class = { sc: { latex: ), plain: (=> pdc.walk_inline inline2span(@), uc_str), }, usc: { latex: ltc'textusc', plain: false, other: (=> pdc.walk_inline @, pdc_usc), }, pra: { any: strw('⟪', '⟫'), latex: ncc('⟪', '⟫'), plain: strw('«', '»'), }, gr: { other: strw('⟨', '⟩'), latex: ncc('⟨', '⟩'), plain: strw(,'‹', '›') }, ipt: { any: strw('[', ']'), latex: ncc('[', ']'), }, ipm: { any: strw'/' latex: ncc'/' } } inline_tag = { Emph: { latex: ltc'uline' plain: strw'_' }, Strong: { latex: ltc'uuline' plain: strw'__' } Strikeout: { latex: ltc'textsc' plain: => inline_class.sc.plain }, } for disps in *{inline_class, inline_tag} for name, disp in pairs disps if nil == disp.markdown disp.markdown = disp.plain inline_style = => rv = @ if @classes classes = reverse_array @classes for cls in *classes if ic = inline_class[cls][FORMAT] or inline_class[cls].other rv = ic rv elseif it = inline_tag[@tag][FORMAT] or inline_tag[@tag].other rv = it rv return rv -- replace a span with its content if it has no attributes strip_bare_span = => for a in *{@identifier, @classes, @attributes} unless a -- has no attrs? return @ -- fortunately # works on both strings and arrays if #a > 0 then return @ return @content return { { Inline: inline_style } { Span: strip_bare_span } }
23
82
0.587549
7c760feeaabbf6b50cedefc03caa6a24dbb0802e
24,863
-- -- 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. import PPM2 from _G vector_one = Vector(1, 1, 1) ENABLE_FLASHLIGHT_PASS = CreateConVar('ppm2_flashlight_pass', '1', {FCVAR_ARCHIVE}, 'Enable flashlight render pass. This kills FPS.') ENABLE_LEGS = CreateConVar('ppm2_draw_legs', '1', {FCVAR_ARCHIVE}, 'Draw pony legs.') USE_RENDER_OVERRIDE = CreateConVar('ppm2_legs_new', '1', {FCVAR_ARCHIVE}, 'Use RenderOverride function for legs drawing') LEGS_RENDER_TYPE = CreateConVar('ppm2_render_legstype', '0', {FCVAR_ARCHIVE}, 'When render legs. 0 - Before Opaque renderables; 1 - after Translucent renderables') ENABLE_STARE = CreateConVar('ppm2_render_stare', '1', {FCVAR_ARCHIVE}, 'Make eyes follow players and move when idling') SLOW_STARE_UPDATE = CreateConVar('ppm2_render_stare_slow', '0', {FCVAR_ARCHIVE}, 'Lazy stare update to save a bit frames') class PonyRenderController extends PPM2.ControllerChildren @AVALIABLE_CONTROLLERS = {} @MODELS = {'models/ppm/player_default_base.mdl', 'models/ppm/player_default_base_nj.mdl', 'models/cppm/player_default_base.mdl', 'models/cppm/player_default_base_nj.mdl'} CompileTextures: => @GetTextureController()\CompileTextures() if @GetTextureController and @GetTextureController() new: (controller) => super(controller) @hideModels = false @modelCached = controller\GetModel() @IGNORE_DRAW = false @CompileTextures() if @GetEntity()\IsValid() @CreateLegs() if @GetEntity() == LocalPlayer() @socksModel = controller\GetSocksModel() @socksModel\SetNoDraw(false) if IsValid(@socksModel) @hornModel = controller\GetSocksModel() @hornModel\SetNoDraw(false) if IsValid(@hornModel) @newSocksModel = controller\GetNewSocksModel() @newSocksModel\SetNoDraw(false) if IsValid(@newSocksModel) @clothesModel = controller\GetClothesModel() @clothesModel\SetNoDraw(false) if IsValid(@clothesModel) @lastStareUpdate = 0 @staringAt = NULL @staringAtDirectly = NULL @staringAtDirectlyLast = 0 @staringAtDirectlyTr = false @rotatedHeadTarget = false @idleEyes = true @idleEyesActive = false @nextRollEyes = 0 @rollEyesDelta = CurTimeL() if @GetEntity()\IsValid() @CreateFlexController() @CreateEmotesController() GetModel: => @controller\GetModel() GetLegs: => return NULL if not @isValid return NULL if @GetEntity() ~= LocalPlayer() @CreateLegs() if not IsValid() return @legsModel CreateLegs: => return NULL if not @isValid return NULL if @GetEntity() ~= LocalPlayer() for _, ent in ipairs ents.GetAll() if ent.isPonyLegsModel ent\Remove() with @legsModel = ClientsideModel(@modelCached) .isPonyLegsModel = true .lastRedrawFix = 0 \SetNoDraw(true) .__PPM2_PonyData = @GetData() --\PPMBonesModifier() @GrabData('WeightController')\UpdateWeight(@legsModel) @lastLegUpdate = CurTimeL() @legClipPlanePos = Vector(0, 0, 0) @legBGSetup = CurTimeL() @legUpdateFrame = 0 @legClipDot = 0 @duckOffsetHack = @@LEG_CLIP_OFFSET_STAND @legsClipPlane = @@LEG_CLIP_VECTOR return @legsModel @LEG_SHIFT_CONST = 24 @LEG_SHIFT_CONST_VEHICLE = 14 @LEG_Z_CONST = 0 @LEG_Z_CONST_VEHICLE = 20 @LEG_ANIM_SPEED_CONST = 1 @LEG_CLIP_OFFSET_STAND = 28 @LEG_CLIP_OFFSET_DUCK = 12 @LEG_CLIP_OFFSET_VEHICLE = 11 UpdateLegs: => return if not @isValid return if not ENABLE_LEGS\GetBool() return unless IsValid(@legsModel) return if @legUpdateFrame == FrameNumberL() @legUpdateFrame = FrameNumberL() ctime = CurTimeL() ply = @GetEntity() seq = ply\GetSequence() legsModel = @legsModel with @legsModel PPM2.EntityBonesModifier.ThinkObject(ply.__ppmBonesModifiers) if ply.__ppmBonesModifiers for boneid = 0, ply\GetBoneCount() - 1 \ManipulateBonePosition(0, ply\GetManipulateBonePosition(0)) \ManipulateBoneAngles(0, ply\GetManipulateBoneAngles(0)) \ManipulateBoneScale(0, ply\GetManipulateBoneScale(0)) if seq ~= @legSeq @legSeq = seq \ResetSequence(seq) if @legBGSetup < ctime @legBGSetup = ctime + 1 for _, group in ipairs ply\GetBodyGroups() \SetBodygroup(group.id, ply\GetBodygroup(group.id)) \FrameAdvance(ctime - @lastLegUpdate) \SetPlaybackRate(@@LEG_ANIM_SPEED_CONST * ply\GetPlaybackRate()) @lastLegUpdate = ctime \SetPoseParameter('move_x', (ply\GetPoseParameter('move_x') * 2) - 1) \SetPoseParameter('move_y', (ply\GetPoseParameter('move_y') * 2) - 1) \SetPoseParameter('move_yaw', (ply\GetPoseParameter('move_yaw') * 360) - 180) \SetPoseParameter('body_yaw', (ply\GetPoseParameter('body_yaw') * 180) - 90) \SetPoseParameter('spine_yaw', (ply\GetPoseParameter('spine_yaw') * 180) - 90) if ply\InVehicle() local bonePos if bone = @legsModel\LookupBone('LrigNeck1') if boneData = @legsModel\GetBonePosition(bone) bonePos = boneData veh = ply\GetVehicle() vehAng = veh\GetAngles() eyepos = EyePos() vehAng\RotateAroundAxis(vehAng\Up(), 90) clipAng = Angle(vehAng.p, vehAng.y, vehAng.r) clipAng\RotateAroundAxis(clipAng\Right(), -90) @legsClipPlane = clipAng\Forward() @legsModel\SetRenderAngles(vehAng) drawPos = Vector(@@LEG_SHIFT_CONST_VEHICLE, 0, @@LEG_Z_CONST_VEHICLE) drawPos\Rotate(vehAng) @legsModel\SetPos(eyepos - drawPos) @legsModel\SetRenderOrigin(eyepos - drawPos) if not bonePos legClipPlanePos = Vector(0, 0, @@LEG_CLIP_OFFSET_VEHICLE) legClipPlanePos\Rotate(vehAng) @legClipPlanePos = eyepos - legClipPlanePos else @legClipPlanePos = bonePos else @legsClipPlane = @@LEG_CLIP_VECTOR eangles = EyeAngles() yaw = eangles.y - ply\GetPoseParameter('head_yaw') * 180 + 90 newAng = Angle(0, yaw, 0) rad = math.rad(yaw) sin, cos = math.sin(rad), math.cos(rad) pos = ply\GetPos() {:x, :y, :z} = pos newPos = Vector(x - cos * @@LEG_SHIFT_CONST, y - sin * @@LEG_SHIFT_CONST, z + @@LEG_Z_CONST) if ply\Crouching() @duckOffsetHack = @@LEG_CLIP_OFFSET_DUCK else @duckOffsetHack = Lerp(0.1, @duckOffsetHack, @@LEG_CLIP_OFFSET_STAND) @legsModel\SetRenderAngles(newAng) @legsModel\SetAngles(newAng) @legsModel\SetRenderOrigin(newPos) @legsModel\SetPos(newPos) if bone = @legsModel\LookupBone('LrigNeck1') if boneData = @legsModel\GetBonePosition(bone) @legClipPlanePos = boneData else @legClipPlanePos = Vector(x, y, z + @duckOffsetHack) else @legClipPlanePos = Vector(x, y, z + @duckOffsetHack) @legClipDot = @legsClipPlane\Dot(@legClipPlanePos) @LEG_CLIP_VECTOR = Vector(0, 0, -1) @LEGS_MAX_DISTANCE = 60 ^ 2 DrawLegs: (start3D = false) => return if not @isValid return if not ENABLE_LEGS\GetBool() return if not @GetEntity()\Alive() return if @GetEntity()\InVehicle() and EyeAngles().p < 30 return if not @GetEntity()\InVehicle() and EyeAngles().p < 60 @CreateLegs() unless IsValid(@legsModel) return unless IsValid(@legsModel) return if @GetEntity()\ShouldDrawLocalPlayer() return if (@GetEntity()\GetPos() + @GetEntity()\GetViewOffset())\DistToSqr(EyePos()) > @@LEGS_MAX_DISTANCE if USE_RENDER_OVERRIDE\GetBool() @legsModel\SetNoDraw(false) rTime = RealTimeL() if @legsModel.lastRedrawFix < rTime @UpdateLegs() @legsModel\DrawModel() @legsModel.lastRedrawFix = rTime + 2 if not @legsModel.RenderOverride @legsModel.RenderOverride = -> @DrawLegsOverride() @UpdateLegs() @legsModel\DrawModel() return else @legsModel\SetNoDraw(true) @legsModel.RenderOverride = nil return if hook.Run('PPM2_ShouldDrawLegs', @GetEntity(), @legsModel) == false @UpdateLegs() oldClip = render.EnableClipping(true) render.PushCustomClipPlane(@legsClipPlane, @legClipDot) cam.Start3D() if start3D @GetTextureController()\PreDrawLegs(@legsModel) @legsModel\DrawModel() @GetTextureController()\PostDrawLegs(@legsModel) if LEGS_RENDER_TYPE\GetBool() and ENABLE_FLASHLIGHT_PASS\GetBool() render.PushFlashlightMode(true) @GetTextureController()\PreDrawLegs(@legsModel) if sizes = @GrabData('SizeController') sizes\ModifyNeck(@legsModel) sizes\ModifyLegs(@legsModel) sizes\ModifyScale(@legsModel) @legsModel\DrawModel() @GetTextureController()\PostDrawLegs(@legsModel) render.PopFlashlightMode() render.PopCustomClipPlane() cam.End3D() if start3D render.EnableClipping(oldClip) DrawLegsOverride: => return if not @isValid return if not ENABLE_LEGS\GetBool() return if not @GetEntity()\Alive() return if @GetEntity()\InVehicle() and EyeAngles().p < 30 return if not @GetEntity()\InVehicle() and EyeAngles().p < 60 return if @GetEntity()\ShouldDrawLocalPlayer() return if (@GetEntity()\GetPos() + @GetEntity()\GetViewOffset())\DistToSqr(EyePos()) > @@LEGS_MAX_DISTANCE return if hook.Run('PPM2_ShouldDrawLegs', @GetEntity(), @legsModel) == false @UpdateLegs() oldClip = render.EnableClipping(true) render.PushCustomClipPlane(@legsClipPlane, @legClipDot) @GetTextureController()\PreDrawLegs(@legsModel) @legsModel\DrawModel() @GetTextureController()\PostDrawLegs(@legsModel) render.PopCustomClipPlane() render.EnableClipping(oldClip) DrawLegsDepth: (start3D = false) => return if not @isValid return if not ENABLE_LEGS\GetBool() return if not @GetEntity()\Alive() return if @GetEntity()\InVehicle() and EyeAngles().p < 30 return if not @GetEntity()\InVehicle() and EyeAngles().p < 60 @CreateLegs() unless IsValid(@legsModel) return unless IsValid(@legsModel) return if @GetEntity()\ShouldDrawLocalPlayer() return if (@GetEntity()\GetPos() + @GetEntity()\GetViewOffset())\DistToSqr(EyePos()) > @@LEGS_MAX_DISTANCE @UpdateLegs() oldClip = render.EnableClipping(true) render.PushCustomClipPlane(@legsClipPlane, @legClipDot) cam.Start3D() if start3D @GetTextureController()\PreDrawLegs(@legsModel) if sizes = @GrabData('SizeController') sizes\ModifyNeck(@legsModel) sizes\ModifyLegs(@legsModel) sizes\ModifyScale(@legsModel) @legsModel\DrawModel() @GetTextureController()\PostDrawLegs() render.PopCustomClipPlane() cam.End3D() if start3D render.EnableClipping(oldClip) IsValid: => IsValid(@GetEntity()) and @isValid Reset: => @flexes\Reset() if @flexes and @flexes.Reset @emotes\Reset() if @emotes and @emotes.Reset @GetTextureController()\Reset() if @GetTextureController and @GetTextureController() and @GetTextureController().Reset @GetTextureController()\ResetTextures() if @GetTextureController and @GetTextureController() Remove: => @flexes\Remove() if @flexes @emotes\Remove() if @emotes @GetTextureController()\Remove() if @GetTextureController and @GetTextureController() @isValid = false PlayerDeath: => return if not @isValid if @emotes @emotes\Remove() @emotes = nil @HideModels(true) if PPM2.ENABLE_NEW_RAGDOLLS\GetBool() @GetTextureController()\ResetTextures() if @GetTextureController() and @GetEntity()\IsPony() PlayerRespawn: => return if not @isValid @GetEmotesController() @HideModels(false) if @GetEntity()\IsPony() @flexes\PlayerRespawn() if @flexes @GetTextureController()\ResetTextures() if @GetTextureController() DrawModels: => @socksModel\DrawModel() if IsValid(@socksModel) @newSocksModel\DrawModel() if IsValid(@newSocksModel) @hornModel\DrawModel() if IsValid(@hornModel) @clothesModel\DrawModel() if IsValid(@clothesModel) ShouldHideModels: => @hideModels or @GetEntity()\GetNoDraw() DoHideModels: (status) => @socksModel\SetNoDraw(status) if IsValid(@socksModel) @newSocksModel\SetNoDraw(status) if IsValid(@newSocksModel) @hornModel\SetNoDraw(status) if IsValid(@hornModel) @clothesModel\SetNoDraw(status) if IsValid(@clothesModel) HideModels: (status = true) => return if @hideModels == status @DoHideModels(status) @hideModels = status CheckTarget: (epos, pos) => return not util.TraceLine({ start: epos, endpos: pos, filter: @GetEntity(), mask: MASK_BLOCKLOS }).Hit UpdateStare: => ctime = RealTimeL() return if @lastStareUpdate > ctime and SLOW_STARE_UPDATE\GetBool() if (not @idleEyes or not ENABLE_STARE\GetBool()) and @idleEyesActive @staringAt = NULL @GetEntity()\SetEyeTarget(vector_origin) @idleEyesActive = false return return if not @idleEyes or not ENABLE_STARE\GetBool() @idleEyesActive = true @lastStareUpdate = ctime + 0.2 lpos = @GetEntity()\EyePos() lang = @GetEntity()\EyeAnglesFixed() lply = LocalPlayer() if @GetEntity() == lply and IsValid(PPM2.EditorTopFrame) and PPM2.EditorTopFrame\IsVisible() if PPM2.EditorTopFrame.calcPanel and PPM2.EditorTopFrame.calcPanel.drawPos and PPM2.EditorTopFrame.calcPanel.drawAngle origin, angles = LocalToWorld(PPM2.EditorTopFrame.calcPanel.drawPos, PPM2.EditorTopFrame.calcPanel.drawAngle, lply\GetPos(), Angle(0, lply\EyeAnglesFixed().y, 0)) origin, angles = WorldToLocal(origin, angles, lpos, lang) @staringAt = NULL @staringAtDirectly = NULL @idleEyes = true @eyeRollTargetPos = origin @prevRollTargetPos = origin return @staringAt = NULL if IsValid(@staringAt) and @staringAt\IsPlayer() and not @staringAt\Alive() trNew = util.TraceLine({ start: lpos, endpos: lpos + lang\Forward() * 270, filter: @GetEntity(), }) if IsValid(trNew.Entity) mins, maxs = trNew.Entity\OBBMins(), trNew.Entity\OBBMaxs() size = mins\Distance(maxs) if size < 140 @staringAtDirectly = trNew.Entity @staringAtDirectlyLast = CurTimeL() + 2.5 @staringAtDirectlyTr = trNew if IsValid(@staringAtDirectly) and (not @staringAtDirectly\IsPlayer() and not @staringAtDirectly\IsNPC()) if @staringAtDirectlyLast > CurTimeL() pos = @staringAtDirectlyTr.HitPos if pos\Distance(lpos) < 300 and DLib.combat.inPVS(@GetEntity(), @staringAtDirectly) and @CheckTarget(lpos, pos) @GetEntity()\SetEyeTarget(pos) _lpos, _lang = WorldToLocal(pos, angle_zero, lpos, lang) @prevRollTargetPos = _lpos return @staringAtDirectly = NULL @staringAtDirectlyLast = 0 @GetEntity()\SetEyeTarget(vector_origin) else @staringAtDirectly = NULL if trNew.Entity\IsValid() and (trNew.Entity\IsPlayer() or trNew.Entity\IsNPC()) @staringAt = trNew.Entity if IsValid(@staringAt) epos = @staringAt\EyePos() if epos\Distance(lpos) < 300 and DLib.combat.inPVS(@GetEntity(), @staringAt) and @CheckTarget(lpos, epos) @GetEntity()\SetEyeTarget(epos) @prevRollTargetPos = epos return @staringAt = NULL @GetEntity()\SetEyeTarget(vector_origin) if player.GetCount() ~= 1 local last max = 300 local lastpos for _, ply in ipairs player.GetAll() if @GetEntity() ~= ply and ply\Alive() epos = ply\EyePos() dist = epos\Distance(lpos) if dist < max and DLib.combat.inPVS(@GetEntity(), ply) and @CheckTarget(lpos, epos) max = dist last = ply lastpos = epos if last @GetEntity()\SetEyeTarget(lastpos) @staringAt = last return return if @nextRollEyes > ctime @nextRollEyes = ctime + math.random(4, 8) / 6 @eyeRollTargetPos = Vector(math.random(200, 400), math.random(-80, 80), math.random(-20, 20)) @prevRollTargetPos = @prevRollTargetPos or @eyeRollTargetPos -- @GetEntity()\SetEyeTarget(@prevRollTargetPos) UpdateEyeRoll: => return if not ENABLE_STARE\GetBool() or not @idleEyes or not @eyeRollTargetPos or IsValid(@staringAt) or IsValid(@staringAtDirectly) ctime = CurTimeL() delta = ctime - @rollEyesDelta @rollEyesDelta = ctime @prevRollTargetPos = LerpVector(delta * 25, @prevRollTargetPos, @eyeRollTargetPos) roll = Vector(@prevRollTargetPos) roll\Rotate(@GetEntity()\EyeAnglesFixed()) @GetEntity()\SetEyeTarget(@GetEntity()\EyePos() + roll) CalculateHideModels: (ent = @GetEntity()) => ent.RenderOverride and not ent.__ppm2RenderOverride and @GrabData('HideManes') and @GrabData('HideManesSocks') CheckModelHide: (ent = @GetEntity()) => if @CalculateHideModels(ent) @socksModel\SetNoDraw(true) if IsValid(@socksModel) @newSocksModel\SetNoDraw(true) if IsValid(@newSocksModel) @hornModel\SetNoDraw(true) if IsValid(@hornModel) @clothesModel\SetNoDraw(true) if IsValid(@clothesModel) else @socksModel\SetNoDraw(@ShouldHideModels()) if IsValid(@socksModel) @newSocksModel\SetNoDraw(@ShouldHideModels()) if IsValid(@newSocksModel) @hornModel\SetNoDraw(@ShouldHideModels()) if IsValid(@hornModel) @clothesModel\SetNoDraw(@ShouldHideModels()) if IsValid(@clothesModel) PreDraw: (ent = @GetEntity(), drawingNewTask = false) => return if not @isValid with @GetTextureController() \PreDraw(ent, drawingNewTask) if drawingNewTask with bones = ent\PPMBonesModifier() \ResetBones() hook.Call('PPM2.SetupBones', nil, ent, @controller) \Think(true) ent.__ppmBonesModified = true @flexes\Think(ent) if @flexes @emotes\Think(ent) if @emotes if ent\IsPlayer() @UpdateStare() @UpdateEyeRoll() @CheckModelHide(ent) PostDraw: (ent = @GetEntity(), drawingNewTask = false) => return if not @isValid @GetTextureController()\PostDraw(ent, drawingNewTask) @HANDS_MATERIAL_INDEX = 1 @MAGIC_ARMS_MATERIAL_INDEX = 0 PreDrawArms: (ent) => return if not @isValid hooves = @GrabData('PonyRaceFlags')\band(PPM2.RACE_HAS_HORN) == 0 or not PPM2.VM_MAGIC_HANDS\GetBool() if ent and hooves weight = 1 + (@GrabData('Weight') - 1) vec = Vector(weight, weight, weight) ent\ManipulateBoneScale(i, vec) for i = 1, 43 elseif ent ent\ManipulateBoneScale(i, vector_one) for i = 1, 13 if hooves ent\SetSubMaterial(@@HANDS_MATERIAL_INDEX, @GetTextureController()\GetBodyName()) PostDrawArms: (ent) => return if not @isValid hooves = @GrabData('PonyRaceFlags')\band(PPM2.RACE_HAS_HORN) == 0 ent\SetSubMaterial(@@HANDS_MATERIAL_INDEX, '') if hooves DataChanges: (state) => return if not @isValid return if not @GetEntity() @GetTextureController()\DataChanges(state) @flexes\DataChanges(state) if @flexes @emotes\DataChanges(state) if @emotes switch state\GetKey() when 'Weight' @armsWeightSetup = false @GrabData('WeightController')\UpdateWeight(@legsModel) if IsValid(@legsModel) when 'SocksModel' @socksModel = state\GetValue() -- @socksModel\SetNoDraw(@ShouldHideModels()) if IsValid(@socksModel) @CheckModelHide() @GetTextureController()\UpdateSocks(@GetEntity(), @socksModel) if @GetTextureController() and IsValid(@socksModel) when 'NewSocksModel' @newSocksModel = state\GetValue() -- @newSocksModel\SetNoDraw(@ShouldHideModels()) if IsValid(@newSocksModel) @CheckModelHide() @GetTextureController()\UpdateNewSocks(@GetEntity(), @newSocksModel) if @GetTextureController() and IsValid(@newSocksModel) when 'HornModel' @hornModel = state\GetValue() -- @hornModel\SetNoDraw(@ShouldHideModels()) if IsValid(@hornModel) @CheckModelHide() @GetTextureController()\UpdateNewHorn(@GetEntity(), @hornModel) if @GetTextureController() and IsValid(@hornModel) when 'ClothesModel' @clothesModel = state\GetValue() -- @clothesModel\SetNoDraw(@ShouldHideModels()) if IsValid(@clothesModel) @CheckModelHide() @GetTextureController()\UpdateClothes(@GetEntity(), @clothesModel) if @GetTextureController() and IsValid(@clothesModel) when 'NoFlex' if state\GetValue() @flexes\ResetSequences() if @flexes @flexes = nil else @CreateFlexController() when 'EyeIrisBottom', 'EyeIrisBottomLeft', 'EyeIrisBottomRight', 'SeparateEyes', 'HornMagicColor', 'EyeIrisTop', 'EyeIrisTopLeft', 'EyeIrisTopRight' if @GetEntity() == LocalPlayer() PPM2.MaterialsRegistry.MAGIC_HANDS_MATERIAL\SetVector('$colortint_base', @GetData()\ComputeMagicColor()\ToVector()) GetTextureController: => return @renderController if not @isValid if not @renderController cls = PPM2.GetTextureController(@modelCached) @renderController = cls(@) @renderController.ent = @GetEntity() return @renderController CreateFlexController: => return @flexes if not @isValid return if @GrabData('NoFlex') if not @flexes cls = PPM2.GetFlexController(@modelCached) return if not cls @flexes = cls(@) @flexes.ent = @GetEntity() return @flexes CreateEmotesController: => return @emotes if not @isValid if not @emotes or not @emotes\IsValid() cls = PPM2.GetPonyExpressionsController(@modelCached) return if not cls @emotes = cls(@) @emotes.ent = @GetEntity() return @emotes GetFlexController: => @flexes GetEmotesController: => @emotes class NewPonyRenderController extends PonyRenderController @MODELS = {'models/ppm/player_default_base_new.mdl', 'models/ppm/player_default_base_new_nj.mdl'} new: (data) => super(data) @upperManeModel = data\GetUpperManeModel() @lowerManeModel = data\GetLowerManeModel() @tailModel = data\GetTailModel() @upperManeModel\SetNoDraw(@ShouldHideModels()) if IsValid(@upperManeModel) @lowerManeModel\SetNoDraw(@ShouldHideModels()) if IsValid(@lowerManeModel) @tailModel\SetNoDraw(@ShouldHideModels()) if IsValid(@tailModel) __tostring: => "[#{@@__name}:#{@objID}|#{@GetData()}]" DataChanges: (state) => return if not @GetEntity() return if not @isValid switch state\GetKey() when 'UpperManeModel' @upperManeModel = @GrabData('UpperManeModel') --@upperManeModel\SetNoDraw(@ShouldHideModels()) if IsValid(@upperManeModel) @CheckModelHide() @GetTextureController()\UpdateUpperMane(@GetEntity(), @upperManeModel) if @GetTextureController() and IsValid(@upperManeModel) when 'LowerManeModel' @lowerManeModel = @GrabData('LowerManeModel') --@lowerManeModel\SetNoDraw(@ShouldHideModels()) if IsValid(@lowerManeModel) @CheckModelHide() @GetTextureController()\UpdateLowerMane(@GetEntity(), @lowerManeModel) if @GetTextureController() and IsValid(@lowerManeModel) when 'TailModel' @tailModel = @GrabData('TailModel') --@tailModel\SetNoDraw(@ShouldHideModels()) if IsValid(@tailModel) @CheckModelHide() @GetTextureController()\UpdateTail(@GetEntity(), @tailModel) if @GetTextureController() and IsValid(@tailModel) super(state) DrawModels: => @upperManeModel\DrawModel() if IsValid(@upperManeModel) @lowerManeModel\DrawModel() if IsValid(@lowerManeModel) @tailModel\DrawModel() if IsValid(@tailModel) super() DoHideModels: (status) => super(status) @upperManeModel\SetNoDraw(status) if IsValid(@upperManeModel) @lowerManeModel\SetNoDraw(status) if IsValid(@lowerManeModel) @tailModel\SetNoDraw(status) if IsValid(@tailModel) PreDraw: (ent = @GetEntity(), drawingNewTask = false) => super(ent, drawingNewTask) if ent.RenderOverride and not ent.__ppm2RenderOverride and @GrabData('HideManes') @upperManeModel\SetNoDraw(true) if IsValid(@upperManeModel) and @GrabData('HideManesMane') @lowerManeModel\SetNoDraw(true) if IsValid(@lowerManeModel) and @GrabData('HideManesMane') @tailModel\SetNoDraw(true) if IsValid(@tailModel) and @GrabData('HideManesTail') else @upperManeModel\SetNoDraw(@ShouldHideModels()) if IsValid(@upperManeModel) @lowerManeModel\SetNoDraw(@ShouldHideModels()) if IsValid(@lowerManeModel) @tailModel\SetNoDraw(@ShouldHideModels()) if IsValid(@tailModel) hook.Add 'NotifyShouldTransmit', 'PPM2.RenderController', (should) => if data = @GetPonyData() if renderer = data\GetRenderController() renderer\HideModels(not should) PPM2.PonyRenderController = PonyRenderController PPM2.NewPonyRenderController = NewPonyRenderController PPM2.GetPonyRenderController = (model = 'models/ppm/player_default_base.mdl') -> PonyRenderController.AVALIABLE_CONTROLLERS[model\lower()] or PonyRenderController PPM2.GetPonyRendererController = PPM2.GetPonyRenderController PPM2.GetRenderController = PPM2.GetPonyRenderController PPM2.GetRendererController = PPM2.GetPonyRenderController
36.349415
171
0.730322
46982f840616f9890dbde688f48001097835b428
1,550
export modinfo = { type: "function" id: "LoadProBlet" func: -> pcall -> LocalPlayer.Character = nil if ConfigSystem("Get", "AutomaticallyRemovePlayer") LocalPlayer.Parent = nil LocalPlayer.Character = nil om = CreateInstance"Part"{ Parent: workspace Shape: "Ball" Size: Vector3.new(3, 3, 3) TopSurface: "Smooth" BottomSurface: "Smooth" BrickColor: BrickColor.new("Black") Material: "Plastic" Anchored: true CanCollide: false } oo = CreateInstance"Part"{ Parent: workspace Shape: "Ball" Size: Vector3.new(5, 5, 5) TopSurface: "Smooth" BottomSurface: "Smooth" BrickColor: BrickColor.new("Black") Material: "Plastic" Transparency: .7 Anchored: true CanCollide: false CreateInstance"PointLight"{ Range: ConfigSystem("Get", "ProbeLightRange") Brightness: ConfigSystem("Get", "ProbeLightBrightness") Color: ConfigSystem("Get", "ProbeLightColour") Enabled: true } } BB = CreateInstance"BillboardGui"{ Parent: oo Size: UDim2.new(3, 0, 3 ,0) ExtentsOffset: Vector3.new(0, 2, 0) CreateInstance"TextLabel"{ FontSize: "Size36" Font: "ArialBold" Text: CharacterName TextTransparency: .3 BackgroundTransparency: 1 TextColor3: Color3.new! TextStrokeTransparency: 0 Size: UDim2.new(1,0,1,0) } } Probe = oo Spawn -> while oo\IsDescendantOf(workspace) and wait! oo.CFrame = ConfigSystem("Get", "Camera").Focus om.CFrame = ConfigSystem("Get", "Camera").Focus oo.Parent = nil om.Parent = nil }
25
59
0.666452
39b28c19594513e7ef079fca63c59a050f2a197b
3,922
import pairs, print, type from _G import match from string import sort, remove from table import Command from "novacbn/command-ops/Command" import layoutText, parseArguments from "novacbn/command-ops/utilities" -- ::PATTERN_BINARY_NAME -> string -- Represents a Lua pattern to validate the command's binary -- PATTERN_BINARY_NAME = "^[%w%-%.%_]+$" -- ::TEMPLATE_HELP_TEXT(string name, string version?, string binary, string commands) -> string -- Formats the help text for the main command -- TEMPLATE_HELP_TEXT = (name, version, binary, commands) -> "#{name}#{version and ' :: '..version or ''} Usage: #{binary} [flags] [command] Commands: #{commands}" -- CommandOps::CommandOps() -- Represents the main CLI configurator -- export export CommandOps = (cliName, binary, version) -> error("bad argument #1 to 'CommandOps' (expected string)") unless type(cliName) == "string" error("bad argument #2 to 'CommandOps' (expected string)") unless type(binary) == "string" error("bad argument #2 to 'CommandOps' (malformed binary)") unless match(binary, PATTERN_BINARY_NAME) error("bad argument #3 to 'CommandOps' (expected string)") unless version == nil or type(version) == "string" return { -- CommandOps::binary -> string -- Represents the name of the command's binary -- binary: binary -- CommandOps::commands -> table -- Represents the configured sub commands of the command -- commands: {} -- CommandOps::name -> string -- Represents the full-text name of the command -- name: name -- CommandOps::version -> string -- Represents the version of the command -- version: version -- CommandOps::command(string name, string description, function callback) -> void -- Registers a new sub command -- command: (name, description, callback) => error("bad argument #1 to 'command' (expected string)") unless type(name) == "string" error("bad argument #1 to 'command' (existing command)") if @commands[name] error("bad argument #2 to 'command' (expected string)") unless type(description) == "string" error("bad argument #3 to 'command' (expected function)") unless type(callback) == "function" command = Command(name, description, callback) @commands[name] = command return command -- CommandOps::exec(table arguments) -> void -- Routes and executes to the appropriate sub command -- exec: (arguments) => arguments, flags = parseArguments(arguments) name = remove(arguments, 1) if name == nil or name == "help" then @printHelp(arguments[1]) elseif @commands[name] command = @commands[name] command\exec(binary, flags, arguments) else print("unknown command '#{name}'") -- CommandOps::formatHelp() -> string -- Formats the help text of the command -- formatHelp: () => commands = [name for name, command in pairs(@commands)] sort(commands) commands = [" "..name.."\t"..@commands[name].description for name in *commands] commands = layoutText(commands, 4) return TEMPLATE_HELP_TEXT(cliName, version, binary, commands) -- CommandOps::printHelp(string name?) -> void -- Prints the help text for the relevant sub command -- printHelp: (name) => unless name print(@formatHelp()) return command = @commands[name] unless command if name then print("unknown command '#{name}'") else print("missing command") else print(command\formatHelp(binary)) }
38.45098
113
0.600969
6952373e32471765e03693356dcf1ec9fe350d2f
13,666
-- Copyright 2012-2015 The Howl Developers -- License: MIT (see LICENSE.md at the top-level directory of the distribution) import Scintilla, styler, BufferContext, BufferLines, Chunk, config, signal from howl import File from howl.io import style from howl.ui import PropertyObject from howl.aux.moon import destructor from howl.aux ffi = require 'ffi' append = table.insert background_sci = Scintilla! background_sci\set_lexer Scintilla.SCLEX_NULL background_buffer = setmetatable {}, __mode: 'v' buffer_titles = setmetatable {}, __mode: 'v' title_counters = {} file_title = (file) -> title = file.basename while buffer_titles[title] file = file.parent return title if not file title = file.basename .. File.separator .. title title title_counter = (title) -> title_counters[title] = 1 if not title_counters[title] title_counters[title] += 1 title_counters[title] class Buffer extends PropertyObject new: (mode = {}, sci) => super! @_scis = setmetatable {}, __mode: 'v' if sci @_sci = sci @doc = sci\get_doc_pointer! append @_scis, sci else @doc = background_sci\create_document! @destructor = destructor background_sci\release_document, @doc @config = config.local_proxy! @completers = {} @mode = mode @properties = {} @data = {} @_len = nil @sci_listener = on_text_inserted: self\_on_text_inserted on_text_deleted: self\_on_text_deleted @property file: get: => @_file set: (file) => @_associate_with_file file if file.exists @text = file.contents @sync_etag = file.etag else @text = '' @sync_etag = nil @modified = false @can_undo = false @property mode: get: => @_mode set: (mode = {}) => old_mode = @_mode had_lexer = old_mode and old_mode.lexer @_mode = mode @config.chain_to mode.config has_lexer = mode.lexer lexer = has_lexer and Scintilla.SCLEX_CONTAINER or Scintilla.SCLEX_NULL sci\set_lexer lexer for sci in *@scis if has_lexer @sci\colourise 0, @sci\get_end_styled! elseif had_lexer styler.clear_styling @sci, self signal.emit 'buffer-mode-set', buffer: self, :mode, :old_mode @property title: get: => @_title or 'Untitled' set: (title) => buffer_titles[@_title] = nil if @_title title ..= '<' .. title_counter(title) .. '>' if buffer_titles[title] @_title = title buffer_titles[title] = self signal.emit 'buffer-title-set', buffer: self @property text: get: => @sci\get_text! set: (text) => @sci\clear_all! @sci\set_code_page Scintilla.SC_CP_UTF8 @sci\add_text #text, text @property modified: get: => @sci\get_modify! set: (status) => if not status then @sci\set_save_point! else -- there's no specific message for marking as modified @append ' ' @sci\delete_range @size - 1, 1 @property can_undo: get: => @sci\can_undo! set: (value) => @sci\empty_undo_buffer! if not value @property size: get: => @sci\get_text_length! @property length: get: => @_len or= @sci\character_count! @_len @property lines: get: => BufferLines self, @sci @property eol: get: => switch @sci\get_eolmode! when Scintilla.SC_EOL_LF then '\n' when Scintilla.SC_EOL_CRLF then '\r\n' when Scintilla.SC_EOL_CR then '\r' set: (eol) => s_mode = switch eol when '\n' then Scintilla.SC_EOL_LF when '\r\n' then Scintilla.SC_EOL_CRLF when '\r' then Scintilla.SC_EOL_CR else error 'Unknown eol mode' @sci\set_eolmode s_mode @property showing: get: => #@scis > 0 @property last_shown: get: => #@scis > 0 and os.time! or @_last_shown set: (timestamp) => @_last_shown = timestamp @property destroyed: get: => @doc == nil @property multibyte: get: => @sci\is_multibyte! @property modified_on_disk: get: => return false if not @file or not @file.exists @file and @file.etag != @sync_etag @property read_only: get: => @sci\get_read_only! set: (status) => @sci\set_read_only status destroy: => return if @destroyed error 'Cannot destroy a currently showing buffer', 2 if @showing if @destructor @destructor.defuse! @sci\release_document @doc @destructor = nil @doc = nil chunk: (start_pos, end_pos) => Chunk self, start_pos, end_pos context_at: (pos) => BufferContext self, pos delete: (start_pos, end_pos) => return if start_pos > end_pos b_start, b_end = @byte_offset(start_pos), @byte_offset(end_pos + 1) @sci\delete_range b_start - 1, b_end - b_start insert: (text, pos) => b_pos = @byte_offset pos @sci\insert_text b_pos - 1, text pos + text.ulen append: (text) => @sci\append_text #text, text @length + 1 replace: (pattern, replacement) => matches = {} pos = 1 text = @text while pos < @length start_pos, end_pos, match = text\ufind pattern, pos break unless start_pos -- only replace the match within pattern if present end_pos = match and (start_pos + #match - 1) or end_pos append matches, start_pos append matches, end_pos pos = end_pos + 1 return if #matches == 0 b_offsets = text\byte_offset matches for i = #b_offsets, 1, -2 start_pos = b_offsets[i - 1] end_pos = b_offsets[i] with @sci \set_target_start start_pos - 1 \set_target_end end_pos \replace_target -1, replacement #matches / 2 save: => if @file if @config.strip_trailing_whitespace ws = '[\t ]' @replace "(#{ws}+)#{@eol}", '' @replace "(#{ws}+)#{@eol}?$", '' if @config.ensure_newline_at_eof and not @text\match "#{@eol}$" @append @eol @file.contents = @text @modified = false @sync_etag = @file.etag signal.emit 'buffer-saved', buffer: self save_as: (file) => @_associate_with_file file @save! as_one_undo: (f) => @sci\begin_undo_action! status, ret = pcall f @sci\end_undo_action! error ret if not status undo: => @sci\undo! redo: => @sci\redo! char_offset: (byte_offset) => if byte_offset < 1 or byte_offset > @size + 1 error "Byte offset '#{byte_offset}' out of bounds (size = #{@size})", 2 1 + @sci\char_offset byte_offset - 1 byte_offset: (char_offset) => if char_offset < 1 or char_offset > @length + 1 error "Character offset '#{char_offset}' out of bounds (length = #{@length})", 2 1 + @sci\byte_offset char_offset - 1 sub: (start_pos, end_pos = -1) => len = @length start_pos += len + 1 if start_pos < 0 end_pos += len + 1 if end_pos < 0 start_pos = 1 if start_pos < 1 end_pos = len if end_pos > len byte_start_pos = @\byte_offset(start_pos) -- we find the start of the next character -- to include the last byte in a multibyte character byte_end_pos = @\byte_offset(end_pos + 1) byte_size = byte_end_pos - byte_start_pos return '' if byte_size <= 0 ffi.string @sci\get_range_pointer(byte_start_pos - 1, byte_size), byte_size rfind_line: (search, init = @length, lineEnd, lineStart) => init = lineEnd if init == @length if init < 0 init = lineEnd + init + 1 if init < 1 or init > lineEnd return nil -- use byte offset of last byte of char at init byte_start_pos = @text\rfind search, @byte_offset(init + 1) - 1 if byte_start_pos if byte_start_pos >= lineStart start_pos = @char_offset byte_start_pos return start_pos, start_pos + search.ulen - 1 nil find_line: (search, init = 1, lineEnd, lineStart) => if init < 0 init = lineEnd + init + 1 if init < 1 or init > lineEnd return nil byte_start_pos, byte_end_pos = @text\find search, @byte_offset(init), true if byte_start_pos if lineEnd >= byte_start_pos and lineStart <= byte_start_pos start_pos = @char_offset byte_start_pos end_pos = @char_offset(byte_end_pos + 1) - 1 return start_pos, end_pos nil begin_line: (init = 1) => return @sci\position_from_line(@sci\line_from_position(init-1))+1 end_line: (init = 1) => return @sci\get_line_end_position(@sci\line_from_position(init-1))-1 find: (search, init = 1) => if init < 0 init = @length + init + 1 if init < 1 or init > @length return nil byte_start_pos, byte_end_pos = @text\find search, @byte_offset(init), true if byte_start_pos start_pos = @char_offset byte_start_pos end_pos = @char_offset(byte_end_pos + 1) - 1 return start_pos, end_pos nil rfind: (search, init = @length) => if init < 0 init = @length + init + 1 if init < 1 or init > @length return nil -- use byte offset of last byte of char at init byte_start_pos = @text\rfind search, @byte_offset(init + 1) - 1 if byte_start_pos start_pos = @char_offset byte_start_pos return start_pos, start_pos + search.ulen - 1 nil reload: (force = false) => error "Cannot reload buffer '#{self}': no associated file", 2 unless @file return false if @modified and not force @file = @file signal.emit 'buffer-reloaded', buffer: self true @property sci: get: => error 'Attempt to invoke operation on destroyed buffer', 3 if @destroyed if @_sci then return @_sci if background_buffer[1] != self background_sci\set_doc_pointer self.doc background_sci\set_code_page Scintilla.SC_CP_UTF8 background_buffer[1] = self background_sci.listener = @sci_listener background_sci lex: (end_pos = @size) => if @_mode.lexer styler.style_text self, end_pos, @_mode.lexer add_sci_ref: (sci) => append @_scis, sci @_sci = sci if background_buffer[1] == self background_sci.listener = nil background_buffer[1] = nil sci\set_code_page Scintilla.SC_CP_UTF8 sci\set_style_bits 8 sci\set_lexer @_mode.lexer and Scintilla.SCLEX_CONTAINER or Scintilla.SCLEX_NULL remove_sci_ref: (sci) => @_scis = [s for s in *@_scis when s != sci and s != nil] @_sci = @_scis[1] if sci == @_sci @property scis: get: => [sci for _, sci in pairs @_scis when sci != nil] _associate_with_file: (file) => buffer_titles[@_title] = nil if @_title @_file = file @title = file_title file _on_text_inserted: (args) => @_len = nil args.buffer = self signal.emit 'text-inserted', args signal.emit 'buffer-modified', buffer: self _on_text_deleted: (args) => @_len = nil args.buffer = self signal.emit 'text-deleted', args signal.emit 'buffer-modified', buffer: self @meta { __len: => @length __tostring: => @title } -- Config variables with config .define name: 'strip_trailing_whitespace' description: 'Whether trailing whitespace will be removed upon save' default: true type_of: 'boolean' .define name: 'ensure_newline_at_eof' description: 'Whether to ensure a trailing newline is present at eof upon save' default: true type_of: 'boolean' -- Signals with signal .register 'buffer-saved', description: 'Signaled right after a buffer was saved', parameters: buffer: 'The buffer that was saved' .register 'text-inserted', description: [[ Signaled right after text has been inserted into an editor. No additional modifications may be done within the signal handler. ]] parameters: buffer: 'The buffer for which the text was inserted' editor: '(Optional) The editor containing the buffer' at_pos: 'The byte start position of the inserted text' length: 'The number of characters in the inserted text' text: 'The text that was inserted' lines_added: 'The number of lines that were added' as_undo: 'The text was inserted as part of an undo operation' as_redo: 'The text was inserted as part of a redo operation' .register 'text-deleted', description: [[ Signaled right after text was deleted from the editor. No additional modifications may be done within the signal handler. ]] parameters: buffer: 'The buffer for which the text was deleted' editor: '(Optional) The editor containing the buffer' at_pos: 'The byte start position of the deleted text' length: 'The number of characters that was deleted' text: 'The text that was deleted' lines_deleted: 'The number of lines that were deleted' as_undo: 'The text was deleted as part of an undo operation' as_redo: 'The text was deleted as part of a redo operation' .register 'buffer-modified', description: 'Signaled right after a buffer was modified', parameters: buffer: 'The buffer that was modified' as_undo: 'The buffer was modified as the result of an undo operation' as_redo: 'The buffer was modified as the result of a redo operation' .register 'buffer-reloaded', description: 'Signaled right after a buffer was reloaded', parameters: buffer: 'The buffer that was reloaded' .register 'buffer-mode-set', description: 'Signaled right after a buffer had its mode set', parameters: buffer: 'The target buffer' mode: 'The new mode that was set' old_mode: 'The old mode if any' .register 'buffer-title-set', description: 'Signaled right after a buffer had its title set', parameters: buffer: 'The buffer receiving the new title' return Buffer
27.889796
86
0.649202
ff4c691f87812767a71951526ee69f8860c2c61e
4,069
import Buffer from howl import Editor from howl.ui import auto_pair from howl.editing describe 'auto_pair', -> describe 'handle(event, editor)', -> local buffer, editor, cursor event = (character, key_name = character) -> :character, :key_name, key_code: 65 before_each -> buffer = Buffer! editor = Editor buffer cursor = editor.cursor buffer.text = '' context 'when the character matches a known pair from buffer.mode.auto_pairs', -> before_each -> buffer.mode.auto_pairs = { '(': ')' '[': ']' '"': '"' } context 'when there is an active selection', -> before_each -> buffer.text = ' foo ' editor.selection\set 2, 5 it 'surrounds the selection with the pair as one undo operation', -> auto_pair.handle event('('), editor assert.equal ' (foo) ', buffer.text buffer\undo! assert.equal ' foo ', buffer.text it 'returns true', -> assert.is_true auto_pair.handle event('('), editor context 'with no selection active', -> it 'returns true', -> assert.is_true auto_pair.handle event('('), editor it 'inserts the pair in the buffer, as one undo operation', -> for start_c, end_c in pairs buffer.mode.auto_pairs auto_pair.handle event(start_c), editor assert.equal "#{start_c}#{end_c}", buffer.text buffer\undo! assert.equal '', buffer.text it 'positions the cursor within the pair', -> auto_pair.handle event('['), editor assert.equal 2, cursor.pos it 'does not trigger for a same character pair if the current balance is uneven', -> buffer.text = '"foo' cursor.pos = 5 assert.is_not_true auto_pair.handle event('"'), editor it 'does not trigger when the next character is a word character', -> buffer.text = 'foo' cursor.pos = 1 assert.is_not_true auto_pair.handle event('('), editor context 'overtyping companion characters', -> before_each -> buffer.mode.auto_pairs = { '(': ')' '"': '"' } it 'overtypes any companion characters if the current pair-balance is even', -> buffer.text = '()' cursor.pos = 2 assert.is_true auto_pair.handle event(')'), editor assert.equal '()', buffer.text assert.equal 3, cursor.pos it 'overtypes any companion characters for even pair-balance when the start characters and end character is the same', -> buffer.text = '""' cursor.pos = 2 assert.is_true auto_pair.handle event('"'), editor assert.equal '""', buffer.text assert.equal 3, cursor.pos it 'does not overtype if the current pair-balance is non-even', -> buffer.text = '(foo' cursor.pos = 5 assert.is_not_true auto_pair.handle event(')'), editor it 'does not overtype if the current character is different', -> buffer.text = '(foo)' cursor.pos = 6 assert.is_not_true auto_pair.handle event(')'), editor context 'deleting back inside a pair', -> before_each -> buffer.mode.auto_pairs = ['(']: ')' it 'returns true', -> buffer.text = '()' cursor.pos = 2 assert.is_true auto_pair.handle event('\8', 'backspace'), editor it 'deletes both characters as one undo', -> buffer.text = '()' cursor.pos = 2 auto_pair.handle event('\8', 'backspace'), editor assert.equal '', buffer.text buffer\undo! assert.equal '()', buffer.text it 'returns non-true when the character does not match a known pair', -> assert.is_not_true auto_pair.handle event('x'), editor it 'always returns non-true if the auto_pair config variable is false', -> buffer.mode.auto_pairs = { ['(']: ')' } buffer.config.auto_pair = false assert.is_not_true auto_pair.handle event('('), editor
34.483051
127
0.590563
9fd896c3d19175be43272e9e4b537e6af81a77cd
8
"1.9.0"
4
7
0.375
a06a4a1364bfc1a86b3e084f634582b9f921a98e
160
config = require "lapis.config" config "development", -> postgres -> host "127.0.0.1" user "username" password "" database "personalisation"
17.777778
31
0.6375
e2543a04cd7f72585afcc206a26e4553321ee6a2
673
anim8 = require('vendor/anim8/anim8') Caste = require('vendor/caste/lib/caste') { :Vector } = require('vendor/hug/lib/geo') class Animation extends Caste @options: { scale: Vector(1, 1), rotation: 0 } new: (frameData, @options = {}) => @options.frameData = frameData init: (options) => @options = _.defaults(@options, options, @@options) @shape = @options.shape @image = love.graphics.newImage("assets/sprites/#{@options.image}") g = anim8.newGrid(@shape.width, @shape.height, @image\getWidth(), @image\getHeight(), @options.offset.x, @options.offset.y, @options.border) @value = anim8.newAnimation(g(unpack(@options.frameData)), @options.duration)
32.047619
142
0.687964
c7fbd5ece401153861da5cf994597091c96f4af4
4,679
db = require "lapis.db.postgres" import gen_index_name from require "lapis.db.base" import escape_literal, escape_identifier, is_raw from db import concat from table append_all = (t, ...) -> for i=1, select "#", ... t[#t + 1] = select i, ... extract_options = (cols) -> options = {} cols = for col in *cols if type(col) == "table" and not is_raw(col) for k,v in pairs col options[k] = v continue col cols, options entity_exists = (name) -> name = escape_literal name res = unpack db.select "COUNT(*) as c from pg_class where relname = #{name}" res.c > 0 create_table = (name, columns, opts={}) -> prefix = if opts.if_not_exists "CREATE TABLE IF NOT EXISTS " else "CREATE TABLE " buffer = {prefix, escape_identifier(name), " ("} add = (...) -> append_all buffer, ... for i, c in ipairs columns add "\n " if type(c) == "table" name, kind = unpack c add escape_identifier(name), " ", tostring kind else add c add "," unless i == #columns add "\n" if #columns > 0 add ");" db.query concat buffer create_index = (tname, ...) -> index_name = gen_index_name tname, ... columns, options = extract_options {...} if options.if_not_exists return if entity_exists index_name buffer = {"CREATE"} append_all buffer, " UNIQUE" if options.unique append_all buffer, " INDEX ", escape_identifier(index_name), " ON ", escape_identifier tname if options.method append_all buffer, " USING ", options.method append_all buffer, " (" for i, col in ipairs columns append_all buffer, escape_identifier(col) append_all buffer, ", " unless i == #columns append_all buffer, ")" if options.tablespace append_all buffer, " TABLESPACE ", options.tablespace if options.where append_all buffer, " WHERE ", options.where if options.when error "did you mean create_index `where`?" append_all buffer, ";" db.query concat buffer drop_index = (...) -> index_name = gen_index_name ... db.query "DROP INDEX IF EXISTS #{escape_identifier index_name}" drop_table = (tname) -> db.query "DROP TABLE IF EXISTS #{escape_identifier tname};" add_column = (tname, col_name, col_type) -> tname = escape_identifier tname col_name = escape_identifier col_name db.query "ALTER TABLE #{tname} ADD COLUMN #{col_name} #{col_type}" drop_column = (tname, col_name) -> tname = escape_identifier tname col_name = escape_identifier col_name db.query "ALTER TABLE #{tname} DROP COLUMN #{col_name}" rename_column = (tname, col_from, col_to) -> tname = escape_identifier tname col_from = escape_identifier col_from col_to = escape_identifier col_to db.query "ALTER TABLE #{tname} RENAME COLUMN #{col_from} TO #{col_to}" rename_table = (tname_from, tname_to) -> tname_from = escape_identifier tname_from tname_to = escape_identifier tname_to db.query "ALTER TABLE #{tname_from} RENAME TO #{tname_to}" class ColumnType default_options: { null: false } new: (@base, @default_options) => __call: (opts) => out = @base for k,v in pairs @default_options -- don't use the types default default since it's not an array continue if k == "default" and opts.array opts[k] = v unless opts[k] != nil if opts.array for i=1,type(opts.array) == "number" and opts.array or 1 out ..= "[]" unless opts.null out ..= " NOT NULL" if opts.default != nil out ..= " DEFAULT " .. escape_literal opts.default if opts.unique out ..= " UNIQUE" if opts.primary_key out ..= " PRIMARY KEY" out __tostring: => @__call @default_options class TimeType extends ColumnType __tostring: ColumnType.__tostring __call: (opts) => base = @base @base = base .. " with time zone" if opts.timezone with ColumnType.__call @, opts @base = base C = ColumnType T = TimeType types = setmetatable { serial: C "serial" varchar: C "character varying(255)" text: C "text" time: T "timestamp" date: C "date" enum: C "smallint", null: false integer: C "integer", null: false, default: 0 numeric: C "numeric", null: false, default: 0 real: C "real", null: false, default: 0 double: C "double precision", null: false, default: 0 boolean: C "boolean", null: false, default: false foreign_key: C "integer" }, __index: (key) => error "Don't know column type `#{key}`" { :types, :create_table, :drop_table, :create_index, :drop_index, :add_column, :drop_column, :rename_column, :rename_table, :entity_exists, :gen_index_name }
25.429348
78
0.648002
3dbc41ba3a6d18e41661089b812b7f78ac6ca828
405
-- just parses output from acpi -b -- into percent, status and time_remaining (output) -> acpi = output\split '\n' batt = ([line for line in *acpi when line\match '^Battery'])[1] if batt status = batt\match ':%s(%a+),' status = status\lower! percent = tonumber batt\match(',%s(%d+)%%') time_remaining = batt\match ',%s(%d+:%d+):%d+%s%a+' return status, percent, time_remaining
28.928571
65
0.619753
7a885bf7371abdc156ffae98f45a5b1c66e86cb4
29,294
-- Copyright 2014-2015 The Howl Developers -- License: MIT (see LICENSE.md at the top-level directory of the distribution) ffi = require 'ffi' bit = require 'bit' ffi_cast = ffi.cast Gdk = require 'ljglibs.gdk' Gtk = require 'ljglibs.gtk' Pango = require 'ljglibs.pango' signal = require 'ljglibs.gobject.signal' require 'ljglibs.cairo.context' DisplayLines = require 'aullar.display_lines' Cursor = require 'aullar.cursor' Selection = require 'aullar.selection' Buffer = require 'aullar.buffer' Gutter = require 'aullar.gutter' CurrentLineMarker = require 'aullar.current_line_marker' config = require 'aullar.config' {:define_class} = require 'aullar.util' {:parse_key_event} = require 'ljglibs.util' {:max, :min, :floor} = math append = table.insert jit.off true, true notify = (view, event, ...) -> listener = view.listener if listener and listener[event] handled = listener[event] view, ... return true if handled == true false text_cursor = Gdk.Cursor.new(Gdk.XTERM) View = { new: (buffer = Buffer('')) => @_handlers = {} @margin = 3 @_base_x = 0 @_first_visible_line = 1 @_last_visible_line = nil @_cur_mouse_cursor = text_cursor @_y_scroll_offset = 0 @config = config.local_proxy! @area = Gtk.DrawingArea! @selection = Selection @ @cursor = Cursor @, @selection @cursor.show_when_inactive = @config.view_show_inactive_cursor @cursor.blink_interval = @config.cursor_blink_interval @gutter = Gutter @, config.gutter_styling @current_line_marker = CurrentLineMarker @ @scroll_speed_y = config.scroll_speed_y @scroll_speed_x = config.scroll_speed_x @im_context = Gtk.ImContextSimple! with @im_context append @_handlers, \on_commit (ctx, s) -> @insert s, allow_coalescing: true append @_handlers, \on_preedit_start -> @in_preedit = true notify @, 'on_preedit_start' append @_handlers, \on_preedit_changed (ctx) -> str, attr_list, cursor_pos = ctx\get_preedit_string! notify @, 'on_preedit_change', :str, :attr_list, :cursor_pos append @_handlers, \on_preedit_end -> @in_preedit = false notify @, 'on_preedit_end' with @area .can_focus = true \add_events bit.bor(Gdk.KEY_PRESS_MASK, Gdk.BUTTON_PRESS_MASK, Gdk.BUTTON_RELEASE_MASK, Gdk.POINTER_MOTION_MASK, Gdk.SCROLL_MASK, Gdk.SMOOTH_SCROLL_MASK) font_desc = Pango.FontDescription { family: @config.view_font_name, size: @config.view_font_size * Pango.SCALE } \override_font font_desc .style_context\add_class 'transparent_bg' append @_handlers, \on_key_press_event self\_on_key_press append @_handlers, \on_button_press_event self\_on_button_press append @_handlers, \on_button_release_event self\_on_button_release append @_handlers, \on_motion_notify_event self\_on_motion_event append @_handlers, \on_scroll_event self\_on_scroll append @_handlers, \on_draw self\_draw append @_handlers, \on_screen_changed self\_on_screen_changed append @_handlers, \on_focus_in_event self\_on_focus_in append @_handlers, \on_focus_out_event self\_on_focus_out @horizontal_scrollbar = Gtk.Scrollbar Gtk.ORIENTATION_HORIZONTAL append @_handlers, @horizontal_scrollbar.adjustment\on_value_changed (adjustment) -> return if @_updating_scrolling @base_x = floor adjustment.value @area\queue_draw! @horizontal_scrollbar_alignment = Gtk.Alignment { left_padding: @gutter_width, @horizontal_scrollbar } @horizontal_scrollbar_alignment.no_show_all = not config.view_show_h_scrollbar @vertical_scrollbar = Gtk.Scrollbar Gtk.ORIENTATION_VERTICAL @vertical_scrollbar.no_show_all = not config.view_show_v_scrollbar append @_handlers, @vertical_scrollbar.adjustment\on_value_changed (adjustment) -> return if @_updating_scrolling @_scrolling_vertically = true line = floor adjustment.value + 0.5 @scroll_to line @_scrolling_vertically = false @bin = Gtk.Box Gtk.ORIENTATION_HORIZONTAL, { { expand: true, Gtk.Box(Gtk.ORIENTATION_VERTICAL, { { expand: true, @area }, @horizontal_scrollbar_alignment }) }, @vertical_scrollbar } append @_handlers, @bin\on_destroy self\_on_destroy append @_handlers, @bin\on_size_allocate self\_on_size_allocate @_buffer_listener = { on_inserted: (_, b, args) -> self\_on_buffer_modified b, args, 'inserted' on_deleted: (_, b, args) -> self\_on_buffer_modified b, args, 'deleted' on_changed: (_, b, args) -> self\_on_buffer_modified b, args, 'changed' on_styled: (_, b, args) -> self\_on_buffer_styled b, args on_undo: (_, b, args) -> self\_on_buffer_undo b, args on_redo: (_, b, args) -> self\_on_buffer_redo b, args on_markers_changed: (_, b, args) -> self\_on_buffer_markers_changed b, args last_viewable_line: (_, b) -> last = @last_visible_line if @height last = max last, @height / @default_line_height last } @buffer = buffer @config\add_listener self\_on_config_changed destroy: => @bin\destroy! properties: { showing: => @height != nil has_focus: => @area.is_focus gutter_width: => @config.view_show_line_numbers and @gutter.width or 0 first_visible_line: { get: => @_first_visible_line set: (line) => @scroll_to line } middle_visible_line: { get: => return 0 unless @height y = @margin middle = @height / 2 for line = @_first_visible_line, @_last_visible_line d_line = @display_lines[line] y += d_line.height return line if y >= middle @_last_visible_line set: (line) => return unless @height y = @height / 2 for nr = line, 1, -1 d_line = @display_lines[nr] y -= d_line.height if y <= @margin or nr == 1 @first_visible_line = nr break } last_visible_line: { get: => unless @_last_visible_line return 0 unless @height @_last_visible_line = 1 y = @margin for line in @_buffer\lines @_first_visible_line d_line = @display_lines[line.nr] break if y + d_line.height > @height @_last_visible_line = line.nr y += d_line.height -- +1 for last visible, since next line might be partially shown @display_lines\set_window @_first_visible_line, @_last_visible_line + 1 @_last_visible_line set: (line) => return unless @showing last_line_height = @display_lines[line].height available = @height - @margin - last_line_height first_visible = line while first_visible > 1 prev_d_line = @display_lines[first_visible - 1] break if (available - prev_d_line.height) < 0 available -= prev_d_line.height first_visible -= 1 @scroll_to first_visible -- we don't actually set @_last_visible_line here as it -- will be set by the actuall scrolling } y_scroll_offset: { get: => @_y_scroll_offset set: (offset) => @_y_scroll_offset = offset if @_y_scroll_offset < -1 or @_y_scroll_offset > 1 @first_visible_line = max(@first_visible_line + floor(@_y_scroll_offset), 1) @_y_scroll_offset = 0 } lines_showing: => @last_visible_line - @first_visible_line + 1 base_x: { get: => @_base_x set: (x) => x = floor max(0, x) return if x == @_base_x @_base_x = x @area\queue_draw! @_sync_scrollbars horizontal: true } edit_area_x: => @gutter_width + @margin edit_area_width: => return 0 unless @width @width - @edit_area_x buffer: { get: => @_buffer set: (buffer) => if @_buffer @_buffer\remove_listener(@_buffer_listener) @cursor.pos = 1 @selection\clear! @_buffer = buffer buffer\add_listener @_buffer_listener @last_edit_pos = nil @_first_visible_line = 1 @_base_x = 0 @_reset_display! @area\queue_draw! buffer\ensure_styled_to line: @last_visible_line + 1 } } grab_focus: => @area\grab_focus! scroll_to: (line) => return if line < 1 or not @showing line = max(1, line) line = min(line, @buffer.nr_lines) return if @first_visible_line == line @_first_visible_line = line @_last_visible_line = nil @_sync_scrollbars! @buffer\ensure_styled_to line: @last_visible_line + 1 @area\queue_draw! if line != 1 and @last_visible_line == @buffer.nr_lines -- make sure we don't accidentally scroll to much here, -- leaving visual area unclaimed @last_visible_line = @last_visible_line _sync_scrollbars: (opts = { horizontal: true, vertical: true })=> @_updating_scrolling = true if opts.vertical page_size = @lines_showing - 1 adjustment = @vertical_scrollbar.adjustment if adjustment adjustment\configure @first_visible_line, 1, @buffer.nr_lines, 1, page_size, page_size if opts.horizontal max_width = 0 for i = @first_visible_line, @last_visible_line max_width = max max_width, @display_lines[i].width max_width += @width_of_space if @config.view_show_cursor if max_width <= @edit_area_width and @base_x == 0 @horizontal_scrollbar\hide! else adjustment = @horizontal_scrollbar.adjustment if adjustment width = @edit_area_width upper = max_width - (@margin / 2) if @_scrolling_vertically -- we're scrolling vertically so maintain our x, -- but ensure we expand the scrollbar if necessary adjustment.upper = upper if upper > adjustment.upper else adjustment\configure @base_x, 1, upper, 10, width, width @horizontal_scrollbar\show! @_updating_scrolling = false notify @, 'on_scroll', opts insert: (text, opts = {}) => if @selection.is_empty @_buffer\insert @cursor.pos, text, #text, opts else start_pos = @selection\range! @_buffer\replace start_pos, @selection.size, text, #text, opts notify @, 'on_insert_at_cursor', :text nil delete_back: (opts = {}) => if @selection.is_empty cur_pos = @cursor.pos @cursor\backward! prev_pos = @cursor.pos size = cur_pos - prev_pos @cursor.pos = cur_pos if size > 0 text = @_buffer\sub prev_pos, cur_pos @_buffer\delete prev_pos, size, opts notify @, 'on_delete_back', :text, pos: prev_pos else start_pos = @selection\range! @_buffer\delete start_pos, @selection.size, opts to_gobject: => @bin refresh_display: (opts = { from_line: 1 }) => return unless @width d_lines = @display_lines min_y, max_y = nil, nil y = @margin last_valid = 0 from_line = opts.from_line to_line = opts.to_line to_offset = opts.to_offset unless from_line from_offset = min @buffer.size + 1, opts.from_offset from_line = @buffer\get_line_at_offset(from_offset).nr if opts.invalidate -- invalidate any affected lines before first visible for line_nr = from_line, @_first_visible_line - 1 d_lines[line_nr] = nil for line_nr = @_first_visible_line, @last_visible_line + 1 line = @_buffer\get_line line_nr break unless line break if to_offset and line.start_offset > to_offset -- after break if to_line and line.nr > to_line -- after before = line.nr < from_line and line.has_eol d_line = d_lines[line_nr] if not before if opts.invalidate d_lines[line.nr] = nil -- recreate the display line since subsequent modifications has to -- know what the display properties was for the modified lines d_lines[line.nr] elseif opts.update d_line\refresh! min_y or= y max_y = y + d_line.height last_valid = max last_valid, line.nr y += d_line.height if opts.invalidate -- invalidate any lines after visibly affected block local invalidate_to_line if not to_line and not to_offset invalidate_to_line = d_lines.max max_y = @height @_last_visible_line = nil @display_lines.max = last_valid else invalidate_to_line = to_line if to_offset to_offset = min to_offset, @buffer.size + 1 invalidate_to_line = @buffer\get_line_at_offset(to_offset).nr for line_nr = last_valid + 1, invalidate_to_line d_lines[line_nr] = nil if min_y start_x = max 0, @edit_area_x - 1 start_x = 0 if opts.gutter or start_x == 1 width = @width - start_x height = (max_y - min_y) if width > 0 and height > 0 @area\queue_draw_area start_x, min_y, width, height position_from_coordinates: (x, y, opts = {}) => return nil unless @showing cur_y = @margin return nil unless y >= cur_y matched_line = nil for line_nr = @_first_visible_line, @last_visible_line + 1 d_line = @display_lines[line_nr] break unless d_line end_y = cur_y + d_line.height if (y >= cur_y and y <= end_y) matched_line = d_line break elseif opts.fuzzy matched_line = d_line cur_y = end_y if matched_line line = @_buffer\get_line(matched_line.nr) pango_x = (x - @edit_area_x + @base_x) * Pango.SCALE line_y = max(0, min(y - cur_y, matched_line.text_height - 1)) * Pango.SCALE inside, index = matched_line.layout\xy_to_index pango_x, line_y if not inside -- left of the area, point it to first char in line return line.start_offset if x < @edit_area_x -- right of the area, point to end if matched_line.is_wrapped v_line = matched_line.lines\at_pixel_y(y - cur_y) return line.start_offset + v_line.line_end - 1 else return line.start_offset + line.size else -- are we aiming for the next grapheme? rect = matched_line.layout\index_to_pos index if pango_x - rect.x > rect.width * 0.7 index = matched_line.layout\move_cursor_visually true, index, 0, 1 return line.start_offset + index nil coordinates_from_position: (pos) => return nil unless @showing line = @buffer\get_line_at_offset pos return nil unless line return nil if line.nr < @_first_visible_line y = @margin x = @edit_area_x for line_nr = @_first_visible_line, @buffer.nr_lines d_line = @display_lines[line_nr] if d_line.nr == line.nr or (d_line.nr > line.nr and not line.has_eol) -- it's somewhere within this line.. layout = d_line.layout index = pos - line.start_offset -- <-- at this byte index rect = layout\index_to_pos index bottom = y + ((rect.y + rect.height) / Pango.SCALE) + @config.view_line_padding return { x: x + (rect.x / Pango.SCALE) - @base_x x2: x + ((rect.x + rect.width) / Pango.SCALE) - @base_x y: y + (rect.y / Pango.SCALE) y2: bottom } y += d_line.height nil text_dimensions: (text) => p_ctx = @area.pango_context layout = Pango.Layout p_ctx layout.text = text width, height = layout\get_pixel_size! :width, height: height + (@config.view_line_padding * 2) block_dimensions: (start_line, end_line) => height, width = 0, 0 for nr = start_line, end_line d_line = @display_lines[nr] break unless d_line width = max width, d_line.width height += d_line.height width, height _invalidate_display: (from_offset, to_offset) => return unless @width to_offset = min to_offset, @buffer.size + 1 from_line = @buffer\get_line_at_offset(from_offset).nr to_line = max @display_lines.max, @buffer\get_line_at_offset(to_offset).nr - 1 for line_nr = from_line, to_line @display_lines[line_nr] = nil _draw: (_, cr) => p_ctx = @area.pango_context clip = cr.clip_extents conf = @config line_draw_opts = config: conf, buffer: @_buffer draw_gutter = conf.view_show_line_numbers and clip.x1 < @gutter_width if draw_gutter @gutter\start_draw cr, p_ctx, clip edit_area_x, y = @edit_area_x, @margin cr\move_to edit_area_x, y cr\set_source_rgb 0, 0, 0 lines = {} start_y = nil for line in @_buffer\lines @_first_visible_line d_line = @display_lines[line.nr] if y + d_line.height > clip.y1 d_line.block -- force evaluation of any block lines[#lines + 1] = :line, display_line: d_line start_y or= y y += d_line.height break if y + 1 >= clip.y2 current_line = @cursor.line y = start_y cursor_col = @cursor.column for line_info in *lines {:display_line, :line} = line_info line_draw_opts.line = line if line.nr == current_line and conf.view_highlight_current_line @current_line_marker\draw_before edit_area_x, y, display_line, cr, clip, cursor_col if @selection\affects_line line @selection\draw edit_area_x, y, cr, display_line, line display_line\draw edit_area_x, y, cr, clip, line_draw_opts if @selection\affects_line line @selection\draw_overlay edit_area_x, y, cr, display_line, line if draw_gutter @gutter\draw_for_line line.nr, 0, y, display_line if line.nr == current_line if conf.view_highlight_current_line @current_line_marker\draw_after edit_area_x, y, display_line, cr, clip, cursor_col if conf.view_show_cursor @cursor\draw edit_area_x, y, cr, display_line y += display_line.height cr\move_to edit_area_x, y if draw_gutter @gutter\end_draw! _reset_display: => @_last_visible_line = nil p_ctx = @area.pango_context tm = @text_dimensions(' ') @width_of_space = tm.width @default_line_height = tm.height + floor @config.view_line_padding tab_size = @config.view_tab_size @_tab_array = Pango.TabArray(1, true, @width_of_space * tab_size) @display_lines = DisplayLines @, @_tab_array, @buffer, p_ctx @horizontal_scrollbar_alignment.left_padding = @gutter_width @gutter\sync_dimensions @buffer, force: true _on_destroy: => @listener = nil @selection = nil @cursor\destroy! @cursor = nil @config\detach! @_buffer\remove_listener(@_buffer_listener) if @_buffer -- disconnect signal handlers for h in *@_handlers signal.disconnect h _on_buffer_styled: (buffer, args) => return unless @showing last_line = buffer\get_line @last_visible_line return if args.start_line > @display_lines.max + 1 and last_line.has_eol start_line = args.start_line start_dline = @display_lines[start_line] prev_block = start_dline.block prev_block_width = prev_block and prev_block.width update_block = (rescan_width) -> new_block = @display_lines[start_line].block return unless (new_block or prev_block) if new_block and prev_block if new_block.width == prev_block_width return unless rescan_width width = 0 start_scan_line = max(new_block.start_line, @first_visible_line) end_scan_line = min(new_block.end_line, @last_visible_line) for nr = start_scan_line, end_scan_line width = max width, @display_lines[nr].width return if width == prev_block_width new_block.width = width start_refresh = @last_visible_line end_refresh = @first_visible_line if prev_block start_refresh, end_refresh = prev_block.start_line, prev_block.end_line if new_block start_refresh = min start_refresh, new_block.start_line end_refresh = max end_refresh, new_block.end_line @refresh_display from_line: start_refresh, to_line: end_refresh if not args.invalidated and args.start_line == args.end_line -- refresh only the single line, but verify that the modification does not -- have other significant percussions @refresh_display from_line: start_line, to_line: start_line, invalidate: true d_line = @display_lines[start_line] if d_line.height == start_dline.height -- height remains the same -- but we might still need to adjust for block changes update_block(start_dline.width == prev_block_width) @_sync_scrollbars horizontal: true return @refresh_display from_line: start_line, invalidate: true, gutter: true -- we might still need to adjust more for block changes update_block(start_dline.width == prev_block_width) @_sync_scrollbars! _on_buffer_modified: (buffer, args, type) => cur_pos = @cursor.pos sel_anchor, sel_end = @selection.anchor, @selection.end_pos lines_changed = args.lines_changed if not @showing @_reset_display! else if lines_changed @_last_visible_line = nil if args.styled @_on_buffer_styled buffer, args.styled else refresh_all_below = lines_changed unless refresh_all_below -- refresh only the single line buf_line = @buffer\get_line_at_offset args.offset start_dline = @display_lines[buf_line.nr] @refresh_display from_offset: args.offset, to_offset: args.offset + args.size, invalidate: true -- but if the line now has a different height due to line wrapping, -- we still want a major refresh new_dline = @display_lines[buf_line.nr] if new_dline.height != start_dline.height refresh_all_below = true else @_sync_scrollbars horizontal: true if refresh_all_below @refresh_display from_offset: args.offset, invalidate: true, gutter: true @_sync_scrollbars! if args.offset > args.invalidate_offset -- we have lines before the offset of the modification that are -- invalid - they need to be invalidated but not visually refreshed @_invalidate_display args.invalidate_offset, args.offset - 1 if lines_changed and not @gutter\sync_dimensions buffer @area\queue_draw! -- adjust cursor to correctly reflect the change changes = { { :type, offset: args.offset, size: args.size } } changes = args.changes if type == 'changed' c_pos = cur_pos for change in *changes if change.type == 'inserted' and change.offset <= c_pos c_pos += change.size elseif change.type == 'deleted' and change.offset < c_pos c_pos -= min(c_pos - change.offset, change.size) @cursor\move_to pos: c_pos, force: true @selection\clear! if @has_focus and args.revision with args.revision.meta .cursor_before or= cur_pos .cursor_after = @cursor.pos .selection_anchor = sel_anchor .selection_end_pos = sel_end @last_edit_pos = @cursor.pos -- check whether we should scroll up to fit the contents into the view -- we ensure this if the line count was changed, we're showing the last -- line, we have non-visible lines above and it was not an insert if lines_changed and @_first_visible_line > 1 and type != 'inserted' if not @buffer\get_line(@last_visible_line + 1) @last_visible_line = @buffer.nr_lines _on_buffer_markers_changed: (buffer, args) => @refresh_display { from_offset: args.start_offset, to_offset: args.end_offset, update: true } _on_buffer_undo: (buffer, revision) => pos = revision.meta.cursor_before or revision.offset @cursor.pos = pos {:selection_anchor, :selection_end_pos} = revision.meta if selection_anchor @selection\set selection_anchor, selection_end_pos _on_buffer_redo: (buffer, revision) => pos = revision.meta.cursor_after or revision.offset @cursor.pos = pos _on_focus_in: => @im_context\focus_in! @cursor.active = true notify @, 'on_focus_in' _on_focus_out: => @im_context\focus_out! @cursor.active = false notify @, 'on_focus_out' _on_screen_changed: => @_reset_display! _on_key_press: (_, e) => if @in_preedit @im_context\filter_keypress(e) return true event = parse_key_event e unless notify @, 'on_key_press', event @im_context\filter_keypress e true _on_button_press: (_, event) => @area\grab_focus! unless @area.has_focus event = ffi_cast('GdkEventButton *', event) return false if event.x <= @gutter_width return true if notify @, 'on_button_press', event return false if event.button != 1 or event.type != Gdk.BUTTON_PRESS extend = bit.band(event.state, Gdk.SHIFT_MASK) != 0 pos = @position_from_coordinates(event.x, event.y, fuzzy: true) if pos @selection.persistent = false if pos != @cursor.pos @cursor\move_to :pos, :extend else @selection\clear! @_selection_active = true _on_button_release: (_, event) => event = ffi_cast('GdkEventButton *', event) return true if notify @, 'on_button_release', event return if event.button != 1 @_selection_active = false _on_motion_event: (_, event) => event = ffi_cast('GdkEventMotion *', event) return true if notify @, 'on_motion_event', event unless @_selection_active if @_cur_mouse_cursor != text_cursor if event.x > @gutter_width @area.window.cursor = text_cursor @_cur_mouse_cursor = text_cursor elseif event.x <= @gutter_width @area.window.cursor = nil @_cur_mouse_cursor = nil return pos = @position_from_coordinates(event.x, event.y, fuzzy: true) if pos @cursor\move_to :pos, extend: true elseif event.y < @margin if @first_visible_line == 1 @cursor\move_to pos:1, extend: true else @cursor\up extend: true else if @last_visible_line == @buffer.nr_lines @cursor\move_to pos:@buffer.size+1, extend: true else @cursor\down extend: true _scroll_x: (value) => value = value * (@scroll_speed_x / 100) if value > 0 -- Scroll right. new_base_x = @base_x + 20 * value adjustment = @horizontal_scrollbar.adjustment if adjustment new_base_x = min new_base_x, adjustment.upper - adjustment.page_size @base_x = new_base_x elseif value < 0 -- Scroll left. @base_x -= 20 * -value _scroll_y: (value) => @y_scroll_offset += value * (@scroll_speed_y / 100) _on_scroll: (_, event) => event = ffi_cast('GdkEventScroll *', event) if event.direction == Gdk.SCROLL_UP @_scroll_y -1 elseif event.direction == Gdk.SCROLL_DOWN @_scroll_y 1 elseif event.direction == Gdk.SCROLL_RIGHT @_scroll_x 1 elseif event.direction == Gdk.SCROLL_LEFT @_scroll_x -1 elseif event.direction == Gdk.SCROLL_SMOOTH @_scroll_y event.delta_y @_scroll_x event.delta_x _on_size_allocate: (_, allocation) => allocation = ffi_cast('GdkRectangle *', allocation) resized = (not @height or @height != allocation.height) or (not @width or @width != allocation.width) return unless resized gdk_window = @area.window @im_context.client_window = gdk_window if gdk_window != nil gdk_window.cursor = @_cur_mouse_cursor getting_taller = @height and allocation.height > @height @width = allocation.width @height = allocation.height @_reset_display! if getting_taller and @last_visible_line == @buffer.nr_lines -- since we're growing this could be wrong, and we might need -- to re-calculate what the last visible line actually is @last_visible_line = @last_visible_line @buffer\ensure_styled_to line: @last_visible_line + 1 @_sync_scrollbars! notify @, 'on_resized' _on_config_changed: (option, val, old_val) => if option == 'view_font_name' or option == 'view_font_size' @area\override_font Pango.FontDescription { family: @config.view_font_name, size: @config.view_font_size * Pango.SCALE } @_reset_display! elseif option == 'view_show_inactive_cursor' @cursor.show_when_inactive = val elseif option == 'cursor_blink_interval' @cursor.blink_interval = val elseif option == 'scroll_speed_y' or option == 'scroll_speed_x' @[option] = val elseif option == 'gutter_styling' @gutter\reconfigure val @_reset_display! elseif option == 'view_show_v_scrollbar' @vertical_scrollbar.visible = val @vertical_scrollbar.no_show_all = true elseif option == 'view_show_h_scrollbar' @horizontal_scrollbar_alignment.visible = val @horizontal_scrollbar_alignment.no_show_all = true @horizontal_scrollbar_alignment.left_padding = @gutter_width elseif option\match('^view_') @_reset_display! } define_class View
31.634989
159
0.658531
d97c2421241affc014e35cb7967562a59561da0c
360
_ = req(..., 'lib.lodash') class Loader new: (handler) => cache = {} meta = getmetatable(@) oldIndex = meta.__index meta.__index = (key) => if value = cache[key] return value elseif value = handler(key) cache[key] = value return value elseif _.isFunction(oldIndex) return oldIndex(@, key) else return oldIndex[key]
17.142857
32
0.616667
be8db91951aaad13feedcdce092b1385a84f4a96
403
html = require "lapis.html" config = (require "lapis.config").get! import to_json from require "lapis.util" class Error extends html.Widget content: => raw @m[@status].error_page or "<p>Dogodila se greška!</p>" if config._name == 'development' or config._name == 'development-perftest' p class: "debug", @error pre class: "debug", @traceback
33.583333
82
0.615385
68e3775889c46618c39a31b9f019513345ec75e1
5,198
-- Copyright (c) 2015 by Adam Hellberg. -- -- 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. NAME, T = ... T.markov = {} import random from math import db, log, markov from T -- Blacklist contains words that will not be added or processed blacklist = {'^[%s%c%p]+$', '\124%w'} parenpairs = '(': ')' '[': ']' '{': '}' isduplicate = (trigger, reply using nil) -> trigger = trigger\lower! reply = reply\lower! words = {} reply\gsub '[^%s]+', (w) -> words[#words + 1] = w count = 0 start = 1 for word in *words s, e = trigger\find word, start if s and e start = e count += 1 else break return count == #words markov.save = (str) => -- Make it lowercase for less duplicates str = str\lower! -- Strip links str = str\gsub '\124%w.-\124r', '' -- Phrases inside parens, brackets, and braces are extracted to be processed separately --subphrases = {} --for left, right in pairs parenpairs -- str = str\gsub '%' .. left .. '(.-)%' .. right, (p) -> -- subphrases[#subphrases + 1] = p -- '' -- For now, just strip all parens and puncuation, makes for a little more comedic phrases too str = str\gsub '[%.,_!?<>()[%]{}"]', ' ' -- Begin by getting a table of all the words words = {} str\gsub '[^%s]+', (w) -> for pattern in *blacklist return if w\match pattern words[#words + 1] = w if #words < 3 log\debug 'Markov can\'t process lines shorter than 3 words, aborting.' return for i = 1, #words break if #words - i < 2 key = '%s %s'\format words[i], words[i + 1] value = words[i + 2] db.main.words[key] = {} unless db.main.words[key] found = false for entry in *db.main.words[key] if entry.word == value entry.count += 1 found = true break db.main.words[key][#db.main.words[key] + 1] = {word: value, count: 1} unless found --for phrase in *subphrases -- @save phrase markov.getseed = (str) => words = {} str = str\lower! str\gsub '[^%s]+', (w) -> words[#words + 1] = w local seed if #words < 2 candidates = {} for key, _ in pairs db.main.words word = words[1] if key\match("^#{word}%s") or key\match "%s#{word}$" candidates[#candidates + 1] = key seed = candidates[random(1, #candidates)] unless #candidates < 1 else index = random 1, #words - 1 --secondindex = random 1, #words --while secondindex == index -- secondindex = random 1, #words seed = '%s %s'\format words[index], words[index + 1] seed markov.create = (seed, maxwords = random(5, 50)) => -- We build the result string in a table for easier processing result = {} seed\gsub '[^%s]+', (w) -> result[#result + 1] = w count = #result lastword = nil lastcount = 0 while count < maxwords and lastcount < 3 key = '%s %s'\format result[#result - 1], result[#result] list = db.main.words[key] unless list log\debug 'No entries found for %s.', key break word = list[random(1, #list)].word result[#result + 1] = word count += 1 if word == lastword lastcount += 1 else lastcount = 0 lastword = word table.concat result, ' ' markov.reply = (msg, channel, target, silent) => @save msg if msg\len! < 1 chat\send channel, 'Not enough data to process.' unless silent return false local seed if random(0, 1) == 1 seed = @getseed msg else words = {} msg\gsub '[^%s]+', (w) -> words[#words + 1] = w seed = @getseed words[random(1, #words)] if not seed T.chat\send 'Couldn\'t make a sentence based on that input :(', 'GUILD' unless silent return false reply = @create seed return false if silent and isduplicate(msg, reply) --reply == msg\lower! T.chat\send reply, channel, target true
34.423841
97
0.582339
ba0ce8e8d5222c9e902f5e2fef582eca8f1d80ee
3,002
import app, breadcrumbs, interact, log, Project from howl import File, Process from howl.io import ProcessBuffer from howl.ui find_and_set_manifest = (project) -> relative_path = (path) -> tostring path\relative_to_parent project.root manifests = project.root\find sort: true, filter: (file) -> return file.basename[1] == '.' if file.is_directory parts = file.basename\split '%.' return true if #parts < 3 extension = table.remove parts, #parts return true if extension != 'json' and extension != 'yaml' and extension != 'yml' for part in *parts return true if not part\match '^[%a-_][%w-_]*$' false if #manifests == 0 file = interact.select_file_in_project title: 'Select a manifest to use' project: project return false if not choice project.config.flatpak_manifest = relative_path file else manifest_choices = {} for manifest in *manifests continue if manifest.is_directory table.insert manifest_choices, {manifest.short_path, :manifest} if #manifest_choices == 1 project.config.flatpak_manifest = relative_path manifest_choices[1].manifest else choice = interact.select title: 'Select a manifest to use' items: manifest_choices cancel_on_back: true return false if not choice project.config.flatpak_manifest = relative_path choice.selection.manifest return true get_config = (buffer, project, var) -> if #buffer.config[var] > 0 return 'buffer', buffer.config[var] elseif project and #project.config[var] > 0 return 'project', project.config[var] build = (run=false) -> return if not app.editor {:buffer} = app.editor file = buffer.file or buffer.directory error 'No file associated with the current view' unless file project = Project.for_file file error "No project associated with #{file}" unless project where, manifest = get_config buffer, project, 'flatpak_manifest' if not manifest return if not find_and_set_manifest project where, manifest = get_config buffer, project, 'flatpak_manifest' assert manifest, 'manifest is empty after find_and_set_manifest succeeded' local directory if where == 'buffer' directory = file.parent elseif where == 'project' directory = project.root manifest = File manifest, directory default_stop = directory.basename stop = get_config(buffer, project, 'flatpak_module') or default_stop root = get_config(buffer, project, 'flatpak_builder_directory') or 'flatpak-app' p = Process cmd: { tostring bundle_file 'run-local-build.sh' tostring manifest tostring root stop project.config.flatpak_source and 'replace' or '' run and 'run' or '' } read_stdout: true read_stderr: true working_directory: directory breadcrumbs.drop! buffer = ProcessBuffer p, title: "$ flatpak-builder #{manifest.basename}" editor = app\add_buffer buffer editor.cursor\eof! buffer\pump! {:build}
29.722772
85
0.702865
227917d3b5e227b27b62d52af8330de9222c2da4
883
tArgs = { ... } if #tArgs < 1 print "Usage: go <direction> <distance>" return tHandlers = { "fd" = turtle.forward "forward" = turtle.forward "forwards" = turtle.forward "bk" = turtle.back "back" = turtle.back "up" = turtle.up "dn" = turtle.down "down" = turtle.down "lt" = turtle.turnLeft "left" = turtle.turnLeft "rt" = turtle.turnRight "right" = turtle.turnRight } nArg = 1 while nArg <= #tArgs sDirection = tArgs[nArg] nDistance = 1 if nArg < #tArgs num = tonumber tArgs[nArg + 1] if num nDistance = num nArg +=1 nArg += 1 fnHandler = tHandlers[string.lower(sDirection)] if fnHandler while nDistance > 0 if fnHandler! nDistance -= 1 elseif turtle.getFuelLevel! == 0 print "Out of fuel" return else sleep 0.5 else print "No such direction: "..sDirection print "Try: forward, back, up, down" return
16.660377
48
0.634202
ba6ab52c87980dbb7465bbe196e7eab515572830
7,286
-- Copyright 2012-2015 The Howl Developers -- License: MIT (see LICENSE.md at the top-level directory of the distribution) _G = _G import table, coroutine, pairs from _G import pcall, callable, setmetatable, typeof, tostring from _G import signal, command, sys from howl append = table.insert signal.register 'key-press', description: [[Signaled right after a key is pressed. If any handler returns true, the key press is considered to be handled, and any subsequent processing is skipped. ]] parameters: event: 'The event for the key press' translations: 'A list of readable translations for the key event' source: 'The source of the key press (e.g. "editor")' parameters: 'Other source specific parameters (e.g. an editor for source = "editor")' _ENV = {} setfenv(1, _ENV) if setfenv capture_handler = nil keymap_options = setmetatable {}, __mode: 'k' export keymaps = {} export is_capturing = false alternate_names = { kp_up: 'up' kp_down: 'down' kp_left: 'left' kp_right: 'right' kp_page_up: 'page_up' kp_page_down: 'page_down' kp_home: 'home' kp_end: 'end' kp_insert: 'insert' kp_delete: 'delete' kp_enter: { 'return', 'enter' } iso_left_tab: 'tab' return: 'enter' enter: 'return' altL: 'alt' altR: 'alt' shiftL: 'shift' shiftR: 'shift' ctrlL: 'ctrl' ctrlR: 'ctrl' metaL: 'meta' metaR: 'meta' superL: 'super' superR: 'super' hyperL: 'hyper' hyperR: 'hyper' } substituted_names = { meta_l: 'metaL' meta_r: 'metaR' alt_l: 'altL' alt_r: 'altR' shift_l: 'shiftL' shift_r: 'shiftR' control_l: 'ctrlL' control_r: 'ctrlR' super_l: 'superL' super_r: 'superR' kp_prior: 'kp_page_up' kp_next: 'kp_page_down' hyper_l: 'hyperL' hyper_r: 'hyperR' } modifier_keys = { 'alt', 'shift', 'ctrl', 'meta', 'super', 'hyper', 'iso_level3_shift', 'iso_level5_shift', } substitute_keyname = (event) -> key_name = substituted_names[event.key_name] return event unless key_name copy = {k,v for k,v in pairs event} copy.key_name = key_name copy export action_for = (tr, source='editor') -> os = sys.info.os empty = {} for i = #keymaps, 1, -1 km = keymaps[i] continue unless km source_km = km[source] or empty os_map = km.for_os and km.for_os[os] or empty os_source_map = os_map[source] or empty handler = os_source_map[tr] or os_map[tr] or source_km[tr] or km[tr] return handler if handler nil find_handlers = (event, source, translations, maps_to_search, ...) -> handlers = {} empty = {} os = sys.info.os for map in *maps_to_search continue unless map source_map = map[source] or empty handler = nil map_binding_for = map.binding_for source_map_binding_for = source_map.binding_for os_map = map.for_os and map.for_os[os] or empty os_source_map = os_map[source] or empty for t in *translations handler = os_source_map[t] or source_map[t] or os_map[t] or map[t] break if handler if source_map_binding_for or map_binding_for cmd = action_for t if typeof(cmd) == 'string' handler = source_map_binding_for and source_map_binding_for[cmd] break if handler handler = map_binding_for and map_binding_for[cmd] break if handler if not handler and callable map.on_unhandled handler = map.on_unhandled event, source, translations, ... append handlers, handler if handler opts = keymap_options[map] or {} return handlers, map, opts if opts.block or opts.pop handlers export cancel_capture = -> capture_handler = nil is_capturing = false process_capture = (event, source, translations, ...) -> if capture_handler status, ret = pcall capture_handler, event, source, translations, ... if not status or ret != false cancel_capture! _G.log.error ret unless status return true export push = (km, options = {}) -> append keymaps, km keymap_options[km] = options export remove = (map) -> error "No bindings in stack" unless #keymaps > 0 for i = 1, #keymaps if keymaps[i] == map keymap_options[map] = nil table.remove keymaps, i return true false export pop = -> remove keymaps[#keymaps] export translate_key = (event) -> ctrl = (event.control and 'ctrl_') or '' shift = (event.shift and 'shift_') or '' alt = (event.alt and 'alt_') or '' meta = (event.meta and 'meta_') or '' event = substitute_keyname event alternate = alternate_names[event.key_name] translations = {} character = event.character if event.lock and character if event.shift character = character.uupper else character = character.ulower append translations, ctrl .. meta .. alt .. character if character modifiers = ctrl .. meta .. shift .. alt if event.key_name and event.key_name != character append translations, modifiers .. event.key_name if typeof(alternate) == 'table' for a in *alternate append translations, modifiers .. a elseif alternate append translations, modifiers .. alternate append translations, modifiers .. event.key_code translations export is_modifier = (translations) -> for translation in *translations for modifier in *modifier_keys if translation == modifier return true return false export dispatch = (event, source, maps_to_search, ...) -> event = substitute_keyname event translations = translate_key event handlers, halt_map, map_opts = find_handlers event, source, translations, maps_to_search, ... remove halt_map if halt_map and map_opts.pop for handler in *handlers status, ret = true, true htype = typeof handler f = if htype == 'string' -> command.run handler elseif callable handler (...) -> handler ... if f co = coroutine.create f status, ret = coroutine.resume co, ... elseif htype == 'table' push handler, pop: true else _G.log.error "Illegal handler: type #{htype}" _G.log.error ret unless status return true if not status or (status and ret != false) false export can_dispatch = (event, source, maps_to_search) -> event = substitute_keyname event translations = translate_key event handlers = find_handlers event, source, translations, maps_to_search return #handlers > 0 export process = (event, source, extra_keymaps = {}, ...) -> event = substitute_keyname event translations = translate_key event return true if process_capture event, source, translations, ... emit_result = signal.emit 'key-press', :event, :source, :translations, parameters: {...} return true if emit_result == signal.abort maps = {} append maps, map for map in *extra_keymaps for i = #keymaps, 1, -1 append maps, keymaps[i] dispatch event, source, maps, ... export capture = (handler) -> capture_handler = handler is_capturing = true export keystrokes_for = (handler, source = nil) -> keystrokes = {} for i = #keymaps, 1, -1 km = keymaps[i] source_km = km[source] if source_km for keystroke, h in pairs source_km if h == handler append keystrokes, keystroke for keystroke, h in pairs km if h == handler append keystrokes, keystroke keystrokes return _ENV
25.38676
95
0.676366
b3b31e8a9fbbcfa57dfd29df172880030b678016
7,889
---------------------------------------------------------------- -- A @{Block} for the main @{RomlDoc} compiled files. -- -- @classmod MainBlock -- @author Richard Voelker -- @license MIT ---------------------------------------------------------------- local FunctionBlock local DoBlock local SpaceBlock local DoubleBlock local TableBlock local MetatableBlock local IfElseBlock local IfBlock local Line local RequireLine if game pluginModel = script.Parent.Parent.Parent.Parent FunctionBlock = require(pluginModel.com.blacksheepherd.code.FunctionBlock) DoBlock = require(pluginModel.com.blacksheepherd.code.DoBlock) SpaceBlock = require(pluginModel.com.blacksheepherd.code.SpaceBlock) DoubleBlock = require(pluginModel.com.blacksheepherd.code.DoubleBlock) TableBlock = require(pluginModel.com.blacksheepherd.code.TableBlock) MetatableBlock = require(pluginModel.com.blacksheepherd.code.MetatableBlock) IfElseBlock = require(pluginModel.com.blacksheepherd.code.IfElseBlock) IfBlock = require(pluginModel.com.blacksheepherd.code.IfBlock) Line = require(pluginModel.com.blacksheepherd.code.Line) RequireLine = require(pluginModel.com.blacksheepherd.code.RequireLine) else FunctionBlock = require "com.blacksheepherd.code.FunctionBlock" DoBlock = require "com.blacksheepherd.code.DoBlock" SpaceBlock = require "com.blacksheepherd.code.SpaceBlock" DoubleBlock = require "com.blacksheepherd.code.DoubleBlock" TableBlock = require "com.blacksheepherd.code.TableBlock" MetatableBlock = require "com.blacksheepherd.code.MetatableBlock" IfElseBlock = require "com.blacksheepherd.code.IfElseBlock" IfBlock = require "com.blacksheepherd.code.IfBlock" Line = require "com.blacksheepherd.code.Line" RequireLine = require "com.blacksheepherd.code.RequireLine" class MainBlock ---------------------------------------------------------------- -- Constant for adding children to the variable @{Block}. -- -- @prop BLOCK_VARS ---------------------------------------------------------------- @BLOCK_VARS = 1 ---------------------------------------------------------------- -- Constant for adding children to the update function @{Block}. -- -- @prop BLOCK_UPDATE_FUNCTIONS ---------------------------------------------------------------- @BLOCK_UPDATE_FUNCTIONS = 2 ---------------------------------------------------------------- -- Constant for adding children to the object creation @{Block}. -- -- @prop BLOCK_CREATION ---------------------------------------------------------------- @BLOCK_CREATION = 4 ---------------------------------------------------------------- -- Constant for adding children to the update function call -- @{Block}. -- -- @prop BLOCK_FUNCTION_CALLS ---------------------------------------------------------------- @BLOCK_FUNCTION_CALLS = 8 ---------------------------------------------------------------- -- Create the MainBlock. -- -- @tparam MainBlock self -- @tparam string name The name of the subclass for the -- @{RomlDoc} ---------------------------------------------------------------- new: (name) => @_children = {} table.insert @_children, RequireLine("com.blacksheepherd.roml", "RomlVar") table.insert @_children, RequireLine("com.blacksheepherd.roml", "RomlDoc") table.insert @_children, RequireLine("com.blacksheepherd.roml", "RomlObject") @_extraRequiresBlock = SpaceBlock! @_hasCustomObjectBuilderRequire = false table.insert @_children, @_extraRequiresBlock table.insert @_children, Line("local #{name}") cBlock = DoBlock! cBlock\AddChild Line("local _parent_0 = RomlDoc") baseBlock = TableBlock("_base_0") createFunctionBlock = FunctionBlock("_create", "self, parent, vars") createFunctionBlock\AddChild Line("self._rootObject = RomlObject(self, parent)") createFunctionBlock\AddChild Line("local objTemp") @_varsBlock = SpaceBlock! @_updateFunctionsBlock = SpaceBlock! @_creationBlock = SpaceBlock! @_functionCallsBlock = SpaceBlock! createFunctionBlock\AddChild @_varsBlock createFunctionBlock\AddChild @_updateFunctionsBlock createFunctionBlock\AddChild @_creationBlock createFunctionBlock\AddChild @_functionCallsBlock baseBlock\AddChild createFunctionBlock cBlock\AddChild baseBlock cBlock\AddChild Line("_base_0.__index = _base_0") cBlock\AddChild Line("setmetatable(_base_0, _parent_0.__base)") metatableBlock = MetatableBlock("_class_0") initFunctionBlock = FunctionBlock("__init", "self, parent, vars, ross") initFunctionBlock\AddChild Line("return _parent_0.__init(self, parent, vars, ross)") metatableBlock\AddChild DoubleBlock.TOP, initFunctionBlock metatableBlock\AddChild DoubleBlock.TOP, Line("__base = _base_0") metatableBlock\AddChild DoubleBlock.TOP, Line("__name = \"#{name}\"") metatableBlock\AddChild DoubleBlock.TOP, Line("__parent = _parent_0") indexFunctionBlock = FunctionBlock("__index", "cls, name") indexFunctionBlock\AddChild Line("local val = rawget(_base_0, name)") valueNilCheckBlock = IfElseBlock("val == nil") valueNilCheckBlock\AddChild DoubleBlock.TOP, Line("return _parent_0[name]") valueNilCheckBlock\AddChild DoubleBlock.BOTTOM, Line("return val") indexFunctionBlock\AddChild valueNilCheckBlock metatableBlock\AddChild DoubleBlock.BOTTOM, indexFunctionBlock callFunctionBlock = FunctionBlock("__call", "cls, ...") callFunctionBlock\AddChild Line("local _self_0 = setmetatable({}, _base_0)") callFunctionBlock\AddChild Line("cls.__init(_self_0, ...)") callFunctionBlock\AddChild Line("return _self_0") metatableBlock\AddChild DoubleBlock.BOTTOM, callFunctionBlock cBlock\AddChild metatableBlock cBlock\AddChild Line("_base_0.__class = _class_0") cBlock\AddChild Line("local self = _class_0") newFunctionBlock = FunctionBlock("self.new", "parent, vars, ross") newFunctionBlock\AddChild Line("return #{name}(parent, vars, ross)") cBlock\AddChild newFunctionBlock inheritanceIfBlock = IfBlock("_parent_0.__inherited") inheritanceIfBlock\AddChild Line("_parent_0.__inherited(_parent_0, _class_0)") cBlock\AddChild inheritanceIfBlock cBlock\AddChild Line("#{name} = _class_0") table.insert @_children, cBlock table.insert @_children, Line("return #{name}") ---------------------------------------------------------------- -- Add a child to the create function of the subclass inside the -- specified block. -- -- @tparam MainBlock self -- @tparam string block One of @{BLOCK_VARS}, -- @{BLOCK_UPDATE_FUNCTIONS}, @{BLOCK_CREATION}, -- or @{BLOCK_FUNCTION_CALLS}. -- @tparam Block/Line child The child to add. ---------------------------------------------------------------- AddChild: (block, child) => switch block when @@BLOCK_VARS @_varsBlock\AddChild child when @@BLOCK_UPDATE_FUNCTIONS @_updateFunctionsBlock\AddChild child when @@BLOCK_CREATION @_creationBlock\AddChild child when @@BLOCK_FUNCTION_CALLS @_functionCallsBlock\AddChild child ---------------------------------------------------------------- -- Adds the require for the @{CustomObjectBuilder} class to the -- top of the @{RomlDoc} if it is not already there. -- -- @tparam MainBlock self ---------------------------------------------------------------- AddCustomObjectBuilderRequire: => unless @_hasCustomObjectBuilderRequire @_extraRequiresBlock\AddChild RequireLine("com.blacksheepherd.customobject", "CustomObjectBuilder") ---------------------------------------------------------------- -- Render the MainBlock and all children @{Block}s/@{Line}s. -- -- @tparam MainBlock self ---------------------------------------------------------------- Render: => buffer = "" for child in *@_children buffer ..= child\Render! if child.__class.__name != "SpaceBlock" or child.__class.__name == "SpaceBlock" and #child._children > 0 buffer ..= "\n" return buffer return MainBlock
39.054455
107
0.650906
9c462a20ab96a7df1600e9e5a5c682c525eef421
1,964
--- Class that represents a part with some text displayed on it. It can also be clicked. -- @classmod TextPart MouseInputsManager = require script.Parent.Parent\WaitForChild "MouseInputsManager" class TextPart new: (size, location) => --- Roblox part corresponding to this tile -- @field Part Instance @Part --- Roblox TextLabel displayed on the top of this tile -- @field Label Instance @Label -- I like to define every fields at the beginning of the 'new' method, even when they're empty -- because having doc comments in the middle of the scripts looks weird. -- Kids, here's how you create a Roblox instance Moonscript style. -- Introducing: the 'with' statement @Part = with Instance.new "Part" .Anchored = true .TopSurface = "Smooth" .BottomSurface = "Smooth" .Size = size .CFrame = location .Parent = game.Workspace -- You can name the instance you're working with if you need to with surfaceGui = Instance.new("SurfaceGui") .Face = Enum.NormalId.Top .CanvasSize = 25*Vector2.new size.z, size.x @Label = with Instance.new "TextLabel" -- You can even nest them! .Size = UDim2.new 1, 0, 1, 0 .BackgroundTransparency = 1 .TextScaled = true .Text = "" .Parent = surfaceGui .Parent = @Part --- Set functions to be called when the part is left or right clicked -- @tparam function leftClickCallback what to execute when left clicked -- @tparam function rightClickCallback what to execute when right clicked RegisterClick: (leftClickCallback, rightClickCallback) => MouseInputsManager.BindPartToClick @Part, leftClickCallback, rightClickCallback --- Unbind clicks from the part UnregisterClick: => MouseInputsManager.UnbindPartFromClick @Part --- Clear this item Destroy: => @UnregisterClick! -- This is important. Never forget about memory leaks, kids. @Part\Destroy!
35.709091
98
0.686354
8633f522761ddfda2d262418e7468d1a8ba2bc51
1,888
--- JSON Web Token implementation -- @author RyanSquared <vandor2012@gmail.com> -- @classmod JWTSerializer import json from require "cereal" import from_url64, to_url64 from require "basexx" import Signer from require "bassoon" import random_key from require "bassoon.util" signers = {} _get_signer = (key, algo)-> name = "#{algo}.#{key}" if not signers[name] signers[name] = Signer key, digest_method: algo, separator: "." return signers[name] _get_ossl_algorithm = (algo)-> switch algo when "HS256" "sha256" when "HS512" "sha512" when "none" nil else error "Unknown JWT algorithm: #{algo}" class JWTSerializer --- Create a new JWTSerializer object -- @tparam string algorithm JWT algorithm, can be any of: -- `["HS256", "HS512"]` -- @tparam string key HMAC encryption key new: (algorithm = "HS512", key = random_key!)=> @key = key @algorithm = algorithm @ossl_algorithm = _get_ossl_algorithm algorithm @signer = _get_signer key, @ossl_algorithm --- Encode data into a formatted JWT. Current supported formats are: -- `["HS256", "HS512", "none"]` -- @tparam table data JSON-serializable table encode: (data, plain)=> header = to_url64 json.encode alg: @algorithm b64json = to_url64 json.encode data text = "#{header}.#{b64json}" if plain return text else return @signer\sign text _decode_json = (data)-> json.decode from_url64 data --- Verify and decode formatted JWT -- @tparam string b64data URL base64-formatted JWT decode: (b64data, plain)=> return _decode_json b64data\match "^.-%.(.+)$" if plain header_string, pos = b64data\match "^(.-)%.()" body_string = b64data\match "^(.-)%.", pos header = _decode_json header_string body = _decode_json body_string algorithm = _get_ossl_algorithm header.alg assert @signer\verify_text b64data\match "^(.+)%.(.-)$" return body return {:JWTSerializer}
26.591549
69
0.697564
c8529abf1132776030c9bf6048f777141567eb2b
3,456
path = require "lapis.cmd.path" import get_free_port from require "lapis.cmd.util" import AttachedServer from require "lapis.cmd.attached_server" class NginxAttachedServer extends AttachedServer new: (@runner) => start: (environment, env_overrides) => @existing_config = if path.exists @runner.compiled_config_path path.read_file @runner.compiled_config_path @port = get_free_port! if type(environment) == "string" environment = require("lapis.config").get environment if env_overrides assert not getmetatable(env_overrides), "env_overrides already has metatable, aborting" environment = setmetatable env_overrides, __index: environment env = require "lapis.environment" env.push environment @runner\write_config_for environment, @\process_config pid = @runner\get_pid! @fresh = not pid if pid @runner\send_hup! else assert @runner\start_nginx true @wait_until_ready! detach: => if @existing_config path.write_file @runner.compiled_config_path, @existing_config if @fresh @runner\send_term! @wait_until_closed! else @runner\send_hup! env = require "lapis.environment" env.pop! true exec: (lua_code) => assert loadstring lua_code -- syntax check code ltn12 = require "ltn12" http = require "socket.http" buffer = {} _, status = http.request { url: "http://127.0.0.1:#{@port}/run_lua" sink: ltn12.sink.table buffer source: ltn12.source.string lua_code headers: { "content-length": #lua_code } } unless status == 200 error "Failed to exec code on server, got: #{status}\n\n#{table.concat buffer}" table.concat buffer -- this inserts a special server block in the config that gives remote access -- to it over a special port/location. process_config: (cfg) => assert @port, "attached server doesn't have a port to bind rpc to" run_code_action = [[ ngx.req.read_body() -- hijack print to write to buffer local old_print = print local buffer = {} print = function(...) local str = table.concat({...}, "\t") io.stdout:write(str .. "\n") table.insert(buffer, str) end local success, err = pcall(loadstring(ngx.var.request_body)) if not success then ngx.status = 500 print(err) end ngx.print(table.concat(buffer, "\n")) print = old_print ]] -- escape for nginx config run_code_action = run_code_action\gsub("\\", "\\\\")\gsub('"', '\\"') test_server = [[ server { allow 127.0.0.1; deny all; listen ]] .. @port .. [[; location = /run_lua { client_body_buffer_size 10m; client_max_body_size 10m; content_by_lua " ]] .. run_code_action .. [[ "; } } ]] -- inject the lua path if @runner.base_path != "" default_path = os.getenv "LUA_PATH" default_cpath = os.getenv "LUA_CPATH" server_path = path.join @runner.base_path, "?.lua" server_cpath = path.join @runner.base_path, "?.so" test_server = " lua_package_path '#{server_path};#{default_path}'; lua_package_cpath '#{server_cpath};#{default_cpath}'; " .. test_server cfg\gsub "%f[%a]http%s-{", "http {\n" .. test_server { AttachedServer: NginxAttachedServer }
25.226277
93
0.623264
671e4db1f99c65a7c145ac0a0ffc81c1615b57ec
174
f => xs => ys => val => end => (xs x => xs => c => (c x xs) c => end (ys y => ys => x => xs => (val (f x y) (xs ys)) x => xs => end))
19.333333
51
0.281609
733495e04579485edf41bb04032123978eb2a3db
2,352
export JSON = require "rl_moon/external/json" ---------------------------------- -- Gaus randomness ---------------------------------- return_v = false val_v = 0 gauss_random = -> if return_v return_v = false return val_v u = 2 * math.random! - 1 v = 2 * math.random! - 1 r = u^2 + v^2 return gaus_random if r == 0 or r > 1 c = math.sqrt -2 * (math.log r) / r val_v = v * c return_v = false u * c randf = (a, b) -> math.random! * (b - a) + a randi = (a, b) -> math.floor math.random! * (b - a) + a randn = (m, s) -> m + gaus_random! * s zeros = (n) -> return {} unless n res = {} for i = 1, n res[#res + 1] = 0 res ---------------------------------- -- Matrix ---------------------------------- class Matrix new: (@n, @d) => @w = zeros n * d @dw = zeros n * d get: (r, c) => ix = (@d * r) + c assert ix >= 0 and ix < #@w, "invalid index in matrix" @w[ix] @ set: (r, c, v) => ix = (@d * r) + c assert ix >= 0 and ix < #@w, "invalid index in matrix" @w[ix] = v @ set_from: (t) => for i = 1, n = #t @w[i] = t[i] @ set_col: (m, i) => for i = 1, #m.w @w[@d * q + i] = m.w[i] @ serialize: => t = { "n": @n "d": @d "w": @w } t deserialize: (t) => @n = t.n @d = t.d @w = zeros @n * @d @dw = zeros @n * @d for i = 1, @n * @d @w[i] = t.w[i] @ ---------------------------------- -- Network utilities ---------------------------------- copy_mat = (b) -> a = Mat b.n, b.d a\set_from b.w a copy_net = (n) -> new_n = {} for k, v in pairs n new_n[k] = copy_mat v new_n update_mat = (m, alpha) -> for i = 1, m.n * m.d if m.dw[i] != 0 m.w[i] += -alpha * m.dw[i] m.dw[i] = 0 update_net = (n, alpha) -> new_n = {} for k, v in pairs n update_mat v, alpha serialize_net: (n) -> j = {} for k, v in pairs n j[k] = v\serialize! j deserialize_net: (j) -> n = {} for k, v in pairs j n[k] = Mat 1, 1 n[k]\deserialize v n { :gauss_random :randf :randi :randn ---------------------------------- :Matrix ---------------------------------- :copy_mat :copy_net ---------------------------------- :update_mat :update_net ---------------------------------- :serialize_net }
16.109589
58
0.395408
d94be90409117f247d5fc000dec6d21ff710481b
6,147
-- Copyright 2016 Nils Nordman <nino@nordman.org> -- License: MIT (see LICENSE.md at the top-level directory of the distribution) config = require 'moonpick.config' lfs = require 'lfs' dir = require 'pl.dir' describe 'config', -> write_file = (path, contents) -> f = assert io.open(path, 'wb') f\write contents assert f\close! describe 'config_for(file)', -> local base_dir before_each -> base_dir = os.tmpname! assert(os.remove(base_dir)) if lfs.attributes(base_dir) assert(lfs.mkdir(base_dir)) after_each -> dir.rmtree(base_dir) it 'returns the first available lint_config by moving up the path', -> assert(lfs.mkdir("#{base_dir}/sub")) ex_file = "#{base_dir}/sub/file.moon" in_dir_cfg = "#{base_dir}/sub/lint_config.lua" write_file in_dir_cfg, '{}' assert.equal in_dir_cfg, config.config_for(ex_file) os.remove(in_dir_cfg) parent_dir_cfg = "#{base_dir}/lint_config.lua" write_file parent_dir_cfg, '{}' assert.equal parent_dir_cfg, config.config_for(ex_file) it 'supports and prefers moonscript config files if available', -> assert(lfs.mkdir("#{base_dir}/sub")) ex_file = "#{base_dir}/sub/file.moon" lua_cfg = "#{base_dir}/lint_config.lua" moon_cfg = "#{base_dir}/lint_config.moon" write_file lua_cfg, '{}' write_file moon_cfg, '{}' assert.equal moon_cfg, config.config_for(ex_file) os.remove(moon_cfg) assert.equal lua_cfg, config.config_for(ex_file) describe 'load_config_from(config, file)', -> sorted = (t) -> table.sort t t it 'loads the relevant settings for <file> from <config>', -> cfg = { report_loop_variables: true report_params: false whitelist_globals: { ['.']: { 'foo' }, test: { 'bar' } other: { 'zed' } } whitelist_loop_variables: { test: {'k'} } whitelist_params: { ['.']: {'pipe'} } whitelist_unused: { ['.']: {'general'} } whitelist_shadowing: { ['.']: {'table'} } } loaded = config.load_config_from(cfg, '/test/foo.moon') assert.same { 'bar', 'foo' }, sorted loaded.whitelist_globals assert.same { 'k' }, loaded.whitelist_loop_variables assert.same { 'pipe' }, loaded.whitelist_params assert.same { 'general' }, loaded.whitelist_unused assert.same { 'table' }, loaded.whitelist_shadowing assert.is_true loaded.report_loop_variables assert.is_false loaded.report_params it 'loads <config> as a file when passed as a string', -> path = os.tmpname! write_file path, [[ return { whitelist_globals = { test = {'bar'} } } ]] assert.same { whitelist_globals: { 'bar' } }, config.load_config_from(path, '/test/foo.moon') describe 'evaluator(config)', -> evaluator = config.evaluator describe 'allow_unused_param(p)', -> it 'generally returns true', -> assert.is_true evaluator({}).allow_unused_param('foo') it 'returns false if config.report_params is true', -> assert.is_false evaluator(report_params: true).allow_unused_param('foo') it 'returns true if config.whitelist_params contains <p>', -> whitelist_params = {'foo'} assert.is_true evaluator(:whitelist_params).allow_unused_param('foo') it 'supports patterns', -> whitelist_params = {'^a+'} assert.is_true evaluator(:whitelist_params).allow_unused_param('aardwark') it 'defaults to white listings params starting with an underscore', -> for sym in *{'_', '_foo', '_bar2'} assert.is_true evaluator().allow_unused_param(sym) describe 'allow_unused_loop_variable(p)', -> it 'generally returns false', -> assert.is_false evaluator({}).allow_unused_loop_variable('foo') it 'returns true if config.report_loop_variables is false', -> assert.is_true evaluator(report_loop_variables: false).allow_unused_loop_variable('foo') it 'returns true if config.whitelist_loop_variables contains <p>', -> whitelist_loop_variables = {'foo'} assert.is_true evaluator(:whitelist_loop_variables).allow_unused_loop_variable('foo') it 'supports patterns', -> whitelist_loop_variables = {'^a+'} assert.is_true evaluator(:whitelist_loop_variables).allow_unused_loop_variable('aardwark') it 'defaults to white listing params starting with an underscore', -> for sym in *{'_', '_foo', '_bar2'} assert.is_true evaluator().allow_unused_loop_variable(sym) it 'defaults to white listing the common names "i" and "j"', -> for sym in *{'i', 'j'} assert.is_true evaluator().allow_unused_loop_variable(sym) describe 'allow_global_access(p)', -> it 'generally returns false', -> assert.is_false evaluator({}).allow_global_access('foo') it 'returns true if config.whitelist_globals contains <p>', -> whitelist_globals = {'foo'} assert.is_true evaluator(:whitelist_globals).allow_global_access('foo') it 'supports patterns', -> whitelist_globals = {'^a+'} assert.is_true evaluator(:whitelist_globals).allow_global_access('aardwark') it 'always includes whitelisting of builtins', -> for sym in *{'require', '_G', 'tostring'} assert.is_true evaluator().allow_global_access(sym) whitelist_globals = {'foo'} assert.is_true evaluator(:whitelist_globals).allow_global_access('table') describe 'allow_unused(p)', -> it 'generally returns false', -> assert.is_false evaluator({}).allow_unused('foo') it 'returns true if config.whitelist_unused contains <p>', -> whitelist_unused = {'foo'} assert.is_true evaluator(:whitelist_unused).allow_unused('foo') it 'supports patterns', -> whitelist_unused = {'^a+'} assert.is_true evaluator(:whitelist_unused).allow_unused('aardwark')
33.961326
98
0.634619
33e913efaf8dca8a5b25b12d809bc2cc1ca66ab4
1,503
class GradientStop extends Base new: GradientStop = (arg0, arg1) -> if arg0 color = nil rampPoint = nil if arg1 is nil and isArray(arg0) -- [color, rampPoint] color = arg0[0] rampPoint = arg0[1] else if arg0.color -- stop color = arg0.color rampPoint = arg0.rampPoint else -- color, rampPoint color = arg0 rampPoint = arg1 @setColor(color) @setRampPoint(rampPoint) clone: => GradientStop(@_color\clone(), @_rampPoint) _serialize: (options, dictionary) => Base\serialize [@_color, @_rampPoint], options, true, dictionary _changed: => -- Loop through the gradients that use this stop and notify them about -- the change, so they can notify their gradient colors, which in turn -- will notify the items they are used in: @_owner\_changed Change.STYLE if @_owner ----= getRampPoint: => @_rampPoint setRampPoint: (rampPoint) => @_defaultRamp = not rampPoint? @_rampPoint = rampPoint or 0 @_changed() getColor: => @_color setColor: (color) => -- Make sure newly set colors are cloned, since they can only have -- one owner. @_color = Color\read(arg) @_color = color\clone() if @_color is color @_color._owner = @ @_changed() equals: (stop) => stop is this or stop.__class is GradientStop and @_color\equals(stop._color) and @_rampPoint is stop._rampPoint or false
27.327273
124
0.616101
508d056450254aa4baadc85061420d288e43f9e3
5,908
import forms, console from _G import unpackArrValues, dumpPrint, trim from require "utils" export inputTbl = {} export timestampTbl = {} export clientConnector = nil export cSocket = nil export say = nil class FormConnect @_isClient = false new:()-> print "new" @onClose:()-> print "close form" if cSocket~=nil then cSocket\close() return setReadOnly:(self)-> forms.setproperty(@_txtUdpPort, "ReadOnly", true) forms.setproperty(@_txtConnect, "ReadOnly", true) forms.setproperty(@_txtUdpPort, "ReadOnly", true) forms.setproperty(@_txtConnectPort, "ReadOnly", true) --forms.setproperty(@_txtUsername, "ReadOnly", true forms.setproperty(@_btnInvertPort, "Enabled", false) forms.setproperty(@_btnClientConnect, "Enabled", false) forms.setproperty(@_txtChatMsg, "ReadOnly", false) forms.setproperty(@_btnSendMsg, "Enabled", true) return @onInvertPortClick:()-> tmp1 = forms.getproperty(@_txtConnectPort, "Text").."" tmp2 = forms.getproperty(@_txtUdpPort, "Text").."" forms.setproperty(@_txtConnectPort, "Text", tmp2) forms.setproperty(@_txtUdpPort, "Text", tmp1) return @onStartClientClick:()-> @_isClient= not @_isClient if(@_isClient) then forms.setproperty(@_btnClientConnect, "Text", "Stop Connect") if clientConnector==nil then print "setup client connector" client_udp= require("client_udp") clientConnector = client_udp.ClientSpawn cSocket = client_udp.clientSocket bn = "*" bp = forms.getproperty(@_txtUdpPort, "Text") pn = forms.getproperty(@_txtConnect, "Text") pp = forms.getproperty(@_txtConnectPort, "Text") usr=forms.getproperty(@_txtUsername, "Text") clientConnector\setBindname(trim(bn)) clientConnector\setBindport(trim(bp)) clientConnector\setPeername(trim(pn)) clientConnector\setPeerport(trim(pp)) clientConnector\initSocket() clientConnector\setUsername(trim(usr)) clientConnector\testRun(inputTbl) @setReadOnly() clientConnector\setForm(self) clientConnector\setInputQueue(inputTbl) clientConnector\setTimestampList(timestampTbl) clientConnector\startTimer() else forms.setproperty(@_btnClientConnect, "Text", "Client Client") return addMsgQueue:(self, msg)-> if clientConnector ~= nil then clientConnector\addInputQueue(msg) clientConnector\run() updateClient:(self, msg)-> fullMsg = forms.getproperty(@_txtChatBox, "Text") fullMsg = fullMsg..msg.."\r\n" forms.setproperty(@_txtChatMsg, "Text", "") forms.setproperty(@_txtChatBox, "Text", fullMsg) sendMsg:(self, msg)-> usrname = forms.getproperty(@_txtUsername, "Text") txtMsg = usrname..": "..msg @addMsgQueue(txtMsg) @updateClient(txtMsg) updateStatus:(self, newStatus)-> forms.setproperty(@_txtStatus, "Text", newStatus) @onSendMsgClick:()-> msg=forms.getproperty(@_txtChatMsg, "Text") @sendMsg(msg) @_frmConnect = forms.newform unpackArrValues({(w:320),(h:420),(title:"Chat Box"),(fnClose:@onClose)}) @_lblConnect = forms.label unpackArrValues({(frm:@_frmConnect), (cap:"Connect to:"), (x:10), (y:10), (w:140), (h:30), (fw:true)}) @_txtConnect = forms.textbox unpackArrValues({(frm:@_frmConnect), (cap:"localhost"), (w:140), (h:30), (bt:nil), (x:150), (y:10), (mlt:false), (fw:true), (scroll:"NONE")}) @_lblConnectPort = forms.label unpackArrValues({(frm:@_frmConnect), (cap:"Connect to UDP:"), (x:10), (y:40), (w:140), (h:30), (fw:true)}) @_txtConnectPort = forms.textbox unpackArrValues({(frm:@_frmConnect), (cap:"51425"), (w:140), (h:30), (bt:nil), (x:150), (y:40), (mlt:false), (fw:true), (scroll:"NONE")}) @_lblUdpPort = forms.label unpackArrValues({(frm:@_frmConnect), (cap:"UDP Port:"), (x:10), (y:70), (w:140), (h:30), (fw:true)}) @_txtUdpPort = forms.textbox unpackArrValues({(frm:@_frmConnect), (cap:"51424"), (w:140), (h:30), (bt:nil), (x:150), (y:70), (mlt:false), (fw:true), (scroll:"NONE")}) @_lblUsername = forms.label unpackArrValues({(frm:@_frmConnect), (cap:"Username:"), (x:10), (y:100), (w:140), (h:30), (fw:true)}) @_txtUsername = forms.textbox unpackArrValues({(frm:@_frmConnect), (cap:"MyUsername"), (w:140), (h:30), (bt:nil), (x:150), (y:100), (mlt:false), (fw:true), (scroll:"NONE")}) @_btnInvertPort = forms.button unpackArrValues({(frm:@_frmConnect), (cap:"Invert Port"), (fnClick:@onInvertPortClick), (x:10), (y:130), (w:140), (h:30)}) @_btnClientConnect = forms.button unpackArrValues({(frm:@_frmConnect), (cap:"Client Connect"), (fnClick:@onStartClientClick), (x:150), (y:130), (w:140), (h:30)}) @_lblStatus = forms.label unpackArrValues({(frm:@_frmConnect), (cap:"Status:"), (x:10), (y:170), (w:140), (h:30), (fw:true)}) @_txtStatus = forms.textbox unpackArrValues({(frm:@_frmConnect), (cap:"Unknown"), (w:140), (h:30), (bt:nil), (x:150), (y:170), (mlt:false), (fw:true), (scroll:"NONE")}) forms.setproperty(@_txtStatus, "ReadOnly", true) @_txtChatBox = forms.textbox unpackArrValues({(frm:@_frmConnect), (cap:""), (w:280), (h:100), (bt:nil), (x:10), (y:200), (mlt:true), (fw:true), (scroll:"VERTICAL")}) forms.setproperty(@_txtChatBox, "ReadOnly", true) @_lblChatMsg = forms.label unpackArrValues({(frm:@_frmConnect), (cap:"Chat:"), (x:10), (y:310), (w:50), (h:30), (fw:true)}) @_txtChatMsg = forms.textbox unpackArrValues({(frm:@_frmConnect), (cap:""), (w:230), (h:30), (bt:nil), (x:60), (y:310), (mlt:false), (fw:true), (scroll:"NONE")}) forms.setproperty(@_txtChatMsg, "ReadOnly", true) @_btnSendMsg = forms.button unpackArrValues({(frm:@_frmConnect), (cap:"Send Msg"), (fnClick:@onSendMsgClick), (x:150), (y:340), (w:140), (h:30)}) forms.setproperty(@_btnSendMsg, "Enabled", false) say=(msg)-> FormConnect\sendMsg(msg) return {:FormConnect, :say}
44.089552
176
0.656229
7a6078eb87492925cd26e22aba0a9bbd2dde1618
2,272
import concat from table import char from string --- utils ----{{{ zsplit = (n = 1) => [c for c in @\gmatch "."\rep n] string = string -- in THIS chunk, add `zsplit` to `string` module string.zsplit = zsplit map = (fn, xs) -> [fn x for x in *xs] filter = (fn, xs) -> [x for x in *xs when fn x] foldl = (fn, xr, xs) -> for x in *xs xr = fn xr, x xr idcomp = (obj1, obj2) -> (tostring obj1) == (tostring obj2) have = (t, e) -> (filter (=> (idcomp @, e) or @ == e), t)[1] delete = (t, v) -> table.remove t, i for i = 1, #t when (idcomp t[i], v) or t[i] == v last = => @[#@] isk = (rk) -> rk < 0 and (rk % 256) != 0 cstid = (k) -> (math.abs k) % 256 + (k >= 0 and 1 or 0) undecimal = do hexdecode = (cnt = 1) -> ("%02X"\rep cnt)\format -- `"ff"` -> `"11111111"` hextobin = do bintbl = { [0]: "0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111" } (hex) -> concat map (=> bintbl[(tonumber "0x#{@}")]), hex\zsplit! -- `"00011", 4` -> `"0011"` adjustdigit = (r, a) -> if #r > a r\match("#{'.'\rep (#r - a)}(.*)") else "0"\rep(a - #r) .. r -- `"11111111"` -> `256` bintoint = (bin) -> i = -1 with ret = 0 for c in bin\reverse!\gmatch"." i += 1 ret += 2^i * math.tointeger c -- `"0xff"` -> `256` hextoint = (hex) -> tonumber hex, 16 -- `"41"` -> `"A"` hextochar = (ahex) -> string.char tonumber "0x#{ahex}" bintohex = do b2htbl = { ["0000"]: "0", ["0001"]: "1", ["0010"]: "2", ["0011"]: "3", ["0100"]: "4", ["0101"]: "5", ["0110"]: "6", ["0111"]: "7", ["1000"]: "8", ["1001"]: "9", ["1010"]: "a", ["1011"]: "b", ["1100"]: "c", ["1101"]: "d", ["1110"]: "e", ["1111"]: "f" } (b) -> b2htbl[b] inttobin = => (hextobin "%x"\format @) {:hexdecode, :hextobin, :adjustdigit, :bintoint, :hextoint, :hextochar, :bintohex, :inttobin} deepcpy = (t, list = {}) -> with ret = {} for k, v in pairs t if type(v) == "table" kk = tostring v unless list[kk] list[kk] = v ret[k] = deepcpy v, list else ret[k] = list[kk] else ret[k] = v prerr = (ne, msg) -> not ne and io.stdout\write(msg , '\n') ----}}} {:zsplit, :map, :filter, :foldl, :idcomp, :have, :delete, :last, :isk, :cstid, :prerr, :undecimal, :deepcpy}
26.729412
108
0.5
59816a97c9cb73d5b54963347424babf16460d0a
843
db = require "lapis.db" logger = require "lapis.logging" import Model from require "lapis.db.model" class LapisMigrations extends Model primary_key: "name" @exists: (name) => @find tostring name @create: (name) => Model.create @, { name: tostring name } create_migrations_table = (table_name="lapis_migrations") -> schema = require "lapis.db.schema" import create_table, types from schema create_table table_name, { { "name", types.varchar } "PRIMARY KEY(name)" } run_migrations = (migrations) -> tuples = [{k,v} for k,v in pairs migrations] table.sort tuples, (a, b) -> a[1] < b[1] for _, {name, fn} in ipairs tuples unless LapisMigrations\exists name logger.migration name fn name LapisMigrations\create name { :create_migrations_table, :run_migrations, :LapisMigrations }
23.416667
63
0.68446
b6529f518673a9099c43f48d529b97b14f627e88
1,053
-- Copyright 2012-2015 The Howl Developers -- License: MIT (see LICENSE.md at the top-level directory of the distribution) import app, clipboard, interact from howl clip_completions = (max_columns) -> completions = {} for i, clip in ipairs clipboard.clips text = clip.text\gsub '\n', '..↩' if text.ulen > max_columns text = text\usub(1, max_columns - 4) .. '[..]' table.insert completions, { tostring(i), text.stripped, :clip } return completions interact.register name: 'select_clipboard_item' description: 'Selection list for clipboard items' handler: (opts={}) -> opts = moon.copy opts items = clip_completions app.window.command_line.width_cols - 9 if #items == 0 log.info '(Clipboard is empty)' return with opts .title or= 'Clipboard items' .items = items .columns = { { header: 'Position', style: 'number' }, { header: 'Content', style: 'string' } } selected = interact.select opts if selected return selected.selection.clip
25.682927
79
0.646724
b79917c935a2c1f14527eb1a69e0e9b02be95a35
6,948
-- Copyright 2012-2016 The Howl Developers -- License: MIT (see LICENSE.md at the top-level directory of the distribution) import const_char_p from howl.cdefs import g_string from howl.cdefs.glib import string, type from _G ffi = require 'ffi' bit = require 'bit' import C from ffi append = table.insert {:min} = math transform_rets = (s, ...) -> vals = {...} ptr = const_char_p s for i = 1, #vals val = vals[i] if type(val) == 'number' pos_ptr = ptr + val - 1 -- position may be in the middle of a sequence here, so back up as needed while pos_ptr != ptr and bit.band(pos_ptr[0], 0xc0) == 0x80 pos_ptr -= 1 char_offset = C.g_utf8_pointer_to_offset ptr, pos_ptr vals[i] = tonumber char_offset + 1 table.unpack vals ulen = (s) -> tonumber C.g_utf8_strlen const_char_p(s), #s char_to_byte_offset = (s, i) -> return nil if i == nil len = ulen s if i < 0 i = len + i elseif i > len i = len i = 1 if i < 1 ptr = const_char_p(s) (C.g_utf8_offset_to_pointer(ptr, i - 1) - ptr) + 1 -- convert to byte offset byte_offset = (s, ...) -> len = ulen s ptr = const_char_p s multibyte = s.multibyte cur_c_offset = 1 cur_b_offset = 1 args = {...} offsets = {} is_table = false if type(args[1]) == 'table' args = args[1] is_table = true for offset in *args o = offset - cur_c_offset if o == 0 then append offsets, cur_b_offset elseif o < 0 then error "Decreasing offset '#{offset}': must be >= than previous offset '#{cur_c_offset}'", 2 elseif o + cur_c_offset > len + 1 then error "Offset '#{offset}' out of bounds (length = #{len})", 2 elseif not multibyte then append offsets, offset else next_ptr = C.g_utf8_offset_to_pointer ptr, o cur_b_offset += next_ptr - ptr append offsets, cur_b_offset ptr = next_ptr cur_c_offset = offset return if is_table offsets else table.unpack offsets char_offset = (s, ...) -> size = #s ptr = const_char_p s multibyte = s.multibyte cur_c_offset = 1 cur_b_offset = 1 args = {...} offsets = {} is_table = false if type(args[1]) == 'table' args = args[1] is_table = true for offset in *args o = offset - cur_b_offset if o == 0 then append offsets, cur_c_offset elseif o < 0 then error "Decreasing offset '#{offset}': must be >= than previous offset '#{cur_b_offset}'", 2 elseif o + cur_b_offset > size + 1 then error "Offset '#{offset}' out of bounds (size = #{size})", 2 elseif not multibyte then append offsets, offset else next_ptr = ptr + o cur_b_offset += next_ptr - ptr cur_c_offset += tonumber C.g_utf8_pointer_to_offset ptr, next_ptr append offsets, cur_c_offset ptr = next_ptr return if is_table offsets else table.unpack offsets usub = (i, j = -1) => len = ulen @ i += len + 1 if i < 0 j += len + 1 if j < 0 i = 1 if i < 1 j = len if j > len return '' if j < i g_string C.g_utf8_substring(const_char_p(@), i - 1, j) umatch = (s, pattern, init = 1) -> return nil if init and init > ulen s return pattern\match s, init if r.is_instance pattern init = char_to_byte_offset s, init transform_rets s, string.match s, pattern, init ugmatch = (s, pattern) -> return pattern\gmatch(s)if r.is_instance pattern gen = string.gmatch s, pattern -> transform_rets s, gen! ufind = (s, pattern, init = 1, plain = false) -> return nil if init and init > ulen s return pattern\find(s, init) if r.is_instance pattern init = char_to_byte_offset s, init transform_rets s, string.find s, pattern, init, plain rfind = (s, text, init = #s) -> init -= 1 -- 0-based indexing text_len = #text s_bytes = const_char_p(s) text_bytes = const_char_p(text) matched = false for s_idx = init - text_len + 1, 0, -1 for text_idx = text_len - 1, 0, -1 text_byte = text_bytes[text_idx] s_byte = s_bytes[s_idx + text_idx] matched = text_byte == s_byte if not matched break if matched match_pos = s_idx + 1 return match_pos, match_pos + text_len - 1 urfind = (s, text, init = s.ulen) -> if init < 0 init = s.ulen + init + 1 if text.is_empty return init, init - 1 -- get offset of last byte of char at init init = s\byte_offset(init) + #s\usub(init, init) - 1 start_pos, end_pos = rfind s, text, init return transform_rets s, start_pos, end_pos ucompare = (s1, s2) -> C.g_utf8_collate const_char_p(s1), const_char_p(s2) starts_with = (s1, s2) -> s1\find(s2, 1, true) == 1 ends_with = (s1, s2) -> start = (#s1 - #s2) + 1 return false if start < 1 s1\find(s2, start, true) == start contains = (s1, s2) -> s1\find(s2, 1, true) != nil count = (s1, s2, is_pattern = false) -> c = 0 pos = 1 while pos _, pos = s1\ufind s2, pos, not is_pattern if pos c += 1 pos += 1 c truncate = (s, len, opts = {}) -> s_len = s.ulen if s_len > len if opts.omission_prefix omission = opts.omission_prefix o_ulen = omission.ulen if o_ulen <= len start = o_ulen + s.ulen - len + 1 s = omission .. s\usub(start, start + len) else start = s.ulen - len + 1 s = s\usub(start, start + len - 1) else omission = opts.omission_suffix or '..' if omission.ulen <= len msg_length = len - omission.ulen s = s\usub(1, msg_length) .. omission else s = s\usub(1, len) s split = (s, pattern) -> return {} if s == "" parts = {} s_pos = 1 p, e_pos = s\find pattern while p append parts, s\sub(s_pos, p - 1) p = e_pos + 1 s_pos = p p, e_pos = s\find pattern, p append parts, s\sub(s_pos) parts with string .usub = usub .umatch = umatch .ugmatch = ugmatch .ufind = ufind .rfind = rfind .urfind = urfind .ucompare = ucompare .byte_offset = byte_offset .char_offset = char_offset .starts_with = starts_with .ends_with = ends_with .contains = contains .count = count .truncate = truncate .split = split properties = ulen: => ulen @ multibyte: => ulen(@) != #@ ulower: => g_string C.g_utf8_strdown(const_char_p(@), #@) uupper: => g_string C.g_utf8_strup(const_char_p(@), #@) ureverse: => g_string C.g_utf8_strreverse(const_char_p(@), #@) is_empty: => #@ == 0 is_blank: => @find('%S') == nil is_valid_utf8: => C.g_utf8_validate(ffi.cast('const char *', @), #@, nil) != 0 stripped: => @match '%s*(.-)%s*$' is_likely_binary: => s = ffi.cast 'const unsigned char *', @ non_print = 0 check = min(#@, 150) for i = 0, check - 1 c = s[i] if c < 9 or (c >= 14 and c < 32) non_print += 1 non_print / check >= 0.1 getmetatable('').__index = (k) => return usub(@, k, k) if type(k) == 'number' return properties[k] self if properties[k] rawget string, k
24.814286
115
0.607513
9f95d49a45978680aa49a08af613d49a67cf0ae0
1,655
-- typekit.type.match -- Pattern matching for typekit -- By daelvn import DEBUG from require "typekit.config" import inspect, log, processor from (require "typekit.debug") DEBUG import typeof, kindof from require "typekit.type" import typeError from require "typekit.type.error" import metatype, keysIn, isUpper, isLower from require "typekit.commons" Unbound = (metatype "Unbound") {} Variable = (s) -> (metatype "Variable") {variable: s} _, V = Unbound, Variable -- Function that takes in any value and defines it as a shape. import Tag, TKType, S, Pt, T, L from require "typekit.tableshape" shapeFor = (x) -> switch typeof x when "Unbound" then return T"any" when "Variable" then return (Tag T"any") x.variable when "String", "Number", "Thread", "Boolean", "Userdata", "Nil" return (Tag L x) "value" when "Table" return (Tag Pt x) "value" when "Pair" a, b = x[1], x[2] return (Pt {(shapeFor a), (shapeFor b)}) else -- if kindof x then return Pt [shapeFor v for v in *x] -- else return E x -- should match type *and* kind and also values inside return (TKType x, shapeFor) -- Takes a list of things to match and returns a shape -- case V"x", (Just V"y"), _ case = (...) -> shapel = {} for arg in *{...} table.insert shapel, shapeFor arg return (metatype "Case") shapel -- Matches a value to part of a case match = (C, i, v) -> C[i] v -- Advances an argument in the case advance = (C) -> if 0 == keysIn C then return nil table.remove C, 1 return C { :case, :match, :advance :Unbound, :Variable }
29.035088
65
0.62719
23d32e63777b11c918a65ad2b33ac854feea3349
95
export modinfo = { type: "command" desc: "Troll" alias: {"tr"} func: -> SetSky 23881644 }
13.571429
18
0.610526
260773144ed2c6e525ab9dfe622763100424a2ee
622
application = require "lapis.application" import Application from application app_cache = {} setmetatable app_cache, __mode: "k" local dispatcher serve = (app_cls) -> app = app_cache[app_cls] unless app name = app_cls if type(name) == "string" app_cls = require(name) app = if app_cls.__base -- is a class app_cls! else app_cls\build_router! app_cls app_cache[name] = app unless dispatcher dispatcher = if __leda require "lapis.leda" else require "lapis.nginx" dispatcher.dispatch app { :serve, :application, :Application, :app_cache }
15.948718
48
0.659164
253b6a21b879e7ee7b75eea76369a435d25dfd81
506
cdef_BF_FRAME=[[ #pragma pack(1) struct BF_FRAME { char magic[4]; // unterminated "BFPX" uint32_t x,y; uint8_t r,g,b,a; }; ]] cdef_FF_IMAGE=[[ // all numbers in big endian #pragma pack(1) struct FF_IMAGE_header { char magic[8]; // unterminated 'farbfeld' uint32_t w; uint32_t h; }; struct FF_IMAGE_pixel { uint16_t r,g,b,a; }; struct FF_IMAGE { struct FF_IMAGE_header header; struct FF_IMAGE_pixel pixels[?]; }; ]] {:cdef_BF_FRAME, :cdef_FF_IMAGE}
18.740741
45
0.640316
739728a9041ca07b748acc7ae5b7efbf4de7b005
928
import Widget from require "lapis.html" class register extends Widget content: => h1 "Register account" form action: @url_for("lazuli_modules_usermanagement_register_do"), method: "post", class: "pure-form pure-form-aligned", -> input type: "hidden", name: "csrf_token", value: @modules.user_management.csrf_token fieldset -> div class: "pure-control-group", -> label for: "username", "Username:" input id: "username",name: "username" div class: "pure-control-group", -> label for: "password", "Password:" input id: "password", type: "password", name: "password" div class: "pure-control-group", -> label for: "password_repeat", "Repeat:" input id: "password_repeat", type: "password",name: "password_repeat" div class: "pure-controls", -> input type: "submit", class: "pure-button pure-button-primary"
46.4
128
0.632543
1f99f371d8a8bec1ab6d9d71445efb8a9255996b
1,229
export modinfo = { type: "function" id: "LoadProbe" func: -> pcall -> LocalPlayer.Character = nil if ConfigSystem "Get", "AutomaticallyRemovePlayer" LocalPlayer.Parent = nil f = CreateInstance"Part"{ _Init: (obj) -> Spawn -> while obj\IsDescendantOf(workspace) and wait! obj.CFrame = ConfigSystem("Get", "Camera").Focus obj.Parent = nil Parent: workspace Name: "Purobu" Anchored: true Shape: "Ball" Size: Vector3.new 5,5,5 Transparency: .3 BrickColor: BrickColor.new "Black" Material: "Plastic" Reflectance: .3 CanCollide: false TopSurface: 0 BottomSurface: 0 CreateInstance"BillboardGui"{ Size: UDim2.new 3, 0, 3, 0 ExtentsOffset: Vector3.new 0, 2, 0 CreateInstance"TextLabel"{ FontSize: "Size36" Font: "ArialBold" Text: CharacterName TextTransparency: .3 BackgroundTransparency: 1 TextColor3: Color3.new! TextStrokeTransparency: 0 Size: UDim2.new 1,0,1,0 } } CreateInstance"PointLight"{ Range: ConfigSystem "Get", "ProbeLightRange" Brightness: ConfigSystem "Get", "ProbeLightBrightness" Color: ConfigSystem "Get", "ProbeLightColour" Enabled: true } } Probe = f }
23.634615
58
0.657445
9058b9670394be0208aadcf317c70dc8acb4fff8
7,196
-- typekit.parser.init -- Main parser module for typekit signatures -- By daelvn import DEBUG from require "typekit.config" import inspect, log from (require "typekit.debug") DEBUG import parserError from require "typekit.parser.error" import trim, isString, getlr from require "typekit.commons" -- Signature format -- f :: Cl a => a -> b -> c -- f :: {a:b} -> {b:a} -- f :: [a] -> [b] -- f :: Eq a, Ord a => Maybe a -> Boolean -- FUTURE? -- f :: s -> (s, a) -- Returns and removes the name for a signature, if exists nameFor = (sig) -> log "parser.nameFor #got", inspect sig local name sig = sig\gsub "^%s*(.+)%s*::%s*", (s) -> log "parser.nameFor", "#{s} ::" name = s "" return (trim name), sig -- Merge constraints -- Overrides current <- base -- merge: -- Eq a => a -> a -- Ord a => a -> a -- clears Eq constraint -- 'a' does not have Eq constraint anymore but has Ord constraint. mergeConstraints = (target, base) -> nt = {var, {const for const in *constl} for var, constl in pairs base} for var, constl in pairs base nt[var] = constl nt -- Returns and removes the constraints in a signature constraintsFor = (sig, pconstl={}) -> constl = {} sig = sig\gsub "^%s*(.-)%s*=>%s*", (s) -> constl = [trim const for const in s\gmatch "[^,]+"] "" -- constraints = {} for const in *constl parts = [part for part in const\gmatch "%S+"] if #parts > 2 then parserError "More than two applications in constraint #{inspect parts} in '#{sig}'" if constraints[parts[2]] table.insert constraints[parts[2]], parts[1] else constraints[parts[2]] = {parts[1]} -- constraints = mergeConstraints pconstl, constraints -- return constraints, sig -- Base for checkParenthesis, checkList and checkTable checkX = (fname, ochar, cchar, charname) -> (sig) -> log "parser.#{fname} #got", inspect sig return false if "string" != type sig i = 0 depth = 0 over0 = 0 -- 0 -> hasnt gone over 0, 1 -> has gone over 1, 2 -> has gone back to 0 -- canremove = true for ch in sig\gmatch "." i += 1 log "parser.#{fname} #status", "#{i}: #{ch} (#{depth}) OVERZERO=#{over0}" switch ch when ochar then depth += 1 when cchar then depth -= 1 parserError "Mismatching #{charname} for signature '#{sig}' at col #{i}" if depth < 0 switch over0 when 0 then over0 = 1 if depth > 0 when 1 then over0 = 2 if depth == 0 when 2 then canremove = false log "parser.#{fname} #over", "over0 = 2" if over0 == 2 -- parserError "Mismatching #{charname} for signature '#{sig}' at col #{i}" if depth != 0 canremove = false if over0 == 0 log "parser.#{fname} #ret", "returning #{canremove}" canremove -- Removes top-most parens -- instead of using a pattern, has to be done manually to ensure they are the same parens -- for that we use checkParens checkParenthesis = checkX "checkParenthesis", "(", ")", "parenthesis" removeParenthesis = (sig) -> if x = sig\match "^%s*%((.+)%)%s*$" then x else sig -- turns [a] -> {container: "List", value: "a"} checkList = checkX "checkList", "[", "]", "square brackets" toList = (sig) -> return sig if "string" != type sig if x = sig\match "^%[(.+)%]$" then {container: "List", value: x} else sig -- turns {a:b} -> {container: "Table", key: "a", value: "b"} checkTable = checkX "checkTable", "{", "}", "curly brackets" toTable = (sig) -> return sig if "string" != type sig key, value = sig\match "^{(.+):(.+)}$" if key and value return {container: "Table", :key, :value} else return sig -- turns 'Maybe a' -> {data: "Maybe a", "Maybe", "a"} checkApplication = (sig) -> return false if "string" != type sig return false if sig\match "%->" return false if not sig\match " " return false if sig\match "^[%{%[]" return true toApplication = (sig) -> parts = [part for part in sig\gmatch "%S+"] parts.data = sig return parts -- Splits a signature in two by an arrow -> -- returns tree binarize = (sig, child=false, pname, pconstl) -> log "parser.binarize #got", sig sig = removeParenthesis sig if checkParenthesis sig -- Get name and constraints name, sig = nameFor sig constl, sig = constraintsFor sig, pconstl -- If we are inside another signature, check if we are scoped. if child constl = mergeConstraints constl, pconstl if name != pname log "parser.binarize #name", "name changed from #{pname} to #{name}" -- Variables log "parser.binarize #sig", sig left, right = "", "" side = false -- false -> left, true -> right depth = 0 flag = {} -- Functions agglutinate = (ch) -> if side then right ..= ch else left ..= ch for char in sig\gmatch "." do log "parser.binarize #loop", inspect { :side :depth {:left, :right} await: flag.await_arrow } switch char when "(" agglutinate char continue if side depth += 1 flag.await_arrow = false when ")" agglutinate char continue if side depth -= 1 flag.await_arrow = false when "-" flag.await_arrow = true if depth == 0 agglutinate char if (depth > 0) or side when ">" if (depth > 0) or side agglutinate char elseif flag.await_arrow flag.await_arrow = false side = true else agglutinate char else flag.await_arrow = false agglutinate char -- Fix arrowless functions if right == "" right = left left = "" log "parser.binarize #ret", "#{left} >> #{right}" return {left: (trim left), right: (trim right), :name, :constl, signature: sig} -- recursively binarize rebinarize = (sig, child=false, pname, pconstl) -> S = binarize sig, child, pname, pconstl l, r = getlr S oldl, oldr = l, r -- S.left = toList S.left if checkList S.left S.left = toTable S.left if checkTable S.left S.left = toApplication S.left if checkApplication S.left S.right = toList S.right if checkList S.right S.right = toTable S.right if checkTable S.right S.right = toApplication S.right if checkApplication S.right -- S.left[#S.left] = toList S.left[#S.left] if (S.left[1]) and checkList S.left[#S.left] S.right[#S.right] = toList S.right[#S.right] if (S.right[1]) and checkList S.right[#S.right] S.left[#S.left] = toTable S.left[#S.left] if (S.left[1]) and checkTable S.left[#S.left] S.right[#S.right] = toTable S.right[#S.right] if (S.right[1]) and checkTable S.right[#S.right] -- S.left = rebinarize S.left, true, S.name, S.constl if (isString S.left) and S.left\match "%->" log "parser.rebinarize #ch", "l: #{oldl} >> #{inspect l}" if S.left != oldl S.right = rebinarize S.right, true, S.name, S.constl if (isString S.right) and S.right\match "%->" log "parser.rebinarize #ch", "r: #{oldr} >> #{inspect r}" if S.right != oldr -- S { :nameFor, :constraintsFor, :getlr :mergeConstraints :binarize, :rebinarize }
33.16129
106
0.59547
7c6e1a74c88b32eadd71dcee6a344d37beaf2130
352
-- Copyright 2016 Jake Russo -- License: MIT howl.mode.register name: 'stanza' extensions: { 'stz,' 'stanza' } -- shebangs: '[/ ]stanza.*$' create: -> bundle_load 'stanza_mode' unload = -> howl.mode.unregister 'stanza' { info: author: 'The Howl Developers' description: 'A Stanza bundle', license: 'MIT', :unload }
16
41
0.613636
430a48ab39d37bbf2afd3f426d0ca4ec0fc30f69
3,664
-- This file defines some methods on Lua numbers, bools, actions, nil, and coroutines require "text" number_mt = __type: "a Number" as_lua: tostring as_nomsu: tostring as_text: tostring as_a_number: => @ rounded: => math.floor(@ + .5) rounded_down: math.floor rounded_up: math.ceil to_the_nearest: (rounder)=> rounder * math.floor(@/rounder + 0.5) base16: => ("%X")\format(@) number_mt.__index = number_mt debug.setmetatable 0, number_mt bool_mt = __type: "a Boolean" __len: => @ and 1 or 0 as_lua: tostring as_nomsu: => @ and "yes" or "no" as_text: => @ and "yes" or "no" _and: (cond)=> @ and cond _or: (cond)=> @ or cond xor: (cond)=> @ == (not cond) bool_mt.__index = bool_mt debug.setmetatable true, bool_mt fn_mt = __type: "an Action" as_text: => (tostring(@)\gsub("function", "Action")) __add: (other)=> if type(@) == 'function' and type(other) == 'function' (...)-> (@(...) + other(...)) elseif type(@) == 'function' then (...)-> (@(...) + other) else (...)-> (@ + other(...)) __sub: (other)=> if type(@) == 'function' and type(other) == 'function' (...)-> (@(...) - other(...)) elseif type(@) == 'function' then (...)-> (@(...) - other) else (...)-> (@ - other(...)) __mul: (other)=> if type(@) == 'function' and type(other) == 'function' (...)-> (@(...) * other(...)) elseif type(@) == 'function' then (...)-> (@(...) * other) else (...)-> (@ * other(...)) __div: (other)=> if type(@) == 'function' and type(other) == 'function' (...)-> (@(...) other(...)) elseif type(@) == 'function' then (...)-> (@(...) other) else (...)-> (@ other(...)) __mod: (other)=> if type(@) == 'function' and type(other) == 'function' (...)-> (@(...) % other(...)) elseif type(@) == 'function' then (...)-> (@(...) % other) else (...)-> (@ % other(...)) __band: (other)=> if type(@) == 'function' and type(other) == 'function' (...)-> (@(...) and other(...)) elseif type(@) == 'function' then (...)-> (@(...) and other) else (...)-> (@ and other(...)) __bor: (other)=> if type(@) == 'function' and type(other) == 'function' (...)-> (@(...) or other(...)) elseif type(@) == 'function' then (...)-> (@(...) or other) else (...)-> (@ or other(...)) __bxor: (other)=> if type(@) == 'function' and type(other) == 'function' (...)-> (@(...) != other(...)) elseif type(@) == 'function' then (...)-> (@(...) != other) else (...)-> (@ != other(...)) fn_mt.__index = fn_mt debug.setmetatable (->), fn_mt _last_co_i = setmetatable({}, {__mode:'k'}) local co_mt co_mt = __type: "a Coroutine" as_text: => (tostring(@)\gsub("thread", "Coroutine")).." ("..coroutine.status(@)..")" __len: => math.huge __call: coroutine.resume __inext: (k)=> ok, val = coroutine.resume(@) return if coroutine.status(@) == 'dead' if ok then return (k or 0) + 1, val __index: (k)=> if k == (_last_co_i[@] or 0) + 1 ret = {coroutine.resume(@, k)} _last_co_i[@] = k if ret[1] return table.unpack(ret, 2) else return nil return co_mt[k] co_mt.__next = co_mt.__inext debug.setmetatable(coroutine.create(->), co_mt) nil_mt = __type: "Nil" as_lua: => "nil" as_nomsu: => "nil" as_text: => "nil" nil_mt.__index = nil_mt debug.setmetatable nil, nil_mt
34.566038
89
0.480349
88761e002177bfe195daac7df76f1600ab182256
167
export modinfo = { type: "function" id: "GetPlayerGui" func: (player) -> for i, v in pairs player\GetChildren! if v\IsA"PlayerGui" return v return nil }
16.7
39
0.652695
dd3a0fbcd4ddef97622227559194f256a76e63d7
188
Component = require "lib.concord.component" Vector = require "src.Vector" Mover = Component (entity, speed, velocity) -> entity.speed = speed entity.velocity = velocity or Vector! Mover
26.857143
46
0.75
6adf9497aaa0720af8f59e07c986ef11321134d8
1,222
---------------------------------------------------------------- -- A @{Block} that allows a variable in a @{TableBlock} or -- @{AnonymousTableBlock} to be a Stack. -- -- @classmod StackBlock -- @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 StackBlock extends Block ---------------------------------------------------------------- -- Create the StackBlock. -- -- @tparam MainBlock self -- @tparam string name The name of the variable that the Stack -- is assigned to. ---------------------------------------------------------------- new: (name) => super! @_name = name 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} = Stack({" AfterRender: => "#{@_indent}})" -- {{ TBSHTEMPLATE:END }} return StackBlock
24.44
65
0.517185
e83d61302440c2b9c49ba1827657b1a74ac75b5a
260
export * title = "Catch the Pizza" author = "Rodrigo Cacilhas" shortname = "pizza" version = "1.0.4" support_email = "batalema@cacilhas.info" copyright_message = "Copyright © 2019, 2020 Rodrigo Cacilhas." luavm = "luajit" icon = "resources/pizza-128x128.png"
23.636364
62
0.730769
b32b8e35486c671c79779873fbd81537d73919b1
5,627
require 'moon.all' import _ from require 'luassert.match' import merge, mtype from require 'ngx-oauth.util' import Left, Right from require 'ngx-oauth.either' HTTP_INST = '<fake-http-instance>' http_stub = {} url = 'https://example.org' accept_json_header = { Accept: 'application/json' } -- Trick Lua to require our fake table instead of resty.http module -- into http_client. setup -> package.loaded['resty.http'] = http_stub export client = require 'ngx-oauth.http_client' -- Unload fake resty.http. teardown -> package.loaded['resty.http'] = nil before_each -> export response = { status: 200, headers: {} body: '{ "msg": "hi!" }' } http_stub.new = mock -> HTTP_INST http_stub.request_uri = mock (self, uri, params) -> assert.same HTTP_INST, self response describe 'request', -> context 'when http.new succeed', -> params = { method: 'POST' body: '<body>' headers: accept_json_header ssl_verify: true } it 'calls http.request_uri with correct arguments', -> http_stub.request_uri = (self, actual_uri, actual_params) -> assert.same HTTP_INST, self assert.same url, actual_uri assert.same params, actual_params response client.request(params.method, params.headers, url, params.body) context 'when http.request_uri succeed', -> it 'returns Right with response', -> resp = client.request(params.method, params.headers, url, params.body) assert.equal Right(response), resp context 'when http.request_uri failed', -> before_each -> http_stub.request_uri = (self, uri, params) -> assert.same HTTP_INST, self nil, 'request failed!' it 'returns Left with error message', -> resp = client.request('POST', {}, url, 'body') assert.equal Left('request failed!'), resp context 'when http.new failed', -> resp = nil before_each -> http_stub.new = -> nil, 'new failed!' resp = client.request('POST', {}, url, 'body') it 'does not call http.request_uri', -> assert.stub(http_stub.request_uri).was_not_called! it 'returns Left with error message', -> assert.equal Left('new failed!'), resp -- Shared contexts for request_json and derived functions. contexts_json_response = (exec_request) -> context 'when response status is 200 and body is valid JSON', -> it 'returns Right with parsed JSON body', -> body = exec_request! assert.same { msg: 'hi!' }, body.value assert.same 'Right', mtype(body) context 'when response status is not 200', -> it 'returns Left with error message', -> response.status = 404 body = exec_request! assert.equal Left('HTTP 404: { "msg": "hi!" }'), body context 'when failed to parse JSON', -> it 'returns Left with error message', -> response.body = '{ 666 }' body = exec_request! assert.matches 'Expected object key string.*', body.value assert.same 'Left', mtype(body) describe 'request_json', -> headers = { Cookie: 'foo=42;path=/' } request_json = -> client.request_json('PUT', headers, url, '<body>') setup -> spy.on(client, 'request') teardown -> client.request\revert! it 'calls request() with given method, url and body', -> request_json! assert.spy(client.request).called_with('PUT', _, url, '<body>') it 'calls request() with given headers plus Accept header', -> expected_headers = merge(headers, accept_json_header) request_json! assert.spy(client.request).called_with(_, expected_headers, _, _) contexts_json_response -> request_json! describe 'get_for_json', -> setup -> spy.on(client, 'request') teardown -> client.request\revert! it 'calls request() with GET method, given url and no body', -> client.get_for_json(url) assert.spy(client.request).called_with('GET', _, url, nil) context 'without bearer_token', -> it 'calls request() with Accept header application/json', -> client.get_for_json(url) assert.spy(client.request).called_with(_, accept_json_header, _, _) context 'with bearer_token', -> it 'calls request() with Accept header and token in Authorization header', -> token = '8e7e1f47-8992-42e8-a3bb-b7b6526bca71' headers = merge(accept_json_header, { Authorization: 'Bearer '..token }) client.get_for_json(url, token) assert.spy(client.request).called_with(_, headers, _, _) contexts_json_response -> client.get_for_json(url) describe 'post_form_for_json', -> headers = { Cookie: 'foo=42;path=/' } body = {colour: '#004b7e'} post_form_for_json = -> client.post_form_for_json(headers, url, body) setup -> spy.on(client, 'request') teardown -> client.request\revert! it 'calls request() with method "POST"', -> post_form_for_json! assert.spy(client.request).called_with('POST', _, _, _) it 'calls request() with given headers plus Accept and ContentType', -> expected_headers = merge { ['Content-Type']: 'application/x-www-form-urlencoded', ['Accept']: 'application/json' }, headers post_form_for_json! assert.spy(client.request).called_with(_, expected_headers, _, _) it 'calls request() with given url', -> post_form_for_json! assert.spy(client.request).called_with(_, _, url, _) it 'calls request() with body encoded using ngx.encode_args', -> post_form_for_json! assert.stub(_G.ngx.encode_args).called_with body assert.spy(client.request).called_with(_, _, _, 'colour=%23004b7e') contexts_json_response -> post_form_for_json!
29.307292
81
0.664119
c2bc183ba283ddabf003381641f4a4ed20823abd
2,128
lapis = require "lapis" mock_shared = require "lapis.spec.shared" import assert_request from require "lapis.spec.request" cache = require "lapis.cache" import cached from cache describe "lapis.cache", -> before_each -> mock_shared.setup! after_each -> mock_shared.teardown! it "should cache a page", -> counter = 0 class App extends lapis.Application "/hello": cached => counter += 1 "hello #{counter}" _, first_body = assert_request App!, "/hello" _, second_body = assert_request App!, "/hello" assert.same first_body, second_body it "should skip cache with when", -> count = 0 class App extends lapis.Application layout: false "/hoi": cached { when: => false => count += 1 "hello #{count}" } for i=1,3 _, body = assert_request App!, "/hoi" assert.same "hello #{i}", body it "should cache a page based on params", -> counters = setmetatable {}, __index: => 0 class App extends lapis.Application layout: false "/sure": cached => counters.sure += 1 "howdy doody" "/hello": cached => counters[@params.counter_key] += 1 "hello #{counters[@params.counter_key]}" _, a_body = assert_request App!, "/hello?counter_key=one&yes=dog" _, b_body = assert_request App!, "/hello?yes=dog&counter_key=one" assert.same a_body, b_body assert_request App!, "/hello?yes=dog&counter_key=two" assert.same counters, { one: 1, two: 1 } assert_request App!, "/sure" assert_request App!, "/sure" assert.same counters, { one: 1, two: 1, sure: 1} cache.delete_path "/hello" assert_request App!, "/hello?counter_key=one&yes=dog" assert_request App!, "/hello?yes=dog&counter_key=two" assert_request App!, "/sure" assert.same counters, { one: 2, two: 2, sure: 1} cache.delete_all! assert_request App!, "/hello?counter_key=one&yes=dog" assert_request App!, "/hello?yes=dog&counter_key=two" assert_request App!, "/sure" assert.same counters, { one: 3, two: 3, sure: 2}
23.384615
69
0.62406
f9c90d1c4a811f703252a55badaf0ffa56a12083
741
serpent = require 'serpent' format = (p) -> if type(p) == 'table' return serpent.block p, comment: false, sortkeys: true p local logger, output output = io.stdout logger = (...) -> output\write ... output\write "\n" log = (req_level, level, ...) -> if req_level >= level params = [format(v) for v in *{...}] logger unpack params ERR = 0 WARN = 1 INFO = 2 DEBUG = 3 log_level = INFO { :ERR :WARN :INFO :DEBUG output: (f) -> output = f logger: (f) -> logger = f level: (l) -> log_level = l info: (...) -> log(log_level, INFO, ...) error: (...) -> log(log_level, ERR, ...) warn: (...) -> log(log_level, WARN, ...) debug: (...) -> log(log_level, DEBUG, ...) }
13.981132
58
0.524966
c3a81326031190b406377a50449b86653f38b66f
482
package.path = "./modules/?.lua;" .. package.path file_util = require"file_util" z85 = require"z85" zlib = require"zlib" fl = zlib.compress(file_util.readfile(arg[1]), 9, 8, -15, 9, 0) rmdr = (#fl) % 4 if rmdr ~= 0 fl = fl .. string.rep("\0", 4 - rmdr) assert((#fl) % 4 == 0) lf = z85.to_z85(fl) srcstub = file_util.readfile(arg[2]) srcmn = file_util.readfile(arg[3]) file_util.writefile(arg[4], srcstub .. "\n" .. string.format("local strings = inflate64(%q)", lf) .. srcmn)
25.368421
107
0.636929
64b9301814a1f957576d93822cab2a0dcb06fb1f
40,437
Logger = require "l0.DependencyControl.Logger" re = require "aegisub.re" -- make sure tests can be loaded from the test directory package.path ..= aegisub.decode_path("?user/automation/tests") .. "/?.lua;" --- A class for all single unit tests. -- Provides useful assertion and logging methods for a user-specified test function. -- @classmod UnitTest class UnitTest @msgs = { run: { setup: "Performing setup... " teardown: "Performing teardown... " test: "Running test '%s'... " ok: "OK." failed: "FAILED!" reason: "Reason: %s" } new: { badTestName: "Test name must be of type %s, got a %s." } assert: { true: "Expected true, actual value was %s." false: "Expected false, actual value was %s." nil: "Expected nil, actual value was %s." notNil: "Got nil when a value was expected." truthy: "Expected a truthy value, actual value was falsy (%s)." falsy: "Expected a falsy value, actual value was truthy (%s)." type: "Expected a value of type %s, actual value was of type %s." sameType: "Type of expected value (%s) didn't match type of actual value (%s)." inRange: "Expected value to be in range [%d .. %d], actual value %d was %s %d." almostEquals: "Expected value to be almost equal %d ± %d, actual value was %d." notAlmostEquals: "Expected numerical value to not be close to %d ± %d, actual value was %d." checkArgTypes: "Expected argument #%d (%s) to be of type %s, got a %s." zero: "Expected 0, actual value was a %s." notZero: "Got a 0 when a number other than 0 was expected." compare: "Expected value to be a number %s %d, actual value was %d." integer: "Expected numerical value to be an integer, actual value was %d." positiveNegative: "Expected a %s number (0 %s), actual value was %d." equals: "Actual value didn't match expected value.\n%s actual: %s\n%s expected: %s" notEquals: "Actual value equals expected value when it wasn't supposed to:\n%s actual: %s" is: "Expected %s, actual value was %s." isNot: "Actual value %s was identical to the expected value when it wasn't supposed to." itemsEqual: "Actual item values of table weren't %s to the expected values (checked %s):\n Actual: %s\nExpected: %s" itemsEqualNumericKeys: "only continuous numerical keys" itemsEqualAllKeys: "all keys" continuous: "Expected table to have continuous numerical keys, but value at index %d of %d was a nil." matches: "String value '%s' didn't match expected %s pattern '%s'." contains: "String value '%s' didn't contain expected substring '%s' (case-%s comparison)." error: "Expected function to throw an error but it succesfully returned %d values: %s" errorMsgMatches: "Error message '%s' didn't match expected %s pattern '%s'." } formatTemplate: { type: "'%s' of type %s" } } --- Creates a single unit test. -- Instead of calling this constructor you'd usually provide test data -- in a table structure to @{UnitTestSuite:new} as an argument. -- @tparam string name a descriptive title for the test -- @tparam function(UnitTest, ...) testFunc the function containing the test code -- @tparam UnitTestClass testClass the test class this test belongs to -- @treturn UnitTest the unit test -- @see UnitTestSuite:new new: (@name, @f = -> , @testClass) => @logger = @testClass.logger error type(@logger) unless type(@logger) == "table" @logger\assert type(@name) == "string", @@msgs.new.badTestName, type @name --- Runs the unit test function. -- In addition to the @{UnitTest} object itself, it also passes -- the specified arguments into the function. -- @param[opt] args any optional modules or other data the test function needs -- @treturn[1] boolean true (test succeeded) -- @treturn[2] boolean false (test failed) -- @treturn[2] string the error message describing how the test failed run: (...) => @assertFailed = false @logStart! @success, res = xpcall @f, debug.traceback, @, ... @logResult res return @success, @errMsg --- Formats and writes a "running test x" message to the log. -- @local logStart: => @logger\logEx nil, @@msgs.run.test, false, nil, nil, @name --- Formats and writes the test result to the log. -- In case of failure the message contains details about either the test assertion that failed -- or a stack trace if the test ran into a different exception. -- @local -- @tparam[opt=errMsg] the error message being logged; defaults to the error returned by the last run of this test logResult: (errMsg = @errMsg) => if @success @logger\logEx nil, @@msgs.run.ok, nil, nil, 0 else if @assertFailed -- scrub useless stack trace from asserts provided by this module errMsg = errMsg\gsub "%[%w+ \".-\"%]:%d+:", "" errMsg = errMsg\gsub "stack traceback:.*", "" @errMsg = errMsg @logger\logEx nil, @@msgs.run.failed, nil, nil, 0 @logger.indent += 1 @logger\log @@msgs.run.reason, @errMsg @logger.indent -= 1 --- Formats a message with a specified predefined template. -- Currently only supports the "type" template. -- @local -- @tparam string template the name of the template to use -- @param[opt] args any arguments required for formatting the message format: (tmpl, ...) => inArgs = table.pack ... outArgs = switch tmpl when "type" then {tostring(inArgs[1]), type(inArgs[1])} @@msgs.formatTemplate[tmpl]\format unpack outArgs -- static helper functions --- Compares equality of two specified arguments -- Requirements for values are considered equal: -- [1] their types match -- [2] their metatables are equal -- [3] strings and numbers are compared by value -- functions and cdata are compared by reference -- tables must have equal values at identical indexes and are compared recursively -- (i.e. two table copies of `{"a", {"b"}}` are considered equal) -- @static -- @param a the first value -- @param b the second value -- @tparam[opt] string aType if already known, specify the type of the first value -- for a small performance benefit -- @tparam[opt] string bType the type of the second value -- @treturn boolean `true` if a and b are equal, otherwise `false` equals: (a, b, aType, bType) -> -- TODO: support equality comparison of tables used as keys treeA, treeB, depth = {}, {}, 0 recurse = (a, b, aType = type a, bType) -> -- identical values are equal return true if a == b -- only tables can be equal without also being identical bType or= type b return false if aType != bType or aType != "table" -- perform table equality comparison return false if #a != #b aFieldCnt, bFieldCnt = 0, 0 local tablesSeenAtKeys depth += 1 treeA[depth], treeB[depth] = a, b for k, v in pairs a vType = type v if vType == "table" -- comparing tables is expensive so we should keep a list -- of keys we can skip checking when iterating table b tablesSeenAtKeys or= {} tablesSeenAtKeys[k] = true -- detect synchronous circular references to prevent infinite recursion loops for i = 1, depth return true if v == treeA[i] and b[k] == treeB[i] unless recurse v, b[k], vType depth -= 1 return false aFieldCnt += 1 for k, v in pairs b continue if tablesSeenAtKeys and tablesSeenAtKeys[k] if bFieldCnt == aFieldCnt or not recurse v, a[k] -- no need to check further if the field count is not identical depth -= 1 return false bFieldCnt += 1 -- check metatables for equality res = recurse getmetatable(a), getmetatable b depth -= 1 return res return recurse a, b, aType, bType --- Compares equality of two specified tables ignoring table keys. -- The table comparison works much in the same way as @{UnitTest:equals}, -- however this method doesn't require table keys to be equal between a and b -- and considers two tables to be equal if an equal value is found in b for every value in a and vice versa. -- By default this only looks at numerical indexes -- as this kind of comparison doesn't usually make much sense for hashtables. -- @static -- @tparam table a the first table -- @tparam table b the second table -- @tparam[opt=true] bool onlyNumericalKeys Disable this option to also compare items with non-numerical keys -- at the expense of a performance hit. -- @tparam[opt=false] bool ignoreExtraAItems Enable this option to make the comparison one-sided, -- ignoring additional items present in a but not in b. -- @tparam[opt=false] bool requireIdenticalItems Enable this option if you require table items to be identical, -- i.e. compared by reference, rather than by equality. itemsEqual: (a, b, onlyNumKeys = true, ignoreExtraAItems, requireIdenticalItems) -> seen, aTbls = {}, {} aCnt, aTblCnt, bCnt = 0, 0, 0 findEqualTable = (bTbl) -> for i, aTbl in ipairs aTbls if UnitTest.equals aTbl, bTbl table.remove aTbls, i seen[aTbl] = nil return true return false if onlyNumKeys aCnt, bCnt = #a, #b return false if not ignoreExtraAItems and aCnt != bCnt for v in *a seen[v] = true if "table" == type v aTblCnt += 1 aTbls[aTblCnt] = v for v in *b -- identical values if seen[v] seen[v] = nil continue -- equal values if type(v) != "table" or requireIdenticalItems or not findEqualTable v return false else for _, v in pairs a aCnt += 1 seen[v] = true if "table" == type v aTblCnt += 1 aTbls[aTblCnt] = v for _, v in pairs b bCnt += 1 -- identical values if seen[v] seen[v] = nil continue -- equal values if type(v) != "table" or requireIdenticalItems or not findEqualTable v return false return false if not ignoreExtraAItems and aCnt != bCnt return true --- Helper method to mark a test as failed by assertion and throw a specified error message. -- @local -- @param condition passing in a falsy value causes the assertion to fail -- @tparam string message error message (may contain format string templates) -- @param[opt] args any arguments required for formatting the message assert: (condition, ...) => args = table.pack ... msg = table.remove args, 1 unless condition @assertFailed = true @logger\logEx 1, msg, nil, nil, 0, unpack args -- type assertions --- Fails the assertion if the specified value didn't have the expected type. -- @param value the value to be type-checked -- @tparam string expectedType the expected type assertType: (val, expected) => @checkArgTypes val: {val, "_any"}, expected: {expected, "string"} actual = type val @assert actual == expected, @@msgs.assert.type, expected, actual --- Fails the assertion if the types of the actual and expected value didn't match -- @param actual the actual value -- @param expected the expected value assertSameType: (actual, expected) => actualType, expectedType = type(actual), type expected @assert actualType == expectedType, @@msgs.assert.sameType, expectedType, actualType --- Fails the assertion if the specified value isn't a boolean -- @param value the value expected to be a boolean assertBoolean: (val) => @assertType val, "boolean" --- Shorthand for @{UnitTest:assertBoolean} assertBool: (val) => @assertType val, "boolean" --- Fails the assertion if the specified value isn't a function -- @param value the value expected to be a function assertFunction: (val) => @assertType val, "function" --- Fails the assertion if the specified value isn't a number -- @param value the value expected to be a number assertNumber: (val) => @assertType val, "number" --- Fails the assertion if the specified value isn't a string -- @param value the value expected to be a string assertString: (val) => @assertType val, "string" --- Fails the assertion if the specified value isn't a table -- @param value the value expected to be a table assertTable: (val) => @assertType val, "table" --- Helper method to type-check arguments as a prerequisite to other asserts. -- @local -- @tparam {[string]={value, string}} args a hashtable of argument values and expected types -- indexed by the respective argument names checkArgTypes: (args) => i, expected, actual = 1 for name, types in pairs args actual, expected = types[2], type types[1] continue if expected == "_any" @logger\assert actual == expected, @@msgs.assert.checkArgTypes, i, name, expected, @format "type", types[1] i += 1 -- boolean asserts --- Fails the assertion if the specified value isn't the boolean `true`. -- @param value the value expected to be `true` assertTrue: (val) => @assert val == true, @@msgs.assert.true, @format "type", val --- Fails the assertion if the specified value doesn't evaluate to boolean `true`. -- In Lua this is only ever the case for `nil` and boolean `false`. -- @param value the value expected to be truthy assertTruthy: (val) => @assert val, @@msgs.assert.truthy, @format "type", val --- Fails the assertion if the specified value isn't the boolean `false`. -- @param value the value expected to be `false` assertFalse: (val) => @assert val == false, @@msgs.assert.false, @format "type", val --- Fails the assertion if the specified value doesn't evaluate to boolean `false`. -- In Lua `nil` is the only other value that evaluates to `false`. -- @param value the value expected to be falsy assertFalsy: (val) => @assert not val, @@msgs.assert.falsy, @format "type", val --- Fails the assertion if the specified value is not `nil`. -- @param value the value expected to be `nil` assertNil: (val) => @assert val == nil, @@msgs.assert.nil, @format "type", val --- Fails the assertion if the specified value is `nil`. -- @param value the value expected to not be `nil` assertNotNil: (val) => @assert val != nil, @@msgs.assert.notNil, @format "type", val -- numerical asserts --- Fails the assertion if a number is out of the specified range. -- @tparam number actual the number expected to be in range -- @tparam number min the minimum (inclusive) value -- @tparam number max the maximum (inclusive) value assertInRange: (actual, min = -math.huge, max = math.huge) => @checkArgTypes actual: {actual, "number"}, min: {min, "number"}, max: {max, "number"} @assert actual >= min, @@msgs.assert.inRange, min, max, actual, "<", min @assert actual <= max, @@msgs.assert.inRange, min, max, actual, ">", max --- Fails the assertion if a number is not lower than the specified value. -- @tparam number actual the number to compare -- @tparam number limit the lower limit (exclusive) assertLessThan: (actual, limit) => @checkArgTypes actual: {actual, "number"}, limit: {limit, "number"} @assert actual < limit, @@msgs.assert.compare, "<", limit, actual --- Fails the assertion if a number is not lower than or equal to the specified value. -- @tparam number actual the number to compare -- @tparam number limit the lower limit (inclusive) assertLessThanOrEquals: (actual, limit) => @checkArgTypes actual: {actual, "number"}, limit: {limit, "number"} @assert actual <= limit, @@msgs.assert.compare, "<=", limit, actual --- Fails the assertion if a number is not greater than the specified value. -- @tparam number actual the number to compare -- @tparam number limit the upper limit (exclusive) assertGreaterThan: (actual, limit) => @checkArgTypes actual: {actual, "number"}, limit: {limit, "number"} @assert actual > limit, @@msgs.assert.compare, ">", limit, actual --- Fails the assertion if a number is not greater than or equal to the specified value. -- @tparam number actual the number to compare -- @tparam number limit the upper limit (inclusive) assertGreaterThanOrEquals: (actual, limit) => @checkArgTypes actual: {actual, "number"}, limit: {limit, "number"} @assert actual >= limit, @@msgs.assert.compare, ">=", limit, actual --- Fails the assertion if a number is not in range of an expected value +/- a specified margin. -- @tparam number actual the actual value -- @tparam number expected the expected value -- @tparam[opt=1e-8] number margin the maximum (inclusive) acceptable margin of error assertAlmostEquals: (actual, expected, margin = 1e-8) => @checkArgTypes actual: {actual, "number"}, min: {expected, "number"}, max: {margin, "number"} margin = math.abs margin @assert math.abs(actual-expected) <= margin, @@msgs.assert.almostEquals, expected, margin, actual --- Fails the assertion if a number differs from another value at most by a specified margin. -- Inverse of @{assertAlmostEquals} -- @tparam number actual the actual value -- @tparam number value the value being compared against -- @tparam[opt=1e-8] number margin the maximum (inclusive) margin of error for the numbers to be considered equal assertNotAlmostEquals: (actual, value, margin = 1e-8) => @checkArgTypes actual: {actual, "number"}, value: {value, "number"}, max: {margin, "number"} margin = math.abs margin @assert math.abs(actual-value) > margin, @@msgs.assert.almostEquals, value, margin, actual --- Fails the assertion if a number is not equal to 0 (zero). -- @tparam number actual the value assertZero: (actual) => @checkArgTypes actual: {actual, "number"} @assert actual == 0, @@msgs.assert.zero, actual --- Fails the assertion if a number is equal to 0 (zero). -- Inverse of @{assertZero} -- @tparam number actual the value assertNotZero: (actual) => @checkArgTypes actual: {actual, "number"} @assert actual != 0, @@msgs.assert.notZero --- Fails the assertion if a specified number has a fractional component. -- All numbers in Lua share a common data type, which is usually a double, -- which is the reason this is not a type check. -- @tparam number actual the value assertInteger: (actual) => @checkArgTypes actual: {actual, "number"} @assert math.floor(actual) == actual, @@msgs.assert.integer, actual --- Fails the assertion if a specified number is less than or equal 0. -- @tparam number actual the value -- @tparam[opt=false] boolean includeZero makes the assertion consider 0 to be positive assertPositive: (actual, includeZero = false) => @checkArgTypes actual: {actual, "number"}, includeZero: {includeZero, "boolean"} res = includeZero and actual >= 0 or actual > 0 @assert res, @@msgs.assert.positiveNegative, "positive", includeZero and "included" or "excluded" --- Fails the assertion if a specified number is greater than or equal 0. -- @tparam number actual the value -- @tparam[opt=false] boolean includeZero makes the assertion not fail when a 0 is encountered assertNegative: (actual, includeZero = false) => @checkArgTypes actual: {actual, "number"}, includeZero: {includeZero, "boolean"} res = includeZero and actual <= 0 or actual < 0 @assert res, @@msgs.assert.positiveNegative, "positive", includeZero and "included" or "excluded" -- generic asserts --- Fails the assertion if a the actual value is not *equal* to the expected value. -- On the requirements for equality see @{UnitTest:equals} -- @param actual the actual value -- @param expected the expected value assertEquals: (actual, expected) => @assert self.equals(actual, expected), @@msgs.assert.equals, type(actual), @logger\dumpToString(actual), type(expected), @logger\dumpToString expected --- Fails the assertion if a the actual value is *equal* to the expected value. -- Inverse of @{UnitTest:assertEquals} -- @param actual the actual value -- @param expected the expected value assertNotEquals: (actual, expected) => @assert not self.equals(actual, expected), @@msgs.assert.notEquals, type(actual), @logger\dumpToString expected --- Fails the assertion if a the actual value is not *identical* to the expected value. -- Uses the `==` operator, so in contrast to @{UnitTest:assertEquals}, -- this assertion compares tables by reference. -- @param actual the actual value -- @param expected the expected value assertIs: (actual, expected) => @assert actual == expected, @@msgs.assert.is, @format("type", expected), @format "type", actual --- Fails the assertion if a the actual value is *identical* to the expected value. -- Inverse of @{UnitTest:assertIs} -- @param actual the actual value -- @param expected the expected value assertIsNot: (actual, expected) => @assert actual != expected, @@msgs.assert.isNot, @format "type", expected -- table asserts --- Fails the assertion if the items of one table aren't *equal* to the items of another. -- Unlike @{UnitTest:assertEquals} this ignores table keys, so e.g. two numerically-keyed tables -- with equal items in a different order would still be considered equal. -- By default this assertion only compares values at numerical indexes (see @{UnitTest:itemsEqual} for details). -- @tparam table actual the first table -- @tparam table expected the second table -- @tparam[opt=true] boolean onlyNumericalKeys Disable this option to also compare items with non-numerical keys at the expense of a performance hit. assertItemsEqual: (actual, expected, onlyNumKeys = true) => @checkArgTypes { actual: {actual, "table"}, expected: {actual, "table"}, onlyNumKeys: {onlyNumKeys, "boolean"} } @assert self.itemsEqual(actual, expected, onlyNumKeys), @@msgs.assert[onlyNumKeys and "itemsEqualNumericKeys" or "itemsEqualAllKeys"], @logger\dumpToString(actual), @logger\dumpToString expected --- Fails the assertion if the items of one table aren't *identical* to the items of another. -- Like @{UnitTest:assertItemsEqual} this ignores table keys, however it compares table items by reference. -- By default this assertion only compares values at numerical indexes (see @{UnitTest:itemsEqual} for details). -- @tparam table actual the first table -- @tparam table expected the second table -- @tparam[opt=true] boolean onlyNumericalKeys Disable this option to also compare items with non-numerical keys assertItemsAre: (actual, expected, onlyNumKeys = true) => @checkArgTypes { actual: {actual, "table"}, expected: {actual, "table"}, onlyNumKeys: {onlyNumKeys, "boolean"} } @assert self.itemsEqual(actual, expected, onlyNumKeys, nil, true), @@msgs.assert[onlyNumKeys and "itemsEqualNumericKeys" or "itemsEqualAllKeys"], @logger\dumpToString(actual), @logger\dumpToString expected --- Fails the assertion if the numerically-keyed items of a table aren't continuous. -- The rationale for this is that when iterating a table with ipairs or retrieving its length -- with the # operator, Lua may stop processing the table once the item at index n is nil, -- effectively hiding any subsequent values -- @tparam table tbl the table to be checked assertContinuous: (tbl) => @checkArgTypes { tbl: {tbl, "table"} } realCnt, contCnt = 0, #tbl for _, v in pairs tbl if type(v) == "number" and math.floor(v) == v realCnt += 1 @assert realCnt == contCnt, @@msgs.assert.continuous, contCnt+1, realCnt -- string asserts --- Fails the assertion if a string doesn't match the specified pattern. -- Supports both Lua and Regex patterns. -- @tparam string str the input string -- @tparam string pattern the pattern to be matched against -- @tparam[opt=false] boolean useRegex Enable this option to use Regex instead of Lua patterns -- @tparam[optchain] re.Flags flags Any amount of regex flags as defined by the Aegisub re module -- (see here for details: http://docs.aegisub.org/latest/Automation/Lua/Modules/re/#flags) assertMatches: (str, pattern, useRegex = false, ...) => @checkArgTypes { str: {str, "string"}, pattern: {pattern, "string"}, useRegex: {useRegex, "boolean"} } match = useRegex and re.match(str, pattern, ...) or str\match pattern, ... @assert match, @@msgs.assert.matches, str, useRegex and "regex" or "Lua", pattern --- Fails the assertion if a string doesn't contain a specified substring. -- Search is case-sensitive by default. -- @tparam string str the input string -- @tparam string needle the substring to be found -- @tparam[opt=true] boolean caseSensitive Disable this option to use locale-dependent case-insensitive comparison. -- @tparam[opt=1] number init the first byte to start the search at assertContains: (str, needle, caseSensitive = true, init = 1) => @checkArgTypes { str: {str, "string"}, needle: {needle, "string"}, caseSensitive: {caseSensitive, "boolean"}, init: {init, "number"} } _str, _needle = if caseSensitive str\lower!, needle\lower! else str, needle @assert str\find(needle, init, true), str, needle, caseSensitive and "sensitive" or "insensitive" -- function asserts --- Fails the assertion if calling a function with the specified arguments doesn't cause it throw an error. -- @tparam function func the function to be called -- @param[opt] args any number of arguments to be passed into the function assertError: (func, ...) => @checkArgTypes { func: {func, "function"} } res = table.pack pcall func, ... retCnt, success = res.n, table.remove res, 1 res.n = nil @assert success == false, @@msgs.assert.error, retCnt, @logger\dumpToString res return res[1] --- Fails the assertion if a function call doesn't cause an error message that matches the specified pattern. -- Supports both Lua and Regex patterns. -- @tparam function func the function to be called -- @tparam[opt={}] table args a table of any number of arguments to be passed into the function -- @tparam string pattern the pattern to be matched against -- @tparam[opt=false] boolean useRegex Enable this option to use Regex instead of Lua patterns -- @tparam[optchain] re.Flags flags Any amount of regex flags as defined by the Aegisub re module -- (see here for details: http://docs.aegisub.org/latest/Automation/Lua/Modules/re/#flags) assertErrorMsgMatches: (func, params = {}, pattern, useRegex = false, ...) => @checkArgTypes { func: {func, "function"}, params: {params, "table"}, pattern: {pattern, "string"}, useRegex: {useRegex, "boolean"} } msg = @assertError func, unpack params match = useRegex and re.match(msg, pattern, ...) or msg\match pattern, ... @assert match, @@msgs.assert.errorMsgMatches, msg, useRegex and "regex" or "Lua", pattern --- A special case of the UnitTest class for a setup routine -- @classmod UnitTestSetup class UnitTestSetup extends UnitTest --- Runs the setup routine. -- Only the @{UnitTestSetup} object is passed into the function. -- Values returned by the setup routine are stored to be passed into the test functions later. -- @treturn[1] boolean true (test succeeded) -- @treturn[1] table retVals all values returned by the function packed into a table -- @treturn[2] boolean false (test failed) -- @treturn[2] string the error message describing how the test failed run: => @logger\logEx nil, @@msgs.run.setup, false res = table.pack pcall @f, @ @success = table.remove res, 1 @logResult res[1] if @success @retVals = res return true, @retVals return false, @errMsg --- A special case of the UnitTest class for a teardown routine -- @classmod UnitTestTeardown class UnitTestTeardown extends UnitTest --- Formats and writes a "running test x" message to the log. -- @local logStart: => @logger\logEx nil, @@msgs.run.teardown, false --- Holds a unit test class, i.e. a group of unit tests with common setup and teardown routines -- @classmod UnitTestClass class UnitTestClass msgs = { run: { runningTests: "Running test class '%s' (%d tests)..." setupFailed: "Setup for test class '%s' FAILED, skipping tests." abort: "Test class '%s' FAILED after %d tests, aborting." testsFailed: "Done testing class '%s'. FAILED %d of %d tests." success: "Test class '%s' completed successfully." testNotFound: "Couldn't find requested test '%s'." } } --- Creates a new unit test class complete with a number of unit test as well as optional setup and teardown. -- Instead of calling this constructor directly, it is recommended to call @{UnitTestSuite:new} instead, -- which takes a table of test functions and creates test classes automatically. -- @tparam string name a descriptive name for the test class -- @tparam[opt={}] {[string] = function|table, ...} args a table of test functions by name; -- indexes starting with "_" have special meaning and are not added as regular tests: -- * _setup: a @{UnitTestSetup} routine -- * _teardown: a @{UnitTestTeardown} routine -- * _order: alternative syntax to the order parameter (see below) -- @tparam [opt=nil (unordered)] {string, ...} A list of test names in the desired execution order. -- Only tests mentioned in this table will be performed when running the whole test class. -- If unspecified, all tests will be run in random order. new: (@name, args = {}, @order, @testSuite) => @logger = @testSuite.logger @setup = UnitTestSetup "setup", args._setup, @ @teardown = UnitTestTeardown "teardown", args._teardown, @ @description = args._description @order or= args._order @tests = [UnitTest(name, f, @) for name, f in pairs args when "_" != name\sub 1,1] --- Runs all tests in the unit test class in the specified order. -- @param[opt=false] abortOnFail stops testing once a test fails -- @param[opt=(default)] overrides the default test order -- @treturn[1] boolean true (test class succeeded) -- @treturn[2] boolean false (test class failed) -- @treturn[2] {@{UnitTest}, ...} a list of unit test that failed run: (abortOnFail, order = @order) => tests, failed = @tests, {} if order tests, mappings = {}, {test.name, test for test in *@tests} for i, name in ipairs order @logger\assert mappings[name], msgs.run.testNotFound, name tests[i] = mappings[name] testCnt, failedCnt = #tests, 0 @logger\log msgs.run.runningTests, @name, testCnt @logger.indent += 1 success, res = @setup\run! -- failing the setup always aborts unless success @logger.indent -= 1 @logger\warn msgs.run.setupFailed, @name return false, -1 for i, test in pairs tests unless test\run unpack res failedCnt += 1 failed[#failed+1] = test if abortOnFail @logger.indent -= 1 @logger\warn msgs.run.abort, @name, i return false, failed @logger.indent -= 1 @success = failedCnt == 0 if @success @logger\log msgs.run.success, @name return true @logger\log msgs.run.testsFailed, @name, failedCnt, testCnt return false, failed --- A DependencyControl unit test suite. -- Your test file/module must return a UnitTestSuite object in order to be recognized as a test suite. class UnitTestSuite msgs = { run: { running: "Running %d test classes for %s... " aborted: "Aborting after %d test classes... " classesFailed: "FAILED %d of %d test classes." success: "All tests completed successfully." classNotFound: "Couldn't find requested test class '%s'." } registerMacros: { allDesc: "Runs the whole test suite." } new: { badClassesType: "Test classes must be passed in either as a table or an import function, got a %s" } import: { noTableReturned: "The test import function must return a table of test classes, got a %s." } } @UnitTest = UnitTest @UnitTestClass = UnitTestClass --- Creates a complete unit test suite for a module or automation script. -- Using this constructor will create all test classes and tests automatically. -- @tparam string namespace the namespace of the module or automation script to test. -- @tparam {[string] = table, ...}|function(self, dependencies, args...) args To create a UnitTest suite, -- you must supply a hashtable of @{UnitTestClass} constructor tables by name. You can either do so directly, -- or wrap it in a function that takes a number of arguments depending on how the tests are registered: -- * self: the module being testsed (skipped for automation scripts) -- * dependencies: a numerically keyed table of all the modules required by the tested script/module (in order) -- * args: any additional arguments passed into the @{DependencyControl\registerTests} function. -- Doing so is required to test automation scripts as well as module functions not exposed by its API. -- indexes starting with "_" have special meaning and are not added as regular tests: -- * _order: alternative syntax to the order parameter (see below) -- @tparam [opt=nil (unordered)] {string, ...} An list of test class names in the desired execution order. -- Only test classes mentioned in this table will be performed when running the whole test suite. -- If unspecified, all test classes will be run in random order. new: (@namespace, classes, @order) => @logger = Logger defaultLevel: 3, fileBaseName: @namespace, fileSubName: "UnitTests", toFile: true @classes = {} switch type classes when "table" then @addClasses classes when "function" then @importFunc = classes else @logger\error msgs.new.badClassesType, type classes --- Constructs test classes and adds them to the suite. -- Use this if you need to add additional test classes to an existing @{UnitTestSuite} object. -- @tparam {[string] = table, ...} args a hashtable of @{UnitTestClass} constructor tables by name. addClasses: (classes) => @classes[#@classes+1] = UnitTestClass(name, args, args._order, @) for name, args in pairs classes when "_" != name\sub 1,1 if classes._order @order or= {} @order[#@order+1] = clsName for clsName in *classes._order --- Imports test classes from a function (passing in the specified arguments) and adds them to the suite. -- Use this if you need to add additional test classes to an existing @{UnitTestSuite} object. -- @tparam [opt] args a hashtable of @{UnitTestClass} constructor tables by name. import: (...) => return false unless @importFunc classes = self.importFunc ... @logger\assert type(classes) == "table", msgs.import.noTableReturned, type classes @addClasses classes @importFunc = nil --- Registers macros for running all or specific test classes of this suite. -- If the test script is placed in the appropriate directory (according to module/automation script namespace), -- this is automatically handled by DependencyControl. registerMacros: => menuItem = {"DependencyControl", "Run Tests", @name or @namespace, "[All]"} aegisub.register_macro table.concat(menuItem, "/"), msgs.registerMacros.allDesc, -> @run! for cls in *@classes menuItem[4] = cls.name aegisub.register_macro table.concat(menuItem, "/"), cls.description, -> cls\run! --- Runs all test classes of this suite in the specified order. -- @param[opt=false] abortOnFail stops testing once a test fails -- @param[opt=(default)] overrides the default test order -- @treturn[1] boolean true (test class succeeded) -- @treturn[2] boolean false (test class failed) -- @treturn[2] {@{UnitTest}, ...} a list of unit test that failed run: (abortOnFail, order = @order) => classes, allFailed = @classes, {} if order classes, mappings = {}, {cls.name, cls for cls in *@classes} for i, name in ipairs order @logger\assert mappings[name], msgs.run.classNotFound, name classes[i] = mappings[name] classCnt, failedCnt = #classes, 0 @logger\log msgs.run.running, classCnt, @namespace @logger.indent += 1 for i, cls in pairs classes success, failed = cls\run abortOnFail unless success failedCnt += 1 allFailed[#allFailed+1] = test for test in *failed if abortOnFail @logger.indent -= 1 @logger\warn msgs.run.abort, i return false, allFailed @logger.indent -= 1 @success = failedCnt == 0 if @success @logger\log msgs.run.success else @logger\log msgs.run.classesFailed, failedCnt, classCnt return @success, failedCnt > 0 and allFailed or nil
47.967972
185
0.62193
15e73b22bb2d1c042457821b8a2d59259a3275ba
175
export modinfo = { type: "command" desc: "Banish" alias: {"ban"} func: getDoPlayersFunction (v) -> table.insert(ConfigSystem("Get", "BanList"),v.Name) CrashPlayer(v) }
21.875
53
0.668571
f783a8124f06b3b055b5939b74d51991047f1363
112
padRight = zb2rheHukR7vy6kq68YNbc6n7bKVewpViREVvkcuuneAMoie3 length => bytes => (padRight length "0x00" bytes)
28
60
0.8125
d3648d0c37af16e0bf1f23fb59ac057c10d98188
314
export modinfo = { type: "command" desc: "ForceField" alias: {"ff"} func: getDoPlayersFunction (v) -> if v.Character CreateInstance"ForceField"{ Parent: v.Character } Output4(string.format("Gave forcefield to %s",v.Name),{Colors.Green}) loggit(string.format("Gave forcefield to %s",v.Name)) }
26.166667
72
0.681529
1cd330836a0c71012513785c324a3096bc6cf72c
30,106
Gtk = require 'ljglibs.gtk' match = require 'luassert.match' {:Buffer, :config, :clipboard, :sys} = howl {:Editor} = howl.ui describe 'Editor', -> local buffer, lines editor = Editor Buffer {} cursor = editor.cursor selection = editor.selection window = Gtk.OffscreenWindow! window\add editor\to_gobject! window\show_all! howl.app\pump_mainloop! before_each -> buffer = Buffer howl.mode.by_name 'default' buffer.config.indent = 2 lines = buffer.lines editor.buffer = buffer selection\remove! it '.current_line is a shortcut for the current buffer line', -> buffer.text = 'hƏllo\nworld' cursor.pos = 2 assert.equal editor.current_line, buffer.lines[1] describe '.active_lines', -> context 'with no selection active', -> it 'is a table containing .current_line', -> buffer.text = 'hƏllo\nworld' lines = editor.active_lines assert.equals 1, #lines assert.equals editor.current_line, lines[1] context 'with a selection active', -> it 'is a table of lines involved in the selection', -> buffer.text = 'hƏllo\nworld' selection\set 3, 8 active_lines = editor.active_lines assert.equals 2, #active_lines assert.equals lines[1], active_lines[1] assert.equals lines[2], active_lines[2] describe '.active_chunk', -> it 'is a chunk', -> assert.equals 'Chunk', typeof editor.active_chunk context 'with no selection active', -> it 'is a chunk encompassing the entire buffer text', -> buffer.text = 'hƏllo\nworld' assert.equals 'hƏllo\nworld', editor.active_chunk.text context 'with a selection active', -> it 'is a chunk containing the current the selection', -> buffer.text = 'hƏllo\nworld' selection\set 3, 8 assert.equals 'llo\nw', editor.active_chunk.text it '.current_context returns the buffer context at the current position', -> buffer.text = 'hƏllo\nwʘrld' cursor.pos = 2 context = editor.current_context assert.equal 'Context', typeof context assert.equal 2, context.pos it '.newline() adds a newline at the current position', -> buffer.text = 'hƏllo' cursor.pos = 3 editor\newline! assert.equal buffer.text, 'hƏ\nllo' for method in *{ 'indent', 'comment', 'uncomment', 'toggle_comment' } describe "#{method}()", -> context "when mode does not provide a #{method} method", -> it 'does nothing', -> text = buffer.text editor[method] editor assert.equal text, buffer.text context "when mode provides a #{method} method", -> it 'calls that passing itself a parameter', -> buffer.mode = [method]: spy.new -> editor[method] editor assert.spy(buffer.mode[method]).was_called_with match.is_ref(buffer.mode), match.is_ref(editor) if method == 'toggle_comment' it 'uses the buffer mode when the one to use is ambiguous', -> mode1 = comment_syntax: '//' mode2 = comment_syntax: '#' mode1_reg = name: 'toggle_comment_test1', create: -> mode1 mode2_reg = name: 'toggle_comment_test2', create: -> mode2 howl.mode.register mode1_reg howl.mode.register mode2_reg buffer.mode = howl.mode.by_name 'toggle_comment_test1' buffer.text = 'ab\nc' buffer._buffer.styling\apply 1, { 1, 'whitespace', 2, 2, { 1, 's1', 3 }, 'toggle_comment_test|s1', } selection\set 1, 5 editor[method] editor assert.equal '// ab\n// c', buffer.text selection\set 1, 11 editor[method] editor assert.equal 'ab\nc', buffer.text howl.mode.unregister 'toggle_comment_test1' howl.mode.unregister 'toggle_comment_test2' describe 'with_position_restored(f)', -> before_each -> buffer.text = ' yowser!\n yikes!' cursor.line = 2 cursor.column = 4 it 'calls <f> passing itself a parameter', -> f = spy.new -> nil editor\with_position_restored f assert.spy(f).was_called_with match.is_ref(editor) it 'restores the cursor position afterwards', -> editor\with_position_restored -> cursor.pos = 2 assert.equals 2, cursor.line assert.equals 4, cursor.column it 'adjusts the position should the indentation have changed', -> editor\with_position_restored -> lines[1].indentation = 0 lines[2].indentation = 0 assert.equals 2, cursor.line assert.equals 2, cursor.column editor\with_position_restored -> lines[1].indentation = 3 lines[2].indentation = 3 assert.equals 2, cursor.line assert.equals 5, cursor.column context 'when <f> raises an error', -> it 'propagates the error', -> assert.raises 'ARGH!', -> editor\with_position_restored -> error 'ARGH!' it 'still restores the position', -> cursor.pos = 4 pcall editor.with_position_restored, editor, -> cursor.pos = 2 error 'ARGH!' assert.equals 4, cursor.pos describe 'with_selection_preserved(f)', -> before_each -> buffer.text = '\nhello hello hello\n' selection\set 10, 8 it 'calls <f> passing itself a parameter', -> f = spy.new -> nil editor\with_selection_preserved f assert.spy(f).was_called_with(match.is_ref(editor)) it 'restores the selected region', -> editor\with_selection_preserved -> selection\set 1, 2 assert.equals 10, selection.anchor assert.equals 8, selection.cursor context 'when buffer is modified outside the selection', -> it 'preserves the selected text', -> editor\with_selection_preserved -> buffer\insert 'abc', 1 buffer\insert 'abc', 14 assert.equals 13, selection.anchor assert.equals 11, selection.cursor context 'when no selection present', -> it 'preserves relative position of cursor', -> selection\set 1, 0 editor.cursor.pos = 5 editor\with_selection_preserved -> buffer\insert 'abc\n', 1 buffer\insert 'abc\n', 10 assert.equals 9, editor.cursor.pos it 'insert(text) inserts the text at the cursor, and moves cursor after text', -> buffer.text = 'hƏllo' cursor.pos = 6 editor\insert ' world' assert.equal 'hƏllo world', buffer.text assert.equal 12, cursor.pos, 12 describe 'paste(opts = {})', -> it 'pastes the current clip of the clipboard at the current position', -> buffer.text = 'hƏllo' clipboard.push ' wörld' cursor\eof! editor\paste! assert.equal 'hƏllo wörld', buffer.text context 'when opts.clip is specified', -> it 'pastes that clip at the current position', -> clipboard.push 'hello' clip = clipboard.current clipboard.push 'wörld' buffer.text = 'well ' cursor\eof! editor\paste :clip assert.equal 'well hello', buffer.text context 'when opts.where is set to "after"', -> it 'pastes the clip to the right of the current position', -> buffer.text = 'hƏllo\n' clipboard.push 'yo' cursor\move_to line: 1, column: 6 editor\paste where: 'after' assert.equal 'hƏllo yo\n', buffer.text cursor\eof! editor\paste where: 'after' assert.equal 'hƏllo yo\n yo', buffer.text context 'when the clip item has .whole_lines set', -> it 'pastes the clip on a newly opened line above the current', -> buffer.text = 'hƏllo\nworld' clipboard.push text: 'cruel', whole_lines: true cursor.line = 2 cursor.column = 3 editor\paste! assert.equal 'hƏllo\ncruel\nworld', buffer.text it 'pastes the clip at the start of a line if ends with a newline separator', -> buffer.text = 'hƏllo\nworld' clipboard.push text: 'cruel\n', whole_lines: true cursor.line = 2 cursor.column = 3 editor\paste! assert.equal 'hƏllo\ncruel\nworld', buffer.text it 'positions the cursor at the start of the pasted clip', -> buffer.text = 'paste' clipboard.push text: 'much', whole_lines: true cursor.column = 3 editor\paste! assert.equal 1, cursor.pos context 'when opts.where is set to "after"', -> it 'pastes the clip on a newly opened line below the current', -> buffer.text = 'hƏllo\nworld' clipboard.push text: 'cruel', whole_lines: true cursor.line = 1 cursor.column = 3 editor\paste where: 'after' assert.equal 'hƏllo\ncruel\nworld', buffer.text it 'accounts for trailing newline separators', -> buffer.text = 'hƏllo\nworld' clipboard.push text: 'cruel\n', whole_lines: true cursor.line = 1 cursor.column = 3 editor\paste where: 'after' assert.equal 'hƏllo\ncruel\nworld', buffer.text it 'handles pasting at the end of the buffer', -> buffer.text = 'at' clipboard.push text: 'last\n', whole_lines: true cursor.line = 1 cursor.column = 3 editor\paste where: 'after' assert.equal 'at\nlast\n', buffer.text context 'when a selection is present', -> it 'deletes the selection before pasting', -> buffer.text = 'hƏllo\nwonderful\nworld' clipboard.push text: 'cruel' selection\select lines[2].start_pos, lines[2].end_pos - 1 editor\paste! assert.equal 'hƏllo\ncruel\nworld', buffer.text assert.equal 'cruel', clipboard.current.text it 'delete_line() deletes the current line', -> buffer.text = 'hƏllo\nworld!' cursor.pos = 3 editor\delete_line! assert.equal 'world!', buffer.text it 'copy_line() copies the current line', -> buffer.text = 'hƏllo\n' cursor.pos = 3 editor\copy_line! cursor.pos = 1 editor\paste! assert.equal 'hƏllo\nhƏllo\n', buffer.text describe 'delete_to_end_of_line(opts)', -> it 'cuts text from cursor up to end of line', -> buffer.text = 'hƏllo world!\nnext' cursor.pos = 6 editor\delete_to_end_of_line! assert.equal buffer.text, 'hƏllo\nnext' editor\paste! assert.equal buffer.text, 'hƏllo world!\nnext' it 'handles lines without EOLs', -> buffer.text = 'abc' cursor.pos = 3 editor\delete_to_end_of_line! assert.equal 'ab', buffer.text cursor.pos = 3 editor\delete_to_end_of_line! assert.equal 'ab', buffer.text it 'deletes without copying if no_copy is specified', -> buffer.text = 'hƏllo world!' cursor.pos = 3 editor\delete_to_end_of_line no_copy: true assert.equal buffer.text, 'hƏ' editor\paste! assert.not_equal 'hƏllo world!', buffer.text it 'join_lines joins the current line with the one after', -> buffer.text = 'hƏllo\n world!\n' cursor.pos = 1 editor\join_lines! assert.equal 'hƏllo world!\n', buffer.text assert.equal 6, cursor.pos it 'forward_to_match(string) moves the cursor to next occurence of <string>, if found in the line', -> buffer.text = 'hƏll\to\n world!' cursor.pos = 1 editor\forward_to_match 'l' assert.equal 3, cursor.pos editor\forward_to_match 'l' assert.equal 4, cursor.pos editor\forward_to_match 'o' assert.equal 6, cursor.pos editor\forward_to_match 'w' assert.equal 6, cursor.pos it 'backward_to_match(string) moves the cursor back to previous occurence of <string>, if found in the line', -> buffer.text = 'h\tƏllo\n world!' cursor.pos = 6 editor\backward_to_match 'l' assert.equal 5, cursor.pos editor\backward_to_match 'l' assert.equal 4, cursor.pos editor\backward_to_match 'h' assert.equal 1, cursor.pos editor\backward_to_match 'w' assert.equal 1, cursor.pos context 'buffer switching', -> it 'remembers the position for different buffers', -> buffer.text = 'hƏllo\n world!' cursor.pos = 8 buffer2 = Buffer {} buffer2.text = 'a whole different whale' editor.buffer = buffer2 cursor.pos = 15 editor.buffer = buffer assert.equal 8, cursor.pos editor.buffer = buffer2 assert.equal 15, cursor.pos it 'updates .last_shown for buffer switched out', -> time = sys.time now = time! sys.time = -> now pcall -> editor.buffer = Buffer {} sys.time = time assert.same now, buffer.last_shown context 'previewing', -> it 'does not update last_shown for previewed buffer', -> new_buffer = Buffer {} new_buffer.last_shown = 2 editor\preview new_buffer editor.buffer = Buffer {} assert.same 2, new_buffer.last_shown it 'updates .last_shown for original buffer switched out', -> time = sys.time now = time! sys.time = -> now pcall -> editor\preview Buffer {} sys.time= time assert.same now, buffer.last_shown context 'indentation, tabs, spaces and backspace', -> it 'defines a "tab_width" config variable, defaulting to 4', -> assert.equal config.tab_width, 4 it 'defines a "use_tabs" config variable, defaulting to false', -> assert.equal config.use_tabs, false it 'defines a "indent" config variable, defaulting to 2', -> assert.equal config.indent, 2 it 'defines a "tab_indents" config variable, defaulting to true', -> assert.equal config.tab_indents, true it 'defines a "backspace_unindents" config variable, defaulting to true', -> assert.equal config.backspace_unindents, true describe 'smart_tab()', -> it 'inserts a tab character if use_tabs is true', -> config.use_tabs = true buffer.text = 'hƏllo' cursor.pos = 2 editor\smart_tab! assert.equal buffer.text, 'h\tƏllo' it 'inserts spaces to move to the next tab if use_tabs is false', -> config.use_tabs = false buffer.text = 'hƏllo' cursor.pos = 1 editor\smart_tab! assert.equal string.rep(' ', config.indent) .. 'hƏllo', buffer.text it 'inserts a tab to move to the next tab stop if use_tabs is true', -> config.use_tabs = true config.tab_width = config.indent buffer.text = 'hƏllo' cursor.pos = 1 editor\smart_tab! assert.equal '\thƏllo', buffer.text context 'when in whitespace and tab_indents is true', -> before_each -> config.tab_indents = true config.use_tabs = false config.indent = 2 it 'indents the current line if in whitespace and tab_indents is true', -> indent = string.rep ' ', config.indent buffer.text = indent .. 'hƏllo' cursor.pos = 2 editor\smart_tab! assert.equal buffer.text, string.rep(indent, 2) .. 'hƏllo' it 'moves the cursor to the beginning of the text', -> buffer.text = ' hƏllo' cursor.pos = 1 editor\smart_tab! assert.equal 5, cursor.pos it 'corrects any half-off indentation', -> buffer.text = ' hƏllo' cursor.pos = 1 editor\smart_tab! assert.equal 5, cursor.pos assert.equal ' hƏllo', buffer.text context 'when a selection is active', -> it 'right-shifts the lines included in a selection if any', -> config.indent = 2 buffer.text = 'hƏllo\nselected\nworld!' selection\set 2, 10 editor\smart_tab! assert.equal ' hƏllo\n selected\nworld!', buffer.text context 'when in whitespace and tab_indents is false', -> it 'just inserts the corresponding tab or spaces', -> config.tab_indents = false config.indent = 2 buffer.text = ' hƏllo' cursor.pos = 1 config.use_tabs = false editor\smart_tab! assert.equal ' hƏllo', buffer.text assert.equal 3, cursor.pos config.use_tabs = true editor\smart_tab! assert.equal ' \t hƏllo', buffer.text assert.equal 4, cursor.pos describe 'smart_back_tab()', -> context 'when tab_indents is false', -> it 'moves the cursor back to the previous tab position', -> config.tab_indents = false config.tab_width = 4 buffer.text = ' hƏ567890' cursor.pos = 10 editor\smart_back_tab! assert.equal 9, cursor.pos editor\smart_back_tab! assert.equal 5, cursor.pos editor\smart_back_tab! assert.equal 1, cursor.pos editor\smart_back_tab! assert.equal 1, cursor.pos cursor.pos = 2 editor\smart_back_tab! assert.equal 1, cursor.pos context 'when tab_indents is true', -> it 'unindents when in whitespace', -> config.tab_indents = true config.tab_width = 4 buffer.text = ' 567890' cursor.pos = 10 editor\smart_back_tab! assert.equal 9, cursor.pos editor\smart_back_tab! assert.equal 5, cursor.pos editor\smart_back_tab! assert.equal 3, cursor.pos assert.equal ' 567890', buffer.text editor\smart_back_tab! assert.equal 1, cursor.pos assert.equal '567890', buffer.text context 'when a selection is active', -> it 'left-shifts the lines included in a selection if any', -> config.indent = 2 buffer.text = ' hƏllo\n selected\nworld!' selection\set 4, 12 editor\smart_back_tab! assert.equal 'hƏllo\nselected\nworld!', buffer.text describe '.delete_back()', -> it 'deletes back by one character', -> buffer.text = 'hƏllo' cursor.pos = 2 editor\delete_back! assert.equal buffer.text, 'Əllo' it 'deletes previous newline when at start of line', -> config.backspace_unindents = false buffer.text = 'hƏllo\nworld' cursor.pos = 7 editor\delete_back! assert.equal 'hƏlloworld', buffer.text config.backspace_unindents = true buffer.text = 'hƏllo\nworld' cursor.pos = 7 editor\delete_back! assert.equal 'hƏlloworld', buffer.text it 'unindents if in whitespace and backspace_unindents is true', -> config.indent = 2 buffer.text = ' hƏllo' cursor.pos = 3 config.backspace_unindents = true editor\delete_back! assert.equal buffer.text, 'hƏllo' assert.equal 1, cursor.pos it 'deletes back if in whitespace and backspace_unindents is false', -> config.indent = 2 buffer.text = ' hƏllo' cursor.pos = 3 config.backspace_unindents = false editor\delete_back! assert.equal buffer.text, ' hƏllo' context 'with a selection', -> it 'deletes the selection', -> buffer.text = ' 2\n 5' selection\set 1, 5 cursor.pos = 5 editor\delete_back! assert.equal buffer.text, '5' describe '.delete_back_word()', -> it 'deletes back by one word', -> buffer.text = 'hello world' cursor.pos = 12 editor\delete_back_word! assert.equal buffer.text, 'hello ' context 'with a selection', -> it 'deletes the selection', -> buffer.text = ' 2\n 5' selection\set 1, 5 cursor.pos = 5 editor\delete_back_word! assert.equal buffer.text, '5' describe '.delete_forward()', -> it 'deletes the character at cursor', -> buffer.text = 'hƏllo' cursor.pos = 2 editor\delete_forward! assert.equal 'hllo', buffer.text context 'when a selection is active', -> it 'deletes the selection', -> buffer.text = 'hƏllo' editor.selection\set 2, 5 editor\delete_forward! assert.equal 'ho', buffer.text assert.not_equal 'Əll', clipboard.current.text context 'when at the end of a line', -> it 'deletes the line break', -> buffer.text = 'hƏllo\nworld' cursor\move_to line: 1, column: 6 editor\delete_forward! assert.equal 'hƏlloworld', buffer.text context 'when at the end of the buffer', -> it 'does nothing', -> buffer.text = 'hƏllo' cursor\eof! editor\delete_forward! assert.equal 'hƏllo', buffer.text describe '.delete_forward_word()', -> it 'deletes forward by one word', -> buffer.text = 'hello world' cursor.pos = 1 editor\delete_forward_word! assert.equal buffer.text, 'world' context 'when a selection is active', -> it 'deletes the selection', -> buffer.text = 'hƏllo' editor.selection\set 2, 5 editor\delete_forward_word! assert.equal 'ho', buffer.text assert.not_equal 'Əll', clipboard.current.text describe '.shift_right()', -> before_each -> config.use_tabs = false config.indent = 2 context 'with a selection', -> it 'right-shifts the lines included in the selection', -> buffer.text = 'hƏllo\nselected\nworld!' selection\set 2, 10 editor\shift_right! assert.equal ' hƏllo\n selected\nworld!', buffer.text it 'adjusts and keeps the selection', -> buffer.text = ' xx\nyy zz' selection\set 3, 8 -- 'xx\nyy' editor\shift_right! assert.equal 'xx\n yy', selection.text assert.same { 5, 12 }, { selection\range! } it 'right-shifts the current line when nothing is selected, remembering column', -> buffer.text = 'hƏllo\nworld!' cursor.pos = 3 editor\shift_right! assert.equal ' hƏllo\nworld!', buffer.text assert.equal 5, cursor.pos describe '.shift_left()', -> context 'with a selection', -> it 'left-shifts the lines included in the selection', -> config.indent = 2 buffer.text = ' hƏllo\n selected\nworld!' selection\set 4, 12 editor\shift_left! assert.equal 'hƏllo\nselected\nworld!', buffer.text it 'adjusts and keeps the selection', -> buffer.text = ' xx\n yy zz' selection\set 3, 12 -- ' xx\nyy' editor\shift_left! assert.equal ' xx\nyy', selection.text assert.same { 1, 8 }, { selection\range! } it 'left-shifts the current line when nothing is selected, remembering column', -> config.indent = 2 buffer.text = ' hƏllo\nworld!' cursor.pos = 4 editor\shift_left! assert.equal ' hƏllo\nworld!', buffer.text assert.equal 2, cursor.pos describe 'cycle_case()', -> context 'with a selection active', -> it 'changes all lowercase selection to all uppercase', -> buffer.text = 'hello selectëd #world' selection\set 7, 22 editor\cycle_case! assert.equals 'hello SELECTËD #WORLD', buffer.text it 'changes all uppercase selection to titlecase', -> buffer.text = 'hello SELECTËD #WORLD HELLO' selection\set 7, 28 editor\cycle_case! -- #world is not capitalized because title case considers -- words to be any contiguous non space chars assert.equals 'hello Selectëd #world Hello', buffer.text it 'changes mixed case selection to all lowercase', -> buffer.text = 'hello SelectËD #WorLd' selection\set 7, 22 editor\cycle_case! assert.equals 'hello selectëd #world', buffer.text it 'preserves selection', -> buffer.text = 'select' selection\set 3, 5 editor\cycle_case! assert.equals 3, selection.anchor assert.equals 5, selection.cursor context 'with no selection active', -> it 'changes all lowercase word to all uppercase', -> buffer.text = 'hello wörld' cursor.pos = 7 editor\cycle_case! assert.equals 'hello WÖRLD', buffer.text it 'changes all uppercase word to titlecase', -> buffer.text = 'hello WÖRLD' cursor.pos = 7 editor\cycle_case! assert.equals 'hello Wörld', buffer.text it 'changes mixed case word to all lowercase', -> buffer.text = 'hello WörLd' cursor.pos = 7 editor\cycle_case! assert.equals 'hello wörld', buffer.text describe 'duplicate_current', -> context 'with an active selection', -> it 'duplicates the selection', -> buffer.text = 'hello\nwörld' cursor.pos = 2 selection\set 2, 5 -- 'ell' editor\duplicate_current! assert.equals 'hellello\nwörld', buffer.text it 'keeps the cursor and current selection', -> buffer.text = '123456' selection\set 5, 2 editor\duplicate_current! assert.equals 2, cursor.pos assert.equals 2, selection.cursor assert.equals 5, selection.anchor context 'with no active selection', -> it 'duplicates the current line', -> buffer.text = 'hello\nwörld' cursor.pos = 3 editor\duplicate_current! assert.equals 'hello\nhello\nwörld', buffer.text describe 'cut', -> context 'with an active selection', -> it 'cuts the selection', -> buffer.text = 'hello\nwörld' cursor.pos = 2 selection\set 2, 5 -- 'ell' editor\cut! assert.equals 'ho\nwörld', buffer.text cursor.pos = 1 editor\paste! assert.equal 'ellho\nwörld', buffer.text context 'with no active selection', -> it 'cuts the current line', -> buffer.text = 'hello\nwörld' cursor.pos = 3 editor\cut! assert.equals 'wörld', buffer.text cursor.pos = 1 editor\paste! assert.equal 'hello\nwörld', buffer.text it 'cuts the empty line', -> buffer.text = '\nwörld' cursor.pos = 1 editor\cut! assert.equals 'wörld', buffer.text editor\paste! assert.equal '\nwörld', buffer.text describe 'copy', -> context 'with an active selection', -> it 'copies the selection', -> buffer.text = 'hello\nwörld' cursor.pos = 2 selection\set 2, 5 -- 'ell' editor\copy! cursor.pos = 1 editor\paste! assert.equals 'ellhello\nwörld', buffer.text context 'with no active selection', -> it 'copies the current line', -> buffer.text = 'hello\nwörld' cursor.pos = 3 editor\copy! cursor.pos = 1 editor\paste! assert.equals 'hello\nhello\nwörld', buffer.text context 'resource management', -> it 'editors are collected as they should', -> e = Editor Buffer {} editors = setmetatable {e}, __mode: 'v' e\to_gobject!\destroy! e = nil collect_memory! assert.is_true editors[1] == nil it 'releases resources after buffer switching', -> b1 = Buffer {} b2 = Buffer {} e = Editor b1 buffers = setmetatable { b1, b2 }, __mode: 'v' editors = setmetatable { e }, __mode: 'v' e.buffer = b2 e.buffer = b1 e\to_gobject!\destroy! e = nil b1 = nil b2 = nil collectgarbage! assert.is_nil editors[1] assert.is_nil buffers[1] assert.is_nil buffers[2] context 'get_matching_brace', -> it 'finds position of matching opending/closing brace', -> editor.buffer.mode.auto_pairs = {'[': ']'} editor.buffer.text = '[]' assert.same 2, editor\get_matching_brace 1 assert.same 1, editor\get_matching_brace 2 assert.same nil, editor\get_matching_brace 3 editor.buffer.text = '[Ü]' assert.same 3, editor\get_matching_brace 1 assert.same 1, editor\get_matching_brace 3 assert.same nil, editor\get_matching_brace 2 editor.buffer.text = '1ÜÜ4[6ÜÜ9]---' assert.same 10, editor\get_matching_brace 5 assert.same 5, editor\get_matching_brace 10 assert.same nil, editor\get_matching_brace 1 assert.same nil, editor\get_matching_brace 4 assert.same nil, editor\get_matching_brace 6 assert.same nil, editor\get_matching_brace 11 it 'returns nil for unmatched/mismatched braces', -> editor.buffer.mode.auto_pairs = {'[': ']'} editor.buffer.text = '][' assert.same nil, editor\get_matching_brace 1 assert.same nil, editor\get_matching_brace 2 editor.buffer.text = '([]]' assert.same nil, editor\get_matching_brace 4 context 'config updates', -> local editor2 before_each -> editor2 = Editor Buffer {} it 'buffer config updates affect containing editor only', -> editor.buffer.config.line_numbers = true editor2.buffer.config.line_numbers = true assert.true editor.line_numbers assert.true editor2.line_numbers editor2.buffer.config.line_numbers = false assert.true editor.line_numbers assert.false editor2.line_numbers it 'buffer mode change triggers config refresh for containing editor', -> mode1 = {} mode2 = {} howl.mode.register name: 'test_mode1', create: -> mode1 howl.mode.register name: 'test_mode2', create: -> mode2 howl.mode.configure 'test_mode1', line_numbers: false howl.mode.configure 'test_mode2', line_numbers: true buffer.mode = howl.mode.by_name 'test_mode1' assert.false editor.line_numbers buffer.mode = howl.mode.by_name 'test_mode2' assert.true editor.line_numbers howl.mode.unregister 'test_mode1' howl.mode.unregister 'test_mode2'
32.974808
114
0.609546
65b8024744948c961f1b2477dc3475cc9c35e5fe
1,297
describe "moor.opt module", -> local opts, moor, bkenv, env setup -> opts = require'moor.opts' moor = require'moor' deepcpy = (t, list = {}) -> with ret = {} for k, v in pairs t if type(v) == "table" kk = tostring v unless list[kk] list[kk] = v ret[k] = deepcpy v, list else ret[k] = list[kk] else ret[k] = v if _ENV then bkenv = deepcpy _ENV else _G["_ENV"] = deepcpy _G bkenv = deepcpy _ENV env = {} it "execute and exit test", -> assert.falsy opts {}, {"-e", "nil"} it "load library to global test", -> with assert .is_true opts env, {"-luakatsu", "-E", [[kii = Aikatsu\find_birthday "12/03"]]} .is_not_nil env.kii .is_not_nil Aikatsu --- yes, it's correct behavior it "load library as LIB test", -> with assert .is_true opts env, {"-Linspect", "-E", [[foo = inspect {x: 3}, newline: ""]]} .is_same env.foo, "{ x = 3}" it "load moon file test", -> opts env, {"-E", [[test = require"spec.test_for_require"]], "-E", [[ok = nil]]} opts env, {[[-Lspec.test_for_require]]} with assert .is_same 0, env.MOOR_EXITCODE .is_same "hello", env.test .is_same "ok", env.ok_require .is_not_nil ok_require it "help and exit test", -> opts env, {'-h'} assert.is_same 1, env.MOOR_EXITCODE
24.471698
82
0.590594
27efb9e287695b80c3cbff7598bd6d8dd6a2e4bc
3,884
local * mines = assert require "mines" color = assert require "color" import floor from math app = {} -------------------------------------------------------------------------------- love.load = -> with love.graphics objects = .newImage "images/objects.png" tiles = .newImage "images/tiles.png" smileys = .newImage "images/smileys.png" app.font = .newFont "resources/beech.ttf", 40 app.score = .newFont "resources/sans.ttf", 40 width, height = objects\getWidth!, objects\getHeight! app.objects = mine: img: objects quad: .newQuad 0, 0, 48, 48, width, height flag: img: objects quad: .newQuad 48, 0, 48, 48, width, height xflag: img: objects quad: .newQuad 96, 0, 48, 48, width, height width, height = tiles\getWidth!, tiles\getHeight! app.tiles = closed: img: tiles quad: .newQuad 0, 0, 48, 48, width, height open: img: tiles quad: .newQuad 48, 0, 48, 48, width, height red: img: tiles quad: .newQuad 96, 0, 48, 48, width, height width, height = smileys\getWidth!, smileys\getHeight! app.smileys = playing: img: smileys quad: .newQuad 0, 0, 48, 48, width, height win: img: smileys quad: .newQuad 48, 0, 48, 48, width, height lose: img: smileys quad: .newQuad 96, 0, 48, 48, width, height app.fontcolors = [1]: color 0x00, 0x00, 0xa0, 0xff [2]: color 0x00, 0xa0, 0x00, 0xff [3]: color 0xa0, 0x00, 0x00, 0xff [4]: color 0xa0, 0xa0, 0x00, 0xff [5]: color 0xa0, 0x00, 0xa0, 0xff [6]: color 0xa0, 0xa0, 0x00, 0xff [7]: color 0xa0, 0xa0, 0xa0, 0xff [8]: color 0x00, 0x00, 0x00, 0xff default: color 0x00, 0x00, 0x00, 0xff setmetatable app.fontcolors, { __call: (index) => return @[index] or @default } reset! -------------------------------------------------------------------------------- love.draw = -> app.board\draw 0, 48, app.objects, app.tiles, app.font, app.fontcolors with love.graphics .setFont app.score if app.gameover and app.win .setColor 0x00, 0xff, 0x00 elseif app.gameover .setColor 0xff, 0x00, 0x00 else .setColor 0x00, 0x00, 0xff .print app.board\gettime!, 10, 4 .reset! local smiley if app.board.gameover and app.board.win smiley = app.smileys.win elseif app.board.gameover smiley = app.smileys.lose else smiley = app.smileys.playing .draw smiley.img, smiley.quad, 216, 0 -------------------------------------------------------------------------------- love.mousereleased = (x, y, button) -> lx = (floor x / 48) + 1 ly = (floor y / 48) with love.keyboard if button == 1 and not (.isDown"rgui" or .isDown"lgui") app.board\open lx, ly else app.board\toggleflag lx, ly -------------------------------------------------------------------------------- love.keyreleased = (key) -> reset! if key == "escape" -------------------------------------------------------------------------------- reset = -> app.board = mines.newboard 10, 10, 16 -------------------------------------------------------------------------------- with g = love.graphics with graphics_reset = g.reset g.reset = (...) -> graphics_reset ... g.setBackgroundColor 0xc6, 0xc7, 0xc9
31.836066
80
0.448507
1acf2f1eb78a877fbcb78232ff352e603cdf0f52
7,858
local Result, Option, Ok, Err expect_class = (value, expected)-> assert value.__class == expected, "expected type #{expected.__name}<#{expected}>, got " .. "#{value.__class.__name}<#{value.__class}>" class Result Ok: 0 Err: 1 new: (variant, content)=> @variant = variant @content = content is_ok: => @variant == Ok is_err: => @variant == Err --- Unwrap a result, returning the content or otherwise erroring expect: (error_value)=> @content if @is_ok! else error "#{error_value}: #{@content}" --- Raise error if is_err!, otherwise return content unwrap: => @content if @is_ok! else error content --- Raises error if is_ok!, otherwise returns error value unwrap_err: => @content if @is_err! else error content --- Returns content if is_ok!, otherwise `fallback` -- @param fallback unwrap_or: (fallback)=> @content if @is_ok! else fallback --- Returns content if is_ok!, otherwise the called output of `fallback_fn` -- @tparam fallback_fn unwrap_or_else: (fallback_fn)=> @content if @is_ok! else fallback_fn! ok: => Option(@content) if @is_ok! else Option! err: => Option(@content) if @is_err! else Option! --- Map Result<T, E> to Result<U, E> - Error can be kept if is_err! -- @tparam function fn Function to use for mapping content map: (fn)=> Ok fn @content if @is_ok else self --- Map Result<T, E> to Result<T, F> - Content can be kept if is_ok! -- @tparam function fn Function to use for mapping error map_err: (fn)=> if @is_err return Err fn @content self --- Return `right` if the variant is `Ok`, otherwise return self's `Err` -- @param right and_also: (right)=> self if @is_error! else right --- Return evaluated output of `right_fn` if the variant is `Ok`, otherwise -- return self's `Err` -- @tparam function right_fn and_then: (right_fn)=> self if @is_error! else right_fn @content --- Return `right` if the variant is `Err`, otherwise return self's `Ok` -- @param right or_other: (right)=> self if @is_ok! else right --- Return evaluated output of `right_fn` if the variant is `Err`, -- otherwise return self's `Ok` -- @tparam function right_fn or_else: (right_fn)=> self if @is_ok! else right_fn @content --- Transpose a Result of an Option into an Option of a Result transpose: => expect_class @content, Result if @content\is_some! return @variant @content.data -- Some Option! -- None import Ok, Err from Result result_variant_mt = { __call: (...)=> Result self, ... } debug.setmetatable Ok, result_variant_mt debug.setmetatable Err, result_variant_mt class Option new: (some=nil)=> if some @data = some is_some: => @data != nil is_none: => @data == nil --- Transform an Option<Option<T>> into an Option<T> flatten: => expect_class @data, Option Option @data\expect! --- Unwrap an option, returning the content or otherwise erroring -- @param error_value Value raised if variant is None expect: (error_value)=> @data if @is_some! else Err(error_value)\unwrap! --- Moves a value `v` out of `Option<T>` if it is a `Some(v)` variant unwrap: => @expect "called Option.unwrap() on a None variant" --- Return the contained value if is_some! or a fallback value -- @param fallback unwrap_or: (fallback)=> @data if @is_some! else fallback --- Return the contained value if is_some!, otherwise the called output of -- `fallback_fn` -- @tparam function fallback_fn unwrap_or_else: (fallback_fn)=> @data if @is_some! else fallback_fn! --- Applies a function to the contained value -- @tparam function fn Function to use for mapping content map: (fn)=> Option fn @data if @is_some! else self --- Applies a function to the contained value, or returns a fallback -- @param fallback -- @tparam function fn Function to use for mapping content map_or: (fallback, fn)=> Option fn @data if @is_some! else fallback --- Applies a function to the contained value, or calls fallback function -- @tparam function fallback_fn -- @tparam function fn Function to use for mapping content map_or_else: (fallback_fn, fn)=> Option fn @data if @is_some! else fallback_fn! --- Transform an `Option<T>` into a `Result<T, E>`, mapping `Some(v)` to -- `Ok(v)` and `None` to `Err(error_value)` -- @param error_value ok_or: (error_value)=> if @is_some! Ok @data else -- None Err error_value --- Transform an `Option<T>` into a `Result<T, E>`, mapping `Some(v)` to -- `Ok(v)` and `None` to `Err(error_fn!)` -- @tparam function error_fn ok_or_else: (error_fn)=> if @is_some! Ok @data else -- None Err error_fn! --- Return `None` if already `None`, otherwise call `predicate` function -- and returns `Some(v)` if the predicate function returns true, otherwise -- None if `predicate` returns false -- @tparam function predicate filter: (predicate)=> if @is_some! and predicate @data return @data Option! --- Return `right` if the variant is `Some` -- @param right and_also: (right)=> self if @is_none! else right --- Return evaluated output of `right_fn` if the variant is `Some`, -- otherwise return None -- @tparam function right_fn and_then: (right_fn)=> self if @is_none! else right_fn @data --- Return `right` if the variant is `None`, else return self's `Some` -- @param right or_other: (right)=> self if @is_some! else right --- Returns evaluated output of `right_fn` if the variant is `None`, -- otherwise returns self's `Some` -- @tparam function right_fn or_else: (right_fn)=> self if @is_some! else right_fn! --- Returns a `Some(value)` if either the self or the `right` have a -- `Some(value)`, but not both xor: (right)=> if (@is_some! and right\is_none!) or (@is_none! and right\is_some!) return @or_other right Option! -- None --- Transpose an Option of a Result into a Result of an Option transpose: => if @is_none! return Ok self -- Result(None) @data.variant Option(@data.content) class Entry new: (source, key)=> @source = source @key = key --- Determine whether or not a `key` exists currently in the table exists: => @source[@key] != nil --- Create a `default` value in the source if the key doesn't have an -- associated value already -- @param default or_insert: (default)=> source, key = @source, @key source[key] = default unless source[key] source[key] --- Create a default value from the result of `default_fn` in the source if -- the key doesn't have an associated value already -- @tparam function default_fn or_insert_with: (default_fn)=> source, key = @source, @key source[key] = default_fn! unless source[key] source[key] --- Apply a function `fn` to the entry, if it exists; should be called -- before returning the value, and can be chained -- @tparam function fn and_modify: (fn)=> source, key = @source, @key if source[key] source[key] = fn source[key] self class Map new: (data={})=> @data = data --- Return an `Entry` to the potential value in the Map, which can be used -- to add a default value. If a default value isn't available or desired, -- instead use get() -- @param name entry: (key)=> Entry @data, key --- Returns `true` if a key exists within the table, or otherwise `false` contains_key: (key)=> @data[key] != nil --- Return an `Option<T>` to the potential value in the Map, which can be -- used to see if a value exists. If you want to insert a default value in -- the case it doesn't exist, use entry() get: (key)=> Option @data[key] --- Return a value expected to exist in the Map expect: (key)=> @get(key)\expect! --- Set a `value` in the Map to an associated `key` -- @param key -- @param value set: (key, value)=> @data[key] = value --- Remove a `key` from a Map remove: (key)=> @data[key] = nil --- Iterate over the Map iter: => pairs @data return :Result, :Ok, :Err, :Option, :Entry, :Map
28.783883
76
0.679817
521a0f465172e1ca71ecb2c3d097fa96de9f976b
3,784
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' -- FolderPath 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' 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' 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
23.214724
116
0.659091
90ccd34f2c46f183e69b1ba9fae112c1fc26c658
113
Dorothy! UIEditorView = require "View.Control.GUI.UIEditor" Class UIEditorView, __init:(args)=> return
16.142857
51
0.716814
11cc0876c2ba44d36490adb35dffa7e4a82cfd21
1,383
parse = require'moonscript.parse' compile = require'moonscript.compile' inspect = require'inspect' ms = require'moonscript.base' import remove, concat from table init_moonpath = -> moonpath = package.moonpath ms.insert_loader! moonpath != nil deinit_moonpath = (has_moonpath) -> ms.remove_loader! unless has_moonpath package.moonpath = nil printerr = (...) -> io.stderr\write "#{concat {...}, "\t"}\n" to_lua = (code) -> tree, err = parse.string code return nil, err if err lua_code, err, pos = compile.tree tree unless lua_code nil, compile.format_error err, pos, code else lua_code -- Lua evaluator & printer fnwrap = (code) -> "return function(__newenv) local _ENV = setmetatable(__newenv, {__index = _ENV}) #{code} end" evalprint = (env, lua_code, non_verbose) -> has_moonpath = init_moonpath! if nolocal = lua_code\match "^local%s+(.*)" lua_code = nolocal unless lua_code\match "^[^\n]*=" lua_code = lua_code\match"^.-\n(.*)" luafn, err = load fnwrap(lua_code != nil and lua_code or ""), "tmp" return printerr err if err result = {pcall luafn!, env} deinit_moonpath has_moonpath ok = remove result, 1 ok, unless ok then result[1] else if #result > 0 print (inspect result)\match"^%s*{%s*(.*)%s*}%s*%n?%s*$" unless non_verbose table.unpack result {:printerr, :to_lua, :fnwrap, :evalprint, :init_moonpath, :deinit_moonpath}
23.440678
112
0.690528
92ea027768d6fd8fb89b3353864d22461648fa0f
358
import lib from require "magick.gmwand.lib" lib.InitializeMagick nil import Image from require "magick.gmwand.image" import make_thumb from require "magick.thumb" load_image = Image\load { VERSION: require "magick.version" mode: "graphics_magick" :Image :load_image thumb: make_thumb load_image load_image_from_blob: Image\load_from_blob }
17.9
47
0.776536
25f2ed83dd2d5b95584ec862271083e7cb47312b
1,241
-- Copyright 2014-2015 The Howl Developers -- License: MIT (see LICENSE.md at the top-level directory of the distribution) ffi = require 'ffi' bit = require 'bit' Gdk = require 'ljglibs.gdk' require 'ljglibs.cdefs.glib' C, ffi_cast, ffi_string = ffi.C, ffi.cast, ffi.string band = bit.band gchar_arr = ffi.typeof 'gchar [?]' explain_key_code = (code, event) -> effective_code = code == 10 and Gdk.KEY_Return or code key_name = C.gdk_keyval_name effective_code if key_name != nil event.key_name = ffi_string(key_name)\lower! unicode_char = C.gdk_keyval_to_unicode code if unicode_char != 0 utf8 = gchar_arr(6) nr_utf8 = C.g_unichar_to_utf8 unicode_char, utf8 if nr_utf8 > 0 event.character = ffi.string utf8, nr_utf8 event.key_code = code { parse_key_event: (key_event) -> key_event = ffi_cast('GdkEventKey *', key_event) event = { shift: band(key_event.state, C.GDK_SHIFT_MASK) != 0, control: band(key_event.state, C.GDK_CONTROL_MASK) != 0, alt: band(key_event.state, C.GDK_MOD1_MASK) != 0, super: band(key_event.state, C.GDK_SUPER_MASK) != 0, meta: band(key_event.state, C.GDK_META_MASK) != 0, } explain_key_code key_event.keyval, event event }
28.204545
79
0.693795
a4cb97a2ea2b0745c32dfa30ca1ef67603925e59
4,122
sound_player = require "src/player/sound" make = (x, y, z, settings) -> plant = { pos: { [1]: x [2]: y [3]: z - 5 } } plant.tag = {} plant.w = 4 plant.h = 5 plant.frcx = 18 plant.frcy = 1 plant.dx = 0 plant.dy = 0 plant.gravity = 30 plant.grounded = false plant.seed = true plant.dirx = nil plant.life = 5 plant.touched = false plant.update = (dt) => @pos[1], @pos[2], @collisions = world\move @, @pos[1] + @dx, @pos[2] + @dy, game.filter if @seed and @touched @life -= dt if @life <= 0 game\remove @ world\remove @ for c in *@collisions @touched = true if c.normal.y ~= 0 if c.normal.y == -1 @grounded = true @dy = 0 if c.normal.x ~= 0 @dx = 0 if @seed and (c.other.name == "dirt" or c.other.name == "grass") if settings.condition continue unless settings\condition c if settings.adjustdir @dirx = -c.normal.x @settings.dirx = @dirx if @settings @grow settings if @settings @settings\collide c if @settings.collide game\tag_check c.other.tags, c.other, @ if c.other.tags if c.other.settings game\tag_check c.other.settings.tags, c.other, @ if c.other.settings.tags if @grounded @dx -= @dx * @frcx * dt unless 0.01 > math.abs @dx - @frcx else @dx -= @dx * @frcy * dt unless 0.01 > math.abs @dx - @frcy @dy -= @dy * @frcy * dt unless 0.01 > math.abs @dy - @frcy @dy += @gravity * dt plant.draw = => if @settings if @settings.draw @settings\draw @, @real_draw else @real_draw! else @real_draw! plant.real_draw = => if @settings if @dirx == -1 @draw_pos = { game.x + @pos[1] + (@settings.ox or 0) + sprites.plants[@settings.name]\getWidth! / 2 game.y + @pos[2] + (@settings.oy or 0) @pos[3] } elseif @dirx == 1 @draw_pos = { game.x + @pos[1] + (@settings.ox or 0) game.y + @pos[2] + (@settings.oy or 0) @pos[3] } else @draw_pos = { game.x + @pos[1] + (@settings.ox or 0) + sprites.plants[@settings.name]\getWidth! / 2 game.y + @pos[2] + (@settings.oy or 0) @pos[3] } else @draw_pos = { game.x + @pos[1] game.y + @pos[2] @pos[3] } with projection.graphics if @seed love.graphics.setColor 100, 255, 100 .square3d fov, "fill", @draw_pos, @w, @h else sprite = sprites.plants[@settings.name] love.graphics.setColor 255, 255, 255 .draw fov, sprite, @draw_pos, 0, (@dirx or 1) * 1.5, 1.5, sprite\getWidth! / 2 plant.grow = (settings) => @touchable = settings.touchable or true world\update @, @pos[1] - (@dirx or 1) * (settings.w / 2), @pos[2] - settings.h - @h * 3, settings.w, settings.h for tag in *settings.tags @tag[#@tag + 1] = tag @settings = settings @gravity = 0 if @settings.flying @w = @settings.w @h = @settings.h @dx = 0 @dy = 0 @seed = false world\add plant, plant.pos[1], plant.pos[2], plant.w, plant.h plant skunk = { name: "skunk" w: 24 h: 24 touchable: true tags: {"pick"} -- draw nice stuff effect: shine.godsray! draw: (plant_self, real_draw_function) => @effect\draw -> real_draw_function plant_self on_pick: (a) => a.dxmul = -1 world\remove @ game\remove @ } shrub = { name: "shrub" w: 24 h: 24 touchable: true tags: {"touch"} on_touch: (c) => sound_player\play_bop! c.pos[2] -= 1 if c.dy > -6 c.dy = -6 else c.dy = c.dy * 0.9 } berry = { name: "berry" w: 4 h: 24 touchable: true adjustdir: true flying: true tags: {"grab"} dirx: 0 condition: (c) => c.normal.x ~= 0 on_grab: (a) => a.attatched = -@dirx } { :make settings: { :skunk :shrub :berry } }
21.138462
116
0.510432
9892055a5defb3ecb4ac426eadfc45897fb17fbe
3,251
import Widget from require "lapis.html" import Users, Resources, ResourcePackages, ResourceRatings from require "models" import time_ago_in_words from require "lapis.util" date = require "date" i18n = require "i18n" class MTAResourceLayout extends Widget @include "widgets.utils" content: => if @rights and not @rights.user_confirmed div class: "alert alert-info", role: "alert", -> strong i18n "resources.manage.author.moderation_invite" raw " " form class: "mta-inline-form", method: "POST", action: @url_for("resources.manage.invite_reply", resource_slug: @resource), -> @write_csrf_input! button type: "submit", class: "btn btn-secondary btn-sm", name: "accept_state", value: "true", -> text i18n "resources.manage.author.accept_invite" raw " " button type: "submit", class: "btn btn-secondary btn-sm", name: "accept_state", value: "false", -> text i18n "resources.manage.author.decline_invite" div class: "row", -> div class: "card", -> div class: "card-header", -> h2 -> text "#{@resource.longname} (#{@resource.name}) " span class: "label label-primary", Resources.types[@resource.type] span class: "pull-xs-right", -> if @rights and @rights.user_confirmed a class: "btn btn-secondary", href: @url_for("resources.manage.dashboard", resource_slug: @resource), -> i class: "fa fa-cogs" raw " " text i18n "resources.manage.title" raw " " if @route_name == "resources.view" if @active_user form method: "POST", action: @url_for("resources.cast_vote", resource_slug: @resource), class: "mta-inline-form", -> @write_csrf_input! rating = ResourceRatings\find resource: @resource.id, user: @active_user.id rating = rating.rating if rating span class: "btn-group", role: "group", ["aria-label"]: i18n("resources.cast_vote"), -> button type: "submit", name: "vote", value: "down", class: {"btn btn-secondary", active: (rating == false)}, -> i class: "fa fa-thumbs-down" button type: "submit", name: "vote", value: "none", class: {"btn btn-secondary", active: (rating == nil)}, -> i class: "fa fa-circle" button type: "submit", name: "vote", value: "up", class: {"btn btn-secondary", active: (rating == true)}, -> i class: "fa fa-thumbs-up" raw " " form method: "POST", action: @url_for("resources.report_resource", resource_slug: @resource), class: "mta-inline-form", -> @write_csrf_input! button type: "submit", class: "btn btn-secondary", -> i class: "fa fa-flag" raw " " a class: "btn btn-primary", href: @url_for("resources.get", resource_slug: @resource), -> i class: "fa fa-download" raw " " text i18n "download" else raw " " a class: "btn btn-secondary", href: @url_for("resources.view", resource_slug: @resource), -> i class: "fa fa-arrow-left" raw " " text i18n "resources.view_resource" viewWidget = require "views." .. @route_name widget viewWidget
45.152778
132
0.602276
f6d2b734f8c01ba68095b4306e27cda9117e8921
11,660
-- This script can be used to adjust the color so that subtitles made with matrix BT.601 can fit it a script made with matrix BT.709, or vice versa -- In other words, it can convert the color matrix of the script -- Users of Aegisub version 2.9 and 3.0 should use the lua version, and users of version 3.1 or later should use the moonscript version -- If you want to convert the whole file (or several files), you should use the C# version as it's much faster and supports batch processing export script_name = "Color Matrix Converter" export script_description = "Adjusts the color so that subtitles made with matrix BT.601 can fit in scripts made with matrix BT.709, or vice versa" export script_author = "dreamer2908" export script_version = "0.1.4" local * -- util = require 'aegisub.util' -- slower, not gonna use -- clipboard = require 'clipboard' -- for testing only -- Defination: height = dimention 1 = number of rows, width = dimention 3 = number of columns -- {{1, 3, 3}} is an 1x3 matrix, whose height = 1, width = 3 -- {{4}, {5}, {6}} is a 3x1 matrix, whose height = 3, width = 1 createMatrix = (n, m) -> if n == 3 and m == 1 return {{0}, {0}, {0}} -- This should be faster as I only use 3x1 and 3x3 matrixes if n == 3 and m == 3 return {{0,0,0},{0,0,0},{0,0,0}} resultMatrix = {} for i = 1, n resultMatrix[i] = {} for j = 1, m resultMatrix[i][j] = 0.0 return resultMatrix matrixMultiplication = (m1, m2) -> resultMatrix = createMatrix(#m1, #m2[1]) for i = 1, #m1 for j = 1, #m2[1] for k = 1, #m1[1] resultMatrix[i][j] += m1[i][k] * m2[k][j] return resultMatrix matrixScalarMultiplication = (m1, scalar) -> resultMatrix = createMatrix(#m1,#m1[1]) for i = 1, #m1 for j = 1, #m1[1] resultMatrix[i][j] = m1[i][j] * scalar return resultMatrix matrixInverse3x3 = (m1) -> if #m1 ~= 3 or #m1[1] ~= 3 return m1 resultMatrix = createMatrix(3, 3) a = m1[1][1] b = m1[1][2] c = m1[1][3] d = m1[2][1] e = m1[2][2] f = m1[2][3] g = m1[3][1] h = m1[3][2] i = m1[3][3] det_1 = 1.0 / (a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g)) resultMatrix[1][1] = det_1 * (e * i - f * h) resultMatrix[1][2] = det_1 * (c * h - b * i) resultMatrix[1][3] = det_1 * (b * f - c * e) resultMatrix[2][1] = det_1 * (f * g - d * i) resultMatrix[2][2] = det_1 * (a * i - c * g) resultMatrix[2][3] = det_1 * (c * d - a * f) resultMatrix[3][1] = det_1 * (d * h - e * g) resultMatrix[3][2] = det_1 * (b * g - a * h) resultMatrix[3][3] = det_1 * (a * e - b * d) return resultMatrix printMatrix = (m) -> for i = 1, #m s = "" for j = 1, #m[1] s ..= " "..m[i][j] print s -- One time init digital_8_bit_rgb_full_range_to_digital_ycbcr_using_bt601 = {{65.738, 129.057, 25.046}, {-37.945, -74.494, 112.439}, {112.439, -94.154, -18.285}} digital_8_bit_rgb_full_range_to_digital_ycbcr_using_bt709 = {{46.742, 157.243, 15.874}, {-25.765, -86.674, 112.439}, {112.439, -102.129, -10.310}} digital_8_bit_rgb_full_range_to_digital_ycbcr_using_bt2020 = {{57.757, 149.064, 13.038}, {-31.400, -81.039, 112.439}, {112.439, -103.396, -9.043}} digital_ycbcr_to_digital_8_bit_rgb_full_range_using_bt601 = {{298.082, 0, 408.583}, {298.082, -100.291, -208.120}, {298.082, 516.411, 0}} digital_ycbcr_to_digital_8_bit_rgb_full_range_using_bt709 = {{298.082, 0, 458.942}, {298.082, -54.592, -136.425}, {298.082, 540.775, 0}} digital_ycbcr_to_digital_8_bit_rgb_full_range_using_bt2020 = {{298.082, 0, 429.741}, {298.082, -47.955, -166.509}, {298.082, 548.294, 0}} -- Haven't tested if un-scaled matrixes still work digital_8_bit_rgb_full_range_to_digital_ycbcr_using_bt601 = matrixScalarMultiplication(digital_8_bit_rgb_full_range_to_digital_ycbcr_using_bt601, 1/256.0) digital_8_bit_rgb_full_range_to_digital_ycbcr_using_bt709 = matrixScalarMultiplication(digital_8_bit_rgb_full_range_to_digital_ycbcr_using_bt709, 1/256.0) digital_8_bit_rgb_full_range_to_digital_ycbcr_using_bt2020 = matrixScalarMultiplication(digital_8_bit_rgb_full_range_to_digital_ycbcr_using_bt2020, 1/256.0) digital_ycbcr_to_digital_8_bit_rgb_full_range_using_bt601 = matrixScalarMultiplication(digital_ycbcr_to_digital_8_bit_rgb_full_range_using_bt601, 1/256.0) digital_ycbcr_to_digital_8_bit_rgb_full_range_using_bt709 = matrixScalarMultiplication(digital_ycbcr_to_digital_8_bit_rgb_full_range_using_bt709, 1/256.0) digital_ycbcr_to_digital_8_bit_rgb_full_range_using_bt2020 = matrixScalarMultiplication(digital_ycbcr_to_digital_8_bit_rgb_full_range_using_bt2020, 1/256.0) -- This takes advantage of matrix math to reduce two steps (RGB -> YCbCr, YCbCr -> RGB) to one etep (RGB(bt601) -> RGB(bt709)) -- Offseting is skipped because it's useless for this purpose bt601_to_bt709 = matrixMultiplication(digital_ycbcr_to_digital_8_bit_rgb_full_range_using_bt709, digital_8_bit_rgb_full_range_to_digital_ycbcr_using_bt601) bt709_to_bt601 = matrixMultiplication(digital_ycbcr_to_digital_8_bit_rgb_full_range_using_bt601, digital_8_bit_rgb_full_range_to_digital_ycbcr_using_bt709) bt601_to_bt2020 = matrixMultiplication(digital_ycbcr_to_digital_8_bit_rgb_full_range_using_bt2020, digital_8_bit_rgb_full_range_to_digital_ycbcr_using_bt601) bt709_to_bt2020 = matrixMultiplication(digital_ycbcr_to_digital_8_bit_rgb_full_range_using_bt2020, digital_8_bit_rgb_full_range_to_digital_ycbcr_using_bt709) bt2020_to_bt601 = matrixMultiplication(digital_ycbcr_to_digital_8_bit_rgb_full_range_using_bt601, digital_8_bit_rgb_full_range_to_digital_ycbcr_using_bt2020) bt2020_to_bt709 = matrixMultiplication(digital_ycbcr_to_digital_8_bit_rgb_full_range_using_bt709, digital_8_bit_rgb_full_range_to_digital_ycbcr_using_bt2020) mode = 1 matrixTable = {bt601_to_bt709, bt709_to_bt601, bt601_to_bt2020, bt709_to_bt2020, bt2020_to_bt601, bt2020_to_bt709} modeTable = { "BT.601 to BT.709", "BT.709 to BT.601", "BT.601 to BT.2020", "BT.709 to BT.2020", "BT.2020 to BT.601", "BT.2020 to BT.709"} tableMode = { v,k for k,v in ipairs modeTable } -- autogen from modeTable fieldTable = {"TV.709", "TV.601", "TV.2020", "TV.2020", "TV.601", "TV.709"} convertAll = false convertSelected = true convertDialog = false convertStyles = false setYCyCrField = false roundAndClip = (value) -> if value < 0 return 0 if value > 255 return 255 return math.floor(value + 0.5) -- colorString should be either &HAABBGGRR or &HBBGGRR -- Invalid strings will be returned as is convertColor = (colorString) -> -- Here is the profiling result: -- Sample: https://www.dropbox.com/s/1u2bqy1gvz1yu7c/big.7z -- With Aegisub r8138 (and earlier versions), which uses lua5.1 -- -- TL;DR: Aegisub's lua interpreter seems to suck at creating nested tables: it accounts for 2/3 of computation cost. -- -- Total time: 30s -- -- Color extraction: 2.4s (util.extract_color is unsurprisingly slower: 3.1s) -- -- The actual calculation: 25.8s -- -- -- Matrix creation: 9s. Yes, it's damn 9s. -- -- -- Multiplication: 14.3s (this uses one matrix creation) -- -- -- Rounding and clipping: 2.5s -- -- Generating result: 2.7s -- With Aegisub r8330 (and later versions), which uses LuaJIT -- -- Total time: 8.2s -- -- Color extraction: 1.4s -- -- The actual calculation: 3.1s -- -- -- Matrix creation: 1.5s. (overwhelmingly faster than lua5.1) -- -- -- Multiplication: 1.6s (this uses one matrix creation) -- -- -- Rounding and clipping: 0.0s (Yup!) -- -- Generating result: 3.7s <~~ What?! -- if true return colorString -- test sourceLen = string.len(colorString) R = 0 G = 0 B = 0 A = '' if sourceLen == 8 -- R, G, B, A = util.extract_color(colorString..'&') -- Slower, not gonna use. B = tonumber(string.sub(colorString, 3, 4), 16) G = tonumber(string.sub(colorString, 5, 6), 16) R = tonumber(string.sub(colorString, 7, 8), 16) else if sourceLen == 10 A = string.sub(colorString, 3, 4) B = tonumber(string.sub(colorString, 5, 6), 16) G = tonumber(string.sub(colorString, 7, 8), 16) R = tonumber(string.sub(colorString, 9, 10), 16) else return colorString storage = {{R}, {G}, {B}} storage = matrixMultiplication(matrixTable[mode], storage) R = roundAndClip(storage[1][1]) G = roundAndClip(storage[2][1]) B = roundAndClip(storage[3][1]) return string.format("&H%s%02X%02X%02X", A, B, G, R) convertLine = (line) -> result = string.gsub(line, "&H%x+", convertColor) return result -- Note: convertAll doesn't work in the same way as the C# version as Aegisub doesn't parse line.raw so all changes here are ignored -- Just text and effect for now convertSubtitle = (subtitle, selected, active) -> num_lines = #subtitle if convertDialog or convertAll for i = 1, num_lines line = subtitle[i] if line.class == "dialogue" line.text = convertLine(line.text) line.effect = convertLine(line.effect) subtitle[i] = line elseif convertSelected for si,li in ipairs(selected) line = subtitle[li] line.text = convertLine(line.text) line.effect = convertLine(line.effect) subtitle[li] = line if convertStyles or convertAll -- Search for style session style = 0 for i = 1, num_lines line = subtitle[i] if line.class == "style" style = 1 line.color1 = convertLine(line.color1) line.color2 = convertLine(line.color2) line.color3 = convertLine(line.color3) line.color4 = convertLine(line.color4) subtitle[i] = line elseif style == 1 -- reached the end of style session break if setYCyCrField or convertAll -- Search for YCbCr field in info session info = 0 lastFieldIndex = 0 for i = 1, num_lines line = subtitle[i] if line.class == "info" info = 1 lastFieldIndex = i if line.key == "YCbCr Matrix" line.value = fieldTable[mode] subtitle[i] = line break elseif info == 1 -- reached the end of info session but didn't find that field. Insert a new one line = subtitle[lastFieldIndex] line.key = "YCbCr Matrix" line.value = fieldTable[mode] subtitle.insert(lastFieldIndex, line) break return selected mainDialog = { {class:"label",x:0,y:0,width:1,height:1,label:"Mode:"}, {class:"dropdown",x:1,y:0,width:2,height:1,name:"modeselect",items:modeTable,value:"BT.601 to BT.709"}, {class:"checkbox",x:0,y:1,width:2,height:1,name:"convertSelected",label:"Convert selected lines",value:false}, {class:"checkbox",x:0,y:2,width:2,height:1,name:"convertDialog",label:"Convert all lines",value:false}, {class:"checkbox",x:0,y:3,width:2,height:1,name:"convertStyles",label:"Convert styles",value:false}, {class:"checkbox",x:0,y:4,width:2,height:1,name:"setYCyCrField",label:"Set YCbCr Matrix field",value:false}, {class:"checkbox",x:0,y:5,width:2,height:1,name:"convertAll",label:"ALL of above",value:false}, } macro_function = (subtitle, selected, active) -> -- load settings from last time (or default) mainDialog[2]["value"] = modeTable[mode] mainDialog[3]["value"] = convertSelected mainDialog[4]["value"] = convertDialog mainDialog[5]["value"] = convertStyles mainDialog[6]["value"] = setYCyCrField mainDialog[7]["value"] = convertAll pressed, results = aegisub.dialog.display(mainDialog, {"OK", "Cancel"}, {cancel: "Cancel"}) if pressed == "OK" aegisub.progress.set math.random(100) -- professional progress bars. #basedtorque™ -- save settings mode = tableMode[results.modeselect] convertSelected = results.convertSelected convertDialog = results.convertDialog convertStyles = results.convertStyles setYCyCrField = results.setYCyCrField convertAll = results.convertAll convertSubtitle(subtitle, selected, active) aegisub.set_undo_point(script_name) else aegisub.cancel() return selected aegisub.register_macro(script_name, script_description, macro_function)
43.834586
157
0.717067
69beb11b4eeabd46caab3b9d37e02dded9fd8288
264
s.input = { "input" } s.input.update = (i, input) -> with love.keyboard input.x, _ = controls\get "move" input.up = controls\pressed "up" input.down = controls s.input_reset = { "input" } s.input_reset.update = (i, input) -> input.up = false
24
39
0.609848
42ca36603ff03df503edab0d42d95f2ea2721a02
2,940
db = require "lapis.db.postgres" import select, pairs, type, select from _G unpack = unpack or table.unpack import insert from table import BaseModel, Enum, enum from require "lapis.db.base_model" import preload from require "lapis.db.model.relations" 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 if @timestamp time = @db.format_date! values.created_at or= time values.updated_at or= time local returning, return_all, nil_fields 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 for k, v in pairs values if v == db.NULL nil_fields or= {} nil_fields[k] = true continue elseif 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 if nil_fields for k in pairs nil_fields values[k] = nil @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) time = @@db.format_date! values.updated_at or= time local returning for k, v in pairs values if v == db.NULL @[k] = nil elseif 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, :preload }
24.5
72
0.579932
8e2d5aa659cb0d9ccb38ff373c65c5ea822679b4
491
-- concatenate many lists into one M = {} me = ... split = (str, symbol="%s") -> [x for x in string.gmatch(str, "([^"..symbol.."]+)")] root1 = (split me, ".")[1] concat2 = require(root1..".".."._lists._concat2").concat2 tail = require(root1..".".."._lists._tail").tail -- concatenate many lists M.concat = (...) -> args = {...} aux = (input, accum) -> return accum if #input == 0 return aux (tail input), (concat2 accum, input[1]) return aux args, {} return M
27.277778
83
0.562118
c6d13b3dddd19abcaf2eeea8763aacbbad2ad450
1,469
moonscript = require "moonscript.base" class Template new: (renderer) => -- Forcing it to ignore self. -- Why is this even a class? Consistency? Coherence? Ease of documentation? =/ -- TODO: Decide if stuff will be downgraded to simple modules or not. @render = (self, document) -> renderer document render: (document) => -- Templates would usually overwrite this method and do some -- operations with the document. Like printing html around and -- dumping its .body in the middle. document.body @fromMoon: (filePath) -> template, reason = moonscript.loadfile filePath unless template return nil, "moonscript could not load template file", reason, filePath {:render_html} = require "hestia.lapis.html" @@ (document) -> environment = {k, v for k, v in pairs _G} environment.document = document environment.project = document.project -- Not exactly thread-safe. We’ll probably never care. setfenv template, environment render_html template @fromEtlua: (filePath) -> file, reason = io.open filePath, "r" unless file return nil, reason content = file\read "*all" template = require("etlua").compile content file\close! @@ template @fromFilePath: (filePath) -> extension = filePath\match '^.*%.([^.]*)$' if extension == "moon" return @@.fromMoon filePath elseif extension == "elua" return @@.fromEtlua filePath else return nil, "unrecognized template format", extension
24.081967
80
0.692308
1aa152570decb8cb1edaaeae3498781bfa8ddb57
22
request "lapis.router"
22
22
0.818182
29f79b313958eecaa5ffa559505748a9a8f19e7d
7,690
-- -- adapted from json.lua by John Axel Eriksson https://github.com/johnae -- -- Copyright (c) 2015 rxi -- -- This library is free software; you can redistribute it and/or modify it -- under the terms of the MIT license. See LICENSE for details. -- json = { _version: "0.1.0" } ------------------------------------------------------------------------------- -- Encode ------------------------------------------------------------------------------- local encode escape_char_map = { "\\": "\\\\", "\"": "\\\"", "\b": "\\b", "\f": "\\f", "\n": "\\n", "\r": "\\r", "\t": "\\t", } escape_char_map_inv = { ["\\/"]: "/" } for k, v in pairs escape_char_map escape_char_map_inv[v] = k escape_char = (c) -> escape_char_map[c] or string.format("\\u%04x", c\byte!) encode_nil = (val) -> "null" encode_table = (val, stack) -> res = {} stack = stack or {} -- Circular reference? if stack[val] error "circular reference" stack[val] = true if val[1] != nil or next(val) == nil -- Treat as array -- check keys are valid and it is not sparse n = 0 for k,_ in pairs(val) if type(k) != "number" error("invalid table: mixed or invalid key types") n = n + 1 if n != #val then error("invalid table: sparse array") -- Encode for i, v in ipairs(val) table.insert(res, encode(v, stack)) stack[val] = nil "[#{table.concat(res, ',')}]" else -- Treat as an object for k, v in pairs(val) if type(k) != "string" error("invalid table: mixed or invalid key types") table.insert(res, encode(k, stack) .. ":" .. encode(v, stack)) stack[val] = nil "{#{table.concat(res, ",")}}" encode_string = (val) -> '"' .. val\gsub('[%z\1-\31\\"]', escape_char) .. '"' encode_number = (val) -> -- Check for NaN, -inf and inf if val != val or val <= -math.huge or val >= math.huge error("unexpected number value '" .. tostring(val) .. "'") string.format("%.14g", val) type_func_map = { nil: encode_nil, table: encode_table, string: encode_string, number: encode_number, boolean: tostring } encode = (val, stack) -> t = type(val) f = type_func_map[t] if f return f(val, stack) error("unexpected type '" .. t .. "'") json.encode = (val) -> encode(val) ------------------------------------------------------------------------------- -- Decode ------------------------------------------------------------------------------- local parse create_set = (...) -> res = {} for i = 1, select("#", ...) res[ select(i, ...) ] = true res space_chars = create_set(" ", "\t", "\r", "\n") delim_chars = create_set(" ", "\t", "\r", "\n", "]", "}", ",") escape_chars = create_set("\\", "/", '"', "b", "f", "n", "r", "t", "u") literals = create_set("true", "false", "null") literal_map = { true: true, false: false, null: nil, } next_char = (str, idx, set, negate) -> for i = idx, #str if set[str\sub(i, i)] != negate return i #str + 1 decode_error = (str, idx, msg) -> line_count = 1 col_count = 1 for i = 1, idx - 1 col_count = col_count + 1 if str\sub(i, i) == "\n" line_count = line_count + 1 col_count = 1 error( string.format("%s at line %d col %d", msg, line_count, col_count) ) codepoint_to_utf8 = (n) -> -- http://scripts.sil.org/cms/scripts/page.php?site_id=nrsi&id=iws-appendixa f = math.floor if n <= 0x7f return string.char(n) elseif n <= 0x7ff return string.char(f(n / 64) + 192, n % 64 + 128) elseif n <= 0xffff return string.char(f(n / 4096) + 224, f(n % 4096 / 64) + 128, n % 64 + 128) elseif n <= 0x10ffff return string.char(f(n / 262144) + 240, f(n % 262144 / 4096) + 128, f(n % 4096 / 64) + 128, n % 64 + 128) error( string.format("invalid unicode codepoint '%x'", n) ) parse_unicode_escape = (s) -> n1 = tonumber s\sub(3, 6), 16 n2 = tonumber s\sub(9, 12), 16 -- Surrogate pair? if n2 return codepoint_to_utf8((n1 - 0xd800) * 0x400 + (n2 - 0xdc00) + 0x10000) else return codepoint_to_utf8(n1) parse_string = (str, i) -> has_unicode_escape = false has_surrogate_escape = false has_escape = false local last for j = i + 1, #str x = str\byte j if x < 32 decode_error str, j, "control character in string" if last == 92 -- "\\" (escape char) if x == 117 -- "u" (unicode escape sequence) hex = str\sub j + 1, j + 5 unless hex\find "%x%x%x%x" decode_error str, j, "invalid unicode escape in string" if hex\find "^[dD][89aAbB]" has_surrogate_escape = true else has_unicode_escape = true else c = string.char x unless escape_chars[c] decode_error str, j, "invalid escape char '" .. c .. "' in string" has_escape = true last = nil elseif x == 34 -- '"' (end of string) s = str\sub i + 1, j - 1 if has_surrogate_escape s = s\gsub "\\u[dD][89aAbB]..\\u....", parse_unicode_escape if has_unicode_escape s = s\gsub "\\u....", parse_unicode_escape if has_escape s = s\gsub "\\.", escape_char_map_inv return s, j + 1 else last = x decode_error str, i, "expected closing quote for string" parse_number = (str, i) -> x = next_char str, i, delim_chars s = str\sub i, x - 1 n = tonumber s unless n decode_error str, i, "invalid number '" .. s .. "'" return n, x parse_literal = (str, i) -> x = next_char str, i, delim_chars word = str\sub i, x - 1 unless literals[word] decode_error str, i, "invalid literal '" .. word .. "'" return literal_map[word], x parse_array = (str, i) -> res = {} n = 1 i = i + 1 while true do local x i = next_char str, i, space_chars, true -- Empty / end of array? if str\sub(i, i) == "]" i = i + 1 break -- Read token x, i = parse str, i res[n] = x n = n + 1 -- Next token i = next_char str, i, space_chars, true chr = str\sub i, i i = i + 1 break if chr == "]" decode_error(str, i, "expected ']' or ','") if chr !=',' return res, i parse_object = (str, i) -> res = {} i = i + 1 while true do local key, val i = next_char str, i, space_chars, true -- Empty / end of object? if str\sub(i, i) == "}" i = i + 1 break -- Read key if str\sub(i, i) != '"' then decode_error str, i, "expected string for key" key, i = parse str, i -- Read ':' delimiter i = next_char str, i, space_chars, true if str\sub(i, i) != ":" decode_error str, i, "expected ':' after key" i = next_char str, i + 1, space_chars, true -- Read value val, i = parse str, i -- Set res[key] = val -- Next token i = next_char str, i, space_chars, true chr = str\sub i, i i = i + 1 break if chr == "}" decode_error(str, i, "expected '}' or ','") if chr !=',' return res, i char_func_map = { '"': parse_string, "0": parse_number, "1": parse_number, "2": parse_number, "3": parse_number, "4": parse_number, "5": parse_number, "6": parse_number, "7": parse_number, "8": parse_number, "9": parse_number, "-": parse_number, "t": parse_literal, "f": parse_literal, "n": parse_literal, "[": parse_array, "{": parse_object, } parse = (str, idx) -> chr = str\sub idx, idx f = char_func_map[chr] return f(str, idx) if f decode_error str, idx, "unexpected character '" .. chr .. "'" json.decode = (str) -> if type(str) != "string" error "expected argument of type string, got " .. type(str) parse(str, next_char(str, 1, space_chars, true)) json
24.806452
109
0.537841
d474c0f157d8196a2bce1ceab285de4bea7c109b
4,068
--> # libllengua --> Library for managing conlangs -- By daelvn -- 28.04.2019 import schemas, indexes from require "libllengua.db.initialize" import Schema, create, insert, prepare from require "libllengua.db.schema" import runOn, runSeveralOn from require "libllengua.db" import unpackFn, fileExists from require "libllengua.util" import LIBLLENGUA_DB_VERSION from require "libllengua.config" clutch = require "clutch" --> # Llengua --> Llengua is a constructed language framework for the development and management of those. It is based upon the --> functionality of [ConWorkShop](https://conworkshop.info), and seeks to expand on top of that. The general idea is to --> build it as a library, so that it can be used in command-line applications (curses?), webapps (using --> [Lapis](https://leafo.net/lapis)), apps (Java-Lua bridge, perhaps?) and many others. It uses --> [Clutch](https://github.com/akojo/clutch) for managing SQLite databases. --> ## Database structure --> The database uses SQLite, and each language is stored as a single database, so these can be exported and read by --> other libraries and programs. There are some tables destined to certain parts of the database, like the dictionary --> or the phonetic inventory, these are prefixed with `ll_`, where as other user-modifiable content, such as --> conjugation tables, are defined in other database tables prefixed with `conj_` or `user_`. --> ### `ll_metadata` --> Key-value storage for the language. Stores stuff like the language name, the schema version... --> #### Common fields --> - `schema_version`: Version of the schema. --> - `language_name`: Name of the language. --> - `language_code`: Code of the language (xx\_XX) --> - `language_autonym`: Autonym for the language. An autonym is the name of the language in the language itself. --> ### `ll_inventory` --> This table contains the list of sounds and its associated graphemes, it is possible to assign qualities to the --> sounds, custom uppercase versions, allophones and variants, and it supports blends natively. --> ### `ll_categories` --> Comma-separated sound categories for the tools provided by libllengua. --> ### `ll_dictionary` --> Word list for the language. Supports definitions, transliterations, etymology, notes, classes, pronounciation and --> more. --> ### `ll_namebase` --> Keep track of proper names and other kinds of names in your language. With support for gender and notes. --> ### `ll_translations` --> Text or phrase translations for the language. --> ### `ll_grammar_declinations` --> Table that links a part of speech to its declinations, so later it can form conjugation tables. --> # getSchemaVersion --> Returns the schema version. getSchemaVersion = (db) -> (db\queryone "SELECT value FROM ll_metadata WHERE key='schema_version'").value --> # Language --> Creates a new Language structure. Language = unpackFn {"code", "name", "autonym"}, (code, name=(string.lower code), autonym=(string.lower code)) -> db = clutch.open "#{code}.llengua.db" unless fileExists "#{code}.llengua.db" insertMeta = prepare insert schemas.ll_metadata_schema initLanguage = runSeveralOn db initLanguage [create schema for schema in *schemas] initLanguage indexes initLanguage { insertMeta {key: "schema_version", value: LIBLLENGUA_DB_VERSION} insertMeta {key: "language_name", value: name} insertMeta {key: "language_code", value: code} insertMeta {key: "language_autonym", value: autonym} } else error "Schema version mismatch. Expected #{LIBLLENGUA_DB_VERSION}, got #{getSchemaVersion db}" unless (getSchemaVersion db) == LIBLLENGUA_DB_VERSION { :name, :autonym, :code, :db } --> # queryLanguage --> Performs a query on a language. queryLanguage = (lang) -> db = lang.db (sql) -> (varl) -> db\queryall sql, varl --> # finalizeLanguage --> Finalize all edits to the language. finalizeLanguage = (lang) -> lang.db\close! { :Language, :queryLanguage, :finalizeLanguage, :getDatabaseVersion }
50.85
152
0.720747
6cdce2e0c22985b8423aa338bbffda33749e2cc5
822
insulate 'effect', -> import Effect from require 'mae.effect' it 'creates a table with a name', -> a = Effect 'test' assert.equal 'table', type a assert.equal 'test', a.name it 'returns itself with arguments when called', -> a = Effect 'test' b, c = a 'val' assert.equal b, a assert.equal c, 'val' b, c, d = a 'c', 'd' assert.equal b, a assert.equal c, 'c' assert.equal d, 'd' it 'can have a default implementation', -> a = Effect 'test' assert.equal a.defaultimp, nil f = -> a\default f assert.equal a.defaultimp, f insulate 'effect performing', -> maeperform = require 'mae.perform' stub maeperform, 'perform' import Effect from require 'mae.effect' it 'can be performed', -> a = Effect 'test' a\perform 'aza' assert.stub(maeperform.perform).was.called_with a, 'aza'
22.216216
58
0.653285
ecf2f4df9aa676a01b3421098dc07f2a385a1cb9
456
#!/usr/bin/env moon -- vim: ts=2 sw=2 et : package.moonpath = '../src/?.moon;' .. package.moonpath import said,csv,cli,eg from require "fun" import Cols,Data from require "data" eg={} eg.cols = -> x = Cols {"A?", "B","C-"} assert #x.ys == 1 assert x.ys[1].w == -1 assert #x.xs == 1 assert #x.all == 3 eg.data = -> t=Data! [t\add x for x in csv "../etc/data/auto93.csv"] [said c for c in *t.cols.ys] assert 398 == #t.rows cli eg
19.826087
55
0.567982
30587aaf43b771929729a2a778510f678c83c31c
549
describe "transforms run.lua", -> setup -> parse = require('lush.parser') ast = parse -> { A { gui: "italic", blend: 40 }, B { gui: "italic", blend: 40 } } package.loaded["theme"] = ast _G.vim = { inspect: -> "inspect mock" list_slice: (list, s, e) -> [item for item in *list[s,e]] } teardown -> package.loaded["theme"] = nil it "returns lua code", -> to_lua = require("shipwright.transform.lush.to_lua") value = to_lua(require("theme")) assert.is.table(value)
23.869565
56
0.546448
cf4346e8f0b6ddb893277357fc842d6e9553cd6a
3,259
import insert from table local * config_cache = {} -- the final merged config by environment configs = {} -- lists of fns/tables to build config by environment default_config = { server: "nginx" port: "8080" secret: "please-change-me" session_name: "lapis_session" code_cache: "off" num_workers: "1" -- optional: -- max_request_args: nil -- measure_performance: false -- show_queries: false -- mysql: { -- backend: "" -- luasql, resty_mysql -- host: "" -- port: "" -- path: "" -- unix domain socket -- database: "" -- user: "" -- ssl: boolean -- for resty_mysql -- ssl_verify: boolean -- for resty_mysql -- timeout: ms -- for resty_mysql -- max_idle_timeout: ms -- for resty_mysql -- pool_size: integer -- for resty_mysql -- } -- postgres: { -- backend: "" -- host: "" -- port: "" -- database: "" -- user: "" -- } logging: { queries: true requests: true server: true } } merge_set = (t, k, v) -> existing = t[k] if type(v) == "table" if type(existing) != "table" existing = {} t[k] = existing for sub_k, sub_v in pairs v merge_set existing, sub_k, sub_v else t[k] = v set = (conf, k, v) -> if type(k) == "table" for sub_k, sub_v in pairs k merge_set conf, sub_k, sub_v else if type(v) == "function" merge_set conf, k, run_with_scope v, {} else merge_set conf, k, v scope_meta = { __index: (name) => val = _G[name] return val unless val == nil with val = switch name when "set" (...) -> set @_conf, ... when "unset" (...) -> for k in *{...} @_conf[k] = nil when "include" (fn) -> run_with_scope fn, @_conf else (v) -> set @_conf, name, v @[name] = val } config = (environment, fn) -> if type(environment) == "table" for env in *environment config env, fn return configs[environment] or= {} table.insert configs[environment], fn nil reset = (env) -> if env == true for k in pairs configs configs[k] = nil for k in pairs config_cache config_cache[k] = nil else configs[env] = nil config_cache[env] = nil run_with_scope = (fn, conf) -> old_env = getfenv fn env = setmetatable { _conf: conf }, scope_meta setfenv fn, env fn! setfenv fn, old_env conf get_env = -> os.getenv"LAPIS_ENVIRONMENT" or require("lapis.cmd.util").default_environment! get = do loaded_config = false (name=get_env!) -> error "missing environment name" unless name unless loaded_config loaded_config = true success, err = pcall -> require "config" unless success or err\match "module 'config' not found" error err return config_cache[name] if config_cache[name] conf = { k,v for k,v in pairs(default_config) } conf._name = name if fns = configs[name] for fn in *fns switch type(fn) when "function" run_with_scope fn, conf when "table" set conf, fn config_cache[name] = conf conf setmetatable { :get, :config, :merge_set, :default_config, :reset }, { __call: (...) => config ... }
21.162338
80
0.573796
141fc798897723b614d81b64d3aa9e29fb382b7a
948
export modinfo = { type: "command" desc: "Ping" alias: {"ping"} func: (Msg,Speaker) -> rtn = {} fty = {} if #Msg == 0 table.insert(rtn,"Options: plog, log, atmp, ver, sn") elseif Msg\sub(1,2) == "a;" table.insert(rtn,tostring(loadstring(string.format("return %s",Msg\sub(3)))())) elseif Msg == "plog" for i,p in pairs(ConfigSystem("Get", "PlayerLog")) Output(p,{Colors.Red}) elseif Msg == "log" for _,v in pairs(ConfigSystem("Get", "Log")) table.insert(rtn,v) Output("Most Recent here",{Colors.Black}) elseif Msg == "atmp" rtn = [v for _,v in pairs(ConfigSystem("Get", "AttemptedJoinList"))] elseif Msg == "ver" Output(string.format("Version of this script: %s",ConfigSystem("Get", "Version")),{Colors.Orange}) elseif Msg == "sn" Output(string.format("The script's name is: %s",Name),{Colors.Orange}) else table.insert(rtn,Msg) for _,m in pairs(rtn) Output(m,{Color3.new(1,1,1)}) }
32.689655
101
0.624473
bf8b1091f0e1cc16867e8a4038d29b46b6ecd4f5
159
ln = (x) -> ret = 0 last = (x - 1) / (x + 1) sq = last * last for i = 1, 10000, 2 ret += (1 / i) * last last *= sq return 2 * ret return ln
14.454545
26
0.433962
c85f088b3c921373ad87de1df85effbeadf5c5f1
4,847
db = require "lapis.db.mysql" import escape_literal, escape_identifier from db import concat from table import gen_index_name from require "lapis.db.base" append_all = (t, ...) -> for i=1, select "#", ... t[#t + 1] = select i, ... extract_options = (cols) -> options = {} cols = for col in *cols if type(col) == "table" and col[1] != "raw" for k,v in pairs col options[k] = v continue col cols, options entity_exists = (name) -> config = require("lapis.config").get! mysql_config = assert config.mysql, "missing mysql configuration" database = escape_literal assert mysql_config.database name = escape_literal name res = unpack db.select "COUNT(*) as c from information_schema.tables where table_schema = #{database} and table_name = #{name} LIMIT 1" res.c > 0 create_table = (name, columns, opts={}) -> prefix = if opts.if_not_exists "CREATE TABLE IF NOT EXISTS " else "CREATE TABLE " buffer = {prefix, escape_identifier(name), " ("} add = (...) -> append_all buffer, ... for i, c in ipairs columns add "\n " if type(c) == "table" name, kind = unpack c add escape_identifier(name), " ", tostring kind else add c add "," unless i == #columns add "\n" if #columns > 0 add ")" add " ENGINE=", opts.engine if opts.engine add " CHARSET=", opts.charset or "UTF8" add ";" db.query concat buffer drop_table = (tname) -> db.query "DROP TABLE IF EXISTS #{escape_identifier tname};" create_index = (tname, ...) -> index_name = gen_index_name tname, ... columns, options = extract_options {...} buffer = {"CREATE"} append_all buffer, " UNIQUE" if options.unique append_all buffer, " INDEX ", escape_identifier index_name if options.using append_all buffer, " USING ", options.using append_all buffer, " ON ", escape_identifier tname append_all buffer, " (" for i, col in ipairs columns append_all buffer, escape_identifier(col) append_all buffer, ", " unless i == #columns append_all buffer, ")" append_all buffer, ";" db.query concat buffer drop_index = (tname, ...) -> index_name = gen_index_name tname, ... tname = escape_identifier tname db.query "DROP INDEX #{escape_identifier index_name} on #{tname};" add_column = (tname, col_name, col_type) -> tname = escape_identifier tname col_name = escape_identifier col_name db.query "ALTER TABLE #{tname} ADD COLUMN #{col_name} #{col_type}" drop_column = (tname, col_name) -> tname = escape_identifier tname col_name = escape_identifier col_name db.query "ALTER TABLE #{tname} DROP COLUMN #{col_name}" rename_column = (tname, col_from, col_to, col_type)-> assert col_type, "A column type is required when renaming a column" tname = escape_identifier tname col_from = escape_identifier col_from col_to = escape_identifier col_to db.query "ALTER TABLE #{tname} CHANGE COLUMN #{col_from} #{col_to} #{col_type}" rename_table = (tname_from, tname_to) -> tname_from = escape_identifier tname_from tname_to = escape_identifier tname_to db.query "RENAME TABLE #{tname_from} TO #{tname_to}" class ColumnType default_options: { null: false } new: (@base, @default_options) => __call: (length, opts={}) => out = @base if type(length) == "table" opts = length length = nil for k,v in pairs @default_options opts[k] = v unless opts[k] != nil if l = length or opts.length out ..= "(#{l}" if d = opts.decimals out ..= ",#{d})" else out ..= ")" -- type mods if opts.unsigned out ..= " UNSIGNED" if opts.binary out ..= " BINARY" -- column mods unless opts.null out ..= " NOT NULL" if opts.default != nil out ..= " DEFAULT " .. escape_literal opts.default if opts.auto_increment out ..= " AUTO_INCREMENT" if opts.unique out ..= " UNIQUE" if opts.primary_key out ..= " PRIMARY KEY" out __tostring: => @__call {} C = ColumnType types = setmetatable { id: C "INT", auto_increment: true, primary_key: true varchar: C "VARCHAR", length: 255 char: C "CHAR" text: C "TEXT" blob: C "BLOB" bit: C "BIT" tinyint: C "TINYINT" smallint: C "SMALLINT" mediumint: C "MEDIUMINT" integer: C "INT" bigint: C "BIGINT" float: C "FLOAT" double: C "DOUBLE" date: C "DATE" time: C "TIME" timestamp: C "TIMESTAMP" datetime: C "DATETIME" boolean: C "TINYINT", length: 1 }, __index: (key) => error "Don't know column type `#{key}`" { :entity_exists :gen_index_name :types :create_table :drop_table :create_index :drop_index :add_column :drop_column :rename_column :rename_table }
23.643902
81
0.629668
5e15132f2a0be1d530bbccd0236f01a2bcc33149
2,253
import Parser, Compiler from require "etlua" import Widget, Buffer, CONTENT_FOR_PREFIX from require "lapis.html" import locked_fn, release_fn from require "lapis.util.functions" parser = Parser! class BufferCompiler extends Compiler header: => @push "local _tostring, _escape, _b = ...\n", "local _b_buffer = _b.buffer\n", "local _b_i\n" increment: => @push "_b_i = _b.i + 1\n" @push "_b.i = _b_i\n" assign: (...) => @push "_b_buffer[_b_i] = ", ... @push "\n" if ... class EtluaWidget extends Widget @load: (code) => lua_code, err = parser\compile_to_lua code, BufferCompiler fn, err = unless err parser\load lua_code return nil, err if err class TemplateWidget extends EtluaWidget _tpl_fn: fn _tpl_fn: nil -- set by superclass content_for: (name, val) => if val super name, val else if val = @[CONTENT_FOR_PREFIX .. name] @_buffer\write val "" _find_helper: (name) => switch name when "render" return @_buffer\render when "widget" return @_buffer\render_widget if chain = @_get_helper_chain! for h in *chain helper_val = h[name] if helper_val != nil -- call functions in scope of helper value = if type(helper_val) == "function" (...) -> helper_val h, ... else helper_val return value -- look on self val = @[name] if val != nil real_value = if type(val) == "function" (...) -> val @, ... else val return real_value render: (buffer) => @_buffer = if buffer.__class == Buffer buffer else Buffer buffer old_widget = @_buffer.widget @_buffer.widget = @ seen_helpers = {} scope = setmetatable { }, { __index: (scope, key) -> if not seen_helpers[key] seen_helpers[key] = true helper_value = @_find_helper key if helper_value != nil scope[key] = helper_value return helper_value } clone = locked_fn @_tpl_fn parser\run clone, scope, @_buffer release_fn clone @_buffer.widget = old_widget nil { :EtluaWidget, :BufferCompiler }
21.873786
67
0.582779
abc34b2a4329d446d1fb2aa2b968a0be6dedd240
1,825
export script_name = 'JumpScroll' export script_description = 'Save and load subtitle grid scrollbar positions' export script_author = 'CoffeeFlux' export script_version = '2.3.0' export script_namespace = 'Flux.JumpScroll' DependencyControl = require('l0.DependencyControl') { url: 'https://github.com/TypesettingTools/CoffeeFlux-Aegisub-Scripts/blob/master/macros/Flux.TitleCase.moon' feed: 'https://raw.githubusercontent.com/TypesettingTools/CoffeeFlux-Aegisub-Scripts/master/DependencyControl.json' { {'Flux.ScrollHandler', version: '1.0.0', url: 'http://github.com/TypesettingTools/CoffeeFlux-Aegisub-Scripts'} } } ScrollHandler = DependencyControl\requireModules!! ConfigHandler = DependencyControl\getConfigHandler { settings: { macroLength: 3 } } -- adjust for change in coding conventions if ConfigHandler.c.Settings ConfigHandler.c.settings = {} ConfigHandler.c.settings.macroLength = ConfigHandler.c.Settings.macroLength ConfigHandler.c.Settings = nil ConfigHandler\write! settings = ConfigHandler.c.settings dialog = { { class: 'label' label: 'Macro Length:' x: 0 y: 0 } { class: 'intedit' name: 'macroLength' value: settings.macroLength min: 1 max: 10 -- arbitrary value, but one has to exist to work x: 2 y: 0 } } config = -> button, results = aegisub.dialog.display dialog unless button == false settings.macroLength = results.macroLength ConfigHandler\write! macroLength = settings.macroLength macros = { { "Configure", "Launches the configuration dialog", config } } for i = 1, macroLength macros[#macros + 1] = {'Save/' .. i, '', -> ScrollHandler\savePos i} for i = 1, macroLength macros[#macros + 1] = {'Load/' .. i, '', -> ScrollHandler\loadPos i} DependencyControl\registerMacros macros
28.076923
119
0.715068
a680eaa700434f91c958b8f816707bcd6d87c6f6
3,978
-- assorted utilities for moonc command line tool lfs = require "lfs" import split from require "moonscript.util" local * dirsep = package.config\sub 1,1 dirsep_chars = if dirsep == "\\" "\\/" -- windows else dirsep -- similar to mkdir -p mkdir = (path) -> chunks = split path, dirsep local accum for dir in *chunks accum = accum and "#{accum}#{dirsep}#{dir}" or dir lfs.mkdir accum lfs.attributes path, "mode" -- strips excess / and ensures path ends with / normalize_dir = (path) -> path\match("^(.-)[#{dirsep_chars}]*$") .. dirsep -- parse the directory out of a path parse_dir = (path) -> (path\match "^(.-)[^#{dirsep_chars}]*$") -- parse the filename out of a path parse_file = (path) -> (path\match "^.-([^#{dirsep_chars}]*)$") -- converts .moon to a .lua path for calcuating compile target convert_path = (path) -> new_path = path\gsub "%.moon$", ".lua" if new_path == path new_path = path .. ".lua" new_path format_time = (time) -> "%.3fms"\format time*1000 gettime = do local socket -> if socket == nil pcall -> socket = require "socket" unless socket socket = false if socket socket.gettime() else nil, "LuaSocket needed for benchmark" -- compiles file to lua, returns lua code -- returns nil, error on error -- returns true if some option handled the output instead compile_file_text = (text, opts={}) -> parse = require "moonscript.parse" compile = require "moonscript.compile" parse_time = if opts.benchmark assert gettime! tree, err = parse.string text return nil, err unless tree if parse_time parse_time = gettime! - parse_time if opts.show_parse_tree dump = require "moonscript.dump" dump.tree tree return true compile_time = if opts.benchmark gettime! code, posmap_or_err, err_pos = compile.tree tree unless code return nil, compile.format_error posmap_or_err, err_pos, text if compile_time compile_time = gettime() - compile_time if opts.show_posmap import debug_posmap from require "moonscript.util" print "Pos", "Lua", ">>", "Moon" print debug_posmap posmap_or_err, text, code return true if opts.benchmark print table.concat { opts.fname or "stdin", "Parse time \t" .. format_time(parse_time), "Compile time\t" .. format_time(compile_time), "" }, "\n" return nil code write_file = (fname, code) -> mkdir parse_dir fname f, err = io.open fname, "w" unless f return nil, err assert f\write code assert f\write "\n" f\close! "build" compile_and_write = (src, dest, opts={}) -> f = io.open src unless f return nil, "Can't find file" text = assert f\read("*a") f\close! code, err = compile_file_text text, opts if not code return nil, err if code == true return true if opts.print print code return true write_file dest, code is_abs_path = (path) -> first = path\sub 1, 1 if dirsep == "\\" first == "/" or first == "\\" or path\sub(2,1) == ":" else first == dirsep -- calcuate where a path should be compiled to -- target_dir: the directory to place the file (optional, from -t flag) -- base_dir: the directory where the file came from when globbing recursively path_to_target = (path, target_dir=nil, base_dir=nil) -> target = convert_path path if target_dir target_dir = normalize_dir target_dir if base_dir and target_dir -- one directory back head = base_dir\match("^(.-)[^#{dirsep_chars}]*[#{dirsep_chars}]?$") if head start, stop = target\find head, 1, true if start == 1 target = target\sub(stop + 1) if target_dir if is_abs_path target target = parse_file target target = target_dir .. target target { :dirsep :mkdir :normalize_dir :parse_dir :parse_file :convert_path :gettime :format_time :path_to_target :compile_file_text :compile_and_write }
20.611399
77
0.649321
ad0caf29c6bc5645a7856b36b5989733ed504cff
5,190
-- generates lua file containing all the translations compile = require "moonscript.compile" lfs = require "lfs" DIR = "locales/" SOURCE_LOCALE = "en" import types from require "tableshape" argparse = require "argparse" parser = argparse "build_translations.moon", "Build all translations into single file" parser\option "--source-locale", "Which locale is the default", SOURCE_LOCALE parser\option "--dir", "Directory to load translation files from", DIR, (str) -> if str\match "/$" then str else "#{str}/" parser\option "--format", "Output format (lua, json, json_raw)", "lua", types.one_of({"lua", "json", "json_raw"})\transform parser\flag "--nested", "Nest keys", false args = parser\parse [v for _, v in ipairs arg] json = require "cjson" output = { } flatten_nested = (t, prefix="", out={}) -> for k,v in pairs t if type(v) == "table" flatten_nested v, "#{prefix}#{k}.", out else out["#{prefix}#{k}"] = v out empty_object = types.equivalent {} merge_tables = (target, to_merge) -> assert type(target) == "table", "target for merge is not table" assert type(to_merge) == "table", "table to merge is not table" for k, v in pairs to_merge if target[k] if type(target[k]) == "string" error "can't merge into string: #{k}" merge_tables target[k], v else target[k] = v visit_directory = (dir) -> for file in assert lfs.dir dir continue if file\match "^%.+$" path = "#{dir}#{file}" switch lfs.attributes path, "mode" when "directory" visit_directory "#{path}/" when "file" name = file\match "^([%w_]+).json$" continue unless name handle = assert io.open path contents = assert handle\read "*a" object = json.decode contents if empty_object object continue unless args.nested object = flatten_nested object if output[name] merge_tables output[name], object else output[name] = object visit_directory args.dir -- summarize completion if args.format == "lua" -- remove any plural suffixes normalize_key = (key) -> (key\gsub("_%d+$", "")\gsub("_plural$", "")) source_translations = assert output[args.source_locale], "missing source locale: #{args.source_locale}" source_keys = {normalize_key(key), true for key in pairs source_translations} source_keys = [key for key in pairs source_keys] for locale, translations in pairs output found = 0 translated_keys = {normalize_key(key), true for key in pairs output when type(key) == "string"} for key in *source_keys if translations[key] found += 1 table.insert translations, { :found completion_ratio: found / #source_keys } import parse_tags, chunk_to_syntax from require "helpers.compiler" import types from require "tableshape" simple_string = types.shape { types.string } string_to_syntax = (str) -> chunks = parse_tags\match str unless chunks error "failed to parse string: #{str}" if simple_string chunks return nil lines = [chunk_to_syntax chunk for chunk in *chunks] {"fndef", {{"text_fn"}, {"variables"}}, {}, "slim", lines} encode_value = (v) -> switch type(v) when "number" {"number", v} when "table" keys = [k for k in pairs v] table.sort keys, (a, b) -> if type(a) != type(b) if type(a) == "number" return true if type(b) == "number" return false else return a < b {"table", for k in *keys if type(k) == "number" { encode_value v[k] } else k = tostring k { if k\match "%." {"string", '"', k} else {"key_literal", k} encode_value v[k] } } else str = tostring v if fn = string_to_syntax str return fn delim = if str\match '"' if str\match "'" '[==[' else "'" else '"' {"string", delim, v} switch args.format when "json_raw" print json.encode output when "json" local convert_syntax convert_syntax = types.one_of { types.equivalent({""}) / nil types.shape({ types.string }) / (t) -> t[1] types.array_of types.one_of { types.string types.shape({ variable: types.string }, open: true) / (v) -> {"v", v.variable} types.shape({ tag: types.string contents: types.nil + types.proxy -> convert_syntax }, open: true) / (v) -> {"t", v.tag, v.contents} } } import parse_tags from require "helpers.compiler" local strings_level strings_level = types.map_of types.string, types.one_of { types.string / parse_tags\match * convert_syntax if args.nested types.proxy -> strings_level } document = types.map_of types.string, strings_level print json.encode assert document\transform output when "lua" print (compile.tree { {"return", encode_value output} }) else error "unknown format: #{args.format}"
25.441176
123
0.594605
9289c0e087e0ce07e30f382548f76ea7648ae881
920
ffi = require "ffi" requireffi = require "requireffi.requireffi" ffi.cdef [[ ___INCLUDE___ ]] BM, loadedLibraryPath = requireffi "BM.BadMutex.BadMutex" BMVersion = 0x000100 libVer = BM.version! if libVer < BMVersion or math.floor(libVer/65536%256) > math.floor(BMVersion/65536%256) error "Library version mismatch. Wanted #{BMVersion}, got #{libVer}." local BadMutex BadMutex = { lock: -> BM.lock! tryLock: -> return BM.try_lock! unlock: -> BM.unlock! version: 0x000103 __depCtrlInit: ( DependencyControl ) -> BadMutex.version = DependencyControl { name: "BadMutex", version: BadMutex.version, description: "A global mutex.", author: "torque", url: "https://github.com/TypesettingTools/ffi-experiments", moduleName: "BM.BadMutex", feed: "https://raw.githubusercontent.com/TypesettingTools/ffi-experiments/master/DependencyControl.json", } :loadedLibraryPath } return BadMutex
23.589744
108
0.727174
9c1e5912ae944a4172a3dc5dd4acdede89f46772
450
-- Copyright 2014-2015 The Howl Developers -- License: MIT (see LICENSE.md at the top-level directory of the distribution) require 'ljglibs.gio.input_stream' ffi = require 'ffi' core = require 'ljglibs.core' {:ref_ptr} = require 'ljglibs.gobject' C = ffi.C core.define 'GUnixInputStream < GInputStream', { properties: { fd: 'gint' close_fd: 'gboolean' } }, (t, fd, close_fd = true) -> ref_ptr C.g_unix_input_stream_new fd, close_fd
23.684211
79
0.706667
4dd5e8eaebd2cda78152b6a3c5b4d04b9b6c1c93
306
import Widget from require "lapis.html" class Estate extends Widget content: => dl class: "details", -> dt "build" dd @e.build dt "comment" dd @e.comment dl class: "address", -> dt "street" dd @a.street dt "city" dd @a.zipcode .. " " .. @a.city
18
39
0.53268
f10da7bc91f16765c605fb5c38de1648acb93721
139
if ngx require "lapis.nginx.http" elseif pcall require, "http.compat.socket" require "http.compat.socket" else require "socket.http"
19.857143
42
0.748201
64b5430ca636d2c866b7da5bf2161bcdd6e0fe2b
17,796
-- Copyright 2012-2015 The Howl Developers -- License: MIT (see LICENSE.md at the top-level directory of the distribution) import app, activities, breadcrumbs, Buffer, command, config, bindings, bundle, interact, signal, mode, Project from howl import ActionBuffer, ProcessBuffer, BufferPopup, StyledText from howl.ui import Process from howl.io serpent = require 'serpent' get_project_root = -> buffer = app.editor and app.editor.buffer file = buffer.file or buffer.directory error "No file associated with the current view" unless file project = Project.get_for_file file error "No project associated with #{file}" unless project return project.root belongs_to_project = (buffer, project_root) -> file = buffer.file or buffer.directory return false unless file project = Project.for_file file return false unless project return project.root == project_root command.register name: 'quit', description: 'Quit the application' handler: -> howl.app\quit! command.alias 'quit', 'q' command.register name: 'save-and-quit', description: 'Save modified buffers and quit the application' handler: -> with howl.app \quit! if \save_all! command.alias 'save-and-quit', 'wq' command.register name: 'quit-without-save', description: 'Quit the application, disregarding any modified buffers' handler: -> howl.app\quit true command.alias 'quit-without-save', 'q!' command.register name: 'run' description: 'Run a command' handler: command.run command.register name: 'new-buffer', description: 'Opens a new buffer' handler: -> breadcrumbs.drop! app.editor.buffer = howl.app\new_buffer! command.register name: 'switch-buffer', description: 'Switch to another buffer' input: interact.select_buffer handler: (buf) -> breadcrumbs.drop! app.editor.buffer = buf command.register name: 'project-switch-buffer', description: 'Switch to another buffer in current project' input: -> project_root = get_project_root! return unless project_root interact.select_buffer get_buffers: -> [buf for buf in *app.buffers when belongs_to_project buf, project_root] title: "Buffers under #{project_root}" handler: (buf) -> breadcrumbs.drop! app.editor.buffer = buf command.register name: 'buffer-reload', description: 'Reload the current buffer from file' handler: -> buffer = app.editor.buffer if buffer.modified unless interact.yes_or_no prompt: 'Buffer is modified, reload anyway? ' log.info "Not reloading; buffer is untouched" return buffer\reload true log.info "Buffer reloaded from file" command.register name: 'switch-to-last-hidden-buffer', description: 'Switch to the last active hidden buffer' handler: -> for buffer in *howl.app.buffers if not buffer.showing breadcrumbs.drop! app.editor.buffer = buffer return _G.log.error 'No hidden buffer found' command.register name: 'set', description: 'Set a configuration variable' input: interact.get_variable_assignment handler: (variable_assignment) -> target = variable_assignment.target target[variable_assignment.var] = variable_assignment.value _G.log.info ('"%s" is now set to "%s" for %s')\format variable_assignment.var, variable_assignment.value, variable_assignment.scope_name command.register name: 'describe-key', description: 'Show information for a key' handler: -> buffer = ActionBuffer! buffer.title = 'Key watcher' buffer\append 'Press any key to show information for it (press escape to quit)..\n\n', 'string' editor = howl.app\add_buffer buffer editor.cursor\eof! bindings.capture (event, source, translations) -> buffer.lines\delete 3, #buffer.lines buffer\append 'Key translations (usable from bindings):\n', 'comment' buffer\append serpent.block translations, comment: false buffer\append '\n\nKey event:\n', 'comment' buffer\append serpent.block event, comment: false bound_commands = {} for t in *translations cmd = bindings.action_for t cmd = '<function>' if typeof(cmd) == 'function' bound_commands[t] = cmd buffer\append '\n\nBound command:\n', 'comment' buffer\append serpent.block bound_commands, comment: false if event.key_name == 'escape' buffer.lines[1] = '(Snooping done, close this buffer at your leisure)' buffer\style 1, #buffer, 'comment' buffer.modified = false else return false command.register name: 'describe-signal', description: 'Describe a given signal' input: interact.select_signal handler: (signal_name) -> def = signal.all[signal_name] error "Unknown signal '#{signal_name}'" unless def buffer = with ActionBuffer! .title = "Signal: #{signal_name}" \append "#{def.description}\n\n" \append "Parameters:" params = def.parameters if not params buffer\append "None" else buffer\append '\n\n' buffer\append StyledText.for_table [ { name, desc } for name, desc in pairs params ], { { header: 'Name', style: 'string'}, { header: 'Description', style: 'comment' } } buffer.read_only = true buffer.modified = false howl.app\add_buffer buffer command.register name: 'bundle-unload' description: 'Unload a specified bundle' input: interact.select_loaded_bundle handler: (name) -> log.info "Unloading bundle '#{name}'.." bundle.unload name log.info "Unloaded bundle '#{name}'" command.register name: 'bundle-load' description: 'Load a specified, currently unloaded, bundle' input: interact.select_unloaded_bundle handler: (name) -> log.info "Loading bundle '#{name}'.." bundle.load_by_name name log.info "Loaded bundle '#{name}'" command.register name: 'bundle-reload' description: 'Reload a specified bundle' input: interact.select_loaded_bundle handler: (name) -> log.info "Reloading bundle '#{name}'.." bundle.unload name if _G.bundles[name] bundle.load_by_name name log.info "Reloaded bundle '#{name}'" command.register name: 'bundle-reload-current' description: 'Reload the last active bundle (with files open)' handler: -> for buffer in *app.buffers bundle_name = buffer.file and bundle.from_file(buffer.file) or nil if bundle_name command.bundle_reload bundle_name return log.warn 'Could not find any currently active bundle to reload' command.register name: 'buffer-grep' description: 'Show buffer lines containing boundary and exact matches in real time' input: -> command_line = app.window.command_line command_line\add_keymap binding_for: ['buffer-grep']: -> command_line\switch_to 'buffer-grep-regex' command_line\add_help key_for: 'buffer-grep' action: 'Switch to regular expression search' buffer = app.editor.buffer return interact.select_line title: "Buffer grep in #{buffer.title}" editor: app.editor lines: buffer.lines handler: (selection) -> breadcrumbs.drop! app.editor.cursor\move_to line: selection.line.nr, column: selection.column command.register name: 'buffer-grep-exact' description: 'Show buffer lines containing exact matches in real time' input: -> command_line = app.window.command_line command_line\add_keymap binding_for: ['buffer-grep']: -> command_line\switch_to 'buffer-grep' command_line\add_help key_for: 'buffer-grep' action: 'Switch to default search' buffer = app.editor.buffer return interact.select_line title: "Buffer grep exact in #{buffer.title}" editor: app.editor lines: buffer.lines find: (query, text) -> start_pos, end_pos = text\ufind query, 1, true if start_pos return {{start_pos, end_pos - start_pos + 1}} handler: (selection) -> breadcrumbs.drop! app.editor.cursor\move_to line: selection.line.nr, column: selection.column command.register name: 'buffer-grep-regex' description: 'Show buffer lines containing regular expression matches in real time' input: -> command_line = app.window.command_line command_line\add_keymap binding_for: ['buffer-grep']: -> command_line\switch_to 'buffer-grep-exact' command_line\add_help key_for: 'buffer-grep' action: 'Switch to exact search' buffer = app.editor.buffer return interact.select_line title: "Buffer grep regex in #{buffer.title}" editor: app.editor lines: buffer.lines find: (query, text) -> ok, rex = pcall -> r(query) return unless ok start_pos, end_pos = rex\find text if start_pos return {{start_pos, end_pos - start_pos + 1}} handler: (selection) -> breadcrumbs.drop! app.editor.cursor\move_to line: selection.line.nr, column: selection.column command.register name: 'buffer-structure' description: 'Show the structure for the current buffer' input: -> buffer = app.editor.buffer lines = buffer.mode\structure app.editor cursor_lnr = app.editor.cursor.line local selected_line for line in *lines if line.nr <= cursor_lnr selected_line = line if line.nr >= cursor_lnr break return interact.select_line title: "Structure for #{buffer.title}" :lines :selected_line handler: (selection) -> breadcrumbs.drop! app.editor.cursor\move_to line: selection.line.nr, column: selection.column command.register name: 'navigate-back' description: 'Goes back to the last location recorded' handler: -> if breadcrumbs.previous breadcrumbs.go_back! log.info "navigate: now at #{breadcrumbs.location} of #{#breadcrumbs.trail}" else log.info "No previous location recorded" command.register name: 'navigate-forward' description: 'Goes to the next location recorced' handler: -> if breadcrumbs.next breadcrumbs.go_forward! log.info "navigate: now at #{breadcrumbs.location} of #{#breadcrumbs.trail}" else log.info "No next location recorded" ----------------------------------------------------------------------- -- Howl eval commands ----------------------------------------------------------------------- do_howl_eval = (load_f, mode_name, transform_f) -> editor = app.editor text = editor.selection.empty and editor.current_line.text or editor.selection.text text = transform_f and transform_f(text) or text f = assert load_f text ret = { pcall f } if ret[1] out = '' for i = 2, #ret out ..= "\n#{serpent.block ret[i], comment: false}" if editor.popup log.info "(Eval) => #{ret[2]}" else buf = Buffer mode.by_name mode_name buf.text = "-- Howl eval (#{mode_name}) =>#{out}" editor\show_popup BufferPopup buf, scrollable: true howl.clipboard.push out else log.error "(ERROR) => #{ret[2]}" command.register name: 'howl-lua-eval' description: 'Eval the current line or selection as Lua' handler: -> do_howl_eval load, 'lua', (text) -> unless text\match 'return%s' text = if text\find '\n' text\gsub "\n([^\n]+)$", "\n return %1" else "return #{text}" text command.register name: 'howl-moon-eval' description: 'Eval the current line or selection as Moonscript' handler: -> moonscript = require('moonscript') transform = (text) -> initial_indent = text\match '^([ \t]*)%S' if initial_indent -- remove the initial indent from all lines if any lines = [l\gsub("^#{initial_indent}", '') for l in text\gmatch('[^\n]+')] text = table.concat lines, '\n' moonscript.loadstring text do_howl_eval transform, 'moonscript' command.register name: 'howl-moon-print' description: 'Compile and show the Lua for the current buffer or selection' handler: -> moonscript = require('moonscript.base') editor = app.editor buffer = editor.buffer title = "#{buffer.title} (compiled to Lua)" text = buffer.text unless editor.selection.empty title = "#{buffer.title} (Lua - from selection)" text = editor.selection.text lua, err = moonscript.to_lua text local buf if not lua buf = ActionBuffer! buf\append howl.ui.markup.howl "<error>#{err}</error>" else buf = Buffer mode.by_name 'lua' buf.text = lua buf.title = title buf.modified = false if #buf.lines > 20 breadcrumbs.drop! editor.buffer = buf else buf\insert "-- #{title}\n", 1 editor\show_popup BufferPopup buf, scrollable: true ----------------------------------------------------------------------- -- Launch commands ----------------------------------------------------------------------- launch_cmd = (working_directory, cmd) -> shell = howl.sys.env.SHELL or '/bin/sh' p = Process { :cmd, :shell, read_stdout: true, read_stderr: true, working_directory: working_directory, } breadcrumbs.drop! buffer = ProcessBuffer p editor = app\add_buffer buffer editor.cursor\eof! buffer\pump! get_project = -> buffer = app.editor and app.editor.buffer file = buffer.file or buffer.directory error "No file associated with the current view" unless file project = Project.get_for_file file error "No project associated with #{file}" unless project return project command.register name: 'project-exec', description: 'Run an external command from within the project directory' input: -> interact.get_external_command path: get_project!.root handler: launch_cmd command.register name: 'project-build' description: 'Run the command in config.project_build_command from within the project directory' handler: -> launch_cmd get_project!.root, (app.editor and app.editor.buffer.config or config).project_build_command command.register name: 'exec', description: 'Run an external command' input: (path=nil) -> interact.get_external_command :path handler: launch_cmd command.register name: 'save-config' description: 'Save the current configuration' handler: -> config.save_config! log.info 'Configuration saved' config.define name: 'project_build_command' description: 'The command to execute when project-build is run' default: 'make' type_of: 'string' ----------------------------------------------------------------------- -- File search commands ----------------------------------------------------------------------- config.define name: 'file_search_hit_display' description: 'How to display file search hits in the list' default: 'rich' type_of: 'string' options: -> { {'plain', 'Display as plain unicolor strings'}, {'highlighted', 'Highlight search terms in hits'} , {'rich', 'Show syntax highlighted snippets with highlighted terms'}, } file_search_hit_mt = { __tostyled: (item) -> text = item.text m = mode.for_file(item.match.file) if m and m.lexer styles = m.lexer(text) return StyledText text, styles text __tostring: (item) -> item.text } file_search_hit_to_location = (match, search, display_as) -> hit_display = if display_as == 'rich' setmetatable {text: match.message, :match}, file_search_hit_mt else match.message path = match.path\truncate(50, omission_prefix: '..') loc = { howl.ui.markup.howl "<comment>#{path}</>:<number>#{match.line_nr}</>" hit_display, file: match.file, line_nr: match.line_nr, column: match.column } search = search.ulower s, e = match.message.ulower\ufind(search, 1, true) unless s s, e = match.message\ufind((r(search))) if loc.column loc.highlights = { { byte_start_column: loc.column, byte_end_column: loc.column + #search } } elseif s loc.highlights = { { start_column: s, end_column: e + 1 } } if s and display_as != 'plain' loc.item_highlights = { nil, { {byte_start_column: s, count: e - s + 1} } } loc command.register name: 'project-file-search', description: 'Searches files in the the current project' input: (...) -> editor = app.editor search = nil whole_word = false unless app.window.command_line.showing if editor.selection.empty search = app.editor.current_context.word.text whole_word = true unless search.is_empty else search = editor.selection.text if not search or search.is_empty search = interact.read_text! if not search or search.is_empty log.warn "No search query specified" return project = get_project! file_search = howl.file_search matches, searcher = file_search.search project.root, search, :whole_word unless #matches > 0 log.error "No matches found for '#{search}'" return matches = file_search.sort matches, project.root, search, editor.current_context display_as = project.config.file_search_hit_display status = "Loaded 0 out of #{#matches} locations.." cancel = false locations = activities.run { title: "Loading #{#matches} locations..", status: -> status cancel: -> cancel = true }, -> return for i = 1, #matches if i % 1000 == 0 break if cancel status = "Loaded #{i} out of #{#matches}.." activities.yield! m = matches[i] file_search_hit_to_location(m, search, display_as) selected = interact.select_location title: "#{#matches} matches for '#{search}' in #{project.root.short_path} (using #{searcher.name} searcher)" items: locations selected and selected.selection handler: (loc) -> if loc app\open loc
29.959596
140
0.660879
91649feae5768b65e6699eb63cfd09851974433d
24,721
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) -> old expected, get_queries! 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 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 "id" = 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 "id" 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 "id" 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)]] }
24.476238
108
0.565875
07eb66d198f0b5df0eef0030e46b447258f33e35
4,901
db = require "lapis.db.postgres" import gen_index_name from require "lapis.db.base" import escape_literal, escape_identifier, is_raw from db import concat from table unpack = unpack or table.unpack append_all = (t, ...) -> for i=1, select "#", ... t[#t + 1] = select i, ... extract_options = (cols) -> options = {} cols = for col in *cols if type(col) == "table" and not is_raw(col) for k,v in pairs col options[k] = v continue col cols, options entity_exists = (name) -> name = escape_literal name res = unpack db.select "COUNT(*) as c from pg_class where relname = #{name}" res.c > 0 create_table = (name, columns, opts={}) -> prefix = if opts.if_not_exists "CREATE TABLE IF NOT EXISTS " else "CREATE TABLE " buffer = {prefix, escape_identifier(name), " ("} add = (...) -> append_all buffer, ... for i, c in ipairs columns add "\n " if type(c) == "table" name, kind = unpack c add escape_identifier(name), " ", tostring kind else add c add "," unless i == #columns add "\n" if #columns > 0 add ")" db.query concat buffer create_index = (tname, ...) -> index_name = gen_index_name tname, ... columns, options = extract_options {...} prefix = if options.unique "CREATE UNIQUE INDEX " else "CREATE INDEX " buffer = {prefix} append_all buffer, "CONCURRENTLY " if options.concurrently append_all buffer, "IF NOT EXISTS " if options.if_not_exists append_all buffer, escape_identifier(index_name), " ON ", escape_identifier tname if options.method append_all buffer, " USING ", options.method append_all buffer, " (" for i, col in ipairs columns append_all buffer, escape_identifier col append_all buffer, ", " unless i == #columns append_all buffer, ")" if options.tablespace append_all buffer, " TABLESPACE ", escape_identifier options.tablespace if options.where append_all buffer, " WHERE ", options.where if options.when error "did you mean create_index `where`?" db.query concat buffer drop_index = (...) -> index_name = gen_index_name ... _, options = extract_options {...} buffer = { "DROP INDEX IF EXISTS #{escape_identifier index_name}" } if options.cascade append_all buffer, " CASCADE" db.query concat buffer drop_table = (tname) -> db.query "DROP TABLE IF EXISTS #{escape_identifier tname}" add_column = (tname, col_name, col_type) -> tname = escape_identifier tname col_name = escape_identifier col_name db.query "ALTER TABLE #{tname} ADD COLUMN #{col_name} #{col_type}" drop_column = (tname, col_name) -> tname = escape_identifier tname col_name = escape_identifier col_name db.query "ALTER TABLE #{tname} DROP COLUMN #{col_name}" rename_column = (tname, col_from, col_to) -> tname = escape_identifier tname col_from = escape_identifier col_from col_to = escape_identifier col_to db.query "ALTER TABLE #{tname} RENAME COLUMN #{col_from} TO #{col_to}" rename_table = (tname_from, tname_to) -> tname_from = escape_identifier tname_from tname_to = escape_identifier tname_to db.query "ALTER TABLE #{tname_from} RENAME TO #{tname_to}" class ColumnType default_options: { null: false } new: (@base, @default_options) => __call: (opts) => out = @base for k,v in pairs @default_options -- don't use the types default default since it's not an array continue if k == "default" and opts.array opts[k] = v unless opts[k] != nil if opts.array for i=1,type(opts.array) == "number" and opts.array or 1 out ..= "[]" unless opts.null out ..= " NOT NULL" if opts.default != nil out ..= " DEFAULT " .. escape_literal opts.default if opts.unique out ..= " UNIQUE" if opts.primary_key out ..= " PRIMARY KEY" out __tostring: => @__call @default_options class TimeType extends ColumnType __tostring: ColumnType.__tostring __call: (opts) => base = @base @base = base .. " with time zone" if opts.timezone with ColumnType.__call @, opts @base = base C = ColumnType T = TimeType types = setmetatable { serial: C "serial" varchar: C "character varying(255)" text: C "text" time: T "timestamp" date: C "date" enum: C "smallint", null: false integer: C "integer", null: false, default: 0 numeric: C "numeric", null: false, default: 0 real: C "real", null: false, default: 0 double: C "double precision", null: false, default: 0 boolean: C "boolean", null: false, default: false foreign_key: C "integer" }, __index: (key) => error "Don't know column type `#{key}`" { :types, :create_table, :drop_table, :create_index, :drop_index, :add_column, :drop_column, :rename_column, :rename_table, :entity_exists, :gen_index_name }
25.262887
78
0.651704
c669fadad3f7558a20cfc1cc832390d11c259de3
1,296
Entity = require('lib/entities/entity') { :Vector } = require('vendor/hug/lib/geo') Shape = require('lib/geo/shape') Animation = require('lib/display/animation') AnimationList = require('lib/display/animation-list') Input = require('lib/input/input') Queue = require('vendor/hug/lib/queue') class Player extends Entity new: (...) => super(...) maxSpeed = 100 runSpeed = maxSpeed * 2 @addMultiple({ :maxSpeed, :runSpeed, commandQueue: Queue(), Input({ left: { 'key:left', 'key:a', 'key:h', 'axis:leftx-', 'button:dpleft' }, right: { 'key:right', 'key:d', 'key:l', 'axis:leftx+', 'button:dpright' }, up: { 'key:up', 'key:w', 'key:k', 'axis:lefty-', 'button:dpup' }, down: { 'key:down', 'key:s', 'key:j', 'axis:lefty+', 'button:dpdown' }, run: { 'key:lshift', 'key:rshift', 'button:b' }, attack: { 'key:space', 'button:a' }, use: { 'key:return', 'button:x' } }), AnimationList(@, { default: Animation({ 1, 1 }, { duration: 2 }), NORTH: Animation({ '5-6', 1 }), SOUTH: Animation({ '1-2', 1 }), WEST: Animation({ '3-4', 1 }), EAST: Animation({ '7-8', 1 }, { offset: Vector(45, 4) }), }, { image: 'ff4-characters.png', shape: Shape(16, 16), offset: Vector(46, 4), border: 1, duration: 0.2 }) })
29.454545
78
0.56713