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
61ba2fee8b9f142bace4c9fda133ec28d6602f13
2,354
export gamera = require "kit/lib/gamera" math.randomseed os.time! export game = { game_objects: {} ---------------------------------- -- level loading *hash-map* ---------------------------------- map_stuff: { "player": {r: 255, g: 0, b: 0} "block": {r: 0, g: 0, b: 0} } ---------------------------------- -- grid parameters ---------------------------------- grid_size: 16 ---------------------------------- -- levels ---------------------------------- level: 1 levels: { [1]: "whatsyourask" } level_map: {} } game.load = -> with game .game_objects = {} .camera = gamera.new 0, 0, love.graphics.getWidth!, love.graphics.getHeight! .camera\setWindow 0, 0, love.graphics.getWidth!, love.graphics.getHeight! .camera\setScale 3 .load_level "assets/levels/#{.levels[.level]}.png" game.update = (dt) -> with game for g in *.game_objects continue if g == nil g\update dt if g.update game.draw = -> with game .camera\draw -> .draw_world! game.draw_world = -> with game for g in *.game_objects continue if g == nil g\draw! if g.draw game.load_level = (path) -> with game image = love.image.newImageData path for x = 1, image\getWidth! row = {} for y = 1, image\getHeight! rx, ry = x - 1, y - 1 r, g, b = image\getPixel rx, ry ref = { id: -1 } for k, v in pairs .map_stuff if r == v.r and g == v.g and b == v.b ref = .make_entity k, .grid_size * rx, .grid_size * ry row[y] = ref .level_map[x] = row game.check_map = (x, y, ox, oy) -> with game return .level_map[(ox / .grid_size) + x][(oy / .grid_size) + y].id == 1 game.make_entity = (id, x, y) -> import Player, Block from require "src/entities" switch id when "player" player = Player x, y ---------------------------------- -- do things with player here ... ---------------------------------- game.player = player table.insert game.game_objects, player return player when "block" block = Block x, y table.insert game.game_objects, block return block love.keypressed = (key) -> with game for g in *.game_objects continue if g == nil g\press key if g.press game
21.796296
80
0.495752
8e17995095ab4cbba9ee82734007d0b1797d9cab
603
import new from require 'buffet.resty' import is_closed from require 'buffet' describe 'setkeepalive()', -> it 'should close the buffet and return 1 if not closed', -> bf = new 'deadbeef' n, ok = nargs bf\setkeepalive! assert.are.equal 1, n assert.are.equal 1, ok assert.is.true is_closed bf it 'should return error if closed', -> bf = new 'deadbeef' bf\close! n, ok, err = nargs bf\setkeepalive! assert.are.equal 2, n assert.is.nil ok assert.are.equal 'closed', err assert.is.true is_closed bf
27.409091
63
0.603648
4c60939a93f8b0875150153cd866629c4bce6dc6
388
import Widget from require "lapis.html" class JumbotronWidget extends Widget content: => @content_for 'jumbotron', -> div class:'jumbotron jumbotron-fluid', -> div class:'container', -> h1 class:'display-4', "Hello Traveler!" p class:'lead', "Welcome on this website, it's far from completed but feel free to take a look :)" { :JumbotronWidget }
32.333333
108
0.654639
765f2ccecaae4b467e311f4e0702b5b0e4a21108
1,387
createRT = (name) -> texture = GetRenderTargetEx name, Moonpanel.Canvas.Resolution, Moonpanel.Canvas.Resolution, RT_SIZE_OFFSCREEN, MATERIAL_RT_DEPTH_SHARED, 2, CREATERENDERTARGETFLAGS_HDR, IMAGE_FORMAT_RGBA8888 material = CreateMaterial name, "UnlitGeneric", ["$basetexture"]: texture\GetName! ["$translucent"]: 1 ["$vertexcolor"]: 1 ["$vertexalpha"]: 1 texture, material Moonpanel.Canvas.BakePages = => @__allocatedRTs = {} @__freeRTs = util.Stack! @__rtTokens = {} for page = 1, 100 texture, material = createRT "TheMP RT #{page}" @__freeRTs\Push { :texture :material } texture, material = createRT "TheMP RT Aux" @__auxiliaryRT = { :texture :material } Moonpanel.Canvas.GetAuxiliaryRT = => @BakePages! if not @__auxiliaryRT @__auxiliaryRT Moonpanel.Canvas.AllocateRT = => @BakePages! if not @__freeRTs return if 0 >= @__freeRTs\Size! rt = @__freeRTs\Pop! @__allocatedRTs[rt] = rt proxy = newproxy true token = tostring proxy @__rtTokens[token] = true alloc = { :token :proxy :rt } with getmetatable proxy .__gc = -> @DeallocateRT alloc alloc Moonpanel.Canvas.DeallocateRT = (alloc) => if @__rtTokens[alloc.token] @__rtTokens[alloc.token] = nil @__allocatedRTs[alloc.rt] = nil @__freeRTs\Push alloc.rt Moonpanel.Canvas.IsRTAllocated = (alloc) => @__rtTokens[alloc.token] or false
18.493333
77
0.695025
72fb62700fd3197dab0f94508b2bcbd22534204d
700
import NewExpr,NewExprVal,ExprIndex,ExprToString,AddItem from require "Data.API.Expression" for item in *{ { Name:"EffectName" Text:"Effect Name" Type:"EffectName" MultiLine:false TypeIgnore:false Group:"Special" Desc:"A name for effect." CodeOnly:true ToCode:=> @[2] Create:NewExprVal "InvalidName" Args:false __index:ExprIndex __tostring:ExprToString } { Name:"EffectByName" Text:"Get Effect" Type:"Effect" MultiLine:false TypeIgnore:false Group:"Effect" Desc:"Get effect [EffectName] from scene." CodeOnly:false ToCode:=> "Effect.#{ @[2] }" Create:NewExpr "EffectName" Args:false __index:ExprIndex __tostring:ExprToString } } AddItem item
19.444444
91
0.714286
768c9430ea4d880edd194f51225440b144b222d7
488
-- Copyright 2012-2014 The Howl Developers -- License: MIT (see LICENSE.md at the top-level directory of the distribution) ffi = require 'ffi' require 'ljglibs.cdefs.pango' core = require 'ljglibs.core' C = ffi.C core.define 'PangoContext', { properties: { font_description: { get: => C.pango_context_get_font_description @ set: (description) => print "set font description for context" C.pango_context_set_font_description @, description } } }
24.4
79
0.692623
2f8fda7ca6e4da718ef2e011020006590f54491e
79
one = io.read! two = io.read! three = io.read! print one print two print three
11.285714
16
0.696203
1a4f170fd352d99e0b31a040dae861bb7413c5b3
988
#!/usr/bin/env moon require"buildah".from "docker://docker.io/library/debian:buster-slim", "zerotier" SCRIPT "rmusers" SCRIPT "rmsuid" COPY "01_nodoc", "/etc/dpkg/dpkg.cfg.d/01_nodoc" RUN "cp --remove-destination /usr/share/zoneinfo/UTC /etc/localtime" APT_GET "update" APT_GET "full-upgrade" APT_GET "install curl gnupg dirmngr ca-certificates" COPY "zerotier.gpg" RUN "apt-key add /zerotier.gpg" RM "/zerotier.gpg" COPY "zerotier.list", "/etc/apt/sources.list.d/zerotier.list" APT_GET "update" APT_GET "install zerotier-one=1.6.4" APT_GET "purge curl gnupg dirmngr ca-certificates" APT_PURGE "sysvinit-utils bash tzdata e2fsprogs e2fslibs util-linux mount login hostname fdisk bsdutils findutils" APT_GET "--purge autoremove" APT_GET "autoclean" WIPE "docs" WIPE "directories" WIPE "perl" WIPE "debian" WIPE "userland" WIPE "sh" ENTRYPOINT "/usr/sbin/zerotier-one" PUSH "zerotier-one", "1.6.4"
35.285714
114
0.69332
3d67c5e4e11a411efc941d3d37f2cda290b9759c
4,874
-- custom url parsing implementation -- since there are so many that does not meet requirements - wtf? util = require "mooncrafts.util" log = require "mooncrafts.log" import insert from table import url_unescape from util local * re_match = string.match tonumber = tonumber setmetatable = setmetatable string_split = util.string_split table_insert = table.insert string_sub = string.sub trim = util.trim url_escape = util.url_escape string_join = table.concat string_gsub = string.gsub strlen = string.len ports = { acap: 674, cap: 1026, dict: 2628, ftp: 21, gopher: 70, http: 80, https: 443, iax: 4569, icap: 1344, imap: 143, ipp: 631, ldap: 389, mtqp: 1038, mupdate: 3905, news: 2009, nfs: 2049, nntp: 119, rtsp: 554, sip: 5060, snmp: 161, telnet: 23, tftp: 69, vemmi: 575, afs: 1483, jms: 5673, rsync: 873, prospero: 191, videotex: 516 } default_port = (scheme) -> tostring(ports[scheme]) if ports[scheme] split = (url, pathOnly=false) -> assert(url, "url parameter is required") url = trim(url) scheme, hostp, path, queryp = string.match(url, "(%a*)://([^/]*)([^?#]*)?*(.*)") user, pass, port, query, authority, host, fragment = nil, nil, nil, nil, nil, nil, "" if scheme == nil and pathOnly assert(string_sub(url, 1, 1) == "/", "path must starts with /") else assert(scheme, "parsing of url must have scheme") assert(hostp, "parsing of url must have host and/or authority") -- parse user pass if hostp m = string_split(hostp, "@") if m[2] n = string_split(m[1], ":") user = n[1] pass = n[2] hostp = m[2] -- parse port authority = hostp m = string_split(hostp, ":") host = m[1] port = m[2] else path, queryp = string.match(url, "([^?#]*)?*(.*)") pathAndQuery = path if queryp and strlen(queryp) > 0 m = string_split(queryp, "#") query = m[1] fragment = if m[2] then "#" .. m[2] else "" pathAndQuery = path .. "?" .. queryp port = default_port(scheme or "https") if port == nil or port == "" authority = "#{host}:#{port}" if (host and port) return { scheme, user or false, pass or false, host, port, path or nil, query or nil, fragment, authority or nil, pathAndQuery } parse = (url, pathOnly=false) -> parts, err = split(url, pathOnly) return parts, err if err rst = { scheme: parts[1] or nil, user: parts[2] or nil, password: parts[3] or nil, host: parts[4] or nil, port: parts[5] or nil, path: parts[6] or nil, query: parts[7] or nil, fragment: parts[8], authority: parts[9] or nil, path_and_query: parts[10] } rst.original = url if (rst.scheme and rst.authority) rst.sign_url = "#{rst.scheme}://#{rst.authority}#{rst.path_and_query}" rst.full_url = "#{rst.scheme}://#{rst.host}#{rst.path_and_query}" rst compile_pattern = (pattern) -> uri = parse(pattern, true) compiled_pattern = { original: pattern, params: { } } pattern = pattern\gsub("[%(%)%.%%%+%-%%?%[%^%$%*]", (char) -> return "%" .. char unless char == "*" ":*" ) pattern = pattern\gsub(':([a-z_%*]+)(/?)', (param, slash) -> if param == "*" table_insert(compiled_pattern.params, "splat") return "(.*)" .. slash table_insert(compiled_pattern.params, param) "([^/?&#]+)" .. slash ) if pattern\sub(-1) ~= "/" do pattern = pattern .. "/" -- if original url does not ends with forward slash, remove if compiled_pattern.original\sub(-1) ~= "/" pattern = pattern\sub(1, -2) if compiled_pattern.original\sub(-1) ~= "*" pattern = pattern .. "$" compiled_pattern.pattern = pattern compiled_pattern extract_parameters = (pat, matches) -> params = { } t = pat.params -- ngx.log(ngx.ERR, "xx " .. util.to_json(matches)) for i=1, #t k = t[i] params[k] = url_unescape(matches[i]) params match_pattern = (reqUrl, pat) -> -- if pattern is not full url if pat.original\find('https?') == nil -- and path is full, then just use path and query if reqUrl\find('https?') ~= nil reqUrl = parse(reqUrl, true).path_and_query matches = { re_match(reqUrl, pat.pattern) } -- ngx.log(ngx.ERR, reqUrl .. " matches " .. util.to_json(matches)) return true, extract_parameters(pat, matches) if #matches > 0 false, nil build_with_splats = (dest, splats) -> assert(dest, "dest url is required") assert(splats, "splats are required") -- add spaces so we can do split and join url = dest -- split url by each params -- ngx.log(ngx.ERR, dest .. "--" .. util.to_json(splats)) for k, v in pairs(splats) vv = if type(v) == "table" then v[1] else v url = string_gsub(url, ":" .. k, v) url { :split, :parse, :default_port, :compile_pattern, :match_pattern, :extract_parameters, :build_with_splats }
24.128713
130
0.610792
46098a108f8bea2e29ebce8e953a6e9c45498794
594
M = {} TK = require("PackageToolkit") tail = (TK.module.import ..., '_tail').tail -- append an item a list M.append = (list, ...) -> items = {...} return list if #items == 0 return items if (type list) != "table" and #items != 0 return table if (type list) == "table" and #items == 0 return {} if (type list) != "table" and #items == 0 -- note: a = b in Lua means let a have the address of list b -- Thus deep copy must be done explicitly output = [x for x in *list] for item in *items output[#output+1] = item return output return M
31.263158
64
0.575758
d8858a64f9bc1befae1ff8b6fb38fe9ed1b573a0
6,581
-- -- Copyright (C) 2017-2019 DBot -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -- of the Software, and to permit persons to whom the Software is furnished to do so, -- subject to the following conditions: -- The above copyright notice and this permission notice shall be included in all copies -- or substantial portions of the Software. -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, -- INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR -- PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE -- FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -- OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -- DEALINGS IN THE SOFTWARE. DLib.CMessage(PPM2, 'PPM2') DEBUG_LEVEL = CreateConVar('ppm2_debug', '0', {}, 'Enables debug printing. LOTS OF IT. 1 - simple messages; 2 - messages with traceback.') PPM2.DebugPrint = (...) -> return if DEBUG_LEVEL\GetInt() <= 0 frmt = PPM2.formatMessage(DEBUG_COLOR, ...) MsgC(DEBUG_COLOR, PREFIX_DEBUG, unpack(frmt)) MsgC('\n') if DEBUG_LEVEL\GetInt() >= 2 MsgC(DEBUG_COLOR, debug.traceback()) MsgC('\n') return frmt PPM2.TransformNewModelID = (id = 0) -> bgID = id % 16 maneModelID = math.floor(id / 16) + 1 maneModelID = 1 if maneModelID == 0 return maneModelID, bgID do randomColor = (a = 255) -> Color(math.random(0, 255), math.random(0, 255), math.random(0, 255), a) PPM2.Randomize = (object, ...) -> mane, manelower, tail = math.random(PPM2.MIN_UPPER_MANES_NEW, PPM2.MAX_UPPER_MANES_NEW), math.random(PPM2.MIN_LOWER_MANES_NEW, PPM2.MAX_LOWER_MANES_NEW), math.random(PPM2.MIN_TAILS_NEW, PPM2.MAX_TAILS_NEW) irisSize = math.random(PPM2.MIN_IRIS * 10, PPM2.MAX_IRIS * 10) / 10 with object \SetGender(math.random(0, 1), ...) \SetRace(math.random(0, 3), ...) \SetPonySize(math.random(85, 110) / 100, ...) \SetNeckSize(math.random(92, 108) / 100, ...) \SetLegsSize(math.random(90, 120) / 100, ...) \SetWeight(math.random(PPM2.MIN_WEIGHT * 10, PPM2.MAX_WEIGHT * 10) / 10, ...) \SetTailType(tail, ...) \SetTailTypeNew(tail, ...) \SetManeType(mane, ...) \SetManeTypeLower(manelower, ...) \SetManeTypeNew(mane, ...) \SetManeTypeLowerNew(manelower, ...) \SetBodyColor(randomColor(), ...) \SetEyeIrisTop(randomColor(), ...) \SetEyeIrisBottom(randomColor(), ...) \SetEyeIrisLine1(randomColor(), ...) \SetEyeIrisLine2(randomColor(), ...) \SetIrisSize(irisSize, ...) \SetManeColor1(randomColor(), ...) \SetManeColor2(randomColor(), ...) \SetManeDetailColor1(randomColor(), ...) \SetManeDetailColor2(randomColor(), ...) \SetUpperManeColor1(randomColor(), ...) \SetUpperManeColor2(randomColor(), ...) \SetUpperManeDetailColor1(randomColor(), ...) \SetUpperManeDetailColor2(randomColor(), ...) \SetLowerManeColor1(randomColor(), ...) \SetLowerManeColor2(randomColor(), ...) \SetLowerManeDetailColor1(randomColor(), ...) \SetLowerManeDetailColor2(randomColor(), ...) \SetTailColor1(randomColor(), ...) \SetTailColor2(randomColor(), ...) \SetTailDetailColor1(randomColor(), ...) \SetTailDetailColor2(randomColor(), ...) \SetSocksAsModel(math.random(1, 2) == 1, ...) \SetSocksColor(randomColor(), ...) return object entMeta = FindMetaTable('Entity') entMeta.GetPonyRaceFlags = => return 0 if not @IsPonyCached() data = @GetPonyData() return 0 if not data switch data\GetRace() when PPM2.RACE_EARTH return 0 when PPM2.RACE_PEGASUS return PPM2.RACE_HAS_WINGS when PPM2.RACE_UNICORN return PPM2.RACE_HAS_HORN when PPM2.RACE_ALICORN return PPM2.RACE_HAS_HORN + PPM2.RACE_HAS_WINGS entMeta.IsPony = => model = @GetModel() @__ppm2_lastmodel = @__ppm2_lastmodel or model if @__ppm2_lastmodel ~= model data = @GetPonyData() if data and data.ModelChanges oldModel = @__ppm2_lastmodel @__ppm2_lastmodel = model data\ModelChanges(oldModel, model) switch model when 'models/ppm/player_default_base.mdl' return true when 'models/ppm/player_default_base_new.mdl' return true when 'models/ppm/player_default_base_new_nj.mdl' return true when 'models/ppm/player_default_base_nj.mdl' return true when 'models/cppm/player_default_base.mdl' return true when 'models/cppm/player_default_base_nj.mdl' return true else return false entMeta.IsNJPony = => model = @GetModel() @__ppm2_lastmodel = @__ppm2_lastmodel or model if @__ppm2_lastmodel ~= model data = @GetPonyData() if data and data.ModelChanges oldModel = @__ppm2_lastmodel @__ppm2_lastmodel = model data\ModelChanges(oldModel, model) switch model when 'models/ppm/player_default_base_new_nj.mdl' return true when 'models/ppm/player_default_base_nj.mdl' return true when 'models/cppm/player_default_base_nj.mdl' return true else return false entMeta.IsNewPony = => model = @GetModel() @__ppm2_lastmodel = @__ppm2_lastmodel or model if @__ppm2_lastmodel ~= model data = @GetPonyData() if data and data.ModelChanges oldModel = @__ppm2_lastmodel @__ppm2_lastmodel = model data\ModelChanges(oldModel, model) return model == 'models/ppm/player_default_base_new.mdl' or model == 'models/ppm/player_default_base_new_nj.mdl' entMeta.IsPonyCached = => switch @__ppm2_lastmodel when 'models/ppm/player_default_base.mdl' return true when 'models/ppm/player_default_base_new.mdl' return true when 'models/ppm/player_default_base_new_nj.mdl' return true when 'models/ppm/player_default_base_nj.mdl' return true when 'models/cppm/player_default_base.mdl' return true when 'models/cppm/player_default_base_nj.mdl' return true else return false entMeta.IsNewPonyCached = => switch @__ppm2_lastmodel when 'models/ppm/player_default_base_new.mdl' return true when 'models/ppm/player_default_base_new_nj.mdl' return true else return false entMeta.IsNJPonyCached = => switch @__ppm2_lastmodel when 'models/ppm/player_default_base_new_nj.mdl' return true when 'models/ppm/player_default_base_nj.mdl' return true when 'models/cppm/player_default_base_nj.mdl' return true else return false entMeta.HasPonyModel = entMeta.IsPony
33.576531
207
0.725726
b569fe518838503dc10d2b028df370e06302fe9f
105
export modinfo = { type: "command" desc: "Shedletsky" alias: {"shedlet"} func: -> SetSky 92767799 }
15
19
0.647619
3ce2ca70a2ce3c490d786987a89913086a460df3
369
<template> <h1>{{content}}</h1> </template> <style scoped> h1 { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", sans-serif; font-weight: 200; font-size: 100px; color: #414141; } </style> <script> exports = { props: ['content'] } </script>
21.705882
163
0.609756
3108437e11ba23864b4b5a454ad6db49eb3c5b99
10,075
export script_name = "Text in Clip" export script_description = "Causes the characters in your text to go through the coordinates of your clip!" export script_author = "Zeref" export script_version = "1.0.0" -- LIB zf = require "ZF.main" import POINT from require "ZF.2D.point" import SHAPE from require "ZF.2D.shape" -- https://github.com/KaraEffect0r/Kara_Effector/blob/2a0a9cae4a0ebd7a254cfa360f52fcdd5fb61f03/Effector4/effector-auto4.lua#L5069 class PyointaBezier new: (line, shape, px, py, mode, offset = 0) => lWidth, lLeft, nN, bLen, lineOffset, pBezier, vBezier, paths, PtNo = line.width, line.left, 8, 0, 0, {}, {}, {}, {} paths = @getCoords shape for m in *paths for p in *m bLen += @getBezierLength p, 0, 1, nN lineOffset = switch mode when 2 then offset when 3 then (bLen - lWidth) - offset when 4 then (bLen - lWidth) * offset when 5 then (bLen - lWidth) * (1 - offset) else (bLen - lWidth) / 2 + offset targetLength, angle = 0, 0 PtNo, targetLength = @length2PtNo paths, lineOffset + px - lLeft, nN if PtNo != false tb = @length2t PtNo, targetLength, nN if tb != false pBezier = @getBezierPos PtNo, tb vBezier = @normal2P PtNo, tb angle = -deg(atan2(vBezier[2], vBezier[1])) - 90 else pBezier[1] = px pBezier[2] = py @out = { zf.math\round pBezier[1] zf.math\round pBezier[2] a: zf.math\round angle < -180 and angle + 360 or angle } tangential2P: (Pnts, t_) => tanVec, XY = {}, @difference Pnts dpos = @tDifferential XY, t_ for i = 1, 2 tanVec[i] = dpos[2][i] / sqrt(dpos[2][1] ^ 2 + dpos[2][2] ^ 2) return tanVec normal2P: (Pnts, t_) => normalVec = @tangential2P Pnts, t_ normalVec[1], normalVec[2] = normalVec[2], -normalVec[1] return normalVec difference: (Pnts) => DVec = {} DVec[1] = {Pnts[2][1] - Pnts[1][1], Pnts[2][2] - Pnts[1][2]} DVec[2] = {Pnts[3][1] - Pnts[2][1], Pnts[3][2] - Pnts[2][2]} DVec[3] = {Pnts[4][1] - Pnts[3][1], Pnts[4][2] - Pnts[3][2]} DVec[4] = {DVec[2][1] - DVec[1][1], DVec[2][2] - DVec[1][2]} DVec[5] = {DVec[3][1] - DVec[2][1], DVec[3][2] - DVec[2][2]} DVec[6] = {DVec[5][1] - DVec[4][1], DVec[5][2] - DVec[4][2]} { {Pnts[1][1], Pnts[1][2]} {DVec[1][1], DVec[1][2]} {DVec[4][1], DVec[4][2]} {DVec[6][1], DVec[6][2]} } tDifferential: (XY, ta) => { {XY[4][1] * ta ^ 3 + 3 * XY[3][1] * ta ^ 2 + 3 * XY[2][1] * ta + XY[1][1], XY[4][2] * ta ^ 3 + 3 * XY[3][2] * ta ^ 2 + 3 * XY[2][2] * ta + XY[1][2]} {3 * (XY[4][1] * ta ^ 2 + 2 * XY[3][1] * ta + XY[2][1]), 3 * (XY[4][2] * ta ^ 2 + 2 * XY[3][2] * ta + XY[2][2])} {6 * (XY[4][1] * ta + XY[3][1]), 6 * (XY[4][2] * ta + XY[3][2])} } getBezierLength: (p, ta, tb, nN) => t_, XY = {}, @difference p for i = 1, 2 * nN + 1 t_[i] = ta + (i - 1) * (tb - ta) / (2 * nN) dpos = @tDifferential XY, t_[1] Ft1 = (dpos[2][1] ^ 2 + dpos[2][2] ^ 2) ^ 0.5 dpos = @tDifferential XY, t_[2 * nN + 1] Ft2 = (dpos[2][1] ^ 2 + dpos[2][2] ^ 2) ^ 0.5 SFt1 = 0 for i = 1, nN dpos = @tDifferential XY, t_[2 * i] SFt1 += (dpos[2][1] ^ 2 + dpos[2][2] ^ 2) ^ 0.5 SFt2 = 0 for i = 1, nN - 1 dpos = @tDifferential XY, t_[2 * i + 1] SFt2 += (dpos[2][1] ^ 2 + dpos[2][2] ^ 2) ^ 0.5 return ((tb - ta) / (2 * nN) / 3) * ((Ft1 + Ft2) + (4 * SFt1) + (2 * SFt2)) length2t: (Pnts, Ltarget, nN) => ll = {0} ni, tb, t_ = 1 / nN, 0, 0 for i = 2, nN + 1 tb += ni ll[i] = @getBezierLength Pnts, 0, tb, nN * 2 return false if Ltarget > ll[nN + 1] for i = 1, nN if (Ltarget >= ll[i]) and (Ltarget <= ll[i + 1]) t_ = (i - 1) / nN + (Ltarget - ll[i]) / (ll[i + 1] - ll[i]) * (1 / nN) break return t_ length2PtNo: (Pnts, Ltarget, nN) => local cpoint, leng for h = 1, #Pnts bl = {0} for i = 2, #Pnts[h] + 1 bl[i] = bl[i - 1] + @getBezierLength Pnts[h][i - 1], 0, 1, nN if Ltarget > bl[#bl] Ltarget -= bl[#bl] else for k = 1, #Pnts[h] if (Ltarget >= bl[k]) and (Ltarget <= bl[k + 1]) cpoint = Pnts[h][k] leng = Ltarget - bl[k] break if leng break if leng return cpoint, leng return false getBezierPos: (Pnts, t_) => XY, pos_Bzr = @difference(Pnts), {} for i = 1, 2 pos_Bzr[i] = XY[4][i] * t_ ^ 3 + 3 * XY[3][i] * t_ ^ 2 + 3 * XY[2][i] * t_ + XY[1][i] return pos_Bzr getCoords: (shape) => coords, paths = {}, SHAPE(shape, false)\toBezier!.paths for i = 1, #paths coords[i] = {} for j = 2, #paths[i] zf.table(coords[i])\push { {paths[i][j][1].x, paths[i][j][1].y} {paths[i][j][2].x, paths[i][j][2].y} {paths[i][j][3].x, paths[i][j][3].y} {paths[i][j][4].x, paths[i][j][4].y} } return coords interface = -> items = {"Center", "Left", "Right", "Around", "Animated - Start to End", "Animated - End to Start"} hints = { items: "Position of the text relative to the text", offset: "The offset value of the position of the text \nrelative to the clip. \nIn case of animations, the value is a natural \nnumber that equals the frame step." } { {class: "label", label: "Modes:", x: 0, y: 0} {class: "dropdown", name: "mds", :items, hint: hints.items, x: 0, y: 1, value: items[1]} {class: "checkbox", name: "wwd", label: "With Words?", x: 0, y: 2, value: false} {class: "label", label: "\nOffset:", x: 0, y: 3} {class: "intedit", name: "off", hint: hints.offset, x: 0, y: 4, value: 0} {class: "checkbox", name: "remove", label: "Remove selected layers?", x: 0, y: 5, value: true} } main = (subs, selected) -> gui = zf.config\loadGui interface!, script_name local buttons, elements while true buttons, elements = aegisub.dialog.display gui, {"Ok", "Reset", "Cancel"}, close: "Cancel" gui = switch buttons when "Reset" then interface! when "Cancel" then return else break zf.config\saveGui elements, script_name n, i = selected[#selected], 0 for s, sel in ipairs selected aegisub.progress.set 100 * sel / n aegisub.progress.task "Processing line: #{s}" l = subs[sel + i] coords = zf.util\setPreprocLine subs, l px, py = coords.pos.x, coords.pos.y continue if not zf.util\runMacro(l) or zf.util\isShape coords, l.text\gsub "%b{}", "" l.comment = true subs[sel + i] = l line = zf.table(l)\copy! line.comment = false rawTag = zf.tags\getTag line.text zf.tags\dependency rawTag, "clips" -- gets frame duration msa, msb, j = aegisub.ms_from_frame(1), aegisub.ms_from_frame(101), 0 frameDur = msb and (msb - msa) / 100 or 41.708 with elements if .remove subs.delete sel + i i -= 1 mds = switch .mds when "Center" then 1 when "Left" then 2 when "Right" then 3 when "Around" then 4 call = zf.text(subs, line, line.text)\tags! sumWidth = zf.table(call)\arithmeticOp ((val) -> val.width), "+" dffWidth = sumWidth - line.width line.width += dffWidth for t, tag in ipairs call rawTag = zf.tags\getTag tag.text clip = zf.util\clip2Draw rawTag rawTag = zf.tags\clear tag, rawTag, "To Clip" textId = zf.text subs, tag values = .wwd and textId\words! or textId\chars! for key, value in ipairs values value.x += ceil dffWidth / 2 cs, cd = value.start_time, value.duration if .mds == "Animated - Start to End" or .mds == "Animated - End to Start" .off = 1 if .off <= 0 mode = .mds == "Animated - End to Start" and 5 or 4 loop = zf.math\round tag.duration / (frameDur * .off), 0 for j = 1, loop tag.start_time = cs + cd * (j - 1) / loop tag.end_time = cs + cd * j / loop result = PyointaBezier(line, clip, value.x, value.y, mode, (j - 1) / (loop - 1)).out tags = zf.tags\replaceT rawTag, "pos", result tags = zf.tags\merge tags, "\\frz#{result.a}" tag.text = tags .. value.text_stripped subs.insert sel + i + 1, tag i += 1 else result = PyointaBezier(line, clip, value.x, value.y, mds, .mds == "Around" and (key - 1) / (value.n - 1) or nil).out tags = zf.tags\replaceT rawTag, "pos", result tags = zf.tags\merge tags, "\\frz#{result.a}" tag.text = tags .. value.text_stripped subs.insert sel + i + 1, tag i += 1 aegisub.register_macro script_name, script_description, main
37.734082
171
0.467891
37ee9ef9f03f758a1c1997b0416341b9f9f4c974
1,999
--> # llre --> Llengua Rewrite Engine -- By daelvn -- 05.05.2019 import find, insert, split from require "libllengua.llre.string" import categoriesFor from require "libllengua.categories" unpack or= table.unpack --> ## LLRE-Lua --> Simplified version of LLRE, only supporting the features of Lua patterns. Usually, this covers enough cases for --> sound changes. --> # parseLuaRule --> Parses a LLRE rule. parseLuaRule = (rule) -> (split "/") rule --> # compileRule --> Compiles a parsed rule into a LLRE structure. compileLuaRule = (lang) -> (rule) -> compilePart = (r) -> r = r\gsub "%[(.)%]", (c) -> import getCategory from categoriesFor lang getCategory c r { capture: compilePart rule[1] replace: compilePart rule[2] environment: compilePart rule[3] exception: compilePart rule[4] otherwise: compilePart rule[5] } --> # buildRule --> Parses and compiles a LLRE rule buildLuaRule = (lang) -> (rule) -> (compileLuaRule lang) parseLuaRule rule --> # applyRule --> Applies a compiled rule to a string. applyLuaRule = (rule) -> (str) -> insertBack = insert str posl = (find rule.environment) str if #posl > 0 for pair in *posl substr = str\sub unpack pair substr, c = substr\gsub rule.capture, rule.replace if c > 0 return (insertBack substr) pair[1] else substr, c = substr\gsub rule.capture, rule.otherwise if c > 0 return (insertBack substr) pair[1] else return str else excPosl = (find rule.exception) str if #excPosl > 0 substr = str\sub unpack pair substr, c = substr\gsub rule.capture, rule.otherwise if c > 0 return (insertBack substr) pair[1] else return str else return str print (require "inspect") parseLuaRule "i/j/a.e[^l]/a.el/n" print (require "inspect") (buildLuaRule {}) "i/j/a.e[^l]/a.el/n" print (applyLuaRule (buildLuaRule {}) "i/j/a.e[^l]/a.el/n") "faied"
28.971014
115
0.631816
37b97e066bc4363af3c1e7e76337bbdeaa08af53
611
mode_reg = name: 'lisp' extensions: { 'cl', -- common lisp 'el', -- emacs lisp 'lisp', 'lsp', 'hy', -- hylang 'sch', -- scheme 'scm', -- scheme 'sld', -- scheme: R7RS Library Source 'sls', -- scheme: R6RS Library Source 'ss', -- scheme: 'Scheme Source' as used in some implementations (e.g. Chez) 'fnl', -- fennel } create: -> bundle_load('lisp_mode')! howl.mode.register mode_reg unload = -> howl.mode.unregister 'lisp' return { info: author: 'Copyright 2013-2015 The Howl Developers', description: 'Lisp mode', license: 'MIT', :unload }
21.068966
80
0.587561
9583e6eb3e376b8eab7f8c2e22d4414cac8c8e5c
2,654
love.graphics.setBackgroundColor 1, 1, 1 lerp = (a, b, t) -> a + (b - a) * t land = love.graphics.newImage "land.png" states = { {"yellow", -2000, -1500, "Før Kaaananit-æra"} {"yellow", -1500, -1200, "Egyptisk Herredømme"} {"yellow", -1200, -1000, "Jebusit Kaananisk"} {"blue", -1000, -750, "Bibelsk Israel-Judah"} {"yellow", -750, -625, "Ny-Syrisk"} {"yellow", -625, -500, "Ny Babelonsk"} {"yellow", -500, -350, "Persien"} {"yellow", -350, -180, "Ptolemæisk Makedonsk"} {"blue", -180, -70, "Judah"} {"yellow", -70, 300, "Romersk"} {"red", 300, 600, "Byzantinsk"} {"yellow", 600, 610, "Persisk"} {"red", 610, 617, "Byzantinsk"} {"green", 617, 640, "Rashidun Kalifat"} {"green", 640, 690, "Urnayyad Kalifat"} {"green", 690, 950, "Abbasid Kalifat"} {"green", 950, 1050, "Fatimid Kalifat"} {"green", 1050, 1080, "Seljuk Imperiet"} {"red", 1080, 1187, "Kongeriget Jerusalem"} {"green", 1187, 1229, "Det ayyubiske sultanat"} {"red", 1229, 1244, "Kongeriget Jerusalem"} {"green", 1244, 1260, "Det ayyubiske sultanat"} {"green", 1260, 1500, "Mamluk sultanatet"} {"green", 1500, 1917, "Osmanner-riget"} {"red", 1917, 1947, "Britisk Mandat"} {"blue", 1947, 2018, "Israel"} } color_str = (name) -> switch states[state][1] when "yellow" { 1, 1, 0 } when "red" { 1, 0, 0 } when "green" { 0, 1, 0 } when "blue" { 0, 0, 1 } export timer = 0 export state = 1 export color = color_str states[state][1] export new_color = color export use_time = false change_state = (a) -> timer = 0 state += a if state > #states state = #states if state < 1 state = 1 new_color = color_str states[state][1] with love .load = -> timer = 0 state = 1 .update = (dt) -> if use_time timer += dt color[1] = lerp color[1], new_color[1], dt color[2] = lerp color[2], new_color[2], dt color[3] = lerp color[3], new_color[3], dt if timer > (states[state][3] - states[state][2]) / 50 change_state 1 .draw = -> with love.graphics .setColor 0, 0, 0 .push! .scale 1.3, 1.3 .print states[state][4] .. ": fra #{states[state][2]} til #{states[state][3]}", 10, 10 .print "År: " .. (math.floor states[state][2] + timer * 50), 10, 25 .print "Pause", 10, 60 unless use_time .pop! .setColor color .draw land, 0, 0, 0, .getWidth! / land\getWidth!, .getHeight! / land\getHeight! .keypressed = (key) -> switch key when "space" use_time = not use_time when "left" change_state -1 when "right" change_state 1
23.90991
92
0.566692
1583a7c0330ead1825784b102528155b341d23ac
484
db = require "lapis.db" schema = require "lapis.db.schema" import add_column, create_index, drop_index, drop_column, create_table from schema { :serial, :boolean, :varchar, :integer, :text, :foreign_key, :double, :time, :numeric, :enum } = schema.types { [1]: => create_table "keys2", { {"id", integer} {"machine_id", foreign_key} {"time", time} {"count", integer} "PRIMARY KEY (machine_id, id)" } create_index "keys2", "time" }
18.615385
82
0.615702
d67764445782a1b25e34f1c0686ea11ac04cc0d0
547
M = {} T = require("PackageToolkit").module L = T.import ..., "../_lists" S = T.import ..., "../_strings" -- return a path string given the subdirectories M.path = (...) -> dir_separator = L.head (S.split package.config, "%s") aux = (subdirs, accum) -> if #subdirs == 0 return accum else return aux (L.tail subdirs), accum..dir_separator..tostring(subdirs[1]) args = {...} return "" if #args == 0 return args[1] if #args == 1 return aux (L.tail args), (tostring args[1]) return M
28.789474
83
0.564899
a2b17feeb743f7928a3b4aa306199b54da6c92de
11,185
util = require "moonscript.util" dump = require "moonscript.dump" transform = require "moonscript.transform" import NameProxy, LocalName from require "moonscript.transform.names" import Set from require "moonscript.data" import ntype, value_can_be_statement from require "moonscript.types" statement_compilers = require "moonscript.compile.statement" value_compilers = require "moonscript.compile.value" import concat, insert from table import pos_to_line, get_closest_line, trim, unpack from util mtype = util.moon.type indent_char = " " local Line, DelayedLine, Lines, Block, RootBlock -- a buffer for building up lines class Lines new: => @posmap = {} mark_pos: (pos, line=#@) => @posmap[line] = pos unless @posmap[line] -- append a line or lines to the buffer add: (item) => switch mtype item when Line item\render self when Block item\render self else -- also captures DelayedLine @[#@ + 1] = item @ flatten_posmap: (line_no=0, out={}) => posmap = @posmap for i, l in ipairs @ switch mtype l when "string", DelayedLine line_no += 1 out[line_no] = posmap[i] line_no += 1 for _ in l\gmatch"\n" out[line_no] = posmap[i] when Lines _, line_no = l\flatten_posmap line_no, out else error "Unknown item in Lines: #{l}" out, line_no flatten: (indent=nil, buffer={}) => for i = 1, #@ l = @[i] t = mtype l if t == DelayedLine l = l\render! t = "string" switch t when "string" insert buffer, indent if indent insert buffer, l -- insert breaks between ambiguous statements if "string" == type @[i + 1] lc = l\sub(-1) if (lc == ")" or lc == "]") and @[i + 1]\sub(1,1) == "(" insert buffer, ";" insert buffer, "\n" when Lines l\flatten indent and indent .. indent_char or indent_char, buffer else error "Unknown item in Lines: #{l}" buffer __tostring: => -- strip non-array elements strip = (t) -> if "table" == type t [strip v for v in *t] else t "Lines<#{util.dump(strip @)\sub 1, -2}>" -- Buffer for building up a line -- A plain old table holding either strings or Block objects. -- Adding a line to a line will cause that line to be merged in. class Line pos: nil append_list: (items, delim) => for i = 1,#items @append items[i] if i < #items then insert self, delim nil append: (first, ...) => if Line == mtype first -- print "appending line to line", first.pos, first @pos = first.pos unless @pos -- bubble pos if there isn't one @append value for value in *first else insert self, first if ... @append ... -- todo: try to remove concats from here render: (buffer) => current = {} add_current = -> buffer\add concat current buffer\mark_pos @pos for chunk in *@ switch mtype chunk when Block for block_chunk in *chunk\render Lines! if "string" == type block_chunk insert current, block_chunk else add_current! buffer\add block_chunk current = {} else insert current, chunk if current[1] add_current! buffer __tostring: => "Line<#{util.dump(@)\sub 1, -2}>" class DelayedLine new: (fn) => @prepare = fn prepare: -> render: => @prepare! concat @ class Block header: "do" footer: "end" export_all: false export_proper: false value_compilers: value_compilers statement_compilers: statement_compilers __tostring: => h = if "string" == type @header @header else unpack @header\render {} "Block<#{h}> <- " .. tostring @parent new: (@parent, @header, @footer) => @_lines = Lines! @_names = {} @_state = {} @_listeners = {} with transform @transform = { value: .Value\bind self statement: .Statement\bind self } if @parent @root = @parent.root @indent = @parent.indent + 1 setmetatable @_state, { __index: @parent._state } setmetatable @_listeners, { __index: @parent._listeners } else @indent = 0 set: (name, value) => @_state[name] = value get: (name) => @_state[name] get_current: (name) => rawget @_state, name listen: (name, fn) => @_listeners[name] = fn unlisten: (name) => @_listeners[name] = nil send: (name, ...) => if fn = @_listeners[name] fn self, ... extract_assign_name: (node) => is_local = false real_name = switch mtype node when LocalName is_local = true node\get_name self when NameProxy node\get_name self when "table" node[1] == "ref" and node[2] when "string" -- TOOD: some legacy transfomers might use string for ref node real_name, is_local declare: (names) => undeclared = for name in *names real_name, is_local = @extract_assign_name name continue unless is_local or real_name and not @has_name real_name, true -- this also puts exported names so they can be assigned a new value in -- deeper scope @put_name real_name continue if @name_exported real_name real_name undeclared whitelist_names: (names) => @_name_whitelist = Set names name_exported: (name) => return true if @export_all return true if @export_proper and name\match"^%u" put_name: (name, ...) => value = ... value = true if select("#", ...) == 0 name = name\get_name self if NameProxy == mtype name @_names[name] = value -- Check if a name is defined in the current or any enclosing scope -- skip_exports: ignore names that have been exported using `export` has_name: (name, skip_exports) => return true if not skip_exports and @name_exported name yes = @_names[name] if yes == nil and @parent if not @_name_whitelist or @_name_whitelist[name] @parent\has_name name, true else yes is_local: (node) => t = mtype node return @has_name(node, false) if t == "string" return true if t == NameProxy or t == LocalName if t == "table" if node[1] == "ref" or (node[1] == "chain" and #node == 2) return @is_local node[2] false free_name: (prefix, dont_put) => prefix = prefix or "moon" searching = true name, i = nil, 0 while searching name = concat {"", prefix, i}, "_" i = i + 1 searching = @has_name name, true @put_name name if not dont_put name init_free_var: (prefix, value) => name = @free_name prefix, true @stm {"assign", {name}, {value}} name -- add something to the line buffer add: (item, pos) => with @_lines \add item \mark_pos pos if pos item -- todo: pass in buffer as argument render: (buffer) => buffer\add @header buffer\mark_pos @pos if @next buffer\add @_lines @next\render buffer else -- join an empty block into a single line if #@_lines == 0 and "string" == type buffer[#buffer] buffer[#buffer] ..= " " .. (unpack Lines!\add @footer) else buffer\add @_lines buffer\add @footer buffer\mark_pos @pos buffer block: (header, footer) => Block self, header, footer line: (...) => with Line! \append ... is_stm: (node) => @statement_compilers[ntype node] != nil is_value: (node) => t = ntype node @value_compilers[t] != nil or t == "value" -- compile name for assign name: (node, ...) => if type(node) == "string" node else @value node, ... value: (node, ...) => node = @transform.value node action = if type(node) != "table" "raw_value" else node[1] fn = @value_compilers[action] unless fn error { "compile-error" "Failed to find value compiler for: " .. dump.value node node[-1] } out = fn self, node, ... -- store the pos, creating a line if necessary if type(node) == "table" and node[-1] if type(out) == "string" out = with Line! do \append out out.pos = node[-1] out values: (values, delim) => delim = delim or ', ' with Line! \append_list [@value v for v in *values], delim stm: (node, ...) => return if not node -- skip blank statements node = @transform.statement node result = if fn = @statement_compilers[ntype(node)] fn @, node, ... else if value_can_be_statement node @value node else -- coerce value into statement @stm {"assign", {"_"}, {node}} if result if type(node) == "table" and type(result) == "table" and node[-1] result.pos = node[-1] @add result nil stms: (stms, ret) => error "deprecated stms call, use transformer" if ret {:current_stms, :current_stm_i} = @ @current_stms = stms for i=1,#stms @current_stm_i = i @stm stms[i] @current_stms = current_stms @current_stm_i = current_stm_i nil -- takes the existing set of lines and replaces them with the result of -- calling fn on them splice: (fn) => lines = {"lines", @_lines} @_lines = Lines! @stms fn lines class RootBlock extends Block new: (@options) => @root = self super! __tostring: => "RootBlock<>" root_stms: (stms) => unless @options.implicitly_return_root == false stms = transform.Statement.transformers.root_stms self, stms @stms stms render: => -- print @_lines buffer = @_lines\flatten! buffer[#buffer] = nil if buffer[#buffer] == "\n" table.concat buffer format_error = (msg, pos, file_str) -> line_message = if pos line = pos_to_line file_str, pos line_str, line = get_closest_line file_str, line line_str = line_str or "" (" [%d] >> %s")\format line, trim line_str concat { "Compile error: "..msg line_message }, "\n" value = (value) -> out = nil with RootBlock! \add \value value out = \render! out tree = (tree, options={}) -> assert tree, "missing tree" scope = (options.scope or RootBlock) options runner = coroutine.create -> scope\root_stms tree success, err = coroutine.resume runner unless success error_msg, error_pos = if type(err) == "table" switch err[1] when "user-error", "compile-error" unpack err, 2 else -- unknown error, bubble it error "Unknown error thrown", util.dump error_msg else concat {err, debug.traceback runner}, "\n" return nil, error_msg, error_pos or scope.last_pos lua_code = scope\render! posmap = scope._lines\flatten_posmap! lua_code, posmap -- mmmm with data = require "moonscript.data" for name, cls in pairs {:Line, :Lines, :DelayedLine} data[name] = cls { :tree, :value, :format_error, :Block, :RootBlock }
23.014403
77
0.588824
d0920cdab9d1649f2ef19f7495d37d4b7e8d3dd6
1,348
KeyConstants = require "lib.KeyConstants" Gamestate = require "lib.gamestate" import graphics, keyboard from love w, h = graphics.getWidth!, graphics.getHeight! pause = { init: => @font = graphics.newFont 32 @title = "Paused" @x = w / 2 - @font\getWidth(@title) / 2 @y = h / 2 - @font\getHeight! / 2 enter: (previous_state) => @background = previous_state @timer = 0 @allow_keypress = false update: (dt) => @timer += dt if @timer > 0.05 @allow_keypress = true draw: => @background\draw! graphics.origin! graphics.setColor 0, 0, 0, 150 graphics.rectangle "fill", 0, 0, w, h previous_font = graphics.getFont! graphics.setFont @font graphics.setColor 255, 255, 255, 255 graphics.print @title, @x, @y graphics.setFont previous_font if @allow_keypress str = "(press any key to unpause)" graphics.print str, w / 2 - graphics.getFont!\getWidth(str) / 2, h / 2 + 96 keypressed: (key) => if @allow_keypress accept_input = false if key == "escape" or key == "pause" accept_input = true else for keytype in *{"character", "numpad", "navigation", "editing"} if KeyConstants[keytype][key] accept_input = true break if accept_input Gamestate.pop! } return pause
24.071429
81
0.608309
f8c47d7213a584e90287e03b479b9bbf14d6d9c6
1,029
-- Copyright 2012-2015 The Howl Developers -- License: MIT (see LICENSE.md at the top-level directory of the distribution) Gtk = require 'ljglibs.gtk' class IndicatorBar new: (cls) => error('Missing argument #1 (id)', 2) if not cls @box = Gtk.Box { height_request: 20 spacing: 10 } @indics = {} add: (position, id, widget) => pack = nil switch position when 'left' pack = @box\pack_start when 'right' pack = @box\pack_end else error 'Illegal indicator position "' .. position .. '"', 2 indicator = self._create_indicator id, widget @indics[id] = indicator pack indicator, false, false, 0 indicator remove: (id) => indicator = @indics[id] indicator\destroy! if indicator to_gobject: => @box _create_indicator: (id, widget) -> widget or= Gtk.Label single_line_mode: true with widget.style_context \add_class 'indic_default' \add_class 'indic_' .. id widget\show! widget return IndicatorBar
22.866667
79
0.632653
be5f198f48d55b759b38396360c57414fd58ab05
449
import error from _G -- ::argument(any conditional, number argument, string name, string tag, number stackLevel?) -> any -- Performs a Lua-style assert e.g. 'bad argument #? to '?' (?)' export argument = (conditional, argument, name, tag, stackLevel=2) -> -- If the conditional is truthy, return it, otherwise perform formatted error return conditional if conditional error("bad argument ##{argument} to '#{name}' (#{tag})", stackLevel)
56.125
99
0.701559
3adc481ecadcc8f43c5a09b75085a41f89e58325
119
import extra from require "t.extra" reverse = string.reverse "sulpnooM morf olleH" |> reverse |> print print extra!
14.875
41
0.731092
5d5e812de2954ae05b040a554fe1dd74a57b825a
93
h = {} h.load_map_data = (filename) -> return love.image.newImageData(filename) return h
13.285714
42
0.698925
a148a5359be3a3c2e20bb99c390ff5836850cde1
809
buttons = require "yae.constants.buttons" keys = require "yae.constants.keys" formats = require "yae.constants.formats" wraps = require "yae.constants.wraps" filters = require "yae.constants.filters" blendmodes = require "yae.constants.blendmodes" shapetypes = require "yae.constants.shapetypes" aligns = require "yae.constants.aligns" keycodes = {} for k, v in pairs keys keycodes[v] = k buttoncodes = {} for k, v in pairs buttons buttoncodes[v] = k formatcodes = {} for k, v in pairs formats formatcodes[v] = k wrapcodes = {} for k, v in pairs wraps wrapcodes[v] = k filtercodes = {} for k, v in pairs filters filtercodes[v] = k { :keys :keycodes :buttons :buttoncodes :formats :formatcodes :wraps :wrapcodes :filters :filtercodes :blendmodes :shapetypes :aligns }
17.977778
47
0.704574
1c0cbbc7374b29098380736e7cc27f1a174decde
646
-- Copyright 2012-2019 The Howl Developers -- License: MIT (see LICENSE.md at the top-level directory of the distribution) import interact from howl class TextReader new: (opts={}) => @opts = moon.copy opts init: (@command_line, opts = {}) => @command_line.prompt = @opts.prompt @command_line.title = @opts.title keymap: enter: => @command_line\finish @command_line.text escape: => @command_line\finish! interact.register name: 'read_text' description: 'Read free form text entered by user' handler: (opts={}) -> howl.app.window.command_panel\run TextReader(opts), text: opts.text, help: opts.help
25.84
88
0.688854
423e2ba495ac2a4d57a391403c23a0040061e9a2
808
class assert that: (condition, message) -> if not condition if message error("Assert hit! #{message}") else assert.throw! is_class_instance: (instance, class_table) -> assert.is_equal(instance.__class, class_table) throw: -> error("Assert hit!") throws: (error_pattern, action) -> ok, error_str = pcall(action) assert.that(not ok, 'Expected exception but instead nothing was thrown') assert.that(error_str\find(error_pattern) != nil, "Unexpected error message! Expected '#{error_pattern}' but found:\n#{error_str}") is_equal: (left, right) -> assert.that(left == right, "Expected '#{left}' to be equal to '#{right}'") is_not_equal: (left, right) -> assert.that(left != right, "Expected '#{left}' to not be equal to '#{right}'")
29.925926
136
0.649752
a184a8295e26752d52a6565ab9b7571965fda07a
3,863
import Command, option from require "ice.command" import Exec from require "ice.tools.exec" import Json from require "ice.util.json" import loadstring from require "moonscript" py3_script = [[import mmh3; %s]] py3_hash = [[print('[\'%s\']: {}'.format(mmh3.hash('%s', signed=False, seed=0x428639DA)));]] class NatvisCommand extends Command @arguments { } prepare: (args, project) => os.chdir "source/code" iterate_over_headers: (path, shard_names) => return unless path\match "%.hxx" if f = io.open path, "rb" for line in f\lines! var, val = line\match 'static constexpr ice::Shard ([%w_:]+) = "([%w/-]+)"_shard' if var and val print "Warning: Shard with this name '#{var}' already exists!" if shard_names.shard[var] shard_names.shard[var] = val continue var, val = line\match 'Constant_ShardPayloadID<([%w_:%*]+)> = ice::payload_id%("([%w_:*]+)"%)' if var or val shard_names.payloadid[var] = val f\close! iterate_over_directory: (path, shard_names) => for name, mode in os.listdir path, 'mode' continue if name == '.' or name == '..' @iterate_over_directory "#{path}/#{name}", shard_names if mode == 'directory' @iterate_over_headers "#{path}/#{name}", shard_names execute: (args) => names = { shard: { }, payloadid: {} } @iterate_over_directory ".", names generate_hashes = (names) -> all_hashes = "" for name, value in pairs names all_hashes ..= string.format(py3_hash, value, value) cmd = 'python3 -c "' .. string.format(py3_script, all_hashes) .. '"' p = io.popen cmd, 'r' return { } unless p hash_results = p\read '*all' p\close! (loadstring "{\n" .. hash_results .. "\n}")! sort_results = (hash_results) -> sorted_list = { } for name, hash in pairs hash_results table.insert sorted_list, { :name, :hash } table.sort sorted_list, (left, right) -> left.name < right.name return sorted_list hashes = sort_results generate_hashes names.shard payload_hashes = sort_results generate_hashes names.payloadid if f = io.open "./core/core/natvis/shard_names.natvis", "wb+" f\write '<?xml version="1.0" encoding="utf-8"?>\n' f\write '<AutoVisualizer xmlns="http://schemas.microsoft.com/vstudio/debugger/natvis/2010">\n' f\write ' <Type Name="ice::Shard">\n' f\write ' <DisplayString Condition="name == ' .. hash .. '">Shard {{ ' .. name .. ' }}</DisplayString>\n' for { :name, :hash } in *hashes f\write ' <DisplayString>Shard {{ {name,h}, unknown_name }}</DisplayString>\n' f\write ' <Expand>\n' f\write ' <Synthetic Name="[payload type]">\n' f\write ' <DisplayString Condition="payload_id == ' .. hash .. '">' .. name .. '</DisplayString>\n' for { :name, :hash } in *payload_hashes f\write ' <DisplayString Condition="payload_id == 0">{payload_id}, type_not_set</DisplayString>\n' f\write ' <DisplayString>{payload_id}, unknown_type</DisplayString>\n' f\write ' </Synthetic>\n' f\write ' <Item Name="[payload]" Optional="true" Condition="payload_id == ' .. hash .. '">*(' .. name .. '*)&amp;payload</Item>\n' for { :name, :hash } in *payload_hashes f\write ' </Expand>\n' f\write ' </Type>\n' f\write '</AutoVisualizer>\n' f\close! { :NatvisCommand }
43.404494
193
0.539995
b48a8c79d890a2ee1d6ba75a3f39da658a58d8db
36,125
config = require "lapis.config" config.default_config.postgres = {backend: "pgmoon"} config.reset true db = require "lapis.db.postgres" import Model from require "lapis.db.postgres.model" import stub_queries, assert_queries from require "spec.helpers" describe "lapis.db.model.relations", -> get_queries, mock_query = stub_queries! with old = assert_queries assert_queries = (expected, opts) -> old expected, get_queries!, opts local models before_each -> models = {} package.loaded.models = models it "should make belongs_to getter", -> mock_query "SELECT", { { id: 101 } } models.Users = class extends Model @primary_key: "id" models.CoolUsers = class extends Model @primary_key: "user_id" class Posts extends Model @relations: { {"user", belongs_to: "Users"} {"cool_user", belongs_to: "CoolUsers", key: "owner_id"} } post = Posts! post.user_id = 123 post.owner_id = 99 assert post\get_user! assert post\get_user! post\get_cool_user! assert_queries { 'SELECT * from "users" where "id" = 123 limit 1' 'SELECT * from "cool_users" where "user_id" = 99 limit 1' } it "should make belongs_to getter with inheritance", -> mock_query "SELECT", { { id: 101 } } models.Users = class extends Model @primary_key: "id" class Posts extends Model @relations: { {"user", belongs_to: "Users"} } get_user: => with user = super! user.color = "green" post = Posts! post.user_id = 123 assert.same { id: 101 color: "green" }, post\get_user! it "caches nil result from belongs_to_fetch", -> mock_query "SELECT", {} models.Users = class extends Model @primary_key: "id" class Posts extends Model @relations: { {"user", belongs_to: "Users"} } post = Posts! post.user_id = 123 assert.same nil, post\get_user! assert.same nil, post\get_user! assert.same 1, #get_queries! it "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 "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 "fetch with preload & autogenerated getter", -> count = 0 class Posts extends Model @relations: { {"thing" fetch: true preload: (objects) -> for item in *objects count += 1 item.thing = count } } post1 = Posts! post2 = Posts! assert.same 1, post1\get_thing! assert.same 2, post2\get_thing! assert.same 1, post1\get_thing! assert.same 2, post2\get_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 "fails with composite primary key on has_one", -> mock_query "SELECT", { { id: 111, id2: 222 } } models.Users = class Users extends Model @primary_key: {"a_id", "b_id"} @relations: { {"user_profile", has_one: "UserProfiles"} {"user_profile_with_key", has_one: "UserProfiles", key: { id: "a_id" id2: "b_id" }} } models.UserProfiles = class UserProfiles extends Model user = Users! user.a_id = 111 user.b_id = 222 assert.has_error( -> user\get_user_profile! "Model UsersRelations has composite primary keys, you must specify column mapping directly with `key`" ) assert.has_error( -> Users\preload_relations { user }, "user_profile" "Model UsersRelations has composite primary keys, you must specify column mapping directly with `key`" ) user\get_user_profile_with_key! Users\preload_relations { user }, "user_profile_with_key" assert_queries { { 'SELECT * from "user_profiles" where "id2" = 222 AND "id" = 111 limit 1' 'SELECT * from "user_profiles" where "id" = 111 AND "id2" = 222 limit 1' } { 'SELECT * from "user_profiles" where ("id2", "id") in ((222, 111))' 'SELECT * from "user_profiles" where ("id", "id2") in ((111, 222))' } } 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 -- offset paginator 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 -- offset ordered paginator user\get_posts_paginated(ordered: {"id"})\get_page! user\get_posts_paginated(ordered: {"id"})\get_page 1023 user\get_posts_paginated(order: "desc", ordered: {"created_at", "id"})\get_page "2020-1-1", 238 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' 'SELECT * from "posts" where "user_id" = 1234 order by "posts"."id" ASC limit 10' 'SELECT * from "posts" where "posts"."id" > 1023 and ("user_id" = 1234) order by "posts"."id" ASC limit 10' [[SELECT * from "posts" where ("posts"."created_at", "posts"."id") < ('2020-1-1', 238) and ("user_id" = 1234) order by "posts"."created_at" desc, "posts"."id" desc limit 10]] } it "should make has_many getter", -> models.Posts = class extends Model models.Users = class extends Model @relations: { {"posts", has_many: "Posts"} {"more_posts", has_many: "Posts", where: {color: "blue"}} {"fresh_posts", has_many: "Posts", order: "id desc"} } user = models.Users! user.id = 1234 user\get_posts! user\get_posts! user\get_more_posts! user\get_fresh_posts! assert_queries { 'SELECT * from "posts" where "user_id" = 1234' { [[SELECT * from "posts" where "user_id" = 1234 AND "color" = 'blue']] [[SELECT * from "posts" where "color" = 'blue' AND "user_id" = 1234]] } 'SELECT * from "posts" where "user_id" = 1234 order by id desc' } it "should make has_many getter with composite key", -> mock_query "SELECT", { { id: 101, user_id: 99, page_id: 234 } { id: 102, user_id: 99, page_id: 234 } } models.UserPageData = class extends Model models.UserPage = class extends Model @relations: { {"data", has_many: "UserPageData", key: { "user_id", "page_id" }} } up = models.UserPage! up.user_id = 99 up.page_id = 234 assert.same { { id: 101, user_id: 99, page_id: 234 } { id: 102, user_id: 99, page_id: 234 } }, up\get_data! up2 = models.UserPage! up2.user_id = 99 up2.page_id = nil assert up2\get_data! assert_queries { { 'SELECT * from "user_page_data" where "user_id" = 99 AND "page_id" = 234' 'SELECT * from "user_page_data" where "page_id" = 234 AND "user_id" = 99' } { 'SELECT * from "user_page_data" where "user_id" = 99 AND "page_id" IS NULL' 'SELECT * from "user_page_data" where "page_id" IS NULL AND "user_id" = 99' } } it "should create relations for inheritance", -> class Base extends Model @relations: { {"user", belongs_to: "Users"} } class Child extends Base @relations: { {"category", belongs_to: "Categories"} } assert Child.get_user, "expecting get_user" assert Child.get_category, "expecting get_category" assert.same nil, rawget Child, "get_user" describe "polymorphic belongs to", -> local Foos, Bars, Bazs, Items before_each -> models.Foos = class Foos extends Model models.Bars = class Bars extends Model @primary_key: "frog_index" models.Bazs = class Bazs extends Model Items = class Items extends Model @relations: { {"object", polymorphic_belongs_to: { [1]: {"foo", "Foos"} [2]: {"bar", "Bars"} [3]: {"baz", "Bazs"} }} } it "should model_for_object_type", -> assert Foos == Items\model_for_object_type 1 assert Foos == Items\model_for_object_type "foo" assert Bars == Items\model_for_object_type 2 assert Bars == Items\model_for_object_type "bar" assert Bazs == Items\model_for_object_type 3 assert Bazs == Items\model_for_object_type "baz" assert.has_error -> Items\model_for_object_type 4 assert.has_error -> Items\model_for_object_type "bun" it "should object_type_for_model", -> assert.same 1, Items\object_type_for_model Foos assert.same 2, Items\object_type_for_model Bars assert.same 3, Items\object_type_for_model Bazs assert.has_error -> Items\object_type_for_model Items it "should object_type_for_object", -> assert.same 1, Items\object_type_for_object Foos! assert.same 2, Items\object_type_for_object Bars! assert.same 3, Items\object_type_for_object Bazs assert.has_error -> Items\object_type_for_model {} it "should call getter", -> mock_query "SELECT", { { id: 101 } } for i, {type_id, cls} in ipairs {{1, Foos}, {2, Bars}, {3, Bazs}} item = Items\load { object_type: type_id object_id: i * 33 } obj = item\get_object! obj.__class == cls obj2 = item\get_object! assert.same obj, obj2 assert_queries { 'SELECT * from "foos" where "id" = 33 limit 1' 'SELECT * from "bars" where "frog_index" = 66 limit 1' 'SELECT * from "bazs" where "id" = 99 limit 1' } it "should call preload with empty", -> Items\preload_objects {} assert_queries { } it "should call preload", -> k = 0 n = -> k += 1 k items = { Items\load { object_type: 1 object_id: n! } Items\load { object_type: 2 object_id: n! } Items\load { object_type: 1 object_id: n! } Items\load { object_type: 1 object_id: n! } } Items\preload_objects items assert_queries { 'SELECT * from "foos" where "id" in (1, 3, 4)' 'SELECT * from "bars" where "frog_index" in (2)' } it "preloads with fields", -> items = { Items\load { object_type: 1 object_id: 111 } Items\load { object_type: 2 object_id: 112 } Items\load { object_type: 3 object_id: 113 } } Items\preload_objects items, fields: { bar: "a, b" baz: "c, d" } assert_queries { 'SELECT * from "foos" where "id" in (111)' 'SELECT a, b from "bars" where "frog_index" in (112)' 'SELECT c, d from "bazs" where "id" in (113)' } it "finds relation", -> import find_relation from require "lapis.db.model.relations" class Posts extends Model @relations: { {"user", belongs_to: "Users"} {"cool_user", belongs_to: "CoolUsers", key: "owner_id"} } class BetterPosts extends Posts @relations: { {"tags", has_many: "Tags"} } assert.same {"user", belongs_to: "Users"}, (find_relation Posts, "user") assert.same nil, (find_relation Posts, "not there") assert.same {"cool_user", belongs_to: "CoolUsers", key: "owner_id"}, (find_relation BetterPosts, "cool_user") describe "clear_loaded_relation", -> it "clears loaded relation cached with value", -> mock_query "SELECT", { {id: 777, name: "hello"} } models.Users = class Users extends Model class Posts extends Model @relations: { {"user", belongs_to: "Users"} } post = Posts\load { id: 1 user_id: 1 } post\get_user! post\get_user! assert.same 1, #get_queries! assert.not.nil post.user post\clear_loaded_relation "user" assert.nil post.user post\get_user! assert.same 2, #get_queries! it "clears loaded relation cached with nil", -> mock_query "SELECT", {} models.Users = class Users extends Model class Posts extends Model @relations: { {"user", belongs_to: "Users"} } post = Posts\load { id: 1 user_id: 1 } post\get_user! post\get_user! assert.same 1, #get_queries! post\clear_loaded_relation "user" post\get_user! assert.same 2, #get_queries! describe "preload_relations", -> it "preloads relations that return empty", -> mock_query "SELECT", {} models.Dates = class Dates extends Model models.Users = class Users extends Model models.Tags = class Tags extends Model class Posts extends Model @relations: { {"user", belongs_to: "Users"} {"date", has_one: "Dates"} {"tags", has_many: "Tags"} } post = Posts\load { id: 888 user_id: 234 } Posts\preload_relations {post}, "user", "date", "tags" assert_queries { [[SELECT * from "users" where "id" in (234)]] [[SELECT * from "dates" where "post_id" in (888)]] [[SELECT * from "tags" where "post_id" in (888)]] } import LOADED_KEY from require "lapis.db.model.relations" assert.same { user: true date: true tags: true }, post[LOADED_KEY] before_count = #get_queries! post\get_user! post\get_date! post\get_tags! assert.same, before_count, #get_queries! it "preloads has_many with order and fields", -> models.Tags = class Tags extends Model class Posts extends Model @relations: { {"tags", has_many: "Tags", order: "a desc"} } Posts\preload_relation {Posts\load id: 123}, "tags", { fields: "a,b" order: "b asc" } assert_queries { [[SELECT a,b from "tags" where "post_id" in (123) order by b asc]] } it "preloads has_many with composite key", -> mock_query "SELECT", { { id: 101, user_id: 99, page_id: 234 } { id: 102, user_id: 99, page_id: 234 } { id: 103, user_id: 100, page_id: 234 } } models.UserPageData = class extends Model models.UserPage = class UserPage extends Model @relations: { {"data", has_many: "UserPageData", key: { "user_id", "page_id" }} } user_pages = { UserPage\load { user_id: 99 page_id: 234 } UserPage\load { user_id: 100 page_id: 234 } UserPage\load { user_id: 100 page_id: 300 } } UserPage\preload_relation user_pages, "data" assert_queries { 'SELECT * from "user_page_data" where ("user_id", "page_id") in ((99, 234), (100, 234), (100, 300))' } import LOADED_KEY from require "lapis.db.model.relations" for user_page in *user_pages assert.true user_page[LOADED_KEY].data assert.same { { id: 101, user_id: 99, page_id: 234 } { id: 102, user_id: 99, page_id: 234 } }, user_pages[1].data assert.same { { id: 103, user_id: 100, page_id: 234 } }, user_pages[2].data assert.same {}, user_pages[3].data it "preloads has_one with key and local_key", -> mock_query "SELECT", { { id: 99, thing_email: "notleafo@leafo" } { id: 101, thing_email: "leafo@leafo" } } models.Things = class extends Model models.Users = class Users extends Model @relations: { {"thing", has_one: "Things", local_key: "email", key: "thing_email"} } user = Users! user.id = 123 user.email = "leafo@leafo" Users\preload_relations {user}, "thing" assert_queries { [[SELECT * from "things" where "thing_email" in ('leafo@leafo')]] } assert.same { id: 101 thing_email: "leafo@leafo" }, user.thing it "preloads has_one with where", -> mock_query "SELECT", { { thing_id: 123, name: "whaz" } } models.Files = class Files extends Model class Things extends Model @relations: { {"beta_file" has_one: "Files" where: { deleted: false } } } thing = Things\load { id: 123 } Things\preload_relations { thing }, "beta_file" assert.same { thing_id: 123 name: "whaz" }, thing.beta_file assert_queries { [[SELECT * from "files" where "thing_id" in (123) and "deleted" = FALSE]] } it "preloads has_one with composite key", -> import LOADED_KEY from require "lapis.db.model.relations" mock_query "SELECT", { {id: 1, user_id: 11, page_id: 101} } models.UserPageData = class extends Model models.UserPage = class UserPage extends Model @relations: { {"data", has_one: "UserPageData", key: { "user_id", "page_id" }} } user_pages = { UserPage\load { user_id: 10 page_id: 100 } UserPage\load { user_id: 11 page_id: 101 } } UserPage\preload_relation user_pages, "data" assert_queries { [[SELECT * from "user_page_data" where ("user_id", "page_id") in ((10, 100), (11, 101))]] } assert.same { { user_id: 10 page_id: 100 [LOADED_KEY]: { data: true } } { user_id: 11 page_id: 101 data: { id: 1, user_id: 11, page_id: 101 } [LOADED_KEY]: { data: true } } }, user_pages it "preloads has_many with order and name", -> mock_query "SELECT", { { primary_thing_id: 123, name: "whaz" } } models.Tags = class Tags extends Model class Things extends Model @relations: { {"cool_tags" has_many: "Tags" order: "name asc" where: { deleted: false } key: "primary_thing_id" } } thing = Things\load { id: 123 } Things\preload_relations {thing}, "cool_tags" assert.same { { primary_thing_id: 123, name: "whaz" } }, thing.cool_tags assert_queries { [[SELECT * from "tags" where "primary_thing_id" in (123) and "deleted" = FALSE order by name asc]] } it "preloads belongs_to with correct name", -> mock_query "SELECT", { { id: 1, name: "last" } { id: 2, name: "first" } { id: 3, name: "default" } } models.Topics = class Topics extends Model class Categories extends Model @relations: { {"last_topic", belongs_to: "Topics"} {"first_topic", belongs_to: "Topics"} {"topic", belongs_to: "Topics"} } cat = Categories\load { id: 1243 last_topic_id: 1 first_topic_id: 2 topic_id: 3 } Categories\preload_relations {cat}, "last_topic", "first_topic", "topic" assert.same 3, #get_queries! assert.same { id: 1 name: "last" }, cat\get_last_topic!, cat.last_topic assert.same { id: 2 name: "first" }, cat\get_first_topic!, cat.first_topic assert.same { id: 3 name: "default" }, cat\get_topic!, cat.topic assert.same 3, #get_queries! it "preloads has_one with correct name", -> mock_query "SELECT", { {user_id: 1, name: "cool dude"} } models.UserData = class UserData extends Model class Users extends Model @relations: { {"data", has_one: "UserData"} } user = Users\load id: 1 Users\preload_relations {user}, "data" assert.same {user_id: 1, name: "cool dude"}, user.data, user\get_data! it "finds inherited preloaders", -> models.Users = class Users extends Model class SimplePosts extends Model @relations: { {"user", belongs_to: "Users"} } class JointPosts extends SimplePosts @relations: { {"second_user", belongs_to: "Users"} } p = JointPosts\load { id: 999 user_id: 1 second_user_id: 2 } JointPosts\preload_relations {p}, "user", "second_user" describe "has_one", -> it "preloads when using custom keys", -> mock_query "SELECT", { {user_id: 100, name: "first"} {user_id: 101, name: "second"} } models.UserItems = class UserItems extends Model @primary_key: "user_id" @relations: { {"application", has_one: "ItemApplications", key: "user_id"} } new: (user_id) => @user_id = assert user_id, "missing user id" models.ItemApplications = class ItemApplications extends Model id = 1 new: (user_id) => @user_id = assert user_id, "missing user id" @id = id id += 1 ui = UserItems 100 a = assert ui\get_application!, "expected to get relation" assert.same 100, a.user_id ui2 = UserItems 101 UserItems\preload_relations {ui2}, "application" a = assert ui2.application, "expected to get relation" assert.same 101, a.user_id assert_queries { [[SELECT * from "item_applications" where "user_id" = 100 limit 1]] [[SELECT * from "item_applications" where "user_id" in (101)]] } describe "generic preload", -> local preload before_each -> import preload from require "lapis.db.model" models.Users = class Users extends Model @relations: { {"tags", has_many: "Tags"} {"user_data", has_one: "UserData"} {"account", belongs_to: "Accounts"} } new: (@id) => assert @id, "missing id" models.Tags = class Tags extends Model @relations: { {"owner", has_one: "Users"} } models.UserData = class UserData extends Model @relations: { {"images", has_many: "Images"} } models.Accounts = class Accounts extends Model models.Images = class Images extends Model it "preloads basic relations", -> user = models.Users 10 user.account_id = 99 preload { user }, "tags", "user_data", "account" assert_queries { [[SELECT * from "tags" where "user_id" in (10)]] [[SELECT * from "user_data" where "user_id" in (10)]] [[SELECT * from "accounts" where "id" in (99)]] } it "preloads nested relations", -> mock_query 'from "tags"', { models.Tags\load { id: 252 user_id: 10 } models.Tags\load { id: 311 user_id: 10 } } mock_query 'from "user_data"', { models.UserData\load { id: 32 user_id: 10 } } user = models.Users 10 user.account_id = 99 preload { user }, "account", { tags: { "owner" } user_data: {"images"} } assert_queries { [[SELECT * from "accounts" where "id" in (99)]] [[SELECT * from "images" where "user_data_id" in (32)]] [[SELECT * from "tags" where "user_id" in (10)]] [[SELECT * from "user_data" where "user_id" in (10)]] [[SELECT * from "users" where "tag_id" in (252, 311)]] }, sorted: true it "preloads nested fetch relations", -> models.Collections = class Collection extends Model @relations: { {"user", fetch: => {} preload: (collections) -> for c in *collections c.user = models.Users\load { id: 10 } true } {"things", many: true fetch: => {} preload: (collections) -> for c in *collections c.things = { models.Users\load { id: 11 } models.Users\load { id: 12 } } true } } new: (@id) => assert @id, "missing id" collection = models.Collections 44 preload { collection }, { user: "tags" things: { "user_data", tags: {} } } assert_queries { -- TODO: homogeneous preload should be able to merge these queries [[SELECT * from "tags" where "user_id" in (10)]] [[SELECT * from "tags" where "user_id" in (11, 12)]] [[SELECT * from "user_data" where "user_id" in (11, 12)]] }, sorted: true it "passes preload opts", -> local preload_objects, preload_opts class Item extends Model @relations: { {"things", many: true fetch: => error "no fetch me" preload: (...) -> preload_objects, preload_opts = ... } } items = {Item!} preload items, things: { [preload]: { fields: "blue" } } assert.equal items[1], preload_objects[1] assert.nil preload_objects[2] assert.same { fields: "blue" }, preload_opts describe "optional relations", -> it "single optional relation", -> class OtherThing extends Model new: (opts) => for k,v in pairs opts @[k] = v class Thing extends Model @relations: { {"other_thing" fetch: => error "preload should not fetch" preload: (list) -> for item in *list item.other_thing = OtherThing { thing: item } } } class EmptyThing extends Model assert.has_error( -> preload {EmptyThing!, EmptyThing!}, "other_thing" "Model EmptyThing doesn't have preloader for other_thing" ) assert.has_error( -> preload {Thing!, Thing!}, "missing_thing" "Model Thing doesn't have preloader for missing_thing" ) empty_things = {EmptyThing!, EmptyThing!} preload empty_things, "?other_thing" things = {Thing!, Thing!} preload things, "?missing_thing" preload things, other_thing: "?unknown_thing" assert.truthy things[1].other_thing assert.equal things[1], things[1].other_thing.thing assert.truthy things[2].other_thing assert.equal things[2], things[2].other_thing.thing it "many optional relation", -> class OtherThing extends Model new: (opts) => for k,v in pairs opts @[k] = v class ThingConnector extends Model @relations: { {"the_thing" fetch: => error "preload should not fetch" preload: (list) -> for item in *list item.the_thing = OtherThing { parent: item } } } new: (opts) => for k,v in pairs opts @[k] = v class Thing extends Model @relations: { {"other_things" many: true fetch: => error "preload should not fetch" preload: (list) -> for item in *list item.other_things = { OtherThing { idx: 1 parent: item } ThingConnector { idx: 2 parent: item } } } } things = {Thing!, Thing!} preload things, other_things: "?the_thing" for thing_idx=1,2 assert.truthy things[thing_idx].other_things for other_things_idx=1,2 assert.equal things[thing_idx], things[thing_idx].other_things[other_things_idx].parent assert.nil things[thing_idx].other_things[1].the_thing -- the thing connector instance assert.truthy things[thing_idx].other_things[2].the_thing it "optional into more relations", -> class Friend extends Model new: (opts) => for k,v in pairs opts @[k] = v class TheThing extends Model @relations: { {"friend" fetch: => error "preload should not fetch" preload: (items) -> for item in *items item.friend = Friend { parent: item } } } class Thing extends Model @relations: { {"friend" fetch: => error "preload should not fetch" preload: (items) -> for item in *items item.friend = Friend { parent: item } } } class Thong extends Model @relations: { {"the_things" fetch: => error "preload should not fetch" many: true preload: (items) -> for item in *items item.the_things = { TheThing parent: item TheThing parent: item } } } things = {Thing!, Thong!, Thong!} preload things, { "?friend" "?the_things": "friend" } do -- thing assert.truthy things[1].friend assert.nil things[1].the_things assert.equal things[1], things[1].friend.parent do -- thong 1 assert.nil things[2].friend assert.truthy things[2].the_things for the_thing in *things[2].the_things assert.truthy the_thing.friend assert.equal the_thing, the_thing.friend.parent do -- thong 2 assert.nil things[3].friend assert.truthy things[3].the_things for the_thing in *things[3].the_things assert.truthy the_thing.friend assert.equal the_thing, the_thing.friend.parent
25.3331
180
0.546796
ef77ee3185e23058b09fbf154dbfd683842fb40b
402
base58 = require "base58" describe "base58", -> it "should call encode_base58", -> assert.same "TvjnTzXAiTprExJ", base58.encode_base58 "Hello world" it "should call decode_base58", -> assert.same "Hello world", base58.decode_base58 "TvjnTzXAiTprExJ" it "should fail to decode bad still", -> res, err = base58.decode_base58 "hello world" assert.falsy res assert.truthy err
26.8
69
0.70398
dad982fecaa60d703395ab6e84ad24552f4cfa87
723
export class TimerSet new: => @timers = nil update: => return if @timers == nil dead_timers = 0 for timer in *@timers if not timer.alive dead_timers += 1 continue elseif not timer.active continue timer.timer -= axel.dt while timer.timer <= 0 timer.timer += timer.delay timer.times -= 1 timer.callback! if timer.times == 0 timer\stop! break if dead_timers >= 5 for i = #@timers, 1 table.remove @timers, i unless @timers[i].alive add: (delay, times = 1, callback, start = -1) => @timers = {} unless @timers timer = Timer delay, times, callback, start table.insert @timers, timer timer clear: => @timers[key] = nil for key, _ in *@timers
20.657143
52
0.618257
e8dd71a635bd38d4b0b3ccf6376e56fc8aee30d7
1,236
html_builer = { "text" "raw" "widget" "element" "html_5" "capture" 'area' "applet" 'base' 'br' 'col' 'embed' 'frame' 'hr' 'img' 'input' 'link' 'meta' 'param' 'a' 'abbr' 'acronym' 'address' 'article' 'aside' 'audio' 'b' 'bdo' 'big' 'blockquote' 'body' 'button' 'canvas' 'caption' 'center' 'cite' 'code' 'colgroup' 'command' 'datalist' 'dd' 'del' 'details' 'dfn' 'dialog' 'div' 'dl' 'dt' 'em' 'fieldset' 'figure' 'footer' 'form' 'frameset' 'h1' 'h2' 'h3' 'h4' 'h5' 'h6' 'head' 'header' 'hgroup' 'html' 'i' 'iframe' 'ins' 'keygen' 'kbd' 'label' 'legend' 'li' 'map' 'mark' 'meter' 'nav' 'noframes' 'noscript' 'object' 'ol' 'optgroup' 'option' 'p' 'pre' 'progress' 'q' 'ruby' 'rt' 'rp' 's' 'samp' 'script' 'section' 'select' 'small' 'source' 'span' 'strike' 'strong' 'style' 'sub' 'sup' 'table' 'tbody' 'td' 'textarea' 'tfoot' 'th' 'thead' 'time' 'title' 'tr' 'tt' 'u' 'ul' 'var' 'video' } { whitelist_globals: { ["."]: {"ngx", "__leda"} ["lapis/views"]: html_builer } }
8.24
32
0.464401
87580c35bb68bc78f6ed85f26dde6bcfff9f3590
108
path = "src/util/math" export Vector = require "#{path}/vector" export Matrix = require "#{path}/matrix"
21.6
40
0.675926
6f665e26e39ed7bb2bb9f1864277ccb3eb0f479d
106
version = "0.4.0" { version: version, print_version: -> print "MoonScript version #{version}" }
11.777778
41
0.622642
7026ef627eeb013986aee96930e8ecbb133f61c3
1,804
export ^ -- defines a character with : -- sprite, sexe, age, name... -- the charsprite basic info should be in the data folder class CharSprite -- @@sexenum = {MAN => "Man", WOMAN => "Woman"} next: () => @age = 30 -- @sex = @@sexenum.MAN @sex = "Man" @imgPath = nil @spriteImg = nil @spritename = "noname" class Character new:() => @fadinglvl = 0 @hidden = false @charsprite = nil @designation = "Mr." @firstName = "No" @lastName = "Name" visible:() => return @fadinglvl > 0 hide:() => @hidden = true show:() => @hidden = false @fadinglvl = 0 completeName: () => return "#{@designation} #{@lastName} #{@firstName}" update:(dt) => if not @hidden and @fadinglvl < 255 -- fade in @fadinglvl += dt * 300 if @fadinglvl >= 255 @fadinglvl = 255 if @hidden and @visible() -- fade out @fadinglvl -= dt * 300 if @fadinglvl <= 0 @fadinglvl = 0 draw:(maxHeight) => if not @visible() return assert @charsprite != null, "Character #{@completeName!} : no sprite" assert @charsprite.spriteImg != null, "Character : no sprite" scale = maxHeight / @charsprite.spriteImg\getHeight() offset_x = wScr() / 2 - @charsprite.spriteImg\getWidth() * scale / 2 offset_y = hScr() - @charsprite.spriteImg\getHeight() * scale love.graphics.translate(offset_x, offset_y) love.graphics.scale(scale) love.graphics.setColor(255, 255, 255, @fadinglvl) love.graphics.draw(@charsprite.spriteImg, 0, 0) love.graphics.reset()
26.529412
77
0.52051
0783d28b25a0206163abd9afa49b853a7fbe5643
737
[[ joli-lune small framework for love2d MIT License (see licence file) ]] System = require "src.systems.system" SoundSource = require "src.soundsource" class SoundSet extends System __tostring: => return "soundset" onCreate: => @sources = {} addSource: (name,sounds,play,loop,intro) => if not sounds return @sources[name] = SoundSource(sounds, @) if play @sources[name]\play loop, intro return @sources[name] get: (name) => return @sources[name] update: (dt) => for _,source in pairs @sources source\update dt pause: (dur) => for _,source in pairs @sources source\pause dur resume: (dur) => for _,source in pairs @sources source\resume dur onDestroy: => --@\pause! return SoundSet
16.75
44
0.674355
c9be397f2d2e102bd83b68b12ef150a6de5e76f4
554
Gtk = require 'ljglibs.gtk' describe 'Alignment', -> local alignment before_each -> alignment = Gtk.Alignment! describe '(properties)', -> it 'supports property access', -> assert.equal 0.5, alignment.xalign alignment.xalign = 0.7 assert.equal 7, math.ceil alignment.xalign * 10 describe 'get_padding()', -> it 'returns all four paddings as return values (top, bottom, left, right)', -> alignment.bottom_padding = 7 alignment.right_padding = 3 assert.same {0, 7, 0, 3 }, { alignment\get_padding! }
29.157895
82
0.655235
87bf87e66409c12f473e56622746fc1fc35ac954
1,447
-- Copyright 2012-2014-2015 The Howl Developers -- License: MIT (see LICENSE.md at the top-level directory of the distribution) handlers = {} all = {} append = table.insert abort = {} register = (name, options = {}) -> error "Missing field 'description'", 2 unless options.description all[name] = options unregister = (name) -> all[name] = nil handlers[name] = nil handlers_for = (name) -> handlers[name] = handlers[name] or {} handlers[name] emit = (name, params, illegal) -> error "Unknown signal '#{name}'", 2 unless all[name] error "emit can be called with a maximum of two parameters", 2 if illegal error "expected table as second parameter", 2 if params and type(params) != 'table' for handler in *handlers_for name co = coroutine.create (...) -> handler ... status, ret = coroutine.resume co, params if status if ret == abort and coroutine.status(co) == 'dead' return abort else _G.log.error 'Error invoking handler for "' .. name .. '": ' .. ret false connect = (name, handler, index) -> error "Unknown signal '#{name}'", 2 unless all[name] list = handlers_for name if not index or index > #list + 1 then index = #list + 1 else if index < 1 then index = 1 append list, index, handler disconnect = (name, handler) -> handlers[name] = [h for h in *handlers_for name when h != handler] return :abort, :register, :unregister, :emit, :connect, :disconnect, :all
28.94
85
0.658604
4e6d88716ede809128ebb1306b2256804dd32d79
546
export modinfo = { type: "command" desc: "Fix lighting" alias: {"flig"} func: (Msg,Speaker) -> light = Service"Lighting" light\ClearAllChildren() light.Ambient = Color3.new(1,1,1) light.ColorShift_Bottom = Color3.new(0,0,0) light.ColorShift_Top = Color3.new(0,0,0) light.ShadowColor = Color3.new(.69, .69, .69) light.Brightness = .2 light.FogStart = 0 light.FogEnd = 100000 light.FogColor = Color3.new(.74, .74, .74) light.TimeOfDay = 12 Output("Cleaned Lighting",{Colors.Green},Speaker) loggit("Cleaned Lighting") }
28.736842
51
0.684982
8c97f4330e5879a73f52cb541cb17d22880b76a0
8,387
util = require "lapis.util" json = require "cjson" tests = { { -> util.parse_query_string "field1=value1&field2=value2&field3=value3" { {"field1", "value1"} {"field2", "value2"} {"field3", "value3"} field1: "value1" field2: "value2" field3: "value3" } } { -> util.parse_query_string "blahblah" { { "blahblah"} blahblah: true } } { -> util.parse_query_string "hello=wo%22rld&thing" { { "hello", 'wo"rld' } { "thing" } hello: 'wo"rld' thing: true } } { -> util.parse_query_string "hello=&thing=123&world=" { {"hello", ""} {"thing", "123"} {"world", ""} hello: "" thing: "123" world: "" } } { -> util.parse_query_string "null" { {"null"} null: true } } { -> util.underscore "ManifestRocks" "manifest_rocks" } { -> util.underscore "ABTestPlatform" "abtest_platform" } { -> util.underscore "HELLO_WORLD" "" -- TODO: fix } { -> util.underscore "whats_up" "whats__up" -- TODO: fix } { -> util.camelize "hello" "Hello" } { -> util.camelize "world_wide_i_web" "WorldWideIWeb" } { -> util.camelize util.underscore "ManifestRocks" "ManifestRocks" } { -> util.encode_query_string { {"dad", "day"} "hello[hole]": "wor=ld" } "dad=day&hello%5bhole%5d=wor%3dld" } { -> util.encode_query_string { {"cold", "zone"} "hello": true "world": false } "cold=zone&hello" } { -> util.encode_query_string { "world": false } "" } { -> util.encode_query_string { "null": true } "null" } { -- stripping invalid types -> json.decode util.to_json { color: "blue" data: { height: 10 fn: => } } { color: "blue", data: { height: 10} } } { -> util.build_url { path: "/test" scheme: "http" host: "localhost.com" port: "8080" fragment: "cool_thing" query: "dad=days" } "http://localhost.com:8080/test?dad=days#cool_thing" } { -> util.build_url { host: "dad.com" path: "/test" fragment: "cool_thing" } "//dad.com/test#cool_thing" } { -> util.build_url { scheme: "" host: "leafo.net" } "//leafo.net" } { -> util.time_ago os.time! - 34234349 { {"years", 1} {"days", 31} {"hours", 5} {"minutes", 32} {"seconds", 29} years: 1 days: 31 hours: 5 minutes: 32 seconds: 29 } } { -> util.time_ago os.time! + 34234349 { {"years", 1} {"days", 31} {"hours", 5} {"minutes", 32} {"seconds", 29} years: 1 days: 31 hours: 5 minutes: 32 seconds: 29 } } { -> util.time_ago_in_words os.time! - 34234349 "1 year ago" } { -> util.time_ago_in_words os.time! - 34234349, 2 "1 year, 31 days ago" } { -> util.time_ago_in_words os.time! - 34234349, 10 "1 year, 31 days, 5 hours, 32 minutes, 29 seconds ago" } { -> util.time_ago_in_words os.time! "0 seconds ago" } { -> util.parse_cookie_string "__utma=54729783.634507326.1355638425.1366820216.1367111186.43; __utmc=54729783; __utmz=54729783.1364225235.36.12.utmcsr=t.co|utmccn=(referral)|utmcmd=referral|utmcct=/Q95kO2iEje; __utma=163024063.1111023767.1355638932.1367297108.1367341173.42; __utmb=163024063.1.10.1367341173; __utmc=163024063; __utmz=163024063.1366693549.37.11.utmcsr=t.co|utmccn=(referral)|utmcmd=referral|utmcct=/UYMGwvGJNo" { __utma: '163024063.1111023767.1355638932.1367297108.1367341173.42' __utmz: '163024063.1366693549.37.11.utmcsr=t.co|utmccn=(referral)|utmcmd=referral|utmcct=/UYMGwvGJNo' __utmb: '163024063.1.10.1367341173' __utmc: '163024063' } } { -> util.slugify "What is going on right now?" "what-is-going-on-right-now" } { -> util.slugify "whhaa $%#$ hooo" "whhaa-hooo" } { -> util.slugify "what-about-now" "what-about-now" } { -> util.slugify "hello - me" "hello-me" } { -> util.slugify "cow _ dogs" "cow-dogs" } { -> util.uniquify { "hello", "hello", "world", "another", "world" } { "hello", "world", "another" } } { -> util.trim "what the heck" "what the heck" } { -> util.trim " blah blah " "blah blah" } { -> util.trim " hello#{" "\rep 20000}world " "hello#{" "\rep 20000}world" } { -> util.trim_filter { " ", " thing ", yes: " " okay: " no " } { -- TODO: fix indexing? nil, "thing", okay: "no" } } { -> util.trim_filter { hello: " hi" world: " hi" yeah: " " }, {"hello", "yeah"}, 0 { hello: "hi", yeah: 0 } } { -> util.key_filter { hello: "world" foo: "bar" }, "hello", "yeah" { hello: "world" } } { -> "^%()[12332]+$"\match(util.escape_pattern "^%()[12332]+$") and true true } { -> util.title_case "hello" "Hello" } { -> util.title_case "hello world" "Hello World" } { -> util.title_case "hello-world" "Hello-world" } { -> util.title_case "What my 200 Dollar thing You love to eat" "What My 200 Dollar Thing You Love To Eat" } } describe "lapis.util", -> for group in *tests it "should match", -> input = group[1]! if #group > 2 assert.one_of input, { unpack group, 2 } else assert.same input, group[2] it "should autoload", -> package.loaded["things.hello_world"] = "yeah" package.loaded["things.cool_thing"] = "cool" mod = util.autoload "things" assert.equal "yeah", mod.HelloWorld assert.equal "cool", mod.cool_thing assert.equal nil, mod.not_here assert.equal nil, mod.not_here assert.equal "cool", mod.cool_thing it "should autoload with starting table", -> package.loaded["things.hello_world"] = "yeah" package.loaded["things.cool_thing"] = "cool" mod = util.autoload "things", { dad: "world" } assert.equal "yeah", mod.HelloWorld assert.equal "cool", mod.cool_thing assert.equal "world", mod.dad it "should autoload with multiple prefixes", -> package.loaded["things.hello_world"] = "yeah" package.loaded["things.cool_thing"] = "cool" package.loaded["wings.cool_thing"] = "very cool" package.loaded["wings.hats"] = "off to you" mod = util.autoload "wings", "things" assert.equal "off to you", mod.hats assert.equal "very cool", mod.CoolThing assert.equal "yeah", mod.hello_world assert.equal "yeah", mod.HelloWorld it "should singularize words", -> words = { {"banks", "bank"} {"chemists", "chemist"} {"hospitals", "hospital"} {"letters", "letter"} {"vallys", "vally"} {"keys", "key"} {"industries", "industry"} {"ladies", "lady"} {"heroes", "hero"} {"torpedoes", "torpedo"} -- these will never work -- {"halves", "half"} -- {"leaves", "leaf"} -- {"wives", "wife"} } for {plural, single} in *words assert.same single, util.singularize plural describe "lapis.util.mixin", -> it "should mixin mixins", -> import insert from table log = {} class Mixin new: => insert log, "initializing Mixin" @thing = { "hello" } pop: => add_one: (num) => insert log, "Before add_one (Mixin), #{num}" class Mixin2 new: => insert log, "initializing Mixin2" add_one: (num) => insert log, "Before add_one (Mixin2), #{num}" class One util.mixin Mixin util.mixin Mixin2 add_one: (num) => num + 1 new: => insert log, "initializing One" o = One! assert.equal 13, o\add_one(12) assert.same { "initializing One" "initializing Mixin" "initializing Mixin2" "Before add_one (Mixin2), 12" "Before add_one (Mixin), 12" }, log
17.997854
430
0.52641
7915429328c6d4bbb7a7f085e75a3e2df42cad11
336
discount = require "discount" feed = require "feed" set "title", "Changelog" set "link_to_home", true html -> div { class: "changelog" h2 "Changelog" for entry in *feed div { class: "release" id: "v" .. entry._release.version raw discount trim_leading_white entry.description } }
16.8
57
0.604167
4b7069528f2b8a8abdbd8143354d8c3a13113669
2,467
AddCSLuaFile! if CLIENT Moonpanel.InitControl = => -- Watch the "TheMP Control" NW2 variable for changes. LocalPlayer!\SetNW2VarProxy "TheMP Control", (_, _, old, new) -> if old ~= new and Moonpanel\IsFocused! gui.EnableScreenClicker not IsValid new ------------------------------------------------------------ -- Dispatches PanelRequestControl requests to the server. -- ------------------------------------------------------------ Moonpanel.RequestControl = (entity) => ply = LocalPlayer! controlled = ply\GetNW2Entity "TheMP Control" ply\SetNW2Entity "TheMP Control", game.GetWorld! if (IsEntity controlled) and IsValid controlled x, y = entity\GetCursorPos! Moonpanel.Net.PanelRequestControl entity, x, y hook.Add "InputMouseApply", "TheMP Control", (cmd, x, y) -> if Moonpanel\ApplyDeltas LocalPlayer!, x, y cmd\SetMouseX 0 cmd\SetMouseY 0 true else -------------------------------------------------------- -- Acknowledges panel control requests and associates -- -- players with panels. -- -------------------------------------------------------- Moonpanel.RequestControl = (ply, entity, x, y) => controlled = ply\GetNW2Entity "TheMP Control" if (IsEntity controlled) and IsValid controlled Moonpanel\StopControl ply elseif (IsEntity entity) and IsValid entity if entity.Moonpanel and entity.RequestControl and entity\RequestControl ply, x, y ply\SetNW2Entity "TheMP Control", entity ---------------------------------------------- -- Acknowledges panel stopcontrol requests. -- ---------------------------------------------- Moonpanel.StopControl = (ply) => controlled = ply\GetNW2Entity "TheMP Control" if (IsEntity controlled) and IsValid controlled controlled\StopControl! ply\SetNW2Entity "TheMP Control", game.GetWorld! ------------------------------------------------------------- -- Applies panel deltas to the currently controlled panel. -- -- Does nothing if the player isn't controlling anything. -- ------------------------------------------------------------- Moonpanel.ApplyDeltas = (ply, dX = 0, dY = 0) => return if dX == 0 and dY == 0 controlled = ply\GetNW2Entity "TheMP Control" if ((IsEntity controlled) and IsValid controlled) dX = math.Clamp dX, -127, 127 dY = math.Clamp dY, -127, 127 if controlled\GetController! == ply and controlled\ApplyDeltas ply, dX, dY Moonpanel.Net.SendDeltas dX, dY if CLIENT true
36.279412
98
0.584921
5fe105b28f11179e9a6c511501cf8ba7e98df151
7,096
{ ------------------------------------------------------------------------------ -- Default bindings ------------------------------------------------------------------------------ editor: { left: 'cursor-left' right: 'cursor-right' up: 'cursor-up' down: 'cursor-down' shift_left: 'cursor-left-extend' shift_right: 'cursor-right-extend' shift_up: 'cursor-up-extend' shift_down: 'cursor-down-extend' alt_up: 'editor-move-lines-up' alt_down: 'editor-move-lines-down' alt_left: 'editor-move-text-left' alt_right: 'editor-move-text-right' tab: 'editor-smart-tab' shift_tab: 'editor-smart-back-tab' backspace: 'editor-delete-back' shift_backspace: 'editor-delete-back' ctrl_backspace: 'editor-delete-back-word' delete: 'editor-delete-forward' ctrl_delete: 'editor-delete-forward-word' return: 'editor-newline' ctrl_return: 'editor-newline-below' ctrl_shift_return: 'editor-newline-above' page_up: 'cursor-page-up' shift_page_up: 'cursor-page-up-extend' page_down: 'cursor-page-down' shift_page_down: 'cursor-page-down-extend' end: 'cursor-line-end' shift_end: 'cursor-line-end-extend' home: 'cursor-home' shift_home: 'cursor-home-extend' ctrl_home: 'cursor-start' ctrl_shift_home: 'cursor-start-extend' ctrl_end: 'cursor-eof' ctrl_shift_end: 'cursor-eof-extend' ctrl_b: 'switch-buffer' ctrl_c: 'editor-copy' ctrl_d: 'editor-duplicate-current' ctrl_shift_e: 'cursor-goto-inspection' ctrl_f: 'buffer-search-forward' ctrl_shift_f: 'project-file-search' ctrl_shift_g: 'project-file-search-list' ctrl_r: 'buffer-search-backward' ctrl_comma: 'buffer-search-word-backward' ctrl_period: 'buffer-search-word-forward' ctrl_g: 'buffer-grep' ctrl_i: 'editor-indent' ctrl_k: 'editor-delete-to-end-of-line' ctrl_shift_k: 'editor-delete-line' ctrl_n: 'new-buffer' ctrl_w: 'buffer-close' ctrl_shift_i: 'editor-indent-all' ctrl_h: 'buffer-replace' ctrl_s: 'save' ctrl_shift_s: 'save-as' ctrl_v: 'editor-paste' ctrl_shift_v: 'editor-paste..' ctrl_x: 'editor-cut' ctrl_z: 'editor-undo' ctrl_Z: 'editor-redo' ctrl_q: 'show-doc-at-cursor' ctrl_space: 'editor-complete' ctrl_slash: 'editor-toggle-comment' ctrl_tab: 'view-next' shift_delete: 'editor-cut' shift_insert: 'editor-paste' ctrl_insert: 'editor-copy' ctrl_a: 'editor-select-all' alt_s: 'buffer-structure' alt_q: 'editor-reflow-paragraph' ctrl_left: 'cursor-word-left' ctrl_right: 'cursor-word-right' ctrl_up: 'editor-scroll-up' ctrl_down: 'editor-scroll-down' 'ctrl_<': 'navigate-back' 'ctrl_>': 'navigate-forward' 'alt_<': 'navigate-go-to' ctrl_shift_left: 'cursor-word-left-extend' ctrl_shift_right: 'cursor-word-right-extend' ctrl_shift_up: 'editor-scroll-up' ctrl_shift_down: 'editor-scroll-down' ctrl_shift_d: 'vc-diff-file' ctrl_alt_d: 'vc-diff' alt_g: 'cursor-goto-line' } ctrl_o: 'open' ctrl_shift_o: 'open-recent' ctrl_p: 'project-open' ctrl_shift_r: 'exec' ctrl_alt_r: 'project-exec' ctrl_shift_b: 'project-build' ctrl_shift_w: 'view-close' 'ctrl_-': 'zoom-out' 'ctrl_+': 'zoom-in' f11: 'window-toggle-fullscreen' alt_x: 'run' alt_j: 'open-journal' shift_alt_left: 'view-left-or-create' shift_alt_right: 'view-right-or-create' shift_alt_up: 'view-up-or-create' shift_alt_down: 'view-down-or-create' ------------------------------------------------------------------------------ -- OS specific bindings ------------------------------------------------------------------------------ for_os: osx: editor: { meta_a: 'editor-select-all' meta_b: 'switch-buffer' meta_c: 'editor-copy' meta_d: 'editor-duplicate-current' meta_f: 'buffer-search-forward' meta_r: 'buffer-search-backward' meta_comma: 'buffer-search-word-backward' meta_period: 'buffer-search-word-forward' meta_g: 'buffer-grep' meta_i: 'editor-indent' meta_k: 'editor-delete-to-end-of-line' meta_shift_k: 'editor-delete-line' meta_shift_i: 'editor-indent-all' meta_h: 'buffer-replace' meta_n: 'new-buffer' meta_w: 'buffer-close' meta_s: 'save' meta_shift_s: 'save-as' meta_v: 'editor-paste' meta_shift_v: 'editor-paste..' meta_x: 'editor-cut' meta_z: 'editor-undo' meta_Z: 'editor-redo' meta_space: 'editor-complete' meta_slash: 'editor-toggle-comment' meta_insert: 'editor-copy' meta_return: 'editor-newline-below' meta_shift_return: 'editor-newline-above' 'meta_<': 'navigate-go-to' ctrl_tab: 'view-right-wraparound' ctrl_shift_tab: 'view-left-wraparound' ctrl_meta_d: 'show-doc-at-cursor' ctrl_shift_s: 'buffer-structure' ctrl_q: 'editor-reflow-paragraph' meta_up: 'editor-scroll-up' meta_down: 'editor-scroll-down' -- needs option key -- meta_shift_left: 'cursor-word-left-extend' -- meta_shift_right: 'cursor-word-right-extend' -- meta_backspace: 'editor-delete-back-word' -- meta_delete: 'editor-delete-forward-word' 'ctrl_<': 'navigate-back' 'ctrl_>': 'navigate-forward' ctrl_shift_d: 'vc-diff-file' ctrl_meta_d: 'vc-diff' ctrl_g: 'cursor-goto-line' } meta_o: 'open' meta_shift_o: 'open-recent' meta_p: 'project-open' meta_q: 'quit' meta_shift_r: 'project-exec' meta_shift_b: 'project-build' meta_shift_w: 'view-close' 'meta_-': 'zoom-out' 'meta_+': 'zoom-in' ctrl_meta_f: 'window-toggle-fullscreen' ctrl_meta_x: 'run' }
35.303483
80
0.505778
0ab8ac50143f118deb2f161e86ff089e1e654586
3,494
Node = require 'node' V = require 'vector' class PolyDef new: (@name, @color, @groups, @weight, blocks) => @max = V(0, 0) @blocks = {} for i,b in ipairs blocks @blocks[i] = b if b[1] > @max.x then @max.x = b[1] if b[2] > @max.y then @max.y = b[2] fromDef: (name, rawDef) -> {:color, :groups, :weight} = rawDef return PolyDef name, color, groups, weight, rawDef inGroups: (groups) => for group in *groups for sgroup in *@groups if group == sgroup then return true return false toMatrix: => matrix = {} for y=1,@max.y+1 matrix[y] = {} for x=1,@max.x+1 matrix[y][x] = false for block in *@blocks matrix[block[2]+1][block[1]+1] = true return matrix rotateMatrix: (m) -> matrix = {} for y=1,#m[1] matrix[y] = {} for x=1,#m matrix[y][x] = false for i = 1,#m for j = 1,#m[1] matrix[j][#m-i+1] = m[i][j] return matrix deriveFromMatrix: (name, matrix) => newBlocks = {} for y=1,#matrix for x=1,#matrix[y] if matrix[y][x] table.insert newBlocks, {x-1, y-1} return PolyDef name, @color, @groups, @weight, newBlocks reflect: (name) => newBlocks = {} for bl in *@blocks table.insert newBlocks, {-bl[1] + @max.x, bl[2]} return PolyDef name, @color, @groups, @weight, newBlocks rotate: (name, num) => matrix = @toMatrix! for i=1,num matrix = PolyDef.rotateMatrix matrix return @deriveFromMatrix name, matrix rotate90: (name) => @rotate name, 1 rotate180: (name) => @rotate name, 2 rotate270: (name) => @rotate name, 3 class PolyDefCollection new: (...) => args = {...} @defs = {} @weight = 0 for arg in *args for name,def in pairs arg pdef = PolyDef.fromDef name, def @add pdef t = def.transform if string.find(t, 'rotate') @add pdef\rotate90 name .. '_90' if string.find(t, 'all') @add pdef\rotate180 name .. '_180' @add pdef\rotate270 name .. '_270' if string.find(t, 'reflect') reflected = pdef\reflect name .. '_M' @add reflected if string.find(t, 'rotate') @add reflected\rotate90 name .. '_M90' if string.find(t, 'all') @add reflected\rotate180 name .. '_M180' @add reflected\rotate270 name .. '_M270' add: (def) => @weight += def.weight table.insert @defs, def filter: (...) => groups = {...} pdc = PolyDefCollection! for def in *@defs -- TODO: Actually make it check for containment lol if def\inGroups groups pdc\add def return pdc select: (n=3) => [@random! for i=1,n] random: => r = math.random(1, @weight) for def in *@defs r -= def.weight if r <= 0 return def return {:PolyDef, :PolyDefCollection}
29.361345
68
0.45478
5b85bb49dee17a7fd0be08eb065a946ef267fa23
1,911
Dorothy! SettingPanelView = require "View.Control.Unit.SettingPanel" --MessageBox = require "Control.Basic.MessageBox" SolidRect = require "View.Shape.SolidRect" Class SettingPanelView, __init:=> @_enabled = true thread -> @updateSize! animationTime = 0.6 notifySizeChange = -> @height = @maxHeight-@maskContent.positionY @expandBtn.positionY = @height-30 @mask.position = oVec2 0,-@maskContent.positionY @emit "SizeChanged",@ @expandBtn\slot "Expanded",(expanded)-> if expanded @mask.visible = true @expandBtn.enabled = false @maskContent\perform CCSequence { oPos animationTime,0,0,oEase.OutQuad CCCall -> @expandBtn.enabled = true @mask.visible = false children = [child for child in *@maskContent.children] for child in *children child.parent\removeChild child,false @addChild child notifySizeChange! } else @mask.visible = true @mask.stencil = SolidRect x:-1,y:-1,width:@width+2,height:@height+2-60 @maskContent.positionY = 0 children = [child for child in *@children] for child in *children if child ~= @expandBtn and child ~= @mask child.parent\removeChild child,false @maskContent\addChild child @expandBtn.enabled = false @maskContent\perform CCSequence { oPos animationTime,0,@maxHeight-60,oEase.OutQuad CCCall -> @expandBtn.enabled = true @mask.visible = false notifySizeChange! } @schedule once -> cycle animationTime,notifySizeChange updateSize:=> @removeChild @mask,false @height = @alignItems!.height @alignItems! @maxHeight = @height @addChild @mask isEnabled:property => @_enabled, (value)=> @_enabled = value @enabled = value for child in *@children if child ~= @expandBtn and child ~= @mask child.enabled = value
29.4
75
0.654631
59ed7e599513142493bbbff076474a3faf3755fb
925
M = {} -- redis host M.redis_host = '127.0.0.1' -- redis port M.redis_port = '6379' -- redis password M.redis_password = '' -- redis timeout -- number of milliseconds for redis timeout M.redis_timeout = 5000 -- keepalive -- When == 0, don't use keepalive, and close the connection -- When > 0, is the number of keepalive connection to maintain per nginx worker M.redis_keepalive_pool_size = 5 -- max idle timeout for keepalive connection, in milliseconds M.redis_keepalive_max_idle_timeout = 10000 -- the max number of path parts to look up -- examples -- 1 = host.com/contact -- 2 = host.com/contact/us -- 3 = host.com/contact/us/now M.max_path_length = 1 -- Session Length -- Amount of time (in seconds) you wish the session cookie to live M.session_length = 900 -- Plugin list -- List of plugins to enable within redx. Plugins are executed in given order below M.plugins = { 'random' } M.default_score = 0 return M
24.342105
83
0.726486
a62618b2a3e3fcd1a4b6cfcfebb9146a4da83260
5,700
class BlendMode new: (blendMode, srcContext, dstContext, alpha, offset) -> srcCanvas = srcContext.canvas dstData = dstContext\getImageData(offset.x, offset.y, srcCanvas.width, srcCanvas.height) dst = dstData.data src = srcContext\getImageData(0, 0, srcCanvas.width, srcCanvas.height).data -- source -- backdrop -- destination -- Conversion methods for HSL modes, as described by -- http://www.aiim.org/documents/standards/pdf/blend_modes.pdf -- The setters modify the variables dr, dg, db directly. process = modes[blendMode] return if !process i = 0 l = dst.length while i < l sr = src[i] br = dst[i] sg = src[i + 1] bg = dst[i + 1] sb = src[i + 2] bb = dst[i + 2] sa = src[i + 3] ba = dst[i + 3] a1 = sa * alpha / 255 a2 = 1 - a1 dst[i] = a1 * dr + a2 * br dst[i + 1] = a1 * dg + a2 * bg dst[i + 2] = a1 * db + a2 * bb dst[i + 3] = sa * alpha + a2 * ba i += 4 dstContext\putImageData dstData, offset.x, offset.y getLum = (r, g, b) -> 0.2989 * r + 0.587 * g + 0.114 * b setLum = (r, g, b, l) -> d = l - @getLum(r, g, b) dr = r + d dg = g + d db = b + d l = @getLum(dr, dg, db) mn = @min(dr, dg, db) mx = @max(dr, dg, db) if mn < 0 lmn = l - mn dr = l + (dr - l) * l / lmn dg = l + (dg - l) * l / lmn db = l + (db - l) * l / lmn if mx > 255 ln = 255 - l mxl = mx - l dr = l + (dr - l) * ln / mxl dg = l + (dg - l) * ln / mxl db = l + (db - l) * ln / mxl getSat = (r, g, b) -> max(r, g, b) - min(r, g, b) setSat = (r, g, b, s) -> col = [r, g, b] mx = max(r, g, b) -- max mn = min(r, g, b) -- min md = nil -- mid -- Determine indices for min and max in col: mn = (if mn is r then 0 else (if mn is g then 1 else 2)) mx = (if mx is r then 0 else (if mx is g then 1 else 2)) -- Determine the index in col that is not used yet by min and max, -- and assign it to mid: md = (if min(mn, mx) is 0 then (if max(mn, mx) is 1 then 2 else 1) else 0) -- Now perform the actual algorithm if col[mx] > col[mn] col[md] = (col[md] - col[mn]) * s / (col[mx] - col[mn]) col[mx] = s else col[md] = col[mx] = 0 col[mn] = 0 -- Finally write out the values dr = col[0] dg = col[1] db = col[2] min; math.min max; math.max abs; math.abs sr: nil sg: nil sb: nil sa: nil br: nil bg: nil bb: nil ba: nil dr: nil dg: nil db: nil modes: multiply: -> dr = br * sr / 255 dg = bg * sg / 255 db = bb * sb / 255 screen: -> dr = 255 - (255 - br) * (255 - sr) / 255 dg = 255 - (255 - bg) * (255 - sg) / 255 db = 255 - (255 - bb) * (255 - sb) / 255 overlay: -> dr = (if br < 128 then 2 * br * sr / 255 else 255 - 2 * (255 - br) * (255 - sr) / 255) dg = (if bg < 128 then 2 * bg * sg / 255 else 255 - 2 * (255 - bg) * (255 - sg) / 255) db = (if bb < 128 then 2 * bb * sb / 255 else 255 - 2 * (255 - bb) * (255 - sb) / 255) "soft-light": -> t = sr * br / 255 dr = t + br * (255 - (255 - br) * (255 - sr) / 255 - t) / 255 t = sg * bg / 255 dg = t + bg * (255 - (255 - bg) * (255 - sg) / 255 - t) / 255 t = sb * bb / 255 db = t + bb * (255 - (255 - bb) * (255 - sb) / 255 - t) / 255 "hard-light": -> -- = Reverse of overlay dr = (if sr < 128 then 2 * sr * br / 255 else 255 - 2 * (255 - sr) * (255 - br) / 255) dg = (if sg < 128 then 2 * sg * bg / 255 else 255 - 2 * (255 - sg) * (255 - bg) / 255) db = (if sb < 128 then 2 * sb * bb / 255 else 255 - 2 * (255 - sb) * (255 - bb) / 255) "color-dodge": -> dr = (if sr is 255 then sr else min(255, br * 255 / (255 - sr))) dg = (if sg is 255 then sg else min(255, bg * 255 / (255 - sg))) db = (if sb is 255 then sb else min(255, bb * 255 / (255 - sb))) "color-burn": -> dr = (if sr is 0 then 0 else max(255 - ((255 - br) * 255) / sr, 0)) dg = (if sg is 0 then 0 else max(255 - ((255 - bg) * 255) / sg, 0)) db = (if sb is 0 then 0 else max(255 - ((255 - bb) * 255) / sb, 0)) darken: -> dr = (if br < sr then br else sr) dg = (if bg < sg then bg else sg) db = (if bb < sb then bb else sb) lighten: -> dr = (if br > sr then br else sr) dg = (if bg > sg then bg else sg) db = (if bb > sb then bb else sb) difference: -> dr = br - sr dr = -dr if dr < 0 dg = bg - sg dg = -dg if dg < 0 db = bb - sb db = -db if db < 0 exclusion: -> dr = br + sr * (255 - br - br) / 255 dg = bg + sg * (255 - bg - bg) / 255 db = bb + sb * (255 - bb - bb) / 255 -- HSL Modes: hue: -> setSat sr, sg, sb, getSat(br, bg, bb) setLum dr, dg, db, getLum(br, bg, bb) saturation: -> setSat br, bg, bb, getSat(sr, sg, sb) setLum dr, dg, db, getLum(br, bg, bb) luminosity: -> setLum br, bg, bb, getLum(sr, sg, sb) color: -> setLum sr, sg, sb, getLum(br, bg, bb) -- TODO: Not in Illustrator: add: -> dr = min(br + sr, 255) dg = min(bg + sg, 255) db = min(bb + sb, 255) subtract: -> dr = max(br - sr, 0) dg = max(bg - sg, 0) db = max(bb - sb, 0) average: -> dr = (br + sr) / 2 dg = (bg + sg) / 2 db = (bb + sb) / 2 negation: -> dr = 255 - abs(255 - sr - br) dg = 255 - abs(255 - sg - bg) db = 255 - abs(255 - sb - bb)
26.146789
94
0.460702
26ae56d5ea0cacb752c3cf9e59a78f9430fad7cd
174
Entity = require('lib/entities/entity') class Sign extends Entity new: (...) => super(...) @text = @tile.properties.text onUse: (entity) => print "Sign: #{@text}"
15.818182
39
0.609195
59c6c205075060b0dff14e56952f329b8e6224dd
7,667
export plane = state\new! export env = require "src/env" export ui = require "src/ui" require "lib/deepcopy" plane.load = => math.randomseed os.time! with plane .w = 1700 .h = 1700 .d = 1000 .count = 0 .epoch = 0 .x = -.w / 2 .y = 500 .z = .w .env = ((env.make!\genfood 15, 15)\genheat 4, 4)\genagents 150, .w, .h, .z .status = ui.status.make 20, 20 plane.update = (dt) => plane.count += 1 if @count >= 10000 plane.count = 0 plane.epoch += 1 if @count % 60 == 0 fx = util.randi 0, #plane.env.food fy = util.randi 0, #plane.env.food[1] plane.env.food[fx][fy] = 0.5 -- todo; store this value -- starvation & sweat for i = 0, #plane.env.agents agent = plane.env.agents[i] loss = 0.0002 + 0.0001 * ((math.abs agent.w1) + (math.abs agent.w2)) / 2 loss = 0.001 if agent.w1 < 0.1 and agent.w2 < 0.1 cx = math.floor agent.pos[1] / (plane.w / #plane.env.heat) cy = math.floor agent.pos[2] / (plane.h / #plane.env.heat[1]) heat = plane.env.food[cx][cy] print math.abs heat - agent.fur loss += .001 * math.abs heat - agent.fur if 0.5 < math.abs heat - agent.fur if agent.boosting agent.health -= loss * 4 else agent.health -= loss -- remove deads for i = 1, #plane.env.agents continue unless plane.env.agents[i] if plane.env.agents[i].health <= 0 dying = plane.env.agents[i] num_around = 0 for j = 0, #plane.env.agents continue if j == i agent = plane.env.agents[j] if agent.health > 0 d = util.distance agent.pos, dying.pos if d < 120 num_around += 1 if num_around > 0 for j = 0, #plane.env.agents continue if j == i agent = plane.env.agents[j] d = util.distance agent.pos, dying.pos if d < 120 agent.health += 3 * (1 - agent.herb) ^ 2 / num_around agent.rep_count -= 2 * (1 - agent.herb) ^ 2 / num_around agent.health = 2 if agent.health > 2 for i = 0, #plane.env.agents continue unless plane.env.agents[i] if plane.env.agents[i].health <= 0 table.remove plane.env.agents, i s = math.abs 400 * ((plane.z - 1000) / 1000) with love.keyboard if .isDown "space" plane.z += dt * 400 if .isDown "lshift" plane.z -= dt * 400 if .isDown "a" plane.x += dt * s if .isDown "d" plane.x -= dt * s if .isDown "w" plane.y += dt * s if .isDown "s" plane.y -= dt * s if .isDown "up" for x = 0, #plane.env.heat for y = 0, #plane.env.heat[1] plane.env.heat[x][y] += dt / 2 if .isDown "down" for x = 0, #plane.env.heat for y = 0, #plane.env.heat[1] plane.env.heat[x][y] -= dt / 2 for i = 0, #plane.env.agents plane.env.agents[i]\update plane plane.draw = => love.graphics.push! love.graphics.translate love.graphics.getWidth! / 2, love.graphics.getHeight! / 2 with projection.graphics love.graphics.setColor 200, 200, 200 .square3d fov, "line", {plane.x, plane.y, plane.z}, plane.w, plane.h .square3v fov, "line", {plane.x, plane.y, plane.z - plane.d}, plane.w, plane.h .square3v fov, "line", {plane.x + plane.w, plane.y, plane.z - plane.d}, plane.w, plane.h .square3h fov, "line", {plane.x , plane.y, plane.z - plane.d}, plane.w, plane.h .square3h fov, "line", {plane.x , plane.y + plane.h, plane.z - plane.d}, plane.w, plane.h with projection.graphics -- organisms for i = 0, #plane.env.agents agent = plane.env.agents[i] pos = {plane.x + agent.pos[1], plane.y + agent.pos[2], plane.z - 10} for j = -3, 3 if j == 0 continue love.graphics.setColor 200, 200, 200 eye_pos = {pos[1] + agent.radius * 1.5 * (math.cos agent.angle + j * math.pi / 8), pos[2] + agent.radius * 1.5 * (math.sin agent.angle + j * math.pi / 8), pos[3]} .line fov, pos, eye_pos love.graphics.setColor 255, 255, 255 .circle fov, "fill", eye_pos, 3 love.graphics.setColor 0, 0, 0 .circle fov, "fill", eye_pos, 1 love.graphics.setColor 100, 100, 100 .circle fov, "line", eye_pos, 3 love.graphics.setColor 200, 200, 200 eye_pos1 = {pos[1] + agent.radius * 1.5 * (math.cos agent.angle + math.pi + 3 * math.pi / 16), pos[2] + agent.radius * 1.5 * (math.sin agent.angle - math.pi + 3 * math.pi / 16), pos[3]} eye_pos2 = {pos[1] + agent.radius * 1.5 * (math.cos agent.angle + math.pi - 3 * math.pi / 16), pos[2] + agent.radius * 1.5 * (math.sin agent.angle - math.pi - 3 * math.pi / 16), pos[3]} .line fov, pos, eye_pos1 .line fov, pos, eye_pos2 love.graphics.setColor 255, 255, 255 .circle fov, "fill", eye_pos1, 3 .circle fov, "fill", eye_pos2, 3 love.graphics.setColor 0, 0, 0 .circle fov, "fill", eye_pos1, 1 .circle fov, "fill", eye_pos2, 1 love.graphics.setColor 100, 100, 100 .circle fov, "line", eye_pos1, 3 .circle fov, "line", eye_pos2, 3 love.graphics.setColor 255, 200, agent.fur * 255, math.abs agent.fur * 255 .circle fov, "fill", {pos[1], pos[2], pos[3]}, 12 love.graphics.setColor agent.color[1], agent.color[2], agent.color[3] .circle fov, "fill", pos, 10 love.graphics.setColor 150, 150, 150 .circle fov, "line", pos, 10 love.graphics.setColor 255, 100, 100 .line fov, pos, {pos[1] + (agent.spike_len * 15 * math.cos agent.angle), pos[2] + (agent.spike_len * 15 * math.sin agent.angle), pos[3] - 5} love.graphics.setColor agent.color[1], agent.color[2], agent.color[3] .circle fov, "fill", {pos[1], pos[2], pos[3] - 10}, 10 love.graphics.setColor 150, 150, 150 .circle fov, "line", {pos[1], pos[2], pos[3] - 10}, 10 love.graphics.setColor agent.health * 255, 0, 0 .circle fov, "fill", {pos[1], pos[2], pos[3] - 15}, 5 -- heat fields heatlen = #plane.env.heat for x = 0, #plane.env.heat - 1 for y = 0, #plane.env.heat[1] - 1 love.graphics.setColor plane.env.heat[x][y] * 255, 200, 255 - plane.env.heat[x][y] * 255, 20 .square3d fov, "cross?", {plane.x + x * (plane.w / heatlen), plane.y + y * (plane.h / heatlen), plane.z - 1}, plane.w / heatlen, plane.h / heatlen love.graphics.setColor 200, 200, 200 .square3d fov, "line", {plane.x + x * (plane.w / heatlen), plane.y + y * (plane.h / heatlen), plane.z}, plane.w / heatlen, plane.h / heatlen -- food fields foodlen = #plane.env.food foodw = plane.w / foodlen foodh = plane.h / foodlen for x = 0, #plane.env.food - 1 for y = 0, #plane.env.food[1] - 1 love.graphics.setColor 100, 255, 100, plane.env.food[x][y] * 190 .cube fov, "fill", {plane.x + x * (plane.w / foodlen), plane.y + (y + 1) * (plane.h / foodlen), plane.z - 1}, foodw, foodh, 1 if plane.env.food[x][y] > 0.001 top = {plane.x + x * (plane.w / foodlen) + foodw / 2, plane.y + y * (plane.h / foodlen) + foodh / 2, plane.z - 100} love.graphics.setColor 150, 150, 150 .line fov, {plane.x + x * (plane.w / foodlen) + foodw / 2, plane.y + y * (plane.h / foodlen) + foodh / 2, plane.z}, top love.graphics.setColor 255, 150, 150 .print fov, (string.format "%.1f", plane.env.food[x][y] * 100) .. "%", top love.graphics.pop! plane.status\draw! plane.press = (key) => if key == "return" fx = util.randi 0, #plane.env.food fy = util.randi 0, #plane.env.food[1] plane.env.food[fx][fy] = 1 plane
31.040486
191
0.56528
ce5327613cb977db65aab02787fcc62813951c35
2,423
export RUN_TESTS = false if RUN_TESTS print('Running tests') utility = nil export LOCALIZATION = nil STATE = { PATHS: { RESOURCES: nil } STACK: false } COMPONENTS = { STATUS: nil } export log = (...) -> print(...) if STATE.LOGGING == true -- TODO: Have a look at the possibility of being able to use Lua patterns (square brackets seem to cause issues, but dot works just fine) export Initialize = () -> SKIN\Bang('[!Hide]') STATE.PATHS.RESOURCES = SKIN\GetVariable('@') dofile(('%s%s')\format(STATE.PATHS.RESOURCES, 'lib\\rainmeter_helpers.lua')) COMPONENTS.STATUS = require('shared.status')() success, err = pcall( () -> require('shared.enums') utility = require('shared.utility') utility.createJSONHelpers() COMPONENTS.SETTINGS = require('shared.settings')() export LOCALIZATION = require('shared.localization')(COMPONENTS.SETTINGS) SKIN\Bang(('[!SetOption "WindowTitle" "Text" "%s"]')\format(LOCALIZATION\get('search_window_all_title', 'Search'))) COMPONENTS.STATUS\hide() SKIN\Bang('[!CommandMeasure "Script" "HandshakeSearch()" "#ROOTCONFIG#"]') ) return COMPONENTS.STATUS\show(err, true) unless success export Update = () -> return export Handshake = (stack) -> success, err = pcall( () -> if stack SKIN\Bang(('[!SetOption "WindowTitle" "Text" "%s"]')\format(LOCALIZATION\get('search_window_current_title', 'Search (current games)'))) STATE.STACK = stack meter = SKIN\GetMeter('WindowShadow') skinWidth = meter\GetW() skinHeight = meter\GetH() mainConfig = utility.getConfig(SKIN\GetVariable('ROOTCONFIG')) monitorIndex = nil if mainConfig ~= nil monitorIndex = utility.getConfigMonitor(mainConfig) or 1 else monitorIndex = 1 x, y = utility.centerOnMonitor(skinWidth, skinHeight, monitorIndex) SKIN\Bang(('[!Move "%d" "%d"]')\format(x, y)) SKIN\Bang('[!Show]') SKIN\Bang('[!CommandMeasure "Input" "ExecuteBatch 1"]') ) return COMPONENTS.STATUS\show(err, true) unless success export SetInput = (str) -> success, err = pcall( () -> SKIN\Bang(('[!CommandMeasure "Script" "Search(\'%s\', %s)" "#ROOTCONFIG#"]')\format(str\sub(1, -2), tostring(STATE.STACK))) SKIN\Bang('[!DeactivateConfig]') ) return COMPONENTS.STATUS\show(err, true) unless success export CancelInput = () -> success, err = pcall( () -> SKIN\Bang('[!DeactivateConfig]') ) return COMPONENTS.STATUS\show(err, true) unless success
30.2875
139
0.680974
2c742eff429e790557f71c93e1547a29b61135f3
1,291
import Object from "novacbn/novautils/utilities/Object" -- Platform::Platform() -- Represents a scripting platform that can be targeted by gmodproj -- export export Platform = Object\extend { -- Platform::isProduction -> boolean -- Represents if the current build is in production mode -- isProduction: nil -- Platform::constructor(boolean isProduction) -- Constructor for Platform -- constructor: (@isProduction) => -- Platform::generatePackageHeader(string entryPoint) -> string -- Generates the header code of the built package -- generatePackageHeader: (entryPoint) => "" -- Platform::generatePackageModule(string assetName, string assetChunk) -> string -- Transforms an asset and generates code understood by the platform's module system -- generatePackageModule: (assetName, assetChunk) => error("bad dispatch to 'generatePackageModule' (method not implemented)") -- Platform::generatePackageFooter() -> string -- Generates the footer code of the built package -- generatePackageFooter: () => "" -- Platform::transformPackage(string packageContents) -> string -- Performs a final transformation on the built package -- transformPackage: (packageContents) => packageContents }
34.891892
88
0.706429
ee246a19534ba59cb2e3ce7d0e7cab282b321762
6,053
-- 🍕 lapis = require "lapis" csrf = require "lapis.csrf" config = require("lapis.config").get! crypto = require "crypto" bcrypt = require "bcrypt" import respond_to, json_params from require "lapis.application" import slack_hook, error_channel, bot_name from require "secret" import verify_token from require "helpers" Messages = require "models.Messages" Users = require "users.models.Users" class extends lapis.Application layout: "layout" @include "githook/githook" @include "users/users" [incoming: "/incoming"]: respond_to { GET: => return status: 405, "Method Not Allowed" POST: json_params => unless verify_token @params.token return status: 401, "Unauthorized" if config.verbose and not @params.user_name == "slackbot" human_date = os.date("%c", tonumber(@params.timestamp\sub(1, @params.timestamp\find(".") - 1))) os.execute "curl -X POST --data-urlencode 'payload={\"channel\": \"#{error_channel}\", \"username\": \"#{bot_name}\", \"text\": \"*Saving message from @#{@params.user_name} (#{@params.user_id}) on #{@params.team_domain}.slack.com (#{@params.team_id}):*\\n#{@params.text\gsub("\\", "\\\\")\gsub("'", "’")\gsub("\"", "\\\"")}\\n*[Sent #{human_date} in ##{@params.channel_name} (#{@params.channel_id})]*\", \"icon_emoji\": \":information_source:\"}' #{slack_hook}" message = Messages\create { team_id: @params.team_id team_domain: @params.team_domain channel_id: @params.channel_id channel_name: @params.channel_name timestamp: @params.timestamp user_id: @params.user_id user_name: @params.user_name text: @params.text } if not message and not @params.user_name == "slackbot" human_date = os.date("%c", tonumber(@params.timestamp\sub(1, @params.timestamp\find(".") - 1))) os.execute "curl -X POST --data-urlencode 'payload={\"channel\": \"#{error_channel}\", \"username\": \"#{bot_name}\", \"text\": \"*Error saving message from @#{@params.user_name} (#{@params.user_id}) on #{@params.team_domain}.slack.com (#{@params.team_id}):*\\n#{@params.text\gsub("\\", "\\\\")\gsub("'", "’")\gsub("\"", "\\\"")}\\n*[Sent #{human_date} in ##{@params.channel_name} (#{@params.channel_id})]*\", \"icon_emoji\": \":warning:\"}' #{slack_hook}" } [index: "/"]: => @html -> p "Welcome to Slackiver." --TODO have actual useful stuff here if someone is logged in [all: "/all(/:page[%d])"]: => if @session.id user = Users\find id: @session.id if user.perm_view == 1 page = tonumber(@params.page) or 1 Paginator = Messages\paginated "ORDER BY timestamp ASC", per_page: 50 --if page > Paginator\num_pages! -- return redirect_to: @url_for "all", page: Paginator\num_pages! @show_channel = true @messages = Paginator\get_page page return render: "messages" return status: 401, "Unauthorized" [name_message_list: "/:team_domain/:channel_name(/:page[%d])"]: => if @session.id user = Users\find id: @session.id if user.perm_view == 1 page = tonumber(@params.page) or 1 Paginator = Messages\paginated "WHERE team_domain = ? AND channel_name = ? ORDER BY timestamp ASC", @params.team_domain, @params.channel_name, per_page: 50 --if page > Paginator\num_pages! -- return redirect_to: @url_for "name_message_list", team_domain: @params.team_domain, channel_name: @params.channel_name, page: Paginator\num_pages! @messages = Paginator\get_page page return render: "messages" return status: 401, "Unauthorized" [id_message_list: "/id/:team_id/:channel_id(/:page[%d])"]: => if @session.id user = Users\find id: @session.id if user.perm_view == 1 page = tonumber(@params.page) or 1 Paginator = Messages\paginated "WHERE team_id = ? AND channel_id = ? ORDER BY timestamp ASC", @params.team_id, @params.channel_id, per_page: 50 --if page > Paginator\num_pages! -- return redirect_to: @url_for "id_message_list", team_id: @params.team_id, channel_id: @params.channel_id, page: Paginator\num_pages! @messages = Paginator\get_page page return render: "messages" return status: 401, "Unauthorized" [short_name_message_list: "/:channel_name(/:page[%d])"]: => if @session.id user = Users\find id: @session.id if user.perm_view == 1 page = tonumber(@params.page) or 1 Paginator = Messages\paginated "WHERE channel_name = ? ORDER BY timestamp ASC", @params.channel_name, per_page: 50 --if page > Paginator\num_pages! -- return redirect_to: @url_for "short_name_message_list", channel_name: @params.channel_name, page: Paginator\num_pages! @messages = Paginator\get_page page return render: "messages" return status: 401, "Unauthorized" [short_id_message_list: "/id/:channel_id(/:page[%d])"]: => if @session.id user = Users\find id: @session.id if user.perm_view == 1 page = tonumber(@params.page) or 1 Paginator = Messages\paginated "WHERE channel_id = ? ORDER BY timestamp ASC", @params.channel_id, per_page: 50 --if page > Paginator\num_pages! -- return redirect_to: @url_for "short_id_message_list", channel_id: @params.channel_id, page: Paginator\num_pages! @messages = Paginator\get_page page return render: "messages" return status: 401, "Unauthorized"
46.206107
477
0.586651
b86e00a0c2729219d616d3cedd9ede8d588d7a29
1,748
-- 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' core = require 'ljglibs.core' { :catch_error, :char_p_arr } = require 'ljglibs.glib' C, ffi_gc, ffi_new = ffi.C, ffi.gc, ffi.new flags = {} for flag in *{ 'DEFAULT', 'LEAVE_DESCRIPTORS_OPEN', 'DO_NOT_REAP_CHILD', 'SEARCH_PATH', 'STDOUT_TO_DEV_NULL', 'STDERR_TO_DEV_NULL', 'CHILD_INHERITS_STDIN', 'FILE_AND_ARGV_ZERO', 'SEARCH_PATH_FROM_ENVP', } flags[flag] = C["G_SPAWN_#{flag}"] get_envp = (env) -> return nil unless env char_p_arr ["#{k}=#{v}" for k,v in pairs env] spawn = { async_with_pipes: (opts = {}) -> error '.argv not specified in opts', 2 unless opts.argv argv = char_p_arr opts.argv pid = ffi_new 'GPid[1]' spawn_flags = core.parse_flags('G_SPAWN_', opts.flags) envp = get_envp opts.env stdin = opts.write_stdin and ffi_new('gint[1]') or nil stdout = opts.read_stdout and ffi_new('gint[1]') or nil stderr = opts.read_stderr and ffi_new('gint[1]') or nil catch_error C.g_spawn_async_with_pipes, opts.working_directory, argv, envp, spawn_flags, nil, nil, pid, stdin, stdout, stderr pid = tonumber pid[0] caller_will_reap = bit.band(flags['DO_NOT_REAP_CHILD'], spawn_flags) != 0 destructor = caller_will_reap and nil or ffi_gc ffi_new('struct {}'), -> C.g_spawn_close_pid pid { :pid flags: spawn_flags stdin_pipe: stdin and stdin[0] or nil stdout_pipe: stdout and stdout[0] or nil stderr_pipe: stderr and stderr[0] or nil __destructor: destructor } } spawn[flag] = flags[v] for flag, v in pairs flags spawn
24.971429
79
0.666476
a93682f0f151712145ba9cc4390c80951d006691
2,314
#!/usr/bin/env moon import attributes, dir, mkdir from require"lfs" import wrap, yield from coroutine import open, stderr from io import exit from os import concat, sort from table TEMPLATES = "./templates" OPTIONS = { path: false name: false short_name: false description: "" lang: "fr-FR" background_color: "white" theme_color: "black" start_url: "/" } err = (...) -> stderr\write("#{concat {...}, " "}\n") opairs = (fn) => _k = [k for k in pairs @] sort _k, fn i = 0 -> i += 1 k = _k[i] k, @[k] do mandatory_options = [" --#{k}=#{k\upper!}" for k, v in opairs OPTIONS when not v] other_options = [" --#{k}=#{k\upper!} (#{v})" for k, v in opairs OPTIONS when v] mandatory = "\n\n Mandatory options:#{#mandatory_options > 0 and '\n' .. concat(mandatory_options, '\n') or ' none'}" or "" other = #other_options > 0 and "\n\n Other options:\n#{concat other_options, '\n'}" or "" export USAGE = "Usage: #{arg[0]} [OPTIONS]#{mandatory}#{other}" do for opt in *arg if opt == "-h" or opt == "--help" print USAGE exit 0 k, v = opt\match("%-%-(.*)=(.*)") if OPTIONS[k] ~= nil OPTIONS[k] = v else err "Unknown argument: #{k}.\n\n#{USAGE}" exit 1 ok = true for k in pairs OPTIONS unless OPTIONS[k] err "Missing mandatory argument: #{k}." ok = false unless ok err "\n#{USAGE}" exit 1 do opt_path = OPTIONS.path path = opt_path\sub(1, 1) == "/" and "/" or "" for d in opt_path\gmatch "[^/]+" path ..= "#{d}/" mkdir path OPTIONS.path = path\sub 1, -2 generate_project = (input_dir, output_dir) -> for template in dir input_dir continue if template\match "^%." input_path = "#{input_dir}/#{template}" output_path = "#{output_dir}/#{template}" switch attributes input_path, "mode" when "directory" mkdir output_path generate_project input_path, output_path when "file" input = assert open input_path, "r" content = input\read "*a" input\close! for k in content\gmatch "<<<(.-)>>>" content = content\gsub("<<<#{k}>>>", OPTIONS[k]) if OPTIONS[k] output = assert open output_path, "w" output\write content output\close! generate_project TEMPLATES, OPTIONS.path
26.597701
126
0.585134
a8e0760cbddc99c6c5642cd0ae391375c27130cb
925
-- Copyright 2012-2015 The Howl Developers -- License: MIT (see LICENSE.md at the top-level directory of the distribution) import clipboard, interact from howl clip_completions = -> completions = {} for i, clip in ipairs clipboard.clips text = clip.text\gsub '\n', '..↩' 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! 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' } } .auto_trim = true selected = interact.select opts if selected return selected.clip
23.717949
79
0.641081
704c102782b69e9bf688f0b8618670e6d48ef55e
351
Entity = require "Lutron/Entity/Entity" class Image extends Entity new: (path, width, height, state) => super 0, 0, width, height, state @path = path @image = nil @width width @height height load: => @image = lutro.graphics.newImage(@path) draw: => super! lutro.graphics.draw(@image, @position.x, @position.y)
20.647059
57
0.62963
069aa567a107184c58f82b7b4232cac8bc6014e4
333
listFold = zb2rhbksBjR3yFP98YrEGss6Yv7wVCgNbYtWiwz9nGRSAoiAa big => val => end => res = (listFold big { val: digit => res => cut = (mul (eql digit 0) (get res "cut")) big = (if cut (get res "big") (val digit (get res "big"))) {cut:cut big:big} end: {cut:1 big:end} }) (get res "big")
25.615385
66
0.54955
427c2ae47f0269cde1253f5e3f78e9b594a4a3f8
1,205
maeperform = require 'mae.perform' stub maeperform, 'handle' match = require 'luassert.match' describe 'sugar', -> describe 'effects', -> import effects from require 'mae.sugar' it 'creates a table with handlers', -> a = effects! assert.equal 'table', type a.handlers assert.same {}, a.handlers it 'can add handlers', -> a = effects! a\handle 'a', 'b' assert.same {a: 'b'}, a.handlers a\handle 'c', 'd' assert.same {a: 'b', c: 'd'}, a.handlers it 'can remove handlers', -> a = effects! a\handle 'a', 'b' a\handle 'c', 'd' a\unhandle 'a' assert.same {c: 'd'}, a.handlers a\unhandle 'c' assert.same {}, a.handlers it 'can call functions', -> a = effects! f = -> a\run f assert.stub(maeperform.handle).was.called_with f, match.is_same {} describe 'value', -> import value from require 'mae.sugar' it 'returns the value property of things', -> a = {value: 1} assert.equal 1, value a describe 'wrap', -> import wrap from require 'mae.sugar' it 'wraps handle', -> handlers = {} f = -> w = wrap handlers assert.equal 'function', type w w f assert.stub(maeperform.handle).was.called_with f, handlers
21.909091
69
0.616598
a181a891b8f7816383980e1082491a5dd8104b93
717
import is_value from require "moonscript.types" construct_comprehension = (inner, clauses) -> current_stms = inner for i=#clauses,1,-1 clause = clauses[i] t = clause[1] current_stms = switch t when "for" {_, name, bounds} = clause {"for", name, bounds, current_stms} when "foreach" {_, names, iter} = clause {"foreach", names, {iter}, current_stms} when "when" {_, cond} = clause {"if", cond, current_stms} else error "Unknown comprehension clause: "..t current_stms = {current_stms} current_stms[1] comprehension_has_value = (comp) -> is_value comp[2] {:construct_comprehension, :comprehension_has_value}
23.129032
52
0.622036
4a226edcd96125d66bc983b1fdc99ce2dbcbfa92
5,276
-- Copyright 2016 Jake Russo -- License: MIT howl.aux.lpeg_lexer -> word = (...) -> word_char = alpha + digit + S'_-+?!' (-B(1) + B(-word_char)) * any(...) * -word_char c = capture ident_filler = (alpha + digit + S'_-+?!')^0 ident = (alpha + S'$#')^1 * ident_filler ws = c 'whitespace', blank identifier = c 'identifier', ident fdecl = c('keyword', word { 'defn', 'defmulti', 'defmethod' }) * (c 'operator', '*')^0 * ws^1 * c('type_def', ident) * (ws^1 + #P'<') decl = c('keyword', word {'defstruct', 'defpackage', 'deftype'}) * ws^1 * c('label', ident) keyword = c 'keyword', word { 'if', 'else', 'when', 'switch', 'match', 'let', 'let-var', 'where', 'for', 'while', 'label', 'yield', 'try', 'catch', 'finally', 'throw', 'attempt', 'fn', 'fn*', 'multifn', 'multifn*', 'qquote', 'return', 'call-c', 'val', 'var', 'import', 'with' } declarator = c 'member', word { 'val', 'var', 'label', 'let', 'let-var', 'new' } functions = c 'function', word({ 'not-equal', 'not-equal?', 'equal', 'equal?', 'compare', 'less?', 'less-eq?', 'greater?', 'greater-eq?', 'to-seq', 'maximum', 'max', 'minimum', 'min', 'hash', 'length', 'push', 'empty?', 'next', 'peek', 'get?', 'get', 'set', 'map!', 'map', 'reverse!', 'reverse', 'in-reverse', 'println-all', 'println', 'print-all', 'print', 'with-output-stream', 'current-output-stream', 'get-char', 'get-byte', 'do-indented', 'indented', 'put', 'close', 'with-output-file', 'spit', 'write-all', 'write', 'close', 'slurp', 'peek?', 'info', 'bits-as-float', 'bits-as-double', 'bits', 'rand', 'fill-template', 'fill', 'ceil-log2', 'floor-log2', 'next-pow2', 'prev-pow2', 'sum', 'product', 'complement', 'digit?', 'letter?', 'upper-case?', 'upper-case', 'lower-case?', 'lower-case', 'start', 'end', 'step', 'inclusive?', 'to-string', 'matches?', 'prefix?', 'suffix?', 'append-all', 'append', 'string-join', 'last-index-of-chars', 'last-index-of-char', 'replace', 'trim', 'add-all', 'add', 'clear', 'to-array', 'get-chars', 'set-chars', 'to-tuple', 'cons', 'to-list', 'head', 'headn', 'tail', 'tailn', 'but-last', 'last', 'transpose', 'seq-append', 'filename', 'line', 'column', 'item', 'unwrap-token', 'unwrap-all', 'key?', 'keys?', 'key', 'value?', 'value!', 'values', 'value', 'to-symbol', 'symbol-join', 'gensym', 'name', 'id', 'qualified?', 'qualifier', 'throw', 'with-exception-handler', 'with-finally', 'try-catch-finally', 'fatal', 'fail', 'with-attempt', 'attempt-else', 'generate', 'resume', 'suspend', 'break', 'close', 'active?', 'open?', 'dynamic-wind', 'find!', 'find', 'first!', 'first', 'seq?', 'seq', 'filter', 'index-when!', 'index-when', 'split', 'take-while', 'take-until', 'seq-cat', 'all?', 'none?', 'any?', 'count', 'repeat_while', 'repeat', 'repeatedly', 'take-n', 'take-up-to-n', 'cat-all', 'cat', 'join', 'zip-all', 'zip', 'contains?', 'index-of!', 'index-of', 'reduce-right', 'reduce', 'unique', 'lookup??', 'parallel-seq', 'qsort!', 'lazy-qsort', 'marker!', 'marker', 'add-gc-notifier', 'command-line-arguments', 'file-exists?', 'delete-file', 'resolve-path', 'current-time-ms', 'current-time-us', 'get-env', 'set-env', 'call-system', 'stop', 'time', 'exp', 'log10', 'log', 'pow', 'sin', 'cos', 'tan', 'asin', 'acos', 'atan', 'atan2', 'sinh', 'cosh', 'tanh', 'ceil', 'floor', 'round', 'to-radians', 'to-degrees', 'to-vector', 'pop', 'peek', 'remove-item', 'remove-when', 'remove', 'update', 'shorten', 'lengthen', 'default?', 'read-file', 'read-all', 'read', 'tagged-list?' }) * #S'({' constant = c 'constant', word { 'true', 'false', 'this' } lotypes = c 'type', upper * ident_filler uniqtypes = c 'special', (word { 'ref', 'ptr' }) + (-B'%w' * '?') lostanza = c 'type', word { 'byte', 'int', 'long', 'float', 'double' } modifier = c 'special', word { 'public', 'protected', 'extern', 'lostanza' } wordop = c 'operator', word { 'to', 'through', 'by', 'in', 'and', 'or', 'not', 'as', 'as?', 'is', 'do', 'seq' } operator = c 'operator', S'~!@#$%^*+-=/.:&|<>'^1 comment = c 'comment', P';' * scan_until eol number = c 'number', digit * scan_until(ws + S'()[]{}' + operator + eol) char = c 'char', P"'" * (P'\\' * P(1) + P(1)) * P"'" P { 'all' all: any { comment, V'string', V'deref', V'fndel', char, number, declarator, wordop, lostanza, modifier, fdecl, decl, keyword, functions, constant, lotypes, uniqtypes, operator, identifier } string: sequence { c('string', '"'), V'string_chunk', c('string', '"') } string_chunk: c('string', scan_until(any('"', '%'), '\\')) * any { #P('"'), V'interpolation' * V'string_chunk', c('string', P(1)) * V'string_chunk' } interpolation: c 'operator', P'%' * S'_*,~@%' deref: sequence { c('blue', B(eol + blank) * '['), any({ ws, V'all', S'()' })^1, c('blue', ']') } fndel: sequence { c('fdecl', '{'), any({ ws, c('constant', P'_'), V'all', })^1, c('fdecl', '}') } }
34.940397
104
0.517437
d5c8e3b459827747fcde592b7538809251f9e656
5,165
class Point extends Base _readIndex: true new: (arg0, arg1) => _type = type(arg0) if _type is "number" hasY = type(arg1) is "number" @x = arg0 @y = (if hasY then arg1 else arg0) @_read = (if hasY then 2 else 1) if @_read else if arg0 is null @x = @y = 0 @_read = (if arg0 is null then 1 else 0) if @_read else if _type is "" @x = arg0[0] @y = (if arg0.length > 1 then arg0[1] else arg0[0]) else if arg0.x? @x = arg0.x @y = arg0.y else if arg0.width? @x = arg0.width @y = arg0.height else if arg0.angle? @x = arg0.length @y = 0 @setAngle arg0.angle else @x = @y = 0 @_read = 0 if @_read @_read = 1 if @_read set: (x, y) => @x = x @y = y equals: (point) => point is @ or point and (@x is point.x and @y is point.y or isArray(point) and @x is point[0] and @y is point[1]) or false clone: => Point(@x, @y) add: (point) => point = Point\read(arg) Point(@x + point.x, @y + point.y) subtract: (point) => point = Point\read(arg) Point(@x - point.x, @y - point.y) multiply: (point) => point = Point.read(arg) Point(@x * point.x, @y * point.y) divide: (point) => point = Point\read(arg) Point(@x / point.x, @y / point.y) modulo: (point) => point = Point\read(arg) Point(@x % point.x, @y % point.y) negate: => Point(-@x, -@y) transform: (matrix) => (if matrix then matrix._transformPoint(@) else @) getDistance: (point, squared) => point = Point\read(arg) x = point.x - @x y = point.y - @y d = x * x + y * y (if squared then d else math.sqrt(d)) getLength: (...) => -- Supports a hidden parameter 'squared', which controls whether the -- squared length should be returned. Hide it so it produces a bean -- property called #length. length = @x * @x + @y * @y (if arg.length and arg[0] then length else math.sqrt(length)) setLength: (length) => -- Whenever setting x/y, use #set() instead of direct assignment, -- so LinkedPoint does not report changes twice. if @isZero() angle = @_angle or 0 @set math.cos(angle) * length, math.sin(angle) * length else scale = length / @getLength() -- Force calculation of angle now, so it will be preserved even when -- x and y are 0 @getAngle() if scale is 0 @set @x * scale, @y * scale normalize: (length) => length = 1 if length is `undefined` current = @getLength() scale = (if current isnt 0 then length / current else 0) point = new Point(@x * scale, @y * scale) # Preserve angle. point._angle = @_angle point getAngle: (...) -> -- Hide parameters from Bootstrap so it injects bean too @getAngleInRadians(arg[0]) * 180 / math.PI setAngle: (angle) => angle = @_angle = angle * Math.PI / 180 if !@isZero() length = @getLength() -- Use #set() instead of direct assignment of x/y, so LinkedPoint -- does not report changes twice. @set math.cos(angle) * length, math.sin(angle) * length getAngleInRadians: => if arg[0] == nil @_angle = math.atan2(@y, @x) if !@_angle? @_angle else point = Point\read(arguments_) div = @getLength() * point\getLength() if Numerical\isZero(div) '' else math.acos @dot(point) / div getAngleInDegrees: => @getAngle arg[0] getQuadrant: => (if @x >= 0 then (if @y >= 0 then 1 else 4) else (if @y >= 0 then 2 else 3)) getDirectedAngle: (point) => point = Point\read(arg) math.atan2(@cross(point), @dot(point)) * 180 / math.PI rotate: (angle, center) => return @clone() if angle is 0 angle = angle * Math.PI / 180 point = (if center then @subtract(center) else @) s = math.sin(angle) c = math.cos(angle) point = Point(point.x * c - point.y * s, point.y * c + point.x * s) (if center then point\add(center) else point) isInside: (rect) => rect.contains @ isClose: (point, tolerance) => @getDistance(point) < tolerance isColinear: (point) => @cross(point) < Numerical.TOLERANCE isOrthogonal: (point) => @dot(point) < Numerical.TOLERANCE isZero: => Numerical\isZero(@x) and Numerical\isZero(@y) isNaN: => isNaN(@x) or isNaN(@y) dot: (point) => point = Point\read(arg) @x * point.x + @y * point.y cross: (point) => point = Point\read(arg) @x * point.y - @y * point.x project: (point) => point = Point\read(arg) if point\isZero() Point(0, 0) else scale = @dot(point) / point\dot(point) Point(point.x * scale, point.y * scale) @min: (point1, point2) => _point1 = Point\read(arg) _point2 = Point\read(arg) Point(math.min(_point1.x, _point2.x), math.min(_point1.y, _point2.y)) @max: (point1, point2) => _point1 = Point.read(arg) _point2 = Point.read(arg) Point(math.max(_point1.x, _point2.x), math.max(_point1.y, _point2.y)) @random: => Point(math.random(), math.random())
26.085859
126
0.565537
0f3d057f32ec59a0b09ee7e3aa29991b9dba1ed0
24,309
-- Copyright (C) 2017-2019 DBot -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -- of the Software, and to permit persons to whom the Software is furnished to do so, -- subject to the following conditions: -- The above copyright notice and this permission notice shall be included in all copies -- or substantial portions of the Software. -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, -- INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR -- PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE -- FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -- OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -- DEALINGS IN THE SOFTWARE. -- editor stuffs gui.ppm2.dxlevel.not_supported = 'Выставленный уровень DirectX™ слишком низок для работы PPM/2. Необходимый минимум - 9.0.\nДолжно быть, вы используете DirectX™ ниже 9.0 по причине видеокарты 2004 года или плохих драйверов.\nНо если вы используете DirectX™ ниже 9.0 ради FPS - то это тупо ещё большая нагрузка на видеокарту, так как\nв gmod FPS зависит прямо от нагрузки ЦП другими аддонами от Васи228, которые, кстати, с этим очень хорошо справляются.' gui.ppm2.dxlevel.toolow = 'Уровень технологии DirectX™ слишком низок для работы PPM/2' gui.ppm2.editor.eyes.separate = 'Использовать разные настройки для глаз' gui.ppm2.editor.eyes.url = 'URL текстура глаза' gui.ppm2.editor.eyes.url_desc = 'Когда используется URL текстура; настройки снизу не имеют силы' gui.ppm2.editor.eyes.lightwarp_desc = 'Lightwarp имеет эффект только на EyeRefract глаза' gui.ppm2.editor.eyes.lightwarp = "Lightwarp" gui.ppm2.editor.eyes.desc1 = "Lightwarp URL текстура\nОБЯЗАНА БЫТЬ 256x16!" gui.ppm2.editor.eyes.desc2 = "Сила 'Зеркалья' у глаз\nЭтот параметр влияет на отражения в режиме Отражений в реальном времени\nЗа это отвечает переменная клиента ppm2_cl_reflections\nОстальные игроки увидят отражения только с ppm2_cl_reflections 1\n0 - матовая поверхность; 1 - зеркальная" for _, {tprefix, prefix} in ipairs {{'def', ''}, {'left', 'Left '}, {'right', 'Right '}} gui.ppm2.editor.eyes[tprefix].lightwarp.shader = "#{prefix}Использовать шейдер EyeRefract" gui.ppm2.editor.eyes[tprefix].lightwarp.cornera = "#{prefix}Испольщовать Cornera диффуз текстуру" gui.ppm2.editor.eyes[tprefix].lightwarp.glossiness = "#{prefix}Стеклянность (?)" gui.ppm2.editor.eyes[tprefix].type = "#{prefix}Тип глаза" gui.ppm2.editor.eyes[tprefix].reflection_type = "#{prefix}Тип отражений глаза" gui.ppm2.editor.eyes[tprefix].lines = "#{prefix}Линии радужной оболочки" gui.ppm2.editor.eyes[tprefix].derp = "#{prefix}Derp глаз" gui.ppm2.editor.eyes[tprefix].derp_strength = "#{prefix}Сила Derp глаза" gui.ppm2.editor.eyes[tprefix].iris_size = "#{prefix}Размер глаза" gui.ppm2.editor.eyes[tprefix].points_inside = "#{prefix}Линии радужной оболочки смотрят внутрь" gui.ppm2.editor.eyes[tprefix].width = "#{prefix}Ширина глаза" gui.ppm2.editor.eyes[tprefix].height = "#{prefix}Высота глаза" gui.ppm2.editor.eyes[tprefix].pupil.width = "#{prefix}Ширина зрачка" gui.ppm2.editor.eyes[tprefix].pupil.height = "#{prefix}Высота зрачка" gui.ppm2.editor.eyes[tprefix].pupil.size = "#{prefix}Размер зрачка" gui.ppm2.editor.eyes[tprefix].pupil.shift_x = "#{prefix}Сдвиг зрачка по X" gui.ppm2.editor.eyes[tprefix].pupil.shift_y = "#{prefix}Сдвиг зрачка по Y" gui.ppm2.editor.eyes[tprefix].pupil.rotation = "#{prefix}Поворот глаза" gui.ppm2.editor.eyes[tprefix].background = "#{prefix}Фон глаза" gui.ppm2.editor.eyes[tprefix].pupil_size = "#{prefix}Зрачок" gui.ppm2.editor.eyes[tprefix].top_iris = "#{prefix}Верхняя радужная оболочка" gui.ppm2.editor.eyes[tprefix].bottom_iris = "#{prefix}Нижняя радужная оболочка" gui.ppm2.editor.eyes[tprefix].line1 = "#{prefix}Радужная линия 1" gui.ppm2.editor.eyes[tprefix].line2 = "#{prefix}Радужная линия 2" gui.ppm2.editor.eyes[tprefix].reflection = "#{prefix}Эффект отражения" gui.ppm2.editor.eyes[tprefix].effect = "#{prefix}Эффект мультяшного глаза" gui.ppm2.editor.generic.title = 'PPM/2 Пони редактор' gui.ppm2.editor.generic.title_file = '%q - PPM/2 Пони редактор' gui.ppm2.editor.generic.title_file_unsaved = '%q* - PPM/2 Пони редактор (несохраненные изменения!)' gui.ppm2.editor.generic.yes = 'Даа!' gui.ppm2.editor.generic.no = 'Ниань!' gui.ppm2.editor.generic.ohno = 'Ойнет!' gui.ppm2.editor.generic.okay = 'Окай ;w;' gui.ppm2.editor.generic.datavalue = '%s\nID в коде: %q' gui.ppm2.editor.generic.url = '%s\n\nСсылка ведёт на: %s' gui.ppm2.editor.generic.url_field = 'URL поле' gui.ppm2.editor.generic.spoiler = 'Таинственный спойлер' gui.ppm2.editor.generic.restart.needed = 'Необходим перезапуск редактора' gui.ppm2.editor.generic.restart.text = 'Вы должны перезапустить редактор для изменений.\nПерезапустить сейчас?\nНесохраненные изменения будут утрачены!' gui.ppm2.editor.generic.fullbright = 'Без затенения' gui.ppm2.editor.generic.wtf = 'Волею хаоса у вас отсутствует NetworkedPonyData который необходимо изменять.\nПопробуйте выполнить ppm2_reload в консоли и открыть редактор снова.' gui.ppm2.editor.io.random = 'Рандомизировать!' gui.ppm2.editor.io.newfile.title = 'Новый файл' gui.ppm2.editor.io.newfile.confirm = 'Вы действительно хотите создать новый файл?' gui.ppm2.editor.io.newfile.toptext = 'Сбросить' gui.ppm2.editor.io.delete.confirm = 'Вы действительно хотите удалить данный файл?\nОн пропадет навсегда!\n(очень долгое время!)' gui.ppm2.editor.io.delete.title = 'Действительно удалить?' gui.ppm2.editor.io.filename = 'Имя файла' gui.ppm2.editor.io.hint = 'Можно открыть двойным нажатием' gui.ppm2.editor.io.reload = 'Перезагрузить список файлов' gui.ppm2.editor.io.failed = 'Ошибка импорта.' gui.ppm2.editor.io.warn.oldfile = '!!! Это может или сработать или нет. Вы будете аннигилированы.' gui.ppm2.editor.io.warn.text = "В данный момент вы не сохранили свои изменения.\nВы действительно хотите открыть другой файл?" gui.ppm2.editor.io.warn.header = 'Несохраненные изменения!' gui.ppm2.editor.io.save.button = 'Сохранить' gui.ppm2.editor.io.save.text = 'Введите имя файла без ppm2/ и .dat\nПодсказка: что бы сохранить файл как авто-загружаемый, введите "_current" (без кавычек)' gui.ppm2.editor.io.wear = 'Применить изменения' gui.ppm2.editor.seq.standing = 'Стоит' gui.ppm2.editor.seq.move = 'Двигается' gui.ppm2.editor.seq.walk = 'Беспечно идет' gui.ppm2.editor.seq.sit = 'Сидит' gui.ppm2.editor.seq.swim = 'Плавает' gui.ppm2.editor.seq.run = 'Бежит' gui.ppm2.editor.seq.duckwalk = 'Идет вприсядку' gui.ppm2.editor.seq.duck = 'Присел' gui.ppm2.editor.seq.jump = 'Прыжок' gui.ppm2.editor.misc.race = 'Раса' gui.ppm2.editor.misc.weight = 'Вес' gui.ppm2.editor.misc.size = 'Размер пони' gui.ppm2.editor.misc.hide_weapons = 'Скрывать ли оружия' gui.ppm2.editor.misc.chest = 'Бафф груди' gui.ppm2.editor.misc.gender = 'Пол' gui.ppm2.editor.misc.wings = 'Тип крыльев' gui.ppm2.editor.misc.flexes = 'Управление flexами' gui.ppm2.editor.misc.no_flexes2 = 'Отключить flex на новых моделях' gui.ppm2.editor.misc.no_flexes_desc = 'Вы можете отдельно отключить любой flex\nПоэтому они могут быть изменены третьим кодом (таким как PAC3)' gui.ppm2.editor.misc.hide_pac3 = 'Скрывать ентити когда используется PAC3 entity' gui.ppm2.editor.misc.hide_mane = 'Скрывать гриву когда используется PAC3 entity' gui.ppm2.editor.misc.hide_tail = 'Скрывать хвост когда используется PAC3 entity' gui.ppm2.editor.misc.hide_socks = 'Скрывать носки когда используется PAC3 entity' gui.ppm2.editor.tabs.main = 'Общее' gui.ppm2.editor.tabs.files = 'Файлы' gui.ppm2.editor.tabs.old_files = 'Старые файлы' gui.ppm2.editor.tabs.cutiemark = 'Кьютимарка' gui.ppm2.editor.tabs.head = 'Анатомия головы' gui.ppm2.editor.tabs.eyes = 'Глаза' gui.ppm2.editor.tabs.face = 'Лицо' gui.ppm2.editor.tabs.mouth = 'Рот' gui.ppm2.editor.tabs.left_eye = 'Левый глаз' gui.ppm2.editor.tabs.right_eye = 'Правый глаз' gui.ppm2.editor.tabs.mane_horn = 'Грива и рог' gui.ppm2.editor.tabs.mane = 'Грива' gui.ppm2.editor.tabs.details = 'Детали' gui.ppm2.editor.tabs.url_details = 'URL Детали' gui.ppm2.editor.tabs.url_separated_details = 'Отдельные URL Детали' gui.ppm2.editor.tabs.ears = 'Уши' gui.ppm2.editor.tabs.horn = 'Рог' gui.ppm2.editor.tabs.back = 'Спина' gui.ppm2.editor.tabs.wings = 'Крылья' gui.ppm2.editor.tabs.left = 'Правое' gui.ppm2.editor.tabs.right = 'Левое' gui.ppm2.editor.tabs.neck = 'Шея' gui.ppm2.editor.tabs.body = 'Тело пони' gui.ppm2.editor.tabs.tattoos = 'Тату' gui.ppm2.editor.tabs.tail = 'Хвост' gui.ppm2.editor.tabs.hooves = 'Анатомия копыт' gui.ppm2.editor.tabs.bottom_hoof = 'Нижняя часть' gui.ppm2.editor.tabs.legs = 'Ноги' gui.ppm2.editor.tabs.socks = 'Носки' gui.ppm2.editor.tabs.newsocks = 'Новые носки' gui.ppm2.editor.tabs.about = 'О PPM/2' gui.ppm2.editor.old_tabs.mane_tail = 'Грива и хвост' gui.ppm2.editor.old_tabs.wings_and_horn_details = 'Детали крыльев и рога' gui.ppm2.editor.old_tabs.wings_and_horn = 'Крылья и рог' gui.ppm2.editor.old_tabs.body_details = 'Детали тела' gui.ppm2.editor.old_tabs.mane_tail_detals = 'URL детали хвоста и гривы' gui.ppm2.editor.cutiemark.display = 'Отображать кьютимарку' gui.ppm2.editor.cutiemark.type = 'Тип кьютимарки' gui.ppm2.editor.cutiemark.size = 'Размер кьютимарки' gui.ppm2.editor.cutiemark.color = 'Цвет кьютимарки' gui.ppm2.editor.cutiemark.input = 'URL кьютимарка\nДолжна быть в формате PNG или JPEG (СЖИМАЕШЬ, НЕБОСЬ?) (работает так же\nкак PAC3 URL текстура)' gui.ppm2.editor.face.eyelashes = 'Ресницы' gui.ppm2.editor.face.eyelashes_color = 'Цвет ресниц' gui.ppm2.editor.face.eyelashes_phong = 'Фонг параметры ресниц' gui.ppm2.editor.face.eyebrows_color = 'Цвет бровей' gui.ppm2.editor.face.new_muzzle = 'Использовать новую мордочку' gui.ppm2.editor.face.nose = 'Цвет ноздрей' gui.ppm2.editor.face.lips = 'Цвет губ' gui.ppm2.editor.face.eyelashes_separate_phong = 'Отделить фонг настройки ресниц от тела' gui.ppm2.editor.face.eyebrows_glow = 'Светящиеся ресницы' gui.ppm2.editor.face.eyebrows_glow_strength = 'Сила свечения' gui.ppm2.editor.face.inherit.lips = 'Наследовать цвет губ от тела' gui.ppm2.editor.face.inherit.nose = 'Наследовать цвет ноздрей от тела' gui.ppm2.editor.mouth.fangs = 'Клыки' gui.ppm2.editor.mouth.alt_fangs = 'Альтернативные клыки' gui.ppm2.editor.mouth.claw = 'Акульи зубы' gui.ppm2.editor.mouth.teeth = 'Цвет зубов' gui.ppm2.editor.mouth.teeth_phong = 'Фонг параметры зубов' gui.ppm2.editor.mouth.mouth = 'Цвет полости рта' gui.ppm2.editor.mouth.mouth_phong = 'Фонг параметры рта' gui.ppm2.editor.mouth.tongue = 'Цвет языка' gui.ppm2.editor.mouth.tongue_phong = 'Фонг параметры языка' gui.ppm2.editor.mane.type = 'Тип гривы' gui.ppm2.editor.mane.phong = 'Отделить фонг настройки гривы от тела' gui.ppm2.editor.mane.mane_phong = 'Фонг параметры гривы' gui.ppm2.editor.mane.phong_sep = 'Отделить нижний и верхний цвета гривы' gui.ppm2.editor.mane.up.phong = 'Фонг настройки верхней гривы' gui.ppm2.editor.mane.down.type = 'Lower Mane Type' gui.ppm2.editor.mane.down.phong = 'Фонг настройки нижней гривы' gui.ppm2.editor.mane.newnotice = 'Следующие опции имеют эффект только на новой модели' for i = 1, 2 gui.ppm2.editor.mane['color' .. i] = "Цвет гривы #{i}" gui.ppm2.editor.mane.up['color' .. i] = "Цвет верхней гривы #{i}" gui.ppm2.editor.mane.down['color' .. i] = "Цвет нижней гривы #{i}" for i = 1, 6 gui.ppm2.editor.mane['detail_color' .. i] = "Деталь гривы #{i}" gui.ppm2.editor.mane.up['detail_color' .. i] = "Деталь верхней гривы #{i}" gui.ppm2.editor.mane.down['detail_color' .. i] = "Деталь нижней гривы #{i}" gui.ppm2.editor.url_mane['desc' .. i] = "URL деталь гривы #{i}" gui.ppm2.editor.url_mane['color' .. i] = "Цвет URL детали #{i}" gui.ppm2.editor.url_mane.sep.up['desc' .. i] = "URL деталь верхней гривы #{i}" gui.ppm2.editor.url_mane.sep.up['color' .. i] = "Цвет URL детали верхней гривы #{i}" gui.ppm2.editor.url_mane.sep.down['desc' .. i] = "URL деталь нижней гривы #{i}" gui.ppm2.editor.url_mane.sep.down['color' .. i] = "Цвет URL детали нижней гривы #{i}" gui.ppm2.editor.ears.bat = 'Уши бэт-пони' gui.ppm2.editor.ears.size = 'Размер ушей' gui.ppm2.editor.horn.detail_color = 'Цвет детали рога' gui.ppm2.editor.horn.glowing_detail = 'Светящаяся деталь рога' gui.ppm2.editor.horn.glow_strength = 'Сила свечения' gui.ppm2.editor.horn.separate_color = 'Отделить цвет рога от тела' gui.ppm2.editor.horn.color = 'Цвет рога' gui.ppm2.editor.horn.horn_phong = 'Фонг параметры рога' gui.ppm2.editor.horn.magic = 'Цвет магии рога' gui.ppm2.editor.horn.separate_magic_color = 'Отделить цвет магии от цвета глаз' gui.ppm2.editor.horn.separate = 'Отделить цвет рога от тела' gui.ppm2.editor.horn.separate_phong = 'Отделить настройки фонга рога от тела' for i = 1, 3 gui.ppm2.editor.horn.detail['desc' .. i] = "URL деталь рога #{i}" gui.ppm2.editor.horn.detail['color' .. i] = "Цвет URL детали рога #{i}" gui.ppm2.editor.wings.separate_color = 'Отделить цвет крыльев от тела' gui.ppm2.editor.wings.color = 'Цвет крыльев' gui.ppm2.editor.wings.wings_phong = 'Фонг параметры крыльев' gui.ppm2.editor.wings.separate = 'Отделить цвет крыльев от тела' gui.ppm2.editor.wings.separate_phong = 'Отделить настройки фонга крыльев от тела' gui.ppm2.editor.wings.bat_color = 'Цвет крыльев летучей мыши' gui.ppm2.editor.wings.bat_skin_color = 'Цвет кожи крыльев летучей мыши' gui.ppm2.editor.wings.bat_skin_phong = 'Фонг параметры кожи бет крыльев' gui.ppm2.editor.wings.normal = 'Обычные крылья' gui.ppm2.editor.wings.bat = 'Крылья летучей мыши' gui.ppm2.editor.wings.bat_skin = 'Кожа крыльев летучей мыши' gui.ppm2.editor.wings.left.size = 'Размер левого крыла' gui.ppm2.editor.wings.left.fwd = 'X левого крыла' gui.ppm2.editor.wings.left.up = 'Z левого крыла' gui.ppm2.editor.wings.left.inside = 'Y левого крыла' gui.ppm2.editor.wings.right.size = 'Размер правого крыла' gui.ppm2.editor.wings.right.fwd = 'X правого крыла' gui.ppm2.editor.wings.right.up = 'Z правого крыла' gui.ppm2.editor.wings.right.inside = 'Y правого крыла' for i = 1, 3 gui.ppm2.editor.wings.details.def['detail' .. i] = "URL деталь крыльев #{i}" gui.ppm2.editor.wings.details.def['color' .. i] = "Цвет URL детали крыльев #{i}" gui.ppm2.editor.wings.details.bat['detail' .. i] = "URL деталь бэт-крыльев #{i}" gui.ppm2.editor.wings.details.bat['color' .. i] = "Цвет URL детали крыльев #{i}" gui.ppm2.editor.wings.details.batskin['detail' .. i] = "Bat wing деталь кожи бэт-крыльев #{i}" gui.ppm2.editor.wings.details.batskin['color' .. i] = "Цвет URL детали кожи бэт-крыльев #{i}" gui.ppm2.editor.neck.height = 'Neck height' gui.ppm2.editor.body.suit = 'Костюм' gui.ppm2.editor.body.color = 'Цвет тела' gui.ppm2.editor.body.body_phong = 'Фонг параметрый тела' gui.ppm2.editor.body.spine_length = 'Длинна спины' gui.ppm2.editor.body.url_desc = 'URL детали тела\nДолжны быть в формате PNG или JPEG (работает так же\nкак и PAC3 URL текстуры)' gui.ppm2.editor.body.disable_hoofsteps = 'Отключить звук копыт' gui.ppm2.editor.body.disable_wander_sounds = 'Отключить звуки остановки' gui.ppm2.editor.body.disable_new_step_sounds = 'Отключить звуки ходьбы' gui.ppm2.editor.body.disable_jump_sound = 'Отключить звуки прыжков' gui.ppm2.editor.body.disable_falldown_sound = 'Отключить звуки приземления' gui.ppm2.editor.body.call_playerfootstep = 'Вызывать PlayerFootstep на каждом звуке' gui.ppm2.editor.body.call_playerfootstep_desc = 'Данная опция ползволяет вызывать PlayerFootstep хук при каждом физически слышымом звуке.\nВключение данной опции должно увеличить погружение путем взаимодействия с другими\nаддонами, которые работают с данным хуком.\nВы можете отключить данную опцию если вы получаете нежелаемый результат от других аддонов\nили ваш FPS уходит в минус из-за плохо накоженых аддонов.' for i = 1, PPM2.MAX_BODY_DETAILS gui.ppm2.editor.body.detail['desc' .. i] = "Деталь #{i}" gui.ppm2.editor.body.detail['color' .. i] = "Цвет детали #{i}" gui.ppm2.editor.body.detail['glow' .. i] = "Деталь #{i} светится" gui.ppm2.editor.body.detail['glow_strength' .. i] = "Сила свечения #{i} детали" gui.ppm2.editor.body.detail.url['desc' .. i] = "Деталь #{i}" gui.ppm2.editor.body.detail.url['color' .. i] = "Цвет детали #{i}" gui.ppm2.editor.tattoo.edit_keyboard = 'Редактировать используя клавиатуру' gui.ppm2.editor.tattoo.type = 'Тип' gui.ppm2.editor.tattoo.over = 'Тату поверх деталей тела' gui.ppm2.editor.tattoo.glow = 'Тату светится' gui.ppm2.editor.tattoo.glow_strength = 'Сила свечения тату' gui.ppm2.editor.tattoo.color = 'Цвет тату' gui.ppm2.editor.tattoo.tweak.rotate = 'Поворот' gui.ppm2.editor.tattoo.tweak.x = 'X позиция' gui.ppm2.editor.tattoo.tweak.y = 'Y позиция' gui.ppm2.editor.tattoo.tweak.width = 'Ширина' gui.ppm2.editor.tattoo.tweak.height = 'Высота' for i = 1, PPM2.MAX_TATTOOS gui.ppm2.editor.tattoo['layer' .. i] = "Тату уровень #{i}" gui.ppm2.editor.tail.type = 'Тип хвоста' gui.ppm2.editor.tail.size = 'Размер хвоста' gui.ppm2.editor.tail.tail_phong = 'Фонг параметры хвоста' gui.ppm2.editor.tail.separate = 'Отделить настройки фонга хвоста от тела' for i = 1, 2 gui.ppm2.editor.tail['color' .. i] = 'Цвет хвоста ' .. i for i = 1, 6 gui.ppm2.editor.tail['detail' .. i] = "Цвет детали хвоста #{i}" gui.ppm2.editor.tail.url['detail' .. i] = "URL деталь хвоста #{i}" gui.ppm2.editor.tail.url['color' .. i] = "Цвет URL детали хвоста #{i}" gui.ppm2.editor.hoof.fluffers = 'Мех у копыт' gui.ppm2.editor.legs.height = 'Высота ног' gui.ppm2.editor.legs.socks.simple = 'Носочки (простая текстура)' gui.ppm2.editor.legs.socks.model = 'Носочки (моделью)' gui.ppm2.editor.legs.socks.color = 'Цвет носок' gui.ppm2.editor.legs.socks.socks_phong = 'Фонг параметры носок' gui.ppm2.editor.legs.socks.texture = 'Текстура носок' gui.ppm2.editor.legs.socks.url_texture = 'URL текстура носок' for i = 1, 6 gui.ppm2.editor.legs.socks['color' .. i] = 'Цвет детали носок ' .. i gui.ppm2.editor.legs.newsocks.model = 'Носочки (как новая модель)' for i = 1, 3 gui.ppm2.editor.legs.newsocks['color' .. i] = 'Цвет новых носков ' .. i gui.ppm2.editor.legs.newsocks.url = 'URL текстура новых носков' -- shared editor stuffs gui.ppm2.editor.tattoo.help = "Что бы выйти из режима редактирования, нажмите ESC Или нажмите где угодно мышью. Двигать на WASD Верхняя и нижняя стрелки отвечают за размер по вертикали Правая и левая стрелки отвечают за размер по горизонтали Q/E отвечают за поворот" gui.ppm2.editor.reset_value = 'Сбросить %s' gui.ppm2.editor.phong.info = 'Больше информации про Фонг на вики' gui.ppm2.editor.phong.exponent = 'Фонговая экспонента - насолько сильна отражающая способность\nЗначение около нуля делает почти зеркальную\nповерхность кожи (робот глянцевой краской)' gui.ppm2.editor.phong.exponent_text = 'Фонговая экспонента' gui.ppm2.editor.phong.boost.title = 'Фонговое усиление - контролирует усиление отражений' gui.ppm2.editor.phong.boost.boost = 'Фонговое усиление' gui.ppm2.editor.phong.tint.title = 'Tint цвет - цвет отражений фонга' gui.ppm2.editor.phong.tint.tint = 'Tint цвет' gui.ppm2.editor.phong.frensel.front.title = 'Фонг впрямь - Множитель отражения при угле Френселя 0' gui.ppm2.editor.phong.frensel.front.front = 'Фонг впрямь' gui.ppm2.editor.phong.frensel.middle.title = 'Фонг в угол - Множитель отражения при угле Френселя 45' gui.ppm2.editor.phong.frensel.middle.front = 'Фонг в угол' gui.ppm2.editor.phong.frensel.sliding.title = 'Фонг вскользь - Множитель отражения при угле Френселя 90' gui.ppm2.editor.phong.frensel.sliding.front = 'Фонг вскользь' gui.ppm2.editor.phong.lightwarp = 'Lightwarp' gui.ppm2.editor.phong.url_lightwarp = 'Lightwarp URL текстура\nОБЯЗАНА БЫТЬ 256x16!' gui.ppm2.editor.phong.bumpmap = 'URL текстура' gui.ppm2.editor.info.discord = "Присоединяйтесь к Дискорд серверу DBotThePony!" gui.ppm2.editor.info.ponyscape = "PPM/2 это проект Ponyscape" gui.ppm2.editor.info.creator = "PPM/2 был создан и поддерживается DBotThePony" gui.ppm2.editor.info.newmodels = "Новые модели были созданы Durpy" gui.ppm2.editor.info.cppmmodels = "CPPM модели (включая руки) принадлежат UnkN" gui.ppm2.editor.info.oldmodels = "Старые модели принадлежат Scentus и Остальным" gui.ppm2.editor.info.bugs = "Нашли баг? Репорт!" gui.ppm2.editor.info.sources = "Вы можете найти исходники аддона тут" gui.ppm2.editor.info.githubsources = "Или на GitHub зеркале" gui.ppm2.editor.info.thanks = "Спасибочки всем участвующим при разработке,\nсо своей критикой к PPM/2!" -- other stuff info.ppm2.fly.pegasus = 'Вы должны быть пегасом или аликорном что бы летать!' info.ppm2.fly.cannot = 'Вы сейчас не можете %s.' gui.ppm2.emotes.sad = 'Грустный' gui.ppm2.emotes.wild = 'Дикий' gui.ppm2.emotes.grin = 'Оскал' gui.ppm2.emotes.angry = 'Злой' gui.ppm2.emotes.tongue = ':P' gui.ppm2.emotes.angrytongue = '>:P' gui.ppm2.emotes.pff = 'пфффф!' gui.ppm2.emotes.kitty = ':3' gui.ppm2.emotes.owo = 'oWo' gui.ppm2.emotes.ugh = 'эмммм' gui.ppm2.emotes.lips = 'Губолиз' gui.ppm2.emotes.scrunch = 'Сморщенный' gui.ppm2.emotes.sorry = 'Ой' gui.ppm2.emotes.wink = 'Подмигивание' gui.ppm2.emotes.right_wink = 'Правое Подмигивание' gui.ppm2.emotes.licking = 'Лижет' gui.ppm2.emotes.suggestive_lips = 'Оч. губолиз' gui.ppm2.emotes.suggestive_no_tongue = 'Оч. без языка' gui.ppm2.emotes.gulp = 'Сглотнуть от страха' gui.ppm2.emotes.blah = 'бла бла бла' gui.ppm2.emotes.happi = 'Счастье!' gui.ppm2.emotes.happi_grin = 'Счастливая улыбка' gui.ppm2.emotes.duck = 'УТОЧКА' gui.ppm2.emotes.ducks = 'АТАКА УТОЧЕК' gui.ppm2.emotes.quack = 'КРЯ' gui.ppm2.emotes.suggestive = 'Оч. с языком' message.ppm2.emotes.invalid = 'Нет эмоции с таким ID: %s' gui.ppm2.editor.intro.text = "Представляю вам... своего... Робохирурга для поней! Он позволит вам стать\n" .. "пони, и да, этот процесс НЕОБРАТИМ! Но неволнуйтесь, вы не потеряете какие либо клетки головного\n" .. "мозга, так как он работает очень аккуратно...\n\n" .. "А если честно я не знаю, ты, биологическое существо! Он обнимет тебя так, как никто иной.\n" .. "И да, не умрите в процессе, иначе это ОБНУЛИТ ВАШУ ГАРАНТИЮ НА ЖИЗНЬ! И вы не сможете стать пони!\n" .. "----\n\n\n" .. "ВНИМЕНИЕ: Не разбирайте робохирурга.\nНе ложите свои руки/копыта в двигающиеся части робохирурга.\n" .. "Не отключать от сети.\nНе противостоять его действиям.\n" .. "Всегда уважайте своего робохирурга.\n" .. "Не бейте робохирурга по лицу.\n" .. "DBot's DLibCo не несёт никакой ответственности за вред приченённый робохирургом.\n" .. "Гарантия обнуляется когда пользователь погибает.\n" .. "Товар не подлежит возврату." gui.ppm2.editor.intro.title = 'Добро пожаловать, Биологическое сущес... Человек!' gui.ppm2.editor.intro.okay = "к, я все равно это никогда не читаю" message.ppm2.debug.race_condition = 'У NetworkedPonyData состояние гонки с движком игры. Ожидаю...' gui.ppm2.spawnmenu.newmodel = 'Создать новую модель' gui.ppm2.spawnmenu.newmodelnj = 'Создать новую модель NJ' gui.ppm2.spawnmenu.oldmodel = 'Создать старую модель' gui.ppm2.spawnmenu.oldmodelnj = 'Создать старую модель NJ' gui.ppm2.spawnmenu.cppmmodel = 'Создать CPPM модель' gui.ppm2.spawnmenu.cppmmodelnj = 'Создать CPPM модель NJ' gui.ppm2.spawnmenu.cleanup = 'Принудительно собрать мусор' gui.ppm2.spawnmenu.reload = 'Перезагрузить вашу пони' gui.ppm2.spawnmenu.require = 'Запросить данные с сервера' gui.ppm2.spawnmenu.drawhooves = 'Отрисовывать копыта как руки' gui.ppm2.spawnmenu.nohoofsounds = 'Отключить звуки копыт' gui.ppm2.spawnmenu.noflexes = 'Отключить flexes (эмоции)' gui.ppm2.spawnmenu.advancedmode = 'Включить расширенный режим редактора' gui.ppm2.spawnmenu.reflections = 'Включить отражения в реальном времени' gui.ppm2.spawnmenu.reflections_drawdist = 'Дистанция для отрисовки' gui.ppm2.spawnmenu.reflections_renderdist = 'Точность отражений' gui.ppm2.spawnmenu.doublejump = 'Двойной прыжок включает режим полета' gui.ppm2.spawnmenu.vm_magic = 'Изменения ViewModel для единорогов' tip.ppm2.in_editor = 'В редакторе PPM/2' tip.ppm2.camera = "PPM/2 камера игрока %s" message.ppm2.queue_notify = '%i текстур ожидают отрисовки' gui.ppm2.editor.body.bump = 'Непрозрачность Bumpmap'
52.053533
453
0.758238
5ad2c8c0279292a5e55aa0d7676a0c02ca2597d7
2,453
-- without nginx the library uses crypto unless pcall -> require "crypto" describe "lapis.session", -> it "should have luacrypto", -> pending "luacrypto is required for session test" return import auto_table from require "lapis.util" session = require "lapis.session" describe "lapis.session", -> config = require"lapis.config".get! local req before_each -> config.secret = "the-secret" req = { cookies: {} session: setmetatable { hello: "world" }, { __index: { car: "engine" } } } stub_lazy_session = (tbl) -> req.cookies[config.session_name] = session.encode_session tbl req.session = session.lazy_session req it "should write unsigned session", -> config.secret = nil session.write_session req assert.same session.get_session(req), { hello: "world", car: "engine" } it "should not read unsigned session with secret", -> config.secret = nil session.write_session req config.secret = "hello" assert.same session.get_session(req), {} it "should write signed session", -> session.write_session req assert.same session.get_session(req), { hello: "world", car: "engine" } it "should not read incorrect secret", -> session.write_session req config.secret = "not-the-secret" assert.same session.get_session(req), {} it "should not fail on malformed session", -> req.cookies.lapis_session = "uhhhh" assert.same session.get_session(req), {} it "should load a lazy_session", -> stub_lazy_session { hello: "world" dog: { height: 10 } } assert.same req.session.hello, "world" assert.same req.session.dog, { height: 10 } it "should write not write an unchanged lazy_session", -> stub_lazy_session { cat: "man" } assert.same req.session.cat, "man" req.cookies = {} -- clear cookies to see if we write new session cookie session.write_session req assert.same req.cookies, {} it "should write a lazy_session with new keys", -> stub_lazy_session { cat: "man" } req.session.cow = 100 session.write_session req assert.same session.get_session(req), { cat: "man", cow: 100 } it "should remove key from lazy_session", -> stub_lazy_session { cat: "man" horse: "pig" } req.session.horse = nil session.write_session req assert.same session.get_session(req), { cat: "man" }
24.53
75
0.647371
9b5908ce811540e8ecb5c6fd9b51f0f076809800
9,000
describe "hsl_like", -> hsl_like = require('lush.vivid.hsl_like') hsl = hsl_like type_fns = { name: -> "type_name", to_hex: -> "#000000", from_hex: -> {h: 100, s: 50, l: 50} } describe "require", -> it "exports a function", -> assert.is.not.nil(hsl_like) assert.is.function(hsl_like) describe "init checks", -> it "checks for from_hex", -> init_fns = {name: -> "test"} assert.error((-> hsl_like(100, 10, 10, init_fns)), "test must provide from_hex() type_fn") it "checks for to_hex", -> init_fns = { name: -> "test", from_hex: -> "" } assert.error((-> hsl_like(100, 10, 10, init_fns)), "test must provide to_hex() type_fn") describe "creation", -> it "can be created from h,s,l", -> color = hsl_like(120, 10, 10, type_fns) assert.not.nil(color) color = hsl_like(361, 111, 302, type_fns) assert.is.equal(color.h, 1) assert.is.equal(color.s, 100) assert.is.equal(color.l, 100) -- these values should just be clamped color = hsl_like(-365, -111, -102, type_fns) assert.is.equal(color.h, 355) assert.is.equal(color.s, 0) assert.is.equal(color.l, 0) it "can be created from a hex value", -> color = hsl_like("#000000", nil, nil, type_fns) assert.is_equal(100, color.h) assert.is_equal(50, color.s) assert.is_equal(50, color.l) it "errors on bad arguments", -> check_e = (fn) -> e = assert.error(fn) assert.matches("type_name expects", e) assert.error((-> hsl_like()), "must provide type_fns") assert.error((-> hsl_like(1)), "must provide type_fns") assert.error((-> hsl_like(1,2)), "must provide type_fns") assert.error((-> hsl_like(1,2,3)), "must provide type_fns") check_e(-> hsl_like(1,2, nil, type_fns)) check_e(-> hsl_like(2, 3, "3", type_fns)) e = assert.error(-> color hsl_like("", nil, nil, type_fns)) assert.matches("invalid hex_str", e) e = assert.error(-> color hsl_like("hsl('#100000')", nil, nil, type_fns)) assert.matches("invalid hex_str", e) e = assert.error(-> color hsl_like("#0df", nil, nil, type_fns)) assert.matches("invalid hex_str", e) e = assert.error(-> color hsl_like("#00FF0Z", nil, nil, type_fns)) assert.matches("invalid hex_str", e) describe "unpacking", -> it "unrolls to table when called", -> color = hsl_like(120, 11, 34, type_fns) assert.not.nil(color()) assert.is.table(color()) assert.is.equal(color().h, 120) assert.is.equal(color().s, 11) assert.is.equal(color().l, 34) it "has .h, .s, .l helpers", -> color = hsl_like(120, 11, 34, type_fns) assert.is.equal(color.h, 120) assert.is.equal(color.s, 11) assert.is.equal(color.l, 34) it "disables assignment", -> color = hsl(0, 0, 0, type_fns) e = assert.error(-> color.h = 100) assert.matches("Member setting disabled", e) e = assert.error(-> color.s = 100) assert.matches("Member setting disabled", e) e = assert.error(-> color.l = 100) assert.matches("Member setting disabled", e) it "can concat with strings", -> color = hsl_like(0,0,0, type_fns) str_start = "my color is: " assert.is_equal(str_start .. "#000000", str_start .. color) it "can convert to hex", -> color = hsl_like(0, 0, 0, type_fns) assert.is_equal("#000000", tostring(color)) describe "modification", -> color = hsl(120, 11, 34, type_fns) it "can warns on bad operation", -> e = assert.error(-> color.garbage(100)) assert.matches("valid operations: ", e) it "can rotate", -> assert.is.equal(color.h, 120) assert.is.equal(120, color.rotate(0).h) assert.is.equal(120 + 40, color.rotate(40).h) assert.is.equal((120 + 240) % 360, color.rotate(240).h) assert.is.equal(color.rotate(-10).h, 110) assert.is.equal(color.rotate(-120).h, 0) assert.is.equal(color.rotate(-125).h, 355) assert.is_same(color.rotate(120).h, color.ro(120).h) e = assert.error(-> color.rotate()) assert.matches("number", e) e = assert.error(-> color.rotate("asd")) assert.matches("number", e) it "can saturate", -> assert.is.equal(color.s, 11) assert.is.equal(color.saturate(10).s, 20) assert.is.equal(color.saturate(-10).s, 10) assert.is.equal(color.saturate(-110).s, 0) assert.is.equal(color.saturate(110).s, 100) assert.is.equal(color.abs_saturate(10).s, 21) assert.is.equal(color.abs_saturate(-10).s, 1) assert.is.equal(color.abs_saturate(-110).s, 0) assert.is.equal(color.abs_saturate(110).s, 100) assert.is_same(color.saturate(10).s, color.sa(10).s) assert.is_same(color.abs_saturate(10).s, color.abs_sa(10).s) e = assert.error(-> color.saturate()) assert.matches("number", e) e = assert.error(-> color.saturate("asd")) assert.matches("number", e) it "can desaturate", -> assert.is.equal(color.s, 11) assert.is.equal(color.desaturate(10).s, 10) assert.is.equal(color.desaturate(-10).s, 20) assert.is.equal(color.desaturate(-110).s,100) assert.is.equal(color.desaturate(110).s, 0) assert.is.equal(color.s, 11) assert.is.equal(color.abs_desaturate(10).s, 1) assert.is.equal(color.abs_desaturate(-10).s, 21) assert.is.equal(color.abs_desaturate(-110).s,100) assert.is.equal(color.abs_desaturate(110).s, 0) assert.is_same(color.desaturate(10).s, color.de(10).s) assert.is_same(color.abs_desaturate(10).s, color.abs_de(10).s) e = assert.error(-> color.desaturate()) assert.matches("number", e) e = assert.error(-> color.desaturate("asd")) assert.matches("number", e) it "can lighten", -> assert.is.equal(color.l, 34) assert.is.equal(color.lighten(10).l, 41) assert.is.equal(color.lighten(-10).l, 31) assert.is.equal(color.lighten(-110).l, 0) assert.is.equal(color.lighten(110).l, 100) assert.is.equal(color.l, 34) assert.is.equal(color.abs_lighten(10).l, 44) assert.is.equal(color.abs_lighten(-10).l, 24) assert.is.equal(color.abs_lighten(-110).l, 0) assert.is.equal(color.abs_lighten(110).l, 100) assert.is_same(color.lighten(10).l, color.li(10).l) assert.is_same(color.abs_lighten(10).l, color.abs_li(10).l) e = assert.error(-> color.lighten()) assert.matches("number", e) e = assert.error(-> color.lighten("asd")) assert.matches("number", e) it "can darken", -> assert.is.equal(color.l, 34) assert.is.equal(color.darken(10).l, 31) assert.is.equal(color.darken(-10).l, 41) assert.is.equal(color.darken(-110).l,100) assert.is.equal(color.darken(110).l, 0) assert.is.equal(color.l, 34) assert.is.equal(color.abs_darken(10).l, 24) assert.is.equal(color.abs_darken(-10).l, 44) assert.is.equal(color.abs_darken(-110).l,100) assert.is.equal(color.abs_darken(110).l, 0) assert.is_same(color.darken(10).l, color.da(10).l) assert.is_same(color.abs_darken(10).l, color.abs_da(10).l) e = assert.error(-> color.darken()) assert.matches("number", e) e = assert.error(-> color.darken("asd")) assert.matches("number", e) it "can set direct values", -> assert.is.equal(color.h, 120) assert.is.equal(color.hue(55).h, 55) assert.is.equal(color.s, 11) assert.is.equal(color.saturation(55).s, 55) assert.is.equal(color.l, 34) assert.is.equal(color.lightness(44).l, 44) e = assert.error(-> color.hue()) assert.matches("number", e) e = assert.error(-> color.hue("asd")) assert.matches("number", e) e = assert.error(-> color.saturation()) assert.matches("number", e) e = assert.error(-> color.saturation("asd")) assert.matches("number", e) e = assert.error(-> color.lightness()) assert.matches("number", e) e = assert.error(-> color.lightness("asd")) assert.matches("number", e) describe "mix", -> it "0 strength returns base", -> color = hsl(123, 50, 100, type_fns) assert.is_same(color.hsl, color.mix(hsl(0, 10, 99, type_fns), 0).hsl) it "100 strength returns target", -> color = hsl(123, 50, 100, type_fns) target = hsl(22, 44, 88, type_fns) assert.is_same(target.hsl, color.mix(target, 100).hsl) describe "modifier behaviour", -> it "can chain modifiers", -> color = hsl(120, 11, 34, type_fns) mod_color = color.rotate(10).lighten(20).desaturate(20).rotate(20) assert.is_same({h: 150, s: 9, l: 47}, mod_color.hsl) it "can modifiers don't modifiy original color", -> color = hsl(120, 11, 34, type_fns) mod_color = color.rotate(10).lighten(20).desaturate(20).rotate(20) assert.is_not_equal(color, mod_color) assert.is_not_equal(color(), mod_color())
35.714286
96
0.612778
4c718183b0567bd617e55d6678822f4a373fa28a
13,002
-- Manipulate the package path path = require 'pl.path' source_path = debug.getinfo(1).source\sub(2, -1) -- Relative path of currently-executing file source_path = path.dirname(path.abspath source_path) source_path = path.normpath("#{source_path}/../moon/earthshine/madfa") package.moonpath = "#{source_path}/?.moon;#{package.moonpath}" inspect = require 'inspect' earthshine_table = require 'earthshine.table' clone_table = earthshine_table.clone require 'earthshine.string' local * describe "MADFA package tests:", -> MADFA = require 'earthshine.madfa' import State, Register from MADFA describe "madfa tests:", -> describe "_step_transition() tests:", -> -- {{{ local madfa, state, next_state, label before_each -> madfa = MADFA! state = madfa.initial_state next_state = madfa\_new_state! label = "a" it "makes the target state reachable from the source state under the given label", -> assert.is.Nil madfa\_step_transition state, label madfa\_add_transition state, label, next_state assert.are.equals (madfa\_step_transition state, label), next_state it "increments the count of sorted transition labels", -> label_count = #state.sorted_keys madfa\_add_transition state, label, next_state assert.are.equals label_count + 1, #state.sorted_keys it "has a sorted label list entry corresponding to the correct label", -> for existing_label in *state.sorted_keys assert.are.not.same label, existing_label madfa\_add_transition state, label, next_state seen_label = false for current_label in *state.sorted_keys if current_label == label seen_label = true assert seen_label it "increases the incoming transition count on the target state", -> old_count = next_state.incoming madfa\_add_transition state, label, next_state assert.are.equal old_count + 1, next_state.incoming -- }}} describe "_step_multiple() tests:", -> -- {{{ labels = { "a", "z", "c" } local madfa, state, next_states before_each -> madfa = MADFA! state = madfa.initial_state next_states = {} _add_transitions_with_fn = (fn) -> for i, label in ipairs labels next_states[i] = madfa\_new_state! madfa\_add_transition state, label, next_states[i] fn! _add_transitions = -> _add_transitions_with_fn -> nil assert_lexicographically_sorted = (tbl) -> key, val = next tbl, nil previous_val = nil while key != nil if previous_val assert val > previous_val previous_val = val key, val = next tbl, key it "preserves the lexicographical sorting of the labels after each addition", -> _add_transitions_with_fn, -> assert_lexicographically_sorted state.sorted_keys -- }}} describe "_clone_state() tests:", -> -- {{{ local madfa, state setup -> madfa = MADFA! parent_state = madfa\_new_state! state = madfa\_new_state! with madfa \_add_transition state, "a", \_new_state! \_add_transition state, "z", \_new_state! \_add_transition state, "d", \_new_state! \_add_transition parent_state, "a", state it "has the same .transitions and .sorted_keys as the original", -> cloned_state = madfa\_clone_state state assert.are.equals #cloned_state.transitions, #state.transitions assert.are.equals #cloned_state.sorted_keys, #state.sorted_keys for i, label in pairs state.sorted_keys assert.are.equals label, cloned_state.sorted_keys[i] assert.are.equals state.transitions[label], cloned_state.transitions[label] it "has the same final value as the original", -> cloned_state = madfa\_clone_state state assert.are.equals state.final, cloned_state.final it "has no incoming transitions", -> cloned_state = madfa\_clone_state state assert.are.equals 0, cloned_state.incoming it "is not the same object as the original", -> cloned_state = madfa\_clone_state state assert.are.not.equal state, cloned_state it "increases the incoming transition count on all pointed-to transitions", -> old_counts = {} for label, transition in madfa\_iterate_transitions state old_counts[label] = transition.incoming cloned_state = madfa\_clone_state state for label, transition in madfa\_iterate_transitions state assert.are.equal old_counts[label] + 1 , transition.incoming -- }}} describe "_delete_state() tests:", -> -- {{{ it "decrements the incoming transition count on all child states", -> nil -- }}} describe "_register_state() tests:", -> -- {{{ -- }}} describe "add_words() tests:", -> -- {{{ base_word = "foobar" later_word = "zebra" sub_word = "foo" prefix_shared = "foonot" suffix_shared = "notbar" -- both_shared shares prefix and suffix with existing_string both_shared = "follar" local madfa before_each -> madfa = MADFA! it "prefixes are shared between added words", -> -- {{{ words = { prefix_shared, base_word } madfa\add_words words base_prefix = string.lcp words -- For the base_prefix's states, there should each be only one child, -- up to the last one current_state = madfa.initial_state for char in (base_prefix\sub 1, -2)\chars! assert.are.equal 1, #current_state.sorted_keys assert.are.equal char, current_state.sorted_keys[1] current_state = madfa\_step_transition current_state, char -- The last state in the base_prefix should instead have 2 children last_shared_state = madfa\_step_multiple madfa.initial_state, base_prefix assert.are.equal 2, #last_shared_state.sorted_keys -- After that, we should have two chains of states, equal to the two suffixes for word in *words suffix = word\sub #base_prefix + 1, -1 current_state = last_shared_state for char in suffix\chars! assert.is.not.Nil madfa\_step_transition current_state, char current_state = madfa\_step_transition current_state, char assert.is.True current_state.final -- }}} it "the suffixes are shared between added words", -> -- {{{ words = { suffix_shared, base_word } madfa\add_words words base_suffix = string.lcs words -- We start with the initial state breaking out into two separate -- chains of states, up to the shared suffix local current_state after_prefix = {} for word in *words prefix = word\sub 1, #word - #base_suffix current_state = madfa.initial_state -- Initial state has two children, subsequent prefix chains only have -- 1 child assert.are.equal 2, #current_state.sorted_keys -- for char in prefix\chars! for i = 1, #prefix char = prefix\sub i, i assert.is.not.Nil madfa\_step_transition current_state, char current_state = madfa\_step_transition current_state, char assert.are.equal 1, #current_state.sorted_keys -- Keep track of the state that follows the prefix for later -- comparison if i == #prefix after_prefix[#after_prefix + 1] = current_state -- Confirm that the following state of each chain is the same assert.are.equal current_state, after_prefix[1], after_prefix[2] for i = 1, #after_prefix assert.are.equal current_state, after_prefix[i] assert.is.True current_state.incoming >= 2 -- Now check that the suffix is shared for i = 1, #base_suffix char = base_suffix\sub i, i -- Each should only have a single child if i != 1 assert.are.equal 1, #current_state.sorted_keys assert.is.not.Nil madfa\_step_transition current_state, char current_state = madfa\_step_transition current_state, char assert.is.True current_state.final -- }}} it "both prefix and suffix can be shared between added words", -> -- {{{ words = { base_word, both_shared } madfa\add_words words base_prefix = string.lcp words base_suffix = string.lcs words -- Confirm that each state in the base_prefix path has only one child, -- up to the last one current_state = madfa.initial_state for char in (base_prefix\sub 1, -2)\chars! assert.are.equal 1, #current_state.sorted_keys assert.are.equal char, current_state.sorted_keys[1] current_state = madfa\_step_transition current_state, char -- The last state in the base_prefix should instead have 2 children last_shared_state = madfa\_step_multiple madfa.initial_state, base_prefix assert.are.equal 2, #last_shared_state.sorted_keys -- Now we should have two separate chains, up until the shared suffix after_unique_middle = {} for word in *words char_start, char_end = #base_prefix + 1, #word - #base_suffix current_state = last_shared_state for i = char_start, char_end char = word\sub i, i assert.is.not.Nil madfa\_step_transition current_state, char current_state = madfa\_step_transition current_state, char assert.are.equal 1, #current_state.sorted_keys -- Keep track of the state that follows the word-unique portion, -- for later comparison if i == char_end after_unique_middle[#after_unique_middle + 1] = current_state -- Confirm that the following state of each chain is the same for i = 2, #after_unique_middle assert.are.equal after_unique_middle[1], after_unique_middle[i] assert.is.True current_state.incoming >= 2 -- Now check that the suffix is shared current_state = after_unique_middle[1] for i = 1, #base_suffix char = base_suffix\sub i, i -- Each should only have a single child if i != 1 assert.are.equal 1, #current_state.sorted_keys assert.is.not.Nil madfa\_step_transition current_state, char current_state = madfa\_step_transition current_state, char assert.is.True current_state.final -- }}} it "words can be added in separate calls with identical results", -> first_words = { base_word } last_words = { later_word } all_words = { base_word, later_word } split_call_madfa = madfa split_call_madfa\add_words first_words split_call_madfa\add_words last_words single_call_madfa = MADFA! assert.is.not.True single_call_madfa\is_equivalent_to split_call_madfa single_call_madfa\add_words all_words assert.is.True single_call_madfa\is_equivalent_to split_call_madfa it "all (and only) the words added are in the subset of the initial state", -> words = { base_word, later_word, sub_word, prefix_shared, suffix_shared, both_shared } madfa\add_words words subset = madfa\subset "" table.sort words assert.are.equal #subset, #words for i = 1, #words assert.are.equal words[i], subset[i] assert.are.equal #words, #subset it "tests against 1,000 random words", -> words = {} for word in io.lines "test/data/1000-words.txt" words[#words + 1] = word madfa\add_words words subset = madfa\subset "" table.sort words assert.are.equal #subset, #words for i = 1, #words assert.are.equal words[i], subset[i] -- }}} describe "add_word() tests:", -> -- {{{ local madfa, words before_each -> words = {"foobar", "zebra", "foo", "foonot", "notbar", "follar", "wollak"} madfa = MADFA! it "the length of the right language of the initial state does not decrease after each call", -> -- One of these two cases always happens: -- - A new word is a prefix of an existing one, in which case the right -- language of the starting state remains the same -- - A new word is not purely a prefix of an existing one, in which -- case the right language of the starting state gets larger previous_length = 0 for word in *words madfa\add_word word current_length = #(madfa\subset "") assert previous_length <= current_length, "NOT: #{previous_length} <= #{current_length}" previous_length = current_length -- }}}
36.728814
102
0.638671
1936cb931c506791f75eff7796b8917006f87c3d
1,488
-- Copyright 2014-2015 The Howl Developers -- License: MIT (see LICENSE.md at the top-level directory of the distribution) {:File, :FileOutputStream} = require 'ljglibs.gio' with_tmpfile = (f) -> p = os.tmpname! status, err = pcall f, p os.remove p error err unless status with_stream = (f) -> with_tmpfile (p) -> f p, File(p)\append_to! describe 'OutputStream', -> setup -> set_howl_loop! describe 'write(contents)', -> it 'writes the contents to the file', -> with_stream (p, stream) -> stream\write_all 'foobar' stream\close! assert.equals 'foobar', File(p)\load_contents! describe 'write_async(data, count, handler)', -> it 'invokes the handler with the status and the number of bytes written', (done) -> with_stream (p, stream) -> stream\write_async 'foobar', nil, async (status, written) -> assert.is_true status assert.equals 'number', type(written) done! describe 'close_async(handler)', -> it 'invokes the handler with the status and any eventual error message', (done) -> with_stream (p, stream) -> stream\close_async async (status, err) -> assert.is_true status assert.is_nil err done! describe '.is_closed', -> it 'is true when the stream is closed and false otherwise', -> with_stream (p, stream) -> assert.is_false stream.is_closed stream\close! assert.is_true stream.is_closed
31
87
0.637769
7ec8293cc0c2386fad382f6097b2de59b9ca3584
1,849
-- Copyright 2012-2015 The Howl Developers -- License: MIT (see LICENSE.md at the top-level directory of the distribution) ffi = require 'ffi' {:catch_error, :char_p_arr} = require 'ljglibs.glib' core = require 'ljglibs.core' require 'ljglibs.gobject.object' require 'ljglibs.cdefs.gdk' {:C, :gc} = ffi core.define 'GdkPixbuf < GObject', { properties: { width: 'gint' height: 'gint' bits_per_sample: 'gint' n_channels: 'gint' rowstride: 'gint' has_alpha: 'gboolean' } new_from_file: (filename) -> pb = catch_error(C.gdk_pixbuf_new_from_file, filename) return nil if pb == nil gc pb, C.g_object_unref new_from_file_at_size: (filename, width, height) -> pb = catch_error(C.gdk_pixbuf_new_from_file_at_size, filename, width, height) return nil if pb == nil gc pb, C.g_object_unref new_from_file_at_scale: (filename, width, height, preserve_aspect_ratio) -> pb = catch_error(C.gdk_pixbuf_new_from_file_at_scale, filename, width, height, preserve_aspect_ratio) return nil if pb == nil gc pb, C.g_object_unref get_from_window: (window, x, y, width, height) -> pixbuf = C.gdk_pixbuf_get_from_window(window, x, y, width, height) error 'Failed to get pixbuf' unless pixbuf gc(pixbuf, C.g_object_unref) pixbuf scale_simple: (dest_width, dest_height, interp_type) => pixbuf = C.gdk_pixbuf_scale_simple @, dest_width, dest_height, interp_type error 'Failed to scale pixbuf' unless pixbuf gc(pixbuf, C.g_object_unref) pixbuf save: (filename, type, opts={}) => opts_pairs = [{:key, :value} for key, value in pairs opts] option_keys = char_p_arr [item.key for item in *opts_pairs] option_values = char_p_arr [item.value for item in *opts_pairs] catch_error(C.gdk_pixbuf_savev, @, filename, type, option_keys, option_values) }, nil
33.618182
105
0.710114
e68c92df272f076ca81c648e4987a5541cdf0fde
20,773
-- -- Copyright (C) 2017-2019 DBot -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -- of the Software, and to permit persons to whom the Software is furnished to do so, -- subject to the following conditions: -- The above copyright notice and this permission notice shall be included in all copies -- or substantial portions of the Software. -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, -- INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR -- PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE -- FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -- OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -- DEALINGS IN THE SOFTWARE. import PPM2 from _G 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') 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) @newSocksModel = controller\GetNewSocksModel() @newSocksModel\SetNoDraw(false) if IsValid(@newSocksModel) @lastStareUpdate = 0 @staringAt = NULL @rotatedHeadTarget = false @idleEyes = true @idleEyesActive = false @nextRollEyes = 0 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() @GetData()\GetWeightController()\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 @legsModel\DrawModel() @legsModel.lastRedrawFix = rTime + 5 if not @legsModel.RenderOverride @legsModel.RenderOverride = -> @DrawLegsOverride() @legsModel\DrawModel() return else @legsModel\SetNoDraw(true) @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 = @GetData()\GetSizeController() 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 @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 = @GetData()\GetSizeController() 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) ShouldHideModels: => @hideModels or @GetEntity()\GetNoDraw() DoHideModels: (status) => @socksModel\SetNoDraw(status) if IsValid(@socksModel) @newSocksModel\SetNoDraw(status) if IsValid(@newSocksModel) 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 if (not @idleEyes or not ENABLE_STARE\GetBool()) and @idleEyesActive @staringAt = NULL @GetEntity()\SetEyeTarget(Vector()) @idleEyesActive = false return return if not @idleEyes or not ENABLE_STARE\GetBool() @idleEyesActive = true @lastStareUpdate = ctime + 0.2 lpos = @GetEntity()\EyePos() @staringAt = NULL if IsValid(@staringAt) and @staringAt\IsPlayer() and not @staringAt\Alive() if IsValid(@staringAt) trNew = util.TraceLine({ start: lpos, endpos: lpos + @GetEntity()\EyeAnglesFixed()\Forward() * 270, filter: @GetEntity(), }) if trNew.Entity\IsValid() and trNew.Entity\IsPlayer() @staringAt = trNew.Entity epos = @staringAt\EyePos() if epos\Distance(lpos) < 300 and DLib.combat.inPVS(@GetEntity(), @staringAt) and @CheckTarget(lpos, epos) @GetEntity()\SetEyeTarget(epos) return @staringAt = NULL @GetEntity()\SetEyeTarget(Vector()) 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, 16) / 6 ang = @GetEntity()\EyeAnglesFixed() @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) @prevRollTargetPos = LerpVector(FrameTime() * 6, @prevRollTargetPos, @eyeRollTargetPos) roll = Vector(@prevRollTargetPos) roll\Rotate(@GetEntity()\EyeAnglesFixed()) @GetEntity()\SetEyeTarget(@GetEntity()\EyePos() + roll) 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 @GetEntity()\IsPlayer() @UpdateStare() @UpdateEyeRoll() if ent.RenderOverride and not ent.__ppm2RenderOverride and @GrabData('HideManes') and @GrabData('HideManesSocks') @socksModel\SetNoDraw(true) if IsValid(@socksModel) @newSocksModel\SetNoDraw(true) if IsValid(@newSocksModel) else @socksModel\SetNoDraw(@ShouldHideModels()) if IsValid(@socksModel) @newSocksModel\SetNoDraw(@ShouldHideModels()) if IsValid(@newSocksModel) PostDraw: (ent = @GetEntity(), drawingNewTask = false) => return if not @isValid @GetTextureController()\PostDraw(ent, drawingNewTask) @ARMS_MATERIAL_INDEX = 0 PreDrawArms: (ent, hooves = true) => return if not @isValid return if not hooves if ent and not @armsWeightSetup @armsWeightSetup = true weight = 1 + (@GetData()\GetWeight() - 1) * 0.4 vec = Vector(weight, weight, weight) ent\ManipulateBoneScale(i, vec) for i = 1, 13 ent\SetSubMaterial(@@ARMS_MATERIAL_INDEX, @GetTextureController()\GetBodyName()) PostDrawArms: (ent, hooves = true) => return if not @isValid ent\SetSubMaterial(@@ARMS_MATERIAL_INDEX, '') 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 @GetData()\GetWeightController()\UpdateWeight(@legsModel) if IsValid(@legsModel) when 'SocksModel' @socksModel = @GetData()\GetSocksModel() @socksModel\SetNoDraw(@ShouldHideModels()) if IsValid(@socksModel) @GetTextureController()\UpdateSocks(@GetEntity(), @socksModel) if @GetTextureController() and IsValid(@socksModel) when 'NewSocksModel' @newSocksModel = @GetData()\GetNewSocksModel() @newSocksModel\SetNoDraw(@ShouldHideModels()) if IsValid(@newSocksModel) @GetTextureController()\UpdateNewSocks(@GetEntity(), @newSocksModel) if @GetTextureController() and IsValid(@newSocksModel) when 'NoFlex' if state\GetValue() @flexes\ResetSequences() if @flexes @flexes = nil else @CreateFlexController() 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 @GetData()\GetNoFlex() 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 = @GetData()\GetUpperManeModel() @upperManeModel\SetNoDraw(@ShouldHideModels()) if IsValid(@upperManeModel) @GetTextureController()\UpdateUpperMane(@GetEntity(), @upperManeModel) if @GetTextureController() and IsValid(@upperManeModel) when 'LowerManeModel' @lowerManeModel = @GetData()\GetLowerManeModel() @lowerManeModel\SetNoDraw(@ShouldHideModels()) if IsValid(@lowerManeModel) @GetTextureController()\UpdateLowerMane(@GetEntity(), @lowerManeModel) if @GetTextureController() and IsValid(@lowerManeModel) when 'TailModel' @tailModel = @GetData()\GetTailModel() @tailModel\SetNoDraw(@ShouldHideModels()) if IsValid(@tailModel) @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
35.877375
171
0.729168
f6c13306543d39f3ecfeaf6a6197c2d8cb1195b5
6,067
-- Copyright 2012-2015 The Howl Developers -- License: MIT (see LICENSE.md at the top-level directory of the distribution) {:breadcrumbs, :config} = howl {:highlight} = howl.ui highlight.define_default 'search', { type: highlight.ROUNDED_RECTANGLE, foreground: '#ffffff' foreground_alpha: 100 } highlight.define_default 'search_secondary', { type: highlight.ROUNDED_RECTANGLE, foreground: '#ffffff' foreground_alpha: 150 background: '#ffffff' background_alpha: 0 } with config .define name: 'search_wraps' description: 'Whether searches wrap around to top or bottom when there are no more matches' default: true type_of: 'boolean' class Searcher new: (editor) => @editor = editor @last_search = nil @last_direction = nil @last_type = nil forward_to: (search, type = 'plain', match_at_cursor = true) => @jump_to search, direction: 'forward', type: type, match_at_cursor: match_at_cursor backward_to: (search, type = 'plain', match_at_cursor = @active) => @jump_to search, direction: 'backward', type: type, match_at_cursor: match_at_cursor jump_to: (search, opts = {}) => @_clear_highlights! return if search.is_empty direction = opts.direction or 'forward' ensure_word = opts.type == 'word' match_at_cursor = opts.match_at_cursor or false unless @active @_init! if direction == 'forward' and ensure_word -- back up to start of current word @editor.cursor.pos = @editor.current_context.word.start_pos init = @editor.cursor.pos if direction == 'forward' if not match_at_cursor init += 1 else init += search.ulen - 2 if match_at_cursor init += 1 start_pos, end_pos = @_find_match search, init, direction, ensure_word if start_pos @editor.cursor.pos = end_pos @editor.cursor.pos = start_pos @_highlight_matches search, start_pos, ensure_word else if ensure_word log.error "No word matches found for '#{search}'" else log.error "No matches found for '#{search}'" @last_search = search @last_direction = direction @last_type = opts.type repeat_last: => @_init! if @last_direction == 'forward' @next! else @previous! @commit! next: => if @last_search and not @last_search.is_empty if @last_type == 'word' log.info "Next match for word '#{@last_search}'" else log.info "Next match for '#{@last_search}'" @forward_to @last_search, @last_type, false previous: => if @last_search and not @last_search.is_empty if @last_type == 'word' log.info "Previous match for word '#{@last_search}'" else log.info "Previous match for '#{@last_search}'" @backward_to @last_search, @last_type, false commit: => if @active if @start_pos != @editor.cursor.pos breadcrumbs.drop { buffer: @buffer, pos: @start_pos, line_at_top: @start_line_at_top } breadcrumbs.drop { buffer: @buffer, pos: @editor.cursor.pos, line_at_top: @editor.line_at_top } @_finish! cancel: => @_clear_highlights! if @active @editor.cursor.pos = @start_pos @editor.line_at_top = @start_line_at_top @_finish! _finish: => @buffer = nil @start_pos = nil @start_line_at_top = nil @active = false _find_match: (search, init, direction, ensure_word) => finder = nil wrap_pos = nil wrap_msg = '' if direction == 'forward' finder = @buffer.find wrap_pos = 1 wrap_msg = 'Search hit BOTTOM, continuing at TOP' else finder = @buffer.rfind wrap_pos = -1 wrap_msg = 'Search hit TOP, continuing at BOTTOM' wrapped = false while true start_pos, end_pos = finder @buffer, search, init if start_pos if not ensure_word or @_is_word(start_pos, search) return start_pos, end_pos -- the match wasn't a word, continue searching if direction == 'forward' init = end_pos + 1 else init = start_pos - 1 else if wrapped or init == wrap_pos -- already wrapped, or no need to wrap return else init = wrap_pos log.info wrap_msg wrapped = true _is_word: (match_pos, word) => match_ctx = @editor.buffer\context_at match_pos return match_ctx.word.text == word _highlight_matches: (search, match_pos, ensure_word) => return unless search buffer = @editor.buffer -- scan the displayed lines and a few more for good measure start_boundary = buffer.lines[math.max(1, @editor.line_at_top - 5)].start_pos end_boundary = buffer.lines[math.min(#buffer.lines, @editor.line_at_bottom + 5)].end_pos ranges = {} -- match at match_pos gets a different highlight than other matches for start_pos, end_pos in @_find_matches search, start_boundary, end_boundary if not ensure_word or @_is_word(start_pos, search) if start_pos != match_pos ranges[#ranges + 1] = { start_pos, end_pos - start_pos + 1 } highlight.apply 'search', buffer, match_pos, search.ulen highlight.apply 'search_secondary', buffer, ranges _find_matches: (search, start_boundary, end_boundary) => match_start_pos = nil match_end_pos = nil text = @buffer\sub start_boundary, end_boundary init = 1 return -> while true if init > #text return match_start_pos, match_end_pos = text\ufind search, init, true return if not match_start_pos init = match_end_pos + 1 return match_start_pos + start_boundary - 1, match_end_pos + start_boundary - 1 _clear_highlights: => highlight.remove_all 'search', @editor.buffer highlight.remove_all 'search_secondary', @editor.buffer _init: => @start_pos = @editor.cursor.pos @start_line_at_top = @editor.line_at_top @buffer = @editor.buffer @active = true
27.703196
95
0.644635
c271c38e167d4d7cfe242f23d4e15ce327b7dda9
21
a=x: 1+2 return a.x
5.25
10
0.571429
f1589970477dedb0a39bafb62d6e8547b9b5f3c6
1,689
-- Copyright 2014-2015 The Howl Developers -- License: MIT (see LICENSE.md at the top-level directory of the distribution) howl.aux.lpeg_lexer -> c = capture ident = (alpha + '_')^1 * (alpha + digit + '_')^0 ws = c 'whitespace', blank identifer = c 'identifer', ident keyword = c 'keyword', word { 'break', 'case', 'catch', 'continue', 'const', 'debugger', 'default', 'delete', 'do', 'else', 'finally', 'for', 'function', 'if', 'in', 'instanceof', 'new', 'return', 'switch', 'this', 'throw', 'try', 'typeof', 'var', 'void', 'while', 'with' } operator = c 'operator', S'+-*/%=<>&^|!(){}[];' comment = c 'comment', any { P'//' * scan_until eol, span '/*', '*/' } number = c 'number', any { float, hexadecimal, digit^1, word('Nan', 'Infinity') } special = c 'special', word('undefined', 'null', 'true', 'false') str = any { span('"', '"', '\\') span("'", "'", '\\') } string = c 'string', str type = c 'type', upper^1 * (alpha + digit + '_')^0 key = c 'key', any(str, ident) * ':' regex = sequence { c('regex', sequence { '/', scan_to(any('/', eol), '\\'), B('/'), }), c('operator', S'gim'^1)^0 } fdecl = any { c('keyword', 'function') * ws^1 * c('fdecl', ident), sequence { -B(alpha), c('fdecl', ident), ws^0, c('operator', '='), ws^0, any { c('keyword', 'new') * ws^1 * c('type', 'Function'), c('keyword', 'function') * #(blank^0 * '(') } } } any { comment, key, string, regex, fdecl, keyword, special, operator, number, type, identifer, }
21.1125
83
0.484902
369c40a97056937908ba5b263256d87155c868ea
6,395
define = require'classy'.define format = string.format Date = define 'Date', -> properties age: get: => now = os.date('*t') age = now.year - @year if now.month < @month age = age - 1 else if now.month == @month if now.day < @day age = age - 1 age set: (age) => today = os.date('*t') @year = today.year - age static from_string: (str) => y, m, d = str\match('(%d+)-(%d+)-(%d+)') y, m, d = tonumber(y), tonumber(m), tonumber(d) new y, m, d instance initialize: (year, month, day) => @year, @month, @day = tonumber(year), tonumber(month), tonumber(day) meta __tostring: => y, m, d = @year, format('%02d', @month), format('%02d', @day) "#{y}-#{m}-#{d}" __add: (num_days) => s = num_days*24*60*60 d = os.time year: @year, month: @month, day: @day newdate = os.date '*t', d+s new newdate.year, newdate.month, newdate.day __sub: (num_days) => s = num_days*24*60*60 d = os.time year: @year, month: @month, day: @day newdate = os.date '*t', d-s new newdate.year, newdate.month, newdate.day Person = define 'Person', -> accessors attributes: {'firstname', 'lastname'} properties name: => "#{@firstname} #{@lastname}" birthdate: get: => tostring(@attributes.birthdate) set: (date) => @attributes.birthdate = Date\from_string(date) age: get: => @attributes.birthdate.age set: (age) => @attributes.birthdate.age = age static find: (name) => name = name\lower! @some_people or= { new('Bob', 'Johnsson', '1964-03-02'), new('Mary', 'Jensen', '1983-05-10'), new('Victoria', 'Hammadi', '1989-12-15') } [p for p in *@some_people when p.name\lower!\match name] instance initialize: (firstname, lastname, birthdate) => @attributes = {:firstname, :lastname, birthdate: Date\from_string(birthdate)} meta __tostring: => @name Employee = define 'Employee', -> parent Person static from_person: (p, salary) => {:firstname, :lastname, :birthdate} = p.attributes birthdate = tostring(birthdate) new :firstname, :lastname, :birthdate, :salary instance initialize: (opts={}) => {:firstname, :lastname, :birthdate} = opts super @, firstname, lastname, birthdate @salary = opts.salary describe 'Smoke test', -> describe 'Date', -> it 'calculates age from date', -> d = Date.new 2000, 01, 01 today = os.date('*t') age = today.year - d.year if today.month < d.month age -= 1 else if today.month == d.month if today.day < d.day age -= 1 assert.equal age, d.age it 'changes the date accordingly by setting age', -> d = Date.new 2000, 01, 01 age = 10 d.age = age assert.equal 10, d.age somedate = os.date('*t') somedate.month, somedate.day = 1, 1 somedate.year -= age expected_date = "#{somedate.year}-#{format('%02d', somedate.month)}-#{format('%02d', somedate.day)}" assert.equal expected_date, tostring(d) it 'has a meta method tostring', -> d = Date.new 2000, 01, 01 assert.equal '2000-01-01', tostring(d) it 'has a meta method add which adds days', -> d = Date.new 2000, 01, 01 d = d + 10 assert.equal '2000-01-11', tostring(d) d = d + 21 assert.equal '2000-02-01', tostring(d) it 'has a meta method sub which subtracts days', -> d = Date.new 2000, 01, 01 d = d - 10 assert.equal '1999-12-22', tostring(d) d = d - 22 assert.equal '1999-11-30', tostring(d) it 'can be created from a string', -> d = Date\from_string '2000-01-01' assert.equal 2000, d.year assert.equal 1, d.month assert.equal 1, d.day describe 'Person', -> local person, expected_age before_each -> person = Person.new 'John', 'Eriksson', '1978-01-05' d = person.attributes.birthdate today = os.date('*t') expected_age = today.year - d.year if today.month < d.month expected_age -= 1 else if today.month == d.month if today.day < d.day expected_age -= 1 it 'has a name getter, concatenating firstname and lastname', -> assert.equal 'John Eriksson', person.name it 'has an age getter, delegating to the internal date', -> assert.equal expected_age, person.age it 'has a birthdate getter, delegating to the internal date', -> assert.equal '1978-01-05', person.birthdate it 'has a firstname getter, delegating to the internal attributes table', -> assert.equal 'John', person.firstname it 'has a firstname setter, delegating to the internal attributes table', -> person.firstname = 'Axel' assert.equal 'Axel', person.firstname assert.equal 'Axel Eriksson', person.name it 'has a class method find', -> bob = Person\find('John')[1] assert.equal 'Bob Johnsson', bob.name it 'has a tostring meta method', -> assert.equal 'John Eriksson', tostring(person) describe 'an Employee', -> local employee, expected_age before_each -> -- making a lot of money it seems :-) employee = Employee.new firstname: 'John' lastname: 'Eriksson' birthdate: '1978-01-05' salary: 1000000000 d = employee.attributes.birthdate today = os.date('*t') expected_age = today.year - d.year if today.month < d.month expected_age -= 1 else if today.month == d.month if today.day < d.day expected_age -= 1 it 'is a Person and an Employee', -> assert.true employee.is_a[Employee] assert.true employee.is_a[Person] assert.equal 1000000000, employee.salary it 'inherits name from Person', -> assert.equal 'John Eriksson', employee.name it 'inherits age from Person', -> assert.equal expected_age, employee.age it 'inherits the tostring meta method from Person', -> assert.equal 'John Eriksson', tostring(employee) it 'can be created from a person object', -> p = Person.new 'John', 'Eriksson', '1978-01-05' e = Employee\from_person p, 1000000 assert.equal 'John Eriksson', e.name
27.683983
106
0.585614
7ebe582f1d78c7b5cad4b7cdcd3800aaddf92950
859
export p class player density = 50 size = 20 source = love.audio.newSource( "Jump2.ogg", "static" ) new: (x = love.graphics.getWidth!/2, y = 100)=> @body = love.physics.newBody(world, x, y, "dynamic") @body\setFixedRotation(true) @shape = love.physics.newRectangleShape(x, y, size, size) @fix = love.physics.newFixture(@body, @shape, @density) @colliders = 0 draw: => love.graphics.setColor 5, 224, 129 love.graphics.polygon "fill", @body\getWorldPoints(@shape\getPoints()) update: (dt)=> --print p[1].colliders if love.keyboard.isDown 'right' @body\applyForce 8000*dt, 0 if love.keyboard.isDown 'left' @body\applyForce -8000*dt, 0 if love.keyboard.isDown('up') and p[1].colliders > 0 -- <- worst solution ever love.audio.play(source) @body\applyForce 0, -15000*dt return
31.814815
83
0.6461
302532d0e1e1c79b7f0d49d487650bda8de6aa07
337
TK = require("PackageToolkit") parent = ... members = { "_append" "_cart2" "_cart" "_concat2" "_concat" "_head" "_initial" "_merge2" "_merge" "_next" "_prepend" "_tail" "_take" "_drop" "_flatten" "_reverse" "_replicate" } return TK.module.subfunctions parent, members
14.652174
45
0.557864
d87a58f5af219cc3fcbade2f3da7e1004cff3baa
4,448
-- -- Copyright (C) 2017-2019 DBot -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -- of the Software, and to permit persons to whom the Software is furnished to do so, -- subject to the following conditions: -- The above copyright notice and this permission notice shall be included in all copies -- or substantial portions of the Software. -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, -- INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR -- PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE -- FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -- OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -- DEALINGS IN THE SOFTWARE. class PPM2.SequenceHolder extends PPM2.ModifierBase @__inherited: (child) => super(child) return if not child.SEQUENCES seq.numid = i for i, seq in ipairs child.SEQUENCES child.SEQUENCES_TABLE = {seq.name, seq for _, seq in ipairs child.SEQUENCES} child.SEQUENCES_TABLE[seq.numid] = seq for _, seq in ipairs child.SEQUENCES @NEXT_HOOK_ID = 0 @SequenceObject = PPM2.SequenceBase new: => super() @isValid = true @hooks = {} @@NEXT_HOOK_ID += 1 @fid = @@NEXT_HOOK_ID @hookID = "PPM2.#{@@__name}.#{@@NEXT_HOOK_ID}" @lastThink = RealTimeL() @lastThinkDelta = 0 @currentSequences = {} @currentSequencesIterable = {} StartSequence: (seqID = '', time) => return false if not @@SEQUENCES_TABLE return false if not @isValid return @currentSequences[seqID] if @currentSequences[seqID] return false if not @@SEQUENCES_TABLE[seqID] SequenceObject = @@SequenceObject @currentSequences[seqID] = SequenceObject(@, @@SEQUENCES_TABLE[seqID]) @currentSequences[seqID]\SetTime(time) if time @currentSequencesIterable = [seq for i, seq in pairs @currentSequences] return @currentSequences[seqID] RestartSequence: (seqID = '', time) => return false if not @isValid if @currentSequences[seqID] @currentSequences[seqID]\Reset() @currentSequences[seqID]\SetTime(time) return @currentSequences[seqID] return @StartSequence(seqID, time) PauseSequence: (seqID = '') => return false if not @isValid return @currentSequences[seqID]\Pause() if @currentSequences[seqID] return false ResumeSequence: (seqID = '') => return false if not @isValid return @currentSequences[seqID]\Resume() if @currentSequences[seqID] return false StopSequence: (...) => @EndSequence(...) EndSequence: (seqID = '', callStop = true) => return false if not @isValid return false if not @currentSequences[seqID] @currentSequences[seqID]\Stop() if callStop @currentSequences[seqID] = nil @currentSequencesIterable = [seq for i, seq in pairs @currentSequences] return true ResetSequences: => return false if not @@SEQUENCES return false if not @isValid seq\Stop() for _, seq in ipairs @currentSequencesIterable @currentSequences = {} @currentSequencesIterable = {} @StartSequence(seq.name) for _, seq in ipairs @@SEQUENCES when seq.autostart Reset: => @ResetSequences() RemoveHooks: => for _, iHook in ipairs @hooks hook.Remove iHook, @hookID PlayerRespawn: => return if not @isValid @ResetSequences() HasSequence: (seqID = '') => return false if not @isValid @currentSequences[seqID] and true or false GetSequence: (seqID = '') => @currentSequences[seqID] Hook: (id, func) => return if not @isValid newFunc = (...) -> if not IsValid(@GetEntity()) or @GetData()\GetData() ~= @GetEntity()\GetPonyData() @RemoveHooks() return func(@, ...) return nil hook.Add id, @hookID, newFunc table.insert(@hooks, id) Think: (ent = @GetEntity()) => return if not @IsValid() delta = RealTimeL() - @lastThink @lastThink = RealTimeL() @lastThinkDelta = delta return if not IsValid(ent) or ent\IsDormant() for _, seq in ipairs @currentSequencesIterable if not seq\IsValid() @EndSequence(seq\GetName(), false) break seq\Think(delta) @TriggerLerpAll(delta * 10) return delta Remove: => @isValid = false @RemoveHooks()
32.705882
92
0.716951
9258c79c386378daa4af9254ee360c3f5a97d500
30
使ってるレジスタのインデックスがまばらになってるのを詰める
15
29
0.966667
256aad4b4be15aeac161a0d15e2c76db0c12025d
1,151
System = require('vendor/secs/lib/system') { :Vector } = require('vendor/hug/lib/geo') MoveCommand = require('lib/commands/move') UseCommand = require('lib/commands/use') AttackCommand = require('lib/commands/attack') class PlayerInputSystem extends System @criteria: System.Criteria({ 'isPlayer', 'input', 'position', 'animation', 'maxSpeed' }) new: (@map) => update: (dt) => for entity in *@entities { :input, :velocity, :animation, :maxSpeed, :runSpeed, :heading } = entity\get() useCmd = entity.cache.useCmd or UseCommand(entity, @map) attackCmd = entity.cache.attackCmd or AttackCommand() if input\down('run') then maxSpeed = runSpeed horizontal = input\get('right') - input\get('left') vertical = input\get('down') - input\get('up') if horizontal != 0 or vertical != 0 velocity = Vector({ horizontal, vertical }, maxSpeed * dt) entity.commandQueue\add(MoveCommand(entity, velocity)) else if velocity then velocity\reset() animation.value\pause() if heading and input\pressed('use') entity.commandQueue\add(useCmd) if input\pressed('attack') entity.commandQueue\add(attackCmd)
31.108108
89
0.691573
267a18eb8525a349fc7f1924992f1ac516f24dc8
3,960
-- TODO: calc scale export script_name = "Vertical Text" export script_description = "Splits a line into vertical text." export script_version = "0.2.0" export script_author = "line0" export script_namespace = "l0.VerticalText" DependencyControl = require "l0.DependencyControl" depCtrl = DependencyControl{ feed: "https://raw.githubusercontent.com/TypesettingTools/line0-Aegisub-Scripts/master/DependencyControl.json", { {"a-mo.LineCollection", version: "1.3.0", url: "https://github.com/TypesettingTools/Aegisub-Motion", feed: "https://raw.githubusercontent.com/TypesettingTools/Aegisub-Motion/DepCtrl/DependencyControl.json"}, {"l0.ASSFoundation", version: "0.4.0", url: "https://github.com/TypesettingTools/ASSFoundation", feed: "https://raw.githubusercontent.com/TypesettingTools/ASSFoundation/master/DependencyControl.json"}, "Yutils" } } LineCollection, ASS, Yutils = depCtrl\requireModules! logger = depCtrl\getLogger! absCos = (a) -> math.abs math.cos math.rad a absSin = (a) -> math.abs math.sin math.rad a alignOffset = (x, a) -> math.abs x / 2 * math.cos math.rad a averageGlyphMetricsByFont = {} getAverageGlyphMetrics = (fontName) -> return averageGlyphMetricsByFont[fontName] if averageGlyphMetricsByFont[fontName] font = Yutils.decode.create_font fontName, false, false, false, false, 100 startChar, endChar = 65, 122 -- character codes within [A-Za-z] totalHeight, totalWidth, nonEmptyGlyphCount = 0, 0, 0 for c = startChar, endChar x1, y1, x2, y2 = Yutils.shape.bounding font.text_to_shape string.char c if x1 totalHeight += y2 - y1 totalWidth += x2 - x1 nonEmptyGlyphCount += 1 averageGlyphMetricsByFont[fontName] = { w: totalWidth/nonEmptyGlyphCount, h: totalHeight/nonEmptyGlyphCount } return averageGlyphMetricsByFont[fontName] process = (sub, sel, res) -> aegisub.progress.task "Processing..." lines = LineCollection sub, sel finalLines = LineCollection sub cb = (lines, line, i) -> data = ASS\parse line -- split line by characters charLines = data\splitAtIntervals 1, 4, false charOffset = 0 for charLine in *charLines logger\warn charLine.text charData = charLine.ASS -- get tags effective as of the first section (we know there won't be any tags after that) effTags = charData.sections[1]\getEffectiveTags(true,true).tags -- determine average width and height of glyphs for this font for vertical spacing generation averageGlyphMetrics = getAverageGlyphMetrics effTags.fontname.value -- with \an5 the type is centered between ascender and baseline, -- so we need to account for the descender and ascender separately metrics = charLine.ASS\getTextMetrics true charBounds = metrics.bounds descender = math.max charBounds[4] - metrics.ascent, 0 ascender = math.max metrics.descent - charBounds[2], 0 -- set \an5 effTags.align.value = 5 charData\removeTags "align" charData\insertTags effTags.align, 1 -- calculate new position frz = effTags.angle.value charOffset += ascender * absCos frz logger\dump {metrics} effTags.position\add 0, charOffset + alignOffset(charBounds.h - math.max(charBounds[2]-metrics.descent, 0), frz) + alignOffset(metrics.width, frz+90) charData\removeTags "position" charData\insertTags effTags.position, 1 -- set position for the next character spacing = 0.2 * averageGlyphMetrics.h * effTags.fontsize.value / 100 charOffset += absCos(frz) * (charBounds.h + spacing + descender) + absSin(frz) * metrics.width charData\commit! finalLines\addLine charLine aegisub.progress.set i * 100 / #lines.lines lines\runCallback cb, true lines\deleteLines! finalLines\insertLines! depCtrl\registerMacro process
38.823529
135
0.696465
049848035eb67b343944ce09239c53f8fd0de79d
5,947
ffi = require 'ffi' core = require 'ljglibs.core' Gtk = require 'ljglibs.gtk' import OffscreenWindow, Window, Box from Gtk describe 'core', -> describe 'define(name, spec, constructor)', -> it 'defines a metatype for the ctype given by <name>', -> ffi.cdef 'typedef struct {} my_type;' core.define 'my_type', {my_method: -> 'ret' } o = ffi.new 'my_type' assert.equal 'ret', o\my_method! it 'exposes any constants given in .constants', -> ffi.cdef 'typedef struct {} my_type2; enum Constants { WAT = 3 };' MyType = core.define 'my_type2', { constants: { 'WAT' } } assert.equal 3, MyType.WAT context '(properties)', -> it 'exposes any properties given in .properties', -> ffi.cdef 'typedef struct {} my_type3;' prop2 = 'unset' core.define 'my_type3', { properties: { my_prop: -> 'prop me up' prop2: { get: => prop2 set: (v) => prop2 = "set-#{v}" } } } o = ffi.new 'my_type3' assert.equal 'prop me up', o.my_prop o.prop2 = 'yes' assert.equal 'set-yes', o.prop2 it 'provides automatic getting and setting for named, GObject, properties', -> ffi.cdef 'typedef struct {} my_gobject_type;' set_typed = setmetatable {}, __call: (t, o, ...) -> t.args = {...} get_typed = setmetatable {}, __call: (t, o, ...) -> t.args = {...} 123 core.define 'my_gobject_type', { properties: my_prop: 'gint' :get_typed :set_typed } o = ffi.new 'my_gobject_type' assert.equal 123, o.my_prop o.my_prop = 234 assert.same { 'my-prop', 'gint' }, get_typed.args assert.same { 'my-prop', 'gint', 234 }, set_typed.args context '(inheritance)', -> it 'dispatches missing methods, properties and constants to the base', -> ffi.cdef [[ typedef struct {} my_base; enum BaseConstants { FIND_ME = 123 }; typedef struct {} my_middle; enum MiddleConstants { MIDDLE_ME = 456 }; typedef struct {} my_child; ]] core.define 'my_base', { constants: { 'FIND_ME' } properties: { inh_prop: => assert.equal ffi.typeof('my_base *'), ffi.typeof(@) 'from_base' } override_me: => 'base' meth: => assert.equal ffi.typeof('my_base *'), ffi.typeof(@) 'base_ret' } core.define 'my_middle < my_base', { constants: { 'MIDDLE_ME' } properties: { middle_prop: => assert.equal ffi.typeof('my_middle *'), ffi.typeof(@) 'from_middle' } override_me: => assert.equal ffi.typeof('my_middle *'), ffi.typeof(@) 'middle' } MyType = core.define 'my_child < my_middle', {} o = ffi.new 'my_child *' assert.equal 'from_base', o.inh_prop assert.equal 123, MyType.FIND_ME assert.equal 'base_ret', o\meth! assert.equal 'from_middle', o.middle_prop assert.equal 456, MyType.MIDDLE_ME assert.equal 'middle', o\override_me! context '(instance creation)', -> context 'when a table is passed as the final arg to the constructor', -> it 'sets any key-value pairs as properties on the instance', -> local first_args ffi.cdef 'typedef struct { int foo; } my_prop_type;' MyPropType = core.define 'my_prop_type', { properties: { foo: { get: => @foo set: (v) => @.foo = v } } }, (spec, ...) -> first_args = {...} ffi.new 'my_prop_type' o = MyPropType 'one', 2, { foo: 123 } assert.equal 123, o.foo assert.same { 'one', 2 }, first_args describe 'with positional (array part) parameters', -> it 'adds them as children', -> child_box = Box! box = Box { { padding: 123, child_box } } assert.equal 123, box\properties_for(child_box).padding children = box.children assert.equal 1, #children assert.equal child_box, children[1] it 'does nothing if the type is specified as a no-container', -> ffi.cdef 'typedef struct { int foo; } my_final_type;' MyPropType = core.define 'my_final_type', { properties: { foo: { get: => @foo set: (v) => @.foo = v } }, meta: { __is_container: false } }, (spec, ...) -> ffi.new 'my_prop_type' o = MyPropType { foo: 123 } assert.not_equal 123, o.foo context '(signals)', -> it 'sets up signal hook functions automatically based on the gtype', -> win = OffscreenWindow! show_handler = spy.new -> win\on_show show_handler, nil, 123 win\show! assert.spy(show_handler).was_called_with win, nil, 123 it 'casts arguments of known types', -> win = OffscreenWindow! show_handler = (signal_win) -> assert.equal Window.show, signal_win.show win\on_show show_handler win\show! describe 'bit_flags(def, prefix, value)', -> it 'offers a convinient way of accessing bit flags using string constants', -> def = { MY_FOO: 1, MY_BAR: 2, } flags = core.bit_flags def, 'MY_', 2 assert.is_true flags.BAR assert.is_false flags.FOO it 'raises an error upon access of a non-existent constant', -> flags = core.bit_flags {}, 2 assert.raises 'Unknown', -> flags.NO
32.856354
84
0.523457
22362df67dd9a9190f85cd8cdfc5e389a1031091
1,173
log = require "log" class STA @config: -> Config = require 'config' cfg = Config.get().sta wifi.sta.sethostname cfg.name wifi.sta.config ssid: cfg.ssid pwd: cfg.pwd auto: true save: true @get: -> {:ssid} = wifi.sta.getconfig true ssid: ssid @set: (cfg) -> wifi.sta.config cfg Config = require 'config' ret = Config.get() ret.sta = cfg Config.set ret class AP @config: -> Config = require 'config' cfg = Config.get().ap wifi.ap.config cfg wifi.ap.setip cfg log.debug sjson.encode ap: AP.get() @get: -> {:ssid} = wifi.ap.getconfig true ip, nm, gw = wifi.ap.getip() return { ssid: ssid ip: ip nm: nm gw: gw } @set: (cfg) -> wifi.ap.config cfg Config = require 'config' ret = Config.get() ret.ap = cfg Config.set ret wifi.setmode wifi.STATIONAP, true wifi.eventmon.register wifi.eventmon.STA_GOT_IP, -> log.debug "STA: #{sjson.encode STA.get()}" wifi.eventmon.register wifi.eventmon.AP_STACONNECTED, (opts) -> log.debug "AP: #{opts.MAC} connected" STA.config() AP.config() return { STA: STA AP: AP }
18.619048
63
0.591645
8daa74433e736176ce537613fb4f7c58f5e8583f
150
export modinfo = { type: "function" id: "Output7" func: (message, color, recipient, stick) -> TabletMerge message, color, recipient, stick, 7 }
18.75
49
0.68
84b43ee2428983b529e8b9df7899d2781312aef4
116
str => val => end => (for 0 (len str) end n => i = (sub (len str) (add n 1)) (val (slc str i (add i 1))))
23.2
33
0.456897
678e48ebc63ea86c09ee6099defd789d1df7b403
2,986
--- Teal Lpeg lexer, based on the lexer from the Lua bundle howl.util.lpeg_lexer -> c = capture keyword = c 'keyword', word { 'and', 'break', 'do', 'elseif', 'else', 'end', 'false', 'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat', 'return', 'then', 'true', 'until', 'while', 'record', 'enum', 'global', 'type' } bracket_quote_lvl_start = P'[' * Cg(P('=')^0, 'lvl') * '[' bracket_quote_lvl_end = ']' * match_back('lvl') * ']' bracket_quote = bracket_quote_lvl_start * scan_to(bracket_quote_lvl_end)^-1 comment = c 'comment', '--' * any { bracket_quote, scan_until eol, } sq_string = span("'", "'", '\\') dq_string = span('"', '"', P'\\') string = c 'string', any { sq_string, dq_string, bracket_quote } operator = c 'operator', S'+-*!/%^#~=<>;:,.(){}[]' hexadecimal_number = P'0' * S'xX' * xdigit^1 * (P'.' * xdigit^1)^0 * (S'pP' * S'-+'^0 * xdigit^1)^0 float = digit^0 * P'.' * digit^1 number = c 'number', any({ hexadecimal_number * any('LL', 'll', 'ULL', 'ull')^-1, digit^1 * any { 'LL', 'll', 'ULL', 'ull' }, (float + digit^1) * (S'eE' * P('-')^0 * digit^1)^0 }) ident = (alpha + '_')^1 * (alpha + digit + '_')^0 identifier = c 'identifier', ident constant = c 'constant', upper^1 * any(upper, '_', digit)^0 * any(eol, -#lower) type_def = sequence { c 'keyword', word { 'record', 'enum', 'type' }, c 'whitespace', blank^1, c 'type_def', upper^1 * (alpha + digit + '_')^0 } type_name = c 'type', upper^1 * (alpha + digit + '_')^0 builtin_type = c 'type', word { 'any', 'boolean', 'integer', 'number', 'string', 'thread', 'userdata' } special = c 'special', any { 'true', 'false', 'nil', '_' * upper^1 -- variables conventionally reserved for Lua } ws = c 'whitespace', blank^0 fdecl = any { sequence { c('keyword', 'function'), c 'whitespace', blank^1, c('fdecl', ident * (S':.' * ident)^-1) }, sequence { c('fdecl', ident), ws, c('operator', '='), ws, c('keyword', 'function'), -#any(digit, alpha) } } cdef = sequence { any { sequence { c('identifier', 'ffi'), c('operator', '.'), }, line_start }, c('identifier', 'cdef'), c('operator', '(')^-1, ws, any { sequence { c('string', bracket_quote_lvl_start), sub_lex('c', bracket_quote_lvl_end), c('string', bracket_quote_lvl_end)^-1, }, sequence { c('string', '"'), sub_lex('c', '"'), c('string', '"')^-1, }, sequence { c('string', "'"), sub_lex('c', "'"), c('string', "'")^-1, } } } any { number, string, comment, operator, special, type_def, builtin_type, fdecl, keyword, cdef, constant, type_name, identifier, }
23.511811
94
0.492632
4012da6f7eff6c9c0975c099447bfd25ddaae4d6
6,267
VERSION = "1.3.0" import insert, concat from table import load, setfenv, assert, type, error, tostring, tonumber, setmetatable from _G setfenv = setfenv or (fn, env) -> local name i = 1 while true name = debug.getupvalue fn, i break if not name or name == "_ENV" i += 1 if name debug.upvaluejoin fn, i, (-> env), 1 fn html_escape_entities = { ['&']: '&amp;' ['<']: '&lt;' ['>']: '&gt;' ['"']: '&quot;' ["'"]: '&#039;' } html_escape = (str) -> (str\gsub [=[["><'&]]=], html_escape_entities) get_line = (str, line_num) -> -- todo: this returns an extra blank line at the end for line in str\gmatch "([^\n]*)\n?" return line if line_num == 1 line_num -= 1 pos_to_line = (str, pos) -> line = 1 for _ in str\sub(1, pos)\gmatch("\n") line += 1 line class Compiler html_escape: true new: => @buffer = {} @i = 0 render: => table.concat @buffer push: (str, ...) => i = @i + 1 @buffer[i] = str @i = i @push ... if ... header: => @push "local _tostring, _escape, _b, _b_i = ...\n" footer: => @push "return _b" increment: => @push "_b_i = _b_i + 1\n" mark: (pos) => @push "--[[", tostring(pos), "]] " assign: (...) => @push "_b[_b_i] = ", ... @push "\n" if ... compile_chunks: (chunks) => @header! for chunk in *chunks t = type chunk t = chunk[1] if t == "table" switch t when "string" @increment! @assign ("%q")\format(chunk) when "code" @mark chunk[3] @push chunk[2], "\n" when "=", "-" @increment! @mark chunk[3] @assign! if t == "=" and @html_escape @push "_escape(_tostring(", chunk[2], "))\n" else @push "_tostring(", chunk[2], ")\n" else error "unknown type #{t}" @footer! @render! class Parser open_tag: "<%" close_tag: "%>" modifiers: "^[=-]" next_tag: => start, stop = @str\find @open_tag, @pos, true -- no more tags, all done unless start @push_raw @pos, #@str return false -- add text before unless start == @pos @push_raw @pos, start - 1 @pos = stop + 1 modifier = if @str\match @modifiers, @pos with @str\sub @pos, @pos @pos += 1 close_start, close_stop = @str\find @close_tag, @pos, true unless close_start return nil, @error_for_pos start, "failed to find closing tag" while @in_string @pos, close_start close_start, close_stop = @str\find @close_tag, close_stop, true unless close_start return nil, @error_for_pos start, "failed to find string close" trim_newline = if "-" == @str\sub close_start - 1, close_start - 1 close_start -= 1 true @push_code modifier or "code", @pos, close_start - 1 @pos = close_stop + 1 if trim_newline if match = @str\match "^\n", @pos @pos += #match true -- see if stop leaves us in the middle of a string in_string: (start, stop) => in_string = false end_delim = nil escape = false pos = 0 skip_until = nil chunk = @str\sub start, stop for char in chunk\gmatch "." pos += 1 if skip_until continue if pos <= skip_until skip_until = nil if end_delim if end_delim == char and not escape in_string = false end_delim = nil else if char == "'" or char == '"' end_delim = char in_string = true if char == "[" if lstring = chunk\match "^%[=*%[", pos lstring_end = lstring\gsub "%[", "]" lstring_p1, lstring_p2 = chunk\find lstring_end, pos, true -- no closing lstring, must be inside string return true unless lstring_p1 skip_until = lstring_p2 escape = char == "\\" in_string push_raw: (start, stop) => insert @chunks, @str\sub start, stop push_code: (kind, start, stop) => insert @chunks, { kind, @str\sub(start, stop), start } compile: (str) => success, err = @parse str return nil, err unless success fn, err = @load @chunks_to_lua! return nil, err unless fn (...) -> buffer, err = @run fn, ... if buffer concat buffer else nil, err parse: (@str) => assert type(@str) == "string", "expecting string for parse" @pos = 1 @chunks = {} while true found, err = @next_tag! return nil, err if err break unless found true parse_error: (err, code) => line_no, err_msg = err\match "%[.-%]:(%d+): (.*)$" line_no = tonumber line_no return unless line_no line = get_line code, line_no source_pos = tonumber line\match "^%-%-%[%[(%d+)%]%]" return unless source_pos @error_for_pos source_pos, err_msg error_for_pos: (source_pos, err_msg) => source_line_no = pos_to_line @str, source_pos source_line = get_line @str, source_line_no "#{err_msg} [#{source_line_no}]: #{source_line}" -- converts lua string into template function load: (code, name="etlua") => code_fn = do code_ref = code -> with ret = code_ref code_ref = nil fn, err = load code_fn, name unless fn -- try to extract meaningful error message if err_msg = @parse_error err, code return nil, err_msg return nil, err fn -- takes a function from @load and executes it with correct parameters run: (fn, env={}, buffer, i, ...) => combined_env = setmetatable {}, __index: (name) => val = env[name] val = _G[name] if val == nil val unless buffer buffer = {} i = 0 setfenv fn, combined_env fn tostring, html_escape, buffer, i, ... compile_to_lua: (str, ...) => success, err = @parse str return nil, err unless success @chunks_to_lua ... -- generates the code of the template chunks_to_lua: (compiler_cls=Compiler) => compiler_cls!\compile_chunks @chunks compile = Parser!\compile render = (str, ...) -> fn, err = compile(str) if fn fn ... else nil, err { :compile, :render, :Parser, :Compiler, _version: VERSION }
21.836237
83
0.553534
74f961db4061f9b54f80b06499938800b321a164
3,311
class CurveLocation extends Base new: (curve, parameter, point, _curve2, _parameter2, _point2, _distance) => -- Define this CurveLocation's unique id. @_id = CurveLocation._id = (CurveLocation._id or 0) + 1 @_curve = curve -- Also store references to segment1 and segment2, in case path -- splitting / dividing is going to happen, in which case the segments -- can be used to determine the new curves, see --getCurve(true) @_segment1 = curve._segment1 @_segment2 = curve._segment2 @_parameter = parameter @_point = point @_curve2 = _curve2 @_parameter2 = _parameter2 @_point2 = _point2 @_distance = _distance getSegment: => if !@_segment curve = @getCurve() parameter = @getParameter() if parameter is 1 @_segment = curve._segment2 else if parameter is 0 or arg[0] @_segment = curve._segment1 else if !parameter? return nil else -- Determine the closest segment by comparing curve lengths @_segment = (if curve\getLength(0, parameter) < curve\getLength(parameter, 1)then curve._segment1 else curve._segment2) @_segment getCurve: => if not @_curve or arg[0] -- If we're asked to get the curve uncached, access current curve -- objects through segment1 / segment2. Since path splitting or -- dividing might have happened in the meantime, try segment1's -- curve, and see if _point lies on it still, otherwise assume it's -- the curve before segment2. @_curve = @_segment1\getCurve() @_curve = @_segment2\getPrevious()\getCurve() if !@_curve\getParameterOf(@_point)? @_curve getIntersection: => intersection = @_intersection if not intersection and @_curve2 param = @_parameter2 -- If we have the parameter on the other curve use that for -- intersection rather than the point. @_intersection = intersection = CurveLocation(@_curve2, param, @_point2 or @_point, @) intersection._intersection = @ intersection getPath: => curve = @getCurve() curve and curve._path getIndex: => curve = @getCurve() curve and curve\getIndex() getOffset: => path = @getPath() path and path\_getOffset(@) getCurveOffset: => curve = @getCurve() parameter = @getParameter() parameter? and curve and curve\getLength(0, parameter) getParameter: => if (not @_parameter? or arg[0]) and @_point curve = @getCurve(arg[0] and @_point) @_parameter = curve and curve\getParameterOf(@_point) @_parameter getPoint: => if (not @_point or arg[0]) and @_parameter? curve = @getCurve() @_point = curve and curve\getPointAt(@_parameter, true) @_point getTangent: => parameter = @getParameter() curve = @getCurve() parameter? and curve and curve\getTangentAt(parameter, true) getNormal: => parameter = @getParameter() curve = @getCurve() parameter? and curve and curve\getNormalAt(parameter, true) getDistance: => @_distance divide: => curve = @getCurve(true) curve and curve\divide(@getParameter(true)) split: => curve = @getCurve(true) curve and curve\split(@getParameter(true))
29.04386
127
0.643008
2cb6c3064f8c5c89622eebe855914efbf8d36967
111
love.conf = (t) -> t.identity = 'pathfun-editor' t.window = false -- window will be created by settings.moon
27.75
60
0.684685
1d853c1b3cc57959b85ae0b2b26642be451333b1
5,510
import bundle, mode, Buffer from howl import File from howl.io import Editor from howl.ui describe 'moonscript-mode', -> local m local buffer, editor, cursor setup -> bundle.load_by_name 'lua' bundle.load_by_name 'moonscript' m = mode.by_name 'moonscript' teardown -> bundle.unload 'moonscript' bundle.unload 'lua' before_each -> m = mode.by_name 'moonscript' buffer = Buffer m editor = Editor buffer cursor = editor.cursor it 'registers a mode', -> assert.not_nil m it 'handles .moon files', -> assert.equal mode.for_file(File 'test.moon'), m describe 'indentation support', -> indent_level = 2 before_each -> buffer.config.indent = indent_level indents = { 'pending function definitions': { 'foo: =>', 'foo: -> ' } 'pending class declarations': { 'class Frob', 'class Frob ', 'class Frob extends Bar ', } 'hanging assignments': { 'var = ', 'var: ', } 'open bracket statements': { 'var = { ', 'var = {', 'other: {', 'some(', '{' } 'open conditionals': { 'if foo and bar', 'else', 'elseif (foo and bar) or frob', 'elseif true', 'while foo', 'unless bar', } 'block statements': { 'switch foo!' 'do', 'for i = 1,10', 'with some.object', 'when conditional', 'foo = if bar and frob' } } non_indents = { 'closed conditionals': { 'if foo then bar', 'elseif foo then bar', 'unless foo then bar', 'bar unless foo', 'else bar', }, 'statement modifiers': { 'foo! if bar', 'foo! unless bar', } 'miscellaneous non-indenting statements': { 'foo = bar', 'foo = bar frob zed' 'foo = not bar(frob zed)' 'ado', 'fortwith bar' 'motif some' 'iffy!' 'dojo_style foo' 'one for two' } } dedents = { 'block starters': { 'else', 'elseif foo', } 'block enders': { '}', } } for desc in pairs indents context 'indents one level for a line after ' .. desc, -> for code in *indents[desc] it "e.g. indents for '#{code}'", -> buffer.text = code .. '\n' cursor.line = 2 editor\indent! assert.equal indent_level, editor.current_line.indentation it 'disregards empty lines above when determining indent', -> for desc in pairs indents for code in *indents[desc] buffer.text = code .. '\n\n' cursor.line = 3 editor\indent! assert.equal indent_level, editor.current_line.indentation for desc in pairs dedents context 'dedents one level for a line containing ' .. desc, -> for code in *dedents[desc] it "e.g. dedents for '#{code}'", -> buffer.text = ' foo\n ' .. code cursor.line = 2 editor\indent! assert.equal 0, editor.current_line.indentation for desc in pairs non_indents context 'keeps the current indent for a line after ' .. desc, -> for code in *non_indents[desc] it "e.g. does not indent for '#{code}'", -> buffer.text = " #{code}\n " cursor.line = 2 editor\indent! assert.equal 2, editor.current_line.indentation it 'enforces the same indent after ","', -> buffer.text = " foo,\nbar" cursor.line = 2 editor\indent! assert.equal 2, editor.current_line.indentation it 'returns a corrected indent for lines that are on incorrect indentation', -> buffer.text = ' bar\n one_column_offset' cursor.line = 2 editor\indent! assert.equal 2, editor.current_line.indentation it 'returns the indent for the previous line for a line with a non-motivated greater indent', -> buffer.text = 'bar\n foo' cursor.line = 2 editor\indent! assert.equal 0, editor.current_line.indentation it 'keeps the indent for lines when nothing particular is known', -> buffer.text = ' foo\nbar' cursor.line = 2 editor\indent! assert.equal 0, editor.current_line.indentation it 'returns the indent for the previous line for a blank line', -> buffer.text = ' bar\n' cursor.line = 2 editor\indent! assert.equal 2, editor.current_line.indentation describe 'structure(editor)', -> it 'returns lines that match class and function declarations', -> buffer.text = [[ bar = -> true foo = -> true but_this_passes_a_callback -> 'no' also = a_callback -> class Foo new: (frob) => nil other: => 'this one to' class_f: -> 'oh yeah' ]] expected = [[ bar = -> true foo = -> class Foo new: (frob) => other: => class_f: -> ]] assert.equal expected.stripped, table.concat [tostring(l) for l in *m\structure(editor)], '\n' it 'always includes the parent line of an included line', -> buffer.text = [[ take_me! { foo: -> 'voila' } ]] assert.same {1, 3}, [l.nr for l in *m\structure editor] it 'falls back to the parent structure method if nothing is found', -> buffer.text = [[ foo { bar: 1 frob: zed: 2 } ]] assert.same {1, 3}, [l.nr for l in *m\structure editor]
24.932127
100
0.553902
5375225327ac68408e2d7106b2d9c60fa1018279
12,532
util = require'util' data = [[ [ "That's a crooked tree. We'll send him to Washington.", "The only thing worse than yellow snow is green snow.", "I like to beat the brush.", "In painting, you have unlimited power. You have the ability to move mountains. You can bend rivers. But when I get home, the only thing I have power over is the garbage.", "You need the dark in order to show the light.", "Look around. Look at what we have. Beauty is everywhere you only have to look to see it.", "Just go out and talk to a tree. Make friends with it.", "There's nothing wrong with having a tree as a friend.", "Trees cover up a multitude of sins.", "They say everything looks better with odd numbers of things. But sometimes I put even numbers\u00e2\u20ac\u201djust to upset the critics.", "How do you make a round circle with a square knife? That's your challenge for the day.", "A thin paint will stick to a thick paint.", "Just beat the devil out of it.", "We don't make mistakes we just have happy little accidents.", "We'll paint one happy little tree right here.", "Just pretend you are a whisper floating across a mountain.", "From all of us here, I want to wish you happy painting and God bless, my friends.", "We tell people sometimes: we're like drug dealers, come into town and get everybody absolutely addicted to painting. It doesn't take much to get you addicted.", "The secret to doing anything is believing that you can do it. Anything that you believe you can do strong enough, you can do. Anything. As long as you believe.", "Water's like me. It's laaazy\u00c2 ... Boy, it always looks for the easiest way to do things", "I really believe that if you practice enough you could paint the 'Mona Lisa' with a two-inch brush.", "If I paint something, I don't want to have to explain what it is.", "We artists are a different breed of people. We're a happy bunch.", "I guess I'm a little weird. I like to talk to trees and animals. That's okay though; I have more fun than most people.", "Let's get crazy.", "I can't think of anything more rewarding than being able to express yourself to others through painting.", "Exercising the imagination, experimenting with talents, being creative; these things, to me, are truly the windows to your soul.", "All you need to paint is a few tools, a little instruction, and a vision in your mind.", "I started painting as a hobby when I was little. I didn't know I had any talent. I believe talent is just a pursued interest. Anybody can do what I do.", "Everyone is going to see things differently - and that's the way it should be.", "No pressure. Just relax and watch it happen.", "When you do it your way you can go anywhere you choose.", "You can create beautiful things - but you have to see them in your mind first", "It's so important to do something every day that will make you happy", "Don't be afraid to make these big decisions. Once you start, they sort of just make themselves.", "With something so strong, a little bit can go a long way.", "You have to allow the paint to break to make it beautiful.", "Think about a cloud. Just float around and be there.", "In nature, dead trees are just as normal as live trees.", "It's hard to see things when you're too close. Take a step back and look.", "Only think about one thing at a time. Don't get greedy.", "If you do too much it's going to lose its effectiveness.", "Use absolutely no pressure. Just like an angel's wing.", "You're meant to have fun in life.", "In life you need colors.", "It's a super day, so why not make a beautiful sky?", "Just let go - and fall like a little waterfall.", "It's beautiful - and we haven't even done anything to it yet.", "Be careful. You can always add more - but you can't take it away.", "Pretend you're water. Just floating without any effort. Having a good day.", "When things happen - enjoy them. They're little gifts.", "Take your time. Speed will come later.", "It's amazing what you can do with a little love in your heart.", "God gave you this gift of imagination. Use it.", "Paint anything you want on the canvas. Create your own world.", "That's what painting is all about. It should make you feel good when you paint.", "You can do anything your heart can imagine.", "With practice comes confidence.", "This is happy place, little squirrels live here and play.", "We have no limits to our world. We're only limited by our imagination.", "Be so very light. Be a gentle whisper.", "The least little bit can do so much.", "All you have to do is let your imagination go wild.", "Didn't you know you had that much power? You can move mountains. You can do anything.", "If you don't like it - change it. It's your world.", "There is immense joy in just watching - watching all the little creatures in nature.", "Don't forget to tell these special people in your life just how special they are to you.", "That is when you can experience true joy, when you have no fear.", "We don't really know where this goes - and I'm not sure we really care.", "Life is too short to be alone, too precious. Share it with a friend.", "Work on one thing at a time. Don't get carried away - we have plenty of time.", "If we're going to have animals around we all have to be concerned about them and take care of them.", "Almost everything is going to happen for you automatically - you don't have to spend any time working or worrying.", "Sometimes you learn more from your mistakes than you do from your masterpieces.", "There are no limits in this world.", "You can create anything that makes you happy.", "You want your tree to have some character. Make it special.", "In your world you have total and absolute power.", "The man who does the best job is the one who is happy at his job.", "Everything's not great in life, but we can still find beauty in it.", "Don't hurry. Take your time and enjoy.", "You're the greatest thing that has ever been or ever will be. You're special. You're so very special.", "There is no right or wrong - as long as it makes you happy and doesn't hurt anyone.", "Everyone needs a friend. Friends are the most valuable things in the world.", "There are no mistakes. You can fix anything that happens.", "That's why I paint - because I can create the kind of world I want - and I can make this world as happy as I want it.", "It's life. It's interesting. It's fun.", "Just think about these things in your mind - then bring them into your world.", "In your imagination you can go anywhere you want.", "That's what makes life fun. That you can make these decisions. That you can create the world that you want.", "Go out on a limb - that's where the fruit is.", "In this world, everything can be happy.", "All you have to learn here is how to have fun.", "Isn't it great to do something you can't fail at?", "Anytime you learn something your time and energy are not wasted.", "A tree cannot be straight if it has a crooked trunk.", "You've got to learn to fight the temptation to resist these things. Just let them happen.", "You create the dream - then you bring it into your world.", "These things happen automatically. All you have to do is just let them happen.", "You can do anything here. So don't worry about it.", "This present moment is perfect simply due to the fact you're experiencing it.", "Only God can make a tree - but you can paint one.", "You can't make a mistake. Anything that happens you can learn to use - and make something beautiful out of it.", "Put light against light - you have nothing. Put dark against dark - you have nothing. It's the contrast of light and dark that each give the other one meaning.", "This is an example of what you can do with just a few things, a little imagination and a happy dream in your heart.", "If what you're doing doesn't make you happy - you're doing the wrong thing.", "Just relax and let it flow. That easy.", "Every single thing in the world has its own personality - and it is up to you to make friends with the little rascals.", "Trees grow however makes them happy.", "Don't kill all your dark areas - you need them to show the light.", "Everyone wants to enjoy the good parts - but you have to build the framework first.", "A big strong tree needs big strong roots.", "The light is your friend. Preserve it.", "Everybody's different. Trees are different. Let them all be individuals.", "We want to use a lot pressure while using no pressure at all.", "Follow the lay of the land. It's most important.", "We don't have anything but happy trees here.", "Even trees need a friend. We all need friends.", "Isn't it fantastic that you can change your mind and create all these happy things?", "The first step to doing anything is to believe you can do it. See it finished in your mind before you ever start.", "No worries. No cares. Just float and wait for the wind to blow you around.", "It just happens - whether or not you worried about it or tried to plan it.", "If it's not what you want - stop and change it. Don't just keep going and expect it will get better.", "You can create the world you want to see and be a part of. You have that power.", "How to paint. That's easy. What to paint. That's much harder.", "We can always carry this a step further. There's really no end to this.", "But we're not there yet, so we don't need to worry about it.", "This is your creation - and it's just as unique and special as you are.", "La- da- da- da- dah. Just be happy.", "Just take out whatever you don't want. It'll change your entire perspective.", "If you don't think every day is a good day - try missing a few. You'll see.", "There isn't a rule. You just practice and find out which way works best for you.", "Just let your mind wander and enjoy. This should make you happy.", "We don't have to be committed. We are just playing here.", "Remember how free clouds are. They just lay around in the sky all day long.", "Any little thing can be your friend if you let it be.", "The very fact that you're aware of suffering is enough reason to be overjoyed that you're alive and can experience it.", "And that's when it becomes fun - you don't have to spend your time thinking about what's happening - you just let it happen.", "This is probably the greatest thing to happen in my life - to be able to share this with you.", "If there are two big trees, eventually there will be a little tree.", "Everybody needs a friend.", "You can do anything here - the only pre-requisite is that it makes you happy.", "The more we do this - the more it will do good things to our heart.", "Even the worst thing we can do here is good.", "Absolutely no pressure. You are just a whisper floating across a mountain.", "You have freedom here. The only guide is your heart.", "Trees grow in all kinds of ways. They're not all perfectly straight. Not every limb is perfect.", "We must be quiet, soft and gentle.", "You can't have light without dark. You can't know happiness unless you've known sorrow.", "Just let this happen. We just let this flow right out of our minds.", "Just make a decision and let it go.", "Everything is happy if you choose to make it that way.", "You could sit here for weeks with your one hair brush trying to do that - or you could do it with one stroke with an almighty brush.", "We're not trying to teach you a thing to copy. We're just here to teach you a technique, then let you loose into the world.", "A tree needs to be your friend if you're going to paint him.", "You have to make almighty decisions when you're the creator.", "This is your world, whatever makes you happy you can put in it. Go crazy.", "We don't have to be concerned about it. We just have to let it fall where it will.", "We don't need any guidelines or formats. All we need to do is just let it flow right out of us.", "Let all these little things happen. Don't fight them. Learn to use them.", "I sincerely wish for you every possible joy life could bring.", "We spend so much of our life looking - but never seeing.", "Talent is a pursued interest. That is to say, anything you practice you can do.", "Let's make some happy little clouds in our world" ] ]] PRIVMSG: '^%pbobross$': => quotes = util.json.decode data choice = math.random(1, #quotes) say quotes[choice]
70.011173
174
0.717124
1fcf61046a63b277d6a21a96e05eb6fd23c4b50b
5,087
-- Copyright 2014 The Howl Developers -- License: MIT (see LICENSE.md at the top-level directory of the distribution) Cursor = require 'aullar.cursor' View = require 'aullar.view' Selection = require 'aullar.selection' Buffer = require 'aullar.buffer' Gtk = require 'ljglibs.gtk' describe 'View', -> local view, buffer, cursor before_each -> buffer = Buffer '' view = View buffer cursor = view.cursor window = Gtk.OffscreenWindow default_width: 800, default_height: 640 window\add view\to_gobject! window\show_all! pump_mainloop! context 'visible line orientation properties', -> local nr_lines_in_screen before_each -> line_height = view\text_dimensions('M').height nr_lines_in_screen = math.floor view.height / line_height buffer.text = string.rep '123456789\n', nr_lines_in_screen * 3 view.first_visible_line = 1 describe '.first_visible_line', -> it 'is the first visible line', -> assert.equals 1, view.first_visible_line view\scroll_to 10 assert.equals 10, view.first_visible_line describe '.middle_visible_line', -> it 'is the center vertical line', -> assert.equals math.ceil(nr_lines_in_screen / 2), view.middle_visible_line it 'scrolls the view to show the specified line in the center when set', -> view.middle_visible_line = nr_lines_in_screen assert.equals nr_lines_in_screen, view.middle_visible_line assert.equals math.ceil(nr_lines_in_screen / 2), view.first_visible_line describe '.last_visible_line', -> it 'is the last visible line', -> assert.equals math.floor(nr_lines_in_screen), view.last_visible_line context '(coordinate translation)', -> before_each -> view.margin = 0 describe 'position_from_coordinates(x, y)', -> it 'returns the matching buffer position', -> dim = view\text_dimensions 'M' buffer.text = '1234\n6789' assert.equals 2, view\position_from_coordinates(view.edit_area_x + dim.width + 1, 0) assert.equals 8, view\position_from_coordinates(view.edit_area_x + (dim.width * 2) + 1, dim.height + 1) it 'favours the preceeding character slightly when in doubt', -> dim = view\text_dimensions 'M' buffer.text = '1234' assert.equals 1, view\position_from_coordinates(view.edit_area_x + dim.width / 2, 0) assert.equals 1, view\position_from_coordinates(view.edit_area_x + dim.width * 0.6, 0) assert.equals 2, view\position_from_coordinates(view.edit_area_x + dim.width * 0.8, 0) it 'returns nil for out of bounds coordinates', -> assert.is_nil view\position_from_coordinates(100, 100) describe 'coordinates_from_position(pos)', -> it 'returns the bounding rectangle for the character at pos', -> dim = view\text_dimensions 'M' buffer.text = '1234\n6789' assert.same { x: view.edit_area_x + dim.width x2: view.edit_area_x + (dim.width * 2) y: 0 y2: dim.height }, view\coordinates_from_position(2) assert.same { x: view.edit_area_x + (dim.width * 2) x2: view.edit_area_x + (dim.width * 3) y: dim.height y2: dim.height * 2 }, view\coordinates_from_position(8) describe '(when text is inserted)', -> it 'moves the cursor down if the insertion is before or at the cursor', -> buffer\insert 1, '123' assert.equals 4, cursor.pos buffer\insert 3, 'X' assert.equals 5, cursor.pos it 'leaves the cursor alone if the insertion is after the cursor', -> buffer.text = '123' cursor.pos = 2 buffer\insert 3, 'X' assert.equals 2, cursor.pos describe '(when text is deleted)', -> it 'moves the cursor up if the deletetion is before the cursor', -> buffer.text = '12345' cursor.pos = 4 buffer\delete 3, 1 assert.equals 3, cursor.pos it 'leaves the cursor alone if the deletetion is after or at the cursor', -> buffer.text = '12345' cursor.pos = 3 buffer\delete 4, 1 assert.equals 3, cursor.pos buffer\delete 3, 1 assert.equals 3, cursor.pos it 'only adjust the cursor by the affected amount', -> buffer.text = '12345' cursor.pos = 3 buffer\delete 2, 3 assert.equals 2, cursor.pos buffer.text = '123456789' cursor.pos = 8 buffer\delete 2, 3 assert.equals 5, cursor.pos describe 'when a buffer operation is undone', -> it 'moves the cursor to the position before action', -> buffer.text = '12345' cursor.pos = 2 buffer\delete 4, 1 cursor.pos = 1 buffer\undo! assert.equals 2, cursor.pos describe 'when a buffer operation is redone', -> it 'moves the cursor to the position after the action', -> buffer.text = '12345' cursor.pos = 2 buffer\insert 2, 'xx' assert.equals 4, cursor.pos buffer\undo! assert.equals 2, cursor.pos buffer\redo! assert.equals 4, cursor.pos
34.842466
111
0.650482
08a29b647b7a95f5a3cf56a495d4e14ce18e72e2
1,280
x = -> print what -> -> -> -> go to the barn open -> the -> door open -> the door hello = -> my func h = -> hi eat ->, world (->)() x = (...) -> hello! hello.world! hello!.something what!["ofefe"] what! the! heck! (a,b,c,d,e) -> (a,a,a,a,a) -> print a (x=23023) -> (x=(y=()->) ->) -> (x = if something then yeah else no) -> something = (hello=100, world=(x=[[yeah cool]])-> print "eat rice") -> print hello (x, y) => (@x, @y) => (x=1) => (@x=1,y,@z="hello world") => x -> return y -> return 1 z -> return 1, "hello", "world" k -> if yes then return else return -> real_name if something -- d( -> print "hello world" 10 ) d( 1,2,3 4 5 6 if something print "okay" 10 10,20 ) f( )( )( what )(-> print "srue" 123) -- x = (a, b) -> print "what" y = (a="hi", b=23) -> print "what" z = ( a="hi", b=23) -> print "what" j = (f,g,m, a="hi", b=23 ) -> print "what" y = (a="hi", b=23, ...) -> print "what" y = (a="hi", b=23, ... ) -> print "what" -- args = (a b) -> print "what" args = (a="hi" b=23) -> print "what" args = ( a="hi" b=23) -> print "what" args = (f,g,m a="hi" b=23 ) -> print "what" nil
8.050314
70
0.435938
23f4ed91294ce15e464c42e9bcaf954b34282d91
4,092
util = require "moonscript.util" import Set from require "moonscript.data" import insert from table import unpack from util -- implicit return does not work on these statements manual_return = Set { "foreach", "for", "while", "return" } -- Assigns and returns are bubbled into their bodies. -- All cascading statement transform functions accept a second arugment that -- is the transformation to apply to the last statement in their body cascading = Set { "if", "unless", "with", "switch", "class", "do" } terminating = Set { "return", "break" } -- type of node as string ntype = (node) -> switch type node when "nil" "nil" when "table" node[1] else "value" -- gets the class of a type if possible mtype = do moon_type = util.moon.type -- lets us check a smart node without throwing an error (val) -> mt = getmetatable val return "table" if mt and mt.smart_node moon_type val -- can this value be compiled in a line by itself value_can_be_statement = (node) -> return false unless ntype(node) == "chain" -- it's a function call ntype(node[#node]) == "call" is_value = (stm) -> compile = require "moonscript.compile" transform = require "moonscript.transform" compile.Block\is_value(stm) or transform.Value\can_transform stm value_is_singular = (node) -> type(node) != "table" or node[1] != "exp" or #node == 2 is_slice = (node) -> ntype(node) == "chain" and ntype(node[#node]) == "slice" t = {} node_types = { class: { {"name", "Tmp"} {"body", t} } fndef: { {"args", t} {"whitelist", t} {"arrow", "slim"} {"body", t} } foreach: { {"names", t} {"iter"} {"body", t} } for: { {"name"} {"bounds", t} {"body", t} } while: { {"cond", t} {"body", t} } assign: { {"names", t} {"values", t} } declare: { {"names", t} } if: { {"cond", t} {"then", t} } } build_table = -> key_table = {} for node_name, args in pairs node_types index = {} for i, tuple in ipairs args prop_name = tuple[1] index[prop_name] = i + 1 key_table[node_name] = index key_table key_table = build_table! make_builder = (name) -> spec = node_types[name] error "don't know how to build node: "..name if not spec (props={}) -> node = { name } for i, arg in ipairs spec key, default_value = unpack arg val = if props[key] then props[key] else default_value val = {} if val == t node[i + 1] = val node build = nil build = setmetatable { group: (body={}) -> {"group", body} do: (body) -> {"do", body} assign_one: (name, value) -> build.assign { names: {name} values: {value} } table: (tbl={}) -> -- convert strings to key literals for tuple in *tbl if type(tuple[1]) == "string" tuple[1] = {"key_literal", tuple[1]} {"table", tbl} block_exp: (body) -> {"block_exp", body} chain: (parts) -> base = parts.base or error"expecting base property for chain" if type(base) == "string" base = {"ref", base} node = {"chain", base} for part in *parts insert node, part node }, { __index: (name) => self[name] = make_builder name rawget self, name } smart_node_mt = setmetatable {}, { __index: (node_type) => index = key_table[node_type] mt = { smart_node: true __index: (node, key) -> if index[key] rawget node, index[key] elseif type(key) == "string" error "unknown key: `"..key.."` on node type: `"..ntype(node).. "`" __newindex: (node, key, value) -> key = index[key] if index[key] rawset node, key, value } self[node_type] = mt mt } -- makes it so node properties can be accessed by name instead of index smart_node = (node) -> setmetatable node, smart_node_mt[ntype node] NOOP = {"noop"} { :ntype, :smart_node, :build, :is_value, :is_slice, :manual_return, :cascading, :value_is_singular, :value_can_be_statement, :mtype, :terminating :NOOP }
20.666667
77
0.589198
53dbce1de0fae3bf54cbc4cbbdd4e40fdfb4f3d1
122
me = ... print me M = {} TK = require("PackageToolkit") m1 = TK.module.import me, "m1" M.hello = () -> m1.hello() return M
17.428571
30
0.598361
2549f289d832b0cf14b87836d316f65c26850cf8
1,843
export tiny = require "src/lib/tiny" export game = { scale: 16 ---------------------------------- -- mapping entity IDs to map colors ---------------------------------- map_stuff: { "player": {r: 255, g: 0, b: 0} "block": {r: 0, g: 0, b: 0} } ---------------------------------- -- initially loaded sprite - "efficiency!" ---------------------------------- sprites: { player: love.graphics.newImage "assets/player.png" block: love.graphics.newImage "assets/block.png" } } game.load = -> love.graphics.setBackgroundColor 100, 100, 100 export world = tiny.world! export draw_world = tiny.world! with world import movement, controller from require "src/systems" \addSystem controller \addSystem movement with draw_world import sprite from require "src/systems" \addSystem sprite with game .load_level "assets/levels/test.png" game.update = (dt) -> love.window.setTitle "FPS: #{love.timer.getFPS!}" world\update dt game.draw = -> draw_world\update! game.assemble = (t, ...) -> import player, block from require "src/entities" switch t when "player" p = player ... bump_world\add p, p.x, p.y, p.w, p.h with world \addEntity p with draw_world \addEntity p when "block" p = block ... bump_world\add p, p.x, p.y, p.w, p.h with world \addEntity p with draw_world \addEntity p game.load_level = (path) -> with game .enemies = {} image = love.image.newImageData path for x = 1, image\getWidth! for y = 1, image\getHeight! rx, ry = x - 1, y - 1 r, g, b = image\getPixel rx, ry for k, v in pairs .map_stuff if r == v.r and g == v.g and b == v.b .assemble k, .scale * rx, .scale * ry game
20.943182
58
0.544221
50edfad3123367ce598764bc80b520b6c2d28ab6
843
bigCmp = zb2rhb6YKkXTWP2SCqP9kq5hdGNvkmjZT4d42YLF9VNu34yXC bigMul = zb2rhnbB1UWmrC8dhYbJZ4aunoWc3o9JJR1W2jBHNpAjrnF2S bigSub = zb2rhecvjCY6eL7ixvBWQnpjECGYEoHNZGWKLA7KfCQrwMEin // Big -> Big -> Uint16 findDigit = a => b => state = {add: (pow 2 16) mul: (pow 2 16)} result = (for 0 17 state i => state => add0 = (get state "add") mul0 = (get state "mul") mult = (bigMul b cons => nil => (cons mul0 nil)) add1 = (div add0 2) mul1 = (bigCmp mult a (sub) (a=>b=>a) (add) mul0 add1) {mul:mul1 add:add1}) (flr (get result "mul")) a => b => (a digit => state => rem = c => n => (c digit (get state "rem" c n)) dig = (findDigit rem b) quo = c => n => (c dig (get state "quo" c n)) dif = (bigMul b (c => n => (c dig n))) {rem:(bigSub rem dif) quo:quo} {rem:c=>n=>n quo:c=>n=>n})
32.423077
58
0.582444
09fedde3936de47000f9cc4a62828fdcd99382c4
714
finder = require 'finder' love.window.close! print '1 - server, other - client' if tonumber(io.read(1)) == 1 print 'server' -- see 45 and 113 lines of Finder source for default values srv = finder.Server { port: 8080 handshake: '93203' } srv\on 'connect', (address) -> print address .. " connected to server!" srv\on 'disconnect', (address) -> print address .. " disconnected from server!" love.update = (dt) -> srv\update! else print 'client' cl = finder.Client { port: 8080 handshake: '93203' } cl\on 'connect', (address) -> print "Found server " .. address .. "!" cl\on 'disconnect', (address) -> print address .. " disconnected!" love.update = (dt) -> cl\update!
17.85
60
0.631653
07de23f007545d13e406c7dea3b513859edb0a11
20,522
export script_name = "Nudge" export script_description = "Provides configurable and hotkeyable tag/line modification macros." export script_version = "0.5.0" export script_author = "line0" export script_namespace = "l0.Nudge" DependencyControl = require "l0.DependencyControl" depCtrl = DependencyControl { feed: "https://raw.githubusercontent.com/TypesettingTools/line0-Aegisub-Scripts/master/DependencyControl.json", { "aegisub.clipboard", "json", {"a-mo.LineCollection", version: "1.3.0", url: "https://github.com/TypesettingTools/Aegisub-Motion"}, {"l0.ASSFoundation", version: "0.4.0", url: "https://github.com/TypesettingTools/ASSFoundation", feed: "https://raw.githubusercontent.com/TypesettingTools/ASSFoundation/master/DependencyControl.json"}, {"l0.Functional", version: "0.5.0", url: "https://github.com/TypesettingTools/Functional", feed: "https://raw.githubusercontent.com/TypesettingTools/Functional/master/DependencyControl.json"}, } } clipboard, json, LineCollection, ASS, Functional = depCtrl\requireModules! {:list, :math, :string, :table, :unicode, :util, :re } = Functional logger = depCtrl\getLogger! -------- Nudger Class ------------------- cmnOps = {"Add", "Multiply", "Power", "Cycle", "Set", "Set Default", "Remove", "Copy", "Paste Over", "Paste Into"} colorOps = list.join cmnOps, {"Add HSV"} stringOps = {"Append", "Prepend", "Replace", "Cycle", "Set", "Set Default", "Remove"} drawingOps = {"Add", "Multiply", "Power", "Remove", "Copy", "Paste Over", "Paste Into", "Expand", "Convert To Clip"} clipOpsVect = list.join drawingOps, {"Invert Clip", "Convert To Drawing", "Set Default"} clipOptsRect = list.join cmnOps, {"Invert Clip", "Convert To Drawing"} msgs = { configuation: { load: { unsupportedConfigFileVersion: "Your configuration file version (%s) is incompatible with %s %s. Please delete %s and reload your scripts." } } } class Nudger @operations = list.makeSet { "Align Up", "Align Down", "Align Left", "Align Right", "Set Default", "Cycle", "Remove", "Convert To Drawing", "Set Comment", "Unset Comment", "Toggle Comment", "Copy", "Paste Over", "Paste Into", "Expand", "Convert To Clip" }, { Add: "add", Multiply: "mul", Power: "pow", Set: "set", Toggle: "toggle", Replace: "replace" Append: "append", Prepend: "prepend", ["Auto Cycle"]: "cycle", ["Add HSV"]: "addHSV", ["Invert Clip"]: "toggleInverse" }, nil, false @targets = { tags: { position: cmnOps, blur_edges: cmnOps, scale_x: cmnOps, scale_y: cmnOps, align: {"Align Up", "Align Down", "Align Left", "Align Right", "Auto Cycle", "Set", "Set Default", "Cycle"}, angle: cmnOps, angle_y: cmnOps, angle_x: cmnOps, outline: cmnOps, outline_x: cmnOps, outline_y: cmnOps, shadow: cmnOps, shadow_x: cmnOps, shadow_y: cmnOps, alpha: cmnOps, alpha1: cmnOps, alpha2: cmnOps, alpha3: cmnOps, alpha4: cmnOps, ["Alphas"]: cmnOps, color1: colorOps, color2: colorOps, color3: colorOps, color4: colorOps, ["Colors"]: colorOps, ["Primary Color"]: colorOps blur: cmnOps, shear_x: cmnOps, shear_y: cmnOps, bold: list.join(cmnOps,{"Toggle"}), underline: {"Toggle","Set", "Set Default"}, spacing: cmnOps, fontsize: cmnOps, k_fill: cmnOps, k_sweep_alt: cmnOps, k_sweep: cmnOps, k_bord: cmnOps, move: cmnOps, move_simple: cmnOps, origin: cmnOps, wrapstyle: {"Auto Cycle","Cycle", "Set", "Set Default"}, fade_simple: cmnOps, fade: cmnOps, ["Fades"]: cmnOps, italic: {"Toggle","Set", "Set Default"}, reset: stringOps, fontname: stringOps, clip_vect: clipOpsVect, iclip_vect: clipOpsVect, clip_rect: clipOptsRect, iclip_rect: clipOptsRect, ["Clips (Vect)"]: clipOpsVect, ["Clips (Rect)"]: clipOptsRect, Clips: clipOpsVect, unknown: {"Remove"}, junk: {"Remove"}, Comment: {"Remove"}, ["Comments/Junk"]: {"Remove"} ["Any Tag"]: {"Remove", "Copy", "Paste Over", "Paste Into"}, }, line: { Line: {"Set Comment", "Unset Comment", "Toggle Comment"}, Text: {"Convert To Drawing", "Expand", "Convert To Clip"}, Drawing: drawingOps, Contents: {"Convert To Drawing", "Expand"} } } @compoundTargets = { Colors: {"color1","color2","color3","color4"}, Alphas: {"alpha", "alpha1", "alpha2", "alpha3", "alpha4"}, Fades: {"fade_simple", "fade"}, Clips: {"clip_vect", "clip_rect", "iclip_vect", "iclip_rect"}, ["Clips (Vect)"]: {"clip_vect", "iclip_vect"}, ["Clips (Rect)"]: {"clip_rect", "iclip_rect"}, ["\\move"]: {"move", "move_simple"}, ["Any Tag"]: ASS.tagNames.all, Contents: {"Text", "Drawing"} } @targetList = list.join table.keys(@@targets.line), [ASS.toFriendlyName[name] or name for name, _ in pairs @@targets.tags] new: (params = {}) => @name = params.name or "Unnamed Nudger" @tag = params.tag or "position" @operation = params.operation or "Add" @value = params.value or {} @id = params.id or util.uuid! @noDefault = params.noDefault or false @keepEmptySections = params.keepEmptySections == nil and true or params.keepEmptySections @targetValue = params.targetValue or 0 @targetName = params.targetName or "Tag Section" @validate! validate: => -- do we need to check the other values? ops = @@targets.tags[@tag] or @@targets.line[@tag] logger\assert list.indexOf(ops, @operation), "Operation %s not supported for tag or section %s.", @operation, @tag nudgeTags: (lineData, lines, line, targets) => tagSect = @targetValue != 0 and tonumber(@targetValue) or nil relative = @targetName == "Matched Tag" builtinOp = @@operations[@operation] foundTags = lineData\getTags targets, tagSect, tagSect, relative foundCnt = #foundTags -- insert default tags if no matching tags are present if foundCnt == 0 and not @noDefault and not relative and @operation != "Remove" lineData\insertDefaultTags targets, tagSect if builtinOp lineData\modTags targets, (tag) -> tag[builtinOp] tag, unpack @value, tagSect, tagSect, relative return switch @operation when "Copy" tagStr = {} lineData\modTags targets, (tag) -> tagStr[#tagStr+1] = tag\getTagString!, tagSect, tagSect, relative clipboard.set table.concat tagStr when "Paste Over" pasteTags = ASS.TagList(ASS.Section.Tag(clipboard.get!))\filterTags targets lineData\replaceTags pasteTags, tagSect, tagSect, relative when "Paste Into" pasteTags = ASS.TagList ASS.Section.Tag clipboard.get! global, normal = pasteTags\filterTags targets, global: true lineData\insertTags normal, tagSect, -1, not relative lineData\replaceTags global when "Cycle" edField = "l0.Nudge.cycleState" ed = line\getExtraData edField if type(ed) == "table" ed[@id] = ed[@id] and ed[@id] < #@value and ed[@id] + 1 or 1 else ed = {[@id]: 1} line\setExtraData edField, ed lineData\modTags targets, (tag) -> tag\set unpack @value[ed[@id]], tagSect, tagSect, relative when foundCnt > 0 and "Set Default" defaults = lineData\getStyleDefaultTags! lineData\modTags targets, (tag) -> tag\set defaults.tags[tag.__tag.name]\get!, tagSect, tagSect, relative lineData\cleanTags 1, false when "Expand" lineData\modTags targets, (tag) -> tag\expand @value[1], @value[2], tagSect, tagSect, relative when "Convert To Drawing" keepPos, drawing, pos = not @value[2] lineData\modTags targets, (tag) -> drawing, pos = tag\getDrawing(keepPos) return @value[1] == true, tagSect, tagSect, relative lineData\insertSections drawing lineData\replaceTags pos if pos when "Remove" lineData\removeTags targets, tagSect, tagSect, relative else opAlign = re.match @operation, "Align (Up|Down|Left|Right)" if opAlign pos, align, org = lineData\getPosition! newAlign = align\copy! newAlign[string.lower(opAlign[2].str)] newAlign if @value[1] == true haveDrawings, haveRotation, w, h = false, false lineData\callback (section,sections,i) -> haveDrawings = true, ASS.Section.Drawing -- While text uses type metrics for positioning and alignment -- vector drawings use a straight bounding box -- TODO: make this work for lines that have both drawings AND text if haveDrawings bounds = lineData\getLineBounds! w, h = bounds.w, bounds.h else metrics = lineData\getTextMetrics true w, h = metrics.width, metrics.height pos\add newAlign\getPositionOffset w, h, align -- add origin if any rotation is applied to the line effTags = lineData\getEffectiveTags -1, true, true, false trans, tags = effTags\checkTransformed!, effTags.tags if tags.angle\modEq(0, 360) and tags.angle_x\modEq(0, 360) and tags.angle_y\modEq(0, 360) and not (trans.angle or trans.angle_x or trans.angle_y) lineData\replaceTags {newAlign, pos} else lineData\replaceTags {newAlign, org, pos} else lineData\replaceTags {newAlign} nudgeLines: (lineData, lines, line, targets) => op = @operation relative = @targetName == "Matched Tag" tagSect = @targetValue != 0 and @targetValue or nil if targets["Line"] line.comment = switch op when "Unset Comment" then false when "Set Comment" then true when "Toggle Comment" then not line.comment if targets["Text"] if op == "Convert To Clip" local toConvert lineData\callback (sect) -> toConvert = sect\convertToDrawing! return false, ASS.Section.Text, 1, 1, true if toConvert lineData\replaceTags toConvert\getClip! else lineData\callback (sect) -> switch op when "Convert To Drawing" then sect\convertToDrawing! when "Expand" then sect\expand(@value[1], @value[2]), ASS.Section.Text, tagSect, tagSect, relative if targets["Drawing"] or targets["Text"] targetSections = {targets["Drawing"] and ASS.Section.Drawing, targets["Text"] and ASS.Section.Text} switch op when "Copy" sectStr = {} lineData\callback (sect) -> sectStr[#sectStr+1] = sect\getString!, targetSections, tagSect, tagSect, relative clipboard.set table.concat sect when "Paste Over" sectStr = clipboard.get! lineData\callback (sect) -> if sect.class == ASS.Section.Text sect.value = sectStr else return ASS.Section.Drawing str: sectStr, targetSections, tagSect, tagSect, relative when "Paste Into" sectStr = clipboard\get! if targets["Drawing"] and sectStr:match("m%s+[%-%d%.]+%s+[%-%d%.]+") lineData\insertSections ASS.Section.Drawing str: sectStr elseif targets["Text"] lineData\insertSections ASS.Section.Text sectStr when "Convert To Clip" local clip lineData\callback (sect) -> if clip clip\insertContours sect\getClip! else clip = sect\getClip! return false, ASS.Section.Drawing, tagSect, tagSect, relative if clip then lineData\replaceTags clip if targets["Drawing"] builtinOp = @@operations[@operation] lineData\callback (sect) -> if builtinOp sect[builtinOp] sect, unpack @value elseif op == "Expand" sect\expand @value[1], @value[2], ASS.Section.Drawing, tagSect, tagSect, relative if targets["Comments/Junk"] and op == "Remove" lineData\stripComments! lineData\removeTags "junk", tagSect, tagSect, relative elseif targets["Comment"] and op == "Remove" lineData\stripComments! nudge: (sub, sel) => targets, tagTargets, lineTargets = @@compoundTargets[@tag], {}, {} if targets for i = 1, #targets if ASS.tagMap[targets[i]] tagTargets[#tagTargets+1] = targets[i] else lineTargets[#lineTargets+1] = targets[i] lineTargets[targets[i]] = true elseif ASS.tagMap[@tag] tagTargets[1] = @tag else lineTargets[1], lineTargets[@tag] = @tag, true lines = LineCollection sub, sel, () -> true lines\runCallback (lines, line) -> lineData = ASS\parse line if #tagTargets > 0 @nudgeTags lineData, lines, line, tagTargets if #lineTargets > 0 @nudgeLines lineData, lines, line, lineTargets lineData\commit nil, @keepEmptySections lines\replaceLines! table.sort Nudger.targetList encodeDlgResName = (id, name) -> "#{id}.#{name}" decodeDlgResName = (un) -> un\match "([^%.]+)%.(.+)" class Configuration @default = { __version: script_version, nudgers: { {operation: "Add", value: {1,0}, id: "d0dad24e-515e-40ab-a120-7b8d24ecbad0", name: "Position Right (+1)", tag: "position"}, {operation: "Add", value: {-1,0}, id: "0c6ff644-ef9c-405a-bb12-032694d432c0", name: "Position Left (-1)", tag: "position"}, {operation: "Add", value: {0,-1}, id: "cb2ec6c1-a8c1-48b8-8a13-cafadf55ffdd", name: "Position Up (-1)", tag: "position"}, {operation: "Add", value: {0,1}, id: "cb9c1a5b-6910-4fb2-b457-a9c72a392d90", name: "Position Down (+1)", tag: "position"}, {operation: "Cycle", value: {{0.6},{0.8},{1},{1.2},{1.5},{2},{3},{4},{5},{8}}, id: "c900ef51-88dd-413d-8380-cebb7a59c793", name: "Cycle Blur", tag: "blur"}, {operation: "Cycle", value: {{255},{0},{16},{48},{96},{128},{160},{192},{224}}, id: "d338cbca-1575-4795-9b80-3680130cce62", name: "Cycle Alpha", tag: "alpha"}, {operation: "Toggle", value: {}, id: "974c3af9-ef51-45f5-a992-4850cb006743", name: "Toggle Bold", tag: "bold"}, {operation: "Auto Cycle", value: {}, id: "aa74461a-477b-47de-bbf4-16ef1ee568f5", name: "Cycle Wrap Styles", tag: "wrapstyle"}, {operation: "Align Up", value: {true}, id: "254bf380-22bc-457b-abb7-3d1f85b90eef", name: "Align Up", tag: "align"}, {operation: "Align Down", value: {true}, id: "260318dc-5bdd-4975-9feb-8c95b41e7b5b", name: "Align Down", tag: "align"}, {operation: "Align Left", value: {true}, id: "e6aeca35-d4e0-4ff4-81ac-8d3a853d5a9c", name: "Align Left", tag: "align"}, {operation: "Align Right", value: {true}, id: "dd80e1c5-7c07-478c-bc90-7c473c3abe49", name: "Align Right", tag: "align"}, {operation: "Set", value: {1}, id: "18a27245-5306-4990-865c-ae7f0062083a", name: "Add Edgeblur", tag: "blur_edges"}, {operation: "Set Default", value: {1}, id: "bb4967a7-fb8a-4907-b5e8-395ea67c0a52", name: "Default Origin", tag: "origin"}, {operation: "Add HSV", value: {0,0,0.1}, id: "015cd09b-3c2b-458e-a65a-80b80bb951b1", name: "Brightness Up", tag: "Colors"}, {operation: "Add HSV", value: {0,0,-0.1}, id: "93f07885-c3f7-41bb-b319-0542e6fd52d7", name: "Brightness Down", tag: "Colors"}, {operation: "Invert Clip", value: {}, id: "e719120a-e45a-44d4-b76a-62943f47d2c5", name: "Invert First Clip", tag: "Clips", noDefault: true, targetName: "Matched Tag", targetValue: "1"}, {operation: "Remove", value: {}, id: "4dfc33fd-3090-498b-8922-7e1eb4515257", name: "Remove Comments & Junk", tag: "Comments/Junk", noDefault: true}, {operation: "Remove", value: {}, id: "bc642b90-8ebf-45e8-a160-98b4658721bd", name: "Strip Tags", tag: "Any Tag", noDefault: true, keepEmptySections: false}, {operation: "Convert To Drawing", value: {false, false}, id: "9cf44e64-9ce9-402e-8097-9e189014c9c1", name: "Clips -> Drawing", tag: "Clips", noDefault: true}, } } new: (fileName) => @fileName = aegisub.decode_path(fileName) @nudgers = {} @load! load: => fileHandle = io.open @fileName local data if fileHandle data = json.decode fileHandle\read '*a' fileHandle\close! else data = @@default -- version checking logger\assert tonumber(data.__version\sub(3,3)) >= 3, msgs.configuation.load.unsupportedConfigFileVersion, data.__version, script_name, script_version, @fileName @nudgers = [Nudger nudgerConfig for nudgerConfig in *data.nudgers] @save! unless fileHandle save: => data = json.encode {nudgers: @nudgers, __version: script_version} fileHandle = io.open @fileName, 'w' fileHandle\write data fileHandle\close! addNudger: (params) => @nudgers[#@nudgers+1] = Nudger params removeNudger: (id) => @nudgers = list.filter @nudgers, (nudger) -> nudger.id != id getNudger: (id) => list.find @nudgers, (nudger) -> nudger.id == id getDialog: => dialog = { {class: "label", label: "Macro Name", x: 0, y: 0, width: 1, height: 1}, {class: "label", label: "Override Tag", x: 1, y: 0, width: 1, height: 1}, {class: "label", label: "Action", x: 2, y: 0, width: 1, height: 1}, {class: "label", label: "Value", x: 3, y: 0, width: 1, height: 1}, {class: "label", label: "Target", x: 4, y: 0, width: 1, height: 1}, {class: "label", label: "Target #", x: 5, y: 0, width: 1, height: 1}, {class: "label", label: "No Default", x: 6, y: 0, width: 1, height: 1}, {class: "label", label: "Keep Empty", x: 7, y: 0, width: 1, height: 1}, {class: "label", label: "Remove", x: 8, y: 0, width: 1, height: 1}, } getUnwrappedJson = (arr) -> jsonString = json.encode arr return jsonString\sub 2, jsonString\len!-1 tags, operations = Nudger.targetList, table.keys Nudger.operations table.sort operations for i, nu in ipairs @nudgers dialog = list.join dialog, { {class: "edit", name: encodeDlgResName(nu.id, "name"), value: nu.name, x: 0, y: i, width: 1, height: 1}, {class: "dropdown", name: encodeDlgResName(nu.id, "tag"), items: tags, value: ASS.toFriendlyName[nu.tag] or nu.tag, x: 1, y: i, width: 1, height: 1}, {class: "dropdown", name: encodeDlgResName(nu.id, "operation"), items: operations, value: nu.operation, x: 2, y: i, width: 1, height: 1}, {class: "edit", name: encodeDlgResName(nu.id, "value"), value: getUnwrappedJson(nu.value), step: 0.5, x: 3, y: i, width: 1, height: 1}, {class: "dropdown", name: encodeDlgResName(nu.id, "targetName"), items: {"Tag Section", "Matched Tag"}, value: nu.targetName, x: 4, y: i, width: 1, height: 1}, {class: "intedit", name: encodeDlgResName(nu.id, "targetValue"), value: nu.targetValue, x: 5, y: i, width: 1, height: 1}, {class: "checkbox", name: encodeDlgResName(nu.id, "noDefault"), value: nu.noDefault, x: 6, y: i, width: 1, height: 1}, {class: "checkbox", name: encodeDlgResName(nu.id, "keepEmptySections"), value: nu.keepEmptySections, x: 7, y: i, width: 1, height: 1}, {class: "checkbox", name: encodeDlgResName(nu.id, "remove"), value: false, x: 8, y: i, width: 1, height: 1} } return dialog update: (res) => for k, v in pairs res id, name = decodeDlgResName k v = switch name when "value" then json.decode "[#{v}]" when "tag" then ASS.toTagName[v] or v else v if name == "remove" and v == true @removeNudger id elseif nudger = @getNudger(id) nudger[name] = v nudger\validate! for nudger in *@nudgers @registerMacros! registerMacros: => for nudger in *@nudgers aegisub.register_macro "#{script_name}/#{nudger.name}", script_description, (sub, sel) -> nudger\nudge sub, sel run: (noReload) => @load! unless noReload btn, res = aegisub.dialog.display @getDialog!, {"Save", "Cancel", "Add Nudger"}, {save: "Save", cancel: "Cancel", close: "Save"} switch btn when "Add Nudger" @addNudger! @run true when "Save" @update res @save! else @load! config = Configuration depCtrl\getConfigFileName! aegisub.register_macro "#{script_name}/Configure Nudge", script_description, () -> config\run! config\registerMacros!
43.204211
167
0.61992
7fd1a3f80918796f74fe6f75f743f4d20c27dca0
3,318
lfs = require "lfs" parse = require "moonscript.parse" compile = require "moonscript.compile" util = require "moonscript.util" pattern = ... import unpack from util options = { in_dir: "spec/inputs", out_dir: "spec/outputs", input_pattern: "(.*)%.moon$", output_ext: ".lua" show_timings: os.getenv "TIME" diff: { tool: "git diff --no-index --color" --color-words" filter: (str) -> -- strip the first four lines table.concat [line for line in *util.split(str, "\n")[5,]], "\n" } } timings = {} gettime = nil pcall -> require "socket" gettime = socket.gettime gettime or= os.clock benchmark = (fn) -> if gettime start = gettime! res = {fn!} gettime! - start, unpack res else nil, fn! read_all = (fname) -> if f = io.open(fname, "r") with f\read "*a" f\close! diff_file = (a_fname, b_fname) -> out = io.popen(options.diff.tool .. " ".. a_fname .. " " .. b_fname, "r")\read "*a" if options.diff.filter out = options.diff.filter out out diff_str = (expected, got) -> a_tmp = os.tmpname! .. ".expected" b_tmp = os.tmpname! .. ".got" with io.open(a_tmp, "w") \write expected \close! with io.open(b_tmp, "w") \write got \close! with diff_file a_tmp, b_tmp os.remove a_tmp os.remove b_tmp string_assert = (expected, got) -> if expected != got diff = diff_str expected, got error "string equality assert failed" if os.getenv "HIDE_DIFF" error "string equality assert failed:\n" .. diff input_fname = (base) -> options.in_dir .. "/" .. base .. ".moon" output_fname = (base) -> options.out_dir .. "/" .. base .. options.output_ext describe "input tests", -> inputs = for file in lfs.dir options.in_dir with match = file\match options.input_pattern continue unless match table.sort inputs for name in *inputs input = input_fname name fn = if pattern and not input\match pattern pending else it fn input .. " #input", -> file_str = read_all input_fname name parse_time, tree, err = benchmark -> parse.string file_str error err if err compile_time, code, err, pos = benchmark -> compile.tree tree error compile.format_error err, pos, file_str unless code table.insert timings, {name, parse_time, compile_time} if os.getenv "BUILD" with io.open output_fname(name), "w" \write code \close! else expected_str = read_all output_fname name error "Test not built: " .. input_fname(name) unless expected_str string_assert expected_str, code nil if options.show_timings teardown -> format_time = (sec) -> ("%.3fms")\format(sec*1000) col_width = math.max unpack [#t[1] for t in *timings] print "\nTimings:" total_parse, total_compile = 0, 0 for tuple in *timings name, parse_time, compile_time = unpack tuple name = name .. (" ")\rep col_width - #name total_parse += parse_time total_compile += compile_time print " * " .. name, "p: " .. format_time(parse_time), "c: " .. format_time(compile_time) print "\nTotal:" print " parse:", format_time total_parse print " compile:", format_time total_compile
23.531915
85
0.614828
dfb1331104b63dbb4afdc4a499f029553f1b2552
535
export modinfo = { type: "command" desc: "Visible" alias: {"visible", "vis"} func: getDoPlayersFunction (v) -> if v and v.Character for a,obj in pairs(v.Character\GetChildren()) if obj\IsA"BasePart" if obj.Name ~= "HumanoidRootPart" obj.Transparency = 0 if obj\FindFirstChild"face" obj.face.Transparency = 0 elseif obj\IsA"Hat" and obj\FindFirstChild"Handle" obj.Handle.Transparency = 0 elseif obj\IsA"Accessory" and obj\FindFirstChild"Handle" obj.Handle.Transparency = 0 }
31.470588
61
0.669159
4fb97e68bcc15597e94e446ef384e480e9d68aae
833
M = {} T = require("PackageToolkit").module parseNumbers = (T.import ..., "../_strings/_parseNumbers").parseNumbers -- If only one input is given, returns the range between 1 and n -- If more than one input are given, return the list of numbers starting from -- the 2nd argument -- indices(3) return {1,2,3} -- indices(3, 1,2) returns {1,2} -- If a string is given as the second argument, -- then it will be parsed and split by " " M.indices = (n=1, ...) -> args = {...} if #args == 0 return [i for i = 1, n] else if type(args[1]) == "number" return args elseif type(args[1]) == "string" return parseNumbers args[1], " " else print "WARNING: unrecognized second argument to FX.numeric.indices(): " .. tostring(args[1]) return {} return M
36.217391
104
0.596639