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
703d51054bde8a2caf434860ddad29694bdf287f
171
export modinfo = { type: "command" desc: "UnDeek" alias: {"undeek"} func: getDoPlayersFunction (v) -> pcall -> tr = v.Character["Nice thing"] tr.Parent = nil }
19
34
0.625731
8f1160e962acc744d6e319a09219d5de21dc2dbf
164
Dorothy! VisualSettingView = require "View.Control.Unit.VisualSetting" --MessageBox = require "Control.Basic.MessageBox" Class VisualSettingView, __init:=>
23.428571
62
0.768293
950fcda6435b984842b808ce32635a03dc22bcd9
3,237
--- Handle outgoing responses -- @author RyanSquared <[email protected]> -- @classmod data.Response http = cookies: require "http.cookies" headers: require "http.headers" class Response --- Return a Response handler -- @tparam http.stream stream lua-http server -> client stream -- @tparam App tbsp_app Turbospoon app -- @tparam Request request Associated request object new: (stream, tbsp_app, request)=> assert stream assert tbsp_app @stream = stream @app = tbsp_app @cookies = {} @session = request.session --- Add a cookie to be sent back to the client -- @tparam table cookie -- **Must have the following fields:** -- -- - `max_age` - Amount of seconds for the cookie to live (`0` == session) -- - `key` - Name to store the cookie by -- - `value` - Value for the cookie, can be any RFC-safe string -- -- **Can also have the following fields:** -- -- - `domain` - PSL-compatible domain name where the cookie is valid -- - `path` - URI path where the cookie is valid -- - `secure` - Whether a cookie can be sent over unencrypted connections -- - `http_only` - Whether browsers, etc. should be able to read the cookie -- - `same_site` (`"strict"` or `"lax"`) - Same Site cookie policy add_cookie: (cookie)=> assert cookie.max_age, "Missing cookie.max_age" assert cookie.key, "Missing cookie.key" assert cookie.value, "Missing cookie.value" @cookies[cookie.key] = cookie.key --- Remove a cookie based on key -- @tparam string key remove_cookie: (key)=> @cookies[key] = nil --- Create session cookies and set it as a header -- @tparam number age Age for cookie (default 28 days) _make_session_cookie: (age = 60 * 60 * 24 * 28)=> -- no need to worry about optimizing ^ because most Lua interpreters -- implement folding of static values automatically return if not @session @cookies.session = key: "session" value: @app.jwt\encode @session max_age: age http_only: true -- ::TODO:: redirect() --- Send HTTP headers to the client -- @tparam number status HTTP status code -- @tparam http.headers headers Optional headers to send to client write_headers: (status, headers = http.headers.new!)=> assert status -- if headers are *not* of http.headers, they should be instead a -- key-value mapping of tables headers_mt = getmetatable headers if headers_mt != http.headers.mt new_headers = http.headers.new! for k, v in pairs headers new_headers\append k, v headers = new_headers if not headers\has "content-type" then headers\append "content-type", "text/plain" @_make_session_cookie! for cookie in *@cookies headers\append "set-cookie", http.cookies.bake_cookie cookie headers\upsert ":status", tostring status @stream\write_headers headers, @method == "HEAD" -- ::TODO:: write_chunk() --- Send text as the body of the message -- @tparam string text write_body: (text)=> return if @method == "HEAD" @stream\write_chunk tostring(text), true --- Send HTTP headers and body text at the same time -- @tparam string text -- @tparam number status HTTP status -- @tparam http.headers headers HTTP headers write_response: (text, status = 200, headers)=> @write_headers status, headers @write_body text
32.049505
76
0.699722
0308929850a91a6e4c354021749ce95735826f30
129
export modinfo = { type: "command" desc: "Tests Output2" alias: {"T2"} func: (Msg,Speaker) -> Output2(Msg,{Colors.Green}) }
18.428571
29
0.635659
b6b55ef8ec532122ba00a22b01362e29086a57ba
5,747
import insert, concat from table import get_fields from require "lapis.util" unpack = unpack or table.unpack query_parts = {"where", "group", "having", "order", "limit", "offset"} rebuild_query_clause = (parsed) -> buffer = {} if joins = parsed.join for {join_type, join_clause} in *joins insert buffer, join_type insert buffer, join_clause for p in *query_parts clause = parsed[p] continue unless clause and clause != "" p = "order by" if p == "order" p = "group by" if p == "group" insert buffer, p insert buffer, clause concat buffer, " " flatten_iter = (iter) -> current_page = iter! idx = 1 -> if current_page with current_page[idx] idx += 1 unless current_page[idx] current_page = iter! idx = 1 class Paginator new: (@model, clause="", ...) => @db = @model.__class.db param_count = select "#", ... opts = if param_count > 0 last = select param_count, ... if type(last) == "table" and not @db.is_encodable last param_count -= 1 last elseif type(clause) == "table" opts = clause clause = "" opts @per_page = @model.per_page @per_page = opts.per_page if opts @_clause = if param_count > 0 @db.interpolate_query clause, ... else clause @opts = opts select: (...) => @model\select ... prepare_results: (items) => if pr = @opts and @opts.prepare_results pr items else items each_item: => flatten_iter @each_page! class OffsetPaginator extends Paginator per_page: 10 each_page: (page=1) => -> results = @get_page page if next results page += 1 results get_all: => @prepare_results @select @_clause, @opts -- 1 indexed page get_page: (page) => page = (math.max 1, tonumber(page) or 0) - 1 limit = @db.interpolate_query " LIMIT ? OFFSET ?", @per_page, @per_page * page, @opts @prepare_results @select @_clause .. limit, @opts num_pages: => math.ceil @total_items! / @per_page has_items: => parsed = @db.parse_clause(@_clause) parsed.limit = "1" parsed.offset = nil parsed.order = nil tbl_name = @db.escape_identifier @model\table_name! res = @db.query "SELECT 1 FROM #{tbl_name} #{rebuild_query_clause parsed}" not not unpack res total_items: => unless @_count parsed = @db.parse_clause(@_clause) parsed.limit = nil parsed.offset = nil parsed.order = nil if parsed.group error "OffsetPaginator: can't calculate total items in a query with group by" tbl_name = @db.escape_identifier @model\table_name! query = "COUNT(*) AS c FROM #{tbl_name} #{rebuild_query_clause parsed}" @_count = unpack(@db.select query).c @_count class OrderedPaginator extends Paginator order: "ASC" -- default sort order per_page: 10 valid_orders = { asc: true desc: true } new: (model, @field, ...) => super model, ... if @opts and @opts.order @order = @opts.order @opts.order = nil each_page: => tuple = {} -> tuple = { @get_page unpack tuple, 2 } if next tuple[1] tuple[1] get_page: (...) => @get_ordered @order, ... after: (...) => @get_ordered "ASC", ... before: (...) => @get_ordered "DESC", ... get_ordered: (order, ...) => parsed = assert @db.parse_clause @_clause has_multi_fields = type(@field) == "table" and not @db.is_raw @field order_lower = order\lower! unless valid_orders[order_lower] error "OrderedPaginator: invalid query order: #{order}" table_name = @model\table_name! prefix = @db.escape_identifier(table_name) .. "." escaped_fields = if has_multi_fields [prefix .. @db.escape_identifier f for f in *@field] else { prefix .. @db.escape_identifier @field } if parsed.order error "OrderedPaginator: order should not be provided for #{@@__name}" if parsed.offset or parsed.limit error "OrderedPaginator: offset and limit should not be provided for #{@@__name}" parsed.order = table.concat ["#{f} #{order}" for f in *escaped_fields], ", " if ... op = switch order\lower! when "asc" ">" when "desc" "<" pos_count = select "#", ... if pos_count > #escaped_fields error "OrderedPaginator: passed in too many values for paginated query (expected #{#escaped_fields}, got #{pos_count})" order_clause = if 1 == pos_count order_clause = "#{escaped_fields[1]} #{op} #{@db.escape_literal (...)}" else positions = {...} buffer = {"("} for i in ipairs positions unless escaped_fields[i] error "passed in too many values for paginated query (expected #{#escaped_fields}, got #{pos_count})" insert buffer, escaped_fields[i] insert buffer, ", " buffer[#buffer] = nil insert buffer, ") " insert buffer, op insert buffer, " (" for pos in *positions insert buffer, @db.escape_literal pos insert buffer, ", " buffer[#buffer] = nil insert buffer, ")" concat buffer if parsed.where parsed.where = "#{order_clause} and (#{parsed.where})" else parsed.where = order_clause parsed.limit = tostring @per_page query = rebuild_query_clause parsed res = @select query, @opts final = res[#res] res = @prepare_results res if has_multi_fields res, get_fields final, unpack @field else res, get_fields final, @field { :OffsetPaginator, :OrderedPaginator, :Paginator}
23.650206
127
0.598747
169be27c068e99f7ff83b3932c5a6950003d80ab
125
parent = ... members = { "split", } M = {} for name in *members M[name] = require(parent.."._"..name)[name] return M
13.888889
47
0.552
7171faf696995a56d2600482871077e358595946
164
export modinfo = { type: "command" desc: "Name" alias: {"SN"} func: (Msg,Speaker) -> Output(string.format("This script's name is: %s",Name),{Colors.Orange}) }
23.428571
73
0.640244
a7bab34cafa39f9f1aaa7277de7f411f70ff718d
387
db = require "lapis.db" import assert_env from require "lapis.environment" truncate_tables = (...) -> assert_env "test", for: "truncate_tables" tables = for t in *{...} if type(t) == "table" t\table_name! else t -- truncate is slow, so delete is used instead -- db.truncate unpack tables for table in *tables db.delete table { :truncate_tables }
17.590909
50
0.638243
f5e50b6f81e44fbae85dbe63851abb997543af85
129
export modinfo = { type: "command" desc: "Tests Output4" alias: {"T4"} func: (Msg,Speaker) -> Output4(Msg,{Colors.Green}) }
18.428571
29
0.635659
dd5ea4e7edbf9d79d2eea01192856afb770284da
18,058
-- Copyright (C) 2018-2020 DBotThePony -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -- of the Software, and to permit persons to whom the Software is furnished to do so, -- subject to the following conditions: -- The above copyright notice and this permission notice shall be included in all copies -- or substantial portions of the Software. -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, -- INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR -- PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE -- FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -- OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -- DEALINGS IN THE SOFTWARE. fixme_init = { '/advdupe2/' 'duplicator.lua' } DPP2.FIXME_HookSpawns = DPP2.FIXME_HookSpawns or fixme_init for init in *fixme_init if not table.qhasValue(DPP2.FIXME_HookSpawns, init) table.insert(DPP2.FIXME_HookSpawns, init) log_blacklist = { 'logic_collision_pair' 'phys_constraint' 'phys_hinge' 'phys_constraintsystem' 'phys_lengthconstraint' } DPP2.PlayerSpawnedSomething = (ply, ent, advancedCheck = false) -> return if ent.__dpp2_hit ent.__dpp2_hit = true ent.__dpp2_dupe_fix = nil return false if ent\GetEFlags()\band(EFL_KILLME) ~= 0 if ply\DPP2IsBanned() SafeRemoveEntity(ent) return false classname = ent\GetClass() if not DPP2.SpawnRestrictions\Ask(classname, ply) hook.Run('DPP_SpawnRestrictionHit', ply, ent) DPP2.NotifyError(ply, 5, 'message.dpp2.restriction.spawn', classname) DPP2.LogSpawn('message.dpp2.log.spawn.tried_generic', ply, color_red, DPP2.textcolor, ent) SafeRemoveEntity(ent) return false if DPP2.PerEntityLimits.IS_INCLUSIVE\GetBool() check = false if entry = DPP2.PerEntityLimits\Get(classname, ply\GetUserGroup()) check = not entry.limit or entry.limit >= #ply\DPP2GetAllEntsByClass(classname) if not check hook.Run('DPP_SpawnLimitHit', ply, ent) DPP2.NotifyError(ply, 5, 'message.dpp2.limit.spawn', classname) DPP2.LogSpawn('message.dpp2.log.spawn.tried_generic', ply, color_red, DPP2.textcolor, ent) SafeRemoveEntity(ent) return false else if entry = DPP2.PerEntityLimits\Get(classname, ply\GetUserGroup()) if entry.limit and entry.limit <= #ply\DPP2GetAllEntsByClass(classname) hook.Run('DPP_SpawnLimitHit', ply, ent) DPP2.NotifyError(ply, 5, 'message.dpp2.limit.spawn', classname) DPP2.LogSpawn('message.dpp2.log.spawn.tried_generic', ply, color_red, DPP2.textcolor, ent) SafeRemoveEntity(ent) return false fixme = false i = 1 info = debug.getinfo(i) while info for fix in *DPP2.FIXME_HookSpawns if string.find(info.src or info.short_src, fix) fixme = true break i += 1 info = debug.getinfo(i) if not fixme return if not advancedCheck and not DPP2.QueueAntispam(ply, ent) if not advancedCheck and DPP2.ENABLE_ANTISPAM\GetBool() and DPP2.ANTISPAM_COLLISIONS\GetBool() and ent\GetSolid() ~= SOLID_NONE -- TODO: Point position calculation near plane, for accurate results -- using OBBMins and OBBMaxs timer.Simple 0, -> return if not IsValid(ply) or not IsValid(ent) mins, maxs = ent\WorldSpaceAABB() if mins and maxs and mins ~= vector_origin and maxs ~= vector_origin for ent2 in *ents.FindInBox(mins, maxs) if ent2 ~= ent and not ent2\IsPlayer() and not ent2\IsNPC() and (not ent2\IsWeapon() or not ent2\GetOwner()\IsValid()) and ent2\GetSolid() ~= SOLID_NONE ent\DPP2Ghost() DPP2.NotifyHint(ply, 5, 'message.dpp2.warn.collisions') break else return if not DPP2.AntispamCheck(ply, true, ent, nil, true) ent.__dpp2_dupe_fix = engine.TickCount() + 5 if DPP2.ENABLE_ANTISPAM_ALTERNATIVE_DUPE\GetBool() if DPP2.ENABLE_ANTIPROPKILL\GetBool() and DPP2.ANTIPROPKILL_TRAP\GetBool() and ent\GetSolid() ~= SOLID_NONE timer.Simple 0, -> DPP2.APKTriggerPhysgunDrop(ply, ent) if IsValid(ply) and IsValid(ent) ent\DPP2SetOwner(ply) eclass = ent\GetClass() if DPP2.NO_ROPE_WORLD\GetBool() and eclass == 'keyframe_rope' start, endpoint = ent\GetInternalVariable('m_hStartPoint'), ent\GetInternalVariable('m_hEndPoint') if start == endpoint and not IsValid(start) ent\Remove() DPP2.LogSpawn('message.dpp2.log.spawn.tried_plain', ply, color_red, DPP2.textcolor, 'keyframe_rope') return false if not eclass or not table.qhasValue(log_blacklist, eclass) if not eclass or not eclass\startsWith('prop_') DPP2.LogSpawn('message.dpp2.log.spawn.generic', ply, ent) else DPP2.LogSpawn('message.dpp2.log.spawn.prop', ply, ent, ent\GetModel() or '<unknown>') hook.Run('DPP_PlayerSpawn', ply, ent) return true PreventModelSpawn = (ply, model = ent and ent\GetModel() or 'wtf', ent = NULL, nonotify = false) -> if ply\DPP2IsBanned() value = ply\DPP2BanTimeLeft() if value == math.huge DPP2.NotifyError(ply, nil, 'message.dpp2.spawn.banned') else DPP2.NotifyError(ply, nil, 'message.dpp2.spawn.banned_for', DLib.I18n.FormatTimeForPlayer(ply, value\ceil())) SafeRemoveEntity(ent) return false model = model\lower() if DPP2.IsModelBlacklisted(IsValid(ent) and ent or model, ply) DPP2.NotifyError(ply, nil, 'message.dpp2.blacklist.model_blocked', model) if not nonotify SafeRemoveEntity(ent) return false if DPP2.IsModelRestricted(IsValid(ent) and ent or model, ply) DPP2.NotifyError(ply, nil, 'message.dpp2.blacklist.model_restricted', model) if not nonotify SafeRemoveEntity(ent) return false if DPP2.PerModelLimits.IS_INCLUSIVE\GetBool() check = false if entry = DPP2.PerModelLimits\Get(model, ply\GetUserGroup()) if entry.limit count = 0 for ent2 in *ply\DPP2GetAllEnts() if ent2\GetModel() == model count += 1 break if entry.limit < count check = entry.limit >= count if not check hook.Run('DPP_ModelLimitHit', ply, model, ent) DPP2.NotifyError(ply, 5, 'message.dpp2.limit.spawn', model) if not nonotify DPP2.LogSpawn('message.dpp2.log.spawn.tried_generic', ply, color_red, DPP2.textcolor, ent) if IsValid(ent) SafeRemoveEntity(ent) return false else if entry = DPP2.PerModelLimits\Get(model, ply\GetUserGroup()) if entry.limit count = 0 for ent2 in *ply\DPP2GetAllEnts() if ent2\GetModel() == model count += 1 break if entry.limit < count if entry.limit < count hook.Run('DPP_ModelLimitHit', ply, model, ent) DPP2.NotifyError(ply, 5, 'message.dpp2.limit.spawn', model) if not nonotify DPP2.LogSpawn('message.dpp2.log.spawn.tried_generic', ply, color_red, DPP2.textcolor, ent) if IsValid(ent) SafeRemoveEntity(ent) return false if DPP2.ENABLE_ANTISPAM\GetBool() and IsValid(ent) hit = false if DPP2.AUTO_BLACKLIST_BY_SIZE\GetBool() volume1 = DPP2.AUTO_BLACKLIST_SIZE\GetFloat() volume2 = 0 phys = ent\GetPhysicsObject() volume2 = phys\GetVolume() if IsValid(phys) if volume1 <= volume2 and not DPP2.ModelBlacklist\Has(model) DPP2.ModelBlacklist\Add(model) DPP2.Notify(true, nil, 'message.dpp2.autoblacklist.added_volume', model) hit = true if not DPP2.ModelBlacklist\Ask(model, ply) DPP2.NotifyError(ply, nil, 'message.dpp2.blacklist.model_blocked', model) if not nonotify SafeRemoveEntity(ent) return false if DPP2.AUTO_BLACKLIST_BY_AABB\GetBool() and not hit volume1 = DPP2.AUTO_BLACKLIST_AABB_SIZE\GetFloat() volume2 = DPP2._ComputeVolume2(ent) if volume1 <= volume2 and not DPP2.ModelBlacklist\Has(model) DPP2.ModelBlacklist\Add(model) DPP2.Notify(true, nil, 'message.dpp2.autoblacklist.added_aabb', model) if not DPP2.ModelBlacklist\Ask(model, ply) DPP2.NotifyError(ply, nil, 'message.dpp2.blacklist.model_blocked', model) if not nonotify SafeRemoveEntity(ent) return false return true PlayerSpawnedEffect = (ply = NULL, model = 'models/error.mdl', ent = NULL) -> return unless ply\IsValid() return unless ent\IsValid() DPP2.PlayerSpawnedSomething(ply, ent) return false if not PreventModelSpawn(ply, model, ent) PlayerSpawnedProp = (ply = NULL, model = 'models/error.mdl', ent = NULL) -> return unless ply\IsValid() return unless ent\IsValid() return false if not PreventModelSpawn(ply, model, ent) DPP2.PlayerSpawnedSomething(ply, ent) return PlayerSpawnedRagdoll = (ply = NULL, model = 'models/error.mdl', ent = NULL) -> return unless ply\IsValid() return unless ent\IsValid() return false if not PreventModelSpawn(ply, model, ent) DPP2.PlayerSpawnedSomething(ply, ent) return PlayerSpawnedNPC = (ply = NULL, ent = NULL) -> return unless ply\IsValid() return unless ent\IsValid() return false if not PreventModelSpawn(ply, model, ent) DPP2.PlayerSpawnedSomething(ply, ent) return PlayerSpawnedSENT = (ply = NULL, ent = NULL) -> return unless ply\IsValid() return unless ent\IsValid() return false if not PreventModelSpawn(ply, model, ent) DPP2.PlayerSpawnedSomething(ply, ent) return PlayerSpawnedSWEP = (ply = NULL, ent = NULL) -> return unless ply\IsValid() return unless ent\IsValid() return false if not PreventModelSpawn(ply, model, ent) DPP2.PlayerSpawnedSomething(ply, ent) return PlayerSpawnedVehicle = (ply = NULL, ent = NULL) -> return unless ply\IsValid() return unless ent\IsValid() return false if not PreventModelSpawn(ply, model, ent) DPP2.PlayerSpawnedSomething(ply, ent) return PlayerSpawnEffect = (ply = NULL, model = 'models/error.mdl') -> return unless ply\IsValid() return false if not PreventModelSpawn(ply, model) return false if not DPP2.AntispamCheck(ply) if not DPP2.SpawnRestrictions\Ask('prop_effect', ply) DPP2.LogSpawn('message.dpp2.log.spawn.tried_plain', ply, color_red, DPP2.textcolor, 'prop_effect') return false PlayerSpawnProp = (ply = NULL, model = 'models/error.mdl') -> return unless ply\IsValid() return false if not PreventModelSpawn(ply, model) return false if not DPP2.AntispamCheck(ply) if not DPP2.SpawnRestrictions\Ask('prop_physics', ply) DPP2.LogSpawn('message.dpp2.log.spawn.tried_plain', ply, color_red, DPP2.textcolor, 'prop_physics') return false PlayerSpawnRagdoll = (ply = NULL, model = 'models/error.mdl') -> return unless ply\IsValid() return false if not PreventModelSpawn(ply, model) return false if not DPP2.AntispamCheck(ply) if not DPP2.SpawnRestrictions\Ask('prop_ragdoll', ply) DPP2.LogSpawn('message.dpp2.log.spawn.tried_plain', ply, color_red, DPP2.textcolor, 'prop_ragdoll') return false PlayerSpawnObject = (ply = NULL, model = 'models/error.mdl', skin = 0) -> return unless ply\IsValid() return false if not PreventModelSpawn(ply, model) return false if not DPP2.AntispamCheck(ply) PlayerSpawnVehicle = (ply = NULL, model = 'models/error.mdl', name = 'prop_vehicle_jeep', info = {}) -> return unless ply\IsValid() return false if not PreventModelSpawn(ply, model) return false if not DPP2.AntispamCheck(ply) if not DPP2.SpawnRestrictions\Ask(name, ply) DPP2.LogSpawn('message.dpp2.log.spawn.tried_plain', ply, color_red, DPP2.textcolor, name) return false PlayerSpawnNPC = (ply = NULL, npcclassname = 'base_entity', weaponclass = 'base_entity') -> return unless ply\IsValid() return false if not DPP2.AntispamCheck(ply) if not DPP2.SpawnRestrictions\Ask(npcclassname, ply) DPP2.LogSpawn('message.dpp2.log.spawn.tried_plain', ply, color_red, DPP2.textcolor, npcclassname) return false PlayerSpawnSENT = (ply = NULL, classname = 'base_entity') -> return unless ply\IsValid() return false if not DPP2.AntispamCheck(ply) if not DPP2.SpawnRestrictions\Ask(classname, ply) DPP2.LogSpawn('message.dpp2.log.spawn.tried_plain', ply, color_red, DPP2.textcolor, classname) return false PlayerGiveSWEP = (ply = NULL, classname = 'base_entity', definition = {ClassName: 'base_entity', WorldModel: 'models/error.mdl', ViewModel: 'models/error.mdl'}) -> return unless ply\IsValid() return false if not PreventModelSpawn(ply, definition.WorldModel) return false if not DPP2.AntispamCheck(ply) if not DPP2.SpawnRestrictions\Ask(classname, ply) DPP2.LogSpawn('message.dpp2.log.spawn.tried_plain', ply, color_red, DPP2.textcolor, classname) return false if not IsValid(ply\GetWeapon(classname)) timer.Simple 0, -> return if not IsValid(ply) wep = ply\GetWeapon(classname) if IsValid(wep) if DPP2.PlayerSpawnedSomething(ply, wep) DPP2.LogSpawn('message.dpp2.log.spawn.giveswep_valid', ply, wep) else DPP2.LogSpawn('message.dpp2.log.spawn.giveswep', ply, color_white, classname) return PlayerSpawnSWEP = (ply = NULL, classname = 'base_entity', definition = {ClassName: 'base_entity', WorldModel: 'models/error.mdl', ViewModel: 'models/error.mdl'}) -> return unless ply\IsValid() return false if not PreventModelSpawn(ply, definition.WorldModel) return false if not DPP2.AntispamCheck(ply) if not DPP2.SpawnRestrictions\Ask(classname, ply) DPP2.LogSpawn('message.dpp2.log.spawn.tried_plain', ply, color_red, DPP2.textcolor, classname) return false PlayerCanPickupItem = (ply = NULL, ent = NULL) -> return if not IsValid(ply) or not IsValid(ent) return false if not DPP2.PickupProtection.Blacklist\Ask(ent\GetClass(), ply) return false if not DPP2.PickupProtection.RestrictionList\Ask(ent\GetClass(), ply) hooksToReg = { :PlayerSpawnedEffect, :PlayerSpawnedProp, :PlayerSpawnedRagdoll :PlayerSpawnedNPC, :PlayerSpawnedSENT, :PlayerSpawnedSWEP :PlayerSpawnedVehicle, :PlayerSpawnEffect, :PlayerSpawnProp :PlayerSpawnRagdoll, :PlayerSpawnObject, :PlayerSpawnVehicle :PlayerSpawnNPC, :PlayerSpawnSENT, :PlayerGiveSWEP, :PlayerSpawnSWEP :PlayerCanPickupItem, PlayerCanPickupWeapon: PlayerCanPickupItem } hook.Add(name, 'DPP2.SpawnHooks', func, -4) for name, func in pairs(hooksToReg) import CurTimeL, table, type from _G CheckEntities = {} DPP2._Spawn_CheckFrame = 0 DPP2.HookedEntityCreation = => table.qhasValue(CheckEntities, @) or @__dpp2_spawn_frame == CurTimeL() local DiveTableCheck local DiveEntityCheck DiveTableCheck = (tab, owner, checkedEnts, checkedTables, found) => return if checkedTables[tab] checkedTables[tab] = true for key, value in pairs(tab) vtype = type(value) if vtype == 'table' and (type(key) ~= 'string' or not key\startsWith('__dpp2')) DiveTableCheck(@, value, owner, checkedEnts, checkedTables, found) elseif vtype == 'Entity' or vtype == 'NPC' or vtype == 'NextBot' or vtype == 'Vehicle' or vtype == 'Weapon' DiveEntityCheck(value, owner, checkedEnts, checkedTables, found) DiveEntityCheck = (owner, checkedEnts, checkedTables, found) => return found if checkedEnts[@] return found if @__dpp2_check_frame == CurTimeL() return found if not @GetTable() checkedEnts[@] = true @__dpp2_check_frame = CurTimeL() table.insert(found, @) if @DPP2GetOwner() ~= owner and @__dpp2_spawn_frame == CurTimeL() DiveTableCheck(@, @GetTable(), owner, checkedEnts, checkedTables, found) DiveTableCheck(@, @GetSaveTable(), owner, checkedEnts, checkedTables, found) return found hook.Add 'Think', 'DPP2.CheckEntitiesOwnage', -> return if DPP2._Spawn_CheckFrame >= CurTimeL() return if #CheckEntities == 0 copy = CheckEntities checkConstraints = {} CheckEntities = {} ctime = CurTimeL() for ent in *copy if ent\IsValid() ent.__dpp2_spawn_frame = ctime while #copy ~= 0 ent = table.remove(copy, 1) if ent\IsValid() if ent\IsConstraint() table.insert(checkConstraints, ent) elseif ent\DPP2OwnerIsValid() ply = ent\DPP2GetOwner() found = DiveEntityCheck(ent, ply, {}, {}, {}) if #found ~= 0 DPP2.UnqueueAntispam(ent) local toremove for ent2 in *found DPP2.UnqueueAntispam(ent2) DPP2.PlayerSpawnedSomething(ply, ent2, true) for i, ent3 in ipairs(copy) if ent2 == ent3 toremove = toremove or {} table.insert(toremove, i) break table.removeValues(copy, toremove) if toremove fail = not PreventModelSpawn(ply, nil, ent, true) if not fail for ent2 in *found fail = not PreventModelSpawn(ply, nil, ent2, true) break if fail if not fail should_queue = not ent.__dpp2_dupe_fix or engine.TickCount() >= ent.__dpp2_dupe_fix if should_queue for ent2 in *found if ent.__dpp2_dupe_fix and engine.TickCount() < ent.__dpp2_dupe_fix should_queue = false break DPP2.QueueAntispam(ply, ent, found) if should_queue else SafeRemoveEntity(ent) SafeRemoveEntity(ent2) for ent2 in *found DPP2.NotifyError(ply, nil, 'message.dpp2.blacklist.models_blocked', #found + 1) for constraint in *checkConstraints ent1, ent2 = constraint\GetConstrainedEntities() if IsValid(ent1) and IsValid(ent2) if ctime == ent1.__dpp2_spawn_frame and ctime == ent2.__dpp2_spawn_frame if ent1\DPP2IsOwned() and ent1\DPP2OwnerIsValid() DPP2.PlayerSpawnedSomething(ent1\DPP2GetOwner(), constraint, true) elseif ent2\DPP2IsOwned() and ent2\DPP2OwnerIsValid() DPP2.PlayerSpawnedSomething(ent2\DPP2GetOwner(), constraint, true) else DPP2.LMessageError('message.dpp2.error.empty_constraint', ' ', constraint, ' ', ent1, ' ', ent2) hook.Add 'OnEntityCreated', 'DPP2.CheckEntitiesOwnage', => DPP2._Spawn_CheckFrame = CurTimeL() table.insert(CheckEntities, @) return hook.Add 'OnEntityCopyTableFinish', 'DPP2.ClearFields', (data) => data.__dpp2_check_frame = nil data.__dpp2_hit = nil data.__dpp2_spawn_frame = nil data.__dpp2_contraption = nil data._dpp2_last_nick = nil data.__dpp2_pushing = nil data.__dpp2_unfreeze = nil data.__dpp2_old_collisions_group = nil data.__dpp2_old_movetype = nil data.__dpp2_old_color = nil data.__dpp2_ghost_callbacks = nil data.__dpp2_old_rendermode = nil
35.829365
164
0.736793
a954c1a9ceadfd2e452c8d2914136f00991e2a62
354
local * package.path = "?.lua;?/init.lua;#{package.path}" sss = assert require "sss" s = with sss.socket! \reuseaddr! \bind host: "*" port: 32000 \listen! while true c, addr = s\accept! addr = sss.toladdress addr got = c\receive! print "got #{got} from #{addr.host}:#{addr.port}" c\send got c\close!
18.631579
53
0.564972
8a6faa76b155a5b2e2a5180a32a5de0fab19a9d7
15,320
-- Copyright 2014-2015 The Howl Developers -- License: MIT (see LICENSE.md at the top-level directory of the distribution) ffi = require 'ffi' require 'ljglibs.cdefs.glib' require 'ljglibs.cdefs.cairo' ffi.cdef [[ /* PangoFontDescription */ typedef struct {} PangoFontDescription; PangoFontDescription * pango_font_description_new (void); void pango_font_description_free (PangoFontDescription *desc); void pango_font_description_set_family (PangoFontDescription *desc, const char *family); const char * pango_font_description_get_family (const PangoFontDescription *desc); void pango_font_description_set_size (PangoFontDescription *desc, gint size); gint pango_font_description_get_size (const PangoFontDescription *desc); void pango_font_description_set_absolute_size (PangoFontDescription *desc, double size); gboolean pango_font_description_get_size_is_absolute (const PangoFontDescription *desc); PangoFontDescription * pango_font_description_from_string (const char *str); char * pango_font_description_to_string (const PangoFontDescription *desc); /* PangoTabArray */ typedef enum { PANGO_TAB_LEFT } PangoTabAlign; typedef struct {} PangoTabArray; PangoTabArray * pango_tab_array_new (gint initial_size, gboolean positions_in_pixels); PangoTabArray * pango_tab_array_new_with_positions (gint size, gboolean positions_in_pixels, PangoTabAlign first_alignment, gint first_position, ...); void pango_tab_array_free (PangoTabArray *tab_array); gint pango_tab_array_get_size (PangoTabArray *tab_array); void pango_tab_array_set_tab (PangoTabArray *tab_array, gint tab_index, PangoTabAlign alignment, gint location); void pango_tab_array_get_tab (PangoTabArray *tab_array, gint tab_index, PangoTabAlign *alignment, gint *location); gboolean pango_tab_array_get_positions_in_pixels (PangoTabArray *tab_array); /* PangoContext */ typedef struct {} PangoContext; PangoFontDescription * pango_context_get_font_description (PangoContext *context); void pango_context_set_font_description (PangoContext *context, const PangoFontDescription *desc); typedef struct { int x; int y; int width; int height; } PangoRectangle; typedef enum { PANGO_ALIGN_LEFT, PANGO_ALIGN_CENTER, PANGO_ALIGN_RIGHT } PangoAlignment; typedef enum { PANGO_ELLIPSIZE_NONE, PANGO_ELLIPSIZE_START, PANGO_ELLIPSIZE_MIDDLE, PANGO_ELLIPSIZE_END } PangoEllipsizeMode; /* PangoColor */ typedef struct { guint16 red; guint16 green; guint16 blue; } PangoColor; gboolean pango_color_parse (PangoColor *color, const char *spec); gchar * pango_color_to_string (const PangoColor *color); /* Attributes */ typedef enum { PANGO_ATTR_INDEX_FROM_TEXT_BEGINNING = 0, PANGO_ATTR_INDEX_TO_TEXT_END = 4294967295 // fix me } PangoAttributeConstants; typedef enum { PANGO_ATTR_INVALID, /* 0 is an invalid attribute type */ PANGO_ATTR_LANGUAGE, /* PangoAttrLanguage */ PANGO_ATTR_FAMILY, /* PangoAttrString */ PANGO_ATTR_STYLE, /* PangoAttrInt */ PANGO_ATTR_WEIGHT, /* PangoAttrInt */ PANGO_ATTR_VARIANT, /* PangoAttrInt */ PANGO_ATTR_STRETCH, /* PangoAttrInt */ PANGO_ATTR_SIZE, /* PangoAttrSize */ PANGO_ATTR_FONT_DESC, /* PangoAttrFontDesc */ PANGO_ATTR_FOREGROUND, /* PangoAttrColor */ PANGO_ATTR_BACKGROUND, /* PangoAttrColor */ PANGO_ATTR_UNDERLINE, /* PangoAttrInt */ PANGO_ATTR_STRIKETHROUGH, /* PangoAttrInt */ PANGO_ATTR_RISE, /* PangoAttrInt */ PANGO_ATTR_SHAPE, /* PangoAttrShape */ PANGO_ATTR_SCALE, /* PangoAttrFloat */ PANGO_ATTR_FALLBACK, /* PangoAttrInt */ PANGO_ATTR_LETTER_SPACING, /* PangoAttrInt */ PANGO_ATTR_UNDERLINE_COLOR, /* PangoAttrColor */ PANGO_ATTR_STRIKETHROUGH_COLOR,/* PangoAttrColor */ PANGO_ATTR_ABSOLUTE_SIZE, /* PangoAttrSize */ PANGO_ATTR_GRAVITY, /* PangoAttrInt */ PANGO_ATTR_GRAVITY_HINT /* PangoAttrInt */ } PangoAttrType; typedef enum { PANGO_STYLE_NORMAL, PANGO_STYLE_OBLIQUE, PANGO_STYLE_ITALIC } PangoStyle; typedef enum { PANGO_VARIANT_NORMAL, PANGO_VARIANT_SMALL_CAPS } PangoVariant; typedef enum { PANGO_WEIGHT_THIN = 100, PANGO_WEIGHT_ULTRALIGHT = 200, PANGO_WEIGHT_LIGHT = 300, PANGO_WEIGHT_BOOK = 380, PANGO_WEIGHT_NORMAL = 400, PANGO_WEIGHT_MEDIUM = 500, PANGO_WEIGHT_SEMIBOLD = 600, PANGO_WEIGHT_BOLD = 700, PANGO_WEIGHT_ULTRABOLD = 800, PANGO_WEIGHT_HEAVY = 900, PANGO_WEIGHT_ULTRAHEAVY = 1000 } PangoWeight; typedef enum { PANGO_STRETCH_ULTRA_CONDENSED, PANGO_STRETCH_EXTRA_CONDENSED, PANGO_STRETCH_CONDENSED, PANGO_STRETCH_SEMI_CONDENSED, PANGO_STRETCH_NORMAL, PANGO_STRETCH_SEMI_EXPANDED, PANGO_STRETCH_EXPANDED, PANGO_STRETCH_EXTRA_EXPANDED, PANGO_STRETCH_ULTRA_EXPANDED } PangoStretch; typedef enum { PANGO_FONT_MASK_FAMILY = 1 << 0, PANGO_FONT_MASK_STYLE = 1 << 1, PANGO_FONT_MASK_VARIANT = 1 << 2, PANGO_FONT_MASK_WEIGHT = 1 << 3, PANGO_FONT_MASK_STRETCH = 1 << 4, PANGO_FONT_MASK_SIZE = 1 << 5, PANGO_FONT_MASK_GRAVITY = 1 << 6 } PangoFontMask; typedef enum { PANGO_UNDERLINE_NONE, PANGO_UNDERLINE_SINGLE, PANGO_UNDERLINE_DOUBLE, PANGO_UNDERLINE_LOW, PANGO_UNDERLINE_ERROR } PangoUnderline; typedef enum { PANGO_GRAVITY_SOUTH, PANGO_GRAVITY_EAST, PANGO_GRAVITY_NORTH, PANGO_GRAVITY_WEST, PANGO_GRAVITY_AUTO } PangoGravity; typedef enum { PANGO_GRAVITY_HINT_NATURAL, PANGO_GRAVITY_HINT_STRONG, PANGO_GRAVITY_HINT_LINE } PangoGravityHint; typedef struct {} _PangoAttribute; typedef struct { PangoAttrType type; _PangoAttribute * (*copy) (const _PangoAttribute *attr); void (*destroy) (_PangoAttribute *attr); gboolean (*equal) (const _PangoAttribute *attr1, const _PangoAttribute *attr2); } PangoAttrClass; typedef struct { const PangoAttrClass *klass; guint start_index; /* in bytes */ guint end_index; /* in bytes. The character at this index is not included */ } PangoAttribute; typedef struct { PangoAttribute attr; char *value; } PangoAttrString; typedef struct { PangoAttribute attr; int value; } PangoAttrInt; typedef struct { PangoAttribute attr; double value; } PangoAttrFloat; typedef struct { PangoAttribute attr; int size; guint absolute : 1; } PangoAttrSize; typedef struct { PangoAttribute attr; PangoColor color; } PangoAttrColor; typedef struct { PangoAttrColor color; } PangoAttributeForeground; typedef struct { PangoAttribute attr; PangoFontDescription *desc; } PangoAttrFontDesc; void pango_attribute_destroy (PangoAttribute *attr); PangoAttribute * pango_attribute_copy (const PangoAttribute *attr); PangoAttrColor * pango_attr_foreground_new (guint16 red, guint16 green, guint16 blue); PangoAttrColor * pango_attr_background_new (guint16 red, guint16 green, guint16 blue); PangoAttrString * pango_attr_family_new (const char *family); PangoAttrInt * pango_attr_style_new (PangoStyle style); PangoAttrInt * pango_attr_variant_new (PangoVariant variant); PangoAttrInt * pango_attr_stretch_new (PangoStretch stretch); PangoAttrInt * pango_attr_weight_new (PangoWeight weight); PangoAttrInt * pango_attr_size_new (int size); PangoAttrInt * pango_attr_size_new_absolute (int size); PangoAttribute * pango_attr_font_desc_new (const PangoFontDescription *desc); PangoAttrInt * pango_attr_strikethrough_new (gboolean strikethrough); PangoAttrColor * pango_attr_strikethrough_color_new (guint16 red, guint16 green, guint16 blue); PangoAttrInt * pango_attr_underline_new (PangoUnderline underline); PangoAttrColor *pango_attr_underline_color_new (guint16 red, guint16 green, guint16 blue); PangoAttrInt * pango_attr_rise_new (int rise); PangoAttrFloat * pango_attr_scale_new (double scale_factor); PangoAttrInt * pango_attr_fallback_new (gboolean enable_fallback); PangoAttrInt * pango_attr_letter_spacing_new (int letter_spacing); PangoAttribute * pango_attr_shape_new (const PangoRectangle *ink_rect, const PangoRectangle *logical_rect); PangoAttrInt * pango_attr_gravity_new (PangoGravity gravity); PangoAttrInt * pango_attr_gravity_hint_new (PangoGravityHint hint); typedef struct {} PangoAttrList; PangoAttrList * pango_attr_list_new (void); void pango_attr_list_unref (PangoAttrList *list); void pango_attr_list_insert (PangoAttrList *list, PangoAttribute *attr); void pango_attr_list_insert_before (PangoAttrList *list, PangoAttribute *attr); void pango_attr_list_change (PangoAttrList *list, PangoAttribute *attr); typedef struct {} PangoAttrIterator; PangoAttrIterator * pango_attr_list_get_iterator (PangoAttrList *list); void pango_attr_iterator_destroy (PangoAttrIterator *iterator); gboolean pango_attr_iterator_next (PangoAttrIterator *iterator); void pango_attr_iterator_range (PangoAttrIterator *iterator, gint *start, gint *end); PangoAttribute * pango_attr_iterator_get (PangoAttrIterator *iterator, PangoAttrType type); /* PangoLayout */ typedef enum { PANGO_WRAP_WORD, PANGO_WRAP_CHAR, PANGO_WRAP_WORD_CHAR } PangoWrapMode; typedef struct {} PangoLayout; typedef struct { PangoLayout *layout; gint start_index; /* start of line as byte index into layout->text */ gint length; /* length of line in bytes */ void *runs; //GSList *runs; guint is_paragraph_start : 1; /* TRUE if this is the first line of the paragraph */ guint resolved_dir : 3; /* Resolved PangoDirection of line */ } PangoLayoutLine; typedef struct {} PangoLayoutIter; PangoLayout * pango_layout_new (PangoContext *context); void pango_layout_set_text (PangoLayout *layout, const char *text, int length); const char *pango_layout_get_text (PangoLayout *layout); void pango_layout_get_pixel_size (PangoLayout *layout, int *width, int *height); void pango_layout_set_alignment (PangoLayout *layout, PangoAlignment alignment); PangoAlignment pango_layout_get_alignment (PangoLayout *layout); void pango_layout_set_width (PangoLayout *layout, int width); int pango_layout_get_width (PangoLayout *layout); void pango_layout_set_height (PangoLayout *layout, int height); int pango_layout_get_height (PangoLayout *layout); void pango_layout_set_spacing (PangoLayout *layout, int spacing); int pango_layout_get_spacing (PangoLayout *layout); void pango_layout_set_attributes (PangoLayout *layout, PangoAttrList *attrs); PangoAttrList * pango_layout_get_attributes (PangoLayout *layout); void pango_layout_set_font_description (PangoLayout *layout, const PangoFontDescription *desc); const PangoFontDescription * pango_layout_get_font_description (PangoLayout *layout); int pango_layout_get_baseline (PangoLayout *layout); gboolean pango_layout_is_wrapped (PangoLayout *layout); PangoWrapMode pango_layout_get_wrap (PangoLayout *layout); void pango_layout_set_wrap (PangoLayout *layout, PangoWrapMode wrap); void pango_layout_index_to_pos (PangoLayout *layout, int index, PangoRectangle *pos); int pango_layout_get_line_count (PangoLayout *layout); void pango_layout_set_indent (PangoLayout *layout, int indent); int pango_layout_get_indent (PangoLayout *layout); gboolean pango_layout_xy_to_index (PangoLayout *layout, int x, int y, int *index_, int *trailing); void pango_layout_index_to_line_x (PangoLayout *layout, int index_, gboolean trailing, int *line, int *x_pos); void pango_layout_move_cursor_visually (PangoLayout *layout, gboolean strong, int old_index, int old_trailing, int direction, int *new_index, int *new_trailing); /* PangoLayoutLine */ PangoLayoutLine * pango_layout_line_ref (PangoLayoutLine *line); void pango_layout_line_unref (PangoLayoutLine *line); PangoLayoutLine * pango_layout_get_line (PangoLayout *layout, int line); PangoLayoutLine * pango_layout_get_line_readonly (PangoLayout *layout, int line); void pango_layout_line_get_pixel_extents (PangoLayoutLine *layout_line, PangoRectangle *ink_rect, PangoRectangle *logical_rect); void pango_layout_line_index_to_x (PangoLayoutLine *line, int index_, gboolean trailing, int *x_pos); gboolean pango_layout_line_x_to_index (PangoLayoutLine *line, int x_pos, int *index_, int *trailing); /* PangoLayoutIter */ PangoLayoutIter * pango_layout_get_iter (PangoLayout *layout); void pango_layout_iter_free (PangoLayoutIter *iter); gboolean pango_layout_iter_next_line (PangoLayoutIter *iter); gboolean pango_layout_iter_at_last_line (PangoLayoutIter *iter); int pango_layout_iter_get_baseline (PangoLayoutIter *iter); PangoLayoutLine * pango_layout_iter_get_line (PangoLayoutIter *iter); PangoLayoutLine * pango_layout_iter_get_line_readonly (PangoLayoutIter *iter); void pango_layout_iter_get_line_yrange (PangoLayoutIter *iter, int *y0_, int *y1_); void pango_layout_set_tabs (PangoLayout *layout, PangoTabArray *tabs); PangoTabArray * pango_layout_get_tabs (PangoLayout *layout); /* PangoCairo */ PangoContext * pango_cairo_create_context (cairo_t *cr); PangoLayout * pango_cairo_create_layout (cairo_t *cr); void pango_cairo_show_layout (cairo_t *cr, PangoLayout *layout); ]]
38.492462
100
0.670953
437d7a9ac9bcdcc2f4a679d0777fda5520c09111
462
-- Copyright 2016 The Howl Developers -- License: MIT (see LICENSE.md at the top-level directory of the distribution) mode_reg = name: 'tao' aliases: 'tao' extensions: 'tao' create: -> bundle_load('tao_mode') parent: 'curly_mode' howl.mode.register mode_reg unload = -> howl.mode.unregister 'tao' return { info: author: 'Joshua Barretto <[email protected]>', description: 'Tao language support', license: 'MIT', :unload }
21
79
0.690476
39fc9e1298c50253eb5e07c3e1b9cf7574eaec06
4,454
-- Copyright (C) 2017-2020 DBotThePony -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -- of the Software, and to permit persons to whom the Software is furnished to do so, -- subject to the following conditions: -- The above copyright notice and this permission notice shall be included in all copies -- or substantial portions of the Software. -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, -- INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR -- PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE -- FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -- OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -- DEALINGS IN THE SOFTWARE. class DLib.Freespace new: (posStart = Vector(0, 0, 0), step = 25, radius = 10) => @pos = posStart @mins = Vector(-4, -4, -4) @maxs = Vector(4, 4, 4) @step = step @radius = radius @addition = Vector(0, 0, 0) @usehull = true @filter = DLib.Set() @mask = MASK_SOLID @maskReachable = MASK_SOLID @strict = false @smins = Vector(-16, -16, 0) @smaxs = Vector(16, 16, 0) @sheight = 70 GetMins: => @mins GetMaxs: => @maxs SetMins: (val) => @mins = val SetMaxs: (val) => @maxs = val GetPos: => @pos SetPos: (val) => @pos = val GetAddition: => @addition SetAddition: (val) => @addition = val GetStrict: => @strict GetStrictHeight: => @sheight SetStrict: (val) => @strict = val SetStrictHeight: (val) => @sheight = val GetAABB: => @mins, @maxs GetSAABB: => @smins, @smaxs SetAABB: (val1, val2) => @mins, @maxs = val1, val2 SetSAABB: (val1, val2) => @smins, @smaxs = val1, val2 GetMask: => @mask SetMask: (val) => @mask = val GetMaskReachable: => @maskReachable SetMaskReachable: (val) => @maskReachable = val GetStep: => @step GetRadius: => @radius SetStep: (val) => @step = val SetRadius: (val) => @radius = val check: (target) => if @usehull tr = util.TraceHull({ start: @pos endpos: target + @addition mins: @mins maxs: @maxs mask: @maskReachable filter: @filter\getValues() }) if @strict and not tr.Hit tr2 = util.TraceHull({ start: target + @addition endpos: target + @addition + Vector(0, 0, @sheight) mins: @smins maxs: @smaxs mask: @mask filter: @filter\getValues() }) return not tr2.Hit, tr, tr2 return not tr.Hit, tr else tr = util.TraceLine({ start: @pos endpos: target + @addition mask: @maskReachable filter: @filter\getValues() }) if @strict and not tr.Hit tr2 = util.TraceHull({ start: target + @addition endpos: target + @addition + Vector(0, 0, @sheight) mins: @smins maxs: @smaxs mask: @mask filter: @filter\getValues() }) return not tr2.Hit, tr, tr2 return not tr.Hit, tr Search: => if @check(@pos) return @pos for radius = 1, @radius for x = -radius, radius pos = @pos + Vector(x * @step, radius * @step, 0) return pos if @check(pos) pos = @pos + Vector(x * @step, -radius * @step, 0) return pos if @check(pos) for y = -radius, radius pos = @pos + Vector(radius * @step, y * @step, 0) return pos if @check(pos) pos = @pos + Vector(-radius * @step, y * @step, 0) return pos if @check(pos) return false SearchOptimal: => validPositions = @SearchAll() return false if #validPositions == 0 table.sort validPositions, (a, b) -> a\DistToSqr(@pos) < b\DistToSqr(@pos) return validPositions[1] SearchAll: => output = {} table.insert(output, @pos) if @check(@pos) for radius = 1, @radius for x = -radius, radius pos = @pos + Vector(x * @step, radius * @step, 0) table.insert(output, pos) if @check(pos) pos = @pos + Vector(x * @step, -radius * @step, 0) table.insert(output, pos) if @check(pos) for y = -radius, radius pos = @pos + Vector(radius * @step, y * @step, 0) table.insert(output, pos) if @check(pos) pos = @pos + Vector(-radius * @step, y * @step, 0) table.insert(output, pos) if @check(pos) return output
28.369427
92
0.63965
35815cae9c825a44da071e67bdba848bcfeb0cbf
2,351
import map, deepcpy from require'opeth.common.utils' Debuginfo = require'opeth.opeth.cmd.debuginfo' print_moddiffgen = (optfn, optname) -> (fnblock) -> fnblock.optdebug\start_rec! optfn fnblock fnblock.optdebug\print_modified optname opt_names = { { name:"unreachable blocks removal" description: "remove all the blocks which are unreachable for the top" } { name: "constant fold" description: "evaluate some operations beforehand" } { name: "constant propagation" description: "replace `MOVE` instruction with the another" } { name:"dead-code elimination" description: "eliminate the instructions which aren't needed" } { name:"function inlining" description: "expand a funcion call with the function's instructions" } } unreachable_remove = print_moddiffgen require'opeth.opeth.unreachable_remove', opt_names[1].name cst_fold = print_moddiffgen require'opeth.opeth.cst_fold', opt_names[2].name cst_prop = print_moddiffgen require'opeth.opeth.cst_prop', opt_names[3].name dead_elim = print_moddiffgen require'opeth.opeth.dead_elim', opt_names[4].name func_inline = print_moddiffgen require'opeth.opeth.func_inline', opt_names[5].name unused_remove = print_moddiffgen require'opeth.opeth.unused_remove', "unused resources removal" opt_tbl = { unreachable_remove (=> func_inline @ if #@prototype > 0) cst_fold cst_prop dead_elim mask: (mask) => newtbl = deepcpy @ newtbl[i] = (=>) for i in *mask newtbl } optimizer = (fnblock, mask, verbose) -> unless fnblock.optdebug fnblock.optdebug = Debuginfo 0, 0, nil, verbose else fnblock.optdebug\reset_modified! map (=> @ fnblock), opt_tbl\mask mask for pi = 1, #fnblock.prototype debuginfo = Debuginfo fnblock.optdebug.level + 1, pi, fnblock.optdebug\fmt!, verbose fnblock.prototype[pi].optdebug = debuginfo optimizer fnblock.prototype[pi], mask, verbose optimizer fnblock, mask if fnblock.optdebug.modified > 0 recursive_clean = (fnblock, verbose) -> unused_remove fnblock for pi = 1, #fnblock.prototype debuginfo = Debuginfo fnblock.optdebug.level + 1, pi, fnblock.optdebug\fmt!, verbose fnblock.prototype[pi].optdebug = debuginfo recursive_clean fnblock.prototype[pi], verbose setmetatable {:opt_names}, __call: (fnblock, mask = {}, verbose) => optimizer fnblock, mask, verbose recursive_clean fnblock, verbose fnblock
29.759494
96
0.753722
57ddd904286e6b267b4073d592b8e97d0f1cd159
3,381
html = require "lapis.html" tag_classes = (tags) -> if tags and #tags > 0 table.concat(["tagged-" .. t for t in *tags], " ") else "tagged-none" class Materials extends html.Widget content: => if @nav @content_for "header", -> render "views.nav" if @footer @content_for "footer", -> render "views.footer" div { class: "parallax-heading", ["data-0"]: "background-position: 50% -30px", ["data-top-bottom"]: "background-position: 50% -150px" }, -> h1 @m.heading section id: "resource-filters", -> div id: "resource-filters-content", -> span id: "resource-filter-label", @m.filtering.label div class: "resource-filter-tags", -> for tag, c in pairs @m.tags a href: "#", class: "tag resource-filter-tag active", ["data-tag"]: tag, c.title a id: "resource-filter-reset", href: "#", @m.filtering['reset-button'] section class: "content-body", -> div class: "resources", -> for edition in *@m.content edition_tags = {} for section in *edition.sections for lecture in *section.lectures if not lecture.tags continue for tag in *lecture.tags edition_tags[tag] = true edition_class = tag_classes [t for t, _ in pairs edition_tags] h1 class: edition_class, edition.edition, -> div class: "edition-info-container", -> if edition.date span class: "edition-info edition-date", edition.date if edition.youtube a class: "edition-info edition-yt-link", href: edition.youtube, @m['yt-link-text'] for i, section in ipairs edition.sections h2 section.name ul -> for lecture in *section.lectures cls = tag_classes lecture.tags li class: cls, -> if lecture.url a href: lecture.url, lecture.title else span lecture.title if lecture.tags span class: "tags", -> for tag in *lecture.tags if @m.tags[tag] == nil print "Invalid tag: #{tag}" continue a href: "#", ['data-tag']: tag, class: "resource-tag tag", title: @m.tags[tag].title, @m.tags[tag].slug if lecture.resources for resource in *lecture.resources span " | " a href: resource.url, resource.name
45.689189
151
0.404614
d9a630c6771fee6b5fa453344db9f7862ea625ea
1,195
--------------------------------------------------------------------------- -- Environment ------------------------------------------------------------ --------------------------------------------------------------------------- import ipairs from _G { sigcheck:T } = require 'typecheck' import ieach, ieachr, merge from require 'fn.table' --------------------------------------------------------------------------- -- Implementation --------------------------------------------------------- --------------------------------------------------------------------------- self = _submods: nil init = (submods, options) -> for _, modname in ipairs submods mod = require 'watchers.' .. modname mod.init options[modname] @[modname] = mod @_submods = submods start = () -> ieach @_submods, (n) -> @[n].start! if @[n].start stop = () -> ieachr @_submods, (n) -> @[n].stop! if @[n].stop --------------------------------------------------------------------------- -- Interface -------------------------------------------------------------- --------------------------------------------------------------------------- merge self, { init: T 'table, table', init :start, :stop }
34.142857
75
0.291213
3ce1b4a36aa8d1d4c97b964ee130d3043cbbc6c5
573
{ order: 'cgstuedfm' kinds: { c: { group: 'neotags_ClassTag' }, g: { group: 'neotags_EnumTypeTag' }, u: { group: 'neotags_UnionTag' }, e: { group: 'neotags_EnumTag' }, s: { group: 'neotags_StructTag' }, m: { group: 'neotags_MemberTag', prefix: [[\%(\%(\>\|\]\|)\)\%(\.\|->\)\)\@5<=]], }, f: { group: 'neotags_FunctionTag' suffix: [[\>\%(\s*(\)\@=]] }, d: { group: 'neotags_PreProcTag' }, t: { group: 'neotags_TypeTag' }, } }
27.285714
60
0.417103
c0fe2c1a179482f8d198526486a6768ff39e3233
3,391
-- Copyright 2018 The Howl Developers -- License: MIT (see LICENSE.md at the top-level directory of the distribution) ffi = require 'ffi' const_char_p = ffi.typeof('const unsigned char *') {:max} = math ffi_copy, ffi_string = ffi.copy, ffi.string SEQ_LENS = ffi.new 'const int[256]', { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,-1,-1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1, } REPLACEMENT_CHARACTER = "\xEF\xBF\xBD" REPLACEMENT_SIZE = #REPLACEMENT_CHARACTER char_arr = ffi.typeof 'char [?]' uint_arr = ffi.typeof 'unsigned int [?]' get_warts = (s, len = #s) -> src = const_char_p s w_size = 0 warts = nil w_idx = 0 conts = 0 seq_start = nil i = 0 mark = -> if w_idx >= w_size - 2 old = warts w_size = max 8192, w_size * 2 warts = uint_arr w_size if old ffi_copy warts, old, w_idx * ffi.sizeof('unsigned int') pos = seq_start or i warts[w_idx] = pos w_idx += 1 i = pos seq_start = nil conts = 0 while i < len b = src[i] if b >= 128 -- non-ascii if b < 192 -- continuation byte if conts > 0 conts -= 1 -- ok continuation if conts == 0 seq_start = nil -- end of seq else mark! -- unexpected continuation byte else -- should be a sequence start s_len = SEQ_LENS[b] if s_len < 0 mark! -- no, an illegal value else if conts > 0 mark! -- in the middle of seq already else -- new seq starting seq_start = i conts = s_len - 1 else -- ascii if conts > 0 mark! -- expected continuation byte instead of ascii elseif b == 0 mark! -- zero byte i += 1 if seq_start -- broken at end mark! size_delta = w_idx * (#REPLACEMENT_CHARACTER - 1) nlen = len + size_delta + 1 -- additional size for \0 warts, w_idx, nlen clean = (s, len = #s) -> src = const_char_p s warts, wart_count, nlen = get_warts s, len if wart_count == 0 return src, len, 0 -- create new valid string dest = char_arr nlen src_idx = 0 dest_idx = 0 for i = 0, wart_count - 1 at = warts[i] diff = at - src_idx if diff > 0 -- copy any content up until the wart ffi_copy dest + dest_idx, src + src_idx, diff dest_idx += diff -- the replacement character ffi_copy dest + dest_idx, REPLACEMENT_CHARACTER, REPLACEMENT_SIZE dest_idx += REPLACEMENT_SIZE src_idx = at + 1 diff = len - src_idx if diff > 0 -- copy any content up until the end ffi_copy dest + dest_idx, src + src_idx, diff dest, nlen - 1, wart_count clean_string = (s, len = #s) -> ptr, len, wart_count = clean s, len return s, 0 unless wart_count != 0 ffi_string(ptr, len), wart_count is_valid = (s, len = #s) -> _, wart_count, _ = get_warts const_char_p(s), len wart_count != 0 :clean, :clean_string, :is_valid
26.700787
79
0.574167
b6a1260c7d71577f6715384f5dfd8aafca3a6158
930
serpent = require "serialization.serpent" M = {} chunk, errormsg = love.filesystem.load("config.lua") M.t = not errormsg and chunk() or {} recent = M.t.recent or {} M.t.recent = [recent[i] for i = 1, math.min(#recent, 10)] width, height = if window = M.t.window window.w, window.h else 800, 600 flags = { resizable: true } love.window.setMode(width, height, flags) love.window.setTitle("pathfun editor") M.save = => data = "return " .. serpent.block(@t, {comment:false}) love.filesystem.write("config.lua", data) M.add_filename = (filename) => for i, entry in ipairs(@t.recent) if filename == entry table.remove(@t.recent, i) break table.insert(@t.recent, 1, filename) @t.recent[11] = nil @save() M.clear_history = => @t.recent = {} @save() M.resize = (w, h) => @t.window = {:w, :h, fullscreen:{love.window.getFullscreen()}} @save() M.font_size = (size) => @t.font_size = size @save() return M
18.979592
63
0.645161
ff6035511b69b47ee208e7d202b1fc4230a16e16
2,211
#!/this/is/ignored a = 1 + 2* 3 / 6 a, bunch, go, here = another, world func arg1, arg2, another, arg3 here, we = () ->, yeah the, different = () -> approach; yeah dad() dad(lord) hello(one,two)() (5 + 5)(world) fun(a)(b) fun(a) b fun(a) b, bad hello hello world what are you doing here what(the)[3243] world, yeck heck hairy[hands][are](gross) okay okay[world] (get[something] + 5)[years] i,x = 200, 300 yeah = (1 + 5) * 3 yeah = ((1+5)*3)/2 yeah = ((1+5)*3)/2 + i % 100 whoa = (1+2) * (3+4) * (4+5) -> if something return 1,2,4 print "hello" -> if hello "heloo", "world" else no, way -> 1,2,34 return 5 + () -> 4 + 2 return 5 + (() -> 4) + 2 print 5 + () -> 34 good nads something 'else', "ya" something'else' something"else" here(we)"go"[12123] -- this runs something = test: 12323 what: -> print "hello world" print something.test frick = hello: "world" argon = num: 100 world: (self) -> print self.num return { something: -> print "hi from something" } somethin: (self, str) -> print "string is", str return world: (a,b) -> print "sum", a + b something.what() argon\world().something() argon\somethin"200".world(1,2) x = -434 x = -hello world one two hi = -"herfef" x = -[x for x in x] print "hello" if cool print "nutjob" if hello then 343 print "what" if cool else whack arg = {...} x = (...) -> dump {...} x = not true y = not(5+5) y = #"hello" x = #{#{},#{1},#{1,2}} hello, world something\hello(what) a,b something\hello what something.hello\world a,b something.hello\world(1,2,3) a,b x = 1232 x += 10 + 3 j -= "hello" y *= 2 y /= 100 m %= 2 hello ..= "world" x = 0 (if ntype(v) == "fndef" then x += 1) for v in *values hello = something: world if: "hello" else: 3434 function: "okay" good: 230203 5 + what wack what whack + 5 5 - what wack what whack - 5 x = hello - world - something ((something = with what \cool 100) -> print something)! if something 03589 -- okay what about this else 3434 if something yeah elseif "ymmm" print "cool" else okay -- test names containing keywords x = notsomething y = ifsomething z = x and b z = x andb
11.280612
53
0.584351
b983e3608fb865434d9b6bbb7d97f5a676dae2b2
2,104
import match, gsub from string import format_error, tree from require "moonscript/compile" import string from require "moonscript/parse" import logFatal from gmodproj.require "novacbn/gmodproj/lib/logging" import LuaAsset from "novacbn/gmodproj-plugin-builtin/assets/LuaAsset" -- ::PATTERN_HAS_IMPORTS -> pattern -- Represents a pattern for checking if the MoonScript has imports declarations PATTERN_HAS_IMPORTS = "import" -- ::PATTERN_EXTRACT_IMPORTS -> pattern -- Represents a pattern to extract imports from a MoonScript for transformation PATTERN_EXTRACT_IMPORTS = "(import[%s]+[%w_,%s]+[%s]+from[%s]+)(['\"][%w/%-_]+['\"])" -- MoonAsset::MoonAsset() -- Represents a MoonScript asset -- export export MoonAsset = LuaAsset\extend { -- MoonAsset::transformImports(string contents) -> string -- Transforms all 'import X from "Y"' statements into 'import X from dependency("Y")' -- transformImports: (contents) => -- If the MoonScript has import statements, convert then if match(contents, PATTERN_HAS_IMPORTS) return gsub(contents, PATTERN_EXTRACT_IMPORTS, (importStatement, assetName) -> -- Append the new source of import to the statement return importStatement.."dependency(#{assetName})" ) return contents -- MoonAsset::preTransform(string contents, boolean isProduction) -> string -- Transforms a MoonScript asset into Lua before dependency collection -- preTransform: (contents, isProduction) => -- Transform the MoonScript string import statements contents = @transformImports(contents) -- Parse the script into an abstract syntax tree and assert for errors syntaxTree, err = string(contents) logFatal("Failed to parse asset '#{@assetName}': #{err}") unless syntaxTree -- Compile the syntax tree into valid Lua code and again assert for errors luaCode, err, pos = tree(syntaxTree) logFatal("Failed to compile asset '#{@assetName}': #{format_error(err, pos, contents)}") unless luaCode return luaCode }
42.08
111
0.699144
2ed75f7bb4d0d84d1a467bfc033ac546a379a319
9,664
-- -- 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. PPM2.ALLOW_TO_MODIFY_SCALE = CreateConVar('ppm2_sv_allow_resize', '1', {FCVAR_NOTIFY, FCVAR_REPLICATED}, 'Allow to resize ponies. Disables resizing completely (visual; mechanical)') player_manager.AddValidModel('pony', 'models/ppm/player_default_base_new.mdl') list.Set('PlayerOptionsModel', 'pony', 'models/ppm/player_default_base_new.mdl') player_manager.AddValidModel('ponynj', 'models/ppm/player_default_base_new_nj.mdl') list.Set('PlayerOptionsModel', 'ponynj', 'models/ppm/player_default_base_new_nj.mdl') player_manager.AddValidModel('ponynj_old', 'models/ppm/player_default_base_nj.mdl') list.Set('PlayerOptionsModel', 'ponynj_old', 'models/ppm/player_default_base_nj.mdl') player_manager.AddValidModel('pony_old', 'models/ppm/player_default_base.mdl') list.Set('PlayerOptionsModel', 'pony_old', 'models/ppm/player_default_base.mdl') player_manager.AddValidModel('pony_cppm', 'models/cppm/player_default_base.mdl') list.Set('PlayerOptionsModel', 'pony_cppm', 'models/cppm/player_default_base.mdl') player_manager.AddValidModel('ponynj_cppm', 'models/cppm/player_default_base_nj.mdl') list.Set('PlayerOptionsModel', 'ponynj_cppm', 'models/cppm/player_default_base_nj.mdl') player_manager.AddValidHands(model, 'models/cppm/pony_arms.mdl', 0, '') for _, model in ipairs {'pony', 'pony_cppm', 'ponynj', 'ponynj_cppm', 'pony_old'} PPM2.MIN_WEIGHT = 0.7 PPM2.MAX_WEIGHT = 1.5 PPM2.MIN_SCALE = 0.5 PPM2.MAX_SCALE = 1.3 PPM2.PONY_HEIGHT_MODIFIER = 0.64 PPM2.PONY_HEIGHT_MODIFIER_DUCK = 1.12 PPM2.PONY_HEIGHT_MODIFIER_DUCK_HULL = 1 PPM2.MIN_NECK = 0.6 PPM2.MAX_NECK = 1.4 PPM2.MIN_LEGS = 0.6 PPM2.MAX_LEGS = 1.75 PPM2.MIN_SPINE = 0.8 PPM2.MAX_SPINE = 2 PPM2.PONY_JUMP_MODIFIER = 1.4 PPM2.PLAYER_VOFFSET = 64 * PPM2.PONY_HEIGHT_MODIFIER PPM2.PLAYER_VOFFSET_DUCK = 28 * PPM2.PONY_HEIGHT_MODIFIER_DUCK PPM2.PLAYER_VIEW_OFFSET = Vector(0, 0, PPM2.PLAYER_VOFFSET) PPM2.PLAYER_VIEW_OFFSET_DUCK = Vector(0, 0, PPM2.PLAYER_VOFFSET_DUCK) PPM2.PLAYER_VIEW_OFFSET_ORIGINAL = Vector(0, 0, 64) PPM2.PLAYER_VIEW_OFFSET_DUCK_ORIGINAL = Vector(0, 0, 28) PPM2.MIN_TAIL_SIZE = 0.6 PPM2.MAX_TAIL_SIZE = 1.7 -- i luv big tails PPM2.MIN_IRIS = 0.4 PPM2.MAX_IRIS = 1.3 PPM2.MIN_HOLE = 0.1 PPM2.MAX_HOLE = .95 PPM2.MIN_HOLE_SHIFT = -0.5 PPM2.MAX_HOLE_SHIFT = 0.5 PPM2.MIN_PUPIL_SIZE = 0.2 PPM2.MAX_PUPIL_SIZE = 1 PPM2.MIN_EYE_ROTATION = -180 PPM2.MAX_EYE_ROTATION = 180 PPM2.AvaliableTails = { 'MAILCALL' 'FLOOFEH' 'ADVENTUROUS' 'SHOWBOAT' 'ASSERTIVE' 'BOLD' 'STUMPY' 'SPEEDSTER' 'EDGY' 'RADICAL' 'BOOKWORM' 'BUMPKIN' 'POOFEH' 'CURLY' 'NONE' } PPM2.AvaliableUpperManes = { 'MAILCALL', 'FLOOFEH', 'ADVENTUROUS', 'SHOWBOAT', 'ASSERTIVE' 'BOLD', 'STUMPY', 'SPEEDSTER', 'RADICAL', 'SPIKED' 'BOOKWORM', 'BUMPKIN', 'POOFEH', 'CURLY', 'INSTRUCTOR', 'NONE' } PPM2.AvaliableLowerManes = { 'MAILCALL', 'FLOOFEH', 'ADVENTUROUS', 'SHOWBOAT' 'ASSERTIVE', 'BOLD', 'STUMPY', 'HIPPIE', 'SPEEDSTER' 'BOOKWORM', 'BUMPKIN', 'CURLY', 'NONE' } PPM2.EyelashTypes = { 'Default', 'Double', 'Coy', 'Full', 'Mess', 'None' } PPM2.BodyDetails = { 'None', 'Leg gradient', 'Lines', 'Stripes', 'Head stripes' 'Freckles', 'Hooves big', 'Hooves small', 'Head layer' 'Hooves big rnd', 'Hooves small rnd', 'Spots 1', 'Robotic' 'DASH-E', 'Eye Scar', 'Eye Wound', 'Scars', 'MGS Socks' 'Sharp Hooves', 'Sharp Hooves 2', 'Muzzle', 'Eye Scar Left' 'Eye Scar Right' } PPM2.BodyDetailsEnum = { 'NONE', 'GRADIENT', 'LINES', 'STRIPES', 'HSTRIPES' 'FRECKLES', 'HOOF_BIG', 'HOOF_SMALL', 'LAYER' 'HOOF_BIG_ROUND', 'HOOF_SMALL_ROUND', 'SPOTS', 'ROBOTIC' 'DASH_E', 'EYE_SCAR', 'EYE_WOUND', 'SCARS', 'MGS_SOCKS' 'SHARP_HOOVES', 'SHARP_HOOVES_2', 'MUZZLE', 'EYE_SCAR_LEFT' 'EYE_SCAR_RIGHT' } PPM2.SocksTypes = { 'DEFAULT' 'GEOMETRIC1' 'GEOMETRIC2' 'GEOMETRIC3' 'GEOMETRIC4' 'GEOMETRIC5' 'GEOMETRIC6' 'GEOMETRIC7' 'GEOMETRIC8' 'DARK1' 'FLOWERS10' 'FLOWERS11' 'FLOWERS12' 'FLOWERS13' 'FLOWERS14' 'FLOWERS15' 'FLOWERS16' 'FLOWERS17' 'FLOWERS18' 'FLOWERS19' 'FLOWERS2' 'FLOWERS20' 'FLOWERS3' 'FLOWERS4' 'FLOWERS5' 'FLOWERS6' 'FLOWERS7' 'FLOWERS8' 'FLOWERS9' 'GREY1' 'GREY2' 'GREY3' 'HEARTS1' 'HEARTS2' 'SNOW1' 'WALLPAPER1' 'WALLPAPER2' 'WALLPAPER3' } PPM2.AvaliableLightwarps = { 'SFM_PONY' 'AIRBRUSH' 'HARD_LIGHT' 'PURPLE_SKY' 'SPAWN' 'TF2' 'TF2_CINEMATIC' 'TF2_CLASSIC' 'WELL_OILED' } PPM2.MAX_LIGHTWARP = #PPM2.AvaliableLightwarps - 1 PPM2.AvaliableLightwarpsPaths = ['models/ppm2/lightwarps/' .. mat\lower() for _, mat in ipairs PPM2.AvaliableLightwarps] PPM2.DefaultCutiemarks = { '8ball', 'dice', 'magichat', 'magichat02', 'record', 'microphone', 'bits', 'checkered', 'lumps', 'mirror', 'camera', 'magnifier', 'padlock', 'binaryfile', 'floppydisk', 'cube', 'bulb', 'battery', 'deskfan', 'flames', 'alarm', 'myon', 'beer', 'berryglass', 'roadsign', 'greentree', 'seasons', 'palette', 'palette02', 'palette03', 'lightningstone', 'partiallycloudy', 'thunderstorm', 'storm', 'stoppedwatch', 'twistedclock', 'surfboard', 'surfboard02', 'star', 'ussr', 'vault', 'anarchy', 'suit', 'deathscythe', 'shoop', 'smiley', 'dawsome', 'weegee' 'applej', 'applem', 'bon_bon', 'carrots', 'celestia', 'cloudy', 'custom01', 'custom02', 'derpy', 'firezap', 'fluttershy', 'fruits', 'island', 'lyra', 'mine', 'note', 'octavia', 'pankk', 'pinkie_pie', 'rainbow_dash', 'rarity', 'rosen', 'sflowers', 'storm', 'time', 'time2', 'trixie', 'twilight', 'waters', 'weer', 'zecora' } PPM2.AvaliableUpperManesNew = { 'MAILCALL', 'FLOOFEH', 'ADVENTUROUS', 'SHOWBOAT', 'ASSERTIVE' 'BOLD', 'STUMPY', 'SPEEDSTER', 'RADICAL', 'SPIKED' 'BOOKWORM', 'BUMPKIN', 'POOFEH', 'CURLY', 'INSTRUCTOR' 'TIMID', 'FILLY', 'MECHANIC', 'MOON', 'CLOUD' 'DRUNK', 'EMO' 'NONE' } PPM2.AvaliableLowerManesNew = { 'MAILCALL', 'FLOOFEH', 'ADVENTUROUS', 'SHOWBOAT' 'ASSERTIVE', 'BOLD', 'STUMPY', 'HIPPIE', 'SPEEDSTER' 'BOOKWORM', 'BUMPKIN', 'CURLY' 'TIMID', 'MOON', 'BUN', 'CLOUD', 'EMO' 'NONE' } PPM2.AvaliableTailsNew = { 'MAILCALL', 'FLOOFEH', 'ADVENTUROUS', 'SHOWBOAT' 'ASSERTIVE', 'BOLD', 'STUMPY', 'SPEEDSTER', 'EDGY' 'RADICAL', 'BOOKWORM', 'BUMPKIN', 'POOFEH', 'CURLY' 'NONE' } PPM2.AvaliableEyeTypes = { 'DEFAULT', 'APERTURE' } PPM2.AvaliableEyeReflections = { 'DEFAULT', 'CRYSTAL_FOAL', 'CRYSTAL' 'FOAL', 'MALE' } PPM2.AvaliablePonyWings = {'DEFAULT', 'BATPONY'} PPM2.AvaliablePonySuits = {'NONE', 'ROYAL_GUARD', 'SHADOWBOLTS_FULL', 'SHADOWBOLTS_LIGHT', 'WONDERBOLTS_FULL', 'WONDERBOLTS_LIGHT', 'SPIDERMANE_LIGHT', 'SPIDERMANE_FULL'} do i = -1 for _, mark in ipairs PPM2.DefaultCutiemarks i += 1 PPM2["CMARK_#{mark\upper()}"] = i PPM2.MIN_EYELASHES = 0 PPM2.MAX_EYELASHES = #PPM2.EyelashTypes - 1 PPM2.EYELASHES_NONE = #PPM2.EyelashTypes - 1 PPM2.MIN_TAILS = 0 PPM2.MAX_TAILS = #PPM2.AvaliableTails - 1 PPM2.MIN_TAILS_NEW = 0 PPM2.MAX_TAILS_NEW = #PPM2.AvaliableTailsNew - 1 PPM2.MIN_UPPER_MANES = 0 PPM2.MAX_UPPER_MANES = #PPM2.AvaliableUpperManes - 1 PPM2.MIN_LOWER_MANES = 0 PPM2.MAX_LOWER_MANES = #PPM2.AvaliableLowerManes - 1 PPM2.MIN_UPPER_MANES_NEW = 0 PPM2.MAX_UPPER_MANES_NEW = #PPM2.AvaliableUpperManesNew - 1 PPM2.MIN_LOWER_MANES_NEW = 0 PPM2.MAX_LOWER_MANES_NEW = #PPM2.AvaliableLowerManesNew - 1 PPM2.MIN_EYE_TYPE = 0 PPM2.MAX_EYE_TYPE = #PPM2.AvaliableEyeTypes - 1 PPM2.MIN_DETAIL = 0 PPM2.MAX_DETAIL = #PPM2.BodyDetails - 1 PPM2.MIN_CMARK = 0 PPM2.MAX_CMARK = #PPM2.DefaultCutiemarks - 1 PPM2.MIN_SUIT = 0 PPM2.MAX_SUIT = #PPM2.AvaliablePonySuits - 1 PPM2.MIN_WINGS = 0 PPM2.MAX_WINGS = #PPM2.AvaliablePonyWings - 1 PPM2.MIN_SOCKS = 0 PPM2.MAX_SOCKS = #PPM2.SocksTypes - 1 PPM2.GENDER_FEMALE = 0 PPM2.GENDER_MALE = 1 PPM2.MAX_BODY_DETAILS = 8 PPM2.RACE_EARTH = 0 PPM2.RACE_PEGASUS = 1 PPM2.RACE_UNICORN = 2 PPM2.RACE_ALICORN = 3 PPM2.RACE_ENUMS = {'EARTH', 'PEGASUS', 'UNICORN', 'ALICORN'} PPM2.RACE_HAS_HORN = 0x1 PPM2.RACE_HAS_WINGS = 0x2 PPM2.AGE_FILLY = 0 PPM2.AGE_ADULT = 1 PPM2.AGE_MATURE = 2 PPM2.AGE_ENUMS = {'FILLY', 'ADULT', 'MATURE'} PPM2.MIN_DERP_STRENGTH = 0.1 PPM2.MAX_DERP_STRENGTH = 1.3 PPM2.MIN_MALE_BUFF = 0 PPM2.DEFAULT_MALE_BUFF = 1 PPM2.MAX_MALE_BUFF = 2 PPM2.MAX_TATTOOS = 25 PPM2.TATTOOS_REGISTRY = { 'NONE', 'ARROW', 'BLADES', 'CROSS', 'DIAMONDINNER', 'DIAMONDOUTER' 'DRACO', 'EVILHEART', 'HEARTWAVE', 'JUNCTION', 'NOTE', 'NOTE2' 'TATTOO1', 'TATTOO2', 'TATTOO3', 'TATTOO4', 'TATTOO5', 'TATTOO6', 'TATTOO7' 'WING', 'HEART' } PPM2.MIN_TATTOOS = 0 PPM2.MAX_TATTOOS = #PPM2.TATTOOS_REGISTRY - 1 PPM2.MIN_WING = 0.1 PPM2.MIN_WINGX = -10 PPM2.MIN_WINGY = -10 PPM2.MIN_WINGZ = -10 PPM2.MAX_WING = 2 PPM2.MAX_WINGX = 10 PPM2.MAX_WINGY = 10 PPM2.MAX_WINGZ = 10
27.376771
181
0.719888
b35fe1b353e1d2717a0be20f5364d6cc92f4c6b5
3,366
import getenv from os import arch, os from jit import join from require "path" import isAffirmative from "novacbn/gmodproj/lib/utilities/string" -- ::userHome -> string -- Represents the home folder for application data of the user -- userHome = switch os when "Windows" then getenv("APPDATA") when "Linux" then getenv("HOME") -- ::APPLICATION_CORE_VERSION -> table -- Represents the current version of the application -- export export APPLICATION_CORE_VERSION = {0, 4, 0} -- ::ENV_ALLOW_UNSAFE_SCRIPTING -> boolean -- Represents a environment variable flag if gmodproj should allow unsafe scripting -- export export ENV_ALLOW_UNSAFE_SCRIPTING = isAffirmative(getenv("GMODPROJ_ALLOW_UNSAFE_SCRIPTING") or "y") -- ::MAP_DEFAULT_PLUGINS -> table -- Represents the default configuration of gmodproj plguins -- export export MAP_DEFAULT_PLUGINS = { "gmodproj-plugin-builtin": {} } -- ::SYSTEM_OS_ARCH -> string -- Represents the architecture of the operating system -- export export SYSTEM_OS_ARCH = arch -- ::SYSTEM_OS_TYPE -> string -- Represents the type of operating system currently running -- export export SYSTEM_OS_TYPE = os -- ::SYSTEM_UNIX_LIKE -> string -- Represents if the operating system is unix-like in its environment -- export export SYSTEM_UNIX_LIKE = os == "Linux" or os == "OSX" -- ::PROJECT_PATH -> table -- Represents a map of paths for stored project data -- export export PROJECT_PATH = with {} -- PROJECT_PATH::home -> string -- Represents the home directory of the current project -- .home = process.cwd() -- PROJECT_PATH::data -> string -- Represents the home directory of gmodproj's project data -- .data = join(.home, ".gmodproj") -- PROJECT_PATH::bin -> string -- Represents the directory of utility scripts shipped with the project directory -- .bin = join(.home, "bin") -- PROJECT_PATH::manifest -> string -- Represents the project's metadata manifest -- .manifest = join(.home, ".gmodmanifest") -- PROJECT_PATH::packages -> string -- Represents the project's package manifest -- .packages = join(.home, ".gmodpackages") -- PROJECT_PATH::cache -> string -- Represents the directory of previously compiled modules in from the current project -- .cache = join(.data, "cache") -- PROJECT_PATH::logs -> string -- Represents the directory of log files from actions previously taken for the current project -- .logs = join(.data, "logs") -- PROJECT_PATH::plugins -> string -- Represents the directory of project installed plugin packages -- .plugins = join(.data, "plugins") -- ::USER_PATH -> table -- Represents a map of paths for stored user data -- export export USER_PATH = with {} -- USER_PATH::data -> string -- Represents the home directory of gmodproj's user data -- .data = join(userHome, ".gmodproj") -- USER_PATH::applications -> string -- Represents the globally installed command line applications -- .applications = join(.home, "applications") -- USER_PATH::cache -> string -- Represents the directory of previously downloaded packages -- .cache = join(.home, "cache") -- USER_PATH::plugins -> string -- Represents the directory of globally installed plugin packages -- .plugins = join(.home, "plugins")
29.787611
99
0.692216
fec9ea4c8f3116abd5c73965aeaa6c3efe03e0b6
218
config = require "lapis.config" config { "development", "test", "production" }, -> port 8080 num_workers 1 worker_connections 7 code_cache "off" postgresql_url "postgres://lamutib:[email protected]/lamutib"
21.8
62
0.711009
86b5ebc8b33cd63c264169d0a4a88ce5521c13d5
609
table = require "table" math = require "math" merge = (left, right, cmp) -> result = {} while (#left > 0) and (#right > 0) if cmp(left[1], right[1]) table.insert result, table.remove left, 1 else table.insert result, table.remove right, 1 while #left > 0 do table.insert result, table.remove left, 1 while #right > 0 do table.insert result, table.remove right, 1 result merge_sort = (tbl, cmp) -> return tbl if #tbl < 2 middle = math.ceil(#tbl / 2) merge merge_sort([tbl[i] for i = 1, middle], cmp), merge_sort([tbl[i] for i = middle + 1, #tbl], cmp), cmp {:merge_sort}
29
108
0.632184
744b3b6cf36ec0d5ce11ab55e3f2343f5126be0b
8,201
import with_query_fn from require "spec.helpers" db = require "lapis.nginx.postgres" schema = require "lapis.db.schema" value_table = { hello: "world", age: 34 } tests = { -- lapis.nginx.postgres { -> db.escape_identifier "dad" '"dad"' } { -> db.escape_identifier "select" '"select"' } { -> db.escape_identifier 'love"fish' '"love""fish"' } { -> db.escape_identifier db.raw "hello(world)" "hello(world)" } { -> db.escape_literal 3434 "3434" } { -> db.escape_literal "cat's soft fur" "'cat''s soft fur'" } { -> db.interpolate_query "select * from cool where hello = ?", "world" "select * from cool where hello = 'world'" } { -> db.encode_values(value_table) [[("hello", "age") VALUES ('world', 34)]] [[("age", "hello") VALUES (34, 'world')]] } { -> db.encode_assigns(value_table) [["hello" = 'world', "age" = 34]] [["age" = 34, "hello" = 'world']] } { -> db.encode_assigns thing: db.NULL [["thing" = NULL]] } { -> db.encode_clause thing: db.NULL [["thing" IS NULL]] } { -> db.interpolate_query "update x set x = ?", db.raw"y + 1" "update x set x = y + 1" } { -> db.select "* from things where id = ?", "cool days" [[SELECT * from things where id = 'cool days']] } { -> db.insert "cats", age: 123, name: "catter" [[INSERT INTO "cats" ("name", "age") VALUES ('catter', 123)]] [[INSERT INTO "cats" ("age", "name") VALUES (123, 'catter')]] } { -> db.update "cats", { age: db.raw"age - 10" }, "name = ?", "catter" [[UPDATE "cats" SET "age" = age - 10 WHERE name = 'catter']] } { -> db.update "cats", { age: db.raw"age - 10" }, { name: db.NULL } [[UPDATE "cats" SET "age" = age - 10 WHERE "name" IS NULL]] } { -> db.update "cats", { age: db.NULL }, { name: db.NULL } [[UPDATE "cats" SET "age" = NULL WHERE "name" IS NULL]] } { -> db.update "cats", { color: "red" }, { weight: 1200, length: 392 } [[UPDATE "cats" SET "color" = 'red' WHERE "weight" = 1200 AND "length" = 392]] [[UPDATE "cats" SET "color" = 'red' WHERE "length" = 392 AND "weight" = 1200]] } { -> db.delete "cats" [[DELETE FROM "cats"]] } { -> db.delete "cats", "name = ?", "rump" [[DELETE FROM "cats" WHERE name = 'rump']] } { -> db.delete "cats", name: "rump" [[DELETE FROM "cats" WHERE "name" = 'rump']] } { -> db.delete "cats", name: "rump", dad: "duck" [[DELETE FROM "cats" WHERE "name" = 'rump' AND "dad" = 'duck']] [[DELETE FROM "cats" WHERE "dad" = 'duck' AND "name" = 'rump']] } { -> db.insert "cats", { hungry: true } [[INSERT INTO "cats" ("hungry") VALUES (TRUE)]] } { -> db.insert "cats", { age: 123, name: "catter" }, "age" [[INSERT INTO "cats" ("name", "age") VALUES ('catter', 123) RETURNING "age"]] [[INSERT INTO "cats" ("age", "name") VALUES (123, 'catter') RETURNING "age"]] } { -> db.insert "cats", { age: 123, name: "catter" }, "age", "name" [[INSERT INTO "cats" ("name", "age") VALUES ('catter', 123) RETURNING "age", "name"]] [[INSERT INTO "cats" ("age", "name") VALUES (123, 'catter') RETURNING "age", "name"]] } -- lapis.db.schema { -> schema.add_column "hello", "dads", schema.types.integer [[ALTER TABLE "hello" ADD COLUMN "dads" integer NOT NULL DEFAULT 0]] } { -> schema.rename_column "hello", "dads", "cats" [[ALTER TABLE "hello" RENAME COLUMN "dads" TO "cats"]] } { -> schema.drop_column "hello", "cats" [[ALTER TABLE "hello" DROP COLUMN "cats"]] } { -> schema.rename_table "hello", "world" [[ALTER TABLE "hello" RENAME TO "world"]] } { -> tostring schema.types.integer "integer NOT NULL DEFAULT 0" } { -> tostring schema.types.integer null: true "integer DEFAULT 0" } { -> tostring schema.types.integer null: true, default: 100, unique: true "integer DEFAULT 100 UNIQUE" } { -> tostring schema.types.serial "serial NOT NULL" } { -> tostring schema.types.time "timestamp NOT NULL" } { -> tostring schema.types.time timezone: true "timestamp with time zone NOT NULL" } { -> import foreign_key, boolean, varchar, text from schema.types schema.create_table "user_data", { {"user_id", foreign_key} {"email_verified", boolean} {"password_reset_token", varchar null: true} {"data", text} "PRIMARY KEY (user_id)" } [[CREATE TABLE IF NOT EXISTS "user_data" ( "user_id" integer NOT NULL, "email_verified" boolean NOT NULL DEFAULT FALSE, "password_reset_token" character varying(255), "data" text NOT NULL, PRIMARY KEY (user_id) );]] } { -> schema.drop_table "user_data" [[DROP TABLE IF EXISTS "user_data";]] } { -> schema.drop_index "user_data", "one", "two", "three" [[DROP INDEX IF EXISTS "user_data_one_two_three_idx"]] } { -> db.parse_clause "" {} } { -> db.parse_clause "where something = TRUE" { where: "something = TRUE" } } { -> db.parse_clause "where something = TRUE order by things asc" { where: "something = TRUE " order: "things asc" } } { -> db.parse_clause "where something = 'order by cool' having yeah order by \"limit\" asc" { having: "yeah " where: "something = 'order by cool' " order: '"limit" asc' } } { -> db.parse_clause "where not exists(select 1 from things limit 100)" { where: "not exists(select 1 from things limit 100)" } } { -> db.parse_clause "order by color asc" { order: "color asc" } } { -> db.parse_clause "ORDER BY color asc" { order: "color asc" } } { -> db.parse_clause "group BY height" { group: "height" } } { -> db.parse_clause "where x = limitx 100" { where: "x = limitx 100" } } { -> db.parse_clause "join dads on color = blue where hello limit 10" { limit: "10" where: "hello " join: { {"join", " dads on color = blue "} } } } { -> db.parse_clause "inner join dads on color = blue left outer join hello world where foo" { where: "foo" join: { {"inner join", " dads on color = blue "} {"left outer join", " hello world "} } } } { -> schema.gen_index_name "hello", "world" "hello_world_idx" } { -> schema.gen_index_name "yes", "please", db.raw "upper(dad)" "yes_please_upper_dad_idx" } { -> db.encode_case("x", { a: "b" }) [[CASE x WHEN 'a' THEN 'b' END]] } { -> db.encode_case("x", { a: "b", foo: true }) [[CASE x WHEN 'a' THEN 'b' WHEN 'foo' THEN TRUE END]] [[CASE x WHEN 'foo' THEN TRUE WHEN 'a' THEN 'b' END]] } { -> db.encode_case("x", { a: "b" }, false) [[CASE x WHEN 'a' THEN 'b' ELSE FALSE END]] } } local old_query_fn describe "lapis.nginx.postgres", -> setup -> old_query_fn = db.set_backend "raw", (q) -> q teardown -> db.set_backend "raw", old_query_fn for group in *tests it "should match", -> output = group[1]! if #group > 2 assert.one_of output, { unpack group, 2 } else assert.same group[2], output it "should create index", -> old_select = db.select db.select = -> { { c: 0 } } input = schema.create_index "user_data", "one", "two" assert.same input, [[CREATE INDEX "user_data_one_two_idx" ON "user_data" ("one", "two");]] db.select = old_select it "should create index with expression", -> old_select = db.select db.select = -> { { c: 0 } } input = schema.create_index "user_data", db.raw("lower(name)"), "height" assert.same input, [[CREATE INDEX "user_data_lower_name_height_idx" ON "user_data" (lower(name), "height");]] db.select = old_select it "should create not create duplicate index", -> old_select = db.select db.select = -> { { c: 1 } } input = schema.create_index "user_data", "one", "two" assert.same input, nil db.select = old_select
20.974425
113
0.552737
5b1b989b83979ce38dcdb12a18a9dcc737bc8061
245
GM.Version = "1.0" GM.Name = "Space Wars" GM.Author = "Emperor Penguin Protector" DeriveGamemode "sandbox" DEFINE_BASECLASS "gamemode_sandbox" GM.Sandbox = BaseClass AddCSLuaFile "cl_init.lua" AddCSLuaFile "shared.lua" include "shared.lua"
18.846154
39
0.763265
290984f435b8c868bd0be9a2e6f4732807b15909
4,577
-- Copyright 2012-2015 The Howl Developers -- License: MIT (see LICENSE.md at the top-level directory of the distribution) import app, Buffer, command, interact, mode from howl import BufferPopup from howl.ui command.register name: 'buffer-search-forward', description: 'Starts an interactive forward search' input: -> if interact.forward_search! return true app.editor.searcher\cancel! handler: -> app.editor.searcher\commit! command.register name: 'buffer-search-backward', description: 'Starts an interactive backward search' input: -> if interact.backward_search! return true app.editor.searcher\cancel! handler: -> app.editor.searcher\commit! command.register name: 'buffer-search-line', description: 'Starts an interactive line search' input: -> if interact.search_line! return true app.editor.searcher\cancel! handler: -> app.editor.searcher\commit! command.register name: 'buffer-search-word-forward', description: 'Jumps to next occurence of word at cursor' input: -> app.window.command_line\write_spillover app.editor.current_context.word.text if interact.forward_search_word! return true app.editor.searcher\cancel! handler: -> app.editor.searcher\commit! command.register name: 'buffer-search-word-backward', description: 'Jumps to previous occurence of word at cursor' input: -> app.window.command_line\write_spillover app.editor.current_context.word.text if interact.backward_search_word! return true app.editor.searcher\cancel! handler: -> app.editor.searcher\commit! command.register name: 'buffer-repeat-search', description: 'Repeats the last search' handler: -> app.editor.searcher\repeat_last! command.register name: 'buffer-replace' description: 'Replaces text (within selection or globally)' input: -> buffer = app.editor.buffer chunk = app.editor.active_chunk replacement = interact.get_replacement title: 'Preview replacements for ' .. buffer.title editor: app.editor return replacement if replacement log.info "Cancelled - buffer untouched" handler: (replacement) -> if replacement.text buffer = app.editor.buffer app.editor\with_position_restored -> buffer\as_one_undo -> buffer.text = replacement.text log.info "Replaced #{replacement.num_replaced} instances" if replacement.cursor_pos app.editor.cursor.pos = replacement.cursor_pos if replacement.line_at_top app.editor.line_at_top = replacement.line_at_top command.register name: 'buffer-replace-regex', description: 'Replaces text using regular expressions (within selection or globally)' input: -> buffer = app.editor.buffer chunk = app.editor.active_chunk replacement = interact.get_replacement_regex title: 'Preview replacements for ' .. buffer.title editor: app.editor return replacement if replacement log.info "Cancelled - buffer untouched" handler: (replacement) -> buffer = app.editor.buffer if replacement.text app.editor\with_position_restored -> buffer\as_one_undo -> buffer.text = replacement.text log.info "Replaced #{replacement.num_replaced} instances" if replacement.cursor_pos app.editor.cursor.pos = replacement.cursor_pos if replacement.line_at_top app.editor.line_at_top = replacement.line_at_top command.register name: 'editor-paste..', description: 'Pastes a selected clip from the clipboard at the current position' input: interact.select_clipboard_item handler: (clip) -> app.editor\paste :clip command.register name: 'show-doc-at-cursor', description: 'Shows documentation for symbol at cursor, if available' handler: -> m = app.editor.buffer.mode ctx = app.editor.current_context if m.api and m.resolve_type node = m.api path, parts = m\resolve_type ctx if path node = node[k] for k in *parts when node node = node[ctx.word.text] if node if node and node.description buf = Buffer mode.by_name('markdown') buf.text = node.description app.editor\show_popup BufferPopup buf return log.info "No documentation found for '#{ctx.word}'" command.register name: 'buffer-mode', description: 'Sets a specified mode for the current buffer' input: interact.select_mode handler: (selected_mode) -> buffer = app.editor.buffer buffer.mode = selected_mode log.info "Forced mode '#{selected_mode.name}' for buffer '#{buffer}'"
31.349315
87
0.715316
698e1d6601ad8a80db91a0f45509f53b30c9fee3
1,554
export class Entity extends Rectangle new: (x = 0, y = 0, width = 0, height = 0) => super x, y, width, height @angle = 0 @offset = Rectangle! @visible = true @active = true @solid = true @exists = true @center = Point @x + @width / 2, @y + @height / 2 @previous = Point @x, @y @velocity = Vector! @pvelocity = Vector! @acceleration = Vector! @max_velocity = Vector math.huge, math.huge, math.huge @drag = Vector! update: => @previous.x = @x @previous.y = @y @pvelocity.x = @velocity.x @pvelocity.y = @velocity.y if not @velocity\is_zero! or not @acceleration\is_zero! @velocity.x = @calculate_velocity @velocity.x, @acceleration.x, @drag.x, @max_velocity.x @velocity.y = @calculate_velocity @velocity.y, @acceleration.y, @drag.y, @max_velocity.y @velocity.a = @calculate_velocity @velocity.a, @acceleration.a, @drag.a, @max_velocity.a @x += (@velocity.x * axel.dt) + ((@pvelocity.x - @velocity.x) * axel.dt / 2) @y += (@velocity.y * axel.dt) + ((@pvelocity.y - @velocity.y) * axel.dt / 2) @angle += @velocity.a * axel.dt @center.x = @x + @width / 2 @center.y = @y + @height / 2 calculate_velocity: (velocity, acceleration, drag, max) => if acceleration != 0 velocity += acceleration * axel.dt else drag_effect = drag * axel.dt if velocity - drag_effect > 0 velocity -= drag_effect elseif velocity + drag_effect < 0 velocity += drag_effect else velocity = 0 if velocity > max velocity = max elseif velocity < -max velocity = -max velocity
27.263158
91
0.633205
3ef92ee16b91d0941d1fdfd4541ba45ab33e3a83
2,328
uv = require "uv" {:capture, :execute, :execute_sync} = require "command" blocks = {} named_blocks = {} data_block = (block) -> color = block.color label = block.label name = block.name separator_block_width = block.separator_block_width full_text = "#{label}#{block.text}" {:color, :label, :full_text, :name, :separator_block_width, short_text: block.text} new_block = (name, setup) -> block_conf = {label: "", color: "#FFFFFF", text: "", :name, separator_block_width: 15} block = setmetatable block_conf, __call: (block, name, setup) -> env = setmetatable { :execute :execute_sync :capture label: (lbl) -> if lbl block_conf.label = lbl block_conf.label color: (clr) -> if clr block_conf.color = clr block_conf.color text: (txt) -> if txt block_conf.text = txt block_conf.text separator_block_width: (sbw) -> sbw = assert tonumber(sbw), "separator_block_width must be a number" if sbw block_conf.separator_block_width = sbw block_conf.separator_block_width }, __index: _G event_handler = (f) -> setfenv f, env -> coroutine.wrap(f)! block_conf.updater = -> nil block_conf.left_click = -> nil block_conf.middle_click = -> nil block_conf.right_click = -> nil block_conf.scroll_up = -> nil block_conf.scroll_down = -> nil block_conf._interval = nil setup_env = setmetatable { interval: (iv) -> block_conf._interval = iv, on_update: (f) -> block_conf.updater = event_handler(f) on_left_click: (f) -> block_conf.left_click = event_handler(f) on_middle_click: (f) -> block_conf.middle_click = event_handler(f) on_right_click: (f) -> block_conf.right_click = event_handler(f) on_scroll_up: (f) -> block_conf.scroll_up = event_handler(f) on_scroll_down: (f) -> block_conf.scroll_down = event_handler(f) }, __index: env setfenv setup, setup_env setup! if block_conf._interval t = uv.new_timer! uv.timer_start t, block_conf._interval, block_conf._interval, block.updater block_conf.updater! blocks[#blocks + 1] = block named_blocks[name] = block block name, setup block: new_block, :named_blocks, :blocks, :data_block
30.631579
88
0.643471
0f3bad221bb4d83638e73fa53041d8c0106629c5
231
export modinfo = { type: "command" desc: "Night" alias: {"night"} func: (Msg,Speaker) -> light = Service"Lighting" light.TimeOfDay = "24:00:00" Output2("Set time to night",{Colors.Green}) loggit("Set time to night") }
23.1
45
0.645022
f54cccfee1db8d1edf69bdf1c830935435116928
2,327
-- Support LuaJIT 'bit' library if bit exports.arshift = bit.arshift exports.band = bit.band exports.bnot = bit.bnot exports.bor = bit.bor exports.bxor = bit.bxor exports.lshift = bit.lshift exports.rol = bit.rol exports.ror = bit.ror exports.rshift = bit.rshift -- Support 'bit' Lua 5.2 standard library elseif bit32 exports.arshift = bit32.arshift exports.band = bit32.band exports.bnot = bit32.bnot exports.bor = bit32.bor exports.bxor = bit32.bxor exports.lshift = bit32.lshift exports.rol = bit32.lrotate exports.ror = bit32.rrotate exports.rshift = bit32.rshift else error("could not find 'bit' LuaJIT or 'bit32' Lua 5.2 libraries") import arshift, band, bor, lshift, rshift from exports -- ::byteFromInt8(number value) -> number -- Packs the 8-bit integer into a single byte -- export export byteFromInt8 = (value) -> return band(value, 255) -- ::bytesFromInt16(number value) -> number, number -- Packs the 16-bit integer into BigEndian-format two bytes -- export export bytesFromInt16 = (value) -> return band(rshift(value, 8), 255), band(value, 255) -- ::bytesFromInt32(number value) -> number, number, number, number -- Packs the 32-bit integer into BigEndian-format four bytes -- export export bytesFromInt32 = (value) -> return band(rshift(value, 24), 255), band(rshift(value, 16), 255), band(rshift(value, 8), 255), band(value, 255) -- int32FromBytes(number byteOne, number byteTwo) -> number -- Unpacks a single byte into a 8-bit integer -- export export int8FromByte = (byte) -> -- NOTE: this is here for the sake of completeness, nothing more return byte -- int32FromBytes(number byteOne, number byteTwo) -> number -- Unpacks BigEndian-format two bytes into a 16-bit integer -- export export int16FromBytes = (byteOne, byteTwo) -> return bor( lshift(byteOne, 8), byteTwo ) -- int32FromBytes(number byteOne, number byteTwo, number byteThree, number byteFour) -> number -- Unpacks BigEndian-format four bytes into a 32-bit integer -- export export int32FromBytes = (byteOne, byteTwo, byteThree, byteFour) -> return bor( lshift(byteOne, 24), lshift(byteTwo, 16), lshift(byteThree, 8), byteFour )
31.445946
116
0.674259
0aa41d9fc1d503cb58c1bfea00e91e432d18a13f
3,565
buffet = require 'buffet' import new from require 'buffet.resty' describe 'is_closed(bf)', -> it "should return true if buffet is closed with 'close' method", -> bf = new 'deadbeef' bf\close! n, closed = nargs buffet.is_closed bf assert.are.equal 1, n assert.are.equal true, closed it "should return true if buffet is closed with 'receive' method", -> bf = new 'deadbeef' bf\receive 1024 n, closed = nargs buffet.is_closed bf assert.are.equal 1, n assert.are.equal true, closed it 'should return false if buffet is not closed', -> bf = new 'deadbeef' n, closed = nargs buffet.is_closed bf assert.are.equal 1, n assert.are.equal false, closed it "should not check object type and return '_closed' field as is", -> n, closed = nargs buffet.is_closed {_closed: 'foo'} assert.are.equal 1, n assert.are.equal 'foo', closed describe 'get_iterator_error(bf)', -> it 'should return nil if there was no error', -> iterator = coroutine.wrap -> coroutine.yield 'foo' coroutine.yield 'bar' coroutine.yield nil coroutine.yield 'baz' bf = new iterator chunks = {} while true chunk, err = bf\receive 2 if err assert.are.equal 'closed', err break table.insert chunks, chunk assert.are.same {'fo', 'ob', 'ar'}, chunks n, iter_err = nargs buffet.get_iterator_error bf assert.are.equal 1, n assert.is.nil iter_err it 'should return error value if there was an error', -> iterator = coroutine.wrap -> coroutine.yield 'foo' coroutine.yield 'bar' coroutine.yield nil, 'some error' coroutine.yield 'baz' bf = new iterator chunks = {} while true chunk, err = bf\receive 2 if err assert.are.equal 'closed', err break table.insert chunks, chunk assert.are.same {'fo', 'ob', 'ar'}, chunks n, iter_err = nargs buffet.get_iterator_error bf assert.are.equal 1, n assert.are.equal 'some error', iter_err it "should not check object type and return '_iterator_error' field as is", -> n, closed = nargs buffet.get_iterator_error {_iterator_error: 'foo'} assert.are.equal 1, n assert.are.equal 'foo', closed describe 'get_send_buffer(bf)', -> it 'should return a reference to the send buffer table', -> bf = new! bf\send 'foo' n, buffer = nargs buffet.get_send_buffer bf assert.are.equal 1, n assert.are.equal bf._send_buffer, buffer it "should not check object type and return '_send_buffer' field as is", -> n, buffer = nargs buffet.get_send_buffer {_send_buffer: 'foo'} assert.are.equal 1, n assert.are.equal 'foo', buffer describe 'get_sent_data(bf)', -> it 'should return concatenated data chunks from send buffer', -> bf = new! bf\send 'foo' bf\send {'bar', 23, 'baz'} n, data = nargs buffet.get_sent_data bf assert.are.equal 1, n assert.are.equal 'foobar23baz', data it "should not check object type and return '_send_buffer' concatenated data", -> n, buffer = nargs buffet.get_sent_data {_send_buffer: {'foo', 'bar'}} assert.are.equal 1, n assert.are.equal 'foobar', buffer
33.632075
85
0.58878
6c546f45c42cf7eb335bd618dcb229dcaa4f0b74
8,553
http = require 'lapis.nginx.http' stringy = require 'stringy' sass = require 'sass' import map, table_index from require 'lib.utils' import from_json, to_json, trim from require 'lapis.util' import aql, document_get, foxx_upgrade from require 'lib.arango' -------------------------------------------------------------------------------- write_content = (filename, content)-> file = io.open(filename, 'w+') io.output(file) io.write(content) io.close(file) -------------------------------------------------------------------------------- read_file = (filename, mode='r')-> file = io.open(filename, mode) io.input(file) data = io.read('*all') io.close(file) data -------------------------------------------------------------------------------- install_service = (sub_domain, name)-> if name\match('^[%w_%-%d]+$') -- allow only [a-zA-Z0-9_-]+ path = "install_service/#{sub_domain}/#{name}" os.execute("mkdir -p #{path}/APP/routes") os.execute("mkdir #{path}/APP/scripts") os.execute("mkdir #{path}/APP/tests") os.execute("mkdir #{path}/APP/libs") request = 'FOR api IN apis FILTER api.name == @name LET routes = (FOR r IN api_routes FILTER r.api_id == api._key RETURN r) LET scripts = (FOR s IN api_scripts FILTER s.api_id == api._key RETURN s) LET tests = (FOR t IN api_tests FILTER t.api_id == api._key RETURN t) LET libs = (FOR l IN api_libs FILTER l.api_id == api._key RETURN l) RETURN { api, routes, scripts, tests, libs }' api = aql("db_#{sub_domain}", request, { 'name': name })[1] write_content("#{path}/APP/main.js", api.api.code) write_content("#{path}/APP/package.json", api.api.package) write_content("#{path}/APP/manifest.json", api.api.manifest) for k, item in pairs api.routes write_content("#{path}/APP/routes/#{item.name}.js", item.javascript) for k, item in pairs api.tests write_content("#{path}/APP/tests/#{item.name}.js", item.javascript) for k, item in pairs api.libs write_content("#{path}/APP/libs/#{item.name}.js", item.javascript) for k, item in pairs api.scripts write_content("#{path}/APP/scripts/#{item.name}.js", item.javascript) os.execute("cd install_service/#{sub_domain}/#{name}/APP && export PATH='$PATH:/usr/local/bin' && yarn") os.execute("cd install_service/#{sub_domain} && zip -rq #{name}.zip #{name}/") os.execute("rm --recursive install_service/#{sub_domain}/#{name}") foxx_upgrade( "db_#{sub_domain}", name, read_file("install_service/#{sub_domain}/#{name}.zip") ) -------------------------------------------------------------------------------- install_script = (sub_domain, name)-> if name\match('^[%w_%-%d]+$') -- allow only [a-zA-Z0-9_-]+ path = "scripts/#{sub_domain}/#{name}" os.execute("mkdir -p #{path}") request = 'FOR script IN scripts FILTER script.name == @name RETURN script' script = aql("db_#{sub_domain}", request, { 'name': name })[1] write_content("#{path}/package.json", script.package) os.execute("export PATH='$PATH:/usr/local/bin' && cd #{path} && yarn") write_content("#{path}/index.js", script.code) -------------------------------------------------------------------------------- deploy_site = (sub_domain, settings)-> config = require('lapis.config').get! db_config = require('lapis.config').get("db_#{config._name}") path = "dump/#{sub_domain[1]}/" home = from_json(settings.home) deploy_to = stringy.split(settings.deploy_secret, '#') request = 'FOR s IN settings LIMIT 1 RETURN s' sub_domain_settings = aql(deploy_to[1], request)[1] if deploy_to[2] == sub_domain_settings.secret os.execute("mkdir -p #{path}") command = "arangodump --collection layouts --collection partials --collection components --collection spas --collection redirections --collection datatypes --collection aqls --collection helpers --collection apis --collection api_libs --collection api_routes --collection api_scripts --collection api_tests --collection scripts --collection pages --collection folder_path --collection folders --collection scripts --server.database db_#{sub_domain} --server.username #{db_config.login} --server.password #{db_config.pass} --server.endpoint #{db_config.endpoint} --output-directory #{path} --overwrite true" command ..= " --collection datasets" if home['deploy_datasets'] command ..= " --collection trads" if home['deploy_trads'] os.execute(command) os.execute("arangorestore --server.database #{deploy_to[1]} --server.username #{db_config.login} --server.password #{db_config.pass} --server.endpoint #{db_config.endpoint} --input-directory #{path} --overwrite true") os.execute("rm -Rf #{path}") -- Restart scripts -- scripts = aql(deploy_to[1], 'FOR script IN scripts RETURN script') -- for k, item in pairs scripts -- install_script(deploy_to[1], item.name) -- Restart apis apis = aql(deploy_to[1], 'FOR api IN apis RETURN api') for k, item in pairs apis install_service(deploy_to[1]\gsub('db_', ''), item.name) -------------------------------------------------------------------------------- compile_riotjs = (sub_domain, name, id)-> if name\match('^[%w_%-%d]+$') -- allow only [a-zA-Z0-9_-]+ path = "compile_tag/#{sub_domain}/#{name}" os.execute("mkdir -p #{path}") tag = document_get("db_" .. sub_domain, id) write_content("#{path}/#{name}.riot", tag.html) command = "export PATH=\"$PATH;/usr/local/bin\" && riot --format umd #{path}/#{name}.riot --output #{path}/#{name}.js && terser --compress --mangle -o #{path}/#{name}.js #{path}/#{name}.js" handle = io.popen(command) result = handle\read('*a') handle\close() read_file("#{path}/#{name}.js") -------------------------------------------------------------------------------- compile_tailwindcss = (sub_domain, layout_id, field)-> subdomain = 'db_' .. sub_domain layout = document_get(subdomain, "layouts/" .. layout_id) settings = aql(subdomain, 'FOR s IN settings LIMIT 1 RETURN s')[1] home_settings = from_json(settings.home) langs = stringy.split(settings.langs, ',') path = "compile_tailwind/#{subdomain}/#{layout_id}" os.execute("mkdir -p #{path}") write_content("#{path}/#{layout_id}.css", sass.compile(layout[field], 'compressed')) -- default config file config_file = "module.exports = { content: ['./*.html'] }" -- check if we have defined a config file if home_settings.tailwindcss_config config_file = aql( subdomain, 'FOR page IN partials FILTER page.slug == @slug RETURN page.html', { slug: home_settings.tailwindcss_config } )[1] write_content("#{path}/tailwind.config.js", config_file) if config_file -- Layouts layouts = aql(subdomain, 'FOR doc IN layouts RETURN { html: doc.html }') for k, item in pairs layouts write_content("#{path}/layout_#{k}.html", item.html) -- Pages pages = aql(subdomain, 'FOR doc IN pages RETURN { html: doc.html, raw_html: doc.raw_html }') for k, item in pairs pages for k2, lang in pairs langs lang = stringy.strip(lang) html = "" if type(item['raw_html']) == 'table' and item['raw_html'][lang] html = html .. item['raw_html'][lang] if type(item['html']) == "table" and item['html'][lang] and item['html'][lang].html html = html .. item['html'][lang].html write_content("#{path}/page_#{k}_#{lang}.html", html) -- Components components = aql(subdomain, 'FOR doc IN components RETURN { html: doc.html }') for k, item in pairs components write_content("#{path}/component_#{k}.html", item.html) -- Partials partials = aql(subdomain, 'FOR doc IN partials RETURN { html: doc.html }') for k, item in pairs partials write_content("#{path}/partial_#{k}.html", item.html) -- Widgets partials = aql(subdomain, 'FOR doc IN widgets RETURN { html: doc.partial }') for k, item in pairs partials write_content("#{path}/widget_#{k}.html", item.html) command = "cd #{path} && export PATH=\"$PATH;/usr/local/bin\" && NODE_ENV=production tailwindcss build -m -i #{layout_id}.css -o #{layout_id}_compiled.css" handle = io.popen(command) result = handle\read('*a') handle\close() data = read_file("#{path}/#{layout_id}_compiled.css") os.execute("rm -Rf #{path}") data -------------------------------------------------------------------------------- -- expose methods { :install_service, :install_script, :deploy_site, :compile_riotjs, :compile_tailwindcss, :write_content, :read_file }
45.983871
610
0.614404
a4528721f9a3cdbc069764bb90882ffcf1b334ca
9,097
import style, theme, ActionBuffer from howl.ui import Scintilla, Buffer, config from howl describe 'style', -> local sci, buffer before_each -> sci = Scintilla! buffer = Buffer {}, sci style.register_sci sci it 'styles can be accessed using direct indexing', -> t = styles: default: color: '#998877' style.set_for_theme t assert.equal style.default.color, t.styles.default.color describe '.define(name, definition)', -> it 'allows defining custom styles', -> style.define 'custom', color: '#334455' assert.equal style.custom.color, '#334455' it 'automatically redefines the style in any existing sci', -> style.define 'keyword', color: '#334455' style.define 'custom', color: '#334455' custom_number = style.number_for 'custom', buffer keyword_number = style.number_for 'keyword', buffer style.define 'keyword', color: '#665544' style.define 'custom', color: '#776655' keyword_fore = sci\style_get_fore keyword_number assert.equal '#665544', keyword_fore custom_fore = sci\style_get_fore custom_number assert.equal '#776655', custom_fore it 'allows specifying font size for a style as an offset spec from "font_size"', -> style.define 'larger_style', font: size: 'larger' style_number = style.number_for 'larger_style', buffer font_size = sci\style_get_size style_number assert.is_true font_size > config.font_size it 'allows aliasing styles using a string as <definition>', -> style.define 'target', color: '#beefed' style.define 'alias', 'target' style_number = style.number_for 'alias', buffer assert.equal '#beefed', sci\style_get_fore style_number it 'the actual style used is based upon the effective default style', -> style.define 'default', background: '#112233' style.define 'other_default', background: '#111111' style.define 'custom', color: '#beefed' sci2 = Scintilla! buffer2 = Buffer {}, sci2 style.register_sci sci2, 'other_default' style_number = style.number_for 'custom', buffer assert.equal '#112233', sci\style_get_back style_number style_number = style.number_for 'custom', buffer2 assert.equal '#111111', sci2\style_get_back style_number it 'redefining a default style causes other styles to be rebased upon that', -> style.define 'own_style', color: '#334455' custom_number = style.number_for 'own_style', buffer default_number = style.number_for 'default', buffer style.define 'default', background: '#998877' -- background should be changed.. custom_back = sci\style_get_back custom_number assert.equal '#998877', custom_back -- ..but custom color should still be intact custom_fore = sci\style_get_fore custom_number assert.equal '#334455', custom_fore describe 'define_default(name, definition)', -> it 'defines the style only if it is not already defined', -> style.define_default 'preset', color: '#334455' assert.equal style.preset.color, '#334455' style.define_default 'preset', color: '#667788' assert.equal style.preset.color, '#334455' describe '.number_for(name, buffer [, base])', -> it 'returns the assigned style number for name in sci', -> assert.equal style.number_for('keyword'), 5 -- default keyword number it 'automatically assigns a style number and defines the style in scis if necessary', -> style.define 'my_style_a', color: '#334455' style.define 'my_style_b', color: '#334455' style_num = style.number_for 'my_style_a', buffer set_fore = sci\style_get_fore style_num assert.equal set_fore, '#334455' assert.is_not.equal style.number_for('my_style_b', buffer), style_num it 'remembers the style number used for a particular style', -> style.define 'got_it', color: '#334455' style_num = style.number_for 'got_it', buffer style_num2 = style.number_for 'got_it', buffer assert.equal style_num2, style_num it 'raises an error if the number of styles are #exhausted', -> for i = 1, 255 style.define 'my_style' .. i, color: '#334455' assert.raises 'Out of style number', -> for i = 1, 255 style.number_for 'my_style' .. i, buffer it 'returns the default style number if the style is not defined', -> assert.equal style.number_for('foo', {}), style.number_for('default', {}) it '.name_for(number, buffer, sci) returns the style name for number', -> assert.equal style.name_for(5, {}), 'keyword' -- default keyword number style.define 'whats_in_a_name', color: '#334455' style_num = style.number_for 'whats_in_a_name', buffer assert.equal style.name_for(style_num, buffer), 'whats_in_a_name' describe '.register_sci(sci, default_style)', -> it 'defines the default styles in the specified sci', -> t = theme.current t.styles.keyword = color: '#112233' style.set_for_theme t sci2 = Scintilla! buffer2 = Buffer {}, sci2 number = style.number_for 'keyword', buffer2 old = sci2\style_get_fore number style.register_sci sci2 new = sci2\style_get_fore number assert.is_not.equal new, old assert.equal new, t.styles.keyword.color it 'allows specifying a different default style through <default_style>', -> t = theme.current t.styles.keyword = color: '#223344' style.set_for_theme t sci2 = Scintilla! style.register_sci sci2, 'keyword' def_fore = sci2\style_get_fore style.number_for 'default', {} def_kfore = sci2\style_get_fore style.number_for 'keyword', {} assert.equal t.styles.keyword.color, def_fore it '.set_for_buffer(sci, buffer) initializes any previously used buffer styles', -> sci2 = Scintilla! style.register_sci sci2 style.define 'style_foo', color: '#334455' prev_number = style.number_for 'style_foo', buffer style.set_for_buffer sci2, buffer defined_fore = sci2\style_get_fore prev_number assert.equal defined_fore, '#334455' new_number = style.number_for 'style_foo', buffer assert.equal new_number, prev_number it '.at_pos(buffer, pos) returns name and style definition at pos', -> style.define 'stylish', color: '#101010' buffer = ActionBuffer! buffer\insert 'hƏllo', 1, 'keyword' buffer\insert 'Bačon', 6, 'stylish' name, def = style.at_pos(buffer, 5) assert.equal name, 'keyword' assert.same def, style.keyword name, def = style.at_pos(buffer, 6) assert.equal name, 'stylish' assert.same def, style.stylish context '(extended styles)', -> before_each -> style.define 'my_base', background: '#112233' style.define 'my_style', color: '#334455' describe '.number_for(name, buffer, base)', -> context 'when base is specified', -> it 'automatically defines an extended style based upon the base and specified style', -> style_num = style.number_for 'my_style', buffer, 'my_base' set_fore = sci\style_get_fore style_num set_back = sci\style_get_back style_num assert.equal set_fore, '#334455' assert.equal set_back, '#112233' assert.is_not_nil style['my_base:my_style'] it 'returns the base style if the specified style is not found', -> style_num = style.number_for 'my_unknown_style', buffer, 'my_base' assert.equal style.number_for('my_base', buffer), style_num context 'when <name> itself specifies an extended style', -> it 'extracts the base automatically', -> style.define 'my_other_base', background: '#112244' style_num = style.number_for 'my_other_base:my_style', buffer set_fore = sci\style_get_fore style_num set_back = sci\style_get_back style_num assert.equal '#334455', set_fore assert.equal '#112244', set_back assert.is_not_nil style['my_other_base:my_style'] context 'when one of composing styles is redefined', -> it 'updates the extended style definition', -> style_num = style.number_for 'my_style', buffer, 'my_base' style.define 'my_base', background: '#222222' assert.equal '#222222', style['my_base:my_style'].background style.define 'my_style', color: '#222222' assert.equal '#222222', style['my_base:my_style'].color set_fore = sci\style_get_fore style_num set_back = sci\style_get_back style_num assert.equal set_fore, '#222222' assert.equal set_back, '#222222' it 'redefining a default style also rebases extended styles', -> style_num = style.number_for 'my_style', buffer, 'my_base' assert.is_false sci\style_get_bold style_num style.define 'default', font: bold: true -- font should be bold now assert.is_true sci\style_get_bold style_num -- ..but custom color should still be intact assert.equal '#112233', sci\style_get_back style_num
39.211207
96
0.676047
ae6d8fd5de96a52288dd0bdf4059e98ee28ca061
13,787
socket = require "pgmoon.socket" import insert from table import rshift, lshift, band from require "bit" unpack = table.unpack or unpack VERSION = "1.10.0" _len = (thing, t=type(thing)) -> switch t when "string" #thing when "table" l = 0 for inner in *thing inner_t = type inner if inner_t == "string" l += #inner else l += _len inner, inner_t l else error "don't know how to calculate length of #{t}" _debug_msg = (str) -> require("moon").dump [p for p in str\gmatch "[^%z]+"] flipped = (t) -> keys = [k for k in pairs t] for key in *keys t[t[key]] = key t MSG_TYPE = flipped { status: "S" auth: "R" backend_key: "K" ready_for_query: "Z" query: "Q" notice: "N" notification: "A" password: "p" row_description: "T" data_row: "D" command_complete: "C" error: "E" } ERROR_TYPES = flipped { severity: "S" code: "C" message: "M" position: "P" detail: "D" schema: "s" table: "t" constraint: "n" } PG_TYPES = { [16]: "boolean" [17]: "bytea" [20]: "number" -- int8 [21]: "number" -- int2 [23]: "number" -- int4 [700]: "number" -- float4 [701]: "number" -- float8 [1700]: "number" -- numeric [114]: "json" -- json [3802]: "json" -- jsonb -- arrays [1000]: "array_boolean" -- bool array [1005]: "array_number" -- int2 array [1007]: "array_number" -- int4 array [1016]: "array_number" -- int8 array [1021]: "array_number" -- float4 array [1022]: "array_number" -- float8 array [1231]: "array_number" -- numeric array [1009]: "array_string" -- text array [1015]: "array_string" -- varchar array [1002]: "array_string" -- char array [1014]: "array_string" -- bpchar array [2951]: "array_string" -- uuid array [199]: "array_json" -- json array [3807]: "array_json" -- jsonb array } NULL = "\0" tobool = (str) -> str == "t" class Postgres convert_null: false NULL: {"NULL"} :PG_TYPES user: "postgres" host: "127.0.0.1" port: "5432" ssl: false -- custom types supplementing PG_TYPES type_deserializers: { json: (val, name) => import decode_json from require "pgmoon.json" decode_json val bytea: (val, name) => @decode_bytea val array_boolean: (val, name) => import decode_array from require "pgmoon.arrays" decode_array val, tobool array_number: (val, name) => import decode_array from require "pgmoon.arrays" decode_array val, tonumber array_string: (val, name) => import decode_array from require "pgmoon.arrays" decode_array val array_json: (val, name) => import decode_array from require "pgmoon.arrays" import decode_json from require "pgmoon.json" decode_array val, decode_json hstore: (val, name) => import decode_hstore from require "pgmoon.hstore" decode_hstore val } set_type_oid: (oid, name) => unless rawget(@, "PG_TYPES") @PG_TYPES = {k,v for k,v in pairs @PG_TYPES} @PG_TYPES[assert tonumber oid] = name setup_hstore: => res = unpack @query "SELECT oid FROM pg_type WHERE typname = 'hstore'" assert res, "hstore oid not found" @set_type_oid tonumber(res.oid), "hstore" new: (opts) => @sock, @sock_type = socket.new opts and opts.socket_type if opts @user = opts.user @host = opts.host @database = opts.database @port = opts.port @password = opts.password @ssl = opts.ssl @ssl_verify = opts.ssl_verify @ssl_required = opts.ssl_required @pool_name = opts.pool @luasec_opts = { key: opts.key cert: opts.cert cafile: opts.cafile } connect: => opts = if @sock_type == "nginx" { pool: @pool_name or "#{@host}:#{@port}:#{@database}:#{@user}" } ok, err = @sock\connect @host, @port, opts return nil, err unless ok if @sock\getreusedtimes! == 0 if @ssl success, err = @send_ssl_message! return nil, err unless success success, err = @send_startup_message! return nil, err unless success success, err = @auth! return nil, err unless success success, err = @wait_until_ready! return nil, err unless success true settimeout: (...) => @sock\settimeout ... disconnect: => sock = @sock @sock = nil sock\close! keepalive: (...) => sock = @sock @sock = nil sock\setkeepalive ... auth: => t, msg = @receive_message! return nil, msg unless t unless MSG_TYPE.auth == t @disconnect! if MSG_TYPE.error == t return nil, @parse_error msg error "unexpected message during auth: #{t}" auth_type = @decode_int msg, 4 switch auth_type when 0 -- trust true when 3 -- cleartext password @cleartext_auth msg when 5 -- md5 password @md5_auth msg else error "don't know how to auth: #{auth_type}" cleartext_auth: (msg) => assert @password, "missing password, required for connect" @send_message MSG_TYPE.password, { @password NULL } @check_auth! md5_auth: (msg) => import md5 from require "pgmoon.crypto" salt = msg\sub 5, 8 assert @password, "missing password, required for connect" @send_message MSG_TYPE.password, { "md5" md5 md5(@password .. @user) .. salt NULL } @check_auth! check_auth: => t, msg = @receive_message! return nil, msg unless t switch t when MSG_TYPE.error nil, @parse_error msg when MSG_TYPE.auth true else error "unknown response from auth" query: (q) => if q\find NULL return nil, "invalid null byte in query" @post q local row_desc, data_rows, command_complete, err_msg local result, notifications num_queries = 0 while true t, msg = @receive_message! return nil, msg unless t switch t when MSG_TYPE.data_row data_rows or= {} insert data_rows, msg when MSG_TYPE.row_description row_desc = msg when MSG_TYPE.error err_msg = msg when MSG_TYPE.command_complete command_complete = msg next_result = @format_query_result row_desc, data_rows, command_complete num_queries += 1 if num_queries == 1 result = next_result elseif num_queries == 2 result = { result, next_result } else insert result, next_result row_desc, data_rows, command_complete = nil when MSG_TYPE.ready_for_query break when MSG_TYPE.notification notifications = {} unless notifications insert notifications, @parse_notification(msg) -- when MSG_TYPE.notice -- TODO: do something with notices if err_msg return nil, @parse_error(err_msg), result, num_queries, notifications result, num_queries, notifications post: (q) => @send_message MSG_TYPE.query, {q, NULL} wait_for_notification: => while true t, msg = @receive_message! return nil, msg unless t switch t when MSG_TYPE.notification return @parse_notification(msg) format_query_result: (row_desc, data_rows, command_complete) => local command, affected_rows if command_complete command = command_complete\match "^%w+" affected_rows = tonumber command_complete\match "%d+%z$" if row_desc return {} unless data_rows fields = @parse_row_desc row_desc num_rows = #data_rows for i=1,num_rows data_rows[i] = @parse_data_row data_rows[i], fields if affected_rows and command != "SELECT" data_rows.affected_rows = affected_rows return data_rows if affected_rows { :affected_rows } else true parse_error: (err_msg) => local severity, message, detail, position error_data = {} offset = 1 while offset <= #err_msg t = err_msg\sub offset, offset str = err_msg\match "[^%z]+", offset + 1 break unless str offset += 2 + #str if field = ERROR_TYPES[t] error_data[field] = str switch t when ERROR_TYPES.severity severity = str when ERROR_TYPES.message message = str when ERROR_TYPES.position position = str when ERROR_TYPES.detail detail = str msg = "#{severity}: #{message}" if position msg = "#{msg} (#{position})" if detail msg = "#{msg}\n#{detail}" msg, error_data parse_row_desc: (row_desc) => num_fields = @decode_int row_desc\sub(1,2) offset = 3 fields = for i=1,num_fields name = row_desc\match "[^%z]+", offset offset += #name + 1 -- 4: object id of table -- 2: attribute number of column (4) -- 4: object id of data type (6) data_type = @decode_int row_desc\sub offset + 6, offset + 6 + 3 data_type = @PG_TYPES[data_type] or "string" -- 2: data type size (10) -- 4: type modifier (12) -- 2: format code (16) -- we only know how to handle text format = @decode_int row_desc\sub offset + 16, offset + 16 + 1 assert 0 == format, "don't know how to handle format" offset += 18 {name, data_type} fields parse_data_row: (data_row, fields) => -- 2: number of values num_fields = @decode_int data_row\sub(1,2) out = {} offset = 3 for i=1,num_fields field = fields[i] continue unless field {field_name, field_type} = field -- 4: length of value len = @decode_int data_row\sub offset, offset + 3 offset += 4 if len < 0 out[field_name] = @NULL if @convert_null continue value = data_row\sub offset, offset + len - 1 offset += len switch field_type when "number" value = tonumber value when "boolean" value = value == "t" when "string" nil else if fn = @type_deserializers[field_type] value = fn @, value, field_type out[field_name] = value out parse_notification: (msg) => pid = @decode_int msg\sub 1, 4 offset = 4 channel, payload = msg\match "^([^%z]+)%z([^%z]*)%z$", offset + 1 unless channel error "parse_notification: failed to parse notification" { operation: "notification" pid: pid channel: channel payload: payload } wait_until_ready: => while true t, msg = @receive_message! return nil, msg unless t if MSG_TYPE.error == t @disconnect! return nil, @parse_error(msg) break if MSG_TYPE.ready_for_query == t true receive_message: => t, err = @sock\receive 1 unless t @disconnect! return nil, "receive_message: failed to get type: #{err}" len, err = @sock\receive 4 unless len @disconnect! return nil, "receive_message: failed to get len: #{err}" len = @decode_int len len -= 4 msg = @sock\receive len t, msg send_startup_message: => assert @user, "missing user for connect" assert @database, "missing database for connect" data = { @encode_int 196608 "user", NULL @user, NULL "database", NULL @database, NULL "application_name", NULL "pgmoon", NULL NULL } @sock\send { @encode_int _len(data) + 4 data } send_ssl_message: => success, err = @sock\send { @encode_int 8, @encode_int 80877103 } return nil, err unless success t, err = @sock\receive 1 return nil, err unless t if t == MSG_TYPE.status if @sock_type == "nginx" @sock\sslhandshake false, nil, @ssl_verify else @sock\sslhandshake @ssl_verify, @luasec_opts elseif t == MSG_TYPE.error or @ssl_required @disconnect! nil, "the server does not support SSL connections" else true -- no SSL support, but not required by client send_message: (t, data, len) => len = _len data if len == nil len += 4 -- includes the length of the length integer @sock\send { t @encode_int len data } decode_int: (str, bytes=#str) => switch bytes when 4 d, c, b, a = str\byte 1, 4 a + lshift(b, 8) + lshift(c, 16) + lshift(d, 24) when 2 b, a = str\byte 1, 2 a + lshift(b, 8) else error "don't know how to decode #{bytes} byte(s)" -- create big endian binary string of number encode_int: (n, bytes=4) => switch bytes when 4 a = band n, 0xff b = band rshift(n, 8), 0xff c = band rshift(n, 16), 0xff d = band rshift(n, 24), 0xff string.char d, c, b, a else error "don't know how to encode #{bytes} byte(s)" decode_bytea: (str) => if str\sub(1, 2) == '\\x' str\sub(3)\gsub '..', (hex) -> string.char tonumber hex, 16 else str\gsub '\\(%d%d%d)', (oct) -> string.char tonumber oct, 8 encode_bytea: (str) => string.format "E'\\\\x%s'", str\gsub '.', (byte) -> string.format '%02x', string.byte byte escape_identifier: (ident) => '"' .. (tostring(ident)\gsub '"', '""') .. '"' escape_literal: (val) => switch type val when "number" return tostring val when "string" return "'#{(val\gsub "'", "''")}'" when "boolean" return val and "TRUE" or "FALSE" error "don't know how to escape value: #{val}" __tostring: => "<Postgres socket: #{@sock}>" { :Postgres, new: Postgres, :VERSION }
22.826159
82
0.585044
f061a751a116ae611444491b769591a23326a8cd
116
TK = require "PackageToolkit" parent = ... members = { "_map", } return TK.module.subfunctions parent, members
16.571429
45
0.681034
b80f8391c85ecb52fb412a150c4339875979a879
1,808
import insert from table validate_functions = { exists: (input) -> input and input != "", "%s must be provided" file_exists: (input) -> type(input) == "table" and input.filename != "" and input.content != "", "Missing file" min_length: (input, len) -> #tostring(input or "") >= len, "%s must be at least #{len} chars" max_length: (input, len) -> #tostring(input or "") <= len, "%s must be at most #{len} chars" is_integer: (input) -> tostring(input)\match"^%d+$", "%s must be an integer" is_color: do hex = "[a-fA-f0-9]" three = "^##{hex\rep 3}$" six = "^##{hex\rep 6}$" (input) -> input = tostring(input) input\match(three) or input\match(six), "%s must be a color" equals: (input, value) -> input == value, "%s must match" one_of: (input, ...) -> choices = {...} for choice in *choices return true if input == choice false, "%s must be one of #{table.concat choices, ", "}" } test_input = (input, func, args) -> fn = assert validate_functions[func], "Missing validation function #{func}" args = {args} if type(args) != "table" fn input, unpack args validate = (object, validations) -> errors = {} for v in *validations key = v[1] error_msg = v[2] input = object[key] if v.optional continue unless validate_functions.exists input v.optional = nil for fn, args in pairs v continue unless type(fn) == "string" success, msg = test_input input, fn, args unless success insert errors, (error_msg or msg)\format key break next(errors) and errors assert_valid = (object, validations) -> errors = validate object, validations coroutine.yield "error", errors if errors { :validate, :assert_valid, :test_input, :validate_functions }
25.828571
91
0.611173
4be2836ae9522b15af1af2b5f3f5f961cc0d9cd5
5,483
import Completer, Buffer, completion from howl import Editor from howl.ui append = table.insert describe 'Completer', -> buffer = nil before_each -> buffer = Buffer {} describe '.complete(pos [, limit])', -> it 'instantiates completers once with (buffer, context)', -> buffer.text = 'mr.cat' factory = spy.new -> nil append buffer.completers, factory completer = Completer(buffer, 6) completer\complete 6 assert.spy(factory).was.called_with buffer, buffer\context_at 6 completer\complete 6 assert.spy(factory).was.called(1) it 'lookups completers in completion when they are specified as strings', -> buffer.text = 'yowser' factory = spy.new -> nil completion.register name: 'comp-name', :factory append buffer.completers, 'comp-name' completer = Completer(buffer, 3) assert.spy(factory).was.called it 'returns completions for completers in buffer and mode', -> mode = completers: { -> complete: -> { 'mode' } } buffer.mode = mode append buffer.completers, -> complete: -> { 'buffer' } completions = Completer(buffer, 1)\complete 1 assert.same completions, { 'buffer', 'mode' } it 'returns completions for mode even if buffer has no completers', -> mode = completers: { -> complete: -> { 'mode' } } buffer.mode = mode assert.same Completer(buffer, 1)\complete(1), { 'mode' } it 'returns the search string after the completions', -> mode = completers: { -> complete: -> { 'prefix' } } buffer.text = 'pre' buffer.mode = mode append buffer.completers, -> complete: -> { 'buffer' } _, search = Completer(buffer, 4)\complete 4 assert.same search, 'pre' it 'calls <completer.complete()> with (completer, context)', -> buffer.text = 'mr.cat' comp = complete: spy.new -> {} append buffer.completers, -> comp completer = Completer(buffer, 6) completer\complete 6 assert.spy(comp.complete).was.called_with comp, buffer\context_at 6 completer\complete 7 assert.spy(comp.complete).was.called_with comp, buffer\context_at 7 it 'returns completions from just one completer if completions.authoritive is set', -> append buffer.completers, -> complete: -> { 'one', authoritive: true } append buffer.completers, -> complete: -> { 'two' } completions = Completer(buffer, 1)\complete 1 assert.same { 'one' }, completions it 'merges duplicate completions from different completers', -> append buffer.completers, -> complete: -> { 'yes'} append buffer.completers, -> complete: -> { 'yes' } completions = Completer(buffer, 1)\complete 1 assert.same { 'yes' }, completions it 'gives a final boost to case-matching completions, all else equal', -> buffer.text = 'he' append buffer.completers, -> complete: -> { 'Hello', 'hello' } completions = Completer(buffer, 3)\complete 3 assert.same { 'hello', 'Hello' }, completions buffer.text = 'He' append buffer.completers, -> complete: -> { 'hello', 'Hello' } completions = Completer(buffer, 3)\complete 3 assert.same { 'Hello', 'hello' }, completions context 'limiting completions', -> it 'returns at most `completion_max_shown` completions', -> completions = ["cand-#{i}" for i = 1,15] append buffer.completers, -> complete: -> completions buffer.config.completion_max_shown = 3 actual = Completer(buffer, 1)\complete 1 assert.equal 3, #actual it 'returns at most <limit> completions if specified', -> completions = ["cand-#{i}" for i = 1,15] append buffer.completers, -> complete: -> completions actual = Completer(buffer, 1)\complete 1, 4 assert.equal 4, #actual it '.start_pos holds the start position for completing', -> buffer.text = 'oh cruel word' assert.equal 4, Completer(buffer, 9).start_pos describe 'accept(completion)', -> context 'when hungry_completion is true', -> it 'replaces the current word with <completion>', -> buffer.text = 'hello there' buffer.config.hungry_completion = true completer = Completer(buffer, 3) completer\accept 'hey', 3 assert.equal 'hey there', buffer.text context 'when hungry_completion is false', -> it 'inserts <completion> at the start position', -> buffer.text = 'hello there' buffer.config.hungry_completion = false completer = Completer(buffer, 7) completer\accept 'over', 7 assert.equal 'hello overthere', buffer.text it 'returns the position after the accepted completion', -> buffer.text = 'hello there' assert.equal 5, Completer(buffer, 4)\accept 'hƏlp', 4 context "(interacting with mode's .on_completion_accepted)", -> it "invokes it with (mode, completion, context) if present", -> mode = on_completion_accepted: spy.new -> nil buffer.mode = mode buffer.text = 'hello there' Completer(buffer, 4)\accept 'help', 4 assert.spy(mode.on_completion_accepted).was_called_with mode, 'help', buffer\context_at(5) it "uses it's return value as the position returned if it's a number", -> mode = on_completion_accepted: -> 6 buffer.mode = mode buffer.text = 'hello there' assert.equal 6, Completer(buffer, 4)\accept 'help', 4
40.021898
98
0.637972
b1d12a5d9b1a5a6d257dcf74a0a57c2e258c3e9d
3,443
-- Copyright 2014-2015 The Howl Developers -- License: MIT (see LICENSE.md at the top-level directory of the distribution) ffi = require 'ffi' require 'ljglibs.cdefs.cairo' core = require 'ljglibs.core' require 'ljglibs.cairo.pattern' C, gc = ffi.C, ffi.gc cairo_gc_ptr = (o) -> gc(o, C.cairo_destroy) core.define 'cairo_t', { properties: { line_width: { get: => tonumber C.cairo_get_line_width @ set: (width) => C.cairo_set_line_width @, width } clip_extents: => a = ffi.new 'double[4]' C.cairo_clip_extents @, a, a + 1, a + 2, a + 3 { x1: tonumber(a[0]), y1: tonumber(a[1]), x2: tonumber(a[2]), y2: tonumber(a[3]) } fill_extents: => a = ffi.new 'double[4]' C.cairo_fill_extents @, a, a + 1, a + 2, a + 3 { x1: tonumber(a[0]), y1: tonumber(a[1]), x2: tonumber(a[2]), y2: tonumber(a[3]) } status: => C.cairo_status @ operator: { get: => C.cairo_get_operator @ set: (operator) => C.cairo_set_operator @, operator } line_join: { get: => C.cairo_get_line_join @ set: (lj) => C.cairo_set_line_join @, lj } line_cap: { get: => C.cairo_get_line_cap @ set: (lc) => C.cairo_set_line_cap @, lc } dash: { get: => @get_dash! set: (a) => @set_dash a } dash_count: => tonumber C.cairo_get_dash_count(@) target: => C.cairo_get_target @ source: { get: => @get_source! set: (v) => @set_source v } has_current_point: => C.cairo_has_current_point(@) != 0 } create: (surface) -> cairo_gc_ptr C.cairo_create surface save: => C.cairo_save @ restore: => C.cairo_restore @ set_source: (source) => C.cairo_set_source @, source set_source_rgb: (r, g, b) => C.cairo_set_source_rgb @, r, g, b set_source_rgba: (r, g, b, a) => C.cairo_set_source_rgba @, r, g, b, a set_source_surface: (surface, x, y) => C.cairo_set_source_surface @, surface, x, y get_source: => src = C.cairo_get_source(@) gc(C.cairo_pattern_reference(src), C.cairo_pattern_destroy) set_dash: (dashes, offset = 1) => count = (#dashes - offset) + 1 a = ffi.new 'double[?]', count for i = 1, count a[i - 1] = dashes[offset + i - 1] C.cairo_set_dash @, a, count, 0 get_dash: => count = @dash_count return {} if count < 1 a = ffi.new 'double[?]', count C.cairo_get_dash @, a, nil dashes = {} for i = 1, count dashes[i] = a[i - 1] stroke: => C.cairo_stroke @ stroke_preserve: => C.cairo_stroke_preserve @ fill: => C.cairo_fill @ fill_preserve: => C.cairo_fill_preserve @ paint_with_alpha: (alpha) => C.cairo_paint_with_alpha @, alpha line_to: (x, y) => C.cairo_line_to @, x, y rel_line_to: (dx, dy) => C.cairo_rel_line_to @, dx, dy move_to: (x, y) => C.cairo_move_to @, x, y rel_move_to: (x, y) => C.cairo_rel_move_to @, x, y in_clip: (x, y) => C.cairo_in_clip(@, x, y) != 0 clip: => C.cairo_clip @ clip_preserve: => C.cairo_clip_preserve @ push_group: => C.cairo_push_group @ pop_group: => C.cairo_pop_group @ -- Path operations rectangle: (x, y, width, height) => C.cairo_rectangle @, x, y, width, height arc: (xc, yc, radius, angle1, angle2) => C.cairo_arc @, xc, yc, radius, angle1, angle2 close_path: => C.cairo_close_path @ new_path: => C.cairo_new_path @ -- Transformations translate: (tx, ty) => C.cairo_translate @, tx, ty }, (t, ...) -> t.create ...
27.544
88
0.602382
cf0bceebfa5f295f650794b2e3353ab9a64f2f3a
1,041
import app, signal, Project from howl import File from howl.io tstack = {} handler = (args) -> tstack[#tstack+1] = args.file if args.file.basename == '-' app.window\remove_view! if #app.window.views > 1 fn = tstack[#tstack-1] or File '.howl-proj' file = fn\open! app\open_file File '.howl-proj' unless tstack[#tstack-1] table.insert Project.roots, File '.' script = '' iscript = false for line in file\lines! continue if line\gsub("^%s*(.-)%s*$", "%1") == '' if iscript script ..= line .. '\n' elseif line == '!:' iscript = true else app\open_file fn.parent\join line app.window\remove_view! if #app.window.views > 1 app\close_buffer args.buffer if script != '' f = require('moonscript').loadstring script assert f f! signal.connect 'file-opened', handler { info: author: 'Ryan Gonzalez' description: 'An extended project system' license: 'MIT' unload: -> signal.disconnect 'file-opened', handler }
25.390244
60
0.604227
adccf4fb2225e55772f0789bc6015f118c3f1785
1,523
ffi = require 'ffi' core = require 'ljglibs.core' require 'ljglibs.cdefs.gtk' C = ffi.C core.auto_loading 'gtk', { constants: { prefix: 'GTK_' -- GtkStateFlags 'STATE_FLAG_NORMAL', 'STATE_FLAG_ACTIVE', 'STATE_FLAG_PRELIGHT', 'STATE_FLAG_SELECTED', 'STATE_FLAG_INSENSITIVE', 'STATE_FLAG_INCONSISTENT', 'STATE_FLAG_FOCUSED', -- GtkPositionType 'POS_LEFT', 'POS_RIGHT', 'POS_TOP', 'POS_BOTTOM' -- GtkOrientation 'ORIENTATION_HORIZONTAL', 'ORIENTATION_VERTICAL', -- GtkPackType 'PACK_START', 'PACK_END' -- GtkJustification 'JUSTIFY_LEFT' 'JUSTIFY_RIGHT' 'JUSTIFY_CENTER' 'JUSTIFY_FILL' -- GtkWindowPosition; 'WIN_POS_NONE' 'WIN_POS_CENTER' 'WIN_POS_MOUSE' 'WIN_POS_CENTER_ALWAYS' 'WIN_POS_CENTER_ON_PARENT' -- GtkAlign 'ALIGN_FILL', 'ALIGN_START', 'ALIGN_END', 'ALIGN_CENTER', 'ALIGN_BASELINE', -- GtkTargetFlags 'TARGET_SAME_APP', 'TARGET_SAME_WIDGET', 'TARGET_OTHER_APP', 'TARGET_OTHER_WIDGET', } cairo_should_draw_window: (cr, window) -> C.gtk_cairo_should_draw_window(cr, window) != 0 get_major_version: -> tonumber C.gtk_get_major_version! get_minor_version: -> tonumber C.gtk_get_minor_version! get_micro_version: -> tonumber C.gtk_get_micro_version! check_version: (major, minor = 0, micro = 0) -> result = C.gtk_check_version major, minor, micro if result != ffi.NULL ffi.string result else nil }
20.581081
57
0.665135
4e3a7311a18e90cd2f18706b4f27004d2b96c105
1,997
-- implement async or bulk logging http = require "mooncrafts.http" azt = require "mooncrafts.aztable" util = require "mooncrafts.util" log = require "mooncrafts.log" import from_json, to_json, table_clone from util local * -- number of items when flush -- currently set to 1 until we get azure bulk to work BUFFER_COUNT = 1 -- time between flush -- currently set to very low until we get azure bulk to work FLUSH_INTERVAL = 0.01 myopts = {} dolog = (rsp) => v = {} req = rsp.req logs = req.logs or {} req.logs = nil -- replace illegal forward slash char rk = "#{req.host} #{req.path}"\gsub("/", "$") time = os.time() btime = os.date("%Y%m%d%H%m%S",time) rtime = 99999999999999 - btime btime = os.date("%Y-%m-%d %H:%m:%S", time) rand = math.random(10, 1000) pk = "#{rtime}_#{btime} #{rand}" btime = os.date("%Y%m", time) table_name = "log#{btime}" opts = azt.item_create({ tenant: "a", table_name: table_name, rk: rk, pk: pk, account_name: myopts.account_name, account_key: myopts.account_key }) v.RowKey = rk v.PartitionKey = pk v.host = req.host v.path = req.path v.time = req.end - req.start v.req = to_json(req) v.err = tostring(rsp.err) v.code = rsp.code v.status = rsp.status v.headers = to_json(rsp.headers) v.body = rsp.body v.logs = to_json(logs) if (#logs > 0) opts.body = to_json(v) res = azt.request(opts, true) res class AsyncLogger new: (opts={:account_name, :account_key}) => assert(opts.account_name, "opts.account_name parameter is required") assert(opts.account_key, "opts.account_key parameter is required") myopts = opts dolog: dolog log: (rsp) => if (ngx) myrsp = table_clone(rsp) delay = math.random(10, 100) ok, err = ngx.timer.at(delay / 1000, dolog, self, myrsp) @ AsyncLogger
24.654321
72
0.594392
7cde8c2f1b82f4b9b22fa5039a0bbe8d62738a16
3,974
path = require "lapis.cmd.path" import get_free_port from require "lapis.cmd.util" class AttachedServer new: (@runner) => start: (environment, env_overrides) => @existing_config = if path.exists @runner.compiled_config_path path.read_file @runner.compiled_config_path @port = get_free_port! if type(environment) == "string" environment = require("lapis.config").get environment if env_overrides assert not getmetatable(env_overrides), "env_overrides already has metatable, aborting" environment = setmetatable env_overrides, __index: environment env = require "lapis.environment" env.push environment @runner\write_config_for environment, @\process_config pid = @runner\get_pid! @fresh = not pid if pid @runner\send_hup! else assert @runner\start_nginx true @wait_until_ready! wait_until: (server_status="open") => socket = require "socket" max_tries = 1000 while true sock = socket.connect "127.0.0.1", @port switch server_status when "open" if sock sock\close! break when "close" if sock sock\close! else break else error "don't know how to wait for #{server_status}" max_tries -= 1 if max_tries == 0 error "Timed out waiting for server to #{server_status}" socket.sleep 0.001 wait_until_ready: => @wait_until "open" wait_until_closed: => @wait_until "close" detach: => if @existing_config path.write_file @runner.compiled_config_path, @existing_config if @fresh @runner\send_term! @wait_until_closed! else @runner\send_hup! env = require "lapis.environment" env.pop! true exec: (lua_code) => assert loadstring lua_code -- syntax check code ltn12 = require "ltn12" http = require "socket.http" buffer = {} _, status = http.request { url: "http://127.0.0.1:#{@port}/run_lua" sink: ltn12.sink.table buffer source: ltn12.source.string lua_code headers: { "content-length": #lua_code } } unless status == 200 error "Failed to exec code on server, got: #{status}" table.concat buffer -- this inserts a special server block in the config that gives remote access -- to it over a special port/location. process_config: (cfg) => assert @port, "attached server doesn't have a port to bind rpc to" run_code_action = [[ ngx.req.read_body() -- hijack print to write to buffer local old_print = print local buffer = {} print = function(...) local str = table.concat({...}, "\t") io.stdout:write(str .. "\n") table.insert(buffer, str) end local success, err = pcall(loadstring(ngx.var.request_body)) if not success then ngx.status = 500 print(err) end ngx.print(table.concat(buffer, "\n")) print = old_print ]] -- escape for nginx config run_code_action = run_code_action\gsub("\\", "\\\\")\gsub('"', '\\"') test_server = [[ server { allow 127.0.0.1; deny all; listen ]] .. @port .. [[; location = /run_lua { client_body_buffer_size 10m; client_max_body_size 10m; content_by_lua " ]] .. run_code_action .. [[ "; } } ]] -- inject the lua path if @runner.base_path != "" default_path = os.getenv "LUA_PATH" default_cpath = os.getenv "LUA_CPATH" server_path = path.join @runner.base_path, "?.lua" server_cpath = path.join @runner.base_path, "?.so" test_server = " lua_package_path '#{server_path};#{default_path}'; lua_package_cpath '#{server_cpath};#{default_cpath}'; " .. test_server cfg\gsub "%f[%a]http%s-{", "http {\n" .. test_server { :AttachedServer }
24.530864
93
0.602919
57bf929abfa80a25908866c5ec76ed7b484d599c
3,053
howl.util.lpeg_lexer -> keyword = capture 'keyword', word { 'return', 'break', 'local', 'for', 'while', 'if', 'elseif', 'else', 'then', 'export', 'import', 'from', 'with', 'in', 'and', 'or', 'not', 'class', 'extends', 'super', 'do', 'using', 'switch', 'when', 'unless', 'continue' } comment = capture 'comment', P'--' * scan_until(eol) 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 = capture '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 }) operator = capture 'operator', any { S'+-*!\\/%^#=<>;:,.(){}[]', any { '~=', 'or=', 'and=' } } ident = (alpha + '_')^1 * (alpha + digit + '_')^0 identifier = capture 'identifier', ident member = capture 'member', (P'@' + 'self.') * ident^0 special = capture 'special', word { 'true', 'false', 'nil' } type_name = capture 'type', upper^1 * (alpha + digit + '_')^0 type_def = sequence { capture('keyword', 'class'), capture 'whitespace', blank^1, capture 'type_def', upper^1 * (alpha + digit + '_')^0 } lua_keywords = capture 'error', word { 'function', 'goto', 'end' } sq_string = span("'", "'", '\\') dq_string = span('"', '"', P'\\') long_string = span('[[', ']]', '\\') key = capture 'key', any { P':' * ident, ident * P':', (sq_string + dq_string) * P':' } ws = capture 'whitespace', blank^0 cdef = sequence { capture('identifier', 'ffi'), capture('operator', '.'), capture('identifier', 'cdef'), ws, any { sequence { capture('string', '[['), sub_lex('c', ']]'), capture('string', ']]')^-1, }, sequence { capture('string', '"'), sub_lex('c', '"'), capture('string', '"')^-1, }, sequence { capture('string', "'"), sub_lex('c', "'"), capture('string', "'")^-1, } } } P { 'all' all: any { number, key, V'string', comment, operator, special, type_def, keyword, member, type_name, lua_keywords, V'fdecl', cdef, identifier } string: any { capture 'string', any { sq_string, long_string } V'dq_string' } interpolation: #P'#' * (-P'}' * (V'all' + 1))^1 * capture('operator', '}') * V'dq_string_chunk' dq_string_chunk: capture('string', scan_to(P'"' + #P'#{', P'\\')) * V('interpolation')^0 dq_string: capture('string', '"') * (V'dq_string_chunk') fdecl: sequence { capture('fdecl', ident), ws, capture('operator', '='), ws, sequence({ capture('operator', '('), any({ -#P')' * operator, special, identifier, capture('whitespace', blank^1), number, V'string' })^0, capture('operator', ')'), ws, })^0, capture('operator', any('->', '=>')), } }
28.268519
102
0.488045
01ede10d77b62d1de87f1effaecfaf4df633a0de
4,822
-- Copyright (C) 2018-2020 DBotThePony -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -- of the Software, and to permit persons to whom the Software is furnished to do so, -- subject to the following conditions: -- The above copyright notice and this permission notice shall be included in all copies -- or substantial portions of the Software. -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, -- INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR -- PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE -- FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -- OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -- DEALINGS IN THE SOFTWARE. savedata = (ent) -> objects = [ent\GetPhysicsObjectNum(i) for i = 0, ent\GetPhysicsObjectCount() - 1] { ent, ent\GetPos(), ent\GetAngles() [obj\GetVelocity() for obj in *objects] [obj\GetPos() for obj in *objects] [obj\GetAngles() for obj in *objects] [obj\IsAsleep() for obj in *objects] [obj\IsMotionEnabled() for obj in *objects] } loaddata = (data) -> {ent, pos, angles, velt, post, angt, asleept, motiont} = data return if not IsValid(ent) objects = [ent\GetPhysicsObjectNum(i) for i = 0, ent\GetPhysicsObjectCount() - 1] ent\SetPos(pos) ent\SetAngles(angles) for i, obj in ipairs(objects) obj\SetVelocity(velt[i]) if velt[i] obj\SetPos(post[i]) if post[i] obj\SetAngles(angt[i]) if angt[i] if asleept[i] == true obj\Sleep() elseif asleept[i] == false obj\Wake() obj\EnableMotion(motiont[i]) if motiont[i] ~= nil snapshot = (ply, ent) -> if ply\GetInfoBool('dpp2_cl_physgun_undo_custom', true) ply.__dpp2_physgun_undo = ply.__dpp2_physgun_undo or {} if contraption = ent\DPP2GetContraption() table.insert(ply.__dpp2_physgun_undo, [savedata(ent) for ent in *contraption.ents when ent\IsValid()]) else table.insert(ply.__dpp2_physgun_undo, {savedata(ent)}) else if contraption = ent\DPP2GetContraption() data2 = [savedata(ent) for ent in *contraption.ents when ent\IsValid()] data = savedata(ent) undo.Create('Physgun') undo.SetPlayer(ply) undo.AddFunction(-> loaddata(data) for data in *data2) undo.Finish() else data = savedata(ent) undo.Create('Physgun') undo.SetPlayer(ply) undo.AddFunction(-> loaddata(data)) undo.Finish() PhysgunPickup = (ply = NULL, ent = NULL) -> return if not DPP2.PHYSGUN_UNDO\GetBool() return if not ply\GetInfoBool('dpp2_cl_physgun_undo', true) return if ent\IsPlayer() snapshot(ply, ent) return IsValid = FindMetaTable('Entity').IsValid invalidate_history_ticks = 0 player_GetAll = player.GetAll table_remove = table.remove EntityRemoved = (ent) -> return if invalidate_history_ticks >= 2 invalidate_history_ticks += 1 ProcessPhysgunInvalidate = -> return if invalidate_history_ticks <= 0 invalidate_history_ticks -= 1 for ply in *player_GetAll() if history = ply.__dpp2_physgun_undo for histroy_index = #history, 1, -1 history_entry = history[histroy_index] if #history_entry == 0 table_remove(history, histroy_index) else for entry_index = #history_entry, 1, -1 if not IsValid(history_entry[entry_index][1]) table_remove(history_entry, entry_index) if #history_entry == 0 table_remove(history, histroy_index) OnPhysgunReload = (physgun = NULL, ply = NULL) -> return if not DPP2.PHYSGUN_UNDO\GetBool() return if not ply\GetInfoBool('dpp2_cl_physgun_undo', true) return if not IsValid(ply) tr = ply\GetEyeTrace() return if not IsValid(tr.Entity) or tr.Entity\IsPlayer() ent = tr.Entity snapshot(ply, ent) return hook.Add 'PhysgunPickup', 'DPP2.PhysgunHistory', PhysgunPickup, 3 hook.Add 'OnPhysgunReload', 'DPP2.PhysgunHistory', OnPhysgunReload, 3 hook.Add 'EntityRemoved', 'DPP2.PhysgunHistory', EntityRemoved hook.Add 'Think', 'DPP2.ProcessPhysgunInvalidate', ProcessPhysgunInvalidate DPP2.cmd.undo_physgun = (args = {}) => if not @__dpp2_physgun_undo DPP2.LMessagePlayer(@, 'gui.dpp2.undo.physgun_nothing') return last = table.remove(@__dpp2_physgun_undo, #@__dpp2_physgun_undo) hit = false while last for entry in *last if IsValid(entry[1]) hit = true loaddata(entry) break if hit last = table.remove(@__dpp2_physgun_undo, #@__dpp2_physgun_undo) if hit DPP2.NotifyUndo(@, nil, 'gui.dpp2.undo.physgun') else DPP2.LMessagePlayer(@, 'gui.dpp2.undo.physgun_nothing')
32.146667
105
0.730195
e5f1f8453aa896066bbbeb6f0f9aa70ab905284b
30,465
class Curve extends Base new: (arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7) -> count = arg.length if count is 0 @_segment1 = Segment() @_segment2 = Segment() else if count is 1 -- Note: This copies src existing segments through bean getters @_segment1 = Segment(arg0.segment1) @_segment2 = Segment(arg0.segment2) else if count is 2 @_segment1 = Segment(arg0) @_segment2 = Segment(arg1) else point1 = nil handle1 = nil handle2 = nil point2 = nil if count is 4 point1 = arg0 handle1 = arg1 handle2 = arg2 point2 = arg3 else if count is 8 -- Convert getValue() array back to points and handles so we -- can create segments for those. point1 = [arg0, arg1] point2 = [arg6, arg7] handle1 = [arg2 - arg0, arg3 - arg1] handle2 = [arg4 - arg6, arg5 - arg7] @_segment1 = Segment(point1, nil, handle1) @_segment2 = Segment(point2, handle2, nil) _changed: => -- Clear cached values. delete @_length delete @_bounds getPoint1: => @_segment1._point setPoint1: (point) => point = Point\read(arg) @_segment1._point\set point.x, point.y getPoint2: => @_segment2._point setPoint2: (point) => point = Point\read(arg) @_segment2._point\set point.x, point.y getHandle1: => @_segment1._handleOut setHandle1: (point) => point = Point\read(arg) @_segment1\_handleOut.set point.x, point.y getHandle2: => @_segment2._handleIn setHandle2: (point) => point = Point\read(arg) @_segment2._handleIn\set point.x, point.y getSegment1: => @_segment1 getSegment2: => @_segment2 getPath: => @_path getIndex: => @_segment1._index getNext: => curves = @_path and @_path._curves curves and (curves[@_segment1._index + 1] or @_path._closed and curves[0]) or nil getPrevious: => curves = @_path and @_path._curves curves and (curves[@_segment1._index - 1] or @_path._closed and curves[curves.length - 1]) or null isSelected: => @getHandle1()\isSelected() and @getHandle2()\isSelected() setSelected: (selected) => @getHandle1()\setSelected selected @getHandle2()\setSelected selected getValues: => Curve\getValues @_segment1, @_segment2 getPoints: => -- Convert to array of absolute points coords = @getValues() points = [] i = 0 while i < 8 points\push Point(coords[i], coords[i + 1]) i += 2 points getLength: -> src = arg_[0] to = arg_[1] fullLength = arg_.length is 0 or src is 0 and to is 1 return @_length if fullLength and @_length? length = Curve\getLength(@getValues(), src, to) @_length = length if fullLength length getArea: => Curve\getArea @getValues() getPart: (src, to) => Curve(Curve\getPart(@getValues(), src, to)) isLinear: => @_segment1._handleOut\isZero() and @_segment2._handleIn\isZero() getIntersections: (curve) => Curve\getIntersections @getValues(), curve\getValues(), this, curve, [] reverse: => Curve(@_segment2\reverse(), @_segment1\reverse()) divide: (parameter) -> res = null -- Accept CurveLocation objects, and objects that act like them: parameter = parameter.parameter if parameter and parameter.curve is this if parameter > 0 and parameter < 1 parts = Curve\subdivide(@getValues(), parameter) isLinear = @isLinear() left = parts[0] right = parts[1] -- Write back the results: if !isLinear @_segment1._handleOut\set left[2] - left[0], left[3] - left[1] -- segment2 is the end segment. By inserting newSegment -- between segment1 and 2, 2 becomes the end segment. -- Convert absolute -> relative @_segment2._handleIn\set right[4] - right[6], right[5] - right[7] -- Create the new segment, convert absolute -> relative: x = left[6] y = left[7] segment = Segment(Point(x, y), not isLinear and Point(left[4] - x, left[5] - y), not isLinear and Point(right[2] - x, right[3] - y)) -- Insert it in the segments list, if needed: if @_path -- Insert at the end if this curve is a closing curve of a -- closed path, since otherwise it would be inserted at 0. if @_segment1._index > 0 and @_segment2._index is 0 @_path\add segment else @_path\insert @_segment2._index, segment -- The way Path--_add handles curves, this curve will always -- become the owner of the newly inserted segment. -- TODO: I expect this.getNext() to produce the correct result, -- but since we're inserting differently in _add (something -- linked with CurveLocation--divide()), this is not the case... res = @ -- this.getNext(); else -- otherwise create it src the result of split eend = @_segment2 @_segment2 = segment res = Curve(segment, eend) res split: (parameter) => (if @_path then @_path\split(@_segment1._index, parameter) else nil) clone: => Curve(@_segment1, @_segment2) @create: (path, segment1, segment2) => curve = Base\create(Curve) curve._path = path curve._segment1 = segment1 curve._segment2 = segment2 curve @getValues: (segment1, segment2) => p1 = segment1._point h1 = segment1._handleOut h2 = segment2._handleIn p2 = segment2._point [p1._x, p1._y, p1._x + h1._x, p1._y + h1._y, p2._x + h2._x, p2._y + h2._y, p2._x, p2._y] @evaluate: (v, offset, isParameter, ttype) => t = (if isParameter then offset else Curve\getParameterAt(v, offset, 0)) p1x = v[0] p1y = v[1] c1x = v[2] c1y = v[3] c2x = v[4] c2y = v[5] p2x = v[6] p2y = v[7] x = nil y = nil -- Handle special case at beginning / end of curve if ttype is 0 and (t is 0 or t is 1) x = (if t is 0 then p1x else p2x) y = (if t is 0 then p1y else p2y) else -- Calculate the polynomial coefficients. cx = 3 * (c1x - p1x) bx = 3 * (c2x - c1x) - cx ax = p2x - p1x - cx - bx cy = 3 * (c1y - p1y) by_ = 3 * (c2y - c1y) - cy ay = p2y - p1y - cy - by_ switch ttype when 0 -- point -- Calculate the curve point at parameter value t x = ((ax * t + bx) * t + cx) * t + p1x y = ((ay * t + by_) * t + cy) * t + p1y -- tangent, 1st derivative when 1, 2 -- normal, 1st derivative -- Prevent tangents and normals of length 0: -- http://stackoverflow.com/questions/10506868/ tMin = Numerical.TOLERANCE ----= if t < tMin and c1x is p1x and c1y is p1y or t > 1 - tMin and c2x is p2x and c2y is p2y x = c2x - c1x y = c2y - c1y else -- Simply use the derivation of the bezier function for both -- the x and y coordinates: x = (3 * ax * t + 2 * bx) * t + cx y = (3 * ay * t + 2 * by_) * t + cy when 3 -- curvature, 2nd derivative x = 6 * ax * t + 2 * bx y = 6 * ay * t + 2 * by_ -- The normal is simply the rotated tangent: (if type is 2 then Point(y, -x) else Point(x, y)) @subdivide: (v, t) => p1x = v[0] p1y = v[1] c1x = v[2] c1y = v[3] c2x = v[4] c2y = v[5] p2x = v[6] p2y = v[7] t = 0.5 if t is nil -- Triangle computation, with loops unrolled. u = 1 - t -- Interpolate src 4 to 3 points p3x = u * p1x + t * c1x p3y = u * p1y + t * c1y p4x = u * c1x + t * c2x p4y = u * c1y + t * c2y p5x = u * c2x + t * p2x p5y = u * c2y + t * p2y -- Interpolate src 3 to 2 points p6x = u * p3x + t * p4x p6y = u * p3y + t * p4y p7x = u * p4x + t * p5x p7y = u * p4y + t * p5y -- Interpolate src 2 points to 1 point p8x = u * p6x + t * p7x p8y = u * p6y + t * p7y -- We now have all the values we need to build the subcurves: -- left [[p1x, p1y, p3x, p3y, p6x, p6y, p8x, p8y], [p8x, p8y, p7x, p7y, p5x, p5y, p2x, p2y]] -- right solveCubic: (v, coord, val, roots) -> p1 = v[coord] c1 = v[coord + 2] c2 = v[coord + 4] p2 = v[coord + 6] c = 3 * (c1 - p1) b = 3 * (c2 - c1) - c a = p2 - p1 - c - b Numerical.solveCubic a, b, c, p1 - val, roots @getParameterOf: (v, x, y) => -- Handle beginnings and end seperately, as they are not detected -- sometimes. return 0 if math.abs(v[0] - x) < Numerical.TOLERANCE and math.abs(v[1] - y) < Numerical.TOLERANCE return 1 if math.abs(v[6] - x) < Numerical.TOLERANCE and math.abs(v[7] - y) < Numerical.TOLERANCE txs = [] tys = [] sx = Curve\solveCubic(v, 0, x, txs) sy = Curve\solveCubic(v, 1, y, tys) tx = nil ty = nil -- sx, sy == -1 means infinite solutions: -- Loop through all solutions for x and match with solutions for y, -- to see if we either have a matching pair, or infinite solutions -- for one or the other. cx = 0 while sx is -1 or cx < sx if sx is -1 or (tx = txs[cx++]) >= 0 and tx <= 1 cy = 0 while sy is -1 or cy < sy if sy is -1 or (ty = tys[cy++]) >= 0 and ty <= 1 -- Handle infinite solutions by assigning root of -- the other polynomial if sx is -1 tx = ty else ty = tx if sy is -1 -- Use average if we're within tolerance return (tx + ty) * 0.5 if math.abs(tx - ty) < Numerical.TOLERANCE -- Avoid endless loops here: If sx is infinite and there was -- no fitting ty, there's no solution for this bezier break if sx is -1 nil -- TODO: Find better name @getPart: (v, src, to) => v = Curve\subdivide(v, src)[1] if src > 0 -- Interpolate the parameter at 'to' in the new curve and -- cut there. v = Curve\subdivide(v, (to - src) / (1 - src))[0] if to < 1 -- [0] left v @isLinear: (v) => v[0] is v[2] and v[1] is v[3] and v[4] is v[6] and v[5] is v[7] @isFlatEnough: (v, tolerance) => -- Thanks to Kaspar Fischer and Roger Willcocks for the following: -- http://hcklbrrfnn.files.wordpress.com/2012/08/bez.pdf p1x = v[0] p1y = v[1] c1x = v[2] c1y = v[3] c2x = v[4] c2y = v[5] p2x = v[6] p2y = v[7] ux = 3 * c1x - 2 * p1x - p2x uy = 3 * c1y - 2 * p1y - p2y vx = 3 * c2x - 2 * p2x - p1x vy = 3 * c2y - 2 * p2y - p1y math.max(ux * ux, vx * vx) + math.max(uy * uy, vy * vy) < 10 * tolerance * tolerance @getArea: (v) => p1x = v[0] p1y = v[1] c1x = v[2] c1y = v[3] c2x = v[4] c2y = v[5] p2x = v[6] p2y = v[7] -- http://objectmix.com/graphics/133553-area-closed-bezier-curve.html (3.0 * c1y * p1x - 1.5 * c1y * c2x - 1.5 * c1y * p2x - 3.0 * p1y * c1x - 1.5 * p1y * c2x - 0.5 * p1y * p2x + 1.5 * c2y * p1x + 1.5 * c2y * c1x - 3.0 * c2y * p2x + 0.5 * p2y * p1x + 1.5 * p2y * c1x + 3.0 * p2y * c2x) / 10 @getBounds: (v) => min = v\slice(0, 2) -- Start with values of point1 max = min\slice() -- clone roots = [0, 0] i = 0 while i < 2 Curve\_addBounds v[i], v[i + 2], v[i + 4], v[i + 6], i, 0, min, max, roots i++ Rectangle(min[0], min[1], max[0] - min[0], max[1] - min[1]) @_getCrossings: (v, prev, x, y, roots) => -- Implementation of the crossing number algorithm: -- http://en.wikipedia.org/wiki/Point_in_polygon -- Solve the y-axis cubic polynomial for y and count all solutions -- to the right of x as crossings. -- Checks the y-slope between the current curve and the previous for a -- change of orientation, when a solution is found at t == 0 changesOrientation = (tangent) => Curve\evaluate(prev, 1, true, 1).y * tangent.y > 0 count = Curve\solveCubic(v, 1, y, roots) crossings = 0 tolerance = Numerical.TOLERANCE abs = math.abs if count is -1 -- Infinite solutions, so we have a horizontal curve. -- Find parameter through getParameterOf() roots[0] = Curve\getParameterOf(v, x, y) count = (if roots[0] isnt nil then 1 else 0) i = 0 while i < count t = roots[i] if t > -tolerance and t < 1 - tolerance pt = Curve\evaluate(v, t, true, 0) if x < pt.x + tolerance -- Pass 1 for Curve.evaluate() type to calculate tangent tan = Curve\evaluate(v, t, true, 1) -- Handle all kind of edge cases when points are on -- contours or rays are touching countours, to termine -- wether the crossing counts or not. -- See if the actual point is on the countour: if abs(pt.x - x) < tolerance -- Do not count the crossing if it is on the left hand -- side of the shape (tangent pointing upwards), since -- the ray will go out the other end, count as crossing -- there, and the point is on the contour, so to be -- considered inside. angle = tan\getAngle() -- Handle special case where point is on a corner, -- in which case this crossing is skipped if both -- tangents have the same orientation. continue if angle > -180 and angle < 0 and (t > tolerance or changesOrientation(tan)) else -- Skip touching stationary points: -- Check derivate for stationary points. If root is -- close to 0 and not changing vertical orientation -- from the previous curve, do not count this root, -- as it's touching a corner. continue if abs(tan.y) < tolerance or t < tolerance and not changesOrientation(tan) crossings++ i++ crossings @_addBounds: (v0, v1, v2, v3, coord, padding, min, max, roots) => -- Code ported and further optimised from: -- http://blog.hackers-cafe.net/2009/06/how-to-calculate-bezier-curves-bounding.html add = (value, padding) -> left = value - padding right = value + padding min[coord] = left if left < min[coord] max[coord] = right if right > max[coord] -- Calculate derivative of our bezier polynomial, divided by 3. -- Doing so allows for simpler calculations of a, b, c and leads to the -- same quadratic roots. a = 3 * (v1 - v2) - v0 + v3 b = 2 * (v0 + v2) - 4 * v1 c = v1 - v0 count = Numerical\solveQuadratic(a, b, c, roots) -- Add some tolerance for good roots, as t = 0 / 1 are added -- seperately anyhow, and we don't want joins to be added with -- radiuses in getStrokeBounds() tMin = Numerical.TOLERANCE ----= tMax = 1 - tMin -- Only add strokeWidth to bounds for points which lie within 0 < t < 1 -- The corner cases for cap and join are handled in getStrokeBounds() add v3, 0 i = 0 while i < count t = roots[i] u = 1 - t -- Test for good roots and only add to bounds if good. -- Calculate bezier polynomial at t. add u * u * u * v0 + 3 * u * u * t * v1 + 3 * u * t * t * v2 + t * t * t * v3, padding if tMin < t and t < tMax i++ @getParameterAt: (offset, start) => Curve\getParameterAt @getValues(), offset, (if start isnt nil then start else (if offset < 0 then 1 else 0)) @getParameterOf: (point) => point = Point\read(arg) Curve\getParameterOf @getValues(), point.x, point.y @getLocationAt: (offset, isParameter) => offset = @getParameterAt(offset) if !isParameter CurveLocation(@, offset) getNearestLocation: (point) => -- Accommodate imprecision in comparison refine = (t) -> if t >= 0 and t <= 1 dist = point\getDistance(Curve\evaluate(values, t, true, 0), true) if dist < minDist minDist = dist minT = t true point = Point\read(arg) values = @getValues() count = 100 tolerance = Numerical.TOLERANCE minDist = Infinity minT = 0 max = 1 + tolerance i = 0 while i <= count refine i / count i++ -- Now iteratively refine solution until we reach desired precision. step = 1 / (count * 2) step /= 2 if not refine(minT - step) and not refine(minT + step) while step > tolerance pt = Curve\evaluate(values, minT, true, 0) CurveLocation(@, minT, pt, null, null, null, point\getDistance(pt)) @getNearestPoint: (point) => @getNearestLocation(arg)\getPoint() @getLengthIntegrand: (v) => -- Calculate the coefficients of a Bezier derivative. p1x = v[0] p1y = v[1] c1x = v[2] c1y = v[3] c2x = v[4] c2y = v[5] p2x = v[6] p2y = v[7] ax = 9 * (c1x - c2x) + 3 * (p2x - p1x) bx = 6 * (p1x + c2x) - 12 * c1x cx = 3 * (c1x - p1x) ay = 9 * (c1y - c2y) + 3 * (p2y - p1y) by_ = 6 * (p1y + c2y) - 12 * c1y cy = 3 * (c1y - p1y) (t) -> -- Calculate quadratic equations of derivatives for x and y dx = (ax * t + bx) * t + cx dy = (ay * t + by_) * t + cy math.sqrt dx * dx + dy * dy @getIterations: (a, b) => -- Guess required precision based and size of range... -- TODO: There should be much better educated guesses for -- this. Also, what does this depend on? Required precision? math.max 2, math.min(16, math.ceil(math.abs(b - a) * 32)) @getLength: (v, a, b) => a = 0 if a is nil b = 1 if b is nil -- See if the curve is linear by checking p1 == c1 and p2 == c2 if v[0] is v[2] and v[1] is v[3] and v[6] is v[4] and v[7] is v[5] -- Straight line dx = v[6] - v[0] dy = v[7] - v[1] return (b - a) * math.sqrt(dx * dx + dy * dy) ds = getLengthIntegrand(v) Numerical\integrate ds, a, b, getIterations(a, b) @getParameterAt: (v, offset, start) => -- See if we're going forward or backward, and handle cases -- differently -- Use integrand to calculate both range length and part -- lengths in f(t) below. -- Get length of total range -- Use offset / rangeLength for an initial guess for t, to -- bring us closer: -- Iteratively calculate curve range lengths, and add them up, -- using integration precision depending on the size of the -- range. This is much faster and also more precise than not -- modifing start and calculating total length each time. f = (t) -> count = @getIterations(start, t) length += (if start < t then Numerical\integrate(ds, start, t, count) else -Numerical.integrate(ds, t, start, count)) start = t length - offset return start if offset is 0 forward = offset > 0 a = (if forward then start else 0) b = (if forward then 1 else start) offset = math.abs(offset) ds = getLengthIntegrand( v) rangeLength = Numerical\integrate(ds, a, b, @getIterations(a, b)) return (if forward then b else a) if offset >= rangeLength guess = offset / rangeLength length = 0 -- Initial guess for x Numerical\findRoot f, ds, (if forward then a + guess else b - guess), a, b, 16, Numerical.TOLERANCE @addLocation: (locations, curve1, t1, point1, curve2, t2, point2) => -- Avoid duplicates when hitting segments (closed paths too) first = locations[0] last = locations[locations.length - 1] locations\push CurveLocation(curve1, t1, point1, curve2, t2, point2) if (not first or not point1.equals(first._point)) and (not last or not point1\equals(last._point)) @addCurveIntersections: (v1, v2, curve1, curve2, locations, range1, range2, recursion) => if options.fatline -- NOTE: range1 and range1 are only used for recusion recursion = (recursion or 0) + 1 -- Avoid endless recursion. -- Perhaps we should fall back to a more expensive method after this, -- but so far endless recursion happens only when there is no real -- intersection and the infinite fatline continue to intersect with the -- other curve outside its bounds! return if recursion > 20 -- Set up the parameter ranges. range1 = range1 or [0, 1] range2 = range2 or [0, 1] -- Get the clipped parts from the original curve, to avoid cumulative -- errors part1 = Curve\getPart(v1, range1[0], range1[1]) part2 = Curve\getPart(v2, range2[0], range2[1]) iteration = 0 -- markCurve(part1, '--f0f', true); -- markCurve(part2, '--0ff', false); -- Loop until both parameter range converge. We have to handle the -- degenerate case seperately, where fat-line clipping can become -- numerically unstable when one of the curves has converged to a point -- and the other hasn't. while iteration++ < 20 -- First we clip v2 with v1's fat-line range = nil intersects1 = @clipFatLine(part1, part2, range = range2.slice()) intersects2 = 0 -- Stop if there are no possible intersections break if intersects1 is 0 if intersects1 > 0 -- Get the clipped parts from the original v2, to avoid -- cumulative errors range2 = range part2 = Curve\getPart(v2, range2[0], range2[1]) -- markCurve(part2, '--0ff', false); -- Next we clip v1 with nuv2's fat-line intersects2 = @clipFatLine(part2, part1, range = range1.slice()) -- Stop if there are no possible intersections break if intersects2 is 0 if intersects1 > 0 -- Get the clipped parts from the original v2, to avoid -- cumulative errors range1 = range part1 = Curve\getPart(v1, range1[0], range1[1]) -- markCurve(part1, '--f0f', true); -- Get the clipped parts from the original v1 -- Check if there could be multiple intersections if intersects1 < 0 or intersects2 < 0 -- Subdivide the curve which has converged the least from the -- original range [0,1], which would be the curve with the -- largest parameter range after clipping if range1[1] - range1[0] > range2[1] - range2[0] -- subdivide v1 and recurse t = (range1[0] + range1[1]) / 2 @addCurveIntersections v1, v2, curve1, curve2, locations, [range1[0], t], range2, recursion @addCurveIntersections v1, v2, curve1, curve2, locations, [t, range1[1]], range2, recursion break else -- subdivide v2 and recurse t = (range2[0] + range2[1]) / 2 @addCurveIntersections v1, v2, curve1, curve2, locations, range1, [range2[0], t], recursion @addCurveIntersections v1, v2, curve1, curve2, locations, range1, [t, range2[1]], recursion break -- We need to bailout of clipping and try a numerically stable -- method if both of the parameter ranges have converged reasonably -- well (according to Numerical.TOLERANCE). ----= if math.abs(range1[1] - range1[0]) <= Numerical.TOLERANCE and math.abs(range2[1] - range2[0]) <= Numerical.TOLERANCE t1 = (range1[0] + range1[1]) / 2 t2 = (range2[0] + range2[1]) / 2 @addLocation locations, curve1, t1, Curve\evaluate(v1, t1, true, 0), curve2, t2, Curve\evaluate(v2, t2, true, 0) break else ---- bounds1 = Curve\getBounds(v1) bounds2 = Curve\getBounds(v2) if bounds1\touches(bounds2) -- See if both curves are flat enough to be treated as lines, either -- because they have no control points at all, or are "flat enough" -- If the curve was flat in a previous iteration, we don't need to -- recalculate since it does not need further subdivision then. ----= if (Curve\isLinear(v1) or Curve\isFlatEnough(v1, Numerical.TOLERANCE)) and (Curve\isLinear(v2) or Curve\isFlatEnough(v2, Numerical.TOLERANCE)) -- See if the parametric equations of the lines interesct. @addLineIntersection v1, v2, curve1, curve2, locations else -- Subdivide both curves, and see if they intersect. -- If one of the curves is flat already, no further subdivion -- is required. v1s = Curve\subdivide(v1) v2s = Curve\subdivide(v2) i = 0 while i < 2 j = 0 while j < 2 Curve\getIntersections v1s[i], v2s[j], curve1, curve2, locations j++ i++ locations @addCurveLineIntersections = (v1, v2, curve1, curve2, locations) => flip = Curve\isLinear(v1) vc = (if flip then v2 else v1) vl = (if flip then v1 else v2) l1x = vl[0] l1y = vl[1] l2x = vl[6] l2y = vl[7] -- Rotate both curve and line around l1 so that line is on x axis lvx = l2x - l1x lvy = l2y - l1y -- Angle with x axis (1, 0) angle = math.atan2(-lvy, lvx) sin = math.sin(angle) cos = math.cos(angle) -- (rl1x, rl1y) = (0, 0) rl2x = lvx * cos - lvy * sin rl2y = lvy * cos + lvx * sin vcr = [] i = 0 while i < 8 x = vc[i] - l1x y = vc[i + 1] - l1y vcr\push x * cos - y * sin, y * cos + x * sin i += 2 roots = [] count = Curve\solveCubic(vcr, 1, 0, roots) -- NOTE: count could be -1 for inifnite solutions, but that should only -- happen with lines, in which case we should not be here. i = 0 while i < count t = roots[i] if t >= 0 and t <= 1 point = Curve\evaluate(vcr, t, true, 0) -- We do have a point on the infinite line. Check if it falls on -- the line *segment*. -- The actual intersection point @addLocation locations, (if flip then curve2 else curve1), t, Curve.evaluate(vc, t, true, 0), (if flip then curve1 else curve2) if point.x >= 0 and point.x <= rl2x i++ @addLineIntersection: (v1, v2, curve1, curve2, locations) => point = Line\intersect(v1[0], v1[1], v1[6], v1[7], v2[0], v2[1], v2[6], v2[7]) -- Passing null for parameter leads to lazy determination of parameter -- values in CurveLocation--getParameter() only once they are requested. @addLocation locations, curve1, null, point, curve2 if point if options.fatline clipFatLine: (v1, v2, range2) => p0x = v1[0] p0y = v1[1] p1x = v1[2] p1y = v1[3] p2x = v1[4] p2y = v1[5] p3x = v1[6] p3y = v1[7] q0x = v2[0] q0y = v2[1] q1x = v2[2] q1y = v2[3] q2x = v2[4] q2y = v2[5] q3x = v2[6] q3y = v2[7] getSignedDistance = Line\getSignedDistance d1 = getSignedDistance(p0x, p0y, p3x, p3y, p1x, p1y) or 0 d2 = getSignedDistance(p0x, p0y, p3x, p3y, p2x, p2y) or 0 factor = (if d1 * d2 > 0 then 3 / 4 else 4 / 9) dmin = factor * Math.min(0, d1, d2) dmax = factor * Math.max(0, d1, d2) dq0 = @getSignedDistance(p0x, p0y, p3x, p3y, q0x, q0y) dq1 = @getSignedDistance(p0x, p0y, p3x, p3y, q1x, q1y) dq2 = @getSignedDistance(p0x, p0y, p3x, p3y, q2x, q2y) dq3 = @getSignedDistance(p0x, p0y, p3x, p3y, q3x, q3y) return 0 if dmin > math.max(dq0, dq1, dq2, dq3) or dmax < math.min(dq0, dq1, dq2, dq3) hull = @getConvexHull(dq0, dq1, dq2, dq3) swap = nil if dq3 < dq0 swap = dmin dmin = dmax dmax = swap tmaxdmin = -Infinity tmin = Infinity tmax = -Infinity i = 0 l = hull.length while i < l p1 = hull[i] p2 = hull[(i + 1) % l] if p2[1] < p1[1] swap = p2 p2 = p1 p1 = swap x1 = p1[0] y1 = p1[1] x2 = p2[0] y2 = p2[1] inv = (y2 - y1) / (x2 - x1) if dmin >= y1 and dmin <= y2 ixdx = x1 + (dmin - y1) / inv tmin = ixdx if ixdx < tmin tmaxdmin = ixdx if ixdx > tmaxdmin if dmax >= y1 and dmax <= y2 ixdx = x1 + (dmax - y1) / inv tmax = ixdx if ixdx > tmax tmin = 0 if ixdx < tmin i++ if tmin isnt Infinity and tmax isnt -Infinity min = math.min(dmin, dmax) max = math.max(dmin, dmax) tmax = 1 if dq3 > min and dq3 < max tmin = 0 if dq0 > min and dq0 < max tmax = 1 if tmaxdmin > tmax v2tmin = range2[0] tdiff = range2[1] - v2tmin range2[0] = v2tmin + tmin * tdiff range2[1] = v2tmin + tmax * tdiff return 1 if (tdiff - (range2[1] - range2[0])) / tdiff >= 0.2 return -1 if Curve\getBounds(v1)\touches(Curve\getBounds(v2)) 0 getConvexHull = (dq0, dq1, dq2, dq3) -> p0 = [0, dq0] p1 = [1 / 3, dq1] p2 = [2 / 3, dq2] p3 = [1, dq3] getSignedDistance = Line\getSignedDistance dist1 = getSignedDistance(0, dq0, 1, dq3, 1 / 3, dq1) dist2 = getSignedDistance(0, dq0, 1, dq3, 2 / 3, dq2) return [p0, p1, p3, p2] if dist1 * dist2 < 0 pmax = nil cross = nil if math.abs(dist1) > math.abs(dist2) pmax = p1 cross = (dq3 - dq2 - (dq3 - dq0) / 3) * (2 * (dq3 - dq2) - dq3 + dq1) / 3 else pmax = p2 cross = (dq1 - dq0 + (dq0 - dq3) / 3) * (-2 * (dq0 - dq1) + dq0 - dq2) / 3 (if cross < 0 then [p0, pmax, p3] else [p0, p1, p2, p3]) @getIntersections: (v1, v2, curve1, curve2, locations) => linear1 = Curve\isLinear(v1) linear2 = Curve\isLinear(v2) -- Determine the correct intersection method based on values of -- linear1 & 2: ((if linear1 and linear2 then @addLineIntersection! else (if linear1 or linear2 then @addCurveLineIntersections() else @addCurveIntersections()))) v1, v2, curve1, curve2, locations locations
32.687768
224
0.56235
d1c87b85256e209abd0ba26d7d169e6fd54ca11b
5,974
export class Collider new: => @source_frame = Rectangle! @target_frame = Rectangle! @source_axis_frame = Rectangle! @target_axis_frame = Rectangle! @callback = nil @comparisons = 0 @solve_x_collision_callback = @\solve_x_collision @solve_y_collision_callback = @\solve_y_collision @overlap_against_bucket_callback = @\overlap_against_bucket @collide_against_bucket_callback = @\collide_against_bucket build: => -- abstract overlap: => -- abstract reset: => -- abstract add_all: (object, group) => if object.__type == "group" @add_all entity, group for entity in *object.members when entity.active and entity.exists elseif object != nil table.insert group, object solve_x_collision: (source, target) => return source\overlap target, @solve_x_collision_callback, true if source.__type == "tilemap" return target\overlap source, @solve_x_collision_callback, true if target.__type == "tilemap" sfx = source.x - source.previous.x tfx = target.x - target.previous.x @source_axis_frame.x = if source.x > source.previous.x then source.previous.x else source.x @source_axis_frame.y = source.previous.y @source_axis_frame.width = source.width + math.abs sfx @source_axis_frame.height = source.height @target_axis_frame.x = if target.x > target.previous.x then target.previous.x else target.x @target_axis_frame.y = target.previous.y @target_axis_frame.width = target.width + math.abs tfx @target_axis_frame.height = target.height overlap = 0 if (@source_axis_frame.x + @source_axis_frame.width - epsilon > @target_axis_frame.x) and (@source_axis_frame.x + epsilon < @target_axis_frame.x + @target_axis_frame.width) and (@source_axis_frame.y + @source_axis_frame.height - epsilon > @target_axis_frame.y) and (@source_axis_frame.y + epsilon < @target_axis_frame.y + @target_axis_frame.height) if sfx > tfx overlap = source.x + source.width - target.x source.touching.right = true target.touching.left = true elseif sfx < tfx overlap = source.x - target.width - target.x target.touching.right = true source.touching.left = true if overlap != 0 source.x -= overlap source.velocity.x = 0 target.velocity.x = 0 return true return false solve_y_collision: (source, target) => return source\overlap target, @solve_y_collision_callback, true if source.__type == "tilemap" return target\overlap source, @solve_y_collision_callback, true if target.__type == "tilemap" sfy = source.y - source.previous.y tfy = target.y - target.previous.y @source_axis_frame.x = source.x @source_axis_frame.y = if source.y > source.previous.y then source.previous.y else source.y @source_axis_frame.width = source.width @source_axis_frame.height = source.height + math.abs sfy @target_axis_frame.x = target.x @target_axis_frame.y = if target.y > target.previous.y then target.previous.y else target.y @target_axis_frame.width = target.width @target_axis_frame.height = target.height + math.abs tfy overlap = 0 if (@source_axis_frame.x + @source_axis_frame.width - epsilon > @target_axis_frame.x) and (@source_axis_frame.x + epsilon < @target_axis_frame.x + @target_axis_frame.width) and (@source_axis_frame.y + @source_axis_frame.height - epsilon > @target_axis_frame.y) and (@source_axis_frame.y + epsilon < @target_axis_frame.y + @target_axis_frame.height) if sfy > tfy overlap = source.y + source.height - target.y source.touching.down = true target.touching.up = true elseif sfy < tfy overlap = source.y - target.height - target.y source.touching.up = true target.touching.down = true if overlap != 0 source.y -= overlap source.velocity.y = 0 target.velocity.y = 0 return true return false build_frame: (frame, entity) => frame.x = if entity.x > entity.previous.x then entity.previous.x else entity.x frame.y = if entity.y > entity.previous.y then entity.previous.y else entity.y frame.width = entity.x + entity.width - frame.x frame.height = entity.y + entity.height - frame.y collide_against_bucket: (source, bucket) => return false if not source.solid or not source.active or not source.exists overlap_found = false @build_frame @source_frame, source for target in *bucket continue unless target.active and target.exists and target.solid and source != target @build_frame @target_frame, target if (@source_frame.x + @source_frame.width > @target_frame.x) and (@source_frame.x < @target_frame.x + @target_frame.width) and (@source_frame.y + @source_frame.height > @target_frame.y) and (@source_frame.y < @target_frame.y + @target_frame.height) if not target.phased and not source.phased collision_found = true if @solve_x_collision source, target @callback source, target if @callback for target in *bucket continue unless target.active and target.exists and target.solid and source != target @build_frame @target_frame, target if (@source_frame.x + @source_frame.width > @target_frame.x) and (@source_frame.x < @target_frame.x + @target_frame.width) and (@source_frame.y + @source_frame.height > @target_frame.y) and (@source_frame.y < @target_frame.y + @target_frame.height) if not target.phased and not source.phased collision_found = true if @solve_y_collision source, target @callback source, target if @callback overlap_found overlap_against_bucket: (source, bucket) => overlap_found = false @build_frame @source_frame, source for target in *bucket continue unless target.active and target.exists and target.solid and source != target @build_frame @target_frame, target if (@source_frame.x + @source_frame.width > @target_frame.x) and (@source_frame.x < @target_frame.x + @target_frame.width) and (@source_frame.y + @source_frame.height > @target_frame.y) and (@source_frame.y < @target_frame.y + @target_frame.height) @callback source, target if @callback overlap_found = true overlap_found
42.671429
350
0.73619
fc9a7124187dd00d6110a24d5ef3bd044b4801af
993
return (ASS, ASSFInst, yutilsMissingMsg, createASSClass, Functional, LineCollection, Line, logger, SubInspector, Yutils) -> {:list, :math, :string, :table, :unicode, :util, :re } = Functional class Sections tagMatchPattern = re.compile "\\\\[^\\\\\\(]+(?:\\([^\\)]+\\)?[^\\\\]*)?" @getTagOrCommentSection = (rawTags) => tags = @parseTags rawTags return ASS.Section.Comment rawTags if #tags == 0 and #rawTags > 0 tagSection = ASS.Section.Tag tags return tagSection @parseTags = (rawTags) => tags, t = {}, 1 return tags if #rawTags == 0 for match in tagMatchPattern\gfind rawTags tag, _, last = ASS\getTagFromString match tags[t] = tag t += 1 -- comments inside tag sections are read into ASS.Tag.Unknowns if last < #match afterStr = match\sub last + 1 tags[t] = ASS\createTag afterStr\sub(1,1)=="\\" and "unknown" or "junk", afterStr t += 1 return tags
33.1
123
0.591138
95904490de63491aa4615db395d2007dcc7c2fe8
872
describe "TableTypes", -> use "./libraries/moonmod-core/dist/moonmod-core.lua" dist -> use "./dist/moonmod-board-ui.lua" source -> use "./src/table/Table.moon" use "./src/table/RadialTable.moon" use "./src/table/GridTable.moon" use "./src/table/TableTypes.moon" it "enumerates the types of Table available in the game", -> assert.is.a.table TableTypes expectEntry = (name, type) -> assert.contains.key name, TableTypes assert.is.of.class type, TableTypes[name] expectEntry "SQUARE", RadialTable expectEntry "HEXAGON", RadialTable expectEntry "OCTAGON", RadialTable expectEntry "ROUND", RadialTable expectEntry "POKER", GridTable expectEntry "RECTANGLE", GridTable expectEntry "ROUND_GLASS", RadialTable expectEntry "CUSTOM_SQUARE", GridTable expectEntry "CUSTOM_RECTANGLE", GridTable
31.142857
62
0.698394
5431f7d3c30f832ee31e2df90e467bf6bbf5984b
316
export modinfo = { type: "command" desc: "Change Ambient" alias: {"ambient"} func: (Msg,Speaker) -> taaa = Split(Msg) light = Service"Lighting" light.Ambient = Color3.new(taaa[1], taaa[2], taaa[3]) light.OutdoorAmbient = Color3.new(taaa[1], taaa[2], taaa[3]) Output2("Changed ambient",{Colors.Green}) }
28.727273
62
0.664557
c686a266025b67dce8770bd6f36c60f966099f5c
153
parent = ... members = { "self", "equal_lists" "case" } M = {} for name in *members M[name] = require(parent.."._"..name)[name] return M
13.909091
47
0.542484
c3aee14bd7410a051306748d08ba063e1fe2e043
16,148
etlua = require 'etlua' stringy = require 'stringy' import aql, document_get from require 'lib.arango' import table_deep_merge, to_timestamp from require 'lib.utils' import http_get from require 'lib.http_client' import encode_with_secret from require 'lapis.util.encoding' import from_json, to_json, trim, unescape from require 'lapis.util' -------------------------------------------------------------------------------- splat_to_table = (splat, sep = '/') -> { k, v for k, v in splat\gmatch "#{sep}?(.-)#{sep}([^#{sep}]+)#{sep}?" } -------------------------------------------------------------------------------- escape_pattern = (text) -> str, _ = tostring(text)\gsub('([%[%]%(%)%+%-%*%%])', '%%%1') str -------------------------------------------------------------------------------- prepare_headers = (html, data, params)-> jshmac = stringy.split(encode_with_secret(data.layout.i_js, ''), ".")[2]\gsub("/", "-") csshmac = stringy.split(encode_with_secret(data.layout.i_css, ''), ".")[2]\gsub("/", "-") html = html\gsub('@js_vendors', "/#{params.lang}/#{data.layout._key}/vendors/#{jshmac}.js") html = html\gsub('@js', "/#{params.lang}/#{data.layout._key}/js/#{data.layout._rev}.js") html = html\gsub('@css_vendors', "/#{params.lang}/#{data.layout._key}/vendors/#{csshmac}.css") html = html\gsub('@css', "/#{params.lang}/#{data.layout._key}/css/#{data.layout._rev}.css") headers = "<title>#{data.item.name}</title>" if(data.item.og_title and data.item.og_title[params.lang]) headers = "<title>#{data.item.og_title[params.lang]}</title>" if(data.item.description and data.item.description[params.lang]) headers ..= "<meta name=\"description\" content=\"#{data.item.description[params.lang]}\" />" if(data.item.og_title and data.item.og_title[params.lang]) headers ..= "<meta property=\"og:title\" content=\"#{data.item.og_title[params.lang]}\" />" if(data.item.og_img and data.item.og_img[params.lang]) headers ..= "<meta property=\"og:image\" content=\"#{data.item.og_img[params.lang]}\" />" if(data.item.og_type and data.item.og_type[params.lang]) headers ..= "<meta property=\"og:type\" content=\"#{data.item.og_type[params.lang]}\" />" if(data.item.canonical and data.item.canonical[params.lang]) headers ..= "<link rel=\"canonical\" href=\"#{data.item.canonical[params.lang]}\" />" headers ..= "<meta property=\"og:url\" content=\"#{data.item.canonical[params.lang]}\" />" html\gsub('@headers', headers) -------------------------------------------------------------------------------- etlua2html = (json, partial, params, global_data) -> template = global_data.partials[partial.item._key] if template == nil template = etlua.compile(partial.item.html) global_data.partials[partial.item._key] = template success, data = pcall( template, { 'dataset': json, 'to_json': to_json, 'lang': params.lang, 'params': params, 'to_timestamp': to_timestamp } ) data -------------------------------------------------------------------------------- load_document_by_slug = (db_name, slug, object) -> request = "FOR item IN #{object} FILTER item.slug == @slug RETURN { item }" aql(db_name, request, { slug: slug })[1] -------------------------------------------------------------------------------- load_page_by_slug = (db_name, slug, lang, uselayout = true) -> request = "FOR item IN pages FILTER item.slug[@lang] == @slug " if uselayout == true request ..= 'FOR layout IN layouts FILTER layout._id == item.layout_id RETURN { item, layout }' else request ..= 'RETURN { item }' page = aql(db_name, request, { slug: slug, lang: lang })[1] if page publication = document_get(db_name, 'publications/pages_' .. page.item._key) if publication.code ~= 404 then page.item = publication.data page -------------------------------------------------------------------------------- page_info = (db_name, slug, lang) -> request = " FOR page IN pages FILTER page.slug[@lang] == @slug LET root = ( FOR folder IN folders FILTER folder.name == 'Root' AND folder.object_type == 'pages' RETURN folder )[0] FOR folder IN folders FILTER folder._key == (HAS(page, 'folder_key') ? page.folder_key : root._key) LET path = ( FOR v, e IN ANY SHORTEST_PATH folder TO root GRAPH 'folderGraph' FILTER HAS(v, 'ba_login') AND v.ba_login != '' RETURN v )[0] RETURN { page: UNSET(page, 'html'), folder: path == null ? folder : path }" aql(db_name, request, { slug: slug, lang: lang })[1] -------------------------------------------------------------------------------- load_dataset_by_slug = (db_name, slug, object, lang, uselayout = true) -> request = "FOR item IN datasets FILTER item.type == '#{object}' FILTER item.slug == @slug " request ..= 'RETURN { item }' dataset = aql(db_name, request, { slug: slug })[1] if dataset publication = document_get(db_name, 'publications/' .. object .. '_' .. dataset.item._key) if publication.code ~= 404 then dataset.item = publication.data dataset -------------------------------------------------------------------------------- -- dynamic_page : check all {{ .* }} and load layout dynamic_page = (db_name, data, params, global_data, history = {}, uselayout = true) -> html = to_json(data) if data page_builder = (data.layout and data.layout.page_builder) or 'page' page_partial = load_document_by_slug(db_name, page_builder, 'partials') global_data.page_partial = page_partial if uselayout html = prepare_headers(data.layout.html, data, params) if(data.item.raw_html and type(data.item.raw_html[params['lang']]) == 'string') html = html\gsub('@raw_yield', escape_pattern(data.item.raw_html[params['lang']])) else html = html\gsub('@raw_yield', '') json = data.item.html[params['lang']].json if(type(json) == 'table' and next(json) ~= nil) html = html\gsub('@yield', escape_pattern(etlua2html(json, page_partial, params, global_data))) else html = etlua2html(data.item.html.json, page_partial, params, global_data) html = html\gsub('@yield', '') html = html\gsub('@raw_yield', '') html -------------------------------------------------------------------------------- load_redirection = (db_name, params) -> request = ' FOR r IN redirections FILTER r.route == @slug LET spa = (FOR s IN spas FILTER s._id == r.spa_id RETURN s)[0] LET layout = (FOR l IN layouts FILTER l._id == r.layout_id RETURN l)[0] RETURN { item: r, spa_name: spa.name, layout } ' redirection = aql(db_name, request, { slug: params.slug })[1] if redirection ~= nil then if redirection.item.type == "spa" html = redirection.layout.html\gsub( '@yield', "<div class='#{redirection.item.class}'>{{ spa | #{redirection.spa_name} }}</div>" ) html = html\gsub('@raw_yield', '') prepare_headers(html, redirection, params) else nil -------------------------------------------------------------------------------- prepare_bindvars = (splat, aql_request, locale = nil) -> bindvar = { } bindvar['page'] = 1 if aql_request\find('@page') bindvar['lang'] = locale if locale and aql_request\find('@lang') for k, v in pairs(splat) do v = unescape(tostring(v)) v = tonumber(v) if v\match('^%d+$') bindvar[k] = v if aql_request\find('@' .. k) bindvar -------------------------------------------------------------------------------- dynamic_replace = (db_name, html, global_data, history, params) -> translations = global_data.trads aqls = global_data.aqls helpers = global_data.helpers splat = {} splat = splat_to_table(params.splat) if params.splat -- {{ lang }} html = html\gsub('{{ lang }}', params.lang) for widget in string.gmatch(html, '{{.-}}') do output, action, item, dataset = '', '', '', '' args, keywords = {}, {} widget_no_deco, _ = widget\gsub('{{ ', '')\gsub(' }}', '') table.insert(keywords, trim(k)) for i, k in pairs(stringy.split(widget_no_deco, '|')) action = keywords[1] if keywords[1] item = keywords[2] if keywords[2] dataset = keywords[3] if keywords[3] args = splat_to_table(keywords[4], '#') if keywords[4] -- {{ settings | key }} -- e.g. {{ settings | chatroom_url }} if action == 'settings' and from_json(global_data.settings[1].home)[item] output = from_json(global_data.settings[1].home)[item] -- {{ splat | key }} -- e.g. {{ splat | salon }} if action == 'splat' and splat[item] then output = splat[item] -- {{ html | key | field }} -- {{ html | key }} data will then come from params og_data.json -- Using og_data reduce http calls if action == 'html' if dataset ~= '' request = 'FOR item IN datasets FILTER item._id == @key ' request ..= 'RETURN item' object = aql(db_name, request, { key: 'datasets/' .. item })[1] output = etlua2html(object[dataset].json, global_data.page_partial, params, global_data) else if params.og_data output = etlua2html(params.og_data[item], global_data.page_partial, params, global_data) -- {{ page | <slug or field> (| <datatype>) }} -- e.g. {{ page | set_a_slug_here }} -- e.g. {{ page | slug | posts }} if action == 'page' if history[widget] == nil -- prevent stack level too deep history[widget] = true page_html = '' if dataset == '' page_html = dynamic_page( db_name, load_page_by_slug(db_name, item, 'pages', params.lang, false), params, global_data, history, false ) else if splat[item] then item = splat[item] page_html = dynamic_page( db_name, load_dataset_by_slug(db_name, item, dataset, params.lang), params, global_data, history, false ) output ..= dynamic_replace(db_name, page_html, global_data, history, params) -- {{ helper | shortcut }} -- e.g. {{ helper | hello_world }} if action == 'helper' helper = helpers[item] dataset = "##{dataset}" if dataset != '' output = "{{ partial | #{helper.partial} | arango | req##{helper.aql}#{dataset} }}" output = dynamic_replace(db_name, output, global_data, history, params) -- {{ partial | slug | <dataset> | <args> }} -- e.g. {{ partial | demo | arango | aql#FOR doc IN pages RETURN doc }} -- params splat will be used to provide data if arango dataset if action == 'partial' partial = load_document_by_slug(db_name, item, 'partials', false) if partial db_data = { "page": 1 } if dataset == 'arango' -- check if it's a stored procedure if args['req'] args['aql'] = aql( db_name, 'FOR aql IN aqls FILTER aql.slug == @slug RETURN aql.aql', { slug: args['req'] } )[1]\gsub('{{ lang }}', params.lang) -- prepare the bindvar variable with variable found in the request -- but also on the parameters sent as args bindvar = prepare_bindvars(table_deep_merge(splat, args), args['aql']) -- handle conditions __IF <bindvar> __ .... __END <bindvar>__ -- @bindvar must be present in the request for str in string.gmatch(args['aql'], '__IF (%w-)__') do unless bindvar[str] then args['aql'] = args['aql']\gsub('__IF ' .. str .. '__.-__END ' .. str .. '__', '') else args['aql'] = args['aql']\gsub('__IF ' .. str .. '__', '') args['aql'] = args['aql']\gsub('__END ' .. str .. '__', '') -- handle strs __IF_NOT <bindvar> __ .... __END_NOT <bindvar>__ for str in string.gmatch(args['aql'], '__IF_NOT (%w-)__') do if bindvar[str] then args['aql'] = args['aql']\gsub( '__IF_NOT ' .. str .. '__.-__END_NOT ' .. str .. '__', '' ) else args['aql'] = args['aql']\gsub('__IF_NOT ' .. str .. '__', '') args['aql'] = args['aql']\gsub('__END_NOT ' .. str .. '__', '') db_data = { results: aql(db_name, args['aql'], bindvar) } db_data = table_deep_merge(db_data, { _params: args }) if dataset == 'rest' db_data = from_json(http_get(args['url'], args['headers'])) if dataset == 'use_params' or args['use_params'] db_data = table_deep_merge(db_data, { _params: args }) if dataset != 'do_not_eval' output = etlua2html(db_data, partial, params, global_data) else output = partial.item.html output = dynamic_replace(db_name, output, global_data, history, params) -- {{ riot | slug(#slug2...) | <mount> }} -- e.g. {{ riot | demo | mount }} -- e.g. {{ riot | demo#demo2 }} if action == 'riot' if history[widget] == nil -- prevent stack level too deep history[widget] = true data = { ids: {}, revisions: {}, names: {} } for i, k in pairs(stringy.split(item, '#')) component = aql( db_name, 'FOR doc in components FILTER doc.slug == @slug RETURN doc', { "slug": k } )[1] table.insert(data.ids, component._key) table.insert(data.revisions, component._rev) table.insert(data.names, k) output ..= "<script src='/#{params.lang}/#{table.concat(data.ids, "-")}/component/#{table.concat(data.revisions, "-")}.tag' type='riot/tag'></script>" if dataset == 'mount' output ..= '<script>' output ..= "document.addEventListener('DOMContentLoaded', function() { riot.mount('#{table.concat(data.names, ", ")}') });" output ..= "document.addEventListener('turbolinks:load', function() { riot.mount('#{table.concat(data.names, ", ")}') });" output ..= '</script>' -- {{ spa | slug }} -- display a single page application -- e.g. {{ spa | account }} if action == 'spa' if history[widget] == nil -- prevent stack level too deep history[widget] = true spa = aql( db_name, 'FOR doc in spas FILTER doc.slug == @slug RETURN doc', { 'slug': item } )[1] output = spa.html output ..= "<script>#{spa.js}</script>" output = dynamic_replace(db_name, output, global_data, history, params) -- {{ aql | slug }} -- Run an AQL request -- e.g. {{ aql | activate_account }} if action == 'aql' aql_request = aql( db_name, 'FOR a in aqls FILTER a.slug == @slug RETURN a', { "slug": item } )[1] if aql_request aql(db_name, aql_request.aql, prepare_bindvars(splat, aql_request.aql)) -- {{ tr | slug }} -- e.g. {{ tr | my_text }} if action == 'tr' output = "Missing translation <em style='color:red'>#{item}</em>" unless translations[item] aql( db_name, 'INSERT { key: @key, value: { @lang: @key} } IN trads', { key: item, lang: params.lang } ) output = item if translations[item] and translations[item][params.lang] output = translations[item][params.lang] -- {{ external | url }} if action == 'external' output = http_get(item, {}) if action == 'external' -- {{ og_data | name }} if action == 'og_data' output = params.og_data[item] if params.og_data -- {{ dataset | key | field }} if action == 'dataset' item = stringy.split(item, "=") request = 'FOR item IN datasets FILTER item.@field == @value RETURN item' object = aql(db_name, request, { field: item[1], value: item[2] })[1] if object output = object[dataset] else output = ' ' html = html\gsub(escape_pattern(widget), escape_pattern(output)) if output ~= '' html -------------------------------------------------------------------------------- -- expose methods { :splat_to_table, :load_page_by_slug, :dynamic_page, :escape_pattern, :dynamic_replace, :load_redirection, :page_info, :prepare_bindvars }
43.525606
158
0.560131
c1089e1582a514783523c22a6c7e198df72227c5
1,442
file_util = require"file_util" moduleTemplate = [=[<roblox xmlns:xmime="http://www.w3.org/2005/05/xmlmime" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://www.roblox.com/roblox.xsd" version="4"> <External>null</External> <External>nil</External> <Item class="ModuleScript"> <Properties> <Content name="LinkedSource"><null></null></Content> <string name="Name">MainModule</string> <ProtectedString name="Source"><![CDATA[%s]]></ProtectedString> </Properties> <Item class="LocalScript"> <Properties> <bool name="Disabled">false</bool> <Content name="LinkedSource"><null></null></Content> <string name="Name">LocalScript</string> <ProtectedString name="Source"><![CDATA[%s]]></ProtectedString> </Properties> </Item> <Item class="Script"> <Properties> <bool name="Disabled">false</bool> <Content name="LinkedSource"><null></null></Content> <string name="Name">Script</string> <ProtectedString name="Source"><![CDATA[%s]]></ProtectedString> </Properties> </Item> </Item> </roblox>]=] M = {} M.getModule = (moduleSource, localScriptSource, scriptSource) -> file_util.writefile("bin/ModuleTemplate.rbxmx", moduleTemplate\format(moduleSource, localScriptSource, scriptSource)) os.execute("rbxplore --shell --format rbxm --output bin/ModuleTemplate.rbxm bin/ModuleTemplate.rbxmx") file_util.readfile("bin/ModuleTemplate.rbxm") M
36.05
207
0.70527
533b2c5038b9e4898d96dadedb0ab58e43e16035
240
export modinfo = { type: "command" desc: "Hack cba" alias: {"hcba"} func: (Msg, Speaker) -> CreateInstance"StringValue" Parent: workspace Name: "CBA Attachment" Value: "CBA.admins[#CBA.admins+1] = {'"..Speaker.Name.."',7}" }
21.818182
64
0.629167
d2b1d294184bf5be1ac92b1944df0fb3c384e754
2,733
import insert from table unpack = unpack or table.unpack validate_functions = { exists: (input) -> input and input != "", "%s must be provided" -- TODO: remove this in favor of is_file file_exists: (input) -> type(input) == "table" and input.filename != "" and input.content != "", "Missing file" min_length: (input, len) -> #tostring(input or "") >= len, "%s must be at least #{len} chars" max_length: (input, len) -> #tostring(input or "") <= len, "%s must be at most #{len} chars" is_file: (input) -> type(input) == "table" and input.filename != "" and input.content != "", "Missing file" is_integer: (input) -> tostring(input)\match"^%d+$", "%s must be an integer" is_color: do hex = "[a-fA-f0-9]" three = "^##{hex\rep 3}$" six = "^##{hex\rep 6}$" (input) -> input = tostring(input) input\match(three) or input\match(six), "%s must be a color" is_timestamp: (input) -> month = input and input\match "^%d+%-(%d+)%-(%d+)%s+(%d+):(%d+):(%d+)$" month != nil, "%s is not a valid timestamp" matches_pattern: (input, pattern) -> match = type(input) == "string" and input\match(pattern) or nil match != nil, "%s is not the right format" equals: (input, value) -> input == value, "%s must match" one_of: (input, ...) -> choices = {...} for choice in *choices return true if input == choice false, "%s must be one of #{table.concat choices, ", "}" type: (input, kind) -> return true if type(input) == kind false, "%s must be a " .. kind test: (input, fn) -> fn input } test_input = (input, func, args) -> fn = assert validate_functions[func], "Missing validation function #{func}" args = {args} if type(args) != "table" fn input, unpack args validate = (object, validations, opts = {}) -> errors = {} for v in *validations key = v[1] error_msg = v[2] input = object[key] if v.optional continue unless validate_functions.exists input v.optional = nil -- TODO: this processes validations in no particular order, which can be bad for tests for fn, args in pairs v continue unless type(fn) == "string" success, msg = test_input input, fn, args unless success if opts.keys and opts.keys == true errors[key] = (error_msg or msg)\format key else insert errors, (error_msg or msg)\format key break next(errors) and errors assert_valid = (object, validations) -> errors = validate object, validations if errors coroutine.yield "error", errors error "assert_valid was not captured: #{table.concat errors, ", "}" { :validate, :assert_valid, :test_input, :validate_functions }
28.175258
91
0.606659
ac56fd8b9c841d3887844614ab62f56e17a70cef
161
class new: (@x, @y, @w, @h) => draw: => with lg .setColor 100, 255, 255 .draw game.sprites.block[0], @x, @y apply: (thing) => 0, -12
14.636364
41
0.465839
d6b763a57ee08b9a9d122d0faa6d69a0a944797c
5
"0.2"
5
5
0.4
eb6ac257d7dc7a490b957907e45107de95c3296d
1,812
import printerr, to_lua, fnwrap, evalprint, init_moonpath, deinit_moonpath from require'moor.utils' -- lasting loop or not loopflag = true -- send 0 or 1 to `os.exit` at the end of repl exitcode = 0 eval_moon = (env, txt, non_verbose) -> lua_code, err = to_lua txt if err then nil, err else evalprint env, lua_code, non_verbose nextagen = => -> table.remove @, 1 msg = -> printerr 'Usage: moonr [options]\n', '\n', ' -h print this message\n', ' -e STR execute string as MoonScript code and exit\n', ' -E STR execute string as MoonScript code and run REPL\n', ' -l LIB load library before running REPL\n', ' -L LIB execute `LIB = require"LIB"` before running REPL\n', '' loopflag = false exitcode = 1 loadlib = (env, lib) -> ok, cont = eval_moon env, "return require '#{lib}'", true unless ok printerr cont msg! cont evalline = (env, line) -> ok, err = eval_moon env, line unless ok printerr err msg! (env, arg) -> local is_exit is_splash = true nexta = nextagen arg while loopflag a = nexta! break unless a flag, rest = a\match '^%-(%a)(.*)' unless flag printerr "Failed to parse argument: #{a}" msg! lstuff = #rest > 0 and rest or nexta! switch flag when 'l' loadlib env, lstuff when 'L' if lib = loadlib env, lstuff env[rest] = lib when 'e' is_exit = true is_splash = evalline env, lstuff when 'E' is_splash = evalline env, lstuff else if "#{flag}#{rest}" == "no-splash" then is_splash = false else printerr "invlid flag: #{flag}" unless flag == "h" is_splash = msg! is_exit = true printerr "moor on MoonScript version #{(require 'moonscript.version').version} on #{_VERSION}" if is_splash env.MOOR_EXITCODE = exitcode not is_exit
20.590909
108
0.634658
ceac0b5afa4455f9ea13e25bd7abe5125143c917
1,709
-- Copyright 2012-2015 The Howl Developers -- License: MIT (see LICENSE.md at the top-level directory of the distribution) {:List, :ListWidget, :Popup} = howl.ui {:bindings, :config} = howl class MenuPopup extends Popup new: (@items, @callback) => error('Missing argument #1: items', 3) if not @items error('Missing argument #2: callback', 3) if not @callback @list = List -> @items @list_widget = ListWidget @list, auto_fit_width: true @highlight_matches_for = '' super @list_widget\to_gobject! with @child .margin_top = 2 .margin_left = 2 @list_widget\show! refresh: => @list\update @highlight_matches_for show: (...) => @refresh! super ... @resize! resize: => h_margin = @child.margin_left + @child.margin_right v_margin = @child.margin_top + @child.margin_bottom super @list_widget.width + h_margin, @list_widget.height + v_margin choose: => if self.callback @list.selection @close! keymap: { down: => @list\select_next! ctrl_n: => @list\select_next! up: => @list\select_prev! ctrl_p: => @list\select_prev! page_down: => @list\next_page! page_up: => @list\prev_page! on_unhandled: (event, source, translations, self) -> -- if a bare modifier such as just 'ctrl', don't close popup return if bindings.is_modifier translations -- any other not character such as home or escape closes the popup unless event.character self\close! tab: => if config.popup_menu_accept_key == 'tab' @choose! else false return: => if config.popup_menu_accept_key == 'enter' @choose! else false }
25.507463
79
0.633704
84dfeb20e91373bfceda0b1448466818c5d788bd
3,041
ffi = require 'ffi' lpeg = require 'lpeg' formatc = require 'test.unit.formatc' Set = require 'test.unit.set' Preprocess = require 'test.unit.preprocess' Paths = require 'test.config.paths' -- add some standard header locations for i,p in ipairs(Paths.include_paths) Preprocess.add_to_include_path(p) -- load neovim shared library libnvim = ffi.load Paths.test_libnvim_path trim = (s) -> s\match'^%s*(.*%S)' or '' -- a Set that keeps around the lines we've already seen export cdefs if cdefs == nil cdefs = Set! export imported if imported == nil imported = Set! -- some things are just too complex for the LuaJIT C parser to digest. We -- usually don't need them anyway. filter_complex_blocks = (body) -> result = {} for line in body\gmatch("[^\r\n]+") -- remove all lines that contain Objective-C block syntax, the LuaJIT ffi -- doesn't understand it. if string.find(line, "(^)", 1, true) ~= nil continue if string.find(line, "_ISwupper", 1, true) ~= nil continue result[#result + 1] = line table.concat(result, "\n") -- use this helper to import C files, you can pass multiple paths at once, -- this helper will return the C namespace of the nvim library. -- cimport = (path) -> cimport = (...) -> -- filter out paths we've already imported paths = [path for path in *{...} when not imported\contains(path)] for path in *paths imported\add(path) if #paths == 0 return libnvim -- preprocess the header stream = Preprocess.preprocess_stream(unpack(paths)) body = stream\read("*a") stream\close! -- format it (so that the lines are "unique" statements), also filter out -- Objective-C blocks body = formatc(body) body = filter_complex_blocks(body) -- add the formatted lines to a set new_cdefs = Set! for line in body\gmatch("[^\r\n]+") new_cdefs\add(trim(line)) -- subtract the lines we've already imported from the new lines, then add -- the new unique lines to the old lines (so they won't be imported again) new_cdefs\diff(cdefs) cdefs\union(new_cdefs) if new_cdefs\size! == 0 -- if there's no new lines, just return return libnvim -- request a sorted version of the new lines (same relative order as the -- original preprocessed file) and feed that to the LuaJIT ffi new_lines = new_cdefs\to_table! ffi.cdef(table.concat(new_lines, "\n")) return libnvim cppimport = (path) -> return cimport Paths.test_include_path .. '/' .. path cimport './src/nvim/types.h' -- take a pointer to a C-allocated string and return an interned -- version while also freeing the memory internalize = (cdata) -> ffi.gc cdata, ffi.C.free return ffi.string cdata cstr = ffi.typeof 'char[?]' to_cstr = (string) -> cstr (string.len string) + 1, string return { cimport: cimport cppimport: cppimport internalize: internalize eq: (expected, actual) -> assert.are.same expected, actual neq: (expected, actual) -> assert.are_not.same expected, actual ffi: ffi lib: libnvim cstr: cstr to_cstr: to_cstr }
27.396396
77
0.688918
67dcb23417033d034cd10a3fb5cd0cf8e01d1252
120
moon = require "moon" return (t) -> clone = class clone: => c = @@! moon.mixin_table c, @ moon.mixin t, clone
15
24
0.575
b9317de1baef5df541759b0921c80f70a38a4f86
2,139
import bindings from howl import getmetatable, setfenv, pairs, callable, print, tostring from _G _G = _G _ENV = {} setfenv 1, _ENV export mode, map export active = false export delete, change, yank, go export count, insert_edit local maps, last_op export has_modifier = -> delete or change or yank or go export reset = -> delete = false change = false yank = false count = nil go = nil bindings.cancel_capture! export add_number = (number) -> count = count or 0 count = (count * 10) + number export change_mode = (editor, to, ...) -> map = maps[to] error 'Invalid mode "' .. to .. '"' if not map if editor meta = map.__meta meta.on_enter(editor) if meta.on_enter editor.indicator.vi.label = '-- ' .. meta.name .. ' --' editor.cursor[k] = v for k,v in pairs meta.cursor_properties mode = to bindings.pop! if active bindings.push map map(editor, ...) if callable map export apply = (editor, f) -> state = :delete, :change, :yank, :count state.has_modifier = delete or change or yank op = (editor) -> editor.buffer\as_one_undo -> cursor = editor.cursor start_pos = cursor.pos for i = 1, state.count or 1 break if true == f editor, state -- count handled by function if state.has_modifier with editor.selection \set start_pos, cursor.pos if state.yank \copy! cursor.pos = start_pos else if state.delete \cut! else if state.change \cut! change_mode editor, 'insert' op editor reset! if state.delete or state.change last_op = op insert_edit = nil export record = (editor, op) -> op editor reset! last_op = op insert_edit = nil export repeat_last = (editor) -> if last_op for i = 1, count or 1 last_op editor if insert_edit insert_edit editor change_mode editor, 'command' reset! export init = (keymaps) -> maps = keymaps export activate = (editor) -> unless active change_mode editor, 'command' active = true export deactivate = -> if active bindings.pop! active = false return _ENV
20.970588
70
0.638616
48c2cf6f78eb35ef77de39076339350a75252b94
2,036
local * _VERSION = "1.0" _DESCRIPTION = "MoonScript implementation of Smalltalk Lights Out" _AUTHOR = "ℜodrigo ℭacilhας <[email protected]>" _URL = "https://github.com/cacilhas/LightsOut" _LICENSE = "BSD 3-Clause License" import random, randomseed from math randomseed os.time! -------------------------------------------------------------------------------- class LOCell pressed: false new: (game, x, y, quads) => @game = game @quads = quads @x, @y = x, y toggle: => @pressed = not @pressed draw: (xoffset, yoffset) => love.graphics.draw @quads.img, @quads[@pressed], (@x - 1) * 16 + xoffset, (@y - 1) * 16 + yoffset -------------------------------------------------------------------------------- class LOGame activecount: 0 new: (quads, font, width=10, height=10) => @quads = quads @font = font @width, @height = width, height @board = [LOCell @, x, y, quads for y = 1, height for x = 1, width] (@\get (random width), (random height))\toggle! @activecount = 1 toggle: (x, y) => unless @activecount == 0 @\get(x, y-1)\toggle! if y > 1 @\get(x-1, y)\toggle! if x > 1 @\get(x+1, y)\toggle! if x < @width @\get(x, y+1)\toggle! if y < @height @\recalculate! recalculate: => @activecount = 0 for cell in *@board @activecount += 1 if cell.pressed get: (x, y) => @board[x + (y - 1) * @width] draw: (xoffset=0, yoffset=0) => cell\draw xoffset, yoffset for cell in *@board if @activecount == 0 with love.graphics .setFont @font .setColor 0xff, 0x00, 0x00 .print "DONE!", 20, 64 .reset! -------------------------------------------------------------------------------- { :_VERSION :_DESCRIPTION :_AUTHOR :_URL :_LICENSE newgame: LOGame }
26.789474
80
0.455305
1700821a1b728cf648523eaeaf7635d986b3fa86
1,579
import use_test_server from require "lapis.spec" import request from require "lapis.spec.server" import truncate_tables from require "lapis.spec.db" import Keys from require "models" import types from require "tableshape" describe "app", -> use_test_server! before_each -> truncate_tables Keys it "gets keys", -> status, res = request "/keys", expect: "json" assert.same { keys: {} }, res it "requests /keys/put with missing params", -> status, res = request "/keys/put", expect: "json" assert.same { errors: { "machine_id must be an integer", "password must be provided" } }, res it "gets max id when there are no keys", -> status, res = request "/keys/put", { expect: "json" get: { machine_id: 1 password: "test" } } assert.same { max_id: -1 }, res it "puts keys", -> status, res = request "/keys/put", { expect: "json" get: { machine_id: 1 password: "test" } headers: { "Content-type": "application/json" } post: '[[1,"2017-12-1 00:00:00",1],[2,"2017-12-2 00:00:00",2]]' } assert.same { success: true inserted: 2 }, res inserted = Keys\select "order by id asc" assert (types.shape { types.shape { id: 1 machine_id: 1 count: 1 time: "2017-12-01 00:00:00" } types.shape { id: 2 machine_id: 1 count: 2 time: "2017-12-02 00:00:00" } }) inserted
19.256098
69
0.541482
a494167f9c5ee934f5d764af1207678e42c950af
6,196
return (ASS, ASSFInst, yutilsMissingMsg, createASSClass, Functional, LineCollection, Line, logger, SubInspector, Yutils) -> {:list, :math, :string, :table, :unicode, :util, :re } = Functional msgs = { checkPositive: { notPositiveNumber: "%s tagProps do not permit numbers < 0, got %d." } coerce: { cantCastTable: "can't cast a table to a %s. Table contents: %s" noNumber: "failed coercing value '%s' of type %s to a base-%d number on creation of %s object." badTargetType: "unsupported conversion target type '%s'" } getArgs: { badArgs: "first argument to getArgs must be a table of arguments, got a %s." incompatibleObject: "object of class %s does not accept instances of class %s as argument." typeMismatch: "%s: type mismatch in argument #%d (%s). Expected a %s or a compatible object, but got a %s." } typeCheck: { badType: "%s: bad type for argument #%d (%s). Expected %s, got %s." } } Base = createASSClass "Base" -- TODO: remove Base.checkPositive = (...) => for i = 1, select '#', ... val = select i, ... if type(val) != "number" or val < 0 error msgs.checkPositive.notPositiveNumber\format @typeName, val Base.coerceNumber = (num, default = 0) => num = tonumber(num) or default if @__tag.positive num = math.max num, 0 elseif range = @__tag.range num = util.clamp num, range[1], range[2] return num Base.coerce = (value, targetType) => valType = type value if "table" == valType error msgs.coerce.cantCastTable\format targetType, logger\dumpToString value return value if valType == targetType tagProps = @__tag or @__defProps return switch targetType when valType == "boolean" and "number" value and 1 or 0 when "number" base = tagProps.base or 10 tonumber(value, base) or error msgs.coerce.noNumber\format tostring(value), valType, base, @typeName when "string" tostring value when "boolean" value != 0 and value != "0" and value != false when "table" {value} else error msgs.coerce.badTargetType\format targetType Base.getArgs = (args = {}, defaults, coerce, first = 1, last, defaultIdx = 1) => -- TODO: make getArgs automatically create objects error msgs.getArgs.badArgs\format type(args) if "table" != type args propTypes = @__meta__.types last or= #args defaultsIsTable = type(defaults) == "table" obj = if args.class args elseif first == last and type(args[first]) == "table" and args[first].class args[first] -- process a single passed object if it's compatible if obj and @compatible[obj.class] if obj.deepCopy args = obj\get! else outArgs = [obj[field] or defaultsIsTable and defaults[f] or defaults for f, field in ipairs @__meta__.order] return outArgs -- process "raw" property that holds all tag parameters when parsed from a string elseif type(args.raw) == "table" args = args.raw -- TODO: what is this useful for? elseif args.raw args = {args.raw} elseif args.class args = {args} -- decompose all arguments into primitive types, then coerce if requested sliceLast, outArgs, o = first, {}, 1 for i, propName in ipairs @__meta__.order propType = propTypes[i] -- ASSFoundation class members consume a known number of arguments if type(propType) == "table" and propType.class rawArgCnt, propRawArgCnt, defSlice = 0, propTypes[i].__meta__.rawArgCnt while rawArgCnt < propRawArgCnt arg = args[sliceLast] rawArgCnt += type(arg) == "table" and arg.class and arg.__meta__.rawArgCnt or 1 sliceLast += 1 sliceArgs = propType\getArgs args, defaults, coerce, first, sliceLast-1, defaultIdx outArgs[o], o = sliceArg, o + 1 for sliceArg in *sliceArgs defaultIdx += propRawArgCnt -- primitive class members consume 1 argument else arg, argType = args[sliceLast], type args[sliceLast] outArgs[o] = if arg == nil -- write defaults if defaultsIsTable defaults[defaultIdx] else defaults elseif argType == "table" and arg.class if arg.__meta__.rawArgCnt != 1 logger\error msgs.getArgs.typeMismatch, @typeName, i, propName, propType, arg.typeName arg\get! elseif coerce and argType != propType @coerce arg, propType else arg sliceLast, defaultIdx, o = sliceLast + 1, defaultIdx + 1, o + 1 first = sliceLast return outArgs Base.copy = => newObj, meta = {}, getmetatable @ setmetatable newObj, meta keys = list.makeSet @__meta__.order if @__meta__ for k, v in pairs @ newObj[k] = if (k == "__tag" or not keys or keys[k]) and "table" == type v v.class and v\copy! or Base.copy v else v return newObj Base.typeCheck = (args, first = 1) => valTypes, valNames = @__meta__.types, @__meta__.order for i, valName in ipairs valNames valType = valTypes[i] if type(valType) == "table" and valType.class if type(args[first]) == "table" and args[first].class -- argument and expected type are both ASSFoundation object -- defer type checking to object @[valNames]\typeCheck {args[first]} else -- collect expected number of arguments for target ASSObject subCnt = #valType.__meta__.order valType\typeCheck args, first, first+subCnt-1 first += subCnt - 1 elseif args[first] != nil and valType != "nil" and type(args[first]) != valType error msgs.typeCheck.badType\format @typeName, i, valName, valType, type args[first] first += 1 Base.get = (packed) => vals, valCnt = {}, 1 for name in *@__meta__.order if type(@[name]) == "table" and @[name].class vals[valCnt], valCnt = subVal, valCnt+1 for j, subVal in pairs {@[name]\get!} else vals[valCnt], valCnt = @[name], valCnt + 1 return if packed vals else unpack vals return Base
35.204545
123
0.627017
82d5f59b69b596f43580133e798843d86b039102
5,440
Dorothy! ExprItemView = require "View.Control.Trigger.ExprItem" TriggerDef = require "Data.TriggerDef" SolidRect = require "View.Shape.SolidRect" import Set from require "Lib.Utils" keywords = Set {"and", "break", "do", "else", "elseif", "end", "false", "for", "function", "if", "in", "local", "nil", "not", "or", "repeat", "return", "then", "true", "until", "while"} textColor = ccColor3 255,255,255 keywordColor = ccColor3 58,135,212 classColor = ccColor3 62,197,127 noteColor = ccColor3 56,142,73 errorColor = ccColor3 255,0,128 targetColor = ccColor3 0,255,255 LineTag = 1 ErrorTag = 2 Class ExprItemView, __init:(args)=> {:text,:indent,:expr,:parentExpr,:index,:lineNumber} = args @_checked = false @_indent = indent or 0 @_text = "" @_index = index @_lineNumber = lineNumber @errorInfo = nil @expr = expr @parentExpr = parentExpr @text = text or "" @slot "TapBegan",@tapBegan @slot "Tapped",-> @checked = not @checked if @expr @slot "TapEnded",@tapEnded tapBegan:=> if not @checked with @addLazyLine! .opacity = 0.5 tapEnded:=> if not @checked with @addLazyLine! \perform CCSequence { oOpacity 0.2,0 CCHide! } addLazyLine:=> line = @getChildByTag LineTag if not line line = oLine { oVec2 0,1 oVec2 @width,1 oVec2 @width,@height-1 oVec2 0,@height-1 oVec2 0,1 },ccColor4 @expr and 0xff00ffff or 0xff0080 @addChild line,0,LineTag line.visible = true line updateLine:=> line = @getChildByTag LineTag if line line\set { oVec2 0,1 oVec2 @width,1 oVec2 @width,@height-1 oVec2 0,@height-1 oVec2 0,1 } checked:property => @_checked, (value)=> @_checked = value with @addLazyLine! if value \perform oOpacity 0.2,1 else \perform CCSequence { oOpacity 0.2,0 CCHide! } indent:property => @_indent, (value)=> @_indent = value @text = @text\gsub "^%s*","" index:property => parentExpr = @parentExpr if parentExpr expr = @expr if parentExpr[@_index] ~= expr for i = 2,#parentExpr if parentExpr[i] == expr @_index = i break @_index lineNumber:property => @_lineNumber, (value)=> if value ~= @_lineNumber @_lineNumber = value @numberLabel.text = value and tostring(value) or "" text:property => @_text, (value)=> @_text = value value = string.rep(" ",@_indent)..value parentExpr = @parentExpr if parentExpr and @itemType ~= "Start" switch parentExpr[1] when "Condition","Available","ConditionNode" if #parentExpr ~= @index value ..= " and" when "ActionGroup" if #parentExpr ~= @index value ..= "," @label.text = value @label.texture.antiAlias = false @height = @label.height+16 posY = @height-8 @label.positionY = posY @numberLabel.positionY = posY if @numberLabel label = @label label\colorText 1,#value,textColor if TriggerDef.CodeMode if value\match "^%s*%-%-%s" label\colorText 1,#value,noteColor else -- color keywords text for start,word,stop in value\gmatch "()([%w_]+)()" if keywords[word] label\colorText start,stop-1,keywordColor elseif word == "InvalidName" or word == "g_InvalidName" label\colorText start,stop-1,errorColor -- color comment text index = value\find "%-%-%s" label\colorText index,#value,noteColor if index start,stop = value\find "%-%-%[%[[^%]]*%]%]%s" label\colorText start,stop,noteColor if start -- color string text value = value\gsub "\\.","xx" for start,word,stop in value\gmatch "()(%b\"\")()" if word == "\"InvalidName\"" label\colorText start,stop-1,errorColor else label\colorText start,stop-1,classColor else if value\match "^%s*Note" label\colorText 1,#value,noteColor else -- color start of expression text for start,word,stop in value\gmatch "()([%w_]*)()" if word == "InvalidName" or word == "g_InvalidName" label\colorText start,stop-1,errorColor elseif word\sub(1,1)\match "%u" label\colorText start,stop-1,keywordColor value = value\gsub "\\.","xx" -- color comment text index = value\find "note %b()" label\colorText index,#value,noteColor if index -- color string text for start,word,stop in value\gmatch "()(%b\"\")()" if word == "\"InvalidName\"" label\colorText start,stop-1,errorColor else label\colorText start,stop-1,classColor -- color target text targetPos = {} for pos in value\gmatch "()|" char = label\getChar pos if char and char.color == textColor char.color = errorColor table.insert targetPos,pos if #targetPos == 2 label\colorText targetPos[1]+1,targetPos[2]-1,targetColor updateText:=> if @expr if @itemType == "End" @text = @_text else @text = tostring @expr @updateLine! markError:(isError,info)=> @errorInfo = info if isError if not @getChildByTag ErrorTag @addChild with SolidRect { width:30 height:@height-10 color:0x66ff0080 } .position = oVec2 5,5 .tag = ErrorTag .zOrder = -1 else @removeChildByTag ErrorTag
26.536585
91
0.602941
0798d95a97df78656034517617a13b0068ad7530
8,274
-- -- Copyright (C) 2017-2020 DBotThePony -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -- of the Software, and to permit persons to whom the Software is furnished to do so, -- subject to the following conditions: -- The above copyright notice and this permission notice shall be included in all copies -- or substantial portions of the Software. -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, -- INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR -- PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE -- FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -- OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -- DEALINGS IN THE SOFTWARE. -- it is defined shared, but used clientside only import PPM2 from _G -- 0 LrigPelvis -- 1 LrigSpine1 -- 2 LrigSpine2 -- 3 LrigRibcage -- 4 LrigNeck1 -- 5 LrigNeck2 -- 6 LrigNeck3 -- 7 LrigScull -- 8 Lrig_LEG_BL_Femur -- 9 Lrig_LEG_BL_Tibia -- 10 Lrig_LEG_BL_LargeCannon -- 11 Lrig_LEG_BL_PhalanxPrima -- 12 Lrig_LEG_BL_RearHoof -- 13 Lrig_LEG_BR_Femur -- 14 Lrig_LEG_BR_Tibia -- 15 Lrig_LEG_BR_LargeCannon -- 16 Lrig_LEG_BR_PhalanxPrima -- 17 Lrig_LEG_BR_RearHoof -- 18 Lrig_LEG_FL_Scapula -- 19 Lrig_LEG_FL_Humerus -- 20 Lrig_LEG_FL_Radius -- 21 Lrig_LEG_FL_Metacarpus -- 22 Lrig_LEG_FL_PhalangesManus -- 23 Lrig_LEG_FL_FrontHoof -- 24 Lrig_LEG_FR_Scapula -- 25 Lrig_LEG_FR_Humerus -- 26 Lrig_LEG_FR_Radius -- 27 Lrig_LEG_FR_Metacarpus -- 28 Lrig_LEG_FR_PhalangesManus -- 29 Lrig_LEG_FR_FrontHoof -- 30 Mane01 -- 31 Mane02 -- 32 Mane03 -- 33 Mane04 -- 34 Mane05 -- 35 Mane06 -- 36 Mane07 -- 37 Mane03_tip -- 38 Tail01 -- 39 Tail02 -- 40 Tail03 class PonyWeightController 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'} @HARD_LIMIT_MINIMAL = 0.1 @HARD_LIMIT_MAXIMAL = 3 @DEFAULT_BONE_SIZE = Vector(1, 1, 1) @NEXT_OBJ_ID = 0 Remap: => @WEIGHT_BONES = [{id: @GetEntity()\LookupBone(id), scale: scale} for _, {:id, :scale} in ipairs @@WEIGHT_BONES] @validSkeleton = true for _, {:id} in ipairs @WEIGHT_BONES if not id @validSkeleton = false break new: (controller, applyWeight = true) => @isValid = true @controller = controller @objID = @@NEXT_OBJ_ID @@NEXT_OBJ_ID += 1 @lastPAC3BoneReset = 0 @scale = 1 @SetWeight(controller\GetWeight()) @Remap() @UpdateWeight() if IsValid(@GetEntity()) and applyWeight __tostring: => "[#{@@__name}:#{@objID}|#{@GetData()}]" IsValid: => IsValid(@GetEntity()) and @isValid GetEntity: => @controller\GetEntity() GetData: => @controller GetController: => @controller GetModel: => @controller\GetModel() PlayerDeath: => @ResetBones() @Remap() PlayerRespawn: => @Remap() @UpdateWeight() @WEIGHT_BONES = { {id: 'LrigPelvis', scale: 1.1} {id: 'LrigSpine1', scale: 0.7} {id: 'LrigSpine2', scale: 0.7} {id: 'LrigRibcage', scale: 0.7} } extrabones = { 'Lrig_LEG_BL_Femur' 'Lrig_LEG_BL_Tibia' 'Lrig_LEG_BL_LargeCannon' 'Lrig_LEG_BL_PhalanxPrima' 'Lrig_LEG_BL_RearHoof' 'Lrig_LEG_BR_Femur' 'Lrig_LEG_BR_Tibia' 'Lrig_LEG_BR_LargeCannon' 'Lrig_LEG_BR_PhalanxPrima' 'Lrig_LEG_BR_RearHoof' 'Lrig_LEG_FL_Scapula' 'Lrig_LEG_FL_Humerus' 'Lrig_LEG_FL_Radius' 'Lrig_LEG_FL_Metacarpus' 'Lrig_LEG_FL_PhalangesManus' 'Lrig_LEG_FL_FrontHoof' 'Lrig_LEG_FR_Scapula' 'Lrig_LEG_FR_Humerus' 'Lrig_LEG_FR_Radius' 'Lrig_LEG_FR_Metacarpus' 'Lrig_LEG_FR_PhalangesManus' 'Lrig_LEG_FR_FrontHoof' } table.insert(@WEIGHT_BONES, {id: name, scale: 1}) for _, name in ipairs extrabones DataChanges: (state) => return if not IsValid(@GetEntity()) or not @isValid @Remap() if state\GetKey() == 'Weight' @SetWeight(state\GetValue()) if state\GetKey() == 'PonySize' @SetSize(state\GetValue()) SetWeight: (weight = 1) => @weight = math.Clamp(weight, @@HARD_LIMIT_MINIMAL, @@HARD_LIMIT_MAXIMAL) SetSize: (scale = 1) => @scale = math.Clamp(math.sqrt(scale), @@HARD_LIMIT_MINIMAL, @@HARD_LIMIT_MAXIMAL) SlowUpdate: => ResetBones: (ent = @GetEntity()) => return if not IsValid(ent) or not @isValid return if not @validSkeleton for {:id} in *@WEIGHT_BONES ent\ManipulateBoneScale(id, @@DEFAULT_BONE_SIZE) Reset: => @ResetBones() UpdateWeight: (ent = @GetEntity()) => return if not IsValid(ent) or not @isValid return if not @GetEntity()\IsPony() return if @GetEntity().Alive and not @GetEntity()\Alive() return if not @validSkeleton for {:id, :scale} in *@WEIGHT_BONES delta = 1 + (@weight * @scale - 1) * scale ent\ManipulateBoneScale(id, Vector(delta, delta, delta)) if delta < 0.99 or delta > 1.01 Remove: => @isValid = false do reset = (ent, data) -> if weight = data\GetWeightController() weight.ent = ent weight\UpdateWeight() hook.Add 'PPM2.SetupBones', 'PPM2.Weight', reset, -2 -- 0 LrigPelvis -- 1 Lrig_LEG_BL_Femur -- 2 Lrig_LEG_BL_Tibia -- 3 Lrig_LEG_BL_LargeCannon -- 4 Lrig_LEG_BL_PhalanxPrima -- 5 Lrig_LEG_BL_RearHoof -- 6 Lrig_LEG_BR_Femur -- 7 Lrig_LEG_BR_Tibia -- 8 Lrig_LEG_BR_LargeCannon -- 9 Lrig_LEG_BR_PhalanxPrima -- 10 Lrig_LEG_BR_RearHoof -- 11 LrigSpine1 -- 12 LrigSpine2 -- 13 LrigRibcage -- 14 Lrig_LEG_FL_Scapula -- 15 Lrig_LEG_FL_Humerus -- 16 Lrig_LEG_FL_Radius -- 17 Lrig_LEG_FL_Metacarpus -- 18 Lrig_LEG_FL_PhalangesManus -- 19 Lrig_LEG_FL_FrontHoof -- 20 Lrig_LEG_FR_Scapula -- 21 Lrig_LEG_FR_Humerus -- 22 Lrig_LEG_FR_Radius -- 23 Lrig_LEG_FR_Metacarpus -- 24 Lrig_LEG_FR_PhalangesManus -- 25 Lrig_LEG_FR_FrontHoof -- 26 LrigNeck1 -- 27 LrigNeck2 -- 28 LrigNeck3 -- 29 LrigScull -- 30 Jaw -- 31 Ear_L -- 32 Ear_R -- 33 Mane02 -- 34 Mane03 -- 35 Mane03_tip -- 36 Mane04 -- 37 Mane05 -- 38 Mane06 -- 39 Mane07 -- 40 Mane01 -- 41 Lrigweaponbone -- 42 right_hand -- 43 wing_l -- 44 wing_r -- 45 Tail01 -- 46 Tail02 -- 47 Tail03 -- 48 wing_l_bat -- 49 wing_r_bat -- 50 wing_open_l -- 51 wing_open_r class NewPonyWeightController extends PonyWeightController @MODELS = {'models/ppm/player_default_base_new.mdl', 'models/ppm/player_default_base_new_nj.mdl'} __tostring: => "[#{@@__name}:#{@objID}|#{@GetData()}]" @WEIGHT_BONES = { {id: 'LrigPelvis', scale: 1.1} {id: 'Lrig_LEG_BL_Femur', scale: 0.7} {id: 'Lrig_LEG_BR_Femur', scale: 0.7} {id: 'LrigSpine1', scale: 0.7} {id: 'LrigSpine2', scale: 0.7} {id: 'LrigRibcage', scale: 0.7} {id: 'Lrig_LEG_FL_Scapula', scale: 0.7} {id: 'Lrig_LEG_FR_Scapula', scale: 0.7} {id: 'Lrig_LEG_BL_RearHoof', scale: 0.9} {id: 'Lrig_LEG_BR_RearHoof', scale: 0.9} {id: 'Lrig_LEG_FL_FrontHoof', scale: 0.9} {id: 'Lrig_LEG_FR_FrontHoof', scale: 0.9} {id: 'Lrig_LEG_BL_Tibia', scale: 1} {id: 'Lrig_LEG_BL_LargeCannon', scale: 1} {id: 'Lrig_LEG_BL_PhalanxPrima', scale: 1} {id: 'Lrig_LEG_BR_Femur', scale: 1} {id: 'Lrig_LEG_BR_Tibia', scale: 1} {id: 'Lrig_LEG_BR_LargeCannon', scale: 1} {id: 'Lrig_LEG_BR_PhalanxPrima', scale: 1} {id: 'Lrig_LEG_FL_Humerus', scale: 1} {id: 'Lrig_LEG_FL_Radius', scale: 1} {id: 'Lrig_LEG_FL_Metacarpus', scale: 1} {id: 'Lrig_LEG_FL_PhalangesManus', scale: 1} {id: 'Lrig_LEG_FR_Humerus', scale: 1} {id: 'Lrig_LEG_FR_Radius', scale: 1} {id: 'Lrig_LEG_FR_Metacarpus', scale: 1} {id: 'Lrig_LEG_FR_PhalangesManus', scale: 1} {id: 'LrigNeck1', scale: 1} {id: 'LrigNeck2', scale: 1} {id: 'LrigNeck3', scale: 1} } PPM2.PonyWeightController = PonyWeightController PPM2.NewPonyWeightController = NewPonyWeightController PPM2.GetPonyWeightController = (model = '') -> PonyWeightController.AVALIABLE_CONTROLLERS[model] or PonyWeightController
28.629758
171
0.70365
6355b68e8889a4644651cb9d55460f1ad24331ab
3,643
import bundle, config, VC from howl import File from howl.io describe 'Hg bundle', -> setup -> bundle.load_by_name 'hg' teardown -> bundle.unload 'hg' it 'registers "hg" with VC', -> assert.not_nil VC.available.hg it 'defines a "hg_path" config variable, defaulting to nil', -> assert.not_nil config.definitions.hg_path assert.equal 'hg', config.hg_path describe 'Hg VC find(file)', -> hg_vc = nil before_each -> hg_vc = VC.available.hg it 'returns a instance with .root set to the Hg root for <file> if applicable', -> with_tmpdir (dir) -> dir\join('.hg')\mkdir! sub = dir / 'subdir' for file in *{ dir, sub, sub\join('file.lua') } instance = hg_vc.find file assert.not_nil instance assert.equal instance.root, dir it 'returns nil if no hg root was found', -> File.with_tmpfile (file) -> assert.is_nil hg_vc.find file describe 'A Hg instance', -> root = nil hg = nil before_each -> root = File.tmpdir! os.execute 'hg init -q ' .. root hg = VC.available.hg.find root os.execute "cd #{root} && printf '[ui]\nusername = Howl Spec <[email protected]>\n' >> .hg/hgrc" after_each -> root\delete_all! describe 'paths()', -> assert_same_paths = (list1, list2) -> table.sort list1 table.sort list2 assert.same list1, list2 it 'returns a list of hg paths, including untracked', (done) -> settimeout 4 howl_async -> assert_same_paths hg\paths!, {} file = root / 'new.lua' file\touch! assert_same_paths hg\paths!, { 'new.lua' } hg\run 'add', file\relative_to_parent root assert_same_paths hg\paths!, { 'new.lua' } hg\run 'commit', '-q', '-m', 'new', file\relative_to_parent root assert_same_paths hg\paths!, { 'new.lua' } file.contents = 'change' assert_same_paths hg\paths!, { 'new.lua' } file2 = root / 'another.lua' file2\touch! assert_same_paths hg\paths!, { 'another.lua', 'new.lua' } done! describe 'diff([file])', -> local file before_each -> file = root\join('new.lua') file.contents = 'line 1\n' os.execute "cd #{root} && hg add #{file}" os.execute "cd #{root} && hg commit -q -m 'rev1' #{file}" it 'returns nil if <file> has not changed', (done) -> howl_async -> assert.is_nil hg\diff file done! it 'returns a string containing the diff if <file> has changed', (done) -> howl_async -> file.contents ..= 'line 2\n' diff = hg\diff file assert.includes diff, file.basename assert.includes diff, '+line 2' done! it 'returns a diff for the entire directory if file is not specified', (done) -> howl_async -> file.contents ..= 'line 2\n' diff = hg\diff! assert.includes diff, file.basename assert.includes diff, '+line 2' done! describe 'run(...)', -> it 'runs hg in the root dir with the given arguments and returns the output', (done) -> howl_async -> assert.includes hg\run('showconfig', 'ui.username'), "Howl Spec" done! it 'uses the executable in variable `hg_path` if specified', (done) -> howl_async -> config.hg_path = '/bin/echo' status, out = pcall hg.run, hg, 'using echo' config.hg_path = nil assert status, out assert.includes out, "using echo" done!
32.238938
97
0.569586
be6b6ff48e614cb7be755b6b6a5668242d785497
557
--- toml lexer for howl from [ta-toml](https://bitbucket.org/a_baez/ta-toml) -- See @{README.md} for details on usage. -- @author [Alejandro Baez](https://keybase.io/baez) -- @copyright 2016 -- @license MIT (see LICENSE) -- @module toml mode_reg = name: 'toml' aliases: 'toml' extensions: 'toml' create: -> bundle_load('toml_mode') howl.mode.register mode_reg unload = -> howl.mode.unregister 'toml' return { info: author: 'Alejandro Baez https://keybase.io/baez', description: 'Toml language support', license: 'MIT', :unload }
22.28
76
0.67325
1590bb3a65dc87344df99f4741814cc53a461d8a
256
-- TODO class AtlasRegion new: (parent, tileindex, rect) => @__parent = parent @__tileIndex = tileindex @rect = rect\clone! @rotated = false tileIndex: => @__tileIndex width: => @rect.width height: => @rect.height clip: => { :AtlasRegion }
16
34
0.648438
164e18a94e4a1c133127682e5270ba216033c6e0
1,632
--- Utility library for Bassoon -- @author RyanSquared <[email protected]> -- @module bassoon.util -- @usage import {random_key, ensure_uniqueness} from require "bassoon.util" _entropy_file = "/dev/random" _set_entropy_file = (filename)-> _entropy_file = filename --- Internal function for generating random bytes -- @tparam number size number of bytes to generate _random_key = (size)-> if file = io.open _entropy_file str = file\read size file\close! str else math.randomseed os.clock! * os.time! table.concat {math.random(1, 255) for n=1, size} --- Make sure there are no more than `max_duplicates duplicate characters -- @tparam string text Text to scan for duplications -- @tparam table opts -- - `opts.max_duplicates: int = 2` - maximum duplicate characters before error -- @usage assert ensure_uniqueness random_key! ensure_uniqueness = (text, opts = {})-> max_duplicates = do if opts.max_duplicates assert type opts.max_duplicates == "int" opts.max_duplicates else 2 hits = {} for byte in text\gmatch "." if not hits[byte] hits[byte] = 1 else hits[byte] += 1 if hits[byte] > max_duplicates false text --- Generate a string of `size` bytes, guaranteed to be unique and random -- @tparam table opts -- - `opts.size: int = 24` - number of bytes to generate -- @usage tbsp.secret_key = random_key! random_key = (opts = {})-> size = do if opts.size then assert type(opts.size) == "number" opts.size else 24 while true key = _random_key size return key if ensure_uniqueness key return {:ensure_uniqueness, :random_key, :_set_entropy_file, :_random_key}
27.661017
79
0.710172
c90b02334a808b27b327bc450c6ba8069ac99f20
1,192
sandbox = require "mooncrafts.sandbox" describe "mooncrafts.sandbox", -> it "correctly load good function", -> expected = "hello world" fn = sandbox.loadstring "return \"hello world\"" actual = fn! assert.same expected, actual it "fail to load bad function", -> expected = nil actual = sandbox.loadstring "asdf" assert.same expected, actual it "fail to execute restricted function", -> expected = "ffail" data = "local function hi()\n" data ..= " return 'hello world'\n" data ..= "end\nreturn string.dump(hi)" ignore, actual = sandbox.exec_code data, expected hasMatch = actual\match(expected) -- actual is error message assert.same expected, hasMatch it "correctly execute good function", -> expected = "hello world" fn = sandbox.loadstring_safe "return string.gsub('hello cruel world', 'cruel ', '')" actual = fn! assert.same expected, actual it "correctly pass in global variables", -> expected = "hello world" env = sandbox.build_env(_G, {test: expected }, sandbox.whitelist) fn = sandbox.loadstring "return _G.test", "test", env actual = fn! assert.same expected, actual
29.073171
88
0.661074
d7089f1ec14747a1f013f3c0c33af320243692e9
316
require "sitegen" tools = require "sitegen.tools" sitegen.create_site => @current_version = "0.0.9" @title = "SCSS Compiler in PHP" scssphp = tools.system_command "pscss < %s > %s", "css" build scssphp, "style.scss", "style/style.css" deploy_to "[email protected]", "www/scssphp/" add "docs/index.md"
19.75
57
0.667722
c6ed096fbc0f050d23d3ef552d01c2a23c26660d
1,817
import Model, enum from require "lapis.db.model" import create_table, types, add_column from require "lapis.db.schema" Users = require "lazuli.modules.user_management.models.users" class ACLs extends Model -- user is one of: -- * "lazuli.modules.user_management.models.users" instance -- * user id (number) to be found by that model -- * nil if no user is logged in/applicable matchUser: do _logic= (user)=> ACL_Entries = require "models.acl_entries" entries=ACL_Entries\select "where acl_id = ? order by position asc nulls first, id", @id for entry in *entries ret, err=entry\matchUser user return nil, err if ret == nil and err return ret if type(ret)=="boolean" (user,return_default=true)=> if user if type(user)=="number" user=Users\find user return nil, "user not found" unless user cname=(user and tostring(user.id) or "[N]").."-"..@id cached=ngx.shared.acl_cache\get cname return @default_policy if cached == "[D]" return cached if cached ~= nil ret,err=_logic @, user if type(ret)=="boolean" ngx.shared.acl_cache\set cname, ret, 10 if ret==nil and not err and return_default ngx.shared.acl_cache\set cname, "[D]", 10 return @default_policy return ret, err @relations: { {"user", belongs_to: "Users"} } @get_relation_model: (name)=> switch name when "Users" require "lazuli.modules.user_management.models.users" when "ACLs" require "models.acls" @migrations: { -> create_table "acls", { {"id", types.serial} {"user_id", types.integer} {"name", types.varchar} {"default_policy", types.boolean} "PRIMARY KEY (id)" } }
30.79661
94
0.616401
22298c3fdeb1d71cc0f19a8616b553c7209c48bd
3,998
-- -- 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. ENABLE_SCAILING = CreateConVar('ppm2_sv_dmg', '1', {FCVAR_NOTIFY}, 'Enable hitbox damage scailing') HEAD = CreateConVar('ppm2_sv_dmg_head', '2', {FCVAR_NOTIFY}, 'Damage scale when pony-player got shot in head') CHEST = CreateConVar('ppm2_sv_dmg_chest', '1', {FCVAR_NOTIFY}, 'Damage scale when pony-player got shot in chest') STOMACH = CreateConVar('ppm2_sv_dmg_stomach', '1', {FCVAR_NOTIFY}, 'Damage scale when pony-player got shot in stomach') LEFTARM = CreateConVar('ppm2_sv_dmg_lfhoof', '0.75', {FCVAR_NOTIFY}, 'Damage scale when pony-player got shot in left-forward hoof') RIGHTARM = CreateConVar('ppm2_sv_dmg_rfhoof', '0.75', {FCVAR_NOTIFY}, 'Damage scale when pony-player got shot in right-forward hoof') LEFTLEG = CreateConVar('ppm2_sv_dmg_lbhoof', '0.75', {FCVAR_NOTIFY}, 'Damage scale when pony-player got shot in back-forward hoof') RIGHTLEG = CreateConVar('ppm2_sv_dmg_rbhoof', '0.75', {FCVAR_NOTIFY}, 'Damage scale when pony-player got shot in back-forward hoof') sk_player_head = GetConVar('sk_player_head') sk_player_chest = GetConVar('sk_player_chest') sk_player_stomach = GetConVar('sk_player_stomach') sk_player_arm = GetConVar('sk_player_arm') sk_player_leg = GetConVar('sk_player_leg') hook.Add 'ScalePlayerDamage', 'PPM2.PlayerDamage', (group = HITGROUP_GENERIC, dmg) => return if not @IsPonyCached() return if not ENABLE_SCAILING\GetBool() -- Reset damage to its original value -- https://github.com/ValveSoftware/source-sdk-2013/blob/master/sp/src/game/server/player.cpp#L180-L184 -- https://github.com/ValveSoftware/source-sdk-2013/blob/master/sp/src/game/server/player.cpp#L923-L946 --switch group -- when HITGROUP_HEAD -- dmg\ScaleDamage(1 / sk_player_head\GetFloat()) -- when HITGROUP_CHEST -- dmg\ScaleDamage(1 / sk_player_chest\GetFloat()) -- when HITGROUP_STOMACH -- dmg\ScaleDamage(1 / sk_player_stomach\GetFloat()) -- when HITGROUP_RIGHTARM -- dmg\ScaleDamage(1 / sk_player_arm\GetFloat()) -- when HITGROUP_RIGHTLEG -- dmg\ScaleDamage(1 / sk_player_leg\GetFloat()) -- but fuck gmod -- https://github.com/Facepunch/garrysmod/blob/cf725f3f66072c83e4d96674814670c97eebb43d/garrysmod/gamemodes/base/gamemode/player.lua#L510 switch group when HITGROUP_HEAD dmg\ScaleDamage(0.5) when HITGROUP_LEFTARM, HITGROUP_RIGHTARM, HITGROUP_LEFTLEG, HITGROUP_RIGHTLEG, HITGROUP_GEAR dmg\ScaleDamage(4) switch group when HITGROUP_HEAD dmg\ScaleDamage(HEAD\GetFloat()) when HITGROUP_CHEST dmg\ScaleDamage(CHEST\GetFloat()) when HITGROUP_STOMACH dmg\ScaleDamage(STOMACH\GetFloat()) when HITGROUP_LEFTARM dmg\ScaleDamage(LEFTARM\GetFloat()) when HITGROUP_RIGHTARM dmg\ScaleDamage(RIGHTARM\GetFloat()) when HITGROUP_LEFTLEG dmg\ScaleDamage(RIGHTLEG\GetFloat()) when HITGROUP_RIGHTLEG dmg\ScaleDamage(RIGHTLEG\GetFloat()) when HITGROUP_GEAR dmg\ScaleDamage(CHEST\GetFloat()) else dmg\ScaleDamage(1)
46.488372
138
0.768884
e893796324d2f195254a622922934d278d9c4fb2
3,275
-- Copyright 2014-2015 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_gc, ffi_cast = ffi.C, ffi.gc, ffi.cast attr_gc = (o) -> ffi_gc o, (_o) -> C.pango_attribute_destroy(ffi_cast('PangoAttribute *', _o)) PangoAttribute = core.define 'PangoAttribute', { constants: { prefix: 'PANGO_ATTR_' -- PangoAttrType 'INVALID', 'LANGUAGE', 'FAMILY', 'STYLE', 'WEIGHT', 'VARIANT', 'STRETCH', 'SIZE', 'FONT_DESC', 'FOREGROUND', 'BACKGROUND', 'UNDERLINE', 'STRIKETHROUGH', 'RISE', 'SHAPE', 'SCALE', 'FALLBACK', 'LETTER_SPACING', 'UNDERLINE_COLOR', 'STRIKETHROUGH_COLOR', 'ABSOLUTE_SIZE', 'GRAVITY', 'GRAVITY_HINT' } -- We define struct fields as properties again here: -- this is make dispatch through sub classes work correctly properties: { start_index: { get: => @start_index set: (idx) => @start_index = idx } end_index: { get: => @end_index set: (idx) => @end_index = idx } } copy: => attr_gc C.pango_attribute_copy @ } for atype in *{ 'Color', 'String', 'Int' } core.define "PangoAttr#{atype} < PangoAttribute", {} new_attr = (attr, start_index, end_index) -> with attr_gc attr .start_index = start_index if start_index .end_index = end_index if end_index with PangoAttribute .Foreground = (r, g, b, start_index, end_index) -> new_attr C.pango_attr_foreground_new(r, g, b), start_index, end_index .Background = (r, g, b, start_index, end_index) -> new_attr C.pango_attr_background_new(r, g, b), start_index, end_index .Family = (family, start_index, end_index) -> new_attr C.pango_attr_family_new(family), start_index, end_index .Style = (style, start_index, end_index) -> new_attr C.pango_attr_style_new(style), start_index, end_index .Variant = (variant, start_index, end_index) -> new_attr C.pango_attr_variant_new(variant), start_index, end_index .Stretch = (stretch, start_index, end_index) -> new_attr C.pango_attr_stretch_new(stretch), start_index, end_index .Weight = (weight, start_index, end_index) -> new_attr C.pango_attr_weight_new(weight), start_index, end_index .Size = (size, start_index, end_index) -> new_attr C.pango_attr_size_new(size), start_index, end_index .AbsoluteSize = (size, start_index, end_index) -> new_attr C.pango_attr_size_new_absolute(size), start_index, end_index .Strikethrough = (active, start_index, end_index) -> new_attr C.pango_attr_strikethrough_new(active), start_index, end_index .StrikethroughColor = (r, g, b, start_index, end_index) -> new_attr C.pango_attr_strikethrough_color_new(r, g, b), start_index, end_index .Underline = (underline, start_index, end_index) -> new_attr C.pango_attr_underline_new(underline), start_index, end_index .UnderlineColor = (r, g, b, start_index, end_index) -> new_attr C.pango_attr_underline_color_new(r, g, b), start_index, end_index .LetterSpacing = (spacing, start_index, end_index) -> new_attr C.pango_attr_letter_spacing_new(spacing), start_index, end_index PangoAttribute
28.72807
82
0.691298
628995adb9a192949475c30a67876e75e7d1b9d0
46
M = {} M.hello = ()-> "hello from m1" return M
15.333333
30
0.543478
553f9b22deb227610195a8138e99ef00f5e22d08
291
import floor from math export class Item new: (sprite) => @changeSprite sprite changeSprite: (@sprite) => @dim = Vector @sprite.width, @sprite.height @offset = @dim / 2 drawIcon: (x, y)=> love.graphics.setColor @sprite.color love.graphics.draw @sprite.img, x, y
22.384615
47
0.649485
3263dfc5c2e7af7335abbaf9b4b91da8b869b58f
555
html = require "lapis.html" import yield_error from require "lapis.application" class Nav extends html.Widget content: => header -> h1 { ["data-0"]: "opacity: 1", ["data-top-bottom"]: "opacity: 0" }, -> a href: (@url_for 'home'), @nav.header_text if @nav.items nav -> div id: "hamburger-icon" ul -> for v in *@nav.items li id: v.id, -> a href: v.href, v.text
29.210526
82
0.427027
0c7ae1bf5ed64900871c22943d48b97d7e5159b7
448
-- Copyright 2017 The Howl Developers -- License: MIT (see LICENSE.md at the top-level directory of the distribution) ffi = require 'ffi' ffi_new = ffi.new require 'ljglibs.cdefs.gdk' core = require 'ljglibs.core' C = ffi.C core.define 'GtkTargetTable', { new_from_list: (list) -> n_targets = ffi_new 'gint[1]' t_ptr = C.gtk_target_table_new_from_list list, n_targets ffi.gc(t_ptr, C.gtk_target_table_free), tonumber n_targets[1] }
28
79
0.729911
29916785f158782052d6c223604675839f5a7c37
674
class LinkedRectangle extends Rectangle set: (x, y, width, height, dontNotify) => @_x = x @_y = y @_width = width @_height = height @_owner[@_setter] this unless dontNotify @isSelected: -> @_owner._boundsSelected @setSelected: (selected) -> owner = @_owner if owner.setSelected! owner._boundsSelected = selected -- Update the owner's selected state too, so the bounds -- actually get drawn. When deselecting, take a path's -- _selectedSegmentState into account too, since it will -- have to remain selected even when bounds are deselected owner\setSelected selected or owner._selectedSegmentState > 0
30.636364
66
0.683976
7930021d777272ffbffc67ecfabcd85edc3479ae
701
import NewExpr,NewExprVal,ExprIndex,ExprToString,AddItem from require "Data.API.Expression" for item in *{ { Name:"SliceName" Text:"Slice Name" Type:"SliceName" MultiLine:false TypeIgnore:false Group:"Special" Desc:"A name for body slice." CodeOnly:true ToCode:=> @[2] Create:NewExprVal "InvalidName" Args:false __index:ExprIndex __tostring:ExprToString } { Name:"SliceByName" Text:"Get Slice" Type:"Slice" MultiLine:false TypeIgnore:false Group:"Physics" Desc:"Get body slice [SliceName] from scene." CodeOnly:false ToCode:=> "Slice.#{ @[2] }" Create:NewExpr "SliceName" Args:false __index:ExprIndex __tostring:ExprToString } } AddItem item
19.472222
91
0.710414
9c68b28adc005bc1671ca83ddf958a79ad9bfe7e
733
config = (require 'lapis.config').get! is_email = (input, tru) -> r = input\match "[A-Za-z0-9%.%%%+%-]+@[A-Za-z0-9%.%%%+%-]+%.%w%w%w?%w?" r, "not a valid email: %s" has_filetype = (input, ...) -> ftypes = {...} return nil, "doesn't look like a file" if not input or not input.filename for t in *ftypes ft = t\gsub '%.', '%%.' return t if input.filename\match "%.#{ft}$" nil, "#{input.filename} must be one of types #{table.concat ftypes, ', '}" smaller_than = (input, size) -> size = config.single_file_limit if type size != 'number' input and input.content and #input.content <= size, "file must be less than #{size} bytes" { :is_email, :has_filetype, :smaller_than }
30.541667
94
0.578445
11ca085691ce94fc9235525ea76d1619f227e95c
20
require "lapis.util"
20
20
0.8
ad0f61efa6fb4a6f9182d76d679c8add429ce174
471
M = {} -- merge two hash tables (nil values will be removed) M.merge = (table1, table2) -> condition1 = (type table1) == "table" condition2 = (type table2) == "table" return {} if (not condition1) and (not condition2) return table1 if not condition2 return table2 if not condition1 output = {} for k, v in pairs table1 output[k] = v if v != nil for k, v in pairs table2 output[k] = v if v != nil return output return M
31.4
54
0.613588
268e7265d3ad7b83f13de2cc3b0129221a2a02e3
2,732
export modinfo = { type: "command" desc: "Jibun jishin o tabemasu" alias: {"jibjistabe"} func: getDoPlayersFunction (v) -> Spawn -> char=v.Character t=char.Torso char.Head.face.Texture = ConfigSystem("Get", "Hadaka no kao") n=t.Neck lw= CreateInstance"Weld"{ Parent: t Name: 'leftWeld' Part0: t Part1: char['Left Arm'] C0: CFrame.new(-(1),1,-(1)) *CFrame.Angles(math.rad(100),math.rad(10),math.rad(30)) } rw= CreateInstance"Weld"{ Parent: t Name: 'rightWeld' Part0: t Part1: char['Right Arm'] C0: CFrame.new(1,0.5,-(1)) *CFrame.Angles(math.rad(80),math.rad(-(10)),math.rad(-(30))) } seg = 5 while not v.Character wait() removeOldDick(v.Character) D = CreateInstance"Model"{ Parent: v.Character Name: ConfigSystem("Get", "Ero-mei") } bg = CreateInstance"BodyGyro"{ Parent: v.Character.Torso } d = CreateInstance"Part"{ TopSurface: 0 BottomSurface: 0 Name: "Main" Parent: D FormFactor: 3 Size: Vector3.new(1,1,1) BrickColor: ConfigSystem("Get", "Ero-iro") Position: v.Character.Torso.Position CanCollide: true } cy = CreateInstance"CylinderMesh"{ Parent: d Scale: Vector3.new(0.3,1,0.3) } w = CreateInstance"Weld"{ Parent: v.Character.Torso Part0: d Part1: v.Character.Torso C0: CFrame.new(0,-(0.8),1)*CFrame.Angles(math.rad(90),0,0) } ball1 = CreateInstance"Part"{ Parent: D Name: "Left Ball" BottomSurface: 0 TopSurface: 0 CanCollide: true FormFactor: 3 Size: Vector3.new(1.5,1.5,1.5) CFrame: CFrame.new(v.Character["Left Leg"].Position) BrickColor: ConfigSystem("Get", "Ero-iro") } bsm = CreateInstance"SpecialMesh"{ Parent: ball1 MeshType: "Sphere" Scale: Vector3.new(0.3,0.3,0.3) } b1w = CreateInstance"Weld"{ Parent: ball1 Part0: v.Character["Left Leg"] Part1: ball1 C0: CFrame.new(0.3,1,-(0.6)) } ball2 = CreateInstance"Part"{ Parent: D Name: "Right Ball" BottomSurface: 0 CanCollide: true TopSurface: 0 FormFactor: 3 Size: Vector3.new(1.5,1.5,1.5) CFrame: CFrame.new(v.Character["Right Leg"].Position) BrickColor: ConfigSystem("Get", "Ero-iro") } b2sm = CreateInstance"SpecialMesh"{ Parent: ball2 MeshType: "Sphere" Scale: Vector3.new(0.3,0.3,0.3) } b2w = CreateInstance"Weld"{ Parent: ball2 Part0: v.Character["Right Leg"] Part1: ball2 C0: CFrame.new(-(0.3),1,-(0.6)) } Neck1(d,seg) while wait() for i=1,50 n.C0 = n.C0 *CFrame.Angles(math.rad(-(0.2)),0,0) wait(0.0015) for i=1,50 n.C0 = n.C0 *CFrame.Angles(math.rad(0.2),0,0) wait(0.0015) }
25.06422
91
0.608712
07468234f822c4c4a4e127614f04652fb273ee3c
2,011
-- Copyright 2015 The Howl Developers -- License: MIT (see LICENSE.md at the top-level directory of the distribution) import PropertyObject from howl.util.moon {:copy} = moon translate = (m, buf) -> m = copy m m.start_offset = buf\char_offset m.start_offset m.end_offset = buf\char_offset m.end_offset m adjust_marker_offsets = (marker, b) -> error "Missing field 'name'", 3 unless marker.name marker = copy marker if marker.byte_start_offset and marker.byte_end_offset marker.start_offset = marker.byte_start_offset marker.end_offset = marker.byte_end_offset marker.byte_start_offset = nil marker.byte_end_offset = nil else for f in *{ 'start_offset', 'end_offset' } v = marker[f] error "Missing field '#{f}'", 3 unless v if v < 1 or v > b.length + 1 error "Invalid offset '#{v}' (length: #{b.length})" marker[f] = b\byte_offset v marker class BufferMarkers extends PropertyObject new: (@a_buffer) => super! @markers = @a_buffer.markers @property all: { get: => ms = @markers\for_range 1, @a_buffer.size + 1 [translate(m, @a_buffer) for m in *ms] } add: (markers) => return if #markers == 0 markers = [adjust_marker_offsets(m, @a_buffer) for m in *markers] @markers\add markers at: (offset, selector) => @for_range offset, offset + 1 for_range: (start_offset, end_offset, selector) => start_offset = @a_buffer\byte_offset start_offset end_offset = @a_buffer\byte_offset end_offset ms = @markers\for_range start_offset, end_offset, selector [translate(m, @a_buffer) for m in *ms] remove: (selector) => @markers\remove selector remove_for_range: (start_offset, end_offset, selector) => start_offset = @a_buffer\byte_offset start_offset end_offset = @a_buffer\byte_offset end_offset @markers\remove_for_range start_offset, end_offset, selector find: (selector) => ms = @markers\find selector [translate(m, @a_buffer) for m in *ms]
29.144928
79
0.685728
d3fa26e193f249a1bcaf61b6fec42a9636720598
168
import exec from require "libs.cfglib" import addMessage from require "libs.say" class Killme handle: (input) => if input\lower!\match("kill") exec "kill"
21
41
0.690476
43b7362d7d5a18d5fe364157533ee9ad9c7d312f
229
export modinfo = { type: "command" desc: "Remove Legs" alias: {"nolegs"} func: getDoPlayersFunction (v) -> for i,j in pairs(v.Character\GetChildren()) if j.Name == "Left Leg" or j.Name == "Right Leg" j.Parent = nil }
25.444444
51
0.637555
5ce23121a77de26bf8d030e90436970fe917dec1
2,096
export script_name = 'Line Separator' export script_description = 'Break apart consecutive lines' export script_author = 'CoffeeFlux' export script_version = '1.0.0' export script_namespace = 'Flux.LineSeparator' DependencyControl = require('l0.DependencyControl') { url: 'https://github.com/TypesettingTools/CoffeeFlux-Aegisub-Scripts/blob/master/macros/Flux.LineSeparator.moon' feed: 'https://raw.githubusercontent.com/TypesettingTools/CoffeeFlux-Aegisub-Scripts/master/DependencyControl.json' { {'a-mo.LineCollection', version: '1.2.0', url: 'https://github.com/TypesettingTools/Aegisub-Motion', feed: 'https://raw.githubusercontent.com/TypesettingTools/Aegisub-Motion/DepCtrl/DependencyControl.json'} } } LineCollection = DependencyControl\requireModules! ConfigHandler = DependencyControl\getConfigHandler { settings: { frames: 3 } } settings = ConfigHandler.c.settings dialog = { { class: "label" label: "Frames:" x: 0 y: 0 } { class: "intedit" name: "frames" value: settings.frames min: 1 max: 99 -- arbitrarily large number x: 2 y: 0 } } updateDialog = -> dialog[2].value = settings.frames separate = (subs, sel, active) -> lines = LineCollection subs, sel lines\runCallback (lines, line, i) -> unless i == #lines endFrame = line.endFrame nextLineStartFrame = lines[i + 1].startFrame diff = settings.frames - (nextLineStartFrame - endFrame) if diff <= settings.frames and diff > 0 line.end_time = aegisub.ms_from_frame endFrame - diff lines\replaceLines! config = -> button, results = aegisub.dialog.display dialog if button settings.frames = results.frames ConfigHandler\write! updateDialog! DependencyControl\registerMacros { { "Separate Lines", "Separates lines that're closer than the specified value", separate } { "Configure", "Launches the configuration dialog", config } }
30.376812
119
0.656966
56952e1ebf434b1c703bd5cca97066683b6eb5bb
799
import Postgres from require "kpgmoon" HOST = "127.0.0.1" PORT = "9999" USER = "postgres" DB = "pgmoon_test" describe "kpgmoon with server", -> local pg setup -> os.execute "spec/postgres.sh start" teardown -> os.execute "spec/postgres.sh stop" it "connects without ssl on ssl server", -> pg = Postgres { database: DB port: PORT user: USER host: HOST } assert pg\connect! assert pg\query "select * from information_schema.tables" pg\disconnect! it "connects with ssl on ssl server", -> pg = Postgres { database: DB port: PORT user: USER host: HOST ssl: true ssl_required: true } assert pg\connect! assert pg\query "select * from information_schema.tables" pg\disconnect!
18.159091
61
0.617021
bf528d44ac392add727d21113b1869b659fec4bd
752
export script_name = "Dup after" export script_description = "Duplicates and shifts by original duration" dup = (subs, sel) -> return for i in *sel with line = subs[i] duration = .end_time - .start_time .start_time += duration .end_time += duration line aegisub.register_macro script_name, script_description, (subs, sel) -> for i,line in pairs dup(subs,sel) subs.insert sel[i] + i, line [k+v for k,v in pairs sel] aegisub.register_macro script_name..' and group', script_description..' (place the copy in continuous group after the last selected line)', (subs, sel) -> subs.insert sel[#sel] + 1, unpack dup(subs,sel) [sel[#sel] + i for i = 1,#sel]
34.181818
93
0.62766
2e4d01ce642983ab09fdd1e5327646d43f7c2afd
111
-- string test describe "string test suit", -> it "is mutable ?", -> x = "xx" assert.True "xx"==x
12.333333
31
0.531532
26f94dc265513f7da4e24568f579b4edbeb3f3e7
18,690
-- Copyright 2012-2015 The Howl Developers -- License: MIT (see LICENSE.md at the top-level directory of the distribution) import Window, Editor, theme from howl.ui import Buffer, Settings, mode, breadcrumbs, bundle, bindings, keymap, signal, interact, timer, clipboard, config from howl import File, Process from howl.io import PropertyObject from howl.util.moon Gtk = require 'ljglibs.gtk' callbacks = require 'ljglibs.callbacks' {:get_monotonic_time} = require 'ljglibs.glib' {:C} = require('ffi') bit = require 'bit' append = table.insert coro_create, coro_status = coroutine.create, coroutine.status non_idle_dispatches = { '^signal motion%-', '^signal key%-press%-event', '^signal button%-', } is_idle_dispatch = (desc) -> for p in *non_idle_dispatches return false if desc\find(p) != nil true last_activity = get_monotonic_time! dispatcher = (f, description, ...) -> unless is_idle_dispatch(description) last_activity = get_monotonic_time! co = coro_create (...) -> f ... status, ret = coroutine.resume co, ... if status if coro_status(co) == 'dead' return ret else error ret false sort_buffers = (buffers, current_buffer=nil) -> table.sort buffers, (a, b) -> if current_buffer == a return true if current_buffer == b return false return true if a.showing and not b.showing return false if b.showing and not a.showing -- if none of the buffers are showing, we compare the last shown time unless a.showing ls_a = a.last_shown or 0 ls_b = b.last_shown or 0 return ls_a > ls_b if ls_a != ls_b a.title < b.title parse_path_args = (paths, cwd=nil) -> files = {} hints = {} for path in *paths local file line, col = 1, 1 e_path, s_line, s_col = path\match '^(.+):(%d+):(%d+)$' if e_path file = e_path line = tonumber s_line col = s_col else e_path, s_line = path\match '^(.+):(%d+)$' if e_path file = e_path line = tonumber s_line else file = path files[#files + 1] = File(file, cwd).gfile hints[#hints + 1] = "#{line}:#{col}" files, hints class Application extends PropertyObject title: 'Howl' new: (@root_dir, @args) => @windows = {} @_editors = {} @_buffers = {} @_recently_closed = {} bundle.dirs = { @root_dir / 'bundles' } @_load_base! bindings.push keymap @window = nil @editor = nil callbacks.configure { :dispatcher, on_error: _G.log.error } signal.connect 'log-entry-appended', (entry) -> level = entry.level message = entry.message return if level == 'traceback' if @window and @window.visible essentials = entry.essentials status = @window.status status[level] status, essentials @window.command_panel\notify essentials, level elseif not @args.spec print message super! @property idle: get: => tonumber(get_monotonic_time! - last_activity) / 1000 / 1000 @property buffers: get: => buffers = { table.unpack @_buffers } sort_buffers buffers, (@editor and @editor.buffer) buffers @property recently_closed: get: => moon.copy @_recently_closed @property editors: get: => @_editors @property next_buffer: get: => return @new_buffer! if #@_buffers == 0 sort_buffers @_buffers hidden_buffers = [b for b in *@_buffers when not b.showing] return #hidden_buffers > 0 and hidden_buffers[1] or @_buffers[1] new_window: (properties = {}) => props = title: @title props[k] = v for k, v in pairs(properties) window = Window props window\set_default_size 800, 640 window\on_delete_event -> if #@windows == 1 modified = [b for b in *@_buffers when b.modified] if #modified > 0 -- postpone the quit check, since we really need to prevent -- the close right away by returning true timer.asap -> @quit! else @quit! true window\on_destroy (destroy_window) -> @windows = [w for w in *@windows when w\to_gobject! != destroy_window] @g_app\add_window window\to_gobject! append @windows, window @window = window if #@windows == 1 window new_editor: (opts = {}) => editor = Editor opts.buffer or @next_buffer (opts.window or @window)\add_view editor, opts.placement or 'right_of' append @_editors, editor editor\grab_focus! editor editor_for_buffer: (buffer) => for visible_editor in *@_editors if visible_editor.buffer == buffer return visible_editor nil new_buffer: (buffer_mode) => buffer_mode or= mode.by_name 'default' buffer = Buffer buffer_mode @_append_buffer buffer buffer add_buffer: (buffer, show = true) => for b in *@buffers return if b == buffer @_append_buffer buffer if show and @editor breadcrumbs.drop! @editor.buffer = buffer @editor close_buffer: (buffer, force = false) => unless force local prompt if buffer.modified prompt = "Buffer '#{buffer.title}' is modified, close anyway? " elseif buffer.activity and buffer.activity\is_running! prompt = "Buffer has a running activity (#{buffer.activity.name}), close anyway? " if prompt @editor.buffer = buffer return unless interact.yes_or_no :prompt @_buffers = [b for b in *@_buffers when b != buffer] if buffer.file @_add_recently_closed buffer if buffer.showing for editor in *@editors if editor.buffer == buffer if editor == @editor -- if showing in the current editor breadcrumbs.drop! -- we drop a crumb here editor.buffer = @next_buffer signal.emit 'buffer-closed', :buffer open_file: (file, editor = @editor) => @open :file, editor open: (loc, editor) => return unless loc unless loc.buffer or loc.file error "Malformed loc: either .buffer or .file must be set", 2 file = loc.file buffer = loc.buffer or @_buffer_for_file(file) if buffer @add_buffer buffer else -- open the file specified buffer = @new_buffer mode.for_file file status, err = pcall -> buffer.file = file if not status @close_buffer buffer error "Failed to open #{file}: #{err}" @_recently_closed = [file_info for file_info in *@_recently_closed when file_info.file != buffer.file] signal.emit 'file-opened', :file, :buffer -- all right, now we got a buffer, let's get an editor if needed unless editor editor = @editor_for_buffer(loc.buffer) or @editor editor or= @new_editor buffer -- buffer and editor in place, drop a crumb and show the location breadcrumbs.drop { buffer: editor.buffer, pos: editor.cursor.pos, line_at_top: editor.line_at_top } editor.buffer = buffer if loc.line_nr editor.line_at_center = loc.line_nr opts = line: loc.line_nr if loc.column opts.column = loc.column elseif loc.column_index opts.column_index = loc.column_index editor.cursor\move_to opts if loc.highlights for hl in *loc.highlights editor\highlight hl, loc.line_nr -- drop another breadcrumb at the new location breadcrumbs.drop! buffer, editor save_all: => for b in *@buffers if b.modified unless b.file log.error "No file associated with modified buffer '#{b}'" return false b\save! true synchronize: => clipboard.synchronize! reload_count = 0 changed_count = 0 for b in *@_buffers if b.modified_on_disk changed_count += 1 unless b.modified b\reload! reload_count += 1 if changed_count > 0 msg = "Files modified on disk: #{reload_count} buffer(s) reloaded" stale_count = changed_count - reload_count if stale_count > 0 log.warn "#{msg}, #{stale_count} modified buffer(s) left" else log.info msg run: => jit.off true, true args = @args app_base = 'io.howl.Editor' flags = bit.bor( Gtk.Application.HANDLES_OPEN, Gtk.Application.HANDLES_COMMAND_LINE ) @g_app = Gtk.Application app_base, flags @g_app\register! -- by default we'll not open files in the same instance, -- but this can be toggled via the --reuse command line parameter if @g_app.is_remote and not @args.reuse @g_app = Gtk.Application "#{app_base}-#{os.time!}", bit.bor( flags, Gtk.Application.NON_UNIQUE ) @g_app\register! @g_app\on_activate -> @_load! @g_app\on_open (_, files, hint) -> hints = [h for h in hint\gmatch '[^,]+'] @_load files, hints @g_app\on_command_line (app, command_line) -> paths = [v for v in *command_line.arguments[2, ] when not v\match('^-')] files, hints = parse_path_args paths, command_line.cwd if #files > 0 app\open files, table.concat(hints, ',') else app\activate! signal.connect 'window-focused', self\synchronize signal.connect 'editor-destroyed', (s_args) -> @_editors = [e for e in *@_editors when e != s_args.editor] breadcrumbs.init! @g_app\run args quit: (force = false) => if force or not @_should_abort_quit! unless #@args > 1 @save_session! if config.save_config_on_exit unless pcall config.save_config print 'Error saving config' for _, process in pairs Process.running process\send_signal 'KILL' for win in * moon.copy @windows win.command_panel\cancel! win\destroy! howl.clipboard.store! save_session: => return if @args.no_profile or #@args > 1 session = { version: 1 buffers: {} recently_closed: {} window: { maximized: @window.maximized fullscreen: @window.fullscreen } } for b in *@buffers continue unless b.file append session.buffers, { file: b.file.path last_shown: b.last_shown properties: b.properties } for f in *@_recently_closed append session.recently_closed, { file: f.file.path last_shown: f.last_shown } @settings\save_system 'session', session pump_mainloop: (max_count = 100) => jit.off true, true count = 0 ctx = C.g_main_context_default! while count < max_count and C.g_main_context_iteration(ctx, false) != 0 count += 1 _append_buffer: (buffer) => if config.autoclose_single_buffer and #@_buffers == 1 present = @_buffers[1] if not present.file and not present.modified and present.length == 0 @_buffers[1] = buffer return append @_buffers, buffer _buffer_for_file: (file) => for b in *@buffers return b if b.file == file nil _load: (files = {}, hints = {}) => local window -- bootstrap if we're booting up unless @_loaded @settings = Settings! config.load_config! @_load_core! if @settings.dir and not @args.no_profile append bundle.dirs, @settings.dir\join 'bundles' fonts_dir = @settings.dir\join('fonts') if fonts_dir.exists C.FcConfigAppFontAddDir(nil, fonts_dir.path) if howl.sys.info.is_flatpak append bundle.dirs, File '/app/bundles' bundle.load_all! unless @args.no_profile status, ret = pcall @settings.load_user, @settings unless status log.error "Failed to load user settings: #{ret}" theme.apply! @_load_application_icon! signal.connect 'mode-registered', self\_on_mode_registered signal.connect 'mode-unregistered', self\_on_mode_unregistered window = @new_window! howl.janitor.start! -- load files from command line loaded_buffers = {} for i = 1, #files file = File files[i] buffer = @_buffer_for_file file unless buffer buffer = @new_buffer mode.for_file file status, ret = pcall -> buffer.file = file if not status @close_buffer buffer buffer = nil log.error "Failed to open file '#{file}': #{ret}" if buffer hint = hints[i] if hint nums = [tonumber(v) for v in hint\gmatch('%d+')] {line, column} = nums buffer.properties.position = :line, :column append loaded_buffers, buffer -- files we've loaded via a --reuse invocation should be shown if #loaded_buffers > 0 and @_loaded for i = 1, math.min(#@editors, #loaded_buffers) b = loaded_buffers[i] pos = b.properties.position with @editors[i] .buffer = b .cursor\move_to pos .line_at_center = .cursor.line -- all loaded files should be considered as having been viewed just now now = howl.sys.time! for b in *loaded_buffers b.last_shown = now -- restore session properties unless @_loaded unless @args.no_profile @_restore_session window, #files == 0 if #@editors == 0 @editor = @new_editor @_buffers[1] or @new_buffer! for b in *loaded_buffers signal.emit 'file-opened', file: b.file, buffer: b unless @_loaded window\show_all! if window @editor.line_at_center = @editor.cursor.line @_loaded = true howl.io.File.async = true config.broadcast_config! signal.emit 'app-ready' @_set_initial_status window _should_abort_quit: => modified = [b for b in *@_buffers when b.modified] if #modified > 0 if not interact.yes_or_no prompt: "Modified buffers exist, close anyway? " return true false _on_mode_registered: (args) => -- check if any buffers with default_mode could use this new mode default_mode = mode.by_name 'default' for buffer in *@_buffers if buffer.file and buffer.mode == default_mode buffer_mode = mode.for_file buffer.file if mode != default_mode buffer.mode = buffer_mode _on_mode_unregistered: (args) => -- remove the mode from any buffers that are previously using it mode_name = args.name default_mode = mode.by_name 'default' for buffer in *@_buffers if buffer.mode.name == mode_name if buffer.file buffer.mode = mode.for_file buffer.file else buffer.mode = default_mode _restore_session: (window, restore_buffers) => session = @settings\load_system 'session' if session and session.version == 1 if restore_buffers for entry in *session.buffers file = File(entry.file) continue unless file.exists status, err = pcall -> buffer = @new_buffer mode.for_file file buffer.file = file buffer.last_shown = entry.last_shown buffer.properties = entry.properties signal.emit 'file-opened', :file, :buffer log.error "Failed to load #{file}: #{err}" unless status if session.recently_closed @_recently_closed = [{file: File(file_info.file), last_shown: file_info.last_shown} for file_info in *session.recently_closed] if session.window with session.window window.maximized = .maximized window.fullscreen = .fullscreen _set_initial_status: (window) => if log.last_error startup_errors = [e for e in *log.entries when e.level == 'error'] window.status\error "#{log.last_error.message} (#{#startup_errors} startup errors in total)" else window.status\info 'Howl ready.' _load_base: => require 'howl.variables.core_variables' require 'howl.modes' _load_core: => require 'howl.ui.icons.font_awesome' require 'howl.completion.in_buffer_completer' require 'howl.completion.api_completer' require 'howl.interactions.basic' require 'howl.interactions.buffer_selection' require 'howl.interactions.buffer_search' require 'howl.interactions.bundle_selection' require 'howl.interactions.clipboard' require 'howl.interactions.external_command' require 'howl.interactions.explorer' require 'howl.interactions.file_selection' require 'howl.interactions.line_selection' require 'howl.interactions.location_selection' require 'howl.interactions.mode_selection' require 'howl.interactions.search' require 'howl.interactions.select' require 'howl.interactions.signal_selection' require 'howl.interactions.text_entry' require 'howl.interactions.variable_assignment' require 'howl.commands.file_commands' require 'howl.commands.app_commands' require 'howl.commands.ui_commands' require 'howl.commands.edit_commands' require 'howl.editing' require 'howl.janitor' require 'howl.inspect' require 'howl.file_search' _load_application_icon: => dir = @root_dir while dir icon = dir\join('share/icons/hicolor/scalable/apps/howl.svg') if icon.exists status, err = pcall Gtk.Window.set_default_icon_from_file, icon.path log.error "Failed to load application icon: #{err}" unless status return dir = dir.parent log.warn "Failed to find application icon" _add_recently_closed: (buffer) => @_recently_closed = [file_info for file_info in *@_recently_closed when file_info.file != buffer.file] append @_recently_closed, { file: buffer.file last_shown: buffer.last_shown } count = #@_recently_closed limit = config.recently_closed_limit if count > limit overage = count - limit @_recently_closed = [@_recently_closed[idx] for idx = 1 + overage, limit + overage] config.define name: 'recently_closed_limit' description: 'The number of files to remember in the recently closed list' default: 1000 type_of: 'number' scope: 'global' config.define name: 'autoclose_single_buffer' description: 'When only one, empty buffer is open, automatically close it when another is created' default: true type_of: 'boolean' scope: 'global' signal.register 'file-opened', description: 'Signaled right after a file was opened in a buffer', parameters: buffer: 'The buffer that the file was opened into' file: 'The file that was opened' signal.register 'buffer-closed', description: 'Signaled right after a buffer was closed', parameters: buffer: 'The buffer that was closed' signal.register 'app-ready', description: 'Signaled right after the application has completed initialization' return Application
28.232628
136
0.645532
9f05a4459db5f15a42a054445577b2648b1af220
16,259
-- -- Copyright (C) 2017-2020 DBotThePony -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -- of the Software, and to permit persons to whom the Software is furnished to do so, -- subject to the following conditions: -- The above copyright notice and this permission notice shall be included in all copies -- or substantial portions of the Software. -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, -- INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR -- PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE -- FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -- OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -- DEALINGS IN THE SOFTWARE. import FrameNumberL, RealTimeL, PPM2 from _G import GetPonyData, IsDormant, PPMBonesModifier, IsPony from FindMetaTable('Entity') RENDER_HORN_GLOW = CreateConVar('ppm2_horn_glow', '1', {FCVAR_ARCHIVE, FCVAR_NOTIFY}, 'Visual horn glow when player uses physgun') HORN_PARTICLES = CreateConVar('ppm2_horn_particles', '1', {FCVAR_ARCHIVE, FCVAR_NOTIFY}, 'Visual horn particles when player uses physgun') HORN_FP = CreateConVar('ppm2_horn_firstperson', '1', {FCVAR_ARCHIVE, FCVAR_NOTIFY}, 'Visual horn effetcs in first person') HORN_HIDE_BEAM = CreateConVar('ppm2_horn_nobeam', '1', {FCVAR_ARCHIVE, FCVAR_NOTIFY}, 'Hide physgun beam') DRAW_LEGS_DEPTH = CreateConVar('ppm2_render_legsdepth', '1', {FCVAR_ARCHIVE, FCVAR_NOTIFY}, 'Render legs in depth pass. Useful with Boken DoF enabled') LEGS_RENDER_TYPE = CreateConVar('ppm2_render_legstype', '0', {FCVAR_ARCHIVE, FCVAR_NOTIFY}, 'When render legs. 0 - Before Opaque renderables; 1 - after Translucent renderables') PPM2.ENABLE_NEW_RAGDOLLS = CreateConVar('ppm2_sv_phys_ragdolls', '0', {FCVAR_NOTIFY, FCVAR_REPLICATED}, 'Enable physics ragdolls (Pre March 2020 gmod update workaround)') ENABLE_NEW_RAGDOLLS = PPM2.ENABLE_NEW_RAGDOLLS SHOULD_DRAW_VIEWMODEL = CreateConVar('ppm2_cl_draw_hands', '1', {FCVAR_ARCHIVE}, 'Should draw hooves as viewmodel') SV_SHOULD_DRAW_VIEWMODEL = CreateConVar('ppm2_sv_draw_hands', '1', {FCVAR_NOTIFY, FCVAR_REPLICATED}, 'Should draw hooves as viewmodel') VM_MAGIC = CreateConVar('ppm2_cl_vm_magic', '0', {FCVAR_ARCHIVE, FCVAR_USERINFO}, 'Modify viewmodel when pony has horn for more immersion. Has no effect when ppm2_cl_vm_magic_hands is on') VM_MAGIC_HANDS = CreateConVar('ppm2_cl_vm_magic_hands', '1', {FCVAR_ARCHIVE, FCVAR_USERINFO}, 'Use magic hands when pony has horn. Due to gmod behavior, sometimes this does not work') PPM2.VM_MAGIC = VM_MAGIC PPM2.VM_MAGIC_HANDS = VM_MAGIC_HANDS validHands = (hands) -> hands == 'models/ppm/c_arms_pony.mdl' hook.Add 'PreDrawPlayerHands', 'PPM2.ViewModel', (arms = NULL, viewmodel = NULL, ply = LocalPlayer(), weapon = NULL) -> return if PPM2.__RENDERING_REFLECTIONS or not IsValid(arms) or not ply.__cachedIsPony observer = ply\GetObserverTarget() return if IsValid(observer) and not observer.__cachedIsPony return true if not SV_SHOULD_DRAW_VIEWMODEL\GetBool() or not SHOULD_DRAW_VIEWMODEL\GetBool() if IsValid(observer) return if not observer\Alive() else return if not ply\Alive() arms\SetPos(ply\EyePos() + Vector(0, 0, 100)) wep = ply\GetActiveWeapon() return true if IsValid(wep) and wep.UseHands == false amodel = arms\GetModel() return if not validHands(amodel) data = ply\GetPonyData() return unless data return true if data\GetPonyRaceFlags()\band(PPM2.RACE_HAS_HORN) ~= 0 and VM_MAGIC\GetBool() and not VM_MAGIC_HANDS\GetBool() status = data\GetRenderController()\PreDrawArms(arms) return status if status ~= nil arms.__ppm2_draw = true hook.Add 'PostDrawPlayerHands', 'PPM2.ViewModel', (arms = NULL, viewmodel = NULL, ply = LocalPlayer(), weapon = NULL) -> return if PPM2.__RENDERING_REFLECTIONS return unless IsValid(arms) return unless arms.__ppm2_draw data = ply\GetPonyData() return unless data data\GetRenderController()\PostDrawArms(arms) arms.__ppm2_draw = false local lastPos, lastAng CalcViewModelView = (weapon, vm, oldPos, oldAng, pos, ang) -> return if not VM_MAGIC\GetBool() or VM_MAGIC_HANDS\GetBool() ply = LocalPlayer() return if PPM2.__RENDERING_REFLECTIONS or not IsValid(vm) or not ply.__cachedIsPony observer = ply\GetObserverTarget() return if IsValid(observer) and not observer.__cachedIsPony return if not SV_SHOULD_DRAW_VIEWMODEL\GetBool() or not SHOULD_DRAW_VIEWMODEL\GetBool() if IsValid(observer) return if not observer\Alive() else return if not ply\Alive() return if ply\GetPonyRaceFlags()\band(PPM2.RACE_HAS_HORN) == 0 return if IsValid(weapon) and weapon.UseHands == false shouldShift = not (weapon.IsTFA and weapon\IsTFA() and weapon.IronSightsProgress > 0.6) -- since pos and ang never get refreshed, i would modify those to get desired results -- with other addons installed if shouldShift fwd = ply\EyeAngles()\Forward() right = ply\EyeAngles()\Right() pos2 = pos + fwd * math.sin(CurTimeL()) + right * math.cos(CurTimeL() + 1.2) + right * 4 - fwd * 2 ang2 = Angle(ang) pos.z -= 4 ang2\RotateAroundAxis(ang\Forward(), -30) lastPos = pos2 lastAng = ang2 else lastPos = LerpVector(FrameTime() * 11, lastPos or pos, pos) lastAng = LerpAngle(FrameTime() * 11, lastAng or ang, ang) pos.x, pos.y, pos.z = lastPos.x, lastPos.y, lastPos.z ang.p, ang.y, ang.r = lastAng.p, lastAng.y, lastAng.r hook.Add 'CalcViewModelView', 'PPM2.ViewModel', CalcViewModelView, -3 -- indraw = false -- -- magicMat = CreateMaterial('ppm2_magic_material', 'UnlitGeneric', { -- '$basetexture': 'models/debug/debugwhite' -- '$ignorez': 1 -- '$vertexcolor': 1 -- '$vertexalpha': 1 -- '$nolod': 1 -- '$color2': '{255 255 255}' -- }) -- hook.Add 'PostDrawViewModel', 'PPM2.ViewModel', (vm, ply, weapon) -> -- return if indraw -- return if not VM_MAGIC\GetBool() or VM_MAGIC_HANDS\GetBool() -- return if not IsValid(vm) or not IsValid(ply) or not IsValid(weapon) -- return if PPM2.__RENDERING_REFLECTIONS or not IsValid(vm) or not ply.__cachedIsPony -- observer = ply\GetObserverTarget() -- return if IsValid(observer) and not observer.__cachedIsPony -- return if not SV_SHOULD_DRAW_VIEWMODEL\GetBool() or not SHOULD_DRAW_VIEWMODEL\GetBool() -- return if IsValid(weapon) and weapon.UseHands == false -- -- if IsValid(observer) -- return if not observer\Alive() -- else -- return if not ply\Alive() -- -- return if ply\GetPonyRaceFlags()\band(PPM2.RACE_HAS_HORN) == 0 -- data = ply\GetPonyData() -- return if not data -- -- indraw = true -- color = data\ComputeMagicColor() -- -- magicMat\SetVector('$color2', color\ToVector()) -- render.MaterialOverride(magicMat) -- render.ModelMaterialOverride(magicMat) -- -- cam.IgnoreZ(true) -- -- mat = Matrix() -- mat\Scale(Vector(1.1, 1.1, 1.1)) -- vm\EnableMatrix('RenderMultiply', mat) -- -- ply\DrawModel() -- vm\DisableMatrix('RenderMultiply') -- -- cam.IgnoreZ(false) -- -- render.MaterialOverride() -- render.ModelMaterialOverride() -- indraw = false mat_dxlevel = GetConVar('mat_dxlevel') timer.Create 'PPM2.CheckDXLevel', 180, 0, -> if mat_dxlevel\GetInt() > 90 timer.Remove 'PPM2.CheckDXLevel' return PPM2.Message('Direct3D Level is LESS THAN 9.1! This will not work!') IN_DRAW = false player_GetAll = player.GetAll PPM2.PreDrawOpaqueRenderables = (bDrawingDepth, bDrawingSkybox) -> return if IN_DRAW or PPM2.__RENDERING_REFLECTIONS if bDrawingDepth and DRAW_LEGS_DEPTH\GetBool() with LocalPlayer() if .__cachedIsPony and \Alive() if data = \GetPonyData() IN_DRAW = true data\GetRenderController()\DrawLegsDepth() IN_DRAW = false return if bDrawingDepth or bDrawingSkybox if not LEGS_RENDER_TYPE\GetBool() with LocalPlayer() if .__cachedIsPony and \Alive() if data = \GetPonyData() IN_DRAW = true data\GetRenderController()\DrawLegs() IN_DRAW = false return PPM2.PostDrawTranslucentRenderables = (bDrawingDepth, bDrawingSkybox) -> if LEGS_RENDER_TYPE\GetBool() with LocalPlayer() if .__cachedIsPony and \Alive() if data = \GetPonyData() IN_DRAW = true data\GetRenderController()\DrawLegs() IN_DRAW = false return PPM2.PostDrawOpaqueRenderables = (bDrawingDepth, bDrawingSkybox) -> return if IN_DRAW or PPM2.__RENDERING_REFLECTIONS if bDrawingDepth and DRAW_LEGS_DEPTH\GetBool() with LocalPlayer() if .__cachedIsPony and \Alive() if data = \GetPonyData() IN_DRAW = true data\GetRenderController()\DrawLegsDepth() IN_DRAW = false return if bDrawingDepth or bDrawingSkybox if not ENABLE_NEW_RAGDOLLS\GetBool() for _, ply in ipairs player.GetAll() alive = ply\Alive() ply.__ppm2_last_dead = RealTimeL() + 2 if not alive if ply.__cachedIsPony if ply\GetPonyData() and not alive data = ply\GetPonyData() rag = ply\GetRagdollEntity() if IsValid(rag) renderController = data\GetRenderController() data\DoRagdollMerge() if renderController renderController\PreDraw(rag) IN_DRAW = true rag\DrawModel() IN_DRAW = false renderController\PostDraw(rag) return Think = -> for _, task in ipairs PPM2.NetworkedPonyData.RenderTasks ent = task.ent if IsValid(ent) and ent.__cachedIsPony if ent.__ppm2_task_hit ent.__ppm2_task_hit = false ent\SetNoDraw(false) if not ent.__ppm2RenderOverride ent = ent ent.__ppm2_oldRenderOverride = ent.RenderOverride ent.__ppm2RenderOverride = -> renderController = task\GetRenderController() renderController\PreDraw(ent, true) if ent.__ppm2_oldRenderOverride ent.__ppm2_oldRenderOverride(ent) else ent\DrawModel() renderController\PostDraw(ent, true) ent.RenderOverride = ent.__ppm2RenderOverride PPM2.PrePlayerDraw = => return if PPM2.__RENDERING_REFLECTIONS with data = GetPonyData(@) return if not data @__cachedIsPony = IsPony(@) return if not @__cachedIsPony f = FrameNumberL() return if @__ppm2_last_draw == f renderController = data\GetRenderController() if renderController renderController\PreDraw() @__ppm2_last_draw = f bones = PPMBonesModifier(@) if data and bones\CanThink() bones\ResetBones() hook.Call('PPM2.SetupBones', nil, @, data) if data bones\Think() @_ppmBonesModified = true return PPM2.PostPlayerDraw = => return if PPM2.__RENDERING_REFLECTIONS with data = GetPonyData(@) return if not data or not @__cachedIsPony renderController = data\GetRenderController() renderController\PostDraw() if renderController return do hornGlowStatus = {} smokeMaterial = 'ppm2/hornsmoke' fireMat = 'particle/fire' hornShift = Vector(1, 0.15, 14.5) hook.Add 'PreDrawHalos', 'PPM2.HornEffects', => return if not HORN_HIDE_BEAM\GetBool() frame = FrameNumberL() cTime = (RealTimeL() % 20) * 4 for ent, status in pairs hornGlowStatus if IsValid(ent) and status.frame == frame and IsValid(status.target) additional = math.sin(cTime / 2 + status.haloSeed * 3) * 40 newCol = status.color + Color(additional, additional, additional) halo.Add({status.target}, newCol, math.sin(cTime + status.haloSeed) * 4 + 8, math.cos(cTime + status.haloSeed) * 4 + 8, 2) hook.Add 'Think', 'PPM2.HornEffects', => frame = FrameNumberL() for ent, status in pairs hornGlowStatus if not IsValid(ent) status.emmiter\Finish() if IsValid(status.emmiter) status.emmiterProp\Finish() if IsValid(status.emmiterProp) hornGlowStatus[ent] = nil elseif status.frame ~= frame status.data\SetHornGlow(status.prevStatus) status.emmiter\Finish() if IsValid(status.emmiter) status.emmiterProp\Finish() if IsValid(status.emmiterProp) hornGlowStatus[ent] = nil else if not status.prevStatus and RENDER_HORN_GLOW\GetBool() and status.data\GetHornGlow() ~= status.isEnabled status.data\SetHornGlow(status.isEnabled) if status.attach and IsValid(status.target) grabHornPos = Vector(hornShift) * status.data\GetPonySize() {:Pos, :Ang} = ent\GetAttachment(status.attach) grabHornPos\Rotate(Ang) if status.isEnabled and IsValid(status.emmiter) and status.nextSmokeParticle < RealTimeL() status.nextSmokeParticle = RealTimeL() + math.Rand(0.1, 0.2) for i = 1, math.random(1, 4) vec = VectorRand() calcPos = Pos + grabHornPos + vec with particle = status.emmiter\Add(smokeMaterial, calcPos) \SetRollDelta(math.rad(math.random(0, 360))) \SetPos(calcPos) life = math.Rand(0.6, 0.9) \SetStartAlpha(math.random(80, 170)) \SetDieTime(life) \SetColor(status.color.r, status.color.g, status.color.b) \SetEndAlpha(0) size = math.Rand(2, 3) \SetEndSize(math.Rand(2, size)) \SetStartSize(size) \SetGravity(Vector()) \SetAirResistance(10) vecRand = VectorRand() vecRand.z *= 2 \SetVelocity(ent\GetVelocity() + vecRand * status.data\GetPonySize() * 2) \SetCollide(false) if status.isEnabled and IsValid(status.emmiterProp) and status.nextGrabParticle < RealTimeL() and status.mins and status.maxs status.nextGrabParticle = RealTimeL() + math.Rand(0.05, 0.3) status.emmiterProp\SetPos(status.tpos) for i = 1, math.random(2, 6) calcPos = Vector(math.Rand(status.mins.x, status.maxs.x), math.Rand(status.mins.y, status.maxs.y), math.Rand(status.mins.z, status.maxs.z)) with particle = status.emmiterProp\Add(fireMat, calcPos) \SetRollDelta(math.rad(math.random(0, 360))) \SetPos(calcPos) life = math.Rand(0.5, 0.9) \SetStartAlpha(math.random(130, 230)) \SetDieTime(life) \SetColor(status.color.r, status.color.g, status.color.b) \SetEndAlpha(0) \SetEndSize(0) \SetStartSize(math.Rand(2, 6)) \SetGravity(Vector()) \SetAirResistance(15) \SetVelocity(VectorRand() * 6) \SetCollide(false) hook.Add 'DrawPhysgunBeam', 'PPM2.HornEffects', (physgun = NULL, isEnabled = false, target = NULL, bone = 0, hitPos = Vector()) => return if not @IsPony() or not HORN_FP\GetBool() and @ == LocalPlayer() and not @ShouldDrawLocalPlayer() data = @GetPonyData() return if not data return if @GetPonyRaceFlags()\band(PPM2.RACE_HAS_HORN) == 0 if not hornGlowStatus[@] hornGlowStatus[@] = { frame: FrameNumberL() prevStatus: data\GetHornGlow() :data, :isEnabled, :hitPos, :target, :bone tpos: @GetPos() attach: @LookupAttachment('eyes') nextSmokeParticle: 0 nextGrabParticle: 0 } with hornGlowStatus[@] if HORN_PARTICLES\GetBool() .emmiter = ParticleEmitter(EyePos()) .emmiterProp = ParticleEmitter(EyePos()) .color = data\ComputeMagicColor() .haloSeed = math.rad(math.random(-1000, 1000)) else with hornGlowStatus[@] .frame = FrameNumberL() .isEnabled = isEnabled .target = target .bone = bone .hitPos = hitPos if IsValid(target) .tpos = target\GetPos() + hitPos center = target\WorldSpaceCenter() .center = center mins, maxs = target\WorldSpaceAABB() .mins = center + (mins - center) * 1.2 .maxs = center + (maxs - center) * 1.2 return false if HORN_HIDE_BEAM\GetBool() and IsValid(target) import ScrWL, ScrHL from _G import HUDCommons from DLib color_black = Color(color_black) hook.Add 'PrePlayerDraw', 'PPM2.PlayerDraw', PPM2.PrePlayerDraw, -2 hook.Add 'PostPlayerDraw', 'PPM2.PostPlayerDraw', PPM2.PostPlayerDraw, -2 hook.Add 'PostDrawOpaqueRenderables', 'PPM2.PostDrawOpaqueRenderables', PPM2.PostDrawOpaqueRenderables, -2 hook.Add 'Think', 'PPM2.UpdateRenderTasks', Think, -2 hook.Add 'PreDrawOpaqueRenderables', 'PPM2.PreDrawOpaqueRenderables', PPM2.PreDrawOpaqueRenderables, -2 hook.Add 'PostDrawTranslucentRenderables', 'PPM2.PostDrawTranslucentRenderables', PPM2.PostDrawTranslucentRenderables, -2
37.549654
188
0.71954
ab4f55eaa865ff901e6e64c3bb3e7b9c9cd72765
863
stringMap = zb2rhmQjnKBxzgPfx2PygzpLkVfQfKitv24swc78whYXvAwJz withoutPrefix = zb2rhWtPgKPHnaZTzFV1YVoAnKyziyiu3FNbfvunH1edEzkzA toLowerCase = zb2rhZycd8oM9ciVJ8D7mHCww5RzeCEXWi4BRbgU6UomyP2G8 toUpperCase = zb2rhXLdXCLBwuN3DX46hAcJxNGHXLsojopDGM1bhcG7KDZJm keccak = zb2rhhNUeNabC2amPnzJ8S5fzdn6XDYiTZ8H8EP8JD2oUFefr charToNumber = zb2rhfBJs8FuBmPT9VjZLPpg2MS7H1jGSFc5MWSP9kKwYD5Pq address => addrNoPrefix = (withoutPrefix address) addrNoPrefixLower = (stringMap toLowerCase addrNoPrefix) addrHash = (withoutPrefix (keccak addrNoPrefixLower)) shouldBeLower = char => (ltn (charToNumber char) 8) (for 0 (len addrNoPrefix) "0x" i => checksum => char = (slc addrNoPrefix i (add i 1)) charHash = (slc addrHash i (add i 1)) correctCaseChar = (if (shouldBeLower charHash) (toLowerCase char) (toUpperCase char)) (con checksum correctCaseChar))
47.944444
89
0.809965
815d8e553bdd5950b885dc5b410f44f1a36754c5
4,544
--- Includes all the .tex files in a given directory. -- @module includer -- @author Keyhan Vakil -- @license MIT module "lua.includer", package.seeall local * --- check if a file is a dotfile -- @local here -- @tparam string filename -- @treturn boolean true iff the filename starts with . is_dotfile = (filename) -> filename\sub(1, 1) == '.' --- split a file into its name and extension -- @local here -- @tparam string filename -- @treturn string the basename of the file -- @treturn string the extension of the file explode_name = (filename) -> filename\match "([^.]+)%.([^.]+)" --- creates a table of all the files and directories in directory -- @local here -- @tparam string directory to traverse -- @treturn table all of the found files include = (directory) -> -- recursively adds files in current_directory to the files table helper = (current_directory, files) -> for entry in lfs.dir current_directory if not is_dotfile entry -- ignore hidden files, esp . and .. entry = current_directory .. "/" .. entry files[entry] = true if lfs.isdir entry helper(entry, files) all_files = {} helper(directory, all_files) return all_files --- iterator which traverses the keys of a table in sorted order -- @local here -- @tparam table t the table to traverse -- @treturn function an iterator which traverses in the desired order skeys = (t) -> keys = [ k for k, _ in pairs t ] table.sort(keys) i = 0 return (using i) -> i = i + 1 if keys[i] return keys[i] --- checks if the given file is a daily log entry -- @local here -- @tparam string filename -- @treturn boolean true iff filename matches YYYY/MM/DD.tex is_day_entry = (filename) -> filename\match("^%d%d%d%d/%d%d/%d%d%.tex$") != nil --- finds the ordinal suffix of the given number -- @local here -- @tparam number number -- @treturn string the appropriate suffix (st, nd, rd or th) ordinal_suffix = (number) -> switch number when 1 then "st" when 2 then "nd" when 3 then "rd" else "th" --- formats a given date "nicely" -- @local here -- @tparam string date a YYYY/MM/DD string representing the date -- @treturn string a nicely formatted date (day name, month name and day) nice_date = (date) -> year, month, day = date\match "([^/]+)/([^/]+)/([^/]+)" utime = os.time(:year, :month, :day) day_of_week = os.date "%A", utime month_name = os.date "%B", utime day = tonumber day -- strip leading zero nice_day = "#{day}#{ordinal_suffix day}" "#{day_of_week}, #{month_name} #{nice_day}" --- outputs the entry for the given day -- @local here -- @tparam string filename containing the entry output_day_entry = (filename) -> basename, _ = explode_name filename tex.sprint "\\section{#{nice_date basename}}" tex.sprint "\\label{#{basename}}" tex.sprint "\\include*{#{basename}}" tex.sprint "\\clearpage" --- checks if the given file is a monthly log directory -- @local here -- @tparam string filename -- @treturn boolean true iff the filename matches YYYY/MM is_month = (filename) -> filename\match("^%d%d%d%d/%d%d$") != nil --- returns the month name and year -- @local here -- @tparam string date as a YYYY/MM string -- @treturn string a nicely formatted month (month name and year) nice_month = (date) -> year, month = date\match "([^/]+)/([^/]+)" utime = os.time(:year, :month, day: 1) os.date "%B %Y", utime --- outputs the entry for the given month -- @local here -- @tparam string filename output_month_entry = (filename) -> tex.sprint "\\chapter{#{nice_month filename}}" tex.sprint "\\clearpage" --- includes recent entries -- @tparam string year the year as a string (e.g. "2017") -- @tparam int n the number of entries to include lua.includer.include_recent = (year, n) -> all_files = include year entry_files = [f for f in skeys all_files when is_day_entry(f) or is_month(f)] -- @todo always include month including the days skip = #entry_files - n for _, filename in ipairs entry_files if skip < 1 if is_day_entry filename output_day_entry filename elseif is_month filename output_month_entry filename else skip -= 1 --- includes all files in the directory year/ -- @tparam string year the year as a string (e.g. "2017") lua.includer.include_year = (year) -> lua.includer.include_recent year, math.huge
33.910448
82
0.646127
86202f90beacf4bafbaf33cdd3dc60399ec8d58b
13,848
socket = require "pgmoon.socket" import insert from table import rshift, lshift, band from require "pgmoon.bit" unpack = table.unpack or unpack VERSION = "1.12.0" _len = (thing, t=type(thing)) -> switch t when "string" #thing when "table" l = 0 for inner in *thing inner_t = type inner if inner_t == "string" l += #inner else l += _len inner, inner_t l else error "don't know how to calculate length of #{t}" _debug_msg = (str) -> require("moon").dump [p for p in str\gmatch "[^%z]+"] flipped = (t) -> keys = [k for k in pairs t] for key in *keys t[t[key]] = key t MSG_TYPE = flipped { status: "S" auth: "R" backend_key: "K" ready_for_query: "Z" query: "Q" notice: "N" notification: "A" password: "p" row_description: "T" data_row: "D" command_complete: "C" error: "E" } ERROR_TYPES = flipped { severity: "S" code: "C" message: "M" position: "P" detail: "D" schema: "s" table: "t" constraint: "n" } PG_TYPES = { [16]: "boolean" [17]: "bytea" [20]: "number" -- int8 [21]: "number" -- int2 [23]: "number" -- int4 [700]: "number" -- float4 [701]: "number" -- float8 [1700]: "number" -- numeric [114]: "json" -- json [3802]: "json" -- jsonb -- arrays [1000]: "array_boolean" -- bool array [1005]: "array_number" -- int2 array [1007]: "array_number" -- int4 array [1016]: "array_number" -- int8 array [1021]: "array_number" -- float4 array [1022]: "array_number" -- float8 array [1231]: "array_number" -- numeric array [1009]: "array_string" -- text array [1015]: "array_string" -- varchar array [1002]: "array_string" -- char array [1014]: "array_string" -- bpchar array [2951]: "array_string" -- uuid array [199]: "array_json" -- json array [3807]: "array_json" -- jsonb array } NULL = "\0" tobool = (str) -> str == "t" class Postgres convert_null: false NULL: {"NULL"} :PG_TYPES user: "postgres" host: "127.0.0.1" port: "5432" ssl: false -- custom types supplementing PG_TYPES type_deserializers: { json: (val, name) => import decode_json from require "pgmoon.json" decode_json val bytea: (val, name) => @decode_bytea val array_boolean: (val, name) => import decode_array from require "pgmoon.arrays" decode_array val, tobool array_number: (val, name) => import decode_array from require "pgmoon.arrays" decode_array val, tonumber array_string: (val, name) => import decode_array from require "pgmoon.arrays" decode_array val array_json: (val, name) => import decode_array from require "pgmoon.arrays" import decode_json from require "pgmoon.json" decode_array val, decode_json hstore: (val, name) => import decode_hstore from require "pgmoon.hstore" decode_hstore val } set_type_oid: (oid, name) => unless rawget(@, "PG_TYPES") @PG_TYPES = {k,v for k,v in pairs @PG_TYPES} @PG_TYPES[assert tonumber oid] = name setup_hstore: => res = unpack @query "SELECT oid FROM pg_type WHERE typname = 'hstore'" assert res, "hstore oid not found" @set_type_oid tonumber(res.oid), "hstore" new: (opts) => @sock, @sock_type = socket.new opts and opts.socket_type if opts @user = opts.user @host = opts.host @database = opts.database @port = opts.port @password = opts.password @ssl = opts.ssl @ssl_verify = opts.ssl_verify @ssl_required = opts.ssl_required @pool_name = opts.pool @luasec_opts = { key: opts.key cert: opts.cert cafile: opts.cafile ssl_version: opts.ssl_version or "tlsv1_2" } connect: => opts = if @sock_type == "nginx" { pool: @pool_name or "#{@host}:#{@port}:#{@database}:#{@user}" } ok, err = @sock\connect @host, @port, opts return nil, err unless ok if @sock\getreusedtimes! == 0 if @ssl success, err = @send_ssl_message! return nil, err unless success success, err = @send_startup_message! return nil, err unless success success, err = @auth! return nil, err unless success success, err = @wait_until_ready! return nil, err unless success true settimeout: (...) => @sock\settimeout ... disconnect: => sock = @sock @sock = nil sock\close! keepalive: (...) => sock = @sock @sock = nil sock\setkeepalive ... auth: => t, msg = @receive_message! return nil, msg unless t unless MSG_TYPE.auth == t @disconnect! if MSG_TYPE.error == t return nil, @parse_error msg error "unexpected message during auth: #{t}" auth_type = @decode_int msg, 4 switch auth_type when 0 -- trust true when 3 -- cleartext password @cleartext_auth msg when 5 -- md5 password @md5_auth msg else error "don't know how to auth: #{auth_type}" cleartext_auth: (msg) => assert @password, "missing password, required for connect" @send_message MSG_TYPE.password, { @password NULL } @check_auth! md5_auth: (msg) => import md5 from require "pgmoon.crypto" salt = msg\sub 5, 8 assert @password, "missing password, required for connect" @send_message MSG_TYPE.password, { "md5" md5 md5(@password .. @user) .. salt NULL } @check_auth! check_auth: => t, msg = @receive_message! return nil, msg unless t switch t when MSG_TYPE.error nil, @parse_error msg when MSG_TYPE.auth true else error "unknown response from auth" query: (q) => if q\find NULL return nil, "invalid null byte in query" @post q local row_desc, data_rows, command_complete, err_msg local result, notifications num_queries = 0 while true t, msg = @receive_message! return nil, msg unless t switch t when MSG_TYPE.data_row data_rows or= {} insert data_rows, msg when MSG_TYPE.row_description row_desc = msg when MSG_TYPE.error err_msg = msg when MSG_TYPE.command_complete command_complete = msg next_result = @format_query_result row_desc, data_rows, command_complete num_queries += 1 if num_queries == 1 result = next_result elseif num_queries == 2 result = { result, next_result } else insert result, next_result row_desc, data_rows, command_complete = nil when MSG_TYPE.ready_for_query break when MSG_TYPE.notification notifications = {} unless notifications insert notifications, @parse_notification(msg) -- when MSG_TYPE.notice -- TODO: do something with notices if err_msg return nil, @parse_error(err_msg), result, num_queries, notifications result, num_queries, notifications post: (q) => @send_message MSG_TYPE.query, {q, NULL} wait_for_notification: => while true t, msg = @receive_message! return nil, msg unless t switch t when MSG_TYPE.notification return @parse_notification(msg) format_query_result: (row_desc, data_rows, command_complete) => local command, affected_rows if command_complete command = command_complete\match "^%w+" affected_rows = tonumber command_complete\match "(%d+)%z$" if row_desc return {} unless data_rows fields = @parse_row_desc row_desc num_rows = #data_rows for i=1,num_rows data_rows[i] = @parse_data_row data_rows[i], fields if affected_rows and command != "SELECT" data_rows.affected_rows = affected_rows return data_rows if affected_rows { :affected_rows } else true parse_error: (err_msg) => local severity, message, detail, position error_data = {} offset = 1 while offset <= #err_msg t = err_msg\sub offset, offset str = err_msg\match "[^%z]+", offset + 1 break unless str offset += 2 + #str if field = ERROR_TYPES[t] error_data[field] = str switch t when ERROR_TYPES.severity severity = str when ERROR_TYPES.message message = str when ERROR_TYPES.position position = str when ERROR_TYPES.detail detail = str msg = "#{severity}: #{message}" if position msg = "#{msg} (#{position})" if detail msg = "#{msg}\n#{detail}" msg, error_data parse_row_desc: (row_desc) => num_fields = @decode_int row_desc\sub(1,2) offset = 3 fields = for i=1,num_fields name = row_desc\match "[^%z]+", offset offset += #name + 1 -- 4: object id of table -- 2: attribute number of column (4) -- 4: object id of data type (6) data_type = @decode_int row_desc\sub offset + 6, offset + 6 + 3 data_type = @PG_TYPES[data_type] or "string" -- 2: data type size (10) -- 4: type modifier (12) -- 2: format code (16) -- we only know how to handle text format = @decode_int row_desc\sub offset + 16, offset + 16 + 1 assert 0 == format, "don't know how to handle format" offset += 18 {name, data_type} fields parse_data_row: (data_row, fields) => -- 2: number of values num_fields = @decode_int data_row\sub(1,2) out = {} offset = 3 for i=1,num_fields field = fields[i] continue unless field {field_name, field_type} = field -- 4: length of value len = @decode_int data_row\sub offset, offset + 3 offset += 4 if len < 0 out[field_name] = @NULL if @convert_null continue value = data_row\sub offset, offset + len - 1 offset += len switch field_type when "number" value = tonumber value when "boolean" value = value == "t" when "string" nil else if fn = @type_deserializers[field_type] value = fn @, value, field_type out[field_name] = value out parse_notification: (msg) => pid = @decode_int msg\sub 1, 4 offset = 4 channel, payload = msg\match "^([^%z]+)%z([^%z]*)%z$", offset + 1 unless channel error "parse_notification: failed to parse notification" { operation: "notification" pid: pid channel: channel payload: payload } wait_until_ready: => while true t, msg = @receive_message! return nil, msg unless t if MSG_TYPE.error == t @disconnect! return nil, @parse_error(msg) break if MSG_TYPE.ready_for_query == t true receive_message: => t, err = @sock\receive 1 unless t @disconnect! return nil, "receive_message: failed to get type: #{err}" len, err = @sock\receive 4 unless len @disconnect! return nil, "receive_message: failed to get len: #{err}" len = @decode_int len len -= 4 msg = @sock\receive len t, msg send_startup_message: => assert @user, "missing user for connect" assert @database, "missing database for connect" data = { @encode_int 196608 "user", NULL @user, NULL "database", NULL @database, NULL "application_name", NULL "pgmoon", NULL NULL } @sock\send { @encode_int _len(data) + 4 data } send_ssl_message: => success, err = @sock\send { @encode_int 8, @encode_int 80877103 } return nil, err unless success t, err = @sock\receive 1 return nil, err unless t if t == MSG_TYPE.status if @sock_type == "nginx" @sock\sslhandshake false, nil, @ssl_verify else @sock\sslhandshake @ssl_verify, @luasec_opts elseif t == MSG_TYPE.error or @ssl_required @disconnect! nil, "the server does not support SSL connections" else true -- no SSL support, but not required by client send_message: (t, data, len) => len = _len data if len == nil len += 4 -- includes the length of the length integer @sock\send { t @encode_int len data } decode_int: (str, bytes=#str) => switch bytes when 4 d, c, b, a = str\byte 1, 4 a + lshift(b, 8) + lshift(c, 16) + lshift(d, 24) when 2 b, a = str\byte 1, 2 a + lshift(b, 8) else error "don't know how to decode #{bytes} byte(s)" -- create big endian binary string of number encode_int: (n, bytes=4) => switch bytes when 4 a = band n, 0xff b = band rshift(n, 8), 0xff c = band rshift(n, 16), 0xff d = band rshift(n, 24), 0xff string.char d, c, b, a else error "don't know how to encode #{bytes} byte(s)" decode_bytea: (str) => if str\sub(1, 2) == '\\x' str\sub(3)\gsub '..', (hex) -> string.char tonumber hex, 16 else str\gsub '\\(%d%d%d)', (oct) -> string.char tonumber oct, 8 encode_bytea: (str) => string.format "E'\\\\x%s'", str\gsub '.', (byte) -> string.format '%02x', string.byte byte escape_identifier: (ident) => '"' .. (tostring(ident)\gsub '"', '""') .. '"' escape_literal: (val) => switch type val when "number" return tostring val when "string" return "'#{(val\gsub "'", "''")}'" when "boolean" return val and "TRUE" or "FALSE" error "don't know how to escape value: #{val}" __tostring: => "<Postgres socket: #{@sock}>" { :Postgres, new: Postgres, :VERSION }
22.851485
82
0.585427