content stringlengths 5 1.05M |
|---|
local constants = require(".lua.common.constants")
local logger = require(".lua.common.logger").new("gateway_new.lua")
local request_builder = require(".lua.request_builder")
local request_dispatcher = require(".lua.request_dispatcher")
local response_dispatcher = require(".lua.response_dispatcher")
local util = require(".lua.common.util")
local bucket_status_cache = require(".lua.cache.bucket_status_cache")
local user_status_cache = require(".lua.cache.user_status_cache")
local cluster_status_cache = require(".lua.cache.cluster_status_cache")
local statsHandle = require(".lua.stats.statscollector")
local replicator = require(".lua.replicator")
local cfgmgr = require(".lua.config_manager.cfgmgr")
local rate_limiter = require(".lua.rate_limiter.rate_limiter")
local function is_bucket_read_operation(context)
if context.is_bucket_operation then
if context.request_method == "GET" then
return true
end
if context.request_method == "HEAD" then
return true
end
end
return false
end
-- API Related to Bucket Status Check
-- Checks if it's a CREATE_BUCKET request
-- Param: context - Request context
-- Returns: Boolean - If it's a CREATE_BUCKET request
local function is_new_bucket_create(context)
return context.request_method == "PUT" and context.is_bucket_operation
end
local function is_bucket_delete_op(context)
return context.request_method == "DELETE" and context.is_bucket_operation
end
-- Checks if the request is a DELETE request
-- Param: context - Request context
-- Returns: Boolean - Returns True if the request is a DELETE request and False otherwise
local function is_delete_request(context)
return context.request_method == "DELETE"
end
-- Checks if the request is a SET_ACL request
-- Param: context - Request context
-- Returns: Boolean - Returns True if the request is a SET_ACL request and False otherwise
local function is_set_acl_request(context)
return context.request_method == "PUT" and context.is_acl_operation
end
-- Checks if the current request is from Elastic Load Balancer. We are seeing different variations of the healthcheck
-- string. One is plain "/" and the other is "/elb-healthcheck". Currently supporting both these variations.
-- TBD: Need to Come Up with a more Robust way of checking healthchecks from ELB.
-- Param: context - Request context
-- Returns: Boolean - Returns True if the request is from Elastic Load Balancer and False otherwise
local function is_elb_health_check(context)
--Check if the access key is non empty. There are requests other than Originating from
--ELB context, whose URI just contain "/". Example is the get_all_buckets issued from BOTO Context.
--Under Such Circumstances, checking the access_key helps differentiate bewteen the health checks and
--other API calls.
--
if context.access_key ~= nil then
return false
end
return context.bucket_name == constants.ELB_REQUEST_LOCATION or context.uri == "/"
end
-- The API expects a request context that needs to be served, as well as the designated primary
-- and secondary clusters for this request.
-- The requests are first tried in the Primary Cluster and in case of if it is unsuccesfull
-- Dispatch response if it need not be suppressed
--~ Sends request to required cluster
--~ Param: cluster_name - Cluster where request has to be sent
--~ Param: context - Request context
--~ Param: suppress_dispatch - If response dispatch has to be suppressed
--~ Returns: response obj - Response of the request sent
local function send_request(cluster_name, context, supress_dispatch)
-- suppress_dispatch is an optional param. By default, it should be false
if supress_dispatch == nil then
supress_dispatch = false
end
-- Build request object that can be dispatched by request_dispatcher
local request = request_builder.build_request(cluster_name, context.access_key, context.request_method, context.is_v4)
local response = request_dispatcher.send_request(request)
local body_size = 0
if response.body ~= nil then
body_size = #response.body
end
logger:notice(string.format("Sent Request to --> %s, Request URI --> %s, Response -->%s, Body Size --> %d", cluster_name, request.uri, response.status, body_size))
--Store the Response for this request Context from the Upstream.
--Note that in case if the same request is sent to multiple upsstreams, then only the
--most recent response will be cached.
context.response_code = response.status
statsHandle.update_req_stats("endTime")
statsHandle.print_req_details(context)
statsHandle.update_local_stats_cache(context)
-- Dispatch response if it need not be suppressed
if supress_dispatch == false then
response_dispatcher.dispatch_response(response)
end
return response
end
-- The API expects a request context that needs to be served, as well as the designated primary
-- and secondary clusters for this request.
-- The requests are first tried in the Primary Cluster and in case of if it is unsuccesfull
-- the secondary cluster is looked into.
-- It does not make sense to have the primary_cluster and secondary_cluster as same, with respect
-- to the semantics of the API.
local function handle_request_read(context, primary_cluster, secondary_cluster)
logger:notice("Serving Read Request from PC-->"..tostring(primary_cluster) .." SC -->"..tostring(secondary_cluster))
--Supress the sending of the response when trying to read from the Primary, as this may succed when
--it is read from the secondary.
local response1 = send_request(primary_cluster, context, true)
local response2 = send_request(secondary_cluster, context, true)
logger:notice("Handling Read Request is PC Resonse-->"..tostring(response1.status).. " SC Response -->"..tostring(response2.status))
-- Honor Dual 200 when both clusters Send a Response , Quite Confusing Ha
if ((response1.status == 200) and (response2.status == 200)) then
body_size_1 = #response1.body
body_size_2 = #response2.body
if (body_size_1 > body_size_2) then
response_dispatcher.dispatch_response(response1)
logger:notice("Dual 200 Read Request Served fronm --->"..tostring(primary_cluster))
else
logger:notice("Dual 200 Read Request Served fronm --->"..tostring(secondary_cluster))
response_dispatcher.dispatch_response(response2)
end
else
if ((response1.status == 404) or (response1.status == 403)) then
logger:error("Read Request Failed PC-->"..tostring(primary_cluster).." Trying in the SC -->"..tostring(secondary_cluster))
--[[
--Read Fallback Count
statsHandle.incr_ctr("readfallback_count")
]]--
logger:notice("Served Read Request from SC -->"..tostring(secondary_cluster))
response_dispatcher.dispatch_response(response2)
else
logger:notice("Served Read Request from PC -->"..tostring(primary_cluster))
response_dispatcher.dispatch_response(response1)
end
end
end
--The API will be called only for SET ACL requests in Buckets which are in failover mode
local function handle_request_write(context, primary_cluster, secondary_cluster)
logger:notice("Serving Write Request from PC-->"..tostring(primary_cluster) .." SC -->"..tostring(secondary_cluster))
--Supress the sending of the response when trying to read from the Primary, as this may succed when
--it is read from the secondary.
local write_response = send_request(primary_cluster, context, true)
logger:notice("Handling Write Request is PC Response-->"..tostring(write_response.status))
if (write_response.status == 404) then
write_response = send_request(secondary_cluster, context, true)
logger:notice("Handling Write Request is SC Response-->"..tostring(write_response.status))
end
response_dispatcher.dispatch_response(write_response)
end
-- Checks if the current request has to be rejected
-- Currently, we reject DELETE and SET_ACL request from user accounts in MIGRATING state
-- Param: context - Request context
-- Returns: Boolean - True if the request has to be rejected and False otherwise
local function reject_request_in_bucket_split_ctx(context)
if is_delete_request(context) then
statsHandle.incr_ctr("delreq_count")
logger:info("Recevied Delete Request while Migration In Progress ")
return 1
end
-- TBD : Add Check for CORS Request
end
local function send_405_response()
ngx.exit(405)
end
-- Handle the Processing of Requests for Bucket Which Are in Split State
local function handle_req_bucket_split_ctx(context)
--Get the ACTIVE and ACTIVE_SYNC Cluster, and the Operation Mode
local active_cluster = nil
local active_sync_cluster = nil
local bucket_opmode = nil
local bs = bucket_status_cache.getField(context.bucket_name,"active","active_sync","opmode")
active_cluster = bs[1]
active_sync_cluster = bs[2]
bucket_opmode = bs[3]
if active_cluster == nil then
logger:error("Bucket Mode Split, No Active Cluster Specified")
util.send_response(503)
return
end
if active_sync_cluster == nil then
logger:error("Bucket Mode Split, No Active Sync Cluster Specified")
util.send_response(503)
return
end
if bucket_opmode == nil then
logger:error("Bucket Mode Split, No BucketOPMode Specified")
util.send_response(503)
return
end
logger:notice("Bucket State: Split, AC ->"..tostring(active_cluster).." ASC ->"..tostring(active_sync_cluster).." Opmode ->"..tostring(bucket_opmode))
--The Mock Modes Are For Testing the readiness of the failover cluster, with respect to both read
--and writes. While passing the live traffic, the requests need to be repliacted as it is both on the
--AC and ASC cluster. Hence this is placed before the check for rejecting the Requests, which are
--generally not allowed when the Bucket is in Split State.
if bucket_opmode == constants.BUCKET_MOCK_FAILOVER then
if util.is_read_request(context.request_method) then
--Handle the Read Request
logger:notice("Bucket --> "..context.bucket_name .. " Mode: MOCK FAILOVER, Request : READ" .." AC -->"..tostring(active_cluster).."ASC -->"..tostring(active_sync_cluster))
handle_request_read(context, active_sync_cluster, active_cluster)
return
else
logger:notice("Bucket --> "..context.bucket_name .. " Mode: MOCK FAILOVER, Request: WRITE" .." ASC -->"..tostring(active_sync_cluster))
local response1 = send_request(active_sync_cluster, context, true)
--This part of the code is being added as a patch to sync to the Active Cluster all the writes that are being recevied
--during the bucket failover mode. In a actual bucket degradation, this call may fail.
logger:notice("Bucket --> "..context.bucket_name .. " Mode: MOCK FAILOVER, Request: WRITE" .." AC -->"..tostring(active_cluster))
local response2 = send_request(active_cluster, context, true)
logger:notice("Response ASC --->"..tostring(response1.status).." Response AC --->"..tostring(response2.status))
--Send the Response Back for The Write to ASC Only
response_dispatcher.dispatch_response(response1)
return
end
end
if bucket_opmode == constants.BUCKET_MOCK_RESTORE then
if util.is_read_request(context.request_method) then
logger:notice("Bucket --> "..context.bucket_name .. " Mode: MOCK RESTORE, Request : READ" .." AC -->"..tostring(active_cluster).."ASC -->"..tostring(active_sync_cluster))
--handle_request_read(context, active_sync_cluster, active_cluster)
--Reversing the order of the reads, the ASC Cluster is Returning 200 on a prefix match for a Object that does not exist. Until fixed the objects read access patterns
--are reversed
handle_request_read(context, active_cluster, active_sync_cluster)
return
else
logger:notice("Bucket --> "..context.bucket_name .. " Mode: MOCK RESTORE, Request: WRITE" .." AC -->"..tostring(active_cluster))
send_request(active_cluster, context)
return
end
end
-- This Block of the Code would Get Hit, if we are Running In a Degraded Mode,
-- basically marking the bucket IN FAILOVER.
-- In case of Degraded mode, the reads are tried to be served from the ASC and if fails AC
-- For writes the requests are always sent to the ASC
if bucket_opmode == constants.BUCKET_FAILOVER then
if util.is_read_request(context.request_method) then
--Handle the Read Request
logger:notice("Bucket --> "..context.bucket_name .. " Mode: FAILOVER, Request : READ" .." AC -->"..tostring(active_cluster).."ASC -->"..tostring(active_sync_cluster))
handle_request_read(context, active_sync_cluster, active_cluster)
return
else
logger:notice("Bucket --> "..context.bucket_name .. " Mode: FAILOVER, Request: WRITE" .." ASC -->"..tostring(active_sync_cluster))
--if we receive a set request in Failover, and the failover window may be extended for long times
--we would need to allow the acl go in a best effort manner
--The new writes however would fall to the active_sync_cluster only
if is_set_acl_request(context) then
handle_request_write(context, active_sync_cluster, active_cluster)
else
send_request(active_sync_cluster, context)
end
return
end
end
--TBD check for nil for any of the above tuple before proceeding
-- Block all deletes and set ACL and CORS Modificartioons from user account
-- that is being migrated for this particular bucket
-- TBD: Add Logic for a CORS GET/SET and approproate update in the API belowe
if reject_request_in_bucket_split_ctx(context) then
statsHandle.incr_ctr("rejectreq_count")
logger:error("Request Cannot be Performed Under Bucket Split State")
send_405_response()
return
end
-- For a bucket with OPMODE as MIGRATION_IN_PROGRESS the following is the flow
-- The reads for the bucket are tried in the Active Cluster First (From Where the Bucket is being Migrated)
-- If this fails the reads are tried in the the Active Sync Cluster (To Where the Bucketr is benng Migrated)
-- In case of writes, for a bucket in migration the requests are always send to the Active Sync Cluster
if bucket_opmode == constants.BUCKET_MIGRATION_IN_PROGRESS then
if util.is_read_request(context.request_method) then
--Handle the Read Request
logger:notice("Bucket --> "..context.bucket_name .. " Mode: MIGRATION, Request : READ" .." AC -->"..tostring(active_cluster).."ASC -->"..tostring(active_sync_cluster))
handle_request_read(context, active_cluster, active_sync_cluster)
return
else
--Handle the Write Request
logger:notice("Bucket --> "..context.bucket_name .. " Mode: MIGRATION, Request: WRITE" .." ASC -->"..tostring(active_sync_cluster))
send_request(context,active_sync_cluster)
return
end
end
-- This Block of the Code would Get Hit, if we are Recovering from a Degraded Mode,
-- Marking the Bucket in RESTORE
-- In case of Restore ode, the reads are tried to be served from the ASC and if fails AC
-- For writes the requests are always sent to the AC (This is the difference between FAILOVER and RESTORE Mode)
if bucket_opmode == constants.BUCKET_RESTORE then
if util.is_read_request(context.request_method) then
logger:notice("Bucket --> "..context.bucket_name .. "Mode: RESTORE, Request: READ" .." AC -->"..tostring(active_cluster).."ASC -->"..tostring(active_sync_cluster))
handle_request_read(context, active_sync_cluster, active_cluster)
return
else
logger:notice("Bucket --> "..context.bucket_name .. "Mode: RESTORE, Request: WRITE" .." AC -->"..tostring(active_cluster))
send_request(active_cluster, context)
return
end
end
end
--API for Handling Bucket Operations, when the Bucket is in Unified State.
--The Majority of the Data Flow would always be through the Unified State of the Bucket
local function handle_req_bucket_unified(context)
local target_cluster = nil
local fallback_cluster = nil
local cluster_state = nil
local orig_response = nil
local replication_response = nil
local bs = bucket_status_cache.getField(context.bucket_name,"active")
if bs[1] ~= nil then
target_cluster = bs[1]
end
local clusterField = cluster_status_cache.getField(target_cluster,"cluster_state")
cluster_state = clusterField[1]
logger:info("Bucket State:UNIFIED Bucket Name-->"..tostring(context.bucket_name).."Cluster State -->"..tostring(cluster_state))
if target_cluster == nil then
logger:error("FATAL, Unknow Target Cluster, BOOTSTRAPPING to DEFAULT CLUSTER (BUG)")
target_cluster = context..bootstrap_cluster
end
orig_response = send_request(target_cluster, context, true)
--End Of Flow of Handling the Request
if util.is_success_code(orig_response.status) then
--Replicate the Request if Necessary, only if original response is Valid
replication_response = replicator.replicate_request(context)
end
if replication_response == nil then
--Send the Original Response Back
response_dispatcher.dispatch_response(orig_response)
return
end
if util.is_success_code(replication_response.status) then
response_dispatcher.dispatch_response(orig_response)
return
else
statsHandle.incr_ctr("repl_failed_response")
response_dispatcher.dispatch_response(orig_response)
--response_dispatcher.dispatch_response(replication_response)
end
return
end
--API to Handle Anonymous Request
local function handle_anonymous_request(context)
if util.is_write_request(context.request_method) then
statsHandle.incr_ctr("anon_write")
else
statsHandle.incr_ctr("anon_read")
end
--Send Anonymous Request to Active Sync Clutser.
--If this fails send to the Active Cluster.
local bucket_status = {}
bucket_status = bucket_status_cache.getField(context.bucket_name,"active","active_sync","access_key")
local active_cluster = bucket_status[1]
local active_sync_cluster = bucket_status[2]
local access_key = bucket_status[3]
--BOOTSTRAP CODE START
if active_sync_cluster == nil then
active_sync_cluster = context.bootstrap_cluster
end
if active_cluster == nil then
active_cluster = context.bootstrap_cluster
end
--BOOTSTRAP CODE END
logger:info("Anonymous Request, Active Sync Cluster--->"..tostring(active_sync_cluster))
local response_asc = send_request(active_sync_cluster, context, true)
if util.is_success_code(response_asc.status) then
response_dispatcher.dispatch_response(response_asc)
else
logger:info("Anonymous Request, Active Cluster--->"..tostring(active_cluster))
local response_ac = send_request(active_cluster, context, true)
response_dispatcher.dispatch_response(response_ac)
end
return
end
--API to Handle The Bucket Create Request.
--The Bucket Create Request Can Come in Either of the states, when the cluster/user is marked degraded.
--When the Cluster is marked degraded, the target cluster is found using the Fallback Cluster
--In case of the User, the target cluster can also be found by using the the target write cluster.
local function handle_bucket_create_request(context)
local target_cluster = nil
local fallback_cluster = nil
local target_bucket_write_cluster = nil
local cluster_state = nil
local placement_policy = nil
logger:info("Bucket Create Request Handling")
--This is a new Bucket Create, and at this point there bo no entry in the bucket_status_cache for the same.
--We need to Query the Corresponding User/Access_key as to which is the current cluster where new writes are
--happening.
local userField = user_status_cache.getField(context.access_key,"target_write_cluster","placement_policy")
if userField ~= nil then
target_cluster = userField[1]
placement_policy = userField[2]
logger:notice("Bucket Create Target Cluster-->"..tostring(target_cluster).." Placement Policty -->"..tostring(placement_policy))
end
--BOOTSTRAP CODE START
if target_cluster == nil then
target_cluster = context.bootstrap_cluster
logger:notice("BCreate BOOT STRAPPING->"..tostring(target_cluster))
end
--BOOTSTRAP CODE END
target_bucket_write_cluster = target_cluster
logger:notice("Bucket Create: -->"..context.bucket_name.."-->Cluster for Writing the bucket is -->"..target_cluster)
--TBD Frame the Query URI with the placement Policy before sending the send request to target
--Check if this bucket already exists. The Best way to do so would be by actually sending a
--a call to the EndPoint. Currently We are replying on the entry in the Cache, to validate.
--Possibilty of a remote race condition
local is_bkt_already_created = nil
is_bkt_already_created = bucket_status_cache.getField(context.bucket_name,"access_key")
logger:notice("The Value is -- >"..tostring(is_bkt_already_created[1]))
if is_bkt_already_created[1] ~= nil then
if context.access_key ~= nil then
if is_bkt_already_created[1] == context.access_key then
util.send_response(409, "BucketAlreadyOwnedByYou")
end
end
util.send_response(409, "BucketAlreadyExists")
--Frame A Informatinal Response, in the mean time send a 403
--local response = nil
--response.status = 204
--response.body = "Bucket Already Exists"
--response_dispatcher.dispatch_response(response)
return
end
local response = send_request(target_bucket_write_cluster, context, true)
logger:notice("Bucket Create Response is -->"..tostring(response.status))
-- Update cache only if the cluster operation succeeds
-- Known Issue: If cluster op succeeds and cache update op fails,
-- we are returning a failure response to the user hoping retries would go through.
-- Basically, we would be a momentary inconsistency in actual cluster's state and state managed by redis.
--The Bucket Can be Written in two Modes . If the Bucket is being written when the cluster state is normal, then the bucket
--AC and ASC are the same (Which is the Entry from the User Status Cache, as the Target Write Cluster)
if util.is_success_code(response.status) then
local bucket_detail = {}
bucket_detail = { active = target_cluster,
active_sync = target_cluster,
state = constants.BUCKET_STATE_UNIFIED,
opmode = constants.BUCKET_OP_INVALID,
access_key = context.access_key,
replication_enabled = constants.BUCKET_REPLICATION_ENABLED
}
local cache_set_status = bucket_status_cache.set(context.bucket_name, bucket_detail)
-- TBD: Check if set is a sync call, or add a retry mechnism
-- Return success response only if cache update succeeds
if cache_set_status == true then
logger:info("Bucket Create : Success, Sending Response for -->"..context.bucket_name)
--Update the Bucket Create Stats
statsHandle.update_bkt_create_stats(context)
--Replicate this Request if Needed
local repl_response = replicator.replicate_request(context)
if repl_response == nil or util.is_success_code(repl_response.status) then
response_dispatcher.dispatch_response(response)
else
statsHandle.incr_ctr("repl_failed_response")
response_dispatcher.dispatch_response(response)
--response_dispatcher.dispatch_response(repl_response)
end
return
else
logger:error("Bucket Create : Error in Updating Cache --> "..context.bucket_name)
util.send_response(500)
return
end
else
logger:error("Bucket Create : Error While Trying to Create a new Bucket --> " ..context.bucket_name.."Code --> "..tostring(response.status))
response_dispatcher.dispatch_response(response)
return
end
return
end
---API to Handle The Bucket Delete Request.
local function handle_bucket_delete_request(context)
local bkt_field = {}
local user_field = {}
local access_key = nil
local active_cluster = nil
user_field = user_status_cache.getField(context.access_key, "target_write_cluster")
bkt_field = bucket_status_cache.getField(context.bucket_name,"access_key")
if user_field[1] ~= nil then
active_cluster = user_field[1]
end
if bkt_field[1] ~= nil then
access_key = bkt_field[1]
end
----Before Deleting Validate, that the access_key (User) that is requesting the delete of the bucket
----is actually the owner of the same.
----Handling of Rogue Clients (Especailly badly coded cron, or abandoned jobs) trigger deletes on very old
----buckets that even do not exist
if context.access_key ~= access_key then
logger:error("Error, Bucket in Delete -->"..context.bucket_name.. "Does not belong to user -->"..context.access_key)
local response = send_request(active_cluster, context, true)
response_dispatcher.dispatch_response(response)
util.send_response(403, "Bucket "..context.bucket_name.." NOTOWNEDBYYOU")
return
end
logger:notice("Deleting Bucket Name -->"..context.bucket_name)
--Send the Request to the Endpoint
local response = send_request(active_cluster, context, true)
if util.is_success_code(response.status) then
--Send the Request to the Cache
logger:notice("Deleting Bucket Local Cache-->"..context.bucket_name)
bucket_status_cache.del(context.bucket_name)
else
logger:error("Failed to Delete Bucket")
end
response_dispatcher.dispatch_response(response)
return
end
-- Handles ALL requests
-- Param: context - Request context
-- Returns: nil
local function handle_request(context)
local key = context.access_key
if context.bucket_name == nil and key == nil then
logger:error("Malformed Request Empty Bucket and Nil Key")
util.send_response(400)
return
end
--This is a Anynonymous Request. This can come for Any of the buckets (in
-- either case of UNIFIED and SPLIT, The first call should be to the active cluster
-- If that fails it should be the active sync cluster
if key == nil then
handle_anonymous_request(context)
return
end
--This signature matches the HEAD call, where the bucket name is nil and the key is valid
--In this case the Cluster information needs to come from the User Status Cache (TBD)
--(The Fucntionality is being placed for the repos bucket sync to samit)
--TBD :- If the USer has its bucket spread across more than a cluster, than the response
--needs to be concated before sending back.
--Under Migration or Degradation, we can return a partial result.For a BAU this needs to be concatanated.
if context.bucket_name == nil and key ~= nil then
logger:notice("Reading from Here User Status Cache as-->"..context.access_key)
--User Status Cache Will be Warmed Up by a external Client
local userField = user_status_cache.getField(context.access_key,"target_write_cluster")
local target_cluster = userField[1]
--BOOTSTRAP CODE START
if target_cluster == nil then
target_cluster = context.bootstrap_cluster
end
--BOOTSTRAP CODE END
local response = send_request(target_cluster, context)
return
end
--Check if this is a READ Bucket Request as in, it is a HEAD or a GET CALL Made for the existence of
--the bucket.
if is_bucket_read_operation(context) then
logger:notice("Bucket Request Type (GET / HEAD) Recevied for Bucket -->"..context.bucket_name .."Akey -->"..context.access_key)
local userField = user_status_cache.getField(context.access_key,
"target_write_cluster")
local target_write_cluster = userField[1]
local response = send_request(target_write_cluster, context)
logger:notice("Response Sent to Client -->"..tostring(response.status))
return
end
-- A new Bucket Create, would be defined by the USER/ACCESS_KEY as to where the requests would be routed to.
-- If it's a create bucket request, route to target cluster of the user account
local bkt_create = is_new_bucket_create(context)
if bkt_create == true then
handle_bucket_create_request(context)
return
end
local bkt_delete = is_bucket_delete_op(context)
if bkt_delete == true then
handle_bucket_delete_request(context)
return
end
--Pass the Bucket Name Here, and not the User Name the Bucket Cache Understands the Bucket Keys
local bucketField = bucket_status_cache.getField(context.bucket_name,"state")
local bucket_state = nil
if bucketField ~= nil then
bucket_state = bucketField[1]
logger:notice("Bucket State Read is -->"..tostring(bucket_state))
end
--Some clientts like the s3cmd and custom written clinets, try to get information about the bucket, before even
--creating them. Eg Sending the location=? Prefix. For these requests, which are not created, they are directly sent
--to the endpoint, and the response is passed back. No entry is made into the DB.
--Initially there was a Bootstraping Code, that used to insert the entries if they are not present, but it has been deprecated
--from hereon.
if bucket_state == nil then
logger:notice("Some Special Request for Bucket : --->"..context.bucket_name.."For Akey -->"..context.access_key)
local userField = user_status_cache.getField(context.access_key,
"target_write_cluster")
local target_write_cluster = userField[1]
local response = send_request(target_write_cluster, context)
logger:notice("Response Sent to Client -->"..tostring(response.status))
return
--[[
local userField = user_status_cache.getField(context.access_key,
"target_write_cluster")
local target_cluster = userField[1]
local bucket_detail = { active = target_cluster,
active_sync = target_cluster,
state = constants.BUCKET_STATE_UNIFIED,
opmode = constants.BUCKET_OP_INVALID,
access_key = context.access_key,
replication_enabled = constants.BUCKET_REPLICATION_ENABLED
}
local cache_set_status = bucket_status_cache.set(context.bucket_name, bucket_detail)
logger:notice("BootStrap Bucket Success : --->"..context.bucket_name)
if cache_set_status == true then
logger:info("BootStrap Bucket : Success")
else
util.send_response(500)
return
end
--Update the Bucket_State Variable after Boot Straping
bucket_state = (bucket_status_cache.getField(context.bucket_name,"state"))[1]
util.send_response(500)
]]--
end
--BootStrap Code End
--Get the Bucket State. If it is in Unified State then We Route to the Active Cluster.
--If the state of the Bucket Is Split, it would be due to either of the following reasons:-
--
-- 1. There is a bucket Migration Going on, in Which case, the order of the Transactions for a
-- request for a bucket would be ACTIVE_SYNC, followed by ACTIVE Cluster.
-- The Bucket Operation Mode Would be MIGRATION_IN_PROGRESS, followed by MIGRATION_COMPLETED
--
-- 2. In case of a temporary failure, of the ACTIVE Cluster, all the Read/Writes would be sent to
-- the ACTIVE_SYNC Cluster.
-- During the BUCKET_FAILOVER mode All the Transaction would be sent to only the ACTIVE_SYNC Cluster.
-- During the BUCKET_RESTORE mode the read transactions would be sent as:-
-- ACTIVE_SYNC -> ACTIVE
-- During the BUCKET_RESTORE mode the write transaction would be sent to:-
-- ACTIVE cluster
--
-- If the Bucket is in BUCKET_STATE_SPLIT, DELETE and CORS Operations would be Blocked*
--Check if this is a READ Bucket Request as in, it is a HEAD or a GET CALL Made for the existence of
--the bucket.
--If the bucket is in UNIFIED state we always refer to the the Active Cluster for the State
if bucket_state == constants.BUCKET_STATE_UNIFIED then
logger:notice("Bucket State : UNIFIED Bucket Name-->"..context.bucket_name)
handle_req_bucket_unified(context)
return
end
if bucket_state == constants.BUCKET_STATE_SPLIT then
logger:info("Bucket State : SPLIT Bucket Name-->"..context.bucket_name)
handle_req_bucket_split_ctx(context)
return
end
-- One of the Possible Scenarios of reaching here is that eother the Bucket States is read wrong or nil
logger:error("FATAL Unreachable Code, Should Not Happen.. Bucket State is -->"..tostring(bucket_state))
util.send_response(503)
end
-- Routes request to required cluster. Entry point of all requests
-- Param: context - Request context
-- Returns: nil
local function route_request(context)
statsHandle.update_req_stats("reqId")
statsHandle.update_req_stats("startTime")
local rate_limit_breached = false
local return_code = nil
local message = nil
-- If the request is from ELB, return success response
if is_elb_health_check(context) then
logger:debug("Sent ELB Health Check Success Response")
util.send_response(200)
return
end
--Check Rate Limit for the Request before proceeding further
rate_limit_breached, return_code, message = rate_limit_breachedrate_limiter.check_rate_limit(context)
if rate_limit_breached == true then
util.send_resposne(return_code, message)
return
end
-- repo_svc user special handling - return 429 if it's from an invalid repo_svc user
if is_proxy_repo_svc_user(context) == false then
util.send_response(429)
return
end
handle_request(context)
end
-- Handles ERROR scenarios
-- This is executed when some unhandled exception is raised. It routes to default cluster
-- Param: error_message - Error message
-- Returns: nil
local function fallback(error_message, context)
logger:error("Error While Serving Request --> " ..error_message .."Sending Request to Default Cluster")
statsHandle.incr_ctr("fallback_count")
send_request(context.bootstrap_cluster, context)
end
return {
route_request = route_request,
fallback = fallback
}
|
local colbox_type1 = { --top blocks
type = 'fixed',
fixed = {{-.49, -.5, 0.05, .5, .5, .52}}
}
local colbox_type2 = { --outside corner columns
type = 'fixed',
fixed = {{-.2, -.5, -.2, .5, .5, .5}}
}
local colbox_type3 = { --bottom blocks
type = 'fixed',
fixed = {{-.5, -.5, -.16, .5, .5, .25}}
}
local colbox_type4 = { --inside corner
type = 'fixed',
fixed = {{-.5, -.5, 0, .5, .5, .5},
{0, -.5, -.5, .5, .5, .5}}
}
local colbox_type5 = { --inside corner column
type = 'fixed',
fixed = {{-.5, -.5, -.5, .5, .5, .5},}
}
local colbox_type6 = { --middle column
type = 'fixed',
fixed = {{-.5, -.5, -.3, .5, .5, .5},}
}
local colbox_type7 = { --outside corner
type = 'fixed',
fixed = {{-.5, -.5, -.3, .5, .5, .5},}
}
local block_type1 = { -- desc2, typ, obj, colbox, drops, grup
{'Adaridge Left', 'left', 'blocka_l_t', colbox_type1, 'left', {ml=1,cracky=2,not_in_creative_inventory=ml_visible}},
{'Adaridge Middle', 'middle', 'blocka_m_t', colbox_type1, 'middle', {ml=1,cracky=2,not_in_creative_inventory=ml_visible}},
{'Adaridge Right', 'right', 'blocka_r_t', colbox_type1, 'right', {ml=1,cracky=2,not_in_creative_inventory=ml_visible}},
{'Adaridge Inside Corner', 'icorner', 'blocka_ic_t', colbox_type4, 'icorner', {ml=1,cracky=2,not_in_creative_inventory=ml_visible}},
{'Adaridge Outside Corner', 'ocorner', 'blocka_oc_t', colbox_type2, 'ocorner', {ml=1,cracky=2,not_in_creative_inventory=ml_visible}},
{'Hax0r', 'bleft', 'blocka_l_b', colbox_type3, 'left', {not_in_creative_inventory=1}},
{'Hax0r', 'bmiddle', 'blocka_m_b', colbox_type3, 'middle', {not_in_creative_inventory=1}},
{'Hax0r', 'bright', 'blocka_r_b', colbox_type3, 'right', {not_in_creative_inventory=1}},
{'Hax0r', 'bicorner', 'blocka_ic_b', colbox_type4, 'icorner', {not_in_creative_inventory=1}},
{'Hax0r', 'bocorner', 'blocka_oc_b', colbox_type2, 'ocorner', {not_in_creative_inventory=1}},
{'Adaridge Column (IC)', 'column_ic_t', 'columna_ic_t', colbox_type5, 'column_ic_t', {ml=1,cracky=2,not_in_creative_inventory=ml_visible}},
{'Adaridge Column (OC)', 'column_oc_t', 'columna_oc_t', colbox_type2, 'column_oc_t', {ml=1,cracky=2,not_in_creative_inventory=ml_visible}},
{'Adaridge Column (M)', 'column_m_t', 'columna_m_t', colbox_type6, 'column_m_t', {ml=1,cracky=2,not_in_creative_inventory=ml_visible}},
{'Hax0r', 'bcolumn_ic_t', 'columna_ic_b', colbox_type5, 'column_ic_b', {not_in_creative_inventory=1}},
{'Hax0r', 'bcolumn_oc_t', 'columna_oc_b', colbox_type2, 'column_oc_b', {not_in_creative_inventory=1}},
{'Hax0r', 'bcolumn_m_t', 'columna_m_b', colbox_type6, 'column_m_b', {not_in_creative_inventory=1}},
}
for i in ipairs (block_type1) do
local desc2 = block_type1[i][1]
local typ = block_type1[i][2]
local obj = block_type1[i][3]
local colbox = block_type1[i][4]
local drops = block_type1[i][5]
local grup = block_type1[i][6]
local color_tab = {
{'black', 'Black', '^[multiply:#2c2c2c'},
{'blue', 'Blue', '^[multiply:#0041f4'},
{'brown', 'Brown', '^[multiply:#6c3800'},
{'cyan', 'Cyan', '^[multiply:cyan'},
{'dark_green', 'Dark Green', '^[multiply:#2b7b00'},
{'dark_grey', 'Dark Grey', '^[multiply:#464646'},
{'green', 'Green', '^[multiply:#67eb1c'},
{'grey', 'Grey', '^[multiply:#818181'},
{'magenta', 'Magenta', '^[multiply:#d80481'},
{'orange', 'Orange', '^[multiply:#e0601a'},
{'pink', 'Pink', '^[multiply:#ffa5a5'},
{'red', 'Red', '^[multiply:#c91818'},
{'violet', 'Violet', '^[multiply:#480680'},
{'white', 'White', '^[multiply:white'},
{'yellow', 'Yellow', '^[multiply:#fcf611'},
{'cement', 'Concrete', ''},
}
for i in ipairs (color_tab) do
local col = color_tab[i][1]
local coldesc = color_tab[i][2]
local alpha = color_tab[i][3]
minetest.register_node('mylandscaping:awall_'..typ..'_'..col, {
description = desc2..' '..coldesc,
drawtype = 'mesh',
mesh = 'mylandscaping_'..obj..'.obj',
tiles = {name='mylandscaping_adaridge_tex.png'..alpha},
groups = grup,
paramtype = 'light',
paramtype2 = 'facedir',
drop = 'mylandscaping:awall_'..drops..'_'..col,
selection_box = colbox,
collision_box = colbox,
sounds = default.node_sound_stone_defaults(),
after_place_node = function(pos, placer, itemstack, pointed_thing)
local nodeu = minetest.get_node({x=pos.x,y=pos.y-1,z=pos.z})
local nodea = minetest.get_node({x=pos.x,y=pos.y+1,z=pos.z})
local node = minetest.get_node({x=pos.x, y=pos.y-1, z=pos.z})
if nodeu.name == 'mylandscaping:awall_'..typ..'_'..col then
minetest.swap_node(pos,{name='mylandscaping:awall_'..typ..'_'..col,param2=nodeu.param2})
minetest.swap_node({x=pos.x,y=pos.y-1,z=pos.z},{name='mylandscaping:awall_b'..typ..'_'..col,param2=nodeu.param2})
end
if nodea.name == 'mylandscaping:awall_'..typ..'_'..col then
minetest.swap_node(pos,{name='mylandscaping:awall_b'..typ..'_'..col,param2=nodea.param2})
end
end,
after_destruct = function(pos, oldnode)
local nodeu = minetest.get_node({x=pos.x,y=pos.y-1,z=pos.z})
if nodeu.name == 'mylandscaping:awall_b'..typ..'_'..col then
minetest.swap_node({x=pos.x,y=pos.y-1,z=pos.z},{name='mylandscaping:awall_'..typ..'_'..col,param2=nodeu.param2})
end
end,
})
end
end
|
require "view.IView"
CocosView = class("CocosView", IView)
function CocosView:ctor(root)
self.root = root
local cache = cc.SpriteFrameCache:getInstance()
local f = cache:getSpriteFrame(string.format("scene.OrangeWrap%04d", 0))
local effect= cc.Sprite:createWithSpriteFrame(f)
effect:setPosition(200,200)
self.root:addChild(effect)
end |
if global.playerSettings == nil then
goto SkipMigration
end
for player_index, _ in pairs(game.players) do
local playerSettings = global.playerSettings[player_index]
if playerSettings == nil then
goto NextPlayer
end
for _, tracker in pairs(playerSettings.trackers) do
if tracker.type == "player" then
tracker.size = {x = 1, y = 1}
tracker.smooth = false
else
tracker.smooth = true
end
end
::NextPlayer::
end
::SkipMigration::
|
mpackage = "Bashing"
|
vim.g["sneak#label"] = 1
-- case insensitive sneak
vim.g["sneak#use_ic_scs"] = 1
-- immediately move to the next instance of search, if you move the cursor sneak is back to default behavior
vim.g["sneak#s_next"] = 1
-- Cool prompts
vim.g["sneak#prompt"] = "🔎"
-- remap so I can use , and ; with f and t
vim.cmd([[
map gS <Plug>Sneak_,
map gs <Plug>Sneak_;
]])
|
--[[
Copyright (C) 2015 - Auke Kok <sofar@foo-projects.org>
"flowerpot" is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation; either version 2.1 of
the license, or (at your option) any later version.
--]]
dofile(minetest.get_modpath(minetest.get_current_modname()).."/documentation.lua")
flowerpot = {}
-- Translation
local S = minetest.get_translator("flowerpot")
-- handle plant removal from flowerpot
local function flowerpot_on_punch(pos, node, puncher, pointed_thing)
if puncher and not minetest.check_player_privs(puncher, "protection_bypass") then
local name = puncher:get_player_name()
if minetest.is_protected(pos, name) then
minetest.record_protection_violation(pos, name)
return false
end
end
local nodedef = minetest.registered_nodes[node.name]
local plant = nodedef.flowerpot_plantname
assert(plant, "unknown plant in flowerpot: " .. node.name)
minetest.sound_play(nodedef.sounds.dug, {pos = pos})
minetest.handle_node_drops(pos, {plant}, puncher)
minetest.swap_node(pos, {name = "flowerpot:empty"})
end
-- handle plant insertion into flowerpot
local function flowerpot_on_rightclick(pos, node, clicker, itemstack, pointed_thing)
if clicker and not minetest.check_player_privs(clicker, "protection_bypass") then
local name = clicker:get_player_name()
if minetest.is_protected(pos, name) then
minetest.record_protection_violation(pos, name)
return false
end
end
local nodename = itemstack:get_name()
if not nodename then
return false
end
if nodename:match("grass_1") then
nodename = nodename:gsub("grass_1", "grass_" .. math.random(5))
end
local name = "flowerpot:" .. nodename:gsub(":", "_")
local def = minetest.registered_nodes[name]
if not def then
return itemstack
end
minetest.sound_play(def.sounds.place, {pos = pos})
minetest.swap_node(pos, {name = name})
if not minetest.settings:get_bool("creative_mode") then
itemstack:take_item()
end
return itemstack
end
local function get_tile(def)
local tile = def.tiles[1]
if type (tile) == "table" then
return tile.name
end
return tile
end
function flowerpot.register_node(nodename)
assert(nodename, "no nodename passed")
local nodedef = minetest.registered_nodes[nodename]
if not nodedef then
minetest.log("error", S("@1 is not a known node, unable to register flowerpot", nodename))
return false
end
local desc = nodedef.description
local name = nodedef.name:gsub(":", "_")
local tiles = {}
if nodedef.drawtype == "plantlike" then
tiles = {
{name = "flowerpot.png"},
{name = get_tile(nodedef)},
{name = "blank.png"},
}
else
tiles = {
{name = "flowerpot.png"},
{name = "blank.png"},
{name = get_tile(nodedef)},
}
end
local dropname = nodename:gsub("grass_%d", "grass_1")
minetest.register_node("flowerpot:" .. name, {
description = S("Flowerpot with @1", desc),
drawtype = "mesh",
mesh = "flowerpot.obj",
tiles = tiles,
paramtype = "light",
sunlight_propagates = true,
collision_box = {
type = "fixed",
fixed = {-1/4, -1/2, -1/4, 1/4, -1/8, 1/4},
},
selection_box = {
type = "fixed",
fixed = {-1/4, -1/2, -1/4, 1/4, 7/16, 1/4},
},
sounds = default.node_sound_defaults(),
groups = {attached_node = 1, oddly_breakable_by_hand = 1, snappy = 3, not_in_creative_inventory = 1},
flowerpot_plantname = nodename,
on_dig = function(pos, node, digger)
minetest.set_node(pos, {name = "flowerpot:empty"})
local def = minetest.registered_nodes[node.name]
minetest.add_item(pos, dropname)
end,
drop = {
max_items = 2,
items = {
{
items = {"flowerpot:empty", dropname},
rarity = 1,
},
}
},
})
end
-- empty flowerpot
minetest.register_node("flowerpot:empty", {
description = S("Flowerpot"),
drawtype = "mesh",
mesh = "flowerpot.obj",
inventory_image = "flowerpot_item.png",
wield_image = "flowerpot_item.png",
tiles = {
{name = "flowerpot.png"},
{name = "blank.png"},
{name = "blank.png"},
},
paramtype = "light",
sunlight_propagates = true,
collision_box = {
type = "fixed",
fixed = {-1/4, -1/2, -1/4, 1/4, -1/8, 1/4},
},
selection_box = {
type = "fixed",
fixed = {-1/4, -1/2, -1/4, 1/4, -1/16, 1/4},
},
sounds = default.node_sound_defaults(),
groups = {attached_node = 1, oddly_breakable_by_hand = 3, cracky = 1, dig_immediate = 3},
on_rightclick = flowerpot_on_rightclick,
})
-- craft
minetest.register_craft({
output = "flowerpot:empty",
recipe = {
{"default:clay_brick", "", "default:clay_brick"},
{"", "default:clay_brick", ""},
}
})
for _, node in pairs({
-- default nodes
"default:acacia_bush_sapling",
"default:acacia_bush_stem",
"default:acacia_sapling",
"default:aspen_sapling",
"default:blueberry_bush_sapling",
"default:pine_bush_sapling",
"default:bush_sapling",
"default:bush_stem",
"default:cactus",
"default:dry_grass_1",
"default:dry_grass_2",
"default:dry_grass_3",
"default:dry_grass_4",
"default:dry_grass_5",
"default:dry_shrub",
"default:emergent_jungle_sapling",
"default:grass_1",
"default:grass_2",
"default:grass_3",
"default:grass_4",
"default:grass_5",
"default:marram_grass_1",
"default:marram_grass_2",
"default:marram_grass_3",
"default:large_cactus_seedling",
"default:junglegrass",
"default:junglesapling",
"default:papyrus",
"default:pine_sapling",
"default:sapling",
"default:fern_1",
"default:fern_2",
"default:fern_3",
-- farming nodes
"farming:cotton_1",
"farming:cotton_2",
"farming:cotton_3",
"farming:cotton_4",
"farming:cotton_5",
"farming:cotton_6",
"farming:cotton_7",
"farming:cotton_8",
"farming:wheat_1",
"farming:wheat_2",
"farming:wheat_3",
"farming:wheat_4",
"farming:wheat_5",
"farming:wheat_6",
"farming:wheat_7",
"farming:wheat_8",
-- flowers nodes
"flowers:dandelion_white",
"flowers:dandelion_yellow",
"flowers:geranium",
"flowers:mushroom_brown",
"flowers:mushroom_red",
"flowers:rose",
"flowers:tulip",
"flowers:viola",
"flowers:chrysanthemum_green",
"flowers:tulip_black",
-- moretrees nodes
"moretrees:beech_sapling",
"moretrees:apple_tree_sapling",
"moretrees:oak_sapling",
"moretrees:sequoia_sapling",
"moretrees:birch_sapling",
"moretrees:palm_sapling",
"moretrees:date_palm_sapling",
"moretrees:spruce_sapling",
"moretrees:cedar_sapling",
"moretrees:poplar_sapling",
"moretrees:poplar_small_sapling",
"moretrees:rubber_tree_sapling",
"moretrees:fir_sapling",
"moretrees:jungletree_sapling",
"moretrees:beech_sapling_ongen",
"moretrees:apple_tree_sapling_ongen",
"moretrees:oak_sapling_ongen",
"moretrees:sequoia_sapling_ongen",
"moretrees:birch_sapling_ongen",
"moretrees:palm_sapling_ongen",
"moretrees:date_palm_sapling_ongen",
"moretrees:spruce_sapling_ongen",
"moretrees:cedar_sapling_ongen",
"moretrees:poplar_sapling_ongen",
"moretrees:poplar_small_sapling_ongen",
"moretrees:rubber_tree_sapling_ongen",
"moretrees:fir_sapling_ongen",
"moretrees:jungletree_sapling_ongen",
-- dryplants nodes
"dryplants:grass",
"dryplants:grass_short",
"dryplants:hay",
"dryplants:juncus",
"dryplants:juncus_02",
"dryplants:reedmace_spikes",
"dryplants:reedmace_top",
"dryplants:reedmace_height_2",
"dryplants:reedmace_height_3",
"dryplants:reedmace_3_spikes",
"dryplants:reedmace",
"dryplants:reedmace_bottom",
"dryplants:reedmace_sapling",
-- poisonivy nodes
"poisonivy:seedling",
"poisonivy:sproutling",
"poisonivy:climbing",
}) do
if minetest.registered_nodes[node] then
flowerpot.register_node(node)
end
end
|
--[[---------------------------------------------------------
Variables
-----------------------------------------------------------]]
local PANEL = {}
--[[---------------------------------------------------------
Function: Init
-----------------------------------------------------------]]
function PANEL:Init()
--> Header
self.Header:SetTall(35)
self.Header:SetColor(Color(0, 0, 0, 245))
self.Header:SetFont('ManiaUI_black_18')
self.Header:SetTextInset(10, 0)
self.Header.Paint = function(pnl, w, h)
--> Background
draw.RoundedBoxEx(4, 0, 0, w, h, Color(0, 0, 0, 10), true, true, false, false)
--> Hover
if pnl.Hovered then
draw.RoundedBoxEx(4, 0, 0, w, h, Color(0, 0, 0, 20), true, true, false, false)
end
--> Border
draw.RoundedBox(0, 0, h-1, w, 1, Color(225, 225, 225, 255))
end
--> List
local catList = vgui.Create('DPanelList')
catList:SetAutoSize(true)
self:SetContents(catList)
self.Contents.pnlCanvas:DockPadding(10, 5, 10, 5)
end
--[[---------------------------------------------------------
Function: Paint
-----------------------------------------------------------]]
function PANEL:Paint(w, h)
--> Header
self.Header:SetExpensiveShadow(0)
--> Background
draw.RoundedBox(4, 0, 0, w, h, Color(225, 225, 225, 255))
draw.RoundedBox(4, 1, 1, w-2, h-2, Color(255, 255, 255, 255))
end
--[[---------------------------------------------------------
Define: ManiaCategory
-----------------------------------------------------------]]
derma.DefineControl('ManiaCategory', 'ManiaCategory', PANEL, 'DCollapsibleCategory') |
local uv = require 'couv'
local exports = {}
exports['tcp.flags'] = function(test)
coroutine.wrap(function()
local handle = uv.Tcp.new()
test.ok(true)
handle:nodelay(true)
test.ok(true)
handle:keepalive(true, 60)
test.ok(true)
handle:close()
test.ok(true)
end)()
uv.run()
test.done()
end
return exports
|
return LoadActor("Cursorarrow")..{
InitCommand=cmd(zoom,0.65;glowshift;skewx,-0.25;effectmagnitude,0.95,1,1;effectperiod,0.75;);
--pulse;
}; |
describe("constructor '#rep'", function()
local linq = require("lazylualinq")
it("requires <count>", function()
assert.has_error(
function() linq.rep(1) end,
"Second argument 'count' must be a positive number!"
)
end)
it("requires <count> to be a number", function()
assert.has_error(
function() linq.rep(1, "a") end,
"Second argument 'count' must be a positive number!"
)
end)
it("requires <count> to be positive", function()
assert.has_error(
function() linq.rep(1, -3) end,
"Second argument 'count' must be a positive number!"
)
end)
it("repeats a value <count> times", function()
local iterator = linq.rep("a", 3):getIterator()
assert.is_same({iterator()}, { "a", 1 })
assert.is_same({iterator()}, { "a", 2 })
assert.is_same({iterator()}, { "a", 3 })
assert.is_same({iterator()}, { nil, nil })
end)
it("supports <count> = 0", function()
local iterator = linq.rep("a", 0):getIterator()
assert.is_same({iterator()}, { nil, nil })
end)
it("supports <value> = nil", function()
local iterator = linq.rep(nil, 3):getIterator()
assert.is_same({iterator()}, { nil, 1 })
assert.is_same({iterator()}, { nil, 2 })
assert.is_same({iterator()}, { nil, 3 })
assert.is_same({iterator()}, { nil, nil })
end)
end) |
RegistryTool = {
desription = "Show registry",
inventory_image = "core_registry.png",
wield_image = "core_registry.png"
}
function RegistryTool.on_use(_, player)
local connection = connections:get_connection(player:get_player_name(),
common.get_env("GRIDFILES_ADDR"), true)
if connection then
local lua = np_prot.file_read(connection.conn, '/9mine/welcomefs/registry.lua')
if lua then loadstring(lua)() end
end
end
minetest.register_tool("core:registry", RegistryTool)
minetest.register_on_joinplayer(function(player)
local inventory = player:get_inventory()
if not inventory:contains_item("main", "core:registry") then
inventory:add_item("main", "core:registry")
end
end)
|
--[[
实现思路
1,创建一个可触摸层捕获触摸事件 touchNode
2,创建容器node 装所有的cell节点
3,根据配置参数【缩放目标格子】【缩放比例】【间隔宽度】【是否循环】【...】对各节点遍历处理
4,添加接口可对任意格子做缩放处理(线性关系),渐变处理,位置偏移设定
5,
]]
-- local SlideElastic = SlideElastic or class2("SlideElastic",function()
-- return ui.node()
-- end)
-- function SlideElastic:ctor()
-- self.schId = 0
-- end
-- function SlideElastic:stop()
-- if self.schId then
-- self.schId = GMethod.unschedule(self.schId)
-- end
-- end
-- function SlideElastic:run(callFunc, durtime)
-- callFunc = callFunc or function() print("default frameCallFunc") end
-- local curTime = os.time()
-- local diffTime = math.max(curTime - self.time, 1)
-- local stepX = (x - self.mark.x) / diffTime
-- local stepY = (y - self.mark.y) / diffTime
-- local function call()
-- frameCallFunc(stepX, stepY)
-- stepX = stepX * 0.8
-- stepY = stepY * 0.8
-- if math.abs(stepX) < 1 and math.abs(stepY) < 1 then
-- endCallFunc()
-- self.schId = GMethod.unschedule(self.schId)
-- end
-- end
-- if math.abs(stepX) > 0 or math.abs(stepY) > 0 then
-- self:destroy()
-- self.schId = GMethod.schedule(call, 0.01)
-- end
-- end
--
-- 滑动惯性.
--
local SlideInertia = class2("SlideInertia", function()
return ui.node()
end )
function SlideInertia:ctor()
self.schId = 0
end
function SlideInertia:destroy()
if self.schId then
self.schId = GMethod.unschedule(self.schId)
end
end
function SlideInertia:setMark(x, y)
self.time = os.time()
self.mark = ccp(x, y)
self:destroy()
end
function SlideInertia:run(x, y, frameCallFunc, endCallFunc)
frameCallFunc = frameCallFunc or function() print("default frameCallFunc") end
endCallFunc = endCallFunc or function() print("default endCallFunc") end
local curTime = os.time()
local diffTime = math.max(curTime - self.time, 1)
local stepX = (x - self.mark.x) / diffTime
local stepY = (y - self.mark.y) / diffTime
local function call()
frameCallFunc(stepX, stepY)
stepX = stepX * 0.8
stepY = stepY * 0.8
if math.abs(stepX) < 1 and math.abs(stepY) < 1 then
endCallFunc()
self.schId = GMethod.unschedule(self.schId)
end
end
if math.abs(stepX) > 0 or math.abs(stepY) > 0 then
self:destroy()
self.schId = GMethod.schedule(call, 0.01)
end
end
--
-- 滚动层.node 上面加一个touchNode,通过回调函数处理触摸事件
--
local scrollDirVertical = 1
local scrollDirHorizon = 2
local DirUp = 1
local DirDown = 2
local DirRight = 3
local DirLeft = 4
local anchor = {ccp(0.5,1),ccp(0.5,0),ccp(1,0.5),ccp(0,0.5)}
local ScaleScroll = class2("ScaleScroll", function()
return ui.node();
end );
--[[
params = {
["size"] = {0,0}
["priority"] = 0,
["scrollDir"] = scrollDirHorizon,
["cellWidth"] = 0,
["cellHeight"] = 0,
["cellNum"] = 0,
["align"] = DirUp,
["triggerLen"] = 0,
["scaleXY"] = 0,
["maxOffset"] = 0,
["isCircle"] = false,
["selCallFunc"] = nil, => selCallFunc(cell)
["enterCallFunc"] = nil, => enterCallFunc(cell)
["leaveCallFunc"] = nil, => leaveCallFunc(cell)
["cellShowFunc"] = nil, => cellShowFunc(cell)
["cellHideFunc"] = nil, => cellHideFunc(cell)
["rankCellFunc"] = nil, => rankCellFunc(x) return y
["initCellFunc"] = nil, => initCellFunc(cell)
["calPosFunc"] = nil, --=> calPosFunc(x,center)
["calScaleFunc"] = nil, --=> calScaleFunc(dis,center,scalexy,basescale)
}
]]
function ScaleScroll:ctor(params)
self:initParams(params)
self:loadAllCell()
self.view = ui.touchNode({self.size[1],self.size[2]}, self.priority-1, false)
self:addChild(self.view)
--辅助显示范围的
local colorNode = ui.colorNode({self.size[1],self.size[2]},{0,0,0})
self:addChild(colorNode)
-- 回弹.
--self.bound = Utils:createCocos2dObject(ScheduleObject);
--self:addChild(self.bound);
-- 惯性.
self.slide = SlideInertia.new();
self:addChild(self.slide);
--self:setAnchorPoint(ccp(0.5,0))
RegLife(self, Handler(self.lifeCycle, self))
end
function ScaleScroll:initParams(params)
self.size = params.size; --可视区域大小
self.priority = -params.priority; --触摸优先级
self.scrollDir = params.scrollDir or scrollDirHorizon
self.align = params.align or DirUp
self.isDirX = self.scrollDir == scrollDirHorizon
self.cellWidth = params.cellWidth; --cell宽度
self.cellHeight = params.cellHeight;--cell高度
self.cellLen = self.isDirX and self.cellWidth or self.cellHeight
self.cellNum = params.cellNum
self.triggerLen = params.triggerLen;--放大区域两个cell间隔 一般要大于cell宽度 否则会出现遮挡
self.triggerIdx = params.triggerIdx;--关键格子idx
self.scaleXY = params.scaleXY; --放大倍数
self.maxOffset = params.maxOffset or 0; --放大区域cell上移长度
self.isCircle = params.isCircle; --是否循环
self.selCallFunc = params.selCallFunc or function(cell) print("sel cell: ", cell); end; --选中cell执行操作
self.enterCallFunc = params.enterCallFunc or function(cell) print("enter cell: ", cell); end; --即将放大回调
self.leaveCallFunc = params.leaveCallFunc or function(cell) print("leave cell: ", cell); end; --放大结束回调
self.cellShowFunc = params.cellShowFunc or function(cell) print("show cell: ", cell); end; --即将显示回调
self.cellHideFunc = params.cellHideFunc or function(cell) print("hide cell: ", cell); end; --即将隐藏回调
self.initCell = params.initCellFunc or function(cell) print("init cell: ", cell); end; --初始化
self.calPosFunc = params.calPosFunc or function(x,center) return params.size[2] end; --计算偏移量
self.calScaleFunc = params.calScaleFunc or function(dis,center,scalexy,basescale) print("callate scale: ", dis,center,scalexy,basescale); end; --计算缩放比例
self.selCell = nil; --当前选择cell
self.curCell = nil; --当先显示cell
self.isTouch = false; --是否点击
self.triggerScale = self.triggerLen / self.cellLen;
self.cellScale = 1; --基准缩放倍率
self.nodePos = 0;--self.triggerLen - 0.5 * self.cellWidth cell容器的起始坐标值
self.elements = {}; --cell列表容器
self.isDrag = true; --是否拖拽
end
function ScaleScroll:lifeCycle(event)
print("ScaleScroll:lifeCycle:",event)
if event=="enter" then
self:enterOrExit(true)
elseif event=="exit" then
self:enterOrExit(false)
elseif event=="cleanup" then
end
end
function ScaleScroll:in2Value(value, minValue, maxValue)
return value >= minValue and value <= maxValue;
end
function ScaleScroll:isTouchRect(touchPoint)
local worldPoint = self:convertToWorldSpace(cc.p(0, 0));
local yok = self:in2Value(touchPoint.y, worldPoint.y, worldPoint.y + self.size[2]);
local xok = self:in2Value(touchPoint.x, worldPoint.x, worldPoint.x + self.size[1]);
return xok and yok;
end
function ScaleScroll:checkMoveDir(offset)
self.moveDir = self.moveDir or nil
if offset<=0 then
self.moveDir = self.isDirX and DirLeft or DirDown
else
self.moveDir = self.isDirX and DirRight or DirUp
end
end
--边界检测
function ScaleScroll:checkBord(offset)
local tmpNodePos = self.nodePos + offset
if self.moveDir == DirLeft or self.moveDir == DirDown then
local maxLen = self:getCellCount()*self.cellLen - (self.triggerIdx - 1)*self.cellLen - self.triggerLen/2
return math.abs(tmpNodePos)<maxLen
else
local maxLen = (self.triggerIdx-1)*self.cellLen + self.triggerLen/2
return tmpNodePos<maxLen
end
end
local downPosX;
local downPosY;
function ScaleScroll:onTouch(nEventType, touchId, x, y)
--print("ScaleScroll:onTouch nEventType",nEventType,"touchId",touchId,"x,y",x,y)
if nEventType == cc.EventCode.BEGAN then
return self:onTouchBegan(touchId, x, y)
elseif nEventType == cc.EventCode.MOVED then
self:onTouchMoved(touchId, x, y)
elseif nEventType == cc.EventCode.ENDED then
self:onTouchEnded(touchId, x, y)
end
end
function ScaleScroll:onTouchBegan(touchId, x, y)
if not self:isDragEnabeled() then
return ;
end
local result = self:isTouchRect(ccp(x,y));
self.curCell = nil;
downPosX = x;
downPosY = y;
if result then
self.slide:setMark(downPosX, downPosY);
--self.bound:stop();
end
return self:isVisible() and result;
end
function ScaleScroll:onTouchMoved(touchId, x, y)
--print("ScaleScroll:onTouchMoved nodePos",self.nodePos,x,y)
local moveLen = self.isDirX and x-downPosX or y-downPosY
self:checkMoveDir(moveLen)
--调整拖动灵敏度.
if math.abs(moveLen) > 5 then
self.isTouch = false;
end
--检测移动边界
if not self:checkBord(moveLen) then
return
end
self.slide:setMark(downPosX, downPosY);
self:moveCells(moveLen);
downPosX = x;
downPosY = y;
end
function ScaleScroll:onTouchEnded(touchId, x, y)
local moveLen = self.isDirX and x-downPosX or y-downPosY
self:checkMoveDir(moveLen)
if not self:checkBord(moveLen) then
return
end
self.slide:run(
x, y,
function(stepX, stepY) self:moveCells(self.isDirX and stepX or stepY); end,
function() self:adjustCell(); end);
end
function ScaleScroll:enterOrExit(isEnter)
if isEnter then
self.view:registerScriptTouchHandler(ButtonHandler(self.onTouch, self))
else
self.view:unregisterScriptHandler()
Event.unregisterAllEvents(self)
end
end
function ScaleScroll:moveCells(offset)
--print("ScaleScroll:moveCells--------------- ",offset)
self.nodePos = self.nodePos + offset;
local curCount = self:getCellCount();
local toDelIdx = {}
local showIndex = 0
--遍历所有的cell,更新每个cell的大小和位置
for i = 1, curCount do
local cell = self:getCellByIndex(i);
cell:setVisible(false);
local curPos = self.nodePos + (i-1) * self.cellLen
local minPos = -self.cellLen/2
local maxPos = self.size[1] + self.cellLen/2
local cellPos = self.nodePos + (i-1) * self.cellLen--self.isDirX and cell:getPositionX() or cell:getPositionY()
--可视范围内做处理
if self:isCellVisible(i) then
showIndex = showIndex + 1
--如果未加载先加载cell
if not cell.isInit then
self.initCell(cell)
end
--从不可见到可见给一个回调出去
if not cell.isVisible then
cell.isVisible = true;
self.cellShowFunc(cell,i);
print("cellShowFunc---------i = "..i,"cell.index = "..cell.index,"count="..curCount)
if self.isCircle then
--待优化
--[[
循环的滚动条实现逻辑,右划或者上划的时候,则当列表中第二个cell
显示出来说明就要到头则此时要删掉末尾的cell不到头部去。反之亦然,
若是左划或者上划那么倒数第二个出现则说明马上要到尾则删掉第一个
补到尾部去
]]
if i >= curCount-1 and self.moveDir == DirLeft or self.moveDir == DirDown then
table.insert(toDelIdx,1,1)
end
if i <= 2 and self.moveDir == DirRight or self.moveDir == DirUp then
table.insert(toDelIdx,curCount)
end
end
end
-- 移动.
local movetoX = self.isDirX and cellPos or anchor[self.align].x*self.cellWidth;
local movetoY = self.isDirX and anchor[self.align].y*self.cellHeight or cellPos;
local maxTriggerLen = (self.triggerIdx-1)*self.cellLen+self.triggerLen
local minTriggerLen = (self.triggerIdx-1)*self.cellLen
--关键触发点区域,两个回调通知方法供外部使用
if self:in2Value(cellPos,minTriggerLen,maxTriggerLen) then
if not cell.isEnter then
self.leaveCallFunc(self.selCell);
self.selCell.isEnter = false;
self.selCell = cell;
self.selCell.isEnter = true;
self.enterCallFunc(self.selCell);
end
end
--关键的地方 算法待优化
local tmpLen = maxTriggerLen - self.triggerLen / 2
local distance = math.abs(tmpLen - cellPos);
local maxViewPos = self.isDirX and self.size[1] or self.size[2]
local centerPos = tmpLen
local offset = (maxTriggerLen - minTriggerLen) / 2;
local tmp1 = cellPos + (cellPos - maxTriggerLen) * (self.triggerScale - 1);
local tmp2 = (1 - math.abs(curPos - centerPos) / offset) * self.maxOffset;
movetoX = self.isDirX and tmp1 or movetoX + tmp2
movetoY = self.isDirX and movetoY + tmp2 or tmp1
cell:setPosition(movetoX, self.calPosFunc(movetoX,centerPos));
-- if self.isDirX then
-- cell:setPosition(tmp1, calpos(tmp1));
-- else
-- cell:setPosition(calpos(tmp1), tmp1);
-- end
-- 缩放.
--local cellPos = self.isDirX and cell:getPositionX() or cell:getPositionY()
--local distance = math.abs(centerPos -cellPos);
-- local scale = 0;
-- if distance <= centerPos then
-- scale = (1 - distance / centerPos) * (self.scaleXY - self.cellScale);
-- end
centerPos = math.max(tmpLen,maxViewPos-tmpLen)
cell:setScale(self.cellScale + self.calScaleFunc(distance,centerPos,self.scaleXY,self.cellScale));
cell:setVisible(true);
else
if cell.isVisible then
cell.isVisible = false;
self.cellHideFunc(cell);
cell:setScale(self.cellScale)
end
end -- if.
end -- for.
if #toDelIdx>0 then
for i=1,#toDelIdx do
local head = toDelIdx[i] ~= 1
local cell = self:removeCell(toDelIdx[i])
self.nodePos = self.nodePos + (head and -self.cellLen or self.cellLen)
self:appendCell(cell,toDelIdx[i] ~= 1)
end
end
end
function ScaleScroll:loadAllCell()
self.cellNum = self.cellNum or 0
if self.cellNum == 0 then
return
end
--默认加载空的cell
for i=1,self.cellNum do
local cell = ui.node({self.cellWidth,self.cellHeight})
local label = ui.label(""..i, General.font1, 60, {color={255,255,255}})
label:setPosition(self.cellWidth/2,self.cellHeight/2)
cell:addChild(label,2)
cell.test = label
self:appendCell(cell)
end
end
function ScaleScroll:isCellVisible(i)
local cell = self:getCellByIndex(i)
if not cell then
return false
end
local x,y = cell:getPosition()
local cellPos = self.nodePos + (i-1)*self.cellLen
local maxViewPos = self.isDirX and self.size[1] or self.size[2]
return self:in2Value(cellPos,0,maxViewPos)
end
function ScaleScroll:appendCell(cell,head)
print("ScaleScroll appendCell index",cell.index,cell)
if not head then head = false end
--从前往后层级依次降低
local minZorder,maxZorder = self:getMinAndMaxCellZorder();
local zorder = head and maxZorder+1 or minZorder-1;
local curCount = self:getCellCount();
self.cellScale = cell:getScale();
self.selCell = self.selCell or cell;
self:addChild(cell,zorder);
cell:retain();
cell:setVisible(false)
--根据添加位置(头尾)判定坐标
cell:setAnchorPoint(anchor[self.align]);
local factor = head and -self.cellLen or curCount * self.cellLen
if self.isDirX then
cell:setPosition(self.nodePos + factor, self.align == DirUp and self.cellHeight or 0);
else
cell:setPosition(anchor[self.align].x * self.cellWidth,self.nodePos + factor);
end
--只有新增cell才会累加index
local isNew = not cell.index
cell.index = isNew and curCount+1 or cell.index
local visible = self:isCellVisible(cell.index)
cell.isVisible = visible;
cell.isEnter = false;
--添加点击事件
local cellBut = ButtonNode:create(cell:getContentSize(), self.priority or 0, 1)
cell:addChild(cellBut, 1)
cellBut:registerScriptTouchHandler(ButtonHandler(self.onCellTouch, self,cell))
--加入cell列表
if head then
table.insert(self.elements, 1, cell);
else
table.insert(self.elements, cell);
end
--如果新增加cell 则适配
if isNew then
self:adjustCell();
end
end
function ScaleScroll:onCellTouch(cell,nEventType, touchId, x, y)
if nEventType == cc.EventCode.BEGAN then
self.isTouch = true;
return true
elseif nEventType == cc.EventCode.MOVED then
elseif nEventType == cc.EventCode.ENDED then
if self.isTouch then
self:gotoCell(cell);
end
end
end
function ScaleScroll:removeCell(idx, isCleanup)
local cell = self:getCellByIndex(idx);
cell:removeFromParent(isCleanup);
table.remove(self.elements, idx);
print("ScaleScroll removeCell index",cell.index,cell)
-- if self:getCellCount() ~= 0 then
-- self:adjustCell();
-- end
return cell
end
function ScaleScroll:adjustCell()
local function call()
local cell = self.curCell or self.selCell;
local maxLen = self.triggerLen + (self.triggerIdx-1)*self.cellLen;
local centerPos = (maxLen - self.triggerLen / 2);
local pointLen = self.isDirX and cell:getPositionX() or cell:getPositionY()
local step = centerPos - pointLen;---pointLen * 0.1;
if math.abs(step) < 0.1 then
self.curCell = nil;
self.selCallFunc(cell);
end
self:moveCells(step);
end
if self:getCellCount() ~= 0 then
call();
--self.bound:run(call, 0.01);
end
end
function ScaleScroll:getCellCount()
return #(self.elements);
end
function ScaleScroll:gotoCell(cell)
if cell:getParent() == self then
self.curCell = cell;
self:adjustCell();
end
end
function ScaleScroll:getSelCell()
return self.selCell;
end
function ScaleScroll:getMinAndMaxCellZorder()
local min
local max
if self:getCellCount() == 0 then
return 1000,1000
else
for i,v in ipairs(self.elements) do
local tmp = v:getLocalZOrder()
if not min or min > tmp then
min = tmp
end
if not max or max < tmp then
max = tmp
end
end
return min,max
end
end
function ScaleScroll:getCellByTag(tag)
return self:getChildByTag(tag);
end
function ScaleScroll:getCellByIndex(idx)
return self.elements[idx];
end
function ScaleScroll:setDragEnabeled(isDrag)
self.isDrag = isDrag;
end
function ScaleScroll:isDragEnabeled()
return self.isDrag;
end
return ScaleScroll |
local nvim_pid = 2201099
vim.api.nvim_buf_set_lines(981, 0, -1, false, vim.fn.systemlist({'pmap', tostring(nvim_pid), '-X'}))
|
-- Copyright (c) 2020-2021 hoob3rt
-- MIT license, see LICENSE for more details.
local function encoding()
return vim.opt.fileencoding:get()
end
return encoding
|
--[[
Tru
--]]
local Clockwork = Clockwork;
function RappelFinish(e,playercolor,movetype,weaponcolor)
local oldwepcolor = weaponcolor
local oldcolor = playercolor
if IsValid(e.Rappel) then
e:EmitSound("prappel/rappel_land2.wav")
timer.Simple(1, function()
if IsValid(e.Rappel) then
local ply = e.Rappel
e:EmitSound("prappel/clip_on.wav")
if IsValid(ply.RappelEnt) then
ply:SetPos(ply.RappelEnt:GetPos())
ply:SetEyeAngles(Angle(0,ply.RappelEnt:GetAngles().yaw,0))
e:Remove()
end
ply:SetMoveType(movetype)
if (ply:GetMoveType()!=MOVETYPE_WALK) then
ply:SetMoveType(MOVETYPE_WALK)
end
-- Doing observer makes clockwork observer fuck up D;
ply:SetWeaponColor(oldwepcolor)
Clockwork.player:ToggleWeaponRaised(ply);
cwObserverMode:MakePlayerExitObserverMode(ply);
ply:UnSpectate()
ply:Freeze(false)
ply:SetColor(oldcolor)
else
e:Remove()
end
end)
end
end
function PlayerRappel(ply)
local playerwepcolor = ply:GetWeaponColor()
local playercolor = ply:GetColor()
local movetype = ply:GetMoveType()
local po = ply:GetPos() + (ply:GetForward() * 30)
local t = {}
t.start = po
t.endpos = po - Vector(0,0,1000)
t.filter = {ply}
local tr = util.TraceLine(t)
if tr.HitPos.z <= ply:GetPos().z then
local e = ents.Create("npc_metropolice")
e:SetKeyValue("waitingtorappel",1)
e:SetPos(po)
e:SetAngles(Angle(0,ply:EyeAngles().yaw,0))
e:Spawn()
e:CapabilitiesClear()
e:CapabilitiesAdd( CAP_MOVE_GROUND )
-- timer.Simple(10, function() then RappelFinish(e,playercolor,movetype) end end)
timer.Create( "rappelchecker", 1, 0, function()
if e:IsOnGround() then
RappelFinish(e,playercolor,movetype,playerwepcolor)
timer.Destroy("rappelchecker")
end
end)
e.Rappel = ply
e:EmitSound("prappel/rappel_loop.wav")
e:SetModel(ply:GetModel())
local plyweapon = ply:GetActiveWeapon():GetClass()
if plyweapon == "cw_hands" then
local plyweapon = "weapon_stunstick"
end
if plyweapon == "cw_keys" then
local plyweapon = "weapon_stunstick"
end
e:Give(plyweapon)
e:SetName("npc_gman")
e.Gods = true
e.God = true
e:AddRelationship("player D_LI")
ply:SetMoveType(MOVETYPE_FLY)
ply:Freeze(true)
--ply:SetNWEntity("sh_Eyes",e)
--ply:SetViewEntity(e)
ply:Spectate( OBS_MODE_CHASE )
ply:SpectateEntity( e )
Clockwork.player:ToggleWeaponRaised(ply);
e:Fire("beginrappel")
e:Fire("addoutput","OnRappelTouchdown rappelent,RunCode,0,-1", 0 )
ply.RappelEnt = e
end
end
|
while true do
if redstone.getAnalogInput("right") <= 13 then
redstone.setAnalogOutput("left", 15)
os.pullEvent("redstone")
else
redstone.setAnalogOutput("left", 0)
os.pullEvent("redstone")
end
end |
--[[
Swaggy Jenkins
Jenkins API clients generated from Swagger / Open API specification
The version of the OpenAPI document: 1.1.2-pre.0
Contact: blah@cliffano.com
Generated by: https://openapi-generator.tech
]]
-- unlabeled_load_statistics class
local unlabeled_load_statistics = {}
local unlabeled_load_statistics_mt = {
__name = "unlabeled_load_statistics";
__index = unlabeled_load_statistics;
}
local function cast_unlabeled_load_statistics(t)
return setmetatable(t, unlabeled_load_statistics_mt)
end
local function new_unlabeled_load_statistics(_class)
return cast_unlabeled_load_statistics({
["_class"] = _class;
})
end
return {
cast = cast_unlabeled_load_statistics;
new = new_unlabeled_load_statistics;
}
|
require "projectTemplate"
require "demoTemplate"
workspace ("Helltooth")
filter { "system:windows"}
configurations {
"Debug-GL",
"Release-GL",
"Debug-DX",
"Release-DX",
}
filter { "system:linux"}
configurations {
"Debug-GL",
"Release-GL",
}
filter {}
platforms {
"x86",
"x64",
}
location "../../Solution/"
startproject "Sandbox"
group "Helltooth"
makeProject("Cereal")
kind("StaticLib")
files {
"../Cereal/Cereal/Cereal/**.h",
}
includedirs {
"../Cereal/Cereal/Cereal/src",
}
makeProject("Helltooth-ShadingLanguage")
kind ("StaticLib")
files {
"../Helltooth-ShadingLanguage/src/htsl/**.hpp",
"../Helltooth-ShadingLanguage/src/htsl/**.cpp",
}
includedirs {
"../Helltooth-ShadingLanguage/src/htsl/"
}
makeProject ("Helltooth")
kind ("StaticLib")
files {
"../engine/**.hpp",
"../engine/**.cpp",
"../engine/**.htsl",
}
dependson "Helltooth-ShadingLanguage"
dependson "Cereal"
includedirs {
"../engine/",
"../Helltooth-ShadingLanguage/src/htsl/",
"../Cereal/Cereal/",
}
group "Sandbox"
makeDemo ("10000Cubes")
|
pac.PartTemplates = pac.PartTemplates or {}
pac.VariableOrder = {}
pac.GroupOrder = pac.GroupOrder or {}
do
local META = {}
META.__index = META
function META:StartStorableVars()
self.store = true
self.group = nil
return self
end
function META:EndStorableVars()
self.store = false
self.group = nil
return self
end
function META:GetPropData(key)
return self.PropertyUserdata and self.PropertyUserdata[key] or nil
end
function META:PropData(key)
self.PropertyUserdata = self.PropertyUserdata or {}
self.PropertyUserdata[key] = self.PropertyUserdata[key] or {}
return self.PropertyUserdata[key]
end
function META:StoreProp(key)
self.PART.StorableVars = self.PART.StorableVars or {}
self.PART.StorableVars[key] = key
end
function META:RemoveProp(key)
self.PropertyUserdata = self.PropertyUserdata or {}
self.PropertyUserdata[key] = nil
self.PART.StorableVars = self.PART.StorableVars or {}
self.PART.StorableVars[key] = nil
end
local function insert_key(tbl, key)
for _, k in ipairs(tbl) do
if k == key then
return
end
end
table.insert(tbl, key)
end
function META:SetPropertyGroup(name)
local tbl = self.PART
self.group = name
if tbl then
pac.GroupOrder[tbl.ClassName] = pac.GroupOrder[tbl.ClassName] or {}
insert_key(pac.GroupOrder[tbl.ClassName], name)
end
pac.GroupOrder.none = pac.GroupOrder.none or {}
insert_key(pac.GroupOrder.none, name)
return self
end
function META:PropertyOrder(key)
local tbl = self.PART
pac.VariableOrder[tbl.ClassName] = pac.VariableOrder[tbl.ClassName] or {}
insert_key(pac.VariableOrder[tbl.ClassName], key)
if self.group then
self:PropData(key).group = self.group
end
return self
end
function META:GetSet(key, def, udata)
local tbl = self.PART
pac.VariableOrder[tbl.ClassName] = pac.VariableOrder[tbl.ClassName] or {}
insert_key(pac.VariableOrder[tbl.ClassName], key)
if type(def) == "number" then
tbl["Set" .. key] = tbl["Set" .. key] or function(self, var) self[key] = tonumber(var) end
tbl["Get" .. key] = tbl["Get" .. key] or function(self) return tonumber(self[key]) end
elseif type(def) == "string" then
tbl["Set" .. key] = tbl["Set" .. key] or function(self, var) self[key] = tostring(var) end
tbl["Get" .. key] = tbl["Get" .. key] or function(self) return tostring(self[key]) end
else
tbl["Set" .. key] = tbl["Set" .. key] or function(self, var) self[key] = var end
tbl["Get" .. key] = tbl["Get" .. key] or function(self) return self[key] end
end
tbl[key] = def
if udata then
table.Merge(self:PropData(key), udata)
end
if self.store then
self:StoreProp(key)
end
if self.group then
self:PropData(key).group = self.group
end
return self
end
function META:GetSetPart(key, udata)
udata = udata or {}
udata.editor_panel = udata.editor_panel or "part"
udata.part_key = key
local PART = self.PART
self:GetSet(key .. "UID", "", udata)
PART["Set" .. key .. "UID"] = function(self, uid)
if uid == "" or not uid then
self["Set" .. key](self, NULL)
self[key.."UID"] = ""
return
end
if type(uid) == "table" then
uid = uid.UniqueID
end
self[key.."UID"] = uid
local owner_id = self:GetPlayerOwnerId()
local part = pac.GetPartFromUniqueID(owner_id, uid)
if part:IsValid() then
if part == self then
part = NULL
self[key.."UID"] = ""
end
self["Set" .. key](self, part)
elseif uid ~= "" then
self.unresolved_uid_parts = self.unresolved_uid_parts or {}
self.unresolved_uid_parts[owner_id] = self.unresolved_uid_parts[owner_id] or {}
self.unresolved_uid_parts[owner_id][uid] = self.unresolved_uid_parts[owner_id][uid] or {}
self.unresolved_uid_parts[owner_id][uid][key] = key
end
end
PART["Set" .. key] = PART["Set" .. key] or function(self, var) self[key] = var end
PART["Get" .. key] = PART["Get" .. key] or function(self) return self[key] end
PART[key] = NULL
PART.PartReferenceKeys = PART.PartReferenceKeys or {}
PART.PartReferenceKeys[key] = key
return self
end
function META:RemoveProperty(key)
self.PART["Set" .. key] = nil
self.PART["Get" .. key] = nil
self.PART["Is" .. key] = nil
self.PART[key] = nil
self:RemoveProp(key)
return self
end
function META:Register()
pac.PartTemplates[self.PART.ClassName] = self
pac.RegisterPart(self.PART)
return self
end
function pac.PartTemplate(name)
local builder
if name and pac.PartTemplates[name] then
builder = pac.CopyValue(pac.PartTemplates[name])
else
builder = {PART = {}}
builder.PART.Builder = builder
end
return setmetatable(builder, META), builder.PART
end
function pac.GetTemplate(name)
return pac.PartTemplates[name]
end
end
function pac.GetPropertyUserdata(obj, key)
return pac.PartTemplates[obj.ClassName] and pac.PartTemplates[obj.ClassName]:GetPropData(key) or {}
end |
local Modules = game:GetService("Players").LocalPlayer.PlayerGui.AvatarEditorInGame.Modules
local Roact = require(Modules.Packages.Roact)
local UIBlox = require(Modules.Packages.UIBlox)
local withStyle = UIBlox.Style.withStyle
local GRADIENT_IMAGE = "rbxasset://textures/ui/LuaApp/graphic/gradient_0_100.png"
local GRADIENT_SIZE = 50
local GradientFrame = Roact.PureComponent:extend("GradientFrame")
function GradientFrame:render()
local gradientStyle = self.props.gradientStyle
local navHeight = self.props.navHeight
local ZIndex = self.props.ZIndex
return withStyle(function(stylePalette)
local theme = stylePalette.Theme
local gradientColor = gradientStyle and gradientStyle.Color or theme.BackgroundDefault.Color
local gradientTransparency = gradientStyle and gradientStyle.Transparency or theme.BackgroundDefault.Transparency
return Roact.createElement("Frame", {
BackgroundTransparency = 1,
Size = UDim2.new(1, 0, 1, 0),
ZIndex = ZIndex,
[Roact.Ref] = self.props.ref,
}, {
Left = Roact.createElement("Frame", {
BackgroundTransparency = 1,
Size = UDim2.new(0, GRADIENT_SIZE, 0, navHeight),
}, {
Image = Roact.createElement("ImageLabel", {
AnchorPoint = Vector2.new(0.5, 0.5),
BackgroundTransparency = 1,
Position = UDim2.new(0.5, 0, 0.5, 0),
Size = UDim2.new(0, navHeight, 0, GRADIENT_SIZE),
Rotation = 90,
Image = GRADIENT_IMAGE,
ImageColor3 = gradientColor,
ImageTransparency = gradientTransparency,
}),
}),
Right = Roact.createElement("Frame", {
AnchorPoint = Vector2.new(1, 0),
BackgroundTransparency = 1,
Position = UDim2.new(1, 0, 0, 0),
Size = UDim2.new(0, GRADIENT_SIZE, 0, navHeight),
}, {
Image = Roact.createElement("ImageLabel", {
AnchorPoint = Vector2.new(0.5, 0.5),
BackgroundTransparency = 1,
Position = UDim2.new(0.5, 0, 0.5, 0),
Size = UDim2.new(0, navHeight, 0, GRADIENT_SIZE),
Rotation = -90,
Image = GRADIENT_IMAGE,
ImageColor3 = gradientColor,
ImageTransparency = gradientTransparency,
}),
}),
})
end)
end
return GradientFrame |
require 'utils'
local car = getCar()
local addr = car:f('name').address
-- Obtain a pointer to the name buffer.
--
local tp = dbgscript.createTypedPointer('kernelbase!char', addr)
-- Print the first few characters.
--
print (tp[0].value)
print (tp[1].value)
|
ix.randomitems.tables["reward_generic_valuable"] = {
{500, {"value_statue_cat"}},
{300, {"value_statue_horse"}},
{400, {"value_statue_lion"}},
{500, {"value_gunpowder_green"}},
{400, {"value_gunpowder_blue"}},
{300, {"value_gunpowder_red"}},
{100, {"value_watch"}},
{250, {"value_phone_old"}},
{125, {"value_phone_new"}},
{50, {"value_goldchain"}},
{350, {"value_wirelesstrans"}},
{450, {"value_documents_3"}},
{400, {"value_documents_4"}},
{500, {"value_documents_5"}},
{300, {"value_documents_9"}},
{100, {"value_documents_10"}},
{100, {"value_documents_11"}},
{100, {"value_documents_14"}},
{300, {"value_gunspray"}},
{300, {"value_guncleaner"}},
{300, {"value_lubricant"}},
{400, {"drink_vodka_4"}},
{250, {"drink_vodka_5"}},
{250, {"drink_spirit_1"}},
{250, {"drink_spirit_2"}},
{250, {"drink_spirit_3"}},
{250, {"food_mre_usa"}},
{250, {"food_mre_ukraine"}},
{250, {"food_mre_russia"}},
{150, {"medic_medkit_3"}},
{150, {"medic_medkit_4"}},
{100, {"drug_cocaine"}},
{100, {"drug_morphine"}},
{100, {"drug_marijuana"}},
{100, {"drug_cigar"}},
{100, {"ar159mm", {["durability"] = 35}}},
{100, {"lugerp08", {["durability"] = 35}}},
{100, {"mateba", {["durability"] = 75}}},
{100, {"mp40", {["durability"] = 35}}},
{100, {"obrez", {["durability"] = 75}}},
{100, {"ppsh", {["durability"] = 35}}},
{100, {"stechaps", {["durability"] = 35}}},
{100, {"stoegerdd", {["durability"] = 75}}},
{100, {"stoegerddshort", {["durability"] = 75}}},
{100, {"swr8", {["durability"] = 75}}},
{100, {"swmodel29", {["durability"] = 75}}},
{100, {"taurusragingbull", {["durability"] = 75}}},
{50, {"acog"}},
{50, {"aimpoint"}},
{200, {"cmore"}},
{50, {"eotech"}},
{50, {"foregrip"}},
{50, {"kingarmsmr"}},
{50, {"kobra"}},
{50, {"microt1"}},
{10, {"nightforce"}},
{50, {"pso1"}},
{50, {"shortdot"}},
{200, {"trijiconrmr"}},
{15, {"cobrasuppressor"}},
{15, {"pbssuppressor"}},
{15, {"sakersuppressor"}},
{15, {"tundrasuppressor"}},
{200, {"hidestash_1"}},
{100, {"hidestash_2"}},
{25, {"hidestash_3"}},
} |
local Pill = script.Parent
local App = Pill.Parent
local UIBlox = App.Parent
local Packages = UIBlox.Parent
local Roact = require(Packages.Roact)
local Cryo = require(Packages.Cryo)
local t = require(Packages.t)
local Images = require(App.ImageSet.Images)
local CursorKind = require(App.SelectionImage.CursorKind)
local withSelectionCursorProvider = require(App.SelectionImage.withSelectionCursorProvider)
local ImageSetComponent = require(UIBlox.Core.ImageSet.ImageSetComponent)
local ControlState = require(UIBlox.Core.Control.Enum.ControlState)
local GenericButton = require(UIBlox.Core.Button.GenericButton)
local GenericTextLabel = require(UIBlox.Core.Text.GenericTextLabel.GenericTextLabel)
local withStyle = require(UIBlox.Core.Style.withStyle)
local getContentStyle = require(Pill.getContentStyle)
local HEIGHT = 48
local PADDING = 24
local BUTTON_STATE_COLOR = {
[ControlState.Default] = "SecondaryDefault",
[ControlState.Hover] = "SecondaryOnHover",
}
local SELECTED_BUTTON_STATE_COLOR = {
[ControlState.Default] = "UIDefault",
}
local CONTENT_STATE_COLOR = {
[ControlState.Default] = "SecondaryContent",
[ControlState.Hover] = "SecondaryOnHover",
}
local SELECTED_CONTENT_STATE_COLOR = {
[ControlState.Default] = "SecondaryOnHover",
}
local LargePill = Roact.PureComponent:extend("LargePill")
LargePill.validateProps = t.strictInterface({
-- Position in an ordered layout
layoutOrder = t.optional(t.number),
-- Width of the pill
width = t.optional(t.UDim),
-- Text shown in the Pill
text = t.optional(t.string),
-- Flag that indicates that the Pill is selected (background is filled)
isSelected = t.optional(t.boolean),
-- Flag that indicates that the Pill is still loading
isLoading = t.optional(t.boolean),
-- Flag that indicates that the Pill is disabled
isDisabled = t.optional(t.boolean),
-- BackgroundColor (used for the loading animation)
backgroundColor = t.optional(t.Color3),
-- Callback function when the Pill is clicked
onActivated = t.callback,
-- optional parameters for RoactGamepad
NextSelectionLeft = t.optional(t.table),
NextSelectionRight = t.optional(t.table),
NextSelectionUp = t.optional(t.table),
NextSelectionDown = t.optional(t.table),
controlRef = t.optional(t.table),
})
LargePill.defaultProps = {
layoutOrder = 1,
width = UDim.new(.5, 0),
text = "",
isSelected = false,
isLoading = false,
isDisabled = false,
}
function LargePill:init()
self.state = {
controlState = ControlState.Initialize
}
self.onStateChanged = function(oldState, newState)
self:setState({
controlState = newState,
})
end
end
function LargePill:render()
local isSelected = self.props.isSelected
local image = isSelected and Images["component_assets/circle_49"] or Images["component_assets/circle_49_stroke_1"]
local buttonColors = isSelected and SELECTED_BUTTON_STATE_COLOR or BUTTON_STATE_COLOR
local contentColors = isSelected and SELECTED_CONTENT_STATE_COLOR or CONTENT_STATE_COLOR
return withStyle(function(style)
return withSelectionCursorProvider(function(getSelectionCursor)
local theme = style.Theme
local currentState = self.state.controlState
local textStyle = getContentStyle(contentColors, currentState, style)
local size = UDim2.new(self.props.width, UDim.new(0, HEIGHT))
local sliceCenter = Rect.new(24, 24, 25, 25)
return Roact.createElement("Frame", {
Size = size,
BackgroundTransparency = 1,
LayoutOrder = self.props.layoutOrder,
}, {
Button = Roact.createElement(GenericButton, {
Size = size,
SliceCenter = sliceCenter,
SelectionImageObject = getSelectionCursor(CursorKind.LargePill),
isLoading = self.props.isLoading,
isDisabled = self.props.isDisabled,
text = self.props.text,
onActivated = self.props.onActivated,
buttonImage = image,
buttonStateColorMap = buttonColors,
contentStateColorMap = contentColors,
onStateChanged = self.onStateChanged,
NextSelectionLeft = self.props.NextSelectionLeft,
NextSelectionRight = self.props.NextSelectionRight,
NextSelectionUp = self.props.NextSelectionUp,
NextSelectionDown = self.props.NextSelectionDown,
[Roact.Ref] = self.props.controlRef,
}, {
UIListLayout = Roact.createElement("UIListLayout", {
FillDirection = Enum.FillDirection.Horizontal,
VerticalAlignment = Enum.VerticalAlignment.Center,
HorizontalAlignment = Enum.HorizontalAlignment.Center,
SortOrder = Enum.SortOrder.LayoutOrder,
Padding = UDim.new(0, PADDING),
}),
Text = Roact.createElement(GenericTextLabel, {
Size = UDim2.new(1, -2 * PADDING, 1, 0),
BackgroundTransparency = 1,
Text = self.props.text,
fontStyle = style.Font.Header2,
colorStyle = textStyle,
LayoutOrder = 2,
TextTruncate = Enum.TextTruncate.AtEnd,
}),
}),
Mask = self.props.isLoading and Roact.createElement(ImageSetComponent.Label, {
BackgroundTransparency = 1,
Image = Images["component_assets/circle_49_mask"],
ImageColor3 = self.props.backgroundColor or theme.BackgroundDefault.Color,
ScaleType = Enum.ScaleType.Slice,
SliceCenter = sliceCenter,
Size = size,
ZIndex = 3,
}),
})
end)
end)
end
return Roact.forwardRef(function (props, ref)
return Roact.createElement(LargePill, Cryo.Dictionary.join(
props,
{controlRef = ref}
))
end)
|
workspace "JetbrainsTask"
architecture "x64"
configurations {
"Debug",
"Release"
}
outputDir = "%{cfg.buildcfg}-%{cfg.system}-%{cfg.architecture}"
includeDir = {}
includeDir["GLFW"] = "JetbrainsTask/vendor/glfw/include"
include "JetbrainsTask/vendor/glfw"
project "JetbrainsTask"
location "JetbrainsTask"
language "C++"
cppdialect "C++17"
systemversion "latest"
targetdir ("out/"..outputDir.. "/%{prj.name}")
objdir ("out/build/"..outputDir.. "/%{prj.name}")
files {
"%{prj.name}/src/**.h",
"%{prj.name}/src/**.cpp",
"%{prj.name}/src/**.c"
}
includedirs {
"%{prj.name}/src",
"%{prj.name}/src/vendor",
"./vendorInclude",
"%{includeDir.GLFW}"
}
links {
"GLFW"
}
filter "system:windows"
buildoptions {
"/Zc:__cplusplus" --for __cplusplus macro work
}
links {
"opengl32.lib"
}
linkoptions {
--https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2010/f9t8842e(v=vs.100)
"/ENTRY:mainCRTStartup" -- Wow, microsoft
}
filter "system:macosx"
--Sreiosly, Apple? Why
linkoptions {
"-framework OpenGL",
"-framework Cocoa",
"-framework IOKit",
"-framework CoreVideo"
}
filter "system:linux"
buildoptions {
"GL",
"X11",
"pthread",
"glfw3",
"Xrandr"
}
filter "configurations:Debug"
defines {
}
symbols "On"
kind "ConsoleApp"
filter "configurations:Release"
defines {
}
optimize "On"
kind "WindowedApp"
filter "system:macosx"
defines {
"T_APPLE"
} |
--[[
FLY
by RedPolygon
The functions in this file combine the orientation and auto flying functions
to calculate the controls based off the mode the user is in
--]]
-- CONSTANTS
local attitude = require "calc/attitude"
local autopilot = require "calc/autopilot"
local fly = {}
fly.motorPins = {
1, 2,
3, 4,
}
-- VARIABLES
-- FRONT LEFT (cw), FRONT RIGHT (ccw),
-- BACK LEFT (ccw), BACK RIGHT (cw)
fly.masks = {
matrix{ -- x/forward
{-1, -1},
{ 1, 1},
},
matrix{ -- y/right
{1, -1},
{1, -1},
},
matrix{ -- z/yaw/turn right
{-1, 1},
{ 1,-1},
},
}
-- The default (calibration) masks to apply before steering masks
fly.defaults = {
calibration = matrix{
{0, 0},
{0, 0},
},
}
-- The motor (output) values
fly.motors = matrix{
{0, 0},
{0, 0},
}
fly.calibrating = false -- false, "sensors", "motors"
-- FUNCTIONS
function fly.reset()
-- Reset desired orientation
attitude.orientation.desired = { position = {}, rotation = {} }
-- TODO: Reset PID
end
-- Apply the masks to the motor values
function fly.translateControls(controls)
-- Defaults
for k, v in pairs(fly.defaults) do
fly.motors = fly.defaults[k] + 1
end
local power = (controls[3][1] + 1) / 2
local pitch = controls[1][1]
local roll = controls[2][1]
local yaw = controls[4][1]
-- Controls: z/up, x/pitch, y/roll, z/yaw
fly.motors[1][1] = power - pitch + roll - yaw
fly.motors[1][2] = power - pitch - roll + yaw
fly.motors[2][1] = power + pitch + roll + yaw
fly.motors[2][2] = power + pitch - roll - yaw
-- fly.motors = fly.motors * controls[4][1]
-- for i = 1, #fly.masks do
-- local mask = fly.masks[i]
-- local scale = 0.2 * controls[i][1] * math.abs(controls[i][1])
-- fly.motors = fly.motors * (mask * scale + 1)
-- end
networkControls = fly.motors -- Debugging
end
function fly.calculateMotors( mode, controls, dt )
if mode == 0 then
fly.translateControls(controls)
elseif mode == 1 then
-- Calculate controls based off desired rotation
fly.translateControls( autopilot.rotation( controls, attitude.orientation, dt ) )
elseif mode == 2 then
-- Calculate controls based off desired speed
fly.translateControls( autopilot.speed( controls, attitude.orientation, dt ) )
elseif mode == 3 then
-- Calculate controls based off desired position
fly.translateControls( autopilot.position( controls, attitude.orientation, dt ) )
end
end
function fly.calibrateMotors() -- TODO: make calibrating function
end
fly.orientate = attitude.orientate
-- RETURN
return fly
|
function love.conf(t)
v1 = 1080
v2 = 540
t.window.title = "LuaChip8"
t.window.width = v2 * (16/9)
t.window.height = v2
t.console = false
t.window.resizeable = false
t.window.vsync = true
end |
-- Small functions for working with player, maybe that should be in base instead of lib
player_meta = FindMetaTable( "Player" )
-- Returns true if player is captain
function player_meta:IsCaptain()
if self.se_role == SE_CAPTAIN then
return true
else
return false
end
end
-- Gets players role
function player_meta:GetRole()
return self.se_role
end
-- Gets players role
function player_meta:GetRoleTable()
return (se_roles[self.se_role] or se_roles[SE_ENGINEER])
end
-- Heals player(wtf, why there is nothing like that in gmod api)
function player_meta:Heal(amount)
self:SetHealth(math.Clamp(self:Health() + amount, 0, self:GetMaxHealth()))
end
|
local packer = require('util.packer')
local global = require('core.global')
local config = {
max_jobs = global.is_mac and 60 or nil,
profile = {
enable = true,
threshold = 0, -- the amount in ms that a plugins load time must be over for it to be included in the profile
},
display = {
open_fn = function()
return require('packer.util').float({ border = 'single' })
end,
},
-- list of plugins that should be taken from ~/projects
-- this is NOT packer functionality!
local_plugins = {},
}
local function plugins(use)
-- Packer can manage itself as an optional plugin
use({ 'wbthomason/packer.nvim', opt = true })
use({
'neoclide/coc.nvim',
disable = true,
branch = 'release',
config = function()
vim.cmd('source ~/.config/nvim/viml/plugins.config/coc.nvim.vim')
end,
})
-- util
use({ 'nvim-lua/plenary.nvim', module = 'plenary' })
use({ 'nvim-lua/popup.nvim', module = 'popup' })
-- LSP related plugins start
use({
'neovim/nvim-lspconfig',
opt = true,
event = 'BufReadPre',
wants = {
'nvim-lsp-ts-utils',
'null-ls.nvim',
'lua-dev.nvim',
},
config = function()
require('config.lsp')
end,
requires = {
'jose-elias-alvarez/nvim-lsp-ts-utils',
'jose-elias-alvarez/null-ls.nvim',
'folke/lua-dev.nvim',
},
})
use({
'RRethy/vim-illuminate',
event = 'CursorHold',
module = 'illuminate',
config = function()
vim.g.Illuminate_delay = 100
end,
})
use({
'simrat39/symbols-outline.nvim',
cmd = { 'SymbolsOutline' },
})
use({
'liuchengxu/vista.vim',
after = 'nvim-lspconfig',
cmd = { 'Vista', 'Vista!!' },
config = function()
vim.g.vista_default_executive = 'nvim_lsp'
end,
})
-- LSP related plugins end
-- auto completion
use({
'hrsh7th/nvim-cmp',
event = 'InsertEnter',
config = function()
require('config.nvim-cmp')
end,
requires = {
'onsails/lspkind-nvim',
'hrsh7th/cmp-nvim-lsp',
{ 'hrsh7th/cmp-buffer', after = 'nvim-cmp' },
{ 'hrsh7th/cmp-vsnip', after = 'nvim-cmp' },
{ 'hrsh7th/cmp-path', after = 'nvim-cmp' },
{ 'hrsh7th/cmp-nvim-lua', after = 'nvim-cmp' },
{ 'octaltree/cmp-look', after = 'nvim-cmp' },
{
'windwp/nvim-autopairs',
after = 'nvim-cmp',
config = function()
require('config.autopairs')
end,
},
{ 'hrsh7th/vim-vsnip', after = 'nvim-cmp' },
{ 'hrsh7th/vim-vsnip-integ', after = 'nvim-cmp' },
{ 'rafamadriz/friendly-snippets', after = 'vim-vsnip' },
},
})
-- comment plugin
use({
'b3nj5m1n/kommentary',
opt = true,
wants = 'nvim-ts-context-commentstring',
keys = { 'gc', 'gcc', '<C-_>' },
config = function()
require('config.comments')
end,
requires = 'JoosepAlviste/nvim-ts-context-commentstring',
})
-- better syntax parser
use({
'nvim-treesitter/nvim-treesitter',
run = ':TSUpdate',
opt = true,
event = 'BufRead',
requires = {
{ 'nvim-treesitter/playground', cmd = 'TSHighlightCapturesUnderCursor' },
'nvim-treesitter/nvim-treesitter-textobjects',
'p00f/nvim-ts-rainbow',
'RRethy/nvim-treesitter-textsubjects',
},
config = [[require('config.treesitter')]],
})
-- display colors
use({
'norcalli/nvim-colorizer.lua',
config = function()
require('config.colorizer')
end,
})
-- Theme: color schemes
-- use("tjdevries/colorbuddy.vim")
-- "shaunsingh/nord.nvim",
-- "shaunsingh/moonlight.nvim",
-- { "olimorris/onedark.nvim", requires = "rktjmp/lush.nvim" },
-- "joshdick/onedark.vim",
-- "wadackel/vim-dogrun",
-- { "npxbr/gruvbox.nvim", requires = "rktjmp/lush.nvim" },
-- "bluz71/vim-nightfly-guicolors",
-- { "marko-cerovac/material.nvim" },
-- "sainnhe/edge",
-- { "embark-theme/vim", as = "embark" },
-- "norcalli/nvim-base16.lua",
-- "RRethy/nvim-base16",
-- "novakne/kosmikoa.nvim",
-- "glepnir/zephyr-nvim",
-- "ghifarit53/tokyonight-vim"
-- "sainnhe/sonokai",
-- "morhetz/gruvbox",
-- "arcticicestudio/nord-vim",
-- "drewtempelmeyer/palenight.vim",
-- "Th3Whit3Wolf/onebuddy",
-- "christianchiarulli/nvcode-color-schemes.vim",
-- "Th3Whit3Wolf/one-nvim"
-- "folke/tokyonight.nvim",
-- "glepnir/zephyr-nvim",
use({
'rose-pine/neovim',
config = function()
require('config.theme')
end,
})
use({
'folke/tokyonight.nvim',
config = function()
require('config.theme')
end,
})
use({
'sainnhe/everforest',
config = function()
require('config.theme')
end,
})
use({
'ray-x/aurora',
config = function()
require('config.theme')
end,
})
use({
'sainnhe/sonokai',
config = function()
require('config.theme')
end,
})
-- Theme: icons
use({
'kyazdani42/nvim-web-devicons',
module = 'nvim-web-devicons',
config = function()
require('nvim-web-devicons').setup({ default = true })
end,
})
-- Dashboard
use({ 'glepnir/dashboard-nvim', config = [[require('config.dashboard')]] })
use({
'norcalli/nvim-terminal.lua',
ft = 'terminal',
config = function()
require('terminal').setup()
end,
})
-- search and replace
use({
'windwp/nvim-spectre',
opt = true,
module = 'spectre',
wants = { 'plenary.nvim', 'popup.nvim' },
requires = { 'nvim-lua/popup.nvim', 'nvim-lua/plenary.nvim' },
})
-- file explorer
use({
'kyazdani42/nvim-tree.lua',
config = function()
require('config.tree')
end,
})
use({
'mhartington/formatter.nvim',
cmd = { 'Format', 'FormatWrite' },
config = function()
require('config.formatter')
end,
})
-- Fuzzy finder
use({
'nvim-telescope/telescope.nvim',
opt = true,
config = function()
require('config.telescope')
end,
cmd = { 'Telescope' },
module = 'telescope',
wants = {
'plenary.nvim',
'popup.nvim',
'telescope-frecency.nvim',
-- 'telescope-fzy-native.nvim',
'telescope-fzf-native.nvim',
'telescope-project.nvim',
'trouble.nvim',
'telescope-symbols.nvim',
'telescope-cheat.nvim',
},
requires = {
'nvim-lua/popup.nvim',
'nvim-lua/plenary.nvim',
'nvim-telescope/telescope-project.nvim',
'nvim-telescope/telescope-symbols.nvim',
-- 'nvim-telescope/telescope-fzy-native.nvim',
{ 'nvim-telescope/telescope-fzf-native.nvim', run = 'make' },
{ 'nvim-telescope/telescope-frecency.nvim', requires = 'tami5/sqlite.lua' },
{ 'nvim-telescope/telescope-cheat.nvim', requires = 'tami5/sqlite.lua' },
},
})
use({
'sudormrfbin/cheatsheet.nvim',
-- requires = {
-- { "nvim-telescope/telescope.nvim" },
-- { "nvim-lua/popup.nvim" },
-- { "nvim-lua/plenary.nvim" },
-- },
config = function()
require('cheatsheet').setup({
bundled_cheatsheets = true,
bundled_plugin_cheatsheets = true,
include_only_installed_plugins = true,
})
end,
})
-- Indent Guides and rainbow brackets
use({
'lukas-reineke/indent-blankline.nvim',
event = 'BufReadPre',
config = function()
require('config.indent-blankline')
end,
})
-- Tabline
use({
'akinsho/nvim-bufferline.lua',
event = 'BufReadPre',
wants = 'nvim-web-devicons',
config = function()
require('config.bufferline')
end,
})
-- Terminal
-- use(
-- {
-- "akinsho/nvim-toggleterm.lua",
-- keys = "<M-`>",
-- config = function()
-- require("config.terminal")
-- end
-- }
-- )
-- Smooth Scrolling
use({
'karb94/neoscroll.nvim',
keys = { '<C-u>', '<C-d>', '<C-b>', '<C-f>', '<C-y>', '<C-e>', 'zt', 'zz', 'zb' },
config = function()
require('config.scroll')
end,
})
use({
'edluffy/specs.nvim',
after = 'neoscroll.nvim',
config = function()
require('config.specs')
end,
})
-- use { "Xuyuanp/scrollbar.nvim", config = function() require("config.scrollbar") end }
-- Git signs
use({
'lewis6991/gitsigns.nvim',
event = 'BufReadPre',
wants = 'plenary.nvim',
requires = { 'nvim-lua/plenary.nvim' },
config = function()
require('config.gitsigns')
end,
})
use({
'TimUntersberger/neogit',
cmd = 'Neogit',
config = function()
require('config.neogit')
end,
})
-- Statusline
use({
'hoob3rt/lualine.nvim',
disable = true,
event = 'VimEnter',
config = [[require('config.lualine')]],
wants = 'nvim-web-devicons',
})
use({
'glepnir/galaxyline.nvim',
config = function()
require('config.galaxyline')
end,
requires = { 'kyazdani42/nvim-web-devicons', opt = true },
})
-- use({"npxbr/glow.nvim", cmd = "Glow"})
use({
'plasticboy/vim-markdown',
opt = true,
requires = 'godlygeek/tabular',
ft = 'markdown',
})
use({
'iamcco/markdown-preview.nvim',
run = function()
vim.fn['mkdp#util#install']()
end,
ft = 'markdown',
cmd = { 'MarkdownPreview' },
})
-- use { "tjdevries/train.nvim", cmd = { "TrainClear", "TrainTextObj", "TrainUpDown", "TrainWord" } }
-- use({
-- "wfxr/minimap.vim",
-- config = function()
-- require("config.minimap")
-- end,
-- })
-- use(
-- {
-- "phaazon/hop.nvim",
-- keys = {"gh"},
-- cmd = {"HopWord", "HopChar1"},
-- config = function()
-- require("util").nmap("gh", "<cmd>HopWord<CR>")
-- -- require("util").nmap("s", "<cmd>HopChar1<CR>")
-- -- you can configure Hop the way you like here; see :h hop-config
-- require("hop").setup({})
-- end
-- }
-- )
-- use(
-- {
-- "ggandor/lightspeed.nvim",
-- event = "BufReadPost",
-- config = function()
-- require("config.lightspeed")
-- end
-- }
-- )
use({
'folke/trouble.nvim',
event = 'BufReadPre',
wants = 'nvim-web-devicons',
cmd = { 'TroubleToggle', 'Trouble' },
config = function()
require('trouble').setup({ auto_open = false })
end,
})
-- use(
-- {
-- "folke/persistence.nvim",
-- event = "BufReadPre",
-- module = "persistence",
-- config = function()
-- require("persistence").setup()
-- end
-- }
-- )
use({ 'tweekmonster/startuptime.vim', cmd = 'StartupTime' })
use({ 'mbbill/undotree', cmd = 'UndotreeToggle' })
use({
'folke/todo-comments.nvim',
cmd = { 'TodoTrouble', 'TodoTelescope' },
event = 'BufReadPost',
config = function()
require('config.todo-comments')
end,
})
use({
'folke/which-key.nvim',
event = 'VimEnter',
config = function()
require('config.keys')
end,
})
use({
'sindrets/diffview.nvim',
cmd = {
'DiffviewOpen',
'DiffviewClose',
'DiffviewToggleFiles',
'DiffviewFocusFiles',
},
config = function()
require('config.diffview')
end,
})
-- use("DanilaMihailov/vim-tips-wiki")
-- use("nanotee/luv-vimdocs")
use({
'andymass/vim-matchup',
event = 'CursorMoved',
})
-- use({"camspiers/snap", rocks = {"fzy"}, module = "snap"})
use({
'tpope/vim-endwise',
config = function()
vim.g.endwise_no_mappings = 1
end,
})
use({ 'mhinz/vim-sayonara', cmd = { 'Sayonara' } })
use({ 'AndrewRadev/switch.vim' })
use({ 'kiooss/vim-zenkaku-space' })
use({
'jghauser/mkdir.nvim',
config = function()
require('mkdir')
end,
})
use({
'lambdalisue/suda.vim',
cmd = { 'SudaWrite', 'SudaRead' },
})
use({
'pechorin/any-jump.vim',
cmd = { 'AnyJump', 'AnyJumpVisual' },
})
use({
'rhysd/committia.vim',
ft = 'gitcommit',
})
use({
'mattn/vim-sqlfmt',
ft = 'sql',
})
-- if global.is_linux then
-- use({
-- 'wincent/vim-clipper',
-- setup = function()
-- vim.g.ClipperMap = 0
-- vim.g.ClipperAddress = '~/.clipper.sock'
-- vim.g.ClipperPort = 0
-- end,
-- })
-- end
-- align
use({ 'junegunn/vim-easy-align' })
-- additional text objects
use({ 'wellle/targets.vim' })
use({ 'rhysd/vim-textobj-anyblock' })
use({ 'kana/vim-textobj-entire' })
use({ 'kana/vim-textobj-function' })
use({ 'kana/vim-textobj-user' })
use({ 'nelstrom/vim-textobj-rubyblock' })
use({ 'thalesmello/vim-textobj-methodcall' })
use({ 'tpope/vim-repeat' })
use({
'tpope/vim-surround',
config = function()
vim.g.surround_no_insert_mappings = 1
end,
})
-- use({
-- "SirVer/ultisnips",
-- setup = function()
-- vim.g.UltiSnipsExpandTrigger = "<c-k>"
-- vim.g.UltiSnipsJumpForwardTrigger = "<c-k>"
-- vim.g.UltiSnipsJumpBackwardTrigger = "<c-j>"
-- vim.g.UltiSnipsEditSplit = "vertical"
-- vim.g.UltiSnipsSnippetDirectories = { "UltiSnips" }
-- end,
-- })
-- use({ 'honza/vim-snippets' })
-- use({ 'algotech/ultisnips-php' })
-- use({ 'epilande/vim-react-snippets' })
use({ 'famiu/bufdelete.nvim', cmd = 'Bdelete' })
use({ 'editorconfig/editorconfig-vim' })
use({
'vimwiki/vimwiki',
opt = true,
cmd = 'VimwikiIndex',
keys = { '<leader>W' },
setup = function()
vim.g.vimwiki_list = {
{ path = '~/vimwiki/', syntax = 'markdown', ext = '.md' },
}
vim.g.vimwiki_conceallevel = 0
vim.g.vimwiki_use_calendar = 1
vim.g.vimwiki_hl_headers = 1
vim.g.vimwiki_hl_cb_checked = 1
vim.g.vimwiki_autowriteall = 0
vim.g.vimwiki_map_prefix = '<F12>'
vim.g.vimwiki_table_mappings = 0
end,
})
use({ 'mg979/vim-visual-multi' })
use({ 'tpope/vim-fugitive' })
use({ 'tpope/vim-rhubarb' })
use({
'ruanyl/vim-gh-line',
config = function()
vim.g.gh_trace = 1
vim.g.gh_open_command = 'echo '
vim.g.gh_use_canonical = 0
vim.g.gh_line_blame_map = '<leader>gm'
end,
})
-- notification windows
use({
'rcarriga/nvim-notify',
config = function()
vim.notify = require('notify')
end,
})
-- copy text to the system clipboard from anywhere
use({ 'ojroques/vim-oscyank' })
-- Syntax plugins
use({ 'lumiliet/vim-twig', ft = 'twig' })
-- other mixed
use({ 'ThePrimeagen/vim-be-good', cmd = 'VimBeGood' })
end
return packer.setup(config, plugins)
|
--[[
Desc: State of being lifted up
Author: SerDing
Since: 2018-02-26 14:25:46
Alter: 2018-02-26 14:25:46
]]
local _Timer = require("utils.timer")
local _Base = require("entity.states.base")
---@class State.Lift : Entity.State.Base
local _Lift = require("core.class")(_Base)
function _Lift:Ctor(data, name)
_Base.Ctor(self, data, name)
self._aerialTimer = _Timer.New(_, _, true)
self._aerialTimeLimit = data.aerialTimeLimit or 2000
self._protectionTimer = _Timer.New()
self._protectionTime = data.protectionTime or 100
self._defaultVz = data.defaultVz or 260
self._defaultAz = data.defaultAz or 20
self._g = 0
self._lowestHeight = data.lowestHeight or 30
self._reliftFrame = data.reliftFrame or 3
self._reliftRate = data.reliftRate or { touchdown = 0.3, lowHeight = 0.5, bounce = 0.5, }
self._bounce = {
enable = true,
hasDone = false,
vz = 0,
az = 0,
}
end
function _Lift:Init(entity)
_Base.Init(self, entity)
end
function _Lift:Enter(vz, az, vx, ax)
_Base.Enter(self)
vz = vz or self._defaultVz
vx = vx or 0
az = az or self._defaultAz
ax = ax or 0
self._g = az
self._avatar:Play(self._animNameSet[1])
if vx == 0 then
self._movement:StopEasemove()
else
self._movement:EaseMove("x", vx, ax)
end
-- if vz ~= 0 then
vz = vz - self._entity.fighter.weight
vz = vz < 0 and 0 or vz
local touchdown = self._STATE.preState == self and self._entity.transform.position.z == 0
vz = touchdown and vz * self._reliftRate.touchdown or vz
local isAerial = self._movement:IsFalling() or self._movement:IsRising()
local isLowHeight = self._entity.transform.position.z >= -self._lowestHeight
if isAerial and isLowHeight then
local h = (vz <= 0) and 0 or math.pow(vz, 2) / (2 * az)
vz = math.sqrt(2 * az * h * self._reliftRate.lowHeight)
end
self._bounce.enable = (vz >= 200) and true or false
self._bounce.vz = vz * self._reliftRate.bounce
self._bounce.az = az
self._movement:StartJump(vz, az, nil)
self._movement.eventMap.topped:AddListener(self, self._Topped)
self._movement.eventMap.touchdown:AddListener(self, self._Touchdown)
-- end
if touchdown or (isAerial and isLowHeight) then
self._avatar:SetFrame(3)
end
if not isAerial then -- first lift
self._aerialTimer:Start(self._aerialTimeLimit)
end
end
function _Lift:_Topped()
while self._avatar:GetFrame() < 3 do
self._avatar:NextFrame()
end
end
function _Lift:_Touchdown()
while self._avatar:GetFrame() < 4 do
self._avatar:NextFrame()
end
if self._bounce.enable and self._bounce.hasDone == false then
self._movement:StartJump(self._bounce.vz, self._bounce.az, nil)
self._bounce.hasDone = true
self._aerialTimer.isRunning = false
else -- final touchdown
while self._avatar:GetFrame() < 5 do
self._avatar:NextFrame()
end
self._movement:StopEasemove()
end
end
function _Lift:Update(dt)
self._aerialTimer:Tick(dt)
self._protectionTimer:Tick(dt)
if self._aerialTimer:GetCount() >= self._aerialTimeLimit then
if self._protectionTimer.isRunning == false then
self._protectionTimer:Start(self._protectionTime)
local overtime = self._aerialTimer:GetCount() - self._aerialTimeLimit
local g = (1 + overtime * 0.001 * 2) * self._g
self._movement:Set_g(g)
end
end
_Base.AutoTransitionAtEnd(self)
end
function _Lift:Exit()
self._bounce.hasDone = false
self._movement.eventMap.topped:DelListener(self, self._Topped)
self._movement.eventMap.touchdown:DelListener(self, self._Touchdown)
end
return _Lift |
local Sp,Si,Sm = "personality.lua","init.lua", "main.lc"
local SA,SR,SL,SC,SM,SH,SW = "Aborting: ","Running: ", "Loading: ", "Connected: " , " Missing", "Heap: ","Waiting... "
print(SH, node.heap())
fver = {} ; OS = false ; print(SL,SH,node.heap()) -- hardware init.lua means NO OS
local fn,fp = "init", {"0.4b","5/23/18","RLH"} ; fver[fn] = fp
print(string.format("Load: %s.lua Ver:%s %s %s \n" ,fn, fp[1], fp[2], fp[3]))
-- load credentials, 'SSID' and 'PASSWORD' declared and initialize in there
if file.exists(Sp) then dofile(Sp) end
-- strings
--[[
nh = node.heap
m = "main"
p = print
d = dofile
fe = file.exists
sS = "Success!"
-- s used in OLED.lua
sR = "Running"
sE = "ERROR"
--]]
function startup()
if file.open(Si) == nil then
print(Si,SM)
else
print(SR)
file.close(Si)
if file.exists(Sm) then print(SL,Sm) dofile(Sm)
else print(Sm, SM)
end
end
end
-- Define WiFi station event callbacks
wf_cnct = function(T)
print ("\n")
print(SC,T.SSID)
print(SW, " for IP address...")
print(SH, node.heap())
if dc ~= nil then dc = nil end
end
wf_gotip = function(T)
-- Note: Having an IP address does not mean there is internet access!
-- Internet connectivity can be determined with net.dns.resolve().
print("Wifi connection is ready! IP address is: "..T.IP)
print("Startup will resume momentarily, you have 3 seconds to abort.")
print(SW)
tmr.create():alarm(3000, tmr.ALARM_SINGLE, startup)
print("Check Internet connectivity")
net.dns.resolve(WEB_CHECK, function(sk, ip)
if (ip == nil) then print("DNS fail!")
else print(ip)
end
end)
end
wf_dscnt = function(T)
if T.reason == wifi.eventmon.reason.ASSOC_LEAVE then
--the station has disassociated from a previously connected AP
return
end
--tries: how many times the station will attempt to connect to the AP. Should consider AP reboot duration.
local total_tries = 75
print("\nWiFi connection to AP("..T.SSID..") has failed!")
--There are many possible disconnect reasons, the following iterates through
--the list and returns the string corresponding to the disconnect reason.
for key,val in pairs(wifi.eventmon.reason) do
if val == T.reason then
print("Disconnect reason: "..val.."("..key..")")
break
end
end
if dc == nil then
dc = 1
else
dc = dc + 1
end
if dc < total_tries then
print("Retrying ("..(dc+1).." of "..total_tries..")")
else
wifi.sta.disconnect()
print(SA)
dc = nil
end
end
-- Register WiFi Station event callbacks
wifi.eventmon.register(wifi.eventmon.STA_CONNECTED, wf_cnct)
wifi.eventmon.register(wifi.eventmon.STA_GOT_IP, wf_gotip)
wifi.eventmon.register(wifi.eventmon.STA_DISCONNECTED, wf_dscnt)
print(SC)
wifi.setmode(wifi.STATION)
wifi.sta.config({ssid=AP.SSID, pwd=AP.PASSWORD})
-- wifi.sta.connect() not necessary because config() uses auto-connect=true by default
|
local Dash = {}
Dash.config = function()
if not lvim.builtin.telescope.active then
return
end
--
-- If Dash.nvim plugin is installed and Dash.app is found
-- configure Dash as a Telescope extension
--
local status_ok, _ = pcall(require, "dash")
if status_ok then
local dash_app = vim.fn.glob "/Applications/Dash.app"
if dash_app == "" then
dash_app = vim.fn.glob "/Applications/Setapp/Dash.app"
end
if dash_app == "" then
Log:warn "Dash.nvim plugin installed but Dash.app was not found. Check configuration."
return
end
lvim.builtin.telescope.extensions["dash"] = {
dash_app_path = dash_app,
-- search engine to fall back to when Dash has no results, must be one of: 'ddg', 'duckduckgo', 'startpage', 'google'
search_engine = "duckduckgo",
-- debounce while typing, in milliseconds
debounce = 0,
-- map filetype strings to the keywords you've configured for docsets in Dash
-- setting to false will disable filtering by filetype for that filetype
-- filetypes not included in this table will not filter the query by filetype
-- check src/lua_bindings/dash_config_binding.rs to see all defaults
-- the values you pass for file_type_keywords are merged with the defaults
-- to disable filtering for all filetypes,
-- set file_type_keywords = false
file_type_keywords = {
dashboard = false,
NvimTree = false,
TelescopePrompt = false,
terminal = false,
packer = false,
fzf = false,
-- a table of strings will search on multiple keywords
javascript = { "javascript", "nodejs" },
typescript = { "typescript", "javascript", "nodejs", "moment" },
typescriptreact = { "typescript", "javascript", "react" },
javascriptreact = { "javascript", "react" },
vue = { "vue", "typescript", "html", "bootstrap-vue", "css" },
html = { "html", "bootstrap", "css" },
css = { "css", "media" },
scss = { "css", "media" },
markdown = { "markdown" },
lua = { "lua" },
python = { "python3" },
-- you can also do a string, for example,
-- sh = 'bash'
},
}
end
end
return Dash
|
local _waypointId = "splinter"
SplinterNpc = {
click = async(function(player, npc)
Tools.configureDialog(player, npc)
local opts = {
"Buy",
"Sell",
"Crafting Skills",
"Gathering Wood",
"Don't Knock Woodworking",
"Woodworking Devotion"
}
if (not Waypoint.isEnabled(player, _waypointId)) then
table.insert(opts, "Waypoint")
end
local menu = player:menuString(
"Hello! What would you like to do today?",
opts
)
if menu == "Buy" then
player:buyExtend(
"I think I can accomodate some of the things you need. What would you like?",
SplinterNpc.buyItems()
)
elseif menu == "Sell" then
player:sellExtend(
"What are you willing to sell today?",
SplinterNpc.sellItems()
)
elseif menu == "Crafting Skills" then
generalNPC.crafting_skills(player, npc)
elseif menu == "Gathering Wood" then
player:dialogSeq(
{
"Yup, I know about that. Go to a place with trees and hack at 'em with your axe.",
"Sometimes you'll find stuff. You should find a 'grove' to cut lumber in. There are a few around in the different forests.",
"For example, there's one near Buya at 46, 20 and one near Kugnae at 111, 178. I doubt you'll have much luck lumbering outside of the groves."
},
0
)
return
elseif menu == "Don't Knock Woodworking" then
player:dialogSeq(
{
"A fine skill. Sure, you can make any armor, or those so-called 'superior' metal weapons. But we woodworkers are much more versatile.",
"Woodworking allows you to make wooden weapons and arrows. Also, woodworking is needed to make weaving tools. When you're ready, just tell me 'wood'.",
"If you do poor work, you'll end up with wood scraps. Show them to me, ask me about 'scraps' and we'll see what we can salvage."
},
0
)
return
elseif menu == "Woodworking Devotion" then
SplinterNpc.woodworkingDevotion(player, npc)
elseif menu == "Waypoint" then
Waypoint.add(player, npc, _waypointId)
end
end),
woodworkingDevotion = function(player, npc)
Tools.configureDialog(player, npc)
if (player.level < 25) then
player:dialogSeq({"You are not ready to devote to a craft yet, come back later."}, 0)
return
end
if crafting.checkSkillLegend(player, "woodworking") then
player:dialogSeq({"You have already devoted yourself to the study of Woodworking."}, 0)
return
end
crafting.checkSkill(player, npc, "jewelry making")
crafting.checkSkill(player, npc, "tailoring")
crafting.checkSkill(player, npc, "metalworking")
player:dialogSeq({"Woodworkers can make wooden weapons, bows, arrows, and weaving tools. Do you wish to become a woodworker?"}, 1)
crafting.addSkill(player, npc, "woodworking")
end,
buyItems = function()
local buyItems = {"axe"}
return buyItems
end,
sellItems = function()
local sellItems = {
"axe",
"ginko_wood",
"weaving_tools",
"fine_weaving_tools",
"spring_quiver",
"summer_quiver",
"wooden_sword",
"viperhead_woodsaber",
"viperhead_woodsword",
"wooden_blade",
"supple_wooden_sword",
"supple_viperhead_woodsaber",
"supple_viperhead_woodsword",
"supple_wooden_blade",
"oaken_sword",
"supple_oaken_sword",
"oaken_blade",
"supple_oaken_blade"
}
return sellItems
end,
onSayClick = async(function(player, npc)
Tools.configureDialog(player, npc)
local speech = string.lower(player.speech)
if speech == "wood" or speech == "scrap" or speech == "scraps" then
crafting.craftingDialog(player, npc, speech)
end
if (speech == "waypoint" and not Waypoint.isEnabled(player, _waypointId)) then
Waypoint.add(player, npc, _waypointId)
return
end
end),
}
|
base_research = nil
base_research =
{
{
Name = "MothershipBUILDSPEEDUpgrade1",
RequiredResearch = "",
RequiredSubSystems = "Research",
RequireTag = "VaygrBuilder",
Cost = 1000,
Time = 60,
DisplayedName = "$7815",
DisplayPriority = 90,
Description = "$7816",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Vgr_MotherShip",
UpgradeName = "BUILDSPEED",
UpgradeValue = 1.3,
Icon = Icon_Build,
ShortDisplayedName = "$7240",
},
{
Name = "CarrierBUILDSPEEDUpgrade1",
RequiredResearch = "",
RequiredSubSystems = "CapShipProduction",
RequireTag = "VaygrBuilder",
Cost = 2500,
Time = 100,
DisplayedName = "$7820",
DisplayPriority = 65,
Description = "$7821",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Vgr_Carrier",
UpgradeName = "BUILDSPEED",
UpgradeValue = 1.3,
Icon = Icon_Build,
ShortDisplayedName = "$7240",
},
{
Name = "ShipyardBUILDSPEEDUpgrade1",
RequiredResearch = "",
RequiredSubSystems = "Research & CapShipProduction & Hyperspace",
RequireTag = "VaygrBuilder",
Cost = 1000,
Time = 95,
DisplayedName = "$7825",
DisplayPriority = 65,
Description = "$7826",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Vgr_ShipYard",
UpgradeName = "BUILDSPEED",
UpgradeValue = 1.3,
Icon = Icon_Build,
ShortDisplayedName = "$7240",
},
}
-- Add these items to the research tree!
for i, e in base_research do
research[res_index] = e
res_index = res_index + 1
end
base_research = nil
|
local SpatialConvolutionMap, parent = torch.class('nn.SpatialConvolutionMap', 'nn.Module')
nn.tables = nn.tables or {}
function nn.tables.full(nin, nout)
local ft = torch.Tensor(nin*nout,2)
local p = 1
for j=1,nout do
for i=1,nin do
ft[p][1] = i
ft[p][2] = j
p = p + 1
end
end
return ft
end
function nn.tables.oneToOne(nfeat)
local ft = torch.Tensor(nfeat,2)
for i=1,nfeat do
ft[i][1] = i
ft[i][2] = i
end
return ft
end
function nn.tables.random(nin, nout, nto)
local nker = nto * nout
local tbl = torch.Tensor(nker, 2)
local fi = torch.randperm(nin)
local frcntr = 1
local tocntr = 1
local nfi = math.floor(nin/nto) -- number of distinct nto chunks
local rfi = math.mod(nin,nto) -- number of remaining from maps
local totbl = tbl:select(2,2)
local frtbl = tbl:select(2,1)
local fitbl = fi:narrow(1, 1, (nfi * nto)) -- part of fi that covers distinct chunks
local ufrtbl= frtbl:unfold(1, nto, nto)
local utotbl= totbl:unfold(1, nto, nto)
local ufitbl= fitbl:unfold(1, nto, nto)
-- start filling frtbl
for i=1,nout do -- fro each unit in target map
ufrtbl:select(1,i):copy(ufitbl:select(1,frcntr))
frcntr = frcntr + 1
if frcntr-1 == nfi then -- reset fi
fi:copy(torch.randperm(nin))
frcntr = 1
end
end
for tocntr=1,utotbl:size(1) do
utotbl:select(1,tocntr):fill(tocntr)
end
return tbl
end
local function constructTableRev(conMatrix)
local conMatrixL = conMatrix:type('torch.LongTensor')
-- Construct reverse lookup connection table
local thickness = conMatrixL:select(2,2):max()
-- approximate fanin check
if (#conMatrixL)[1] % thickness == 0 then
-- do a proper fanin check and set revTable
local fanin = (#conMatrixL)[1] / thickness
local revTable = torch.Tensor(thickness, fanin, 2)
for ii=1,thickness do
local tempf = fanin
for jj=1,(#conMatrixL)[1] do
if conMatrixL[jj][2] == ii then
if tempf <= 0 then break end
revTable[ii][tempf][1] = conMatrixL[jj][1]
revTable[ii][tempf][2] = jj
tempf = tempf - 1
end
end
if tempf ~= 0 then
fanin = -1
break
end
end
if fanin ~= -1 then
return revTable
end
end
return {}
end
function SpatialConvolutionMap:__init(conMatrix, kW, kH, dW, dH)
parent.__init(self)
dW = dW or 1
dH = dH or 1
self.kW = kW
self.kH = kH
self.dW = dW
self.dH = dH
self.connTable = conMatrix
self.connTableRev = constructTableRev(conMatrix)
self.nInputPlane = self.connTable:select(2,1):max()
self.nOutputPlane = self.connTable:select(2,2):max()
self.weight = torch.Tensor(self.connTable:size(1), kH, kW)
self.bias = torch.Tensor(self.nOutputPlane)
self.gradWeight = torch.Tensor(self.connTable:size(1), kH, kW)
self.gradBias = torch.Tensor(self.nOutputPlane)
self:reset()
end
function SpatialConvolutionMap:reset(stdv)
if stdv then
stdv = stdv * math.sqrt(3)
if nn.oldSeed then
self.weight:apply(function()
return torch.uniform(-stdv, stdv)
end)
self.bias:apply(function()
return torch.uniform(-stdv, stdv)
end)
else
self.weight:uniform(-stdv, stdv)
self.bias:uniform(-stdv, stdv)
end
else
local ninp = torch.Tensor(self.nOutputPlane):zero()
for i=1,self.connTable:size(1) do ninp[self.connTable[i][2]] = ninp[self.connTable[i][2]]+1 end
for k=1,self.connTable:size(1) do
stdv = 1/math.sqrt(self.kW*self.kH*ninp[self.connTable[k][2]])
if nn.oldSeed then
self.weight:select(1,k):apply(function() return torch.uniform(-stdv,stdv) end)
else
self.weight:select(1,k):uniform(-stdv,stdv)
end
end
for k=1,self.bias:size(1) do
stdv = 1/math.sqrt(self.kW*self.kH*ninp[k])
self.bias[k] = torch.uniform(-stdv,stdv)
end
end
end
function SpatialConvolutionMap:updateOutput(input)
input.nn.SpatialConvolutionMap_updateOutput(self, input)
return self.output
end
function SpatialConvolutionMap:updateGradInput(input, gradOutput)
input.nn.SpatialConvolutionMap_updateGradInput(self, input, gradOutput)
return self.gradInput
end
function SpatialConvolutionMap:accGradParameters(input, gradOutput, scale)
return input.nn.SpatialConvolutionMap_accGradParameters(self, input, gradOutput, scale)
end
function SpatialConvolutionMap:decayParameters(decay)
self.weight:add(-decay, self.weight)
self.bias:add(-decay, self.bias)
end
|
local CircularBuffer = require(script.Parent.Parent.Parent.CircularBuffer)
local Signal = require(script.Parent.Parent.Parent.Signal)
local MAX_DATASET_COUNT = tonumber(settings():GetFVariable("NewDevConsoleMaxGraphCount"))
local getClientReplicator = require(script.Parent.Parent.Parent.Util.getClientReplicator)
local DataStoresData = {}
DataStoresData.__index = DataStoresData
function DataStoresData.new()
local self = {}
setmetatable(self, DataStoresData)
self._dataStoresUpdated = Signal.new()
self._dataStoresData = {}
self._dataStoresDataCount = 0
self._lastUpdateTime = 0
self._isRunning = false
return self
end
function DataStoresData:Signal()
return self._dataStoresUpdated
end
function DataStoresData:getCurrentData()
return self._dataStoresData, self._dataStoresDataCount
end
function DataStoresData:updateValue(key, value)
if not self._dataStoresData[key] then
local newBuffer = CircularBuffer.new(MAX_DATASET_COUNT)
newBuffer:push_back({
value = value,
time = self._lastUpdateTime
})
self._dataStoresData[key] = {
max = value,
min = value,
dataSet = newBuffer,
}
else
local dataEntry = self._dataStoresData[key]
local currMax = dataEntry.max
local currMin = dataEntry.min
local update = {
value = value,
time = self._lastUpdateTime
}
local overwrittenEntry = self._dataStoresData[key].dataSet:push_back(update)
if overwrittenEntry then
local iter = self._dataStoresData[key].dataSet:iterator()
local dat = iter:next()
if currMax == overwrittenEntry.value then
currMax = currMin
while dat do
currMax = dat.value < currMax and currMax or dat.value
dat = iter:next()
end
end
if currMin == overwrittenEntry.value then
currMin = currMax
while dat do
currMin = currMin < dat.value and currMin or dat.value
dat = iter:next()
end
end
end
self._dataStoresData[key].max = currMax < value and value or currMax
self._dataStoresData[key].min = currMin < value and currMin or value
end
end
function DataStoresData:isRunning()
return self._isRunning
end
function DataStoresData:start()
local clientReplicator = getClientReplicator()
if clientReplicator and not self._statsListenerConnection then
self._statsListenerConnection = clientReplicator.StatsReceived:connect(function(stats)
local dataStoreBudget = stats.DataStoreBudget
self._lastUpdateTime = os.time()
if dataStoreBudget then
local count = 0
for k, v in pairs(dataStoreBudget) do
if type(v) == 'number' then
self:updateValue(k,v)
count = count + 1
end
end
self._dataStoresDataCount = count
self._dataStoresUpdated:Fire(self._dataStoresData, self._dataStoresDataCount)
end
end)
clientReplicator:RequestServerStats(true)
self._isRunning = true
end
end
function DataStoresData:stop()
-- listeners are responsible for disconnecting themselves
if self._statsListenerConnection then
self._statsListenerConnection:Disconnect()
self._statsListenerConnection = nil
end
self._isRunning = false
end
return DataStoresData |
require "Client.Scripts.Modulus.Entity.Const.__init"
require "Client.Scripts.Modulus.Entity.Data.__init"
require "Client.Scripts.Modulus.Entity.SkillEvent.__init"
require "Client.Scripts.Modulus.Entity.Role.__init"
require "Client.Scripts.Modulus.Entity.Mgr.EntityMgr"
require "Client.Scripts.Modulus.Entity.Mgr.SkillMgr"
require "Client.Scripts.Modulus.Entity.Control.__init" |
local ffi = require("ffi")
__VIR_LIBVIRT_H_INCLUDES__ = true;
local export = {}
-- Copy one dictionary into another
local function appendTable(dst, src)
if not src then
return dst;
end
for key, value in pairs(src) do
dst.key = value;
end
return dst;
end
-- Load all the definitions, while copying
-- dictionary values into export table
appendTable(export, require "libvirt-host");
appendTable(export, require "libvirt-domain");
appendTable(export, require "libvirt-domain-snapshot");
appendTable(export, require "libvirt-event");
appendTable(export, require "libvirt-interface");
appendTable(export, require "libvirt-network");
appendTable(export, require "libvirt-nodedev");
appendTable(export, require "libvirt-nwfilter");
appendTable(export, require "libvirt-secret");
appendTable(export, require "libvirt-storage");
appendTable(export, require "libvirt-stream");
appendTable(export, require "virterror");
if ffi.os == "Windows" then
export.Lib = ffi.load("libvirt-0.dll")
elseif ffi.os == "Linux" then
export.Lib = ffi.load("/usr/lib/libvirt.so")
elseif ffi.os == "OSX" then
export.Lib = ffi.load("libvirt");
end
if not export.Lib then
return nil, "could not load library, 'libvirt'"
end
local err = export.Lib.virInitialize();
if (err ~= 0) then
return nil, "could not initialize libvirt";
end
return export
|
local config = require("lvim-kbrd.config")
local utils = require("lvim-kbrd.utils")
local autocmd = require("lvim-kbrd.autocmd")
local M = {}
M.setup = function(user_config)
if user_config ~= nil then
utils.merge(config, user_config)
end
M.init()
end
M.init = function()
if config.active_plugin == 1 then
autocmd.enable()
end
end
M.toggle = function()
if config.active_plugin == 1 then
autocmd.disable()
config.active_plugin = 0
elseif config.active_plugin == 0 then
config.active_plugin = 1
autocmd.enable()
end
end
return M
|
-- Julia
vim.g.default_julia_version = "1.7"
vim.g.latex_to_unicode_tab = "on"
vim.g.latex_to_unicode_auto = false
vim.g.julia_indent_align_import = false
vim.g.julia_indent_align_brackets = false
vim.g.julia_indent_align_funcargs = false
WhichKey.register({
j = {
name = "Julia",
b = { ":call julia#toggle_function_blockassign()<CR>", "Toggle function block" },
},
}, { prefix = "<leader>", noremap = true })
|
local composer = require( "composer" )
local mui = require( "materialui.mui" )
local scene = composer.newScene()
-- -----------------------------------------------------------------------------------
-- Code outside of the scene event functions below will only be executed ONCE unless
-- the scene is removed entirely (not recycled) via "composer.removeScene()"
-- -----------------------------------------------------------------------------------
-- -----------------------------------------------------------------------------------
-- Scene event functions
-- -----------------------------------------------------------------------------------
-- create()
function scene:create( event )
local sceneGroup = self.view
display.setDefault("background", 0,0,0)
background = display.newRect( 0, 0, display.contentWidth, display.contentHeight)
background.anchorX = 0
background.anchorY = 0
background.x, background.y = 0, 0
background:setFillColor( 0,0.6,1,1 )
sceneGroup:insert( background )
mui.init()
local function handleButtonEvent( event )
composer.removeScene("menu")
composer.gotoScene("choose_level_type", { effect = "crossFade", time = 500 } )
return true
end
local function handleButtonEvent2( event )
composer.removeScene("menu")
composer.gotoScene("settings", { effect = "crossFade", time = 500 } )
return true
end
local function handleButtonEvent3( event )
composer.removeScene("menu")
composer.gotoScene("help", { effect = "crossFade", time = 500 } )
return true
end
textOptions = {
parent = sceneGroup,
y = mui.getScaleVal(140),
x = display.contentWidth / 2,
name = "title-main",
text = "My Title Here",
align = "center",
width = mui.contentWidth,
font = native.systemFontBold,
fontSize = mui.getScaleVal(65),
fillColor = { 1, 1, 1, 1 },
}
local title = mui.newText(textOptions)
local button1 = mui.newRoundedRectButton({
parent = sceneGroup,
name = "play",
text = "Play",
width = mui.getScaleVal(400),
height = mui.getScaleVal(100),
x = display.contentWidth/2,
y = mui.getScaleVal(320),
font = native.systemFont,
fillColor = { 1,1,1 },
textColor = { .4,.4,.4 },
callBack = handleButtonEvent,
})
local button2 = mui.newRoundedRectButton({
parent = sceneGroup,
name = "settings",
text = "Settings",
width = mui.getScaleVal(400),
height = mui.getScaleVal(100),
x = display.contentWidth/2,
y = mui.getScaleVal(500),
font = native.systemFont,
fillColor = { 1,1,1 },
textColor = { .4,.4,.4 },
callBack = handleButtonEvent2,
})
local button3 = mui.newRoundedRectButton({
parent = sceneGroup,
name = "Help",
text = "Help",
width = mui.getScaleVal(400),
height = mui.getScaleVal(100),
x = display.contentWidth/2,
y = mui.getScaleVal(680),
font = native.systemFont,
fillColor = { 1,1,1 },
textColor = { .4,.4,.4 },
callBack = handleButtonEvent3,
})
-- Code here runs when the scene is first created but has not yet appeared on screen
end
-- show()
function scene:show( event )
local sceneGroup = self.view
local phase = event.phase
local params = event.params
if ( phase == "will" ) then
-- Code here runs when the scene is still off screen (but is about to come on screen)
elseif ( phase == "did" ) then
-- Code here runs when the scene is entirely on screen
end
end
-- hide()
function scene:hide( event )
local sceneGroup = self.view
local phase = event.phase
if ( phase == "will" ) then
-- Code here runs when the scene is on screen (but is about to go off screen)
elseif ( phase == "did" ) then
-- Code here runs immediately after the scene goes entirely off screen
end
end
-- destroy()
function scene:destroy( event )
local sceneGroup = self.view
mui.destroy()
-- Code here runs prior to the removal of scene's view
end
-- -----------------------------------------------------------------------------------
-- Scene event function listeners
-- -----------------------------------------------------------------------------------
scene:addEventListener( "create", scene )
scene:addEventListener( "show", scene )
scene:addEventListener( "hide", scene )
scene:addEventListener( "destroy", scene )
-- -----------------------------------------------------------------------------------
return scene |
module(...,package.seeall)
--by nirenr
local function ps(str)
str = str:gsub("%b\"\"",""):gsub("%b\'\'","")
local _,f= str:gsub ('%f[%w]function%f[%W]',"")
local _,t= str:gsub ('%f[%w]then%f[%W]',"")
local _,i= str:gsub ('%f[%w]elseif%f[%W]',"")
local _,d= str:gsub ('%f[%w]do%f[%W]',"")
local _,e= str:gsub ('%f[%w]end%f[%W]',"")
local _,r= str:gsub ('%f[%w]repeat%f[%W]',"")
local _,u= str:gsub ('%f[%w]until%f[%W]',"")
local _,a= str:gsub ("{","")
local _,b= str:gsub ("}","")
return (f+t+d+r+a)*4-(i+e+u+b)*4
end
local function _format()
local p=0
return function(str)
str=str:gsub("[ \t]+$","")
str=string.format('%s%s',string.rep(' ',p),str)
p=p+ps(str)
return str
end
end
function format(Text)
local t=os.clock()
local Format=_format()
Text=Text:gsub('[ \t]*([^\r\n]+)',function(str)return Format(str)end)
print('操作完成,耗时:'..os.clock()-t)
return Text
end
function build(path)
if path then
local str,st=loadfile(path)
if st then
return nil,st
end
local path=path..'c'
local st,str=pcall(string.dump,str,true)
if st then
f=io.open(path,'wb')
f:write(str)
f:close()
return path
else
os.remove(path)
return nil,str
end
end
end
function build_aly(path2)
if path2 then
local f,st=io.open(path2)
if st then
return nil,st
end
local str=f:read("*a")
f:close()
str=string.format("local layout=%s\nreturn layout",str)
local path=path2..'c'
str,st=loadstring(str,path2:match("[^/]+/[^/]+$"),"bt")
if st then
return nil,st:gsub("%b[]",path2,1)
end
local st,str=pcall(string.dump,str,true)
if st then
f=io.open(path,'wb')
f:write(str)
f:close()
return path
else
os.remove(path)
return nil,str
end
end
end
|
--[[
Pixel Vision 8 - New Template Script
Copyright (C) 2017, Pixel Vision 8 (http://pixelvision8.com)
Created by Jesse Freeman (@jessefreeman)
This project was designed to display some basic instructions when you create
a new game. Simply delete the following code and implement your own Init(),
Update() and Draw() logic.
Learn more about making Pixel Vision 8 games at https://www.gitbook.com/@pixelvision8
]]--
string.lpad = function(str, len, char)
if char == nil then char = ' ' end
return string.rep(char, len - #str) .. str
end
table.indexOf = function( t, object )
if "table" == type( t ) then
for i = 1, #t do
if object == t[i] then
return i
end
end
return - 1
else
error("table.indexOf expects table for first argument, " .. type(t) .. " given")
end
end
function dump(o)
if type(o) == 'table' then
local s = '{ '
for k, v in pairs(o) do
if type(k) ~= 'number' then k = '"'..k..'"' end
s = s .. '['..k..'] = ' .. dump(v) .. ','
end
return s .. '} '
else
return tostring(o)
end
end
function AutoComplete(text, options)
local matches = {}
-- TODO should we always default to an option?
if(text == "") then
return matches
end
for k, v in pairs(options) do
if(string.find(v, text, 1, true) == 1) then
table.insert(matches, v)
end
end
return matches
end
function string.replaceTokens(text, data)
-- pass the text and data to the `colorizeText()` function and only save the returned text since coloring is ignored.
local text = colorizeText(text, 0, data)
-- Return the text
return text
end
TOTAL_COLORS = 15
function colorizeText(text, defaultColor, tokens)
-- local tokens = {}
local newText = ""
local colors = {}
local token = ""
local inToken = false
local inColor = false
local colorString = ""
local defaultColor = ((defaultColor or 15) * 2) + TOTAL_COLORS + 1
for i = 1, #text do
local char = string.sub(text, i, i)
-- Look to see if we are at the start of a token
if char == "{" then
inToken = true
-- Look to see if we are at the end of a token
elseif char == "}" then
if(tokens ~= nil) then
token = tokens[token] or token
elseif(colorString == "") then
-- This is a special case to take into account for a token in the text or just come characters wrapped in open and closed brakes
colorString = tostring(15)
token = "{" .. token .. "}"
end
-- Time to apply the color so convert the color string into a number
local color = ((tonumber(colorString) or 0) * 2) + TOTAL_COLORS + 1
-- Add the token to the text
newText = newText .. token
-- Add the color to the colors table for each character in the token
for j = 1, #token do
table.insert(colors, color)
end
-- Reset all of the flags since we are out of a token now
inToken = false
inColor = false
token = ""
colorString = ""
-- Look to see if we have a colon and are inside of a token
elseif char == ":" and inToken then
-- Flag that we are now in a color
inColor = true
elseif inColor then
-- Add the character to the color string
colorString = colorString .. char
else
-- Look to see if we are inside of a token
if inToken then
-- Add the character to the token
token = token .. char
else
-- Add the character to the newText
newText = newText .. char
-- Add the default color to the colors table
table.insert(colors, defaultColor)
end
end
end
return newText, colors
end |
--mobs_fallout v0.0.1
--maikerumine
--made for Extreme Survival game
--dofile(minetest.get_modpath("mobs_fallout").."/api.lua")
--CODING NOTES
--REF CODE FROM PMOBS by CProgrammerRU --https://github.com/CProgrammerRU/progress
--[[
-- right clicking with cooked meat will give npc more health
on_rightclick = function(self, clicker)
local item = clicker:get_wielded_item()
if item:get_name() == "mobs:meat" or item:get_name() == "farming:bread" then
local hp = self.object:get_hp()
if hp + 4 > self.hp_max then return end
if not minetest.setting_getbool("creative_mode") then
item:take_item()
clicker:set_wielded_item(item)
end
self.object:set_hp(hp+4)
-- right clicking with gold lump drops random item from mobs.npc_drops
elseif item:get_name() == "default:gold_lump" then
if not minetest.setting_getbool("creative_mode") then
item:take_item()
clicker:set_wielded_item(item)
end
local pos = self.object:getpos()
pos.y = pos.y + 0.5
minetest.add_item(pos, {name = mobs.npc_drops[math.random(1,#mobs.npc_drops)]})
else
if self.owner == "" then
self.owner = clicker:get_player_name()
else
local formspec = "size[8,4]"
formspec = formspec .. "textlist[2.85,0;2.1,0.5;dialog;What can I do for you?]"
formspec = formspec .. "button_exit[1,1;2,2;gfollow;follow]"
formspec = formspec .. "button_exit[5,1;2,2;gstand;stand]"
formspec = formspec .. "button_exit[0,2;4,4;gfandp;follow and protect]"
formspec = formspec .. "button_exit[4,2;4,4;gsandp;stand and protect]"
formspec = formspec .. "button_exit[1,2;2,2;ggohome; go home]"
formspec = formspec .. "button_exit[5,2;2,2;gsethome; sethome]"
minetest.show_formspec(clicker:get_player_name(), "order", formspec)
minetest.register_on_player_receive_fields(function(clicker, formname, fields)
if fields.gfollow then
self.order = "follow"
self.attacks_monsters = false
end
if fields.gstand then
self.order = "stand"
self.attacks_monsters = false
end
if fields.gfandp then
self.order = "follow"
self.attacks_monsters = true
end
if fields.gsandp then
self.order = "stand"
self.attacks_monsters = true
end
if fields.gsethome then
self.floats = self.object:getpos()
end
if fields.ggohome then
if self.floats then
self.order = "stand"
self.object:setpos(self.floats)
end
end
end)
end
end
end,
})
]]
|
--- === cp.apple.finalcutpro.timeline.CaptionsSubrole ==
---
--- *Extends [Role](cp.apple.finalcutpro.timeline.Role.md)*
---
--- A [Role](cp.apple.finalcutpro.timeline.Role.md) representing Captions.
local axutils = require "cp.ui.axutils"
local CheckBox = require "cp.ui.CheckBox"
local StaticText = require "cp.ui.StaticText"
local Role = require "cp.apple.finalcutpro.timeline.Role"
local CaptionsRole = require "cp.apple.finalcutpro.timeline.CaptionsRole"
local CaptionsSubrole = Role:subclass("cp.apple.finalcutpro.timeline.CaptionsSubrole")
--- cp.apple.finalcutpro.timeline.CaptionsSubrole.matches(element) -> boolean
--- Function
--- Checks if the element is a "Captions" Subrole.
---
--- Parameters:
--- * element - An element to check
---
--- Returns:
--- * A boolean
function CaptionsSubrole.static.matches(element)
return Role.matches(element)
and CaptionsRole.matches(element:attributeValue("AXDisclosedByRow"))
end
--- cp.apple.finalcutpro.timeline.CaptionsSubrole(parent, uiFinder)
--- Constructor
--- Creates a new instance with the specified `parent` and `uiFinder`.
---
--- Parameters:
--- * parent - the parent `Element`.
--- * uiFinder - a `function` or `cp.prop` containing the `axuielement`
---
--- Returns:
--- * The new `Row`.
function CaptionsSubrole:initialize(parent, uiFinder)
Role.initialize(self, parent, uiFinder, Role.TYPE.CAPTION)
end
--- cp.apple.finalcutpro.timeline.CaptionsSubrole.format <cp.ui.StaticText>
--- Field
--- A [StaticText](cp.ui.StaticText.md) which represents the subtitle format (e.g. "ITT", "SRT").
function CaptionsSubrole.lazy.value:format()
return StaticText(self, self.cellUI:mutate(function(original)
return axutils.childFromLeft(original(), 1, StaticText.matches)
end))
end
--- cp.apple.finalcutpro.timeline.CaptionsSubrole.visibleInTimeline <cp.ui.CheckBox>
--- Field
--- A [CheckBox](cp.ui.CheckBox.md) that indicates if the subtitle track is visible in the Viewer.
function CaptionsSubrole.lazy.value:visibleInViewer()
return CheckBox(self, self.cellUI:mutate(function(original)
return axutils.childFromLeft(original(), 1, CheckBox.matches)
end))
end
return CaptionsSubrole |
--
-- Small utility module for dealing with battery inventories.
--
local invbat = {}
function invbat.calc_capacity(inv, list_name)
local size = inv:get_size(list_name)
local capacity = 0
for i = 1,size do
local stack = inv:get_stack(list_name, i)
if not stack:is_empty() then
local en = stack:get_definition().energy
if en then
capacity = capacity + en.get_capacity(stack)
end
end
end
return capacity
end
function invbat.calc_stored_energy(inv, list_name)
local size = inv:get_size(list_name)
local stored = 0
for i = 1,size do
local stack = inv:get_stack(list_name, i)
if not stack:is_empty() then
local en = stack:get_definition().energy
if en then
stored = stored + en.get_stored_energy(stack)
end
end
end
return stored
end
function invbat.receive_energy(inv, list_name, amount)
local left = amount
local new_energy = 0
local size = inv:get_size(list_name)
for i = 1,size do
local stack = inv:get_stack(list_name, i)
if not stack:is_empty() then
local en = stack:get_definition().energy
if en then
if left > 0 then
local used = en.receive_energy(stack, left)
left = left - used
inv:set_stack(list_name, i, stack)
end
new_energy = new_energy + en.get_stored_energy(stack)
end
end
end
return new_energy, amount - left
end
function invbat.consume_energy(inv, list_name, amount)
local left = amount
local new_energy = 0
local size = inv:get_size(list_name)
for i = 1,size do
local stack = inv:get_stack(list_name, i)
local en = stack:get_definition().energy
if en then
if left > 0 then
local consumed = en.consume_energy(stack, left)
left = left - consumed
inv:set_stack("batteries", i, stack)
end
new_energy = new_energy + en.get_stored_energy(stack)
end
end
return new_energy, amount - left
end
yatm_energy_storage.inventory_batteries = invbat
|
require('nn')
require('nngraph')
require('loadcaffe')
require('xlua')
require('image')
require('optim')
require('cunn')
require('cudnn')
require('./lib/tvloss')
require('./lib/contentloss')
require('./lib/gramloss')
require('./lib/mrfloss')
require('./lib/masked_gramloss')
require('./lib/amplayer')
require('./lib/randlayer')
local cleanupModel = require('./lib/cleanup_model')
local caffeImage = require('./lib/caffe_image')
local g = {}
g.styleImage = './images/picasso.png'
g.trainImages_Path = './scene/'
g.trainImages_Number = 16657
-----------------------------------------------------------------------------------------
-- helper functions
string.startsWith = function(self, str)
return self:find('^' .. str) ~= nil
end
function loadVGG()
local proto = './cnn/vgg19/VGG_ILSVRC_19_layers_deploy.prototxt'
local caffeModel = './cnn/vgg19/VGG_ILSVRC_19_layers.caffemodel'
local fullModel = loadcaffe.load(proto, caffeModel, 'nn')
local cnn = nn.Sequential()
for i = 1, #fullModel do
local name = fullModel:get(i).name
if ( name:startsWith('relu') or name:startsWith('conv') or name:startsWith('pool') ) then
cnn:add( fullModel:get(i) )
else
break
end
end
fullModel = nil
collectgarbage()
return cnn
end
function loadTrainData()
local randSeq = torch.randperm(g.trainImages_Number)
local trainSplit = math.floor(g.trainImages_Number * 0.85)
g.trainSet = {}
g.trainSet.data = {}
g.trainSet.index = 1
for i = 1, trainSplit do
g.trainSet.data[i] = g.trainImages_Path .. '/' .. randSeq[i] .. '.png'
end
g.testSet = {}
g.testSet.data = {}
g.testSet.index = 1
for i = trainSplit + 1, g.trainImages_Number do
g.testSet.data[i] = g.trainImages_Path .. '/' .. randSeq[i] .. '.png'
end
end
function loadBatch(set, batch_size)
local batch = {}
batch.x = torch.Tensor(batch_size, 3, 256, 256)
for i = 1, batch_size do
local sampleIndex = i + set.index
sampleIndex = sampleIndex % #set.data + 1
local rgb = image.loadPNG( set.data[sampleIndex], 3)
batch.x[i]:copy( caffeImage.img2caffe(rgb) )
end
set.index = (set.index + batch_size) % #set.data + 1
return batch
end
-----------------------------------------------------------------------------------------
-- worker functions
function buildLossNet ()
local gramLoss = {'relu1_2', 'relu2_2', 'relu3_2', 'relu4_1'}
local contentLoss = {'relu4_2'}
local styleCaffeImage = caffeImage.img2caffe( image.loadPNG(g.styleImage, 3) )
local modifier = {}
local cindex = -1
local net = nn.Sequential()
net:add(nn.TVLoss(0.001))
local gram_index = 1
local content_index = 1
for i = 1, #g.vgg do
if ( gram_index > #gramLoss and content_index > #contentLoss) then
break
end
local name = g.vgg:get(i).name
net:add(g.vgg:get(i))
if ( name == gramLoss[ gram_index ] ) then
local target = net:forward( styleCaffeImage )
local layer = nn.GramLoss(0.01, target, false)
net:add(layer)
table.insert(modifier, layer)
gram_index = gram_index + 1
end
if ( name == contentLoss[content_index] ) then
local layer = nn.ContentLoss(1.0, nil, nil)
net:add(layer)
table.insert(modifier, layer)
cindex = #modifier
content_index = content_index + 1
end
end
local lossNet = {}
lossNet.net = net
lossNet.modifier = modifier
lossNet.cindex = cindex
return lossNet
end
function buildStyledNet()
local model = nn.Sequential()
model:add(cudnn.SpatialConvolution(3, 32, 3, 3, 1, 1, 1, 1))
model:add(nn.SpatialBatchNormalization(32))
model:add(nn.LeakyReLU(0.1))
model:add(cudnn.SpatialConvolution(32, 32, 3, 3, 1, 1, 1, 1))
model:add(nn.SpatialBatchNormalization(32))
model:add(nn.LeakyReLU(0.1))
model:add(cudnn.SpatialConvolution(32, 64, 3, 3, 1, 1, 1, 1))
model:add(nn.SpatialBatchNormalization(64))
model:add(nn.LeakyReLU(0.1))
model:add(cudnn.SpatialConvolution(64, 128, 3, 3, 1, 1, 1, 1))
model:add(nn.SpatialBatchNormalization(128))
model:add(nn.LeakyReLU(0.1))
model:add(cudnn.SpatialConvolution(128, 128, 3, 3, 1, 1, 1, 1))
model:add(nn.SpatialBatchNormalization(128))
model:add(nn.LeakyReLU(0.1))
model:add(cudnn.SpatialConvolution(128, 3, 3, 3, 1, 1, 1, 1))
model:add(nn.Tanh())
model:add(nn.MulConstant(128))
return model
end
function doTrain()
g.lossNet.net:cuda()
g.styledNet:cuda()
g.zeroLoss = g.zeroLoss:cuda()
g.styledNet:training()
g.lossNet.net:evaluate()
local batchSize = 4
local oneEpoch = math.floor( #g.trainSet.data / batchSize )
g.trainSet.index = 1
local batch = nil
local dyhat = torch.zeros(batchSize, 3, 256, 256):cuda()
local parameters,gradParameters = g.styledNet:getParameters()
local feval = function(x)
-- get new parameters
if x ~= parameters then
parameters:copy(x)
end
-- reset gradients
gradParameters:zero()
local loss = 0
local yhat = g.styledNet:forward( batch.x )
for i = 1, batchSize do
g.lossNet.net:forward( batch.x[i] )
local contentTarget = g.lossNet.modifier[g.lossNet.cindex].output
g.lossNet.modifier[g.lossNet.cindex]:setTarget(contentTarget)
g.lossNet.net:forward(yhat[i])
local dy = g.lossNet.net:backward(yhat[i], g.zeroLoss)
dyhat[i]:copy(dy)
for _, mod in ipairs(g.lossNet.modifier) do
loss = loss + mod.loss
end
end
g.styledNet:backward(batch.x, dyhat)
return loss/batchSize, gradParameters
end
local minValue = -1
for j = 1, oneEpoch do
batch = loadBatch(g.trainSet, batchSize)
batch.x = batch.x:cuda()
local _, err = optim.adam(feval, parameters, g.optimState)
print(">>>>>>>>> err = " .. err[1]);
if ( j % 100 == 0) then
torch.save('./model/style_' .. err[1] .. '.t7', g.styledNet)
end
collectgarbage();
end
end
function doTest()
end
function doForward()
local net = torch.load( arg[1] )
local img = image.loadPNG( arg[2] , 3)
local img = caffeImage.img2caffe(img)
local x = torch.Tensor(1, img:size(1), img:size(2), img:size(3))
x[1]:copy(img)
x = x:cuda()
local outImg = net:forward(x)
outImg = outImg:float()
outImg = caffeImage.caffe2img(outImg[1])
image.savePNG('./output.png', outImg)
end
-----------------------------------------------------------------------------------------
function main()
torch.setdefaulttensortype('torch.FloatTensor')
torch.manualSeed(1979)
if ( #arg == 2) then
doForward()
return
end
-- build net
g.vgg = loadVGG()
g.lossNet = buildLossNet()
local tempImage = torch.rand(3, 256, 256)
local tempOutput = g.lossNet.net:forward(tempImage)
g.zeroLoss = torch.zeros( tempOutput:size())
g.styledNet = buildStyledNet()
g.optimState = {
learningRate = 0.0005,
}
-- load data
loadTrainData()
-- trainging()
for i = 1, 4 do
doTrain()
doTest()
end
end
main()
|
#!/usr/bin/env tarantool
local test = require("sqltester")
test:plan(109)
--!./tcltestrunner.lua
-- 2005 June 25
--
-- The author disclaims copyright to this source code. In place of
-- a legal notice, here is a blessing:
--
-- May you do good and not evil.
-- May you find forgiveness for yourself and forgive others.
-- May you share freely, never taking more than you give.
--
-------------------------------------------------------------------------
-- This file implements regression tests for sql library. The
-- focus of this file is testing the CAST operator.
--
-- $Id: cast.test,v 1.10 2008/11/06 15:33:04 drh Exp $
-- ["set","testdir",[["file","dirname",["argv0"]]]]
-- ["source",[["testdir"],"\/tester.tcl"]]
-- Only run these tests if the build includes the CAST operator
-- Tests for the CAST( AS SCALAR), CAST( AS text) and CAST( AS numeric) built-ins
--
test:do_execsql_test(
"cast-1.1",
[[
SELECT x'616263'
]], {
-- <cast-1.1>
"abc"
-- </cast-1.1>
})
test:do_execsql_test(
"cast-1.2",
[[
SELECT typeof(x'616263')
]], {
-- <cast-1.2>
"varbinary"
-- </cast-1.2>
})
test:do_execsql_test(
"cast-1.3",
[[
SELECT CAST(x'616263' AS text)
]], {
-- <cast-1.3>
"abc"
-- </cast-1.3>
})
test:do_execsql_test(
"cast-1.4",
[[
SELECT typeof(CAST(x'616263' AS text))
]], {
-- <cast-1.4>
"string"
-- </cast-1.4>
})
test:do_catchsql_test(
"cast-1.5",
[[
SELECT CAST(x'616263' AS NUMBER)
]], {
-- <cast-1.5>
1, "Type mismatch: can not convert varbinary(x'616263') to number"
-- </cast-1.5>
})
test:do_execsql_test(
"cast-1.7",
[[
SELECT CAST(x'616263' AS SCALAR)
]], {
-- <cast-1.7>
"abc"
-- </cast-1.7>
})
test:do_execsql_test(
"cast-1.8",
[[
SELECT typeof(CAST(x'616263' AS SCALAR))
]], {
-- <cast-1.8>
"scalar"
-- </cast-1.8>
})
test:do_catchsql_test(
"cast-1.9",
[[
SELECT CAST(x'616263' AS integer)
]], {
-- <cast-1.9>
1, "Type mismatch: can not convert varbinary(x'616263') to integer"
-- </cast-1.9>
})
test:do_execsql_test(
"cast-1.11",
[[
SELECT null
]], {
-- <cast-1.11>
""
-- </cast-1.11>
})
test:do_execsql_test(
"cast-1.12",
[[
SELECT typeof(NULL)
]], {
-- <cast-1.12>
"NULL"
-- </cast-1.12>
})
test:do_execsql_test(
"cast-1.13",
[[
SELECT CAST(NULL AS text)
]], {
-- <cast-1.13>
""
-- </cast-1.13>
})
test:do_execsql_test(
"cast-1.14",
[[
SELECT typeof(CAST(NULL AS text))
]], {
-- <cast-1.14>
"NULL"
-- </cast-1.14>
})
test:do_execsql_test(
"cast-1.15",
[[
SELECT CAST(NULL AS NUMBER)
]], {
-- <cast-1.15>
""
-- </cast-1.15>
})
test:do_execsql_test(
"cast-1.16",
[[
SELECT typeof(CAST(NULL AS NUMBER))
]], {
-- <cast-1.16>
"NULL"
-- </cast-1.16>
})
test:do_execsql_test(
"cast-1.17",
[[
SELECT CAST(NULL AS SCALAR)
]], {
-- <cast-1.17>
""
-- </cast-1.17>
})
test:do_execsql_test(
"cast-1.18",
[[
SELECT typeof(CAST(NULL AS SCALAR))
]], {
-- <cast-1.18>
"NULL"
-- </cast-1.18>
})
test:do_execsql_test(
"cast-1.19",
[[
SELECT CAST(NULL AS integer)
]], {
-- <cast-1.19>
""
-- </cast-1.19>
})
test:do_execsql_test(
"cast-1.20",
[[
SELECT typeof(CAST(NULL AS integer))
]], {
-- <cast-1.20>
"NULL"
-- </cast-1.20>
})
test:do_execsql_test(
"cast-1.21",
[[
SELECT 123
]], {
-- <cast-1.21>
123
-- </cast-1.21>
})
test:do_execsql_test(
"cast-1.22",
[[
SELECT typeof(123)
]], {
-- <cast-1.22>
"integer"
-- </cast-1.22>
})
test:do_execsql_test(
"cast-1.23",
[[
SELECT CAST(123 AS text)
]], {
-- <cast-1.23>
"123"
-- </cast-1.23>
})
test:do_execsql_test(
"cast-1.24",
[[
SELECT typeof(CAST(123 AS text))
]], {
-- <cast-1.24>
"string"
-- </cast-1.24>
})
test:do_execsql_test(
"cast-1.25",
[[
SELECT CAST(123 AS NUMBER)
]], {
-- <cast-1.25>
123
-- </cast-1.25>
})
test:do_execsql_test(
"cast-1.26",
[[
SELECT typeof(CAST(123 AS DOUBLE))
]], {
-- <cast-1.26>
"double"
-- </cast-1.26>
})
test:do_execsql_test(
"cast-1.27",
[[
SELECT CAST(123 AS SCALAR)
]], {
-- <cast-1.27>
123
-- </cast-1.27>
})
test:do_execsql_test(
"cast-1.28",
[[
SELECT typeof(CAST(123 AS SCALAR))
]], {
-- <cast-1.28>
"scalar"
-- </cast-1.28>
})
test:do_execsql_test(
"cast-1.29",
[[
SELECT CAST(123 AS integer)
]], {
-- <cast-1.29>
123
-- </cast-1.29>
})
test:do_execsql_test(
"cast-1.30",
[[
SELECT typeof(CAST(123 AS integer))
]], {
-- <cast-1.30>
"integer"
-- </cast-1.30>
})
test:do_execsql_test(
"cast-1.31",
[[
SELECT 123.456
]], {
-- <cast-1.31>
123.456
-- </cast-1.31>
})
test:do_execsql_test(
"cast-1.32",
[[
SELECT typeof(123.456)
]], {
-- <cast-1.32>
"double"
-- </cast-1.32>
})
test:do_execsql_test(
"cast-1.33",
[[
SELECT CAST(123.456 AS text)
]], {
-- <cast-1.33>
"123.456"
-- </cast-1.33>
})
test:do_execsql_test(
"cast-1.34",
[[
SELECT typeof(CAST(123.456 AS text))
]], {
-- <cast-1.34>
"string"
-- </cast-1.34>
})
test:do_execsql_test(
"cast-1.35",
[[
SELECT CAST(123.456 AS NUMBER)
]], {
-- <cast-1.35>
123.456
-- </cast-1.35>
})
test:do_execsql_test(
"cast-1.36",
[[
SELECT typeof(CAST(123.456 AS DOUBLE))
]], {
-- <cast-1.36>
"double"
-- </cast-1.36>
})
test:do_execsql_test(
"cast-1.37",
[[
SELECT CAST(123.456 AS SCALAR)
]], {
-- <cast-1.37>
123.456
-- </cast-1.37>
})
test:do_execsql_test(
"cast-1.38",
[[
SELECT typeof(CAST(123.456 AS SCALAR))
]], {
-- <cast-1.38>
"scalar"
-- </cast-1.38>
})
test:do_execsql_test(
"cast-1.39",
[[
SELECT CAST(123.456 AS integer)
]], {
-- <cast-1.39>
123
-- </cast-1.39>
})
test:do_execsql_test(
"cast-1.38",
[[
SELECT typeof(CAST(123.456 AS integer))
]], {
-- <cast-1.38>
"integer"
-- </cast-1.38>
})
test:do_execsql_test(
"cast-1.41",
[[
SELECT '123abc'
]], {
-- <cast-1.41>
"123abc"
-- </cast-1.41>
})
test:do_execsql_test(
"cast-1.42",
[[
SELECT typeof('123abc')
]], {
-- <cast-1.42>
"string"
-- </cast-1.42>
})
test:do_execsql_test(
"cast-1.43",
[[
SELECT CAST('123abc' AS text)
]], {
-- <cast-1.43>
"123abc"
-- </cast-1.43>
})
test:do_execsql_test(
"cast-1.44",
[[
SELECT typeof(CAST('123abc' AS text))
]], {
-- <cast-1.44>
"string"
-- </cast-1.44>
})
test:do_catchsql_test(
"cast-1.45",
[[
SELECT CAST('123abc' AS NUMBER)
]], {
-- <cast-1.45>
1, "Type mismatch: can not convert string('123abc') to number"
-- </cast-1.45>
})
test:do_execsql_test(
"cast-1.48",
[[
SELECT typeof(CAST('123abc' AS SCALAR))
]], {
-- <cast-1.48>
"scalar"
-- </cast-1.48>
})
test:do_catchsql_test(
"cast-1.49",
[[
SELECT CAST('123abc' AS integer)
]], {
-- <cast-1.49>
1, "Type mismatch: can not convert string('123abc') to integer"
-- </cast-1.49>
})
test:do_catchsql_test(
"cast-1.51",
[[
SELECT CAST('123.5abc' AS NUMBER)
]], {
-- <cast-1.51>
1, "Type mismatch: can not convert string('123.5abc') to number"
-- </cast-1.51>
})
test:do_catchsql_test(
"cast-1.53",
[[
SELECT CAST('123.5abc' AS integer)
]], {
-- <cast-1.53>
1, "Type mismatch: can not convert string('123.5abc') to integer"
-- </cast-1.53>
})
test:do_execsql_test(
"case-1.60",
[[
SELECT CAST(null AS NUMBER)
]], {
-- <case-1.60>
""
-- </case-1.60>
})
test:do_execsql_test(
"case-1.61",
[[
SELECT typeof(CAST(null AS NUMBER))
]], {
-- <case-1.61>
"NULL"
-- </case-1.61>
})
test:do_execsql_test(
"case-1.62",
[[
SELECT CAST(1 AS NUMBER)
]], {
-- <case-1.62>
1.0
-- </case-1.62>
})
test:do_execsql_test(
"case-1.63",
[[
SELECT typeof(CAST(1 AS NUMBER))
]], {
-- <case-1.63>
"number"
-- </case-1.63>
})
test:do_execsql_test(
"case-1.64",
[[
SELECT CAST('1' AS NUMBER)
]], {
-- <case-1.64>
1.0
-- </case-1.64>
})
test:do_execsql_test(
"case-1.65",
[[
SELECT typeof(CAST('1' AS NUMBER))
]], {
-- <case-1.65>
"number"
-- </case-1.65>
})
test:do_catchsql_test(
"case-1.66",
[[
SELECT CAST('abc' AS NUMBER)
]], {
-- <case-1.66>
1, "Type mismatch: can not convert string('abc') to number"
-- </case-1.66>
})
test:do_catchsql_test(
"case-1.68",
[[
SELECT CAST(x'31' AS NUMBER)
]], {
-- <case-1.68>
1, "Type mismatch: can not convert varbinary(x'31') to number"
-- </case-1.68>
})
test:do_catchsql_test(
"case-1.69",
[[
SELECT typeof(CAST(x'31' AS NUMBER))
]], {
-- <case-1.69>
1, "Type mismatch: can not convert varbinary(x'31') to number"
-- </case-1.69>
})
-- Ticket #1662. Ignore leading spaces in numbers when casting.
--
test:do_execsql_test(
"cast-2.1",
[[
SELECT CAST(' 123' AS integer)
]], {
-- <cast-2.1>
123
-- </cast-2.1>
})
test:do_execsql_test(
"cast-2.2",
[[
SELECT CAST(' -123.456' AS NUMBER)
]], {
-- <cast-2.2>
-123.456
-- </cast-2.2>
})
-- ticket #2364. Use full percision integers if possible when casting
-- to numeric. Do not fallback to real (and the corresponding 48-bit
-- mantissa) unless absolutely necessary.
--
test:do_execsql_test(
"cast-3.1",
[[
SELECT CAST(9223372036854774800 AS integer)
]], {
-- <cast-3.1>
9223372036854774800LL
-- </cast-3.1>
})
test:do_execsql_test(
"cast-3.2",
[[
SELECT CAST(9223372036854774800 AS NUMBER)
]], {
-- <cast-3.2>
9223372036854774800LL
-- </cast-3.2>
})
test:do_execsql_test(
"cast-3.4",
[[
SELECT CAST(CAST(9223372036854774800 AS NUMBER) AS integer)
]], {
-- <cast-3.4>
9223372036854774800LL
-- </cast-3.4>
})
test:do_execsql_test(
"cast-3.6",
[[
SELECT CAST(-9223372036854774800 AS NUMBER)
]], {
-- <cast-3.6>
-9223372036854774800LL
-- </cast-3.6>
})
test:do_execsql_test(
"cast-3.8",
[[
SELECT CAST(CAST(-9223372036854774800 AS NUMBER) AS integer)
]], {
-- <cast-3.8>
-9223372036854774800LL
-- </cast-3.8>
})
test:do_execsql_test(
"cast-3.11",
[[
SELECT CAST('9223372036854774800' AS integer)
]], {
-- <cast-3.11>
9223372036854774800LL
-- </cast-3.11>
})
test:do_execsql_test(
"cast-3.12",
[[
SELECT CAST('9223372036854774800.' AS NUMBER)
]], {
-- <cast-3.12>
9223372036854774784
-- </cast-3.12>
})
test:do_execsql_test(
"cast-3.14",
[[
SELECT CAST(CAST('9223372036854774800.' AS NUMBER) AS integer)
]], {
-- <cast-3.14>
9223372036854774784LL
-- </cast-3.14>
})
test:do_execsql_test(
"cast-3.15",
[[
SELECT CAST('-9223372036854774800' AS integer)
]], {
-- <cast-3.15>
-9223372036854774800LL
-- </cast-3.15>
})
test:do_execsql_test(
"cast-3.16",
[[
SELECT CAST('-9223372036854774800.' AS NUMBER)
]], {
-- <cast-3.16>
-9223372036854774784
-- </cast-3.16>
})
test:do_execsql_test(
"cast-3.18",
[[
SELECT CAST(CAST('-9223372036854774800.' AS NUMBER) AS integer)
]], {
-- <cast-3.18>
-9223372036854774784LL
-- </cast-3.18>
})
if true then --test:execsql("PRAGMA encoding")[1][1]=="UTF-8" then
test:do_catchsql_test(
"cast-3.21",
[[
SELECT CAST(x'39323233333732303336383534373734383030' AS integer)
]], {
-- <cast-3.21>
1, "Type mismatch: can not convert "..
"varbinary(x'39323233333732303336383534373734383030') to integer"
-- </cast-3.21>
})
test:do_catchsql_test(
"cast-3.22",
[[
SELECT CAST(x'393232333337323033363835343737343830302E' AS NUMBER)
]], {
-- <cast-3.22>
1, "Type mismatch: can not convert "..
"varbinary(x'393232333337323033363835343737343830302E') "..
"to number"
-- </cast-3.22>
})
test:do_catchsql_test(
"cast-3.24",
[[
SELECT CAST(CAST(x'39323233333732303336383534373734383030' AS NUMBER)
AS integer)
]], {
-- <cast-3.24>
1, "Type mismatch: can not convert "..
"varbinary(x'39323233333732303336383534373734383030') to number"
-- </cast-3.24>
})
end
test:do_catchsql_test(
"case-3.25",
[[
SELECT CAST(x'31383434363734343037333730393535313631352E' AS NUMBER);
]], {
1, "Type mismatch: can not convert "..
"varbinary(x'31383434363734343037333730393535313631352E') to number"
})
test:do_catchsql_test(
"case-3.26",
[[
SELECT CAST(x'3138343436373434303733373039353531363135' AS INT);
]], {
-- <cast-3.21>
1, "Type mismatch: can not convert "..
"varbinary(x'3138343436373434303733373039353531363135') to integer"
-- </cast-3.21>
})
test:do_execsql_test(
"case-3.31",
[[
SELECT CAST(NULL AS NUMBER)
]], {
-- <case-3.31>
""
-- </case-3.31>
})
-- MUST_WORK_TEST prepared statements
-- Test to see if it is possible to trick sql into reading past
-- the end of a blob when converting it to a number.
if 0 > 0 then
-- Legacy from the original code. Must be replaced with analogue
-- functions from box.
local sql_prepare = nil
local sql_bind_blob = nil
local sql_step = nil
local sql_column_int = nil
local STMT
test:do_test(
"cast-3.32.1",
function()
local blob = 1234567890
STMT = sql_prepare("SELECT CAST(? AS NUMBER)", -1, "TAIL")
sql_bind_blob("-static", STMT, 1, blob, 5)
return sql_step(STMT)
end, {
-- <cast-3.32.1>
"sql_ROW"
-- </cast-3.32.1>
})
test:do_test(
"cast-3.32.2",
function()
return sql_column_int(STMT, 0)
end, {
-- <cast-3.32.2>
12345
-- </cast-3.32.2>
})
test:do_sql_finalize_test(
"cast-3.32.3",
STMT, {
-- <cast-3.32.3>
"sql_OK"
-- </cast-3.32.3>
})
end
test:do_test(
"cast-4.1",
function()
return test:catchsql [[
CREATE TABLE t1(a TEXT primary key);
INSERT INTO t1 VALUES('abc');
SELECT a, CAST(a AS integer) FROM t1;
]]
end, {
-- <cast-4.1>
1, "Type mismatch: can not convert string('abc') to integer"
-- </cast-4.1>
})
test:do_test(
"cast-4.2",
function()
return test:catchsql [[
SELECT CAST(a AS integer), a FROM t1;
]]
end, {
-- <cast-4.2>
1, "Type mismatch: can not convert string('abc') to integer"
-- </cast-4.2>
})
test:do_test(
"cast-4.4",
function()
return test:catchsql [[
SELECT a, CAST(a AS NUMBER), a FROM t1;
]]
end, {
-- <cast-4.4>
1, "Type mismatch: can not convert string('abc') to number"
-- </cast-4.4>
})
-- gh-4470: Make explicit and implicit casts work according to our rules.
-- Make sure that explicit cast from BOOLEAN to numeric types throws an error.
test:do_catchsql_test(
"cast-6.1.1",
[[
SELECT CAST(TRUE AS UNSIGNED);
]], {
1, "Type mismatch: can not convert boolean(TRUE) to unsigned"
})
test:do_catchsql_test(
"cast-6.1.2",
[[
SELECT CAST(FALSE AS UNSIGNED);
]], {
1, "Type mismatch: can not convert boolean(FALSE) to unsigned"
})
test:do_catchsql_test(
"cast-6.1.3",
[[
SELECT CAST(TRUE AS INTEGER);
]], {
1, "Type mismatch: can not convert boolean(TRUE) to integer"
})
test:do_catchsql_test(
"cast-6.1.4",
[[
SELECT CAST(FALSE AS INTEGER);
]], {
1, "Type mismatch: can not convert boolean(FALSE) to integer"
})
test:do_catchsql_test(
"cast-6.1.5",
[[
SELECT CAST(TRUE AS DOUBLE);
]], {
1, "Type mismatch: can not convert boolean(TRUE) to double"
})
test:do_catchsql_test(
"cast-6.1.6",
[[
SELECT CAST(FALSE AS DOUBLE);
]], {
1, "Type mismatch: can not convert boolean(FALSE) to double"
})
test:do_catchsql_test(
"cast-6.1.7",
[[
SELECT CAST(TRUE AS NUMBER);
]], {
1, "Type mismatch: can not convert boolean(TRUE) to number"
})
test:do_catchsql_test(
"cast-6.1.8",
[[
SELECT CAST(FALSE AS NUMBER);
]], {
1, "Type mismatch: can not convert boolean(FALSE) to number"
})
-- Make sure that explicit cast numeric value to BOOLEAN throws an error.
test:do_catchsql_test(
"cast-6.2.1",
[[
SELECT CAST(0 AS BOOLEAN);
]], {
1, "Type mismatch: can not convert integer(0) to boolean"
})
test:do_catchsql_test(
"cast-6.2.2",
[[
SELECT CAST(-1 AS BOOLEAN);
]], {
1, "Type mismatch: can not convert integer(-1) to boolean"
})
test:do_catchsql_test(
"cast-6.2.3",
[[
SELECT CAST(1.5 AS BOOLEAN);
]], {
1, "Type mismatch: can not convert double(1.5) to boolean"
})
test:do_catchsql_test(
"cast-6.2.4",
[[
SELECT CAST(CAST(1 AS NUMBER) AS BOOLEAN);
]], {
1, "Type mismatch: can not convert number(1) to boolean"
})
-- Make sure that explicit cast from VARBINARY to numeric types throws an error.
test:do_catchsql_test(
"cast-7.1.1",
[[
SELECT CAST(x'31' AS UNSIGNED);
]], {
1, "Type mismatch: can not convert varbinary(x'31') to unsigned"
})
test:do_catchsql_test(
"cast-7.1.2",
[[
SELECT CAST(x'31' AS INTEGER);
]], {
1, "Type mismatch: can not convert varbinary(x'31') to integer"
})
test:do_catchsql_test(
"cast-7.1.3",
[[
SELECT CAST(x'31' AS DOUBLE);
]], {
1, "Type mismatch: can not convert varbinary(x'31') to double"
})
test:do_catchsql_test(
"cast-7.1.4",
[[
SELECT CAST(x'31' AS NUMBER);
]], {
1, "Type mismatch: can not convert varbinary(x'31') to number"
})
-- Make sure that not NULL-terminated can be cast to BOOLEAN.
test:do_execsql_test(
"cast-8",
[[
SELECT CAST(substr('true ', 0, 6) AS BOOLEAN);
]], {
true
})
-- Make sure that implicit conversion of numeric values is precise.
test:execsql([[
CREATE TABLE t2 (i INTEGER PRIMARY KEY AUTOINCREMENT, a INTEGER, b DOUBLE);
CREATE TABLE t3 (i INTEGER PRIMARY KEY AUTOINCREMENT, s STRING);
CREATE TABLE t4 (i INTEGER PRIMARY KEY AUTOINCREMENT, v VARBINARY);
CREATE TABLE t5 (i INTEGER PRIMARY KEY AUTOINCREMENT, u UUID);
]])
test:do_execsql_test(
"cast-9.1.1",
[[
INSERT INTO t2(a) VALUES(1.0e0);
SELECT a FROM t2 WHERE i = 1;
]], {
1
})
test:do_catchsql_test(
"cast-9.1.2",
[[
INSERT INTO t2(a) VALUES(1.5e0);
]], {
1, "Type mismatch: can not convert double(1.5) to integer"
})
test:do_execsql_test(
"cast-9.1.3",
[[
INSERT INTO t2(b) VALUES(10000000000000000);
SELECT b FROM t2 WHERE i = 2;
]], {
10000000000000000
})
test:do_catchsql_test(
"cast-9.1.4",
[[
INSERT INTO t2(b) VALUES(10000000000000001);
]], {
1, "Type mismatch: can not convert integer(10000000000000001) to double"
})
-- Make sure that UUID cannot be implicitly cast to STRING.
local uuid = "CAST('11111111-1111-1111-1111-111111111111' AS UUID)";
test:do_catchsql_test(
"cast-9.2",
[[
INSERT INTO t3(s) VALUES(]]..uuid..[[);
]], {
1, "Type mismatch: can not convert "..
"uuid('11111111-1111-1111-1111-111111111111') to string"
})
-- Make sure that UUID cannot be implicitly cast to VARBINARY.
test:do_catchsql_test(
"cast-9.3",
[[
INSERT INTO t4(v) VALUES(]]..uuid..[[);
]], {
1, "Type mismatch: can not convert "..
"uuid('11111111-1111-1111-1111-111111111111') to varbinary"
})
-- Make sure that STRING and VARBINARY cannot be implicitly cast to UUID.
test:do_catchsql_test(
"cast-9.4.1",
[[
INSERT INTO t5(u) VALUES('11111111-1111-1111-1111-111111111111');
]], {
1, "Type mismatch: can not convert "..
"string('11111111-1111-1111-1111-111111111111') to uuid"
})
test:do_catchsql_test(
"cast-9.4.2",
[[
INSERT INTO t5(u) VALUES(x'11111111111111111111111111111111');
]], {
1, "Type mismatch: can not convert "..
"varbinary(x'11111111111111111111111111111111') to uuid"
})
test:execsql([[
DROP TABLE t1;
DROP TABLE t2;
DROP TABLE t3;
DROP TABLE t4;
DROP TABLE t5;
]])
--
-- Make sure that implicit cast from STRING to number was removed during
-- comparison where index is not used.
--
test:do_catchsql_test(
"cast-10.1",
[[
SELECT 1 < '2';
]], {
1, "Type mismatch: can not convert string('2') to number"
})
test:do_catchsql_test(
"cast-10.2",
[[
SELECT '1' < 2;
]], {
1, "Type mismatch: can not convert integer(2) to string"
})
test:do_catchsql_test(
"cast-10.3",
[[
SELECT 1.5 < '2';
]], {
1, "Type mismatch: can not convert string('2') to number"
})
test:do_catchsql_test(
"cast-10.4",
[[
SELECT '1' < 2.5;
]], {
1, "Type mismatch: can not convert double(2.5) to string"
})
-- Make sure that search using index in field type number work right.
test:do_execsql_test(
"cast-11",
[[
CREATE TABLE t6(d DOUBLE PRIMARY KEY);
INSERT INTO t6 VALUES(10000000000000000);
SELECT d FROM t6 WHERE d < 10000000000000001 and d > 9999999999999999;
DROP TABLE t6;
]], {
10000000000000000
})
-- Make sure that there is no unnecessary implicit casts in IN operator.
test:do_execsql_test(
"cast-12",
[[
SELECT 1 IN (SELECT '1');
]], {
false
})
test:finish_test()
|
local class = require 'lib.middleclass.middleclass'
local Messages = {}
local Message = class('MidiMessage')
function Message:initialize()
end
Messages.NoteOff = class("NoteOff", Message)
function Messages.NoteOff:initialize(n)
Message.initialize(self)
self.prefix = 0
self.note = n
end
Messages.NoteOn = class("NoteOn", Message)
function Messages.NoteOn:initialize(n)
Message.initialize(self)
self.prefix = 1
self.note = n
end
Messages.KeyPressure = class("KeyPressure", Message)
function Messages.KeyPressure:initialize(n)
Message.initialize(self)
self.prefix = 2
end
Messages.ControlChange = class("ControlChange", Message)
function Messages.ControlChange:initialize(n)
Message.initialize(self)
self.prefix = 3
end
Messages.ProgramChange = class("ProgramChange", Message)
function Messages.ProgramChange:initialize(n)
Message.initialize(self)
self.prefix = 4
end
Messages.ChannelPressure = class("ChannelPressure", Message)
function Messages.ChannelPressure:initialize(n)
Message.initialize(self)
self.prefix = 5
end
Messages.PitchBend = class("PitchBend", Message)
function Messages.PitchBend:initialize(n)
Message.initialize(self)
self.prefix = 6
end
Messages.SystemCommon = class("SystemCommon", Message)
function Messages.SystemCommon:initialize(n)
Message.initialize(self)
self.prefix = 7
end
return Messages
|
--- Utilities and generic auxiliary functions
-- @module util
--- Get an element from the matrix
-- @tparam table matrix
-- @tparam int x position of the element
-- @tparam int y position of the element
-- @return The element at the given position or null if there is none
function get_matrix_element(matrix, x, y)
if matrix[x] then
return matrix[x][y]
end
end
--- Insert an element on the matrix
-- @tparam table matrix
-- @tparam int x position of the element
-- @tparam int y position of the element
-- @param The element to be inserted
function insert_matrix_element(matrix, x, y, elem)
if not matrix[x] then
matrix[x] = {}
end
matrix[x][y] = elem
end
--- Remove an element from the matrix
-- @tparam table matrix
-- @tparam int x x position of the element
-- @tparam int y y position of the element
function remove_matrix_elem(matrix, x, y)
if matrix[x] then
matrix[x][y] = nil
end
end
--- Shuffles an array
-- Shuffles an array. This function changes the given array.
-- @tparam table array
-- @treturn table The shuffled array.
function shuffle_array(array)
local n = #array
while n > 2 do
local k = math.random(n)
array[n], array[k] = array[k], array[n]
n = n - 1
end
return array
end
--- Makes a shallow copy of a table.
-- @tparam table t
-- @treturn table
function copy_table(t)
local new_t = {}
for k, v in pairs(t) do
new_t[k] = v
end
return new_t
end
--- Returns an array of elements of a set.
-- This assumes a set being implemented as specified in the Programming in Lua book <a href="http://www.lua.org/pil/11.5.html">here</a>.
-- If the input is <code>{ 'apples' = true, 'oranges' = true, 'pears' = true }</code> the output is <code>{ 'oranges', 'apples', 'pears' }</code>.
-- @tparam table set
-- @treturn table
function set_to_array(set)
local array = {}
for v, _ in pairs(set) do
array[#array+1] = v
end
return array
end
function distance_between_points(v1, v2, u1, u2)
return math.sqrt( (v1 - u1)^2 + (v2 - u2)^2 )
end
|
--Last update by GlitterStorm @ Azralon on Feb,22th,2015
if GetLocale() ~= "ptBR" then return end
local L
--------------
-- Brawlers --
--------------
L= DBM:GetModLocalization("Brigões")
L:SetGeneralLocalization({
name = "Brigões: Geral"
})
L:SetWarningLocalization({
warnQueuePosition2 = "Você é %d na fila",
specWarnYourNext = "Você é o próximo!",
specWarnYourTurn = "É a sua vez!"
})
L:SetOptionLocalization({
warnQueuePosition2 = "Anuncia a sua posição atual na fila toda vez que ouver mudança",
specWarnYourNext = "Exibe aviso especial quando você for o próximo",
specWarnYourTurn = "Exibe aviso especial quando for a sua vez",
SpectatorMode = "Exibe avisos/temporizadores quando estiver assistindo lutas<br/>(Pessoal 'Aviso especial' mensagens não serão exibidas aos espectadores)",
SpeakOutQueue = "Conta em voz alta quando o numero da fila atualizar"
})
L:SetMiscLocalization({
Bizmo = "Bizmo",--Alliance
Bazzelflange = "Chefe Brazaflange",--Horde
--I wish there was a better way to do this....so much localizing. :(
Rank1 = "Rank 1",
Rank2 = "Rank 2",
Rank3 = "Rank 3",
Rank4 = "Rank 4",
Rank5 = "Rank 5",
Rank6 = "Rank 6",
Rank7 = "Rank 7",
Rank8 = "Rank 8",
Rank9 = "Rank 9",
Rank10 = "Rank 10",
Proboskus = "Oh céus... eu sinto muito, mas parece que você tera que lutar com Proboskus.",--Alliance
Proboskus2 = "Ha ha ha! Que falta de sorte! É o Proboskus! Ahhh ha ha ha! Apostei vinte e cinco ouros que você morrera no fogo!"--Horde
})
------------
-- Rank 1 --
------------
L= DBM:GetModLocalization("BrawlRank1")
L:SetGeneralLocalization({
name = "Brigões: Rank 1"
})
------------
-- Rank 2 --
------------
L= DBM:GetModLocalization("BrawlRank2")
L:SetGeneralLocalization({
name = "Brigões: Rank 2"
})
------------
-- Rank 3 --
------------
L= DBM:GetModLocalization("BrawlRank3")
L:SetGeneralLocalization({
name = "Brigões: Rank 3"
})
L:SetOptionLocalization({
SetIconOnBlat = "Marca (caveira) no verdadeiro Blat"
})
------------
-- Rank 4 --
------------
L= DBM:GetModLocalization("BrawlRank4")
L:SetGeneralLocalization({
name = "Brigões: Rank 4"
})
L:SetOptionLocalization({
SetIconOnDominika = "Marca (caveira) na verdadeira Dominika, a ilusionista"
})
------------
-- Rank 5 --
------------
L= DBM:GetModLocalization("BrawlRank5")
L:SetGeneralLocalization({
name = "Brigões: Rank 5"
})
------------
-- Rank 6 --
------------
L= DBM:GetModLocalization("BrawlRank6")
L:SetGeneralLocalization({
name = "Brigões: Rank 6"
})
------------
-- Rank 7 --
------------
L= DBM:GetModLocalization("BrawlRank7")
L:SetGeneralLocalization({
name = "Brigões: Rank 7"
})
------------
-- Rank 8 --
------------
L= DBM:GetModLocalization("BrawlRank8")
L:SetGeneralLocalization({
name = "Brigões: Rank 8"
})
------------
-- Rank 9 --
------------
L= DBM:GetModLocalization("BrawlRank9")
L:SetGeneralLocalization({
name = "Brigões: Rank 9"
})
-------------
-- Rares 1 --
-------------
L= DBM:GetModLocalization("BrawlLegacy")
L:SetGeneralLocalization({
name = "Brigões: Desafios passados"
})
L:SetOptionLocalization({
SpeakOutStrikes = "Contar em voz alta o numero de ataques $spell:141190"
})
-------------
-- Rares 2 --
-------------
L= DBM:GetModLocalization("BrawlChallenges")
L:SetGeneralLocalization({
name = "Brigões: Desafios especiais"
})
L:SetWarningLocalization({
specWarnRPS = "Use %s!"
})
L:SetOptionLocalization({
ArrowOnBoxing = "Exibir flecha DBM durante $spell:140868 e $spell:140862 e $spell:140886",
specWarnRPS = "Exibir aviso especial sobre o que usar para $spell:141206"
})
L:SetMiscLocalization({
rock = "Pedra",
paper = "Papel",
scissors = "Tesoura"
})
|
#!/usr/bin/env luajit
local xmlua = require("xmlua")
local path = arg[1]
local file = assert(io.open(path))
local html = file:read("*all")
file:close()
-- Parses HTML
local success, document = pcall(xmlua.HTML.parse, html)
if not success then
local message = document
print("Failed to parse HTML: " .. message)
os.exit(1)
end
print("Encoding: " .. document:encoding())
print("Title: " .. document:search("/html/head/title"):text())
if #document.errors > 0 then
print()
for i, err in ipairs(document.errors) do
print("Error" .. i .. ":")
print(path .. ":" .. err.line .. ":" .. err.message)
end
end
|
-- Adds an ADSR (Attack, Decay, Sustain, Release) envelope to the input
-- Convert from dB to voltage ratio,
-- e.g. dbToRatio(6) is about 2, dbToRatio(-3) is about 0.7
local function dbToRatio(db)
return 10 ^ (db/20)
end
local defs = {name = 'ADSR', knobs = {}}
defs.knobs.attack = {
min = 0.5, max = 10000.0, default = 10.0,
label = 'Attack (ms)',
onChange = function(state, newVal)
state.attackSmps = newVal * state.sampleRate / 1000
end
}
defs.knobs.decay = {
min = 0.5, max = 10000.0, default = 1000.0,
label = 'Decay (ms)',
onChange = function(state, newVal)
state.decaySmps = newVal * state.sampleRate / 1000
end
}
defs.knobs.sustainLevel = {
min = -40.0, max = 0.0, default = -9.0,
label = 'Sustain level (dB)',
onChange = function(state, newVal)
state.sustainRatio = dbToRatio(newVal)
end
}
defs.knobs.sustainLen = {
min = 0.5, max = 10000.0, default = 2000.0,
label = 'Sustain time (ms)',
onChange = function(state, newVal)
state.sustainSmps = newVal * state.sampleRate / 1000
end
}
defs.knobs.release = {
min = 0.5, max = 10000.0, default = 1000.0,
label = 'Release (ms)',
onChange = function(state, newVal)
state.releaseSmps = newVal * state.sampleRate / 1000
end
}
function defs.processSamplePair(state, left, right)
if not state.n then state.n = 0 end
local mul = 0
local n = state.n
if n <= state.attackSmps then
mul = n / state.attackSmps -- [0, 1]
else
n = n - state.attackSmps
if n <= state.decaySmps then
mul = 1 - (n / state.decaySmps * (1 - state.sustainRatio))
-- [sustainRatio, 1]
else
n = n - state.decaySmps
if n <= state.sustainSmps then
mul = state.sustainRatio
else
n = n - state.sustainSmps
if n <= state.releaseSmps then
mul = state.sustainRatio * (1 - (n / state.releaseSmps))
-- [0, sustainRatio]
end
end
end
end
state.n = state.n + 1
return left * mul, right * mul
end
return require("util.wrap").wrapMachineDefs(defs)
|
-- CONFIGURATION
-- How often to run. At 1, it will run every update. At 10,
-- it will run every 10th update. The lower it is, the more
-- responsive it will be, but it will also take more processing time.
UpdateRate = 4
-- Range to fire interceptors
InterceptRange = 1000
-- Hostile missiles at or below this altitude are considered torpedoes
InterceptTorpedoBelow = 0
-- Weapon slots to fire for each quadrant and hostile missile type. Use nil for unassigned.
InterceptWeaponSlot = {
Missile = {
LeftRear = nil,
LeftForward = nil,
RightRear = nil,
RightForward = nil,
},
Torpedo = {
LeftRear = nil,
LeftForward = nil,
RightRear = nil,
RightForward = nil,
},
}
|
platforms = {} -- To hold all the platform objects from the object layer
-- Platform (Object Layer) related function
function spawnPlatform(x, y, width, height)
-- Create a platform for the player
local platform = world:newRectangleCollider(x, y, width, height, {collision_class = "Platform"})
platform:setType('static') -- Setting it to static because we don't want it to be affected by any force
table.insert(platforms, platform) -- Add the platform object to the platforms table
end |
--[[============================================================
--=
--= Get Latest Version Number Script
--=
--= Args: none
--=
--= Outputs:
--= :version
--= <version>
--= <downloadUrl>
--=
--= :error_request
--= <errorMessage>
--=
--= :error_http
--= <statusCode>
--= <statusText>
--=
--= :error_malformed_response
--= <errorMessage>
--=
--= <error>
--=
--=-------------------------------------------------------------
--=
--= MyHappyList - manage your AniDB MyList
--= - Written by Marcus 'ReFreezed' Thunström
--= - MIT License (See main.lua)
--=
--============================================================]]
local t = {}
local ok, statusCodeOrErr, headers, statusText = require"ssl.https".request{
method = "GET",
url = "https://api.github.com/repos/ReFreezed/MyHappyList/releases/latest",
sink = require"ltn12".sink.table(t),
headers = {
["accept"] = "application/vnd.github.v3+json",
},
}
ok = not not ok
if not ok then
print(":error_request")
print(statusCodeOrErr)
os.exit(1)
end
if statusCodeOrErr ~= 200 then
print(":error_http")
print(statusCodeOrErr)
print(statusText)
os.exit(1)
end
local ok, responseOrErr = pcall(require"json".decode, table.concat(t))
if not ok then
print(":error_malformed_response")
print(responseOrErr)
os.exit(1)
end
local response = responseOrErr
if type(response) ~= "table" then
print(":error_malformed_response")
os.exit(1)
end
local version = tablePathGet(response, "tag_name")
local downloadUrl = tablePathGet(response, "assets", 1, "url")
if not (version and downloadUrl) then
print(":error_malformed_response")
os.exit(1)
end
print(":version")
print(version)
print(downloadUrl)
|
SILE.scratch.masters = {}
local _currentMaster
local function defineMaster (self, args)
SU.required(args, "id", "defining master")
SU.required(args, "frames", "defining master")
SU.required(args, "firstContentFrame", "defining master")
SILE.scratch.masters[args.id] = {frames = {}, firstContentFrame = nil}
for k,spec in pairs(args.frames) do
spec.id=k
SILE.scratch.masters[args.id].frames[k] = SILE.newFrame(spec)
end
SILE.frames = {page = SILE.frames.page}
SILE.scratch.masters[args.id].firstContentFrame = SILE.scratch.masters[args.id].frames[args.firstContentFrame]
end
local function defineMasters (self, list)
if list then
for i=1,#list do defineMaster(self, list[i]) end
end
end
local function doswitch(frames)
SILE.frames = {page = SILE.frames.page}
for id,f in pairs(frames) do
SILE.frames[id] =f
f:invalidate()
end
end
local function switchMasterOnePage (id)
if not SILE.scratch.masters[id] then
SU.error("Can't find master "..id)
end
SILE.documentState.thisPageTemplate = SILE.scratch.masters[id]
doswitch(SILE.scratch.masters[id].frames)
SILE.typesetter:chuck()
SILE.typesetter:initFrame(SILE.scratch.masters[id].firstContentFrame)
end
local function switchMaster (id)
_currentMaster = id
if not SILE.scratch.masters[id] then
SU.error("Can't find master "..id)
end
SILE.documentState.documentClass.pageTemplate = SILE.scratch.masters[id]
SILE.documentState.thisPageTemplate = std.tree.clone(SILE.documentState.documentClass.pageTemplate)
doswitch(SILE.scratch.masters[id].frames)
-- SILE.typesetter:chuck()
-- SILE.typesetter:init(SILE.scratch.masters[id].firstContentFrame)
end
SILE.registerCommand("define-master-template", function(options, content)
SU.required(options, "id", "defining a master")
SU.required(options, "first-content-frame", "defining a master")
-- Subvert the <frame> functionality from baseclass
local spare = SILE.documentState.thisPageTemplate.frames
local sp2 = SILE.frames
SILE.frames = {page = SILE.frames.page}
SILE.documentState.thisPageTemplate.frames = {}
SILE.process(content)
SILE.scratch.masters[options.id] = {}
SILE.scratch.masters[options.id].frames = SILE.documentState.thisPageTemplate.frames
if not SILE.scratch.masters[options.id].frames[options["first-content-frame"]] then
SU.error("first-content-frame "..options["first-content-frame"].." not found")
end
SILE.scratch.masters[options.id].firstContentFrame = SILE.scratch.masters[options.id].frames[options["first-content-frame"]]
SILE.documentState.thisPageTemplate.frames = spare
SILE.frames = sp2
end)
SILE.registerCommand("switch-master-one-page", function ( options, content )
SU.required(options, "id", "switching master")
switchMasterOnePage(options.id)
SILE.typesetter:leaveHmode()
end, "Switches the master for the current page")
SILE.registerCommand("switch-master", function ( options, content )
SU.required(options, "id", "switching master")
switchMaster(options.id)
end, "Switches the master for the current page")
return {
init = defineMasters,
exports = {
switchMasterOnePage = switchMasterOnePage,
switchMaster = switchMaster,
defineMaster = defineMaster,
defineMasters = defineMasters,
currentMaster = function () return _currentMaster end
}
}
|
--[[
Class: Drawable
Base class for drawables.
Properties:
(none)
Methods:
- (void) Draw ((number) dt)
]]
-- Constants
local _C = require("Helpers.Common")
-- Imports
local Class = require("Helpers.Class")
-- This
local Drawable = {}
-- Prototype
Drawable.prototype = {
type = "Drawable", -- type of the object
}
-- Constructor
function Drawable.constructor (newObject)
return
end
--[[
Method: Draw
Draws "Hello World"
]]
function Drawable.Draw (dt)
love.graphics.print("Hello World", 0, 0)
end
--[[
Method: Update
Updates the Drawable.
]]
function Drawable.Update ()
return
end
-- Turn Drawable into a proper class.
Class.CreateClass(Drawable)
return Drawable |
require "/scripts/vec2.lua"
function init()
storage.timer = storage.timer or 0
if storage.active == nil then
updateActive()
end
object.setSoundEffectEnabled(storage.active)
self.fireTime = config.getParameter("fireTime", 1)
self.fireTimeVariance = config.getParameter("fireTimeVariance", 0)
self.projectile = config.getParameter("projectile")
self.projectileConfig = config.getParameter("projectileConfig", {})
self.projectilePosition = config.getParameter("projectilePosition", {0, 0})
self.projectileDirection = config.getParameter("projectileDirection", {1, 0})
self.inaccuracy = config.getParameter("inaccuracy", 0)
self.projectilePosition = object.toAbsolutePosition(self.projectilePosition)
end
function update(dt)
if storage.active then
storage.timer = storage.timer - dt
if storage.timer <= 0 then
storage.timer = self.fireTime + (self.fireTimeVariance * math.random() - self.fireTimeVariance / 2)
shoot()
end
end
end
function onNodeConnectionChange(args)
updateActive()
end
function onInputNodeChange(args)
updateActive()
end
function shoot()
animator.playSound("shoot")
local projectileDirection = vec2.rotate(self.projectileDirection, sb.nrand(self.inaccuracy, 0))
world.spawnProjectile(self.projectile, self.projectilePosition, entity.id(), projectileDirection, false, self.projectileConfig)
end
function updateActive()
local active = (not object.isInputNodeConnected(0)) or object.getInputNodeLevel(0)
if active ~= storage.active then
storage.active = active
if active then
storage.timer = 0
animator.setAnimationState("trapState", "on")
object.setLightColor(config.getParameter("activeLightColor", {0, 0, 0, 0}))
object.setSoundEffectEnabled(true)
animator.playSound("on");
else
animator.setAnimationState("trapState", "off")
object.setLightColor(config.getParameter("inactiveLightColor", {0, 0, 0, 0}))
object.setSoundEffectEnabled(false)
animator.playSound("off");
end
end
end
|
--[[Author: Pizzalol
Date: 06.04.2015.
If the target unit is owned by the caster then heal it to full]]
function HandOfGod( keys )
local caster = keys.caster
local target = keys.target
local ability = keys.ability
local sound = keys.sound
local hand_particle = keys.hand_particle
if target:GetPlayerOwnerID() == caster:GetPlayerOwnerID() and target ~= caster then
local particle = ParticleManager:CreateParticle(hand_particle, PATTACH_POINT_FOLLOW, target)
ParticleManager:SetParticleControlEnt(particle, 0, target, PATTACH_POINT_FOLLOW, "attach_hitloc", target:GetAbsOrigin(), true)
ParticleManager:ReleaseParticleIndex(particle)
EmitSoundOn(sound, target)
target:Heal(target:GetMaxHealth(), ability)
end
end |
vim.g.gruvbox_colors = {
red = '#FA7970',
orange = '#FAA356',
yellow = '#D8A657',
--cyan = '#89B482',
blue = '#7DAEA3',
purple = '#D3869B',
bg_yellow = '#D8A657',
}
|
require('luacov')
local unpack = unpack or table.unpack
local testcase = require('testcase')
local basedir = require('basedir')
local mkdir = require('mkdir')
local rmdir = require('rmdir')
local TESTDIR = 'test_dir'
function testcase.new()
-- test that create a basedir objrect
assert(basedir.new(TESTDIR))
-- test that throws an error
for _, v in ipairs({
{
arg = {},
match = 'pathname must be string',
},
{
arg = {
'unknown-dir',
},
match = 'No .+ directory',
},
{
arg = {
TESTDIR .. '/hello.txt',
},
match = 'is not directory',
},
{
arg = {
TESTDIR,
'',
},
match = 'follow_symlink must be boolean',
},
}) do
local err = assert.throws(basedir.new, unpack(v.arg))
assert.match(err, v.match, false)
end
end
function testcase.normalize()
local r = basedir.new(TESTDIR)
-- test that converts pathname to absolute path in the base directory
local pathname = r:normalize('./foo/../bar/../baz/qux/../empty.txt')
assert.equal(pathname, '/baz/empty.txt')
end
function testcase.dirname()
local r = basedir.new(TESTDIR)
-- test that split pathname into dirname and filename
for _, v in ipairs({
{
pathname = './foo/../bar/../baz/qux/../empty.txt',
dirname = '/baz',
filename = 'empty.txt',
},
{
pathname = './foo/../empty.txt',
dirname = '/',
filename = 'empty.txt',
},
{
pathname = './empty.txt',
dirname = '/',
filename = 'empty.txt',
},
{
pathname = 'empty.txt/..',
dirname = '/',
filename = '',
},
}) do
local dirname, filename = r:dirname(v.pathname)
assert.equal(dirname, v.dirname)
assert.equal(filename, v.filename)
end
end
function testcase.realpath()
local r = basedir.new(TESTDIR)
-- test that converts relative path to absolute path based on base directory
for _, v in ipairs({
{
pathname = './foo/../bar/../baz/qux/../../empty.txt',
match_apath = TESTDIR .. '/empty%.txt$',
equal_rpath = '/empty.txt',
},
{
pathname = '/',
match_apath = TESTDIR,
equal_rpath = '/',
},
}) do
local apath, err, rpath = r:realpath(v.pathname)
assert(apath, err)
assert.match(apath, v.match_apath, false)
assert.equal(rpath, v.equal_rpath)
end
-- test that return nil if pathname is links to the outside of base directory
local apath, err, rpath = r:realpath('./subdir/example.lua')
assert.is_nil(apath)
assert.is_nil(err)
assert.is_nil(rpath)
-- test that resolved pathname if follow_symlink option is true
r = basedir.new(TESTDIR, true)
apath, err, rpath = r:realpath('./subdir/example.lua')
assert(apath, err)
assert.match(apath, 'test/example%.lua$', false)
assert.equal(rpath, '/subdir/example.lua')
end
function testcase.stat()
local r = basedir.new(TESTDIR)
-- test that get stat of file
local info, err = r:stat('empty.txt')
assert.is_nil(err)
-- confirm field definitions
for _, k in pairs({
'ctime',
'mtime',
'pathname',
'rpath',
'type',
}) do
assert(info[k], string.format('field %q is not defined', k))
end
-- confirm field value
assert.equal(info.type, 'file')
assert.equal(info.rpath, '/empty.txt')
assert.match(info.pathname, '/test_dir/empty.txt$', false)
-- test that return nil if it does not exist
info, err = r:stat('empty.txta')
assert.is_nil(info)
assert.is_nil(err)
end
function testcase.open()
local r = basedir.new(TESTDIR)
-- test that can open file
local f, err = r:open('subdir/world.txt')
assert.is_nil(err)
local content = assert(f:read('*a'))
f:close()
assert.equal(content, 'world')
-- test that cannot open a file if it does not exist
f, err = r:open('foo/bar/unknown/file')
assert.is_nil(f)
assert.is_nil(err)
-- test that cannot create a file if parent directory is not exist
f, err = r:open('unknown-dir/write.txt', 'a+')
assert.is_nil(f)
assert.is_nil(err)
-- test that can open a file in write mode
f = assert(r:open('write.txt', 'a+'))
assert(f:write('hello new file'))
f:close()
f = assert(r:open('write.txt'))
content = assert(f:read('*a'))
f:close()
assert.equal(content, 'hello new file')
os.remove(TESTDIR .. '/write.txt')
-- test that throws an error
err = assert.throws(r.open, r, 'write.txt', {})
assert.match(err, 'mode must be string')
end
function testcase.read()
local r = basedir.new(TESTDIR)
-- test that read file content
local content, err = r:read('/hello.txt')
assert.is_nil(err)
assert.equal(content, 'hello')
-- test that cannot read file content if it does not exist
content, err = r:read('/unknown.txt')
assert.is_nil(content)
assert.is_nil(err)
end
function testcase.rmdir()
local r = basedir.new(TESTDIR)
assert(mkdir(TESTDIR .. '/foo/bar/baz', nil, true, false))
-- test that remove a directory
assert(r:rmdir('/foo/bar/baz'))
local stat = r:stat('/foo/bar/baz')
assert.is_nil(stat)
-- test that cannot remove a non-empty directory
local ok, err = r:rmdir('/foo')
assert.is_false(ok)
assert.match(err, 'not empty')
assert(r:stat('/foo'))
-- test that recursively remove directories
assert(r:rmdir('/foo', true))
stat = r:stat('/foo')
assert.is_nil(stat)
end
function testcase.mkdir()
local r = basedir.new(TESTDIR)
-- test that make a directory
assert(r:mkdir('/foo/bar', '0700'))
local stat = assert(r:stat('/foo/bar'))
assert.equal(stat.type, 'directory')
assert.equal(stat.perm, '0700')
assert(rmdir(TESTDIR .. '/foo', true))
end
function testcase.opendir()
local r = basedir.new(TESTDIR)
-- test that open diretory
local dir, err = r:opendir('/')
assert.is_nil(err)
assert.match(tostring(dir), 'dir*:')
dir:closedir()
-- test that returns nil if it is not directory
dir, err = r:opendir('/out_of_basedir')
assert.is_nil(dir)
assert.re_match(err, 'not a directory', 'i')
-- test that open symlink directory
r = basedir.new(TESTDIR, true)
dir, err = r:opendir('/out_of_basedir')
assert.is_nil(err)
assert.match(tostring(dir), 'dir*:')
dir:closedir()
-- test that returns nil if it does not exist
dir, err = r:opendir('/noent')
assert.is_nil(dir)
assert.is_nil(err)
end
function testcase.readdir()
local r = basedir.new(TESTDIR)
-- test that read entries
local entries, err = r:readdir('/')
assert.is_nil(err)
-- confirm that contains 'empty.txt' and 'hello.txt'
local files = {
['subdir'] = true,
['empty.txt'] = true,
['hello.txt'] = true,
['out_of_basedir'] = true,
}
for _, entry in ipairs(entries) do
assert.not_empty(files)
assert(files[entry], string.format('unknown entry: %s', entry))
files[entry] = nil
end
assert.empty(files)
-- test that returns nil if it does not exist
entries, err = r:readdir('/noent')
assert.is_nil(entries)
assert.is_nil(err)
end
function testcase.remove()
local r = basedir.new(TESTDIR)
local f = assert(r:open('/foo.txt', 'a'))
f:close()
-- test that remove filepath
assert(r:remove('/foo.txt'))
-- test that return false if file not exists
local ok, err = r:remove('/foo.txt')
assert.is_false(ok)
assert.match(err, '/foo%.txt.+ file or', false)
end
function testcase.rename()
local r = basedir.new(TESTDIR)
local f = assert(r:open('/foo.txt', 'a'))
f:close()
-- test that rename filepath to new name
assert(r:rename('/foo.txt', '/bar.txt'))
r:remove('/bar.txt')
-- test that return error if cannot be renamed to newpath
local ok, err = r:rename('/bar.txt', '/baa/qux/quux.txt')
assert.is_false(ok)
assert.match(string.lower(err), 'no such file or', false)
end
function testcase.put()
local r = basedir.new(TESTDIR)
local f = assert(io.open('example.txt', 'a'))
f:close()
-- test that put external file into basedir
assert(r:put('example.txt', '/example.txt'))
r:remove('/example.txt')
-- test that return error if cannot be put into non exists directory
f = assert(io.open('example.txt', 'a'))
f:close()
local ok, err = r:put('example.txt', '/example/example.txt')
os.remove('example.txt')
assert.is_false(ok)
assert.match(string.lower(err), 'no such file or', false)
end
|
--[[
VERIFIED @ 2017.08.14
by Qige <qigezhao@gmail.com>
History:
2017.06.19 import abb from Proto-EC54S
2017.08.10 gws_abb|indent
2017.08.11 update_safe_rt|mesh_id
2017.08.14 bitrate
TODO:
1. set()
]]--
-- DEBUG USE ONLY
--local DBG = print
local function DBG(msg) end
local iwinfo = require "iwinfo"
local rarp = require 'arn.utils.rarp'
local ccff = require "arn.utils.ccff"
local fget = ccff.conf.get
local fset = ccff.conf.set
local s = ccff.val.s
local n = ccff.val.n
local exec = ccff.execute
local trimr = ccff.trimr
local ts = os.time
local out = io.write
local prt = print
local sfmt = string.format
local suc = string.upper
local tbl_push = table.insert
local gws_abb = {}
gws_abb.cmd = {}
gws_abb.cmd.wmac = 'cat /sys/class/net/wlan0/address 2>/dev/null | tr -d "\n"'
gws_abb.cmd.ear_id = 'uci get wireless.@wifi-iface[0].ssid 2> /dev/null'
gws_abb.cmd.mesh_id = 'uci get wireless.@wifi-iface[0].mesh_id 2> /dev/null'
-- FIXME: should be read from config file
gws_abb.conf = {}
gws_abb.conf.dev = 'wlan0'
gws_abb.conf.api = 'nl80211'
gws_abb.conf.chanbw = fget('wireless', 'radio0', 'chanbw') or 8
-- limitations
gws_abb.bar = {}
gws_abb.bar.rf_val_min = -110
gws_abb.bar.peer_inactive = 3000
-- .iw, .param, .wmac
gws_abb.cache = {}
gws_abb.cache.iw = nil
gws_abb.cache.wmac = nil
--[[
Tasks:
1. If iw is initialized, do dothing;
2. If not, init by 'iwinfo'.
]]--
function gws_abb.init()
DBG('hal gws_abb--------> init()')
local iw = gws_abb.cache.iw
if (not iw) then
local api = gws_abb.conf.api or 'nl80211'
gws_abb.cache.iw = iwinfo[api]
end
local wmac = gws_abb.cache.wmac
if (not wmac) then
gws_abb.wmac()
end
end
--Read WLAN0 MAC in cli
function gws_abb.wmac()
DBG('hal gws_abb--------> wmac()')
local wmac_cmd = gws_abb.cmd.wmac
local wmac = ccff.execute(wmac_cmd)
DBG(sfmt('hal gws_abb--------# wmac=[%s]', wmac))
gws_abb.cache.wmac = wmac
return wmac
end
function gws_abb.get_network_id(mode)
local network_id
if (mode == 'mesh') then
network_id = exec(gws_abb.cmd.mesh_id) or '--- '
else
network_id = exec(gws_abb.cmd.ear_id) or '--- '
end
network_id = trimr(network_id, 1)
return network_id
end
--[[
TODO:
1. All settings: chanbw|ssid|mode
]]--
function gws_abb.set(key, value)
print(sfmt('%80s', '### {ABB} NOT VERIFIED SINCE 2017.08.10 > set()### '))
DBG(sfmt('hal gws_abb----> (TODO) set(k=%s,v=%s)', key, value))
local cmd
if (key == 'siteno') then
DBG(sfmt('hal gws_abb------+ set siteno=%s', value))
fset('ec54s','v2','siteno', value)
elseif (key == 'mode') then
if (value == 'car' or value == 'CAR') then
cmd = 'config_car; arn_car\n'
elseif (value == 'ear' or value == 'EAR') then
cmd = 'config_ear; arn_ear\n'
elseif (value == 'mesh' or value == 'MESH') then
cmd = 'config_mesh; arn_mesh\n'
elseif (value == 'adhoc' or value == 'ADHOC') then
cmd = 'config_adhoc; arn_adhoc\n'
end
elseif (key == 'chanbw') then
cmd = sfmt('setchanbw %d\n', value)
elseif (key == 'wifi') then
if (value == '0') then
cmd = 'reboot\n'
elseif (value == '1') then
cmd = 'wifi\n'
elseif (value == '2') then
cmd = 'wifi down\n'
else
cmd = 'wifi up\n'
end
end
ccff.execute(cmd)
end
--[[
Return:
1. Maybe nil, and each item maybe nil;
2. Maybe only basic data;
3. Maybe with peers' data.
Tasks:
1. Init ABB;
2. Gather data;
3. Gather peers' data if needed.
]]--
function gws_abb.update_safe_rt()
--print(sfmt('%80s', '### {ABB} VERIFIED SINCE 2017.08.14 ### '))
DBG(sfmt('hal gws_abb------> (FIXME) param()'))
-- init dev/api/iw
gws_abb.init()
DBG(sfmt('hal gws_abb------+ (FIXME) abb initialized'))
DBG(sfmt('hal gws_abb------+ (FIXME) start gather data'))
local abb = {}
local dev = gws_abb.conf.dev
local api = gws_abb.conf.api
local iw = gws_abb.cache.iw
local format_rf = gws_abb.format.rf_val
local format_mode = gws_abb.format.mode
abb.bssid = suc(iw.bssid(dev) or '----')
abb.wmac = suc(gws_abb.cache.wmac or '----')
abb.chanbw = gws_abb.conf.chanbw
abb.mode = format_mode(iw.mode(dev) or '----')
if (abb.mode == 'CAR' or abb.mode == 'car') then
abb.ssid = iw.ssid(dev) or '---'
elseif (abb.mode == 'EAR' or abb.mode == 'ear') then
abb.ssid = gws_abb.get_network_id('ear')
elseif (abb.mode == 'Mesh' or abb.mode == 'mesh' or abb.mode == 'MESH') then
abb.ssid = gws_abb.get_network_id('mesh')
else
abb.ssid = '----'
end
DBG(sfmt('hal gws_abb--------# mode=%s,bssid=%s,ssid=%s,wmac=%s,chanbw=%s,mode=%s',
abb.mode, abb.bssid, abb.ssid, abb.wmac, abb.chanbw, abb.mode))
local noise = format_rf(iw.noise(dev))
-- GWS4K noise may equals 0
if (noise == 0) then
noise = -101
end
local signal = format_rf(iw.signal(dev))
if (signal < noise) then
signal = noise
end
abb.noise = noise
abb.signal = signal
DBG(sfmt('hal gws_abb--------# signal=%s,noise=%s',
abb.signal, abb.noise))
DBG(sfmt('hal gws_abb------+ (FIXME) start gather peers\' data'))
local peers = gws_abb.peers(abb.bssid, abb.noise) or {}
local peer_qty = #peers
abb.peers = peers
abb.peer_qty = peer_qty
DBG(sfmt('hal gws_abb--------# (FIXME) total %s peers', abb.peer_qty))
abb.ts = os.time()
return abb
end
function gws_abb.demo_peer(idx)
local peer = {}
peer.bssid = 'AA:BB:CC:DD:EE:F' .. idx
peer.wmac = 'FF:EE:DD:CC:BB:A' .. idx
peer.ip = '----'
peer.signal = -85 + idx
peer.noise = -101
peer.inactive = 555 * idx
peer.rx_mcs = 1 + idx
peer.rx_br = 1.1 + idx
peer.rx_short_gi = idx
peer.tx_mcs = 0 + idx
peer.tx_br = 2.2 + idx
peer.tx_short_gi = 1 - idx
return peer
end
-- get all peers in table
function gws_abb.peers(bssid, noise)
local peers = {}
local dev = gws_abb.conf.dev
local api = gws_abb.conf.api
local iw = gws_abb.cache.iw
local ai, ae
local al = iw.assoclist(dev)
if al and next(al) then
for ai, ae in pairs(al) do
local peer = {}
local signal = gws_abb.format.rf_val(ae.signal)
local inactive = n(ae.inactive) or 65535
if (signal ~= 0 and signal > noise and inactive < gws_abb.bar.peer_inactive) then
local wmac = s(ai) or ''
local pip = rarp.FETCH_IP(wmac, 1) or ''
peer.bssid = bssid
peer.wmac = wmac
peer.ip = pip
peer.signal = signal or noise
peer.noise = noise
peer.inactive = inactive
--print('abb.peers raw> rx_mcs|tx_mcs = ', ae.rx_mcs, ae.tx_mcs)
peer.rx_mcs = n(ae.rx_mcs) or 0
peer.rx_br = gws_abb.format.bitrate(ae.rx_rate) or 0
peer.rx_short_gi = n(ae.rx_short_gi) or 0
peer.tx_mcs = n(ae.tx_mcs) or 0
peer.tx_br = gws_abb.format.bitrate(ae.tx_rate) or 0
peer.tx_short_gi = n(ae.tx_short_gi) or 0
tbl_push(peers, peer)
end
end
end
-- DEBUG USE ONLY
--tbl_push(peers, gws_abb.demo_peer(1))
--tbl_push(peers, gws_abb.demo_peer(2))
return peers
end
-- format string/number
gws_abb.format = {}
--[[
Modes:
1. CAR: 'Master';
2. EAR: 'Client';
3. Mesh: 'Mesh Point'.
]]--
function gws_abb.format.mode(m)
if (m == 'Master') then
return 'CAR'
elseif (m == 'Client') then
return 'EAR'
elseif (m == 'Mesh Point') then
return 'Mesh'
else
return m
end
end
function gws_abb.format.bitrate(v)
result = 0
if (v) then
result = sfmt("%.1f", v / 1000 / 20 * gws_abb.conf.chanbw)
end
return result
end
--[[
Tasks:
1. Compare with -110, if lt, set to -110;
2. Default return -110.
]]--
function gws_abb.format.rf_val(v)
local r = gws_abb.bar.rf_val_min
if (v and v > r) then
r = v
end
return r
end
return gws_abb
|
local T, C, L = Tukui:unpack()
local _, ns = ...
local RaidCooldowns = ns.RaidCooldowns
local UnitGUID = _G.UnitGUID
local GetRealmName = _G.GetRealmName
local IsInRaid = _G.IsInRaid
local IsInGroup = _G.IsInGroup
local GetNumGroupMembers = _G.GetNumGroupMembers
local GetSpellInfo = _G.GetSpellInfo
local GetSpellBaseCooldown = _G.GetSpellBaseCooldown
local GetTime = _G.GetTime
function RaidCooldowns.UpdateTimer(self, elapsed)
self.time_left = (self.time_left or (self.expiration - GetTime())) - elapsed
if (self.time_left > 0) then
if (self.StatusBar) then
local percentage = (100 * (self.time_left or 0) / self.cooldown)
self.StatusBar:SetValue(percentage)
end
if (self.Timer) then
self.Timer:SetText(T.FormatTime(self.time_left))
end
else
RaidCooldowns.CooldownReady(self)
end
end
function RaidCooldowns:GetGroupUnit(index, size, isParty, isRaid)
if (not index) then index = 0 end
if (isParty == nil) then isParty = IsInGroup() end
if (isRaid == nil) then isRaid = IsInRaid() end
if (isRaid and (index > 0)) then
-- raid1 ... raidN
-- raid index is between 1 and MAX_RAID_MEMBERS, including player
return "raid" .. index
elseif (isParty and (index > 0) and (index < size)) then
-- party1 ... partyN
-- party index is between 1 and 4, excluding player
return "party" .. index
end
return "player"
end
function RaidCooldowns:GuidToUnit(guid)
local isInGroup, isInRaid = IsInGroup(), IsInRaid()
if (isInGroup or isInRaid) then
local size = GetNumGroupMembers()
for index = 1, size do
local unit = self:GetGroupUnit(index, size, isInGroup, isInRaid)
if (guid == UnitGUID(unit)) then
return unit, index
end
end
end
return nil, nil
end
function RaidCooldowns:GetRealm(realm)
if (string.len(realm or "") == 0) then
return GetRealmName()
end
return realm
end
function RaidCooldowns.UpdateBarText(frame, spell_name, member)
if (not frame.Text or not spell_name) then return end
local realm = (member.guid ~= self.guid) and member.realm or nil
local source = (realm) and (member.name .. "-" .. realm) or member.name
frame.Text:SetText(spell_name .. ": " .. source)
end
function RaidCooldowns.UpdateBarTimer(frame, time)
if (not frame.Timer) then return end
frame.Text:SetText(T.FormatTime(time))
end
function RaidCooldowns.CooldownReady(self)
if (self.StatusBar) then
self.StatusBar:SetValue(100)
end
if (self.Timer) then
self.Timer:SetText("Ready")
end
self.time_left = nil
self.expiration = nil
self.start = nil
self:SetScript("OnUpdate", nil)
end
function RaidCooldowns:SpawnBar(index, name, realm, class, spellName, spellIcon)
-- local sourceName = (realm) and (name .. "-" .. realm) or name
local Width, Height = C.RaidCD.BarWidth, C.RaidCD.BarHeight
local Spacing = C.RaidCD.BarSpacing
local Texture = C.Medias.Blank
local Font = T.GetFont(C.UnitFrames.Font)
local color = RAID_CLASS_COLORS[class]
local Bar = CreateFrame("Frame", self:GetName() .. index, UIParent)
Bar:SetSize(Width, Height)
Bar:SetFrameStrata(self:GetFrameStrata())
Bar:SetFrameLevel(self:GetFrameLevel() + 1)
Bar:CreateBackdrop()
local StatusBar = CreateFrame("StatusBar", Bar:GetName() .. "StatusBar", Bar)
StatusBar:SetInside(Bar)
StatusBar:SetFrameStrata(self:GetFrameStrata())
StatusBar:SetFrameLevel(Bar:GetFrameLevel() + 1)
StatusBar:SetStatusBarTexture(Texture)
StatusBar:SetStatusBarColor(color.r, color.g, color.b, 1)
StatusBar:SetMinMaxValues(0, 100)
StatusBar:SetValue(80)
-- StatusBar:CreateBackdrop()
StatusBar.Background = StatusBar:CreateTexture(nil, "BORDER")
StatusBar.Background:SetAllPoints(StatusBar)
StatusBar.Background:SetTexture(Texture)
StatusBar.Background:SetVertexColor(0.15, 0.15, 0.15)
local Button = CreateFrame("Button", Bar:GetName() .. "Button", Bar)
Button:SetPoint("RIGHT", StatusBar, "LEFT", -Spacing, 0)
Button:SetSize(Height, Height)
Button:CreateBackdrop()
local Icon = Button:CreateTexture(nil, "ARTWORK")
-- icon:SetAllPoints(button)
Icon:SetInside(Button)
Icon:SetTexCoord(unpack(T.IconCoord))
Icon:SetTexture(spellIcon)
local Text = StatusBar:CreateFontString(nil, "OVERLAY")
Text:SetFontObject(Font)
Text:SetPoint("LEFT", StatusBar, "LEFT", 5, 0)
Text:SetTextColor(0.84, 0.75, 0.65)
Text:SetWidth(0.8 * Width)
Text:SetJustifyH("LEFT")
Text:SetText(spellName .. ": " .. name)
local Timer = StatusBar:CreateFontString(nil, "OVERLAY")
Timer:SetFontObject(Font)
Timer:SetPoint("RIGHT", StatusBar, "RIGHT", -5, 0)
Timer:SetTextColor(0.84, 0.75, 0.65)
Timer:SetJustifyH("RIGHT")
Timer:SetText("Ready")
Bar.StatusBar = StatusBar
Bar.Button = Button
Bar.Icon = Icon
Bar.Text = Text
Bar.Timer = Timer
return Bar
end
function RaidCooldowns:IsTalentActive(guid, talentID)
return self.group[guid].talents[talentID].selected
end
-- if spell has cooldown modifier we need to update base cooldown time.
function RaidCooldowns:PostUpdateCooldown(guid, spellID, cooldown_ms)
local cooldown_s = (cooldown_ms or 0) / 1000
if (spellID == 15286 and self:IsTalentActive(guid, 23374)) then -- Vampiric Embrace
cooldown_s = cooldown_s - 45
elseif (spellID == 15487 and self:IsTalentActive(guid, 23137)) then -- Silence
cooldown_s = cooldown_s - 15
elseif (spellID == 47585 and self:IsTalentActive(guid, 21976)) then -- Dispersion
cooldown_s = cooldown_s - 30
elseif (spellID == 12975 and self:IsTalentActive(guid, 23099)) then -- Last Stand
cooldown_s = cooldown_s - 60
end
return cooldown_s
end
-- Initialize spell tracker timer when a spell is used by anybody from the group.
function RaidCooldowns:UpdateCooldown(unit, spellID)
local match = string.match(unit, "%a+")
if (unit ~= "player" and match ~= "party" and match ~= "raid") then return end
local guid = UnitGUID(unit)
local index = self:FindCooldownIndex(guid, spellID)
if (not index) then return end
local name, _, icon, _, _, _, _ = GetSpellInfo(spellID)
if (not name) then return end
local cooldown_ms, _ = GetSpellBaseCooldown(spellID)
local cooldown = self:PostUpdateCooldown(guid, spellID, cooldown_ms)
local frame = self.bars[index]
frame.expiration = GetTime() + cooldown
frame.cooldown = cooldown
print(frame.spellID, frame.spellName, cooldown_ms, cooldown)
if (frame.Icon) then
frame.Icon:SetTexture(icon)
end
if (frame.StatusBar) then
frame.StatusBar:SetValue(100)
end
if (frame.Timer) then
frame.Timer:SetText(T.FormatTime(cooldown))
end
frame:SetScript("OnUpdate", self.UpdateTimer)
end
|
local M = {}
local sanitize = require("nvim-rss.modules.utils").sanitize
function M.insert_entries(entries)
local append = vim.fn.append
local line = vim.fn.line
for i, entry in ipairs(entries) do
append(line("$"), "")
append(line("$"), "")
append(line("$"), entry.title)
append(line("$"), "------------------------")
append(line("$"), entry.link)
append(line("$"), "")
if (entry.summary) then
append(line("$"), sanitize(entry.summary))
end
end
vim.cmd("0")
end
function M.update_feed_line(opt)
vim.cmd("/" .. opt.xmlUrl:gsub("/", "\\/"))
vim.cmd("nohlsearch")
vim.cmd("normal 0dth")
if (opt.latest == nil and opt.total == nil) then
return
else
vim.cmd("normal I(" .. os.date(opt.date_format, opt.update_date) .. ") [" .. opt.latest .. "/" .. opt.total .. "] ")
end
end
function M.insert_feed_info(feed_info)
vim.cmd("normal o " .. feed_info.title)
vim.cmd("center")
vim.cmd("normal o")
if feed_info.htmlUrl then
vim.cmd("normal o " .. feed_info.htmlUrl)
vim.cmd("center")
end
vim.cmd("normal o")
if (feed_info.subtitle) then
vim.cmd("normal o " .. feed_info.subtitle)
vim.cmd("center")
end
vim.cmd("normal o")
--[[ if (options.verbose) then
vim.cmd("normal o VERSION : " .. feed_info.version)
vim.cmd("normal o FORMAT : " .. feed_info.format)
vim.cmd("normal o UPDATED : " .. feed_info.updated)
vim.cmd("normal o RIGHTS : " .. feed_info.rights)
vim.cmd("normal o GENERATOR : " .. feed_info.generator)
vim.cmd("normal o AUTHOR : " .. feed_info.author)
end ]]
vim.cmd("normal o ========================================")
vim.cmd("center")
end
function M.create_feed_buffer()
vim.cmd([[
let win = bufwinnr("__FEED__")
if win == -1
vsplit __FEED__
setlocal buftype=nofile
setlocal nobackup noswapfile nowritebackup
setlocal noautoindent nosmartindent
setlocal nonumber norelativenumber
setlocal filetype=markdown
else
exe win . "winvim.cmd w"
normal! ggdG
endif
]])
end
return M
|
local t = Def.ActorFrame {}
local TIMER = THEME:GetMetric("ScreenAdInfo","TimerSeconds")
size = SCREEN_WIDTH/2.5;
distance = SCREEN_WIDTH/4;
t[#t+1] = LoadActor(THEME:GetPathG("","background/common_bg/shared"))..{
InitCommand=cmd(diffusealpha,0;linear,2;diffusealpha,1;sleep,TIMER-1;linear,1;diffusealpha,0);
OffCommand=cmd(linear,0.15;diffusealpha,0);
};
t[#t+1] = LoadActor("1_ad")..{
InitCommand=cmd(x,SCREEN_CENTER_X-distance;y,SCREEN_CENTER_Y;rotationy,90;zoomto,size,size;horizalign,center;);
OnCommand=cmd(sleep,.1;decelerate,1;rotationy,0;sleep,TIMER-0.25;linear,1;diffusealpha,0;);
OffCommand=cmd(linear,0.15;diffusealpha,0);
};
t[#t+1] = LoadActor("2_ad")..{
InitCommand=cmd(x,SCREEN_CENTER_X+distance;y,SCREEN_CENTER_Y;rotationy,90;zoomto,size,size;horizalign,center;);
OnCommand=cmd(sleep,.1;decelerate,1;rotationy,0;sleep,TIMER-0.25;linear,1;diffusealpha,0;);
OffCommand=cmd(linear,0.15;diffusealpha,0);
};
return t
|
return function()
print("GET", game:GetService("HttpService"):GetAsync("https://www.example.com"))
end
|
----------------------------------------------------------------------------------------------------
--
-- All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
-- its licensors.
--
-- For complete copyright and license terms please see the LICENSE at the root of this
-- distribution (the "License"). All use of this software is governed by the License,
-- or, if provided, by the license below or the license accompanying this file. Do not
-- remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
--
--
----------------------------------------------------------------------------------------------------
local FadeButton =
{
Properties =
{
FaderEntity = {default = EntityId()},
FadeValueSlider = {default = EntityId()},
FadeSpeedMinusButton = {default = EntityId()},
FadeSpeedPlusButton = {default = EntityId()},
FadeSpeedText = {default = EntityId()},
},
}
function FadeButton:OnActivate()
-- Connect to the button notification bus on our entity to know when to start the animation
self.animButtonHandler = UiButtonNotificationBus.Connect(self, self.entityId)
-- Connect to the slider notification bus to know what fade value to give to the animation
self.sliderHandler = UiSliderNotificationBus.Connect(self, self.Properties.FadeValueSlider)
-- Connect to the button notification buses of the minus and plus buttons to know when to change the fade speed
self.minusButtonHandler = UiButtonNotificationBus.Connect(self, self.Properties.FadeSpeedMinusButton)
self.plusButtonHandler = UiButtonNotificationBus.Connect(self, self.Properties.FadeSpeedPlusButton)
-- Initialize the fade value (needs to be the same as the start fade value slider value)
self.fadeValue = 0
-- Initialize the fade speed (needs to be the same as the start fade speed text)
self.fadeSpeed = 5
end
function FadeButton:OnDeactivate()
-- Disconnect from all our buses
self.animButtonHandler:Disconnect()
self.sliderHandler:Disconnect()
self.minusButtonHandler:Disconnect()
self.plusButtonHandler:Disconnect()
end
function FadeButton:OnSliderValueChanging(percent)
-- Set the fade value to the slider value
self.fadeValue = percent / 100
end
function FadeButton:OnSliderValueChanged(percent)
-- Set the fade value to the slider value
self.fadeValue = percent / 100
end
function FadeButton:OnButtonClick()
-- If the animation button was clicked
if (UiButtonNotificationBus.GetCurrentBusId() == self.entityId) then
-- Start the fade animation
UiFaderBus.Event.Fade(self.Properties.FaderEntity, self.fadeValue, self.fadeSpeed)
-- Else if the minus button was clicked
elseif (UiButtonNotificationBus.GetCurrentBusId() == self.Properties.FadeSpeedMinusButton) then
-- Decrement the animation speed (min = 1)
self.fadeSpeed = math.max(1, self.fadeSpeed - 1)
-- And update the text
UiTextBus.Event.SetText(self.Properties.FadeSpeedText, self.fadeSpeed)
-- Else the plus button was clicked
else
-- Decrement the animation speed (max = 10)
self.fadeSpeed = math.min(self.fadeSpeed + 1, 10)
-- And update the text
UiTextBus.Event.SetText(self.Properties.FadeSpeedText, self.fadeSpeed)
end
end
return FadeButton |
norns.script.load("code/gatherum/live.lua")
tapestop()
tapestart()
tapebreak()
clock.run(function() clock.sleep(1.5);tapestop();clock.sleep(2.5);tapestart() end)
clock.run(function() clock.sleep(1.5);tapebreak() clock.sleep(1.5);tapebreak() end)
play("bbr",er("if math.random()<0.2 then e.brev(1) end",5))
play("bbb",er("if math.random()<0.1 then; v=math.random(); e.bbreak(v,v+math.random()/40+0.01) end",4),1)
for _, v in ipairs({"crow","bou","hh","bou","usb","op1"}) do stop(v) end
|
require "posix"
-- require "inotify"
require "logging.console"
require 'socket.http'
local logger = logging.console()
local config = {}
local handle
local charmap = {
Arc = "Archeologist",
Bar = "Barbarian",
Cav = "Caveman",
Hea = "Healer",
Kni = "Knight",
Mon = "Monk",
Pri = "Priest",
Rog = "Rogue",
Ran = "Ranger",
Sam = "Samurai",
Tou = "Tourist",
Val = "Valkyrie",
Wiz = "Wizard",
Vam = "Vampire",
Hum = "human",
Orc = "orcish",
Gno = "gnomish",
Elf = "elven",
Dwa = "dwarven",
Fem = "female",
Mal = "male",
Ntr = "neuter",
Law = "lawful",
Cha = "chaotic",
Neu = "neutral",
Una = "evil"
}
local zonemap = {
[0] = "in The Dungeons of Doom",
[1] = "in Gehennom",
[2] = "in The Gnomish Mines",
[3] = "in The Quest",
[4] = "in Sokoban",
[5] = "in Town",
[6] = "in Fort Ludios",
[7] = "in the Black Market",
[8] = "in Vlad's Tower",
[9] = "on The Elemental Planes",
}
local achievements = {
'obtained the Bell of Opening',
'entered Gehennom',
'obtained the Candelabrum of Invocation',
'obtained the Book of the Dead',
'performed the invocation ritual',
'obtained the amulet',
'entered the elemental planes',
'entered the astral plane',
'ascended',
'obtained the luckstone from the Mines',
'obtained the sokoban prize',
'defeated Medusa',
}
local scum = {}
function nh_init(config)
logger:debug("nh_init()")
config = config
irc.hooks_msg_command[".online"] = nh_get_online_players
irc.hooks_msg_command[".cur"] = nh_get_online_players
irc.hooks_msg_command[".last"] = nh_get_last_dump
irc.hooks_msg_command[".lastgame"] = nh_get_last_dump
irc.hooks_msg_command[".lastdump"] = nh_get_last_dump
xlogfile_pos = posix.stat('/opt/nethack.nu/var/unnethack/xlogfile').size
livelog_pos = posix.stat('/opt/nethack.nu/var/unnethack/livelog').size
end
function lol()
f = io.open("/opt/nethack.nu/var/unnethack/livelog", "r")
l = f:read("*l")
while l ~= nil do
d = parse_nh(l)
print(l)
print(livelog_msg(d))
l = f:read("*l")
end
end
function livelog_msg(data)
if data["player"] ~= nil and scum[data["player"]] ~= nil then
logger:info(string.format("scum ignored: %s", data["player"]))
return "ignore"
end
if data['achieve'] ~= nil then
local diff_a = tonumber(data['achieve_diff'])
-- ignore irrelevant achievements & luckstone
if diff_a == 0 or diff_a == 0x200 or diff_a == 0x400 then
return
end
local astr = ""
for i,v in ipairs(achievements) do
if hasbit(diff_a, bit(i)) then
astr = v
end
end
return string.format("%s %s after %s turns.", data['player'], astr, data['turns'])
elseif data['wish'] ~= nil then
if data['wish']:lower() == "nothing" then
return string.format("%s has declined a wish.", data['player'])
else
return string.format("%s wished for '%s' after %s turns.",
data['player'],
data['wish'],
data['turns'])
end
elseif data['shout'] ~= nil then
local msg = string.format("You hear %s's distant rumbling", data['player'])
if data['shout'] == "" then
msg = msg .. "."
else
msg = msg .. string.format(": \"%s\"", data["shout"])
end
return msg
elseif data['killed_uniq'] ~= nil then
return string.format("%s killed %s after %s turns.",
data['player'],
data['killed_uniq'],
data['turns'])
elseif data['shoplifted'] ~= nil then
local suffix = "'s"
if data["shopkeeper"]:find("s$") ~= nil then
suffix = "'"
end
return string.format("%s stole %s zorkmids worth of merchandise from %s%s %s after %s turns",
data['player'],
data['shoplifted'],
data['shopkeeper'],
suffix,
data['shop'],
data['turns'])
elseif data['bones_killed'] ~= nil then
return string.format("%s killed the %s of %s the former %s after %s turns.",
data['player'],
data['bones_monst'],
data['bones_killed'],
data['bones_rank'],
data['turns'])
elseif data['crash'] ~= nil then
return string.format("%s has defied the laws of unnethack, process exited with status %s",
data['player'],
data['crash'])
elseif data['sokobanprize'] ~= nil then
return string.format("%s obtained %s after %s turns in Sokoban.",
data['player'],
data['sokobanprize'],
data['turns'])
elseif data['game_action'] ~= nil then
if data['game_action'] == 'started' and data['character'] ~= nil then
return string.format("%s enters the dungeon as a%s.",
data['player'],
data['character'])
elseif data['game_action'] == 'resumed' and data['character'] ~= nil then
return string.format("%s the%s resumes the adventure.",
data['player'],
data['character'])
elseif data['game_action'] == 'started' then
return string.format("%s enters the dungeon as a%s %s %s.",
data['player'],
data['alignment'],
data['race'],
data['role'])
elseif data['game_action'] == 'resumed' then
return string.format("%s the %s %s resumes the adventure.",
data['player'],
data['race'],
data['role'])
elseif data['game_action'] == 'saved' then
return string.format("%s is taking a break from the hard life as an adventurer.",
data['player'])
elseif data['game_action'] == 'panicked' then
return string.format("The dungeon of %s collapsed after %s turns!",
data['player'],
data['turns'])
end
end
return nil
end
function nh_tick(irc)
for k,v in pairs(scum) do
if v + 60 < os.time() then
logger:info(string.format("forgetting scum: %s", k))
scum[k] = nil
end
end
local fn = nil
if posix.stat('/opt/nethack.nu/var/unnethack/xlogfile').size > xlogfile_pos then
fn = '/opt/nethack.nu/var/unnethack/xlogfile'
elseif posix.stat('/opt/nethack.nu/var/unnethack/livelog').size > livelog_pos then
fn = '/opt/nethack.nu/var/unnethack/livelog'
end
if fn ~= nil then
local f, err = io.open(fn)
logger:debug(string.format("opening %s", fn))
if f == nil then
logger:error(string.format("failed to open %s: %s", fn, err))
else
local line, err
if fn == "/opt/nethack.nu/var/unnethack/xlogfile" then
f:seek("set", xlogfile_pos)
line, err = f:read("*l")
xlogfile_pos = f:seek()
else
f:seek("set", livelog_pos)
line, err = f:read("*l")
livelog_pos = f:seek()
end
if line == nil then
logger:error(string.format("failed to read line from %s: %s", fn, err))
else
f:close()
local data = parse_nh(line)
if fn == '/opt/nethack.nu/var/unnethack/xlogfile' then
local out = string.format("%s, the %s %s %s %s",
data["name"],
charmap[data["align"]],
charmap[data["gender"]],
charmap[data["race"]],
charmap[data["role"]])
zone = zonemap[tonumber(data["deathdnum"])]
if zone == nil then zone = "at an unknown location" end
if data["death"] == "ascended" then
out = out .. " ascended to demigod-good. "
else
out = out .. string.format(", %s %s on level %s, %s. ",
"left this world",
zone,
data["deathlev"],
data["death"])
end
if data["gender"] == "Mal" then
out = out .. "His "
elseif data["gender"] == "Fem" then
out = out .. "Her "
elseif data["gender"] == "Ntr" then
out = out .. "It's "
end
out = out .. string.format("score was %s.", data['points'])
if ((data["death"] == "quit" or data["death"] == "escaped") and tonumber(data["turns"]) < 10) or scum[data["name"]] ~= nil then
scum[data["name"]] = os.time()
logger:info(string.format("ignoring startscummer: %s", data["name"]))
else
irc:send_msg(irc.channel, out)
-- make the twitter message more terse
-- 1234567890 (Rol Rac Gen Ali), 1222333 points, 1222333 turns, death678901234567890123456789012345678901234567890123456789, http://is.gd/12345
out = string.format("%s (%s %s %s %s), %s points, %s turns, %s",
data["name"], data["role"], data["race"], data["gender"], data["align"],
data['points'], data['turns'], data['death'])
out = string.sub(out, 0, 120);
dumpurl = string.format("http://un.nethack.nu/users/%s/dumps/%s.%s.txt.html", data["name"], data["name"], data["endtime"])
b,c = socket.http.request("http://is.gd/api.php?longurl=" .. dumpurl)
if c == 200 then
out = out .. ", " .. b
else
logger:warn(string.format("URL shortening failed for: %s", dumpurl))
end
if string.len(out) > 140 then
logger:warn(string.format("Too long to tweet: %s", out))
else
out = out:gsub("\"", "\\\"")
os.execute("/usr/bin/tweet \"" .. out .. "\"")
end
end
elseif fn == '/opt/nethack.nu/var/unnethack/livelog' then
local msg = livelog_msg(data)
if msg ~= nil and msg ~= "ignore" then
irc:send_msg(irc.channel, msg)
elseif msg == nil then
logger:warn(string.format("unhandled livelog line: %s", line))
end
end
end
end
end
end
function bit(p)
return 2 ^ (p - 1) -- 1-based indexing
end
function hasbit(x, p)
return x % (p + p) >= p
end
function nh_destroy(config)
logger:debug("nh_destroy()")
irc.hooks_msg_command[".online"] = nil
irc.hooks_msg_command[".cur"] = nil
irc.hooks_msg_command[".last"] = nil
irc.hooks_msg_command[".lastgame"] = nil
irc.hooks_msg_command[".lastdump"] = nil
end
function parse_nh(line)
local kvs = split(line, ":")
local result = {}
for i,v in ipairs(kvs) do
local kv = split(v, "=")
result[kv[1]] = kv[2]
end
return result
end
function get_last_dump_url(nick)
nick = nick:gsub("/", "")
nick = nick:gsub("%.", "")
local ext = nil
local stat = posix.stat(string.format("/srv/un.nethack.nu/users/%s/dumps/%s.last.txt.html", nick, nick))
if stat == nil then
stat = posix.stat(string.format("/srv/un.nethack.nu/users/%s/dumps/%s.last.txt", nick, nick))
if stat == nil then
return nil
else
ext = ".txt"
end
else
ext = ".txt.html"
end
if ext ~= nil then
local tg = posix.readlink(string.format("/srv/un.nethack.nu/users/%s/dumps/%s.last%s", nick, nick, ext))
local fn = posix.basename(tg)
return string.format("http://un.nethack.nu/users/%s/dumps/%s", nick, fn)
end
end
function nh_get_last_dump(irc, target, command, sender, line)
local tokens = split(line)
local nick = irc:parse_prefix(sender)
if #tokens >= 2 then
nick = tokens[2]
end
nick = nick:gsub("/", "")
nick = nick:gsub("%.", "")
local url = get_last_dump_url(nick)
if url == nil then
irc:reply("No lastdump for %s", nick)
else
irc:reply(url)
end
end
function nh_get_online_players(irc, target, command)
local playing = 0
for i,v in ipairs(posix.dir("/opt/nethack.nu/dgldir/inprogress/")) do
if v ~= ".." and v ~= "." then
local pos = v:find(":")
if pos == nil then
logger:error(string.format("inprogress file without : %s", v))
else
local player = v:sub(1, pos-1)
local date = v:sub(pos+1)
local stat = posix.stat(string.format("/opt/nethack.nu/dgldir/ttyrec/%s/%s", player, date))
if stat == nil then
logger:error(string.format("no ttyrec corresponding to inprogress: %s | %s",
v,
string.format("/opt/nethack.nu/dgldir/ttyrec/%s/%s", player, date)))
else
local idle = os.time() - stat.mtime
local fd, err = io.open(string.format("/opt/nethack.nu/var/unnethack/%s.whereis", player), "r")
if fd == nil then
logger:error(string.format("failed to open %s: %s", v, err))
else
local t = parse_nh(fd:read("*l"))
io.close(fd)
local amulet = ""
if t["amulet"] == nil then
amulet = " (carrying the amulet)"
end
if t["playing"] ~= "1" then
logger:error(string.format("playing should be 1 for %s",
string.format("/opt/nethack.nu/var/unnethack/%s.whereis", player)))
end
playing = playing + 1
irc:reply("%s the %s %s %s %s is currently at level %s in %s at turn %s%s (idle for %s)",
t["player"],
t["align"],
charmap[t["gender"]],
t["race"],
t["role"],
t["depth"],
t["dname"],
t["turns"],
amulet,
format_time(idle))
end
end
end
end
end
if playing == 0 then
irc:reply("the world of unnethack is currently empty.. why don't you give it a try?")
end
end
return {tick=nh_tick,
init=nh_init,
destroy=nh_destroy}
|
function Bolt:CheckPassword(steam_id64, ip, sv_pass, cl_pass, name)
local steam_id = util.SteamIDFrom64(steam_id64)
local entry = self:get_bans()[steam_id]
if entry and Plugin.call('ShouldCheckBan', steam_id, ip, name) != false then
if entry.duration != 0 and entry.unban_time >= os.time() and Plugin.call('ShouldExpireBan', steam_id, ip, name) != false then
self:remove_ban(steam_id)
return true
else
return false, 'You are still banned: '..tostring(entry.reason)
end
end
end
function Bolt:CanTool(player, trace, tool_name)
local tool = Flux.Tool:get(tool_name)
if tool and tool.permission and !player:can(tool.permission) then
return false
end
end
function Bolt:PlayerCanHearPlayersVoice(player, talker)
if !talker:can('voice') then
return false
end
end
function Bolt:PlayerCreated(player, record)
record.banned = record.banned or false
end
function Bolt:ActiveRecordReady()
Ban:all():get(function(objects)
for k, v in ipairs(objects) do
self:record_ban(v.steam_id, v)
end
end)
end
function Bolt:PlayerRestored(player, record)
local root_steamid = Config.get('root_steamid')
if record.role then
player:SetUserGroup(record.role)
end
if isstring(root_steamid) then
if player:SteamID() == root_steamid then
player:SetUserGroup('admin')
player.can_anything = true
end
elseif istable(root_steamid) then
for k, v in ipairs(root_steamid) do
if v == player:SteamID() then
player:SetUserGroup('admin')
player.can_anything = true
end
end
end
if record.permissions then
local perm_table = {}
for k, v in pairs(record.permissions) do
perm_table[v.permission_id] = v.object
end
player:set_permissions(perm_table)
end
if record.temp_permissions then
local perm_table = {}
for k, v in pairs(record.temp_permissions) do
perm_table[v.permission_id] = {
value = v.object,
expires = time_from_timestamp(v.expires)
}
end
player:set_permissions(perm_table)
end
Log:notify(player:name()..' has connected to the server.', { action = 'player_events' })
end
function Bolt:CommandCheckImmunity(player, target, can_equal)
return self:check_immunity(player, v, can_equal)
end
-- Vanish admins for newly connected players.
function Bolt:PlayerInitialSpawn(player)
for k, v in ipairs(_player.GetAll()) do
if (v.is_vanished or v:get_nv('observer')) and !player:can('moderator') then
v:prevent_transmit(player, true)
end
end
end
function Bolt:PlayerOneMinute(player)
for k, v in pairs(player:get_temp_permissions()) do
if time_from_timestamp(v.expires) <= os.time() then
self:delete_temp_permission(player, k)
end
end
end
function Bolt:PlayerPermissionChanged(player, perm_id, value)
if perm_id == 'toolgun' then
if value == PERM_ALLOW then
player:Give('gmod_tool')
elseif value == PERM_NO then
player:StripWeapon('gmod_tool')
end
elseif perm_id == 'physgun' then
if value == PERM_ALLOW then
player:Give('weapon_physgun')
elseif value == PERM_NO then
player:StripWeapon('weapon_physgun')
end
end
end
function Bolt:PlayerUserGroupChanged(player, group, old_group)
if group:can('toolgun') then
player:Give('gmod_tool')
else
player:StripWeapon('gmod_tool')
end
if group:can('physgun') then
player:Give('weapon_physgun')
else
player:StripWeapon('weapon_physgun')
end
end
function Bolt:ChatboxGetPlayerIcon(player, text, team_chat)
if IsValid(player) then
return { icon = player:get_role_table().icon or 'fa-user', size = 14, margin = 10, is_data = true }
end
end
|
local AlmaApiInternal = {};
AlmaApiInternal.ApiUrl = nil;
AlmaApiInternal.ApiKey = nil;
local types = {};
types["log4net.LogManager"] = luanet.import_type("log4net.LogManager");
types["System.Net.WebClient"] = luanet.import_type("System.Net.WebClient");
types["System.Text.Encoding"] = luanet.import_type("System.Text.Encoding");
types["System.Xml.XmlTextReader"] = luanet.import_type("System.Xml.XmlTextReader");
types["System.Xml.XmlDocument"] = luanet.import_type("System.Xml.XmlDocument");
-- Create a logger
local log = types["log4net.LogManager"].GetLogger(rootLogger .. ".AlmaApi");
AlmaApi = AlmaApiInternal;
local function RetrieveHoldingsList( mmsId )
local requestUrl = AlmaApiInternal.ApiUrl .."bibs/"..
Utility.URLEncode(mmsId) .."/holdings?apikey=" .. Utility.URLEncode(AlmaApiInternal.ApiKey);
local headers = {"Accept: application/xml", "Content-Type: application/xml"};
log:DebugFormat("Request URL: {0}", requestUrl);
local response = WebClient.GetRequest(requestUrl, headers);
log:DebugFormat("response = {0}", response);
return WebClient.ReadResponse(response);
end
local function RetrieveBibs( mmsId )
local requestUrl = AlmaApiInternal.ApiUrl .. "bibs?apikey="..
Utility.URLEncode(AlmaApiInternal.ApiKey) .. "&mms_id=" .. Utility.URLEncode(mmsId);
local headers = {"Accept: application/xml", "Content-Type: application/xml"};
log:DebugFormat("Request URL: {0}", requestUrl);
local response = WebClient.GetRequest(requestUrl, headers);
log:DebugFormat("response = {0}", response);
return WebClient.ReadResponse(response);
end
local function RetrieveItemsList( mmsId, hodingId )
local requestUrl = AlmaApiInternal.ApiUrl .."bibs/"..
Utility.URLEncode(mmsId) .."/holdings/" .. Utility.URLEncode(hodingId) .. "/items?apikey=" ..
Utility.URLEncode(AlmaApiInternal.ApiKey);
local headers = {"Accept: application/xml", "Content-Type: application/xml"};
log:DebugFormat("Request URL: {0}", requestUrl);
local response = WebClient.GetRequest(requestUrl, headers);
log:DebugFormat("response = {0}", response);
return WebClient.ReadResponse(response);
end
-- Exports
AlmaApi.RetrieveHoldingsList = RetrieveHoldingsList;
AlmaApi.RetrieveBibs = RetrieveBibs;
AlmaApi.RetrieveItemsList = RetrieveItemsList;
|
testInfo = {
CodeName="Plot",
ShortName="Plot",
LongName="Plot",
Description="Plots sequences",
Functions= {
"MakePlot",
},
MakesIndividualImages = true,
MakesSampleTypeImages = false,
SamplePageShowsFunctionName = false,
} |
---@type number
local aNumber
---@type boolean
local aBoolean
---@type nil | number
local nilOrNumber
---@type nil | boolean
local nilOrBoolean
---@type fun(): number, boolean...
local varreturnFunction
aNumber, nilOrBoolean, nilOrBoolean = varreturnFunction()
aNumber, nilOrBoolean, nilOrBoolean, <error descr="Type mismatch. Required: 'nil | number' Found: 'boolean | nil'">nilOrNumber</error>, nilOrBoolean = <error descr="Result 4, type mismatch. Required: 'nil | number' Found: 'boolean | nil'">varreturnFunction()</error>
---@param numberParam number
---@return number, boolean...
local function varreturnFunction2()
if aNumber == 1 then
return 1
elseif aNumber == 2 then
return 1, <error descr="Result 2, type mismatch. Required: 'boolean' Found: '\"not a boolean\"'">"not a boolean"</error>
elseif aNumber == 3 then
return 1, true
elseif aNumber == 4 then
return 1, true, false
else
<error descr="Incorrect number of values. Expected 1 but found 0.">return</error>
end
end
aNumber, nilOrBoolean, nilOrBoolean = varreturnFunction2()
aNumber, nilOrBoolean, nilOrBoolean, <error descr="Type mismatch. Required: 'nil | number' Found: 'boolean | nil'">nilOrNumber</error>, nilOrBoolean = <error descr="Result 4, type mismatch. Required: 'nil | number' Found: 'boolean | nil'">varreturnFunction2()</error>
---@param a number
---@param b string
local function acceptsNumberString(a, b) end
acceptsNumberString(<error descr="Result 2, type mismatch. Required: 'string' Found: 'boolean'">varreturnFunction2()</error><error descr="Missing argument: b: string">)</error>
---@param a number
---@vararg string
local function acceptsNumberVariadicString(a, ...) end
acceptsNumberVariadicString(<error descr="Variadic result, type mismatch. Required: 'string' Found: 'boolean'">varreturnFunction2()</error>)
---@type fun(): boolean...
local varreturnFunction3
nilOrBoolean, nilOrBoolean = varreturnFunction3()
nilOrBoolean, nilOrBoolean, <error descr="Type mismatch. Required: 'nil | number' Found: 'boolean | nil'">nilOrNumber</error>, nilOrBoolean = <error descr="Result 3, type mismatch. Required: 'nil | number' Found: 'boolean | nil'">varreturnFunction3()</error>
---@return boolean...
local function varreturnFunction4()
if aNumber == 1 then
return
elseif aNumber == 2 then
return <error descr="Type mismatch. Required: 'boolean' Found: '\"not a boolean\"'">"not a boolean"</error>
elseif aNumber == 3 then
return true
elseif aNumber == 4 then
return true, false
end
end
nilOrBoolean, nilOrBoolean = varreturnFunction4()
nilOrBoolean, nilOrBoolean, <error descr="Type mismatch. Required: 'nil | number' Found: 'boolean | nil'">nilOrNumber</error>, nilOrBoolean = <error descr="Result 3, type mismatch. Required: 'nil | number' Found: 'boolean | nil'">varreturnFunction4()</error>
---@generic T
---@param list T[]
---@return T...
local function genericVarreturn(list)
return table.unpack(list)
end
nilOrNumber, nilOrNumber = genericVarreturn({1, 2})
nilOrNumber, <error descr="Type mismatch. Required: 'boolean | nil' Found: '1 | 2 | nil'">nilOrBoolean</error> = <error descr="Result 2, type mismatch. Required: 'boolean | nil' Found: '1 | 2 | nil'">genericVarreturn({1, 2})</error>
local implicitNilOrNumber1, implicitNilOrNumber2 = genericVarreturn({ 1, 2})
nilOrNumber = implicitNilOrNumber1
nilOrBoolean = <error descr="Type mismatch. Required: 'boolean | nil' Found: '1 | 2 | nil'">implicitNilOrNumber1</error>
nilOrNumber = implicitNilOrNumber2
nilOrBoolean = <error descr="Type mismatch. Required: 'boolean | nil' Found: '1 | 2 | nil'">implicitNilOrNumber2</error>
---@type fun(): boolean...
local booleanVarreturn
---@type fun(a: boolean | nil): void
local nilOrBooleanParameter
nilOrBooleanParameter(booleanVarreturn()<error descr="Missing argument: a: boolean | nil">)</error> -- Expect error
nilOrBooleanParameter((booleanVarreturn()))
|
cluster_center = "127.0.0.1:7000"
cluster_db = "127.0.0.1:7001"
cluster_login = "127.0.0.1:7002"
cluster_gate = "127.0.0.1:7003"
cluster_hall = "127.0.0.1:7004"
cluster_game_niuniu = "127.0.0.1:6000"
cluster_game_br = "127.0.0.1:6001"
|
function onPre(v)
vee.putreg(v, RAX, 64, 50505050)
vee.putreg(v, RBX, 64, 50505050)
vee.putreg(v, RCX, 64, 50505050)
vee.putreg(v, RDX, 64, 50505050)
vee.putreg(v, RBP, 64, 50505050)
vee.putreg(v, RSI, 64, 50505050)
vee.putreg(v, RDI, 64, 50505050)
vee.putreg(v, R8, 64, 50505050)
vee.putreg(v, R9, 64, 50505050)
vee.putreg(v, R10, 64, 50505050)
vee.putreg(v, R11, 64, 50505050)
vee.putreg(v, R12, 64, 50505050)
vee.putreg(v, R13, 64, 50505050)
vee.putreg(v, R14, 64, 50505050)
vee.putreg(v, R15, 64, 50505050)
end
function onPost(v)
rip = vee.getreg(v, RIP, 64)
if rip == nil then
return false
end
if rip == 50505050 and vee.getexit(v) == Call then
return true
end
return false
end
vee.register(onPre, onPost)
|
al MAX_LONG_4BYTE = 1 << 32
local MIN_INT = -2147483648
local MAX_INT = 2147483647
local MIN_LONG = 0x8000000000000000
local MAX_LONG = 0x7fffffffffffffff
local MIN_LONG_STRING = "-9223372036854775808"
--The natural logarithm of 2.
local LN2 = 0.6931471805599453
Long = {}
function Long:new(low, high)
local obj = {
low = low & 0xFFFFFFFF,
high = high & 0xFFFFFFFF
}
setmetatable(obj, self)
self.__index = self
return obj
end
local function clone(value)
return Long:new(value.low, value.high)
end
local function fromBits(lowBits, highBits)
return Long:new(lowBits, highBits)
end
local function fromInt(value)
value = math.tointeger(value)
local param = 0
if value < 0 then
param = -1
end
return fromBits(value, param)
end
local ZERO = fromInt(0)
local ONE = fromInt(1)
local NEG_ONE = fromInt(-1)
local MAX_VALUE = fromBits(0xFFFFFFFF, 0x7FFFFFFF)
local MIN_VALUE = fromBits(0, 0x80000000)
local function fromNumber(value)
if (value <= -MIN_LONG) then
return clone(MIN_VALUE)
end
if (value + 1 >= MAX_LONG) then
return clone(MAX_VALUE)
end
if (value < 0) then
return fromNumber(-value):negate()
end
return fromBits(math.floor((value % MAX_LONG_4BYTE)) | 0, math.floor(value / MAX_LONG_4BYTE) | 0)
end
function Long:fromString(str, radix)
if type(radix) == "nil" then
radix = 10
end
if (type(str) ~= "string") then
error("str不是string类型参数")
end
--进制必须在2到36
if radix < 2 or 36 < radix then
error("range radix error")
end
local p = string.find(str, "-")
if p ~= nil then
if (p > 1) then
error("interior hyphen")
end
if (p == 1) then
return Long:fromString(string.sub(str, 2), radix):negate()
end
end
local radixToPower = fromNumber(radix ^ 8)
local result = clone(ZERO)
str = tostring(str)
for i = 1, #str, 8 do
local size = math.min(8, #str - i + 1)
if (size < 8) then
local value = tonumber(string.sub(str, i), radix)
local power = fromNumber(radix ^ size)
result = result:multiply(power):add(fromNumber(value))
else
local value = tonumber(string.sub(str, i, i + 7), radix)
result = result:multiply(radixToPower):add(fromNumber(value))
end
end
return result
end
--转为10进制的string符号的long
function Long:toString()
local radix = 10
if (Long:isZero()) then
return "0"
end
if (self:isNegative()) then
if (self:equals(MIN_VALUE)) then
return MIN_LONG_STRING
else
return '-' .. self:negate():toString(radix)
end
end
local radixToPower = fromNumber(radix ^ 6)
local rem = self
local result = ''
while (true) do
local remDiv = rem:divide(radixToPower)
local digits = tostring(rem:subtract(remDiv:multiply(radixToPower)):toInt() & 0xFFFFFFFF)
rem = remDiv
if (rem:isZero()) then
return digits .. result
else
while (#digits < 6) do
digits = '0' .. digits
end
result = '' .. digits .. result
end
end
end
--Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa).
function Long:toNumber()
return self.high * MAX_LONG_4BYTE + self.low
end
--Converts the Long to a 32 bit integer, assuming it is a 32 bit integer.
function Long:toInt()
return self.low
end
function Long:isNegative()
return (self.high & 0x80000000) ~= 0
end
function Long:negate()
if self:equals(MIN_VALUE) then
return clone(MIN_VALUE)
end
--正数转为负数的二进制编码,取反加1
local notSelf = fromBits(~self.low, ~self.high)
return notSelf:add(ONE)
end
function Long:equals(other)
return self.high == other.high and self.low == other.low
end
function Long:isZero()
return self.high == 0 and self.low == 0
end
function Long:add(addend)
local a48 = (self.high >> 16)
local a32 = (self.high & 0xFFFF)
local a16 = (self.low >> 16)
local a00 = (self.low & 0xFFFF)
local b48 = (addend.high >> 16)
local b32 = (addend.high & 0xFFFF)
local b16 = (addend.low >> 16)
local b00 = (addend.low & 0xFFFF)
local c48 = 0
local c32 = 0
local c16 = 0
local c00 = 0
c00 = c00 + a00 + b00
c16 = c16 + (c00 >> 16)
c00 = (c00 & 0xFFFF)
c16 = c16 + a16 + b16
c32 = c32 + (c16 >> 16)
c16 = (c16 & 0xFFFF)
c32 = c32 + a32 + b32
c48 = c48 + (c32 >> 16)
c32 = (c32 & 0xFFFF)
c48 = c48 + a48 + b48
c48 = (c48 & 0xFFFF)
return fromBits((c16 << 16) | c00, (c48 << 16) | c32)
end
function Long:subtract(subtrahend)
return self:add(subtrahend:negate())
end
function Long:multiply(multiplier)
if (self:isZero()) then
return clone(ZERO)
end
if (multiplier:isZero()) then
return clone(ZERO)
end
local a48 = (self.high >> 16)
local a32 = (self.high & 0xFFFF)
local a16 = (self.low >> 16)
local a00 = (self.low & 0xFFFF)
local b48 = (multiplier.high >> 16)
local b32 = (multiplier.high & 0xFFFF)
local b16 = (multiplier.low >> 16)
local b00 = (multiplier.low & 0xFFFF)
local c48 = 0
local c32 = 0
local c16 = 0
local c00 = 0
c00 = c00 + a00 * b00
c16 = c16 + (c00 >> 16)
c00 = c00 & 0xFFFF
c16 = c16 + a16 * b00
c32 = c32 + (c16 >> 16)
c16 = c16 & 0xFFFF
c16 = c16 + a00 * b16
c32 = c32 + (c16 >> 16)
c16 = c16 & 0xFFFF
c32 = c32 + a32 * b00
c48 = c48 + (c32 >> 16)
c32 = c32 & 0xFFFF
c32 = c32 + a16 * b16
c48 = c48 + (c32 >> 16)
c32 = c32 & 0xFFFF
c32 = c32 + a00 * b32
c48 = c48 + (c32 >> 16)
c32 = c32 & 0xFFFF
c48 = c48 + a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48
c48 = c48 & 0xFFFF
return fromBits((c16 << 16) | c00, (c48 << 16) | c32)
end
function Long:divide(divisor)
if (divisor:isZero()) then
error('division by zero')
end
if (self:isZero()) then
return clone(ZERO)
end
local approx
local rem
local res
if (self:equals(MIN_VALUE)) then
if (divisor:equals(ONE) or divisor:equals(NEG_ONE)) then
return clone(MIN_VALUE)
elseif (divisor:equals(MIN_VALUE)) then
return clone(ONE)
else
local halfThis = self:shiftRight(1)
approx = halfThis:divide(divisor):shiftLeft(1)
if (approx:equals(ZERO)) then
if (divisor:isNegative()) then
return clone(ONE)
else
return clone(NEG_ONE)
end
else
rem = self:subtract(divisor:multiply(approx))
res = approx:add(rem:divide(divisor))
return res
end
end
elseif (divisor:equals(MIN_VALUE)) then
return clone(ZERO)
end
if (self:isNegative()) then
if (divisor:isNegative()) then
return self:neg():divide(divisor:negate())
end
return self:negate():divide(divisor):negate()
elseif (divisor:isNegative()) then
return self:divide(divisor:negate()):negate()
end
res = clone(ZERO)
rem = self
while (rem:greaterThanOrEqual(divisor)) do
approx = math.max(1, math.floor(rem:toNumber() / divisor:toNumber()))
local log2 = math.ceil(math.log(approx) / LN2)
local delta = 1
if log2 <= 48 then
delta = 2 ^ (log2 - 48)
end
local approxRes = fromNumber(approx)
local approxRem = approxRes:multiply(divisor)
while (approxRem:isNegative() or approxRem:greaterThan(rem)) do
approx = approx - delta
approxRes = fromNumber(approx)
approxRem = approxRes:multiply(divisor)
end
if (approxRes:isZero()) then
approxRes = clone(ONE)
end
res = res:add(approxRes)
rem = rem:subtract(approxRem)
end
return res
end
function shiftRight(numBits)
numBits = numBits & 63
if (numBits == 0) then
return self
elseif (numBits < 32) then
return fromBits((self.low >> numBits) | (self.high << (32 - numBits)), self.high >> numBits)
else
if (self.high >= 0) then
return fromBits(self.high >> (numBits - 32), 0)
else
return fromBits(self.high >> (numBits - 32), -1)
end
end
end
function shiftLeft(numBits)
numBits = numBits & 63
if (numBits == 0) then
return self
elseif (numBits < 32) then
return fromBits(self.low << numBits, (self.high << numBits) | (self.low >> (32 - numBits)))
else
return fromBits(0, self.low << (numBits - 32))
end
end
function Long:compare(other)
if (self:equals(other)) then
return 0
end
local thisNeg = self:isNegative()
local otherNeg = other:isNegative()
if (thisNeg and not (otherNeg)) then
return -1
end
if (not (thisNeg) and otherNeg) then
return 1
end
if self:subtract(other):isNegative() then
return -1
else
return 1
end
end
function Long:greaterThanOrEqual(other)
return self:compare(other) >= 0
end
function Long:greaterThan(other)
return self:compare(other) > 0
end
function Long:encodeZigzagLong()
local mask = self.high >> 31
if mask == 1 then
self.high = ((self.high << 1 | self.low >> 31) ~ 0xFFFFFFFF) & 0xFFFFFFFF
self.low = ((self.low << 1 | mask) ~ 0xFFFFFFFE) & 0xFFFFFFFF
else
self.high = (self.high << 1 | self.low >> 31) & 0xFFFFFFFF
self.low = (self.low << 1) & 0xFFFFFFFF
end
return self
end
function Long:decodeZigzagLong()
local mask = self.low & 1
if mask == 1 then
self.low = (((self.low >> 1) | (self.high << 31)) ~ 0xFFFFFFFF) & 0xFFFFFFFF
self.high = ((self.high >> 1 | (0x80000000)) ~ 0x7FFFFFFF) & 0xFFFFFFFF
else
self.low = ((self.low >> 1) | (self.high << 31)) & 0xFFFFFFFF
self.high = (self.high >> 1) & 0xFFFFFFFF
end
return self
end
function Long:writeLong(byteBuffer, longValue)
if type(longValue) == "string" then
local len = #longValue
if len <= 11 then
local num = tonumber(longValue)
if (MIN_INT <= num) and (num <= MAX_INT) then
byteBuffer:writeInt(num)
return
end
end
end
if type(longValue) == number then
if (MIN_INT <= longValue) and (longValue <= MAX_INT) then
byteBuffer:writeInt(tonumber(longValue))
return
end
end
--写入Long
local value = Long:fromString(longValue)
value:encodeZigzagLong()
local count = 0
while (value.high ~= 0) do
byteBuffer:writeByte(value.low & 127 | 128)
value.low = ((value.low >> 7) | (value.high << 25))
value.high = (value.high >> 7)
count = count + 7
end
while (value.low > 127) do
if count >= 56 then
byteBuffer:writeByte(value.low)
return
end
byteBuffer:writeByte(value.low & 127 | 128)
value.low = value.low >> 7
count = count + 7
end
byteBuffer:writeByte(value.low)
end
local function fromByteBuffer(byteBuffer)
local bits = Long:new(0, 0)
local count = #byteBuffer
local i = 0
local pos = 1
if (count > 4) then
--先读入1到4位
while i < 4 do
bits.low = (bits.low | ((byteBuffer[pos] & 127) << (i * 7))) & 0xFFFFFFFF
i = i + 1
pos = pos + 1
end
--读第5位,第5位底位置读到low,高位置读到high
bits.low = (bits.low | ((byteBuffer[pos] & 127) << 28)) & 0xFFFFFFFF
bits.high = (bits.high | ((byteBuffer[pos] & 127) >> 4)) & 0xFFFFFFFF
if (byteBuffer[pos] < 128) then
return bits
end
i = 0
pos = pos + 1
else
while i < 3 do
bits.low = (bits.low | ((byteBuffer[pos] & 127) << (i * 7))) & 0xFFFFFFFF
if (byteBuffer[pos] < 128) then
return bits
end
i = i + 1
pos = pos + 1
end
bits.low = (bits.low | ((byteBuffer[pos] & 127) << (i * 7))) & 0xFFFFFFFF
return bits
end
--读最后4位
while i < 4 do
if (pos == 9) then
bits.high = (bits.high | (byteBuffer[pos] << (i * 7 + 3))) & 0xFFFFFFFF
return bits
end
bits.high = (bits.high | ((byteBuffer[pos] & 127) << (i * 7 + 3))) & 0xFFFFFFFF
if (byteBuffer[pos] < 128) then
return bits
end
i = i + 1
pos = pos + 1
end
return bits
end
function Long:readLong(buffer)
local byteBuffer = {}
local b = buffer:readByte()
local count = 1
byteBuffer[count] = b
count = count + 1
if ((b & 0x80) ~= 0) then
b = buffer:readByte()
byteBuffer[count] = b
count = count + 1
if ((b & 0x80) ~= 0) then
b = buffer:readByte()
byteBuffer[count] = b
count = count + 1
if ((b & 0x80) ~= 0) then
b = buffer:readByte()
byteBuffer[count] = b
count = count + 1
if ((b & 0x80) ~= 0) then
b = buffer:readByte()
byteBuffer[count] = b
count = count + 1
if ((b & 0x80) ~= 0) then
b = buffer:readByte()
byteBuffer[count] = b
count = count + 1
if ((b & 0x80) ~= 0) then
b = buffer:readByte()
byteBuffer[count] = b
count = count + 1
if ((b & 0x80) ~= 0) then
b = buffer:readByte()
byteBuffer[count] = b
count = count + 1
if ((b & 0x80) ~= 0) then
b = buffer:readByte()
byteBuffer[count] = b
count = count + 1
end
end
end
end
end
end
end
end
local longValue = fromByteBuffer(byteBuffer)
longValue:decodeZigzagLong()
return longValue
end
return Long |
game.AddParticles("particles/tfa_fubar_muzzle.pcf")
game.AddParticles("particles/tfa_fubar_particles.pcf")
game.AddParticles("particles/tfa_fubar_particles_aq.pcf")
game.AddParticles("particles/tfa_fubar_particles_blu.pcf")
PrecacheParticleSystem("tfa_muzzle_fubar")
PrecacheParticleSystem("weapon_fubar_trail")
PrecacheParticleSystem("weapon_fubar_beam")
PrecacheParticleSystem("weapon_fubar_rings")
PrecacheParticleSystem("weapon_fubar_rail")
PrecacheParticleSystem("weapon_fubar_rail_end")
PrecacheParticleSystem("weapon_fubar_rail_noise")
PrecacheParticleSystem("tfa_muzzle_fubar_blu")
PrecacheParticleSystem("weapon_fubar_trail_blu")
PrecacheParticleSystem("weapon_fubar_beam_blu")
PrecacheParticleSystem("weapon_fubar_rings_blu")
PrecacheParticleSystem("weapon_fubar_rail_blu")
PrecacheParticleSystem("weapon_fubar_rail_end_blu")
PrecacheParticleSystem("weapon_fubar_rail_noise_blu")
PrecacheParticleSystem("tfa_muzzle_fubar_aq")
PrecacheParticleSystem("weapon_fubar_trail_aq")
PrecacheParticleSystem("weapon_fubar_beam_aq")
PrecacheParticleSystem("weapon_fubar_rings_aq")
PrecacheParticleSystem("weapon_fubar_rail_aq")
PrecacheParticleSystem("weapon_fubar_rail_end_aq")
PrecacheParticleSystem("weapon_fubar_rail_noise_aq")
sound.Add({
name = "TFA_FusionBlaster.1",
channel = CHAN_USER_BASE+10,
volume = 1.0,
sound = "weapons/tfa_fusionblaster/gunfire/sniper_military_fire_1.wav"
})
sound.Add({
name = "TFA_FusionBlaster.Draw",
channel = CHAN_USER_BASE+11,
volume = 1.0,
sound = "weapons/tfa_fusionblaster/gunother/sniper_military_deploy_1.wav"
})
sound.Add({
name = "TFA_FusionBlaster.BoltBack",
channel = CHAN_USER_BASE+11,
volume = 1.0,
sound = "weapons/tfa_fusionblaster/gunother/sniper_military_slideback_1.wav"
})
sound.Add({
name = "TFA_FusionBlaster.BoltForward",
channel = CHAN_USER_BASE+11,
volume = 1.0,
sound = "weapons/tfa_fusionblaster/gunother/sniper_military_slideforward_1.wav"
})
sound.Add({
name = "TFA_FusionBlaster.ClipOut",
channel = CHAN_USER_BASE+12,
volume = 1.0,
sound = "weapons/tfa_fusionblaster/gunother/sniper_military_clip_out_1.wav"
})
sound.Add({
name = "TFA_FusionBlaster.ClipIn",
channel = CHAN_USER_BASE+12,
volume = 1.0,
sound = "weapons/tfa_fusionblaster/gunother/sniper_military_clip_in_1.wav"
})
sound.Add({
name = "TFA_FusionBlaster.ClipLocked",
channel = CHAN_USER_BASE+12,
volume = 1.0,
sound = "weapons/tfa_fusionblaster/gunother/sniper_military_clip_locked_1.wav"
}) |
force_bread = {
minimumLevel = 0,
maximumLevel = -1,
customObjectName = "Ancient Force Bread",
directObjectTemplate = "object/tangible/loot/misc/mt_flatbread.iff",
craftingValues = {
},
customizationStringNames = {},
customizationValues = {}
}
addLootItemTemplate("force_bread", force_bread)
|
malkloc_bull = Creature:new {
objectName = "@mob/creature_names:malkloc_bull",
socialGroup = "malkloc",
faction = "",
level = 28,
chanceHit = 0.35,
damageMin = 240,
damageMax = 250,
baseXp = 2822,
baseHAM = 8200,
baseHAMmax = 10000,
armor = 0,
resists = {135,135,10,-1,-1,-1,10,150,-1},
meatType = "meat_herbivore",
meatAmount = 1000,
hideType = "hide_leathery",
hideAmount = 1000,
boneType = "bone_mammal",
boneAmount = 1000,
milk = 0,
tamingChance = 0, tamingChance = 0.25, ferocity = 0,
pvpBitmask = ATTACKABLE,
creatureBitmask = PACK + HERD,
optionsBitmask = AIENABLED,
diet = CARNIVORE,
templates = {"object/mobile/malkloc_bull.iff"},
hues = { 0, 1, 2, 3, 4, 5, 6, 7 },
scale = 1.05,
lootGroups = {},
weapons = {},
conversationTemplate = "",
attacks = {
{"stunattack",""}
}
}
CreatureTemplates:addCreatureTemplate(malkloc_bull, "malkloc_bull")
|
--!strict
--[=[
@class ChickynoidServer
@server
Server namespace for the Chickynoid package.
]=]
local DefaultConfigs = require(script.Parent.DefaultConfigs)
local Types = require(script.Parent.Types)
local TableUtil = require(script.Parent.Vendor.TableUtil)
local ServerCharacter = require(script.ServerCharacter)
local ServerTransport = require(script.ServerTransport)
local ChickynoidServer = {}
local ServerConfig = TableUtil.Copy(DefaultConfigs.DefaultServerConfig, true)
function ChickynoidServer.Setup()
-- TODO: Move this into a proper public method
ServerTransport._getRemoteEvent()
end
function ChickynoidServer.SetConfig(config: Types.IServerConfig)
local newConfig = TableUtil.Reconcile(config, DefaultConfigs.DefaultServerConfig)
ServerConfig = newConfig
print("Set server config to:", ServerConfig)
end
--[=[
Spawns a new Chickynoid character for the specified player.
@param player Player -- The player to spawn this Chickynoid for.
@return ServerCharacter -- New character instance made for this player.
]=]
function ChickynoidServer.SpawnForPlayerAsync(player: Player)
local character = ServerCharacter.new(player, ServerConfig)
return character
end
return ChickynoidServer
|
local Server = require 'server'
local TEsound = {}
local server = Server.getSingleton()
local soundList = {}
function TEsound.playSfx(file)
local msg = string.format("%s %s %s","broadcast","sound",file)
for k,v in pairs(server.clients) do
soundList[k] = soundList[k] or {}
table.insert(soundList[k],msg)
end
end
function TEsound.getSounds(entity)
local entitySounds = soundList[entity] or {}
soundList[entity] = {}
return entitySounds
end
return TEsound |
local zone_manager = require(script.ZoneManager).New()
local zone, zone_tag = zone_manager:CreateNewZone(Vector3.new(0, 12.5, 0), Vector3.new(25, 25, 25), false, 'Mald')
zone.OnPlayerEntered:Connect(function(player: Player)
print(player.Name, 'has entered zone #' .. zone_tag)
end)
zone.OnPlayerExited:Connect(function(player: Player)
print(player.Name, 'has left zone #' .. zone_tag)
end)
zone_manager:Start() |
local build_freqtable = function (data)
local freq = { }
for i = 1, #data do
local cur = string.sub (data, i, i)
local count = freq [cur] or 0
freq [cur] = count + 1
end
local nodes = { }
for w, f in next, freq do
nodes [#nodes + 1] = { word = w, freq = f }
end
table.sort (nodes, function (a, b) return a.freq > b.freq end) --- reverse order!
return nodes
end
local build_hufftree = function (nodes)
while true do
local n = #nodes
local left = nodes [n]
nodes [n] = nil
local right = nodes [n - 1]
nodes [n - 1] = nil
local new = { freq = left.freq + right.freq, left = left, right = right }
if n == 2 then return new end
--- insert new node at correct priority
local prio = 1
while prio < #nodes and nodes [prio].freq > new.freq do
prio = prio + 1
end
table.insert (nodes, prio, new)
end
end
local print_huffcodes do
local rec_build_huffcodes
rec_build_huffcodes = function (node, bits, acc)
if node.word == nil then
rec_build_huffcodes (node.left, bits .. "0", acc)
rec_build_huffcodes (node.right, bits .. "1", acc)
return acc
else --- leaf
acc [#acc + 1] = { node.freq, node.word, bits }
end
return acc
end
print_huffcodes = function (root)
local codes = rec_build_huffcodes (root, "", { })
table.sort (codes, function (a, b) return a [1] < b [1] end)
print ("frequency\tword\thuffman code")
for i = 1, #codes do
print (string.format ("%9d\t‘%s’\t“%s”", table.unpack (codes [i])))
end
end
end
local huffcode = function (data)
local nodes = build_freqtable (data)
local huff = build_hufftree (nodes)
print_huffcodes (huff)
return 0
end
return huffcode "this is an example for huffman encoding"
|
require("indent_blankline").setup {
indentLine_enabled = 1,
char = "▏",
filetype_exclude = {
"help", "terminal", "dashboard", "packer", "lspinfo", "TelescopePrompt",
"TelescopeResults", "startify", "dashboard", "dotooagenda", "log",
"fugitive", "gitcommit", "packer", "vimwiki", "markdown", "txt",
"vista", "help", "todoist", "NvimTree", "peekaboo", "git",
"TelescopePrompt", "undotree", "flutterToolsOutline","lsp-installer", ""
},
buftype_exclude = {"terminal"},
show_trailing_blankline_indent = false,
show_first_indent_level = false
}
|
local STACK = require("constraint/stack")
local Throw = require("util/throw")
-- NOTE: Index start from 1 in Lua API
local Stack = {
-- virtual stack
slots = nil,
_top = nil,
-- call info
state = nil,
closure = nil,
varargs = nil,
openuvs = nil,
pc = nil,
prev = nil,
}
function Stack:new(capacity, state)
Stack.__index = Stack
self = setmetatable({}, Stack)
self.slots = {}
for i = 1, capacity do
self.slots[i] = self.slots
end
self._top = 0
self.state = state
self.openuvs = {}
self.pc = 0
return self
end
function Stack:gettop()
return self._top
end
function Stack:settop(n)
self._top = n
end
function Stack:ensure(freenum)
for i = #self.slots + 1, self._top + freenum do
self.slots[i] = self.slots
end
end
function Stack:get(idx)
if idx < STACK.LUA_REGISTRYINDEX then
local uvidx = STACK.LUA_REGISTRYINDEX - idx
if self.closure == nil or uvidx > self.closure.uvnum then
return nil
else
local uv = self.closure.upvalues[uvidx]
if uv.stk ~= nil then
return uv.stk:get(uv.idx + 1)
else
return uv.val
end
end
elseif idx == STACK.LUA_REGISTRYINDEX then
return self.state.registry
end
if not self:isValid(idx) then
Throw:error("[Stack:get ERROR] Invalid index!")
end
local absIdx = self:absIndex(idx)
local val = self.slots[absIdx]
if val == self.slots then
return nil
else
return val
end
end
function Stack:set(idx, val)
if idx < STACK.LUA_REGISTRYINDEX then
local uvidx = STACK.LUA_REGISTRYINDEX - idx
if self.closure == nil or uvidx > self.closure.uvnum then
return
else
local uv = self.closure.upvalues[uvidx]
if uv.stk ~= nil then
uv.stk:set(uv.idx + 1, val)
else
uv.val = val
end
return
end
elseif idx == STACK.LUA_REGISTRYINDEX then
self.state.registry = val
return
end
if not self:isValid(idx) then
Throw:error("[Stack:set ERROR] Invalid index! (%d)", idx)
end
local absIdx = self:absIndex(idx)
if val == nil then
self.slots[absIdx] = self.slots
else
self.slots[absIdx] = val
end
end
function Stack:push(val)
if self._top == #self.slots then
Throw:error("[Stack:push ERROR] Stack overflow!")
end
self._top = self._top + 1
if val == nil then
self.slots[self._top] = self.slots
else
self.slots[self._top] = val
end
end
function Stack:pushN(vals, n)
if n < 0 then
n = #vals
end
for i = 1, n do
self:push(vals[i])
end
end
function Stack:pop()
if self._top < 1 then
Throw:error("[Stack:pop ERROR] Stack underflow!")
end
local val = self.slots[self._top]
self.slots[self._top] = self.slots
self._top = self._top - 1
if val == self.slots then
return nil
else
return val
end
end
function Stack:popN(n)
local vals = {}
for i = n, 1, -1 do
vals[i] = self:pop()
end
return vals
end
function Stack:absIndex(idx)
if idx >= 0 or idx <= STACK.LUA_REGISTRYINDEX then
return idx
end
return self._top + idx + 1
end
function Stack:isValid(idx)
if idx < STACK.LUA_REGISTRYINDEX then
local uvidx = STACK.LUA_REGISTRYINDEX - idx
-- Upvalue index "uvidx" start from 0 but we stored it from 1
return self.closure ~= nil and uvidx <= self.closure.uvnum
elseif idx == STACK.LUA_REGISTRYINDEX then
return true
end
local absIdx = self:absIndex(idx)
local a = absIdx >= 1 and absIdx <= self._top
if a == false then
print("fffffffffffffff", idx, absIdx, self._top)
end
return a
end
function Stack:reverse(i, j)
while i < j do
local vali, valj = self.slots[i], self.slots[j]
self.slots[i], self.slots[j] = valj, vali
i = i + 1
j = j - 1
end
end
return Stack
|
-- ============================================================================
--
-- CommandItems Tab (View)
-- Tab to preview and purchase rights to commands
--
-- ============================================================================
-- ============================================================================
-- ----------------------------------------------------------------------------
-- Initialisation
-- ----------------------------------------------------------------------------
-- ============================================================================
local SGUI = Shine.GUI
CommandsTab = {}
CommandsTab.CurrentCredits = 0
function CommandsTab.OnInit( Panel, Data )
CommandsTab.Label = SGUI:Create( "Label", Panel )
CommandsTab.Label:SetFont( Fonts.kAgencyFB_Small )
CommandsTab.Label:SetText( "Command Items Menu" )
CommandsTab.Label:SetPos( Vector( 16, 24, 0 ) )
CommandsTab.CreditBalanceLabel = SGUI:Create( "Label", Panel )
CommandsTab.CreditBalanceLabel:SetFont( Fonts.kAgencyFB_Small )
CommandsTab.CreditBalanceLabel:SetText( "Available Credits: " .. CommandsTab.CurrentCredits)
CommandsTab.CreditBalanceLabel:SetPos( Vector( 350, 25, 0 ) )
if Data and Data.ImportantInformation then
return true
end
end
function CommandsTab.OnCleanup( Panel )
CommandsTab.Label = nil
CommandsTab.CreditBalanceLabel = nil
return { ImportantInformation = true }
end
function CommandsTab.Update ( Data, NewCurrentCredits)
CommandsTab.CurrentCredits = NewCurrentCredits
return true
end
return CommandsTab
|
local levels = {
[1] = 100,
[2] = 200,
[3] = 300,
[4] = 400,
[5] = 500,
[6] = 600,
[7] = 700,
[8] = 800,
[9] = 900,
[10] = 1000,
[11] = 1100,
[12] = 1200,
[13] = 1300,
[14] = 1400,
[15] = 1500,
[16] = 1600,
[17] = 1700,
[18] = 1800,
[19] = 1900,
[20] = 2000,
[21] = 2100,
[22] = 2200,
[23] = 2300,
[24] = 2400,
[25] = 2500,
[26] = 2600,
[27] = 2700,
[28] = 2800,
[29] = 2900,
[30] = 3000,
[31] = 3100,
[32] = 3200,
[33] = 3300,
[34] = 3400,
[35] = 3500,
[36] = 3600,
[37] = 3700,
[38] = 3800,
[39] = 3900,
[40] = 4000,
[41] = 4100,
[42] = 4200,
[43] = 4300,
[44] = 4400,
[45] = 4500,
[46] = 4600,
[47] = 4700,
[48] = 4800,
[49] = 4900,
[50] = 5000,
[51] = 5100,
[52] = 5200,
[53] = 5300,
[54] = 5400,
[55] = 5500,
[56] = 5600,
[57] = 5700,
[58] = 5800,
[59] = 5900,
[60] = 6000,
[61] = 6100,
[62] = 6200,
[63] = 6300,
[64] = 6400,
[65] = 6500,
[66] = 6600,
[67] = 6700,
[68] = 6800,
[69] = 6900,
[70] = 7000,
[71] = 7100,
[72] = 7200,
[73] = 7300,
[74] = 7400,
[75] = 7500,
[76] = 7600,
[77] = 7700,
[78] = 7800,
[79] = 7900,
[80] = 8000,
[81] = 8100,
[82] = 8200,
[83] = 8300,
[84] = 8400,
[85] = 8500,
[86] = 8600,
[87] = 8700,
[88] = 8800,
[89] = 8900,
[90] = 9000,
[91] = 9100,
[92] = 9200,
[93] = 9300,
[94] = 9400,
[95] = 9500,
[96] = 9600,
[97] = 9700,
[98] = 9800,
[99] = 9900,
[100] = 10000,
[101] = 10100,
[102] = 10200,
[103] = 10300,
[104] = 10400,
[105] = 10500,
[106] = 10600,
[107] = 10700,
[108] = 10800,
[109] = 10900,
[110] = 11000,
[111] = 11100,
[112] = 11200,
[112] = 11300,
[113] = 11400,
[114] = 11500,
[115] = 11600,
[116] = 11700,
}
function checkLevel(player)
local playerExp = getElementData(player, "playerExp") or 0
local minExp = 9999
local level, exp = nil
for i=1, #levels do
exp = levels[i] - playerExp
if exp >= 0 and exp < minExp then
minExp = exp
level = i
if exp == 0 then
level = level + 1
end
end
end
setElementData(player, "nextLevel", minExp)
return level
end
function checkUP(player)
local playerLevel = checkLevel(player)
local expc = levels[playerLevel]
return expc
end
function checkExp(player)
local playerExp = getElementData(player, "playerExp") or 0
return playerExp
end
addEventHandler( "onClientElementDataChange", getRootElement(),
function (dataName)
if (getElementType ( source ) == "player" and dataName == "playerExp") then
local level = checkLevel(source)
if level ~= getElementData(source, "Level") then
setElementData(source, "Level", level)
end
end
end
)
function addXP(player, nexp)
if player and nexp then
local expa = (getElementData(player, "playerExp") or 0)
setElementData(player, "playerExp", expa + nexp)
end
end |
local gd = require 'gd'
local getFormat = function(path)
local file = io.open(path,"r");
if not file then return nil; end
local fileType = file:read(1):byte(1,1);
io.close(file);
--根据图片类型和路径生成gd对象
local ext = nil;
if fileType == 137 then -- png
ext = ".png"
elseif fileType == 71 then -- gif
ext = ".gif"
elseif fileType == 255 then--jpg
ext = ".jpg"
else
end
return ext;
end;
local getGdObj = function(path)
local fileType = getFormat(path);
if not fileType then
return nil;
end
local gdObj = nil;
if fileType == ".png" then -- png
gdObj = gd.createFromPng(path);
elseif fileType == ".gif" then -- gif
gdObj = gd.createFromGif(path);
elseif fileType == ".jpg" then--jpg
gdObj = gd.createFromJpeg(path);
else
end
return gdObj;
end
return {
getFormat = getFormat,
getGdObj = getGdObj
}
|
-- ======= Copyright (c) 2003-2011, Unknown Worlds Entertainment, Inc. All rights reserved. =======
--
-- lua\DamageTypes.lua
--
-- Created by: Andreas Urwalek (andi@unknownworlds.com)
--
-- Contains all rules regarding damage types. New types behavior can be defined BuildDamageTypeRules().
--
-- Important callbacks for classes:
--
-- ComputeDamageAttackerOverride(attacker, damage, damageType)
-- ComputeDamageAttackerOverrideMixin(attacker, damage, damageType)
--
-- for target:
-- ComputeDamageOverride(attacker, damage, damageType)
-- ComputeDamageOverrideMixin(attacker, damage, damageType)
-- GetArmorUseFractionOverride(damageType, armorFractionUsed)
-- GetReceivesStructuralDamage(damageType)
-- GetReceivesBiologicalDamage(damageType)
-- GetHealthPerArmorOverride(damageType, healthPerArmor)
--
--
--
-- Damage types
--
-- In NS2 - Keep simple and mostly in regard to armor and non-armor. Can't see armor, but players
-- and structures spawn with an intuitive amount of armor.
-- http://www.unknownworlds.com/ns2/news/2010/6/damage_types_in_ns2
--
-- Normal - Regular damage
-- Light - Reduced vs. armor
-- Heavy - Extra damage vs. armor
-- Puncture - Extra vs. players
-- Structural - Double against structures
-- GrenadeLauncher - Double against structures with 20% reduction in player damage
-- Flamethrower - 5% increase for player damage from structures
-- Gas - Breathing targets only (Spores, Nerve Gas GL). Ignores armor.
-- StructuresOnly - Doesn't damage players or AI units (ARC)
-- Falling - Ignores armor for humans, no damage for some creatures or exosuit
-- Door - Like Structural but also does damage to Doors. Nothing else damages Doors.
-- Flame - Like normal but catches target on fire and plays special flinch animation
-- Corrode - deals normal damage to structures but armor only to non structures
-- ArmorOnly - always affects only armor
-- Biological - only organic, biological targets (non mechanical)
-- StructuresOnlyLight - same as light damage but will not harm players or units which are not valid for structural damage
--
-- ========= For more information, visit us at http://www.unknownworlds.com =====================
--globals for balance-extension tweaking
kAlienVampirismNotHealArmor = false
kAlienCrushDamagePercentByLevel = 0.07 --Max 21%
kAlienFocusDamageBonusAtMax = 0.5
kGorgeSpitDamageBonusAtMax = 0.5 -- spit does 1.5 damage instead of 2, but will fire faster to compensate
kStabDamageBonusAtMax = kAlienFocusDamageBonusAtMax -- anticipating this will need tweaking later
kAlienVampirismHealingScalarPerLevel = 0.3334
kLifeformVampirismScalars = {} --FIXME change to Weapon/Doer classnames, not lifeform
kLifeformVampirismScalars["Skulk"] = 14
kLifeformVampirismScalars["Gorge"] = 15
kLifeformVampirismScalars["LerkBite"] = 10
kLifeformVampirismScalars["LerkSpikes"] = 0
kLifeformVampirismScalars["Fade"] = 20
kLifeformVampirismScalars["Onos"] = 40 --Stomp?
-- utility functions
function GetReceivesStructuralDamage(entity)
return entity.GetReceivesStructuralDamage and entity:GetReceivesStructuralDamage()
end
function GetReceivesBiologicalDamage(entity)
return entity.GetReceivesBiologicalDamage and entity:GetReceivesBiologicalDamage()
end
function NS2Gamerules_GetUpgradedDamageScalar( attacker )
if GetHasTech(attacker, kTechId.Weapons3, true) then
return kWeapons3DamageScalar
elseif GetHasTech(attacker, kTechId.Weapons2, true) then
return kWeapons2DamageScalar
elseif GetHasTech(attacker, kTechId.Weapons1, true) then
return kWeapons1DamageScalar
end
return 1.2
end
-- Use this function to change damage according to current upgrades
function NS2Gamerules_GetUpgradedDamage(attacker, doer, damage, damageType, hitPoint)
local damageScalar = 1
if attacker ~= nil then
-- Damage upgrades only affect weapons, not ARCs, Sentries, MACs, Mines, etc.
if doer.GetIsAffectedByWeaponUpgrades and doer:GetIsAffectedByWeaponUpgrades() then
damageScalar = NS2Gamerules_GetUpgradedDamageScalar( attacker )
end
end
return damage * damageScalar
end
--TODO Clean up / simplify
function NS2Gamerules_GetAlienVampiricLeechFactor( attacker, doer, damageType, veilLevel )
local leechFactor = 0
local attackerClass = attacker:GetClassName()
local doerClassName = doer:GetClassName()
if attackerClass == "Lerk" then
attackerClass = doerClassName
if attackerClass == "SporeCloud" then
return 0
end
--Note: this will need to be adjusted should Lerk Spikes damage type ever change
if attackerClass == "LerkBite" and damageType == kDamageType.Puncture then --Spikes
attackerClass = "LerkSpikes"
end
elseif attackerClass == "Gorge" then
if doerClassName == "DotMarker" or doerClassName == "Babbler" or doerClassName == "Hydra" or damageType == kDamageType.Biological then
return 0
end
elseif attackerClass == "Onos" and doerClassName == "Shockwave" then
return 0
elseif attackerClass == "Skulk" and ( doerClassName == "Parasite" or doerClassName == "XenocideLeap" )then
return 0
end
local baseLeechAmount = kLifeformVampirismScalars[attackerClass]
if baseLeechAmount ~= nil and type(baseLeechAmount) == "number" then
leechFactor = baseLeechAmount * ( veilLevel * kAlienVampirismHealingScalarPerLevel )
end
return leechFactor
end
--Utility function to apply chamber-upgraded modifications to alien damage
--Note: this should _always_ be called BEFORE damage-type specific modifications are done (i.e. Light vs Normal vs Structural, etc)
function NS2Gamerules_GetUpgradedAlienDamage( target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint, weapon )
if attacker:GetHasUpgrade( kTechId.Crush ) then --CragHive
local shellLevel = GetShellLevel( kTeam2Index )
if shellLevel > 0 then
if target:isa("Exo") or target.GetReceivesStructuralDamage and target:GetReceivesStructuralDamage(damageType) then
damage = damage + ( damage * ( shellLevel * kAlienCrushDamagePercentByLevel ) )
elseif target:isa("Player") then
armorFractionUsed = kBaseArmorUseFraction + ( shellLevel * kAlienCrushDamagePercentByLevel )
end
end
end
if Server then
if attacker:GetHasUpgrade( kTechId.Vampirism ) and target:isa("Player") then --ShadeHive
local veilLevel = GetVeilLevel( kTeam2Index )
if veilLevel > 0 then
local leechedHealth = NS2Gamerules_GetAlienVampiricLeechFactor( attacker, doer, damageType, veilLevel )
if attacker:GetIsAlive() then
attacker:AddHealth( leechedHealth, true, kAlienVampirismNotHealArmor ) --TODO Find better method/location to perform this
end
end
end
end
if attacker:GetHasUpgrade( kTechId.Focus ) and DoesFocusAffectAbility(weapon) then
local veilLevel = GetVeilLevel( kTeam2Index )
local damageBonus = kAlienFocusDamageBonusAtMax
if weapon == kTechId.Spit then -- gorge spit is a special case
damageBonus = kGorgeSpitDamageBonusAtMax
elseif weapon == kTechId.Stab then -- preparing for anticipated changes...
damageBonus = kStabDamageBonusAtMax
end
damage = damage * (1 + (veilLevel/3) * damageBonus) --1.0, 1.333, 1.666, 2
end
--!!!Note: if more than damage and armor fraction modified, be certain the calling-point of this function is updated
return damage, armorFractionUsed
end
-- only certain abilities should work with focus
-- global so mods can easily change this
function InitializeFocusAbilities()
kFocusAbilities = {}
kFocusAbilities[kTechId.Bite] = true
kFocusAbilities[kTechId.Spit] = true
kFocusAbilities[kTechId.LerkBite] = true
kFocusAbilities[kTechId.Swipe] = true
kFocusAbilities[kTechId.Stab] = true
kFocusAbilities[kTechId.Gore] = true
end
function DoesFocusAffectAbility(abilityTech)
if not kFocusAbilities then
InitializeFocusAbilities()
end
if kFocusAbilities[abilityTech] == true then
return true
end
return false
end
function Gamerules_GetDamageMultiplier()
if Server and Shared.GetCheatsEnabled() then
return GetGamerules():GetDamageMultiplier()
end
return 1
end
kDamageType = enum(
{
'Normal', 'Light', 'Heavy', 'Puncture',
'Structural', 'StructuralHeavy', 'Splash',
'Gas', 'NerveGas', 'StructuresOnly',
'Falling', 'Door', 'Flame', 'Infestation',
'Corrode', 'ArmorOnly', 'Biological', 'StructuresOnlyLight',
'Spreading', 'GrenadeLauncher', 'MachineGun'
})
-- Describe damage types for tooltips
kDamageTypeDesc = {
"",
"Light damage: reduced vs. armor",
"Heavy damage: extra vs. armor",
"Puncture damage: extra vs. players",
"Structural damage: Double vs. structures",
"StructuralHeavy damage: Double vs. structures and double vs. armor",
"Gas damage: affects breathing targets only",
"NerveGas damage: affects biological units, player will take only armor damage",
"Structures only: Doesn't damage players or AI units",
"Falling damage: Ignores armor for humans, no damage for aliens",
"Door: Can also affect Doors",
"Corrode damage: Damage structures or armor only for non structures",
"Armor damage: Will never reduce health",
"StructuresOnlyLight: Damages structures only, light damage.",
"Splash: same as structures only but always affects ARCs (friendly fire).",
"Spreading: Does less damage against small targets.",
"GrenadeLauncher: Double structure damage, 20% reduction in player damage",
"MachineGun: Deals 1.5x amount of base damage against players"
}
kSpreadingDamageScalar = 0.75
kBaseArmorUseFraction = 0.7
kExosuitArmorUseFraction = 1 -- exos have no health
kStructuralDamageScalar = 2
kPuncturePlayerDamageScalar = 2
kGLPlayerDamageReduction = 0.5
kFTStructureDamage = 1.125
kLightHealthPerArmor = 4
kHealthPointsPerArmor = 2
kHeavyHealthPerArmor = 1
kFlameableMultiplier = 2.5
kCorrodeDamagePlayerArmorScalar = 0.12
kCorrodeDamageExoArmorScalar = 0.4
kStructureLightHealthPerArmor = 9
kStructureLightArmorUseFraction = 0.9
-- deal only 33% of damage to friendlies
kFriendlyFireScalar = 0.33
local function ApplyDefaultArmorUseFraction(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
return damage, kBaseArmorUseFraction, healthPerArmor
end
local function ApplyHighArmorUseFractionForExos(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
if target:isa("Exo") then
armorFractionUsed = kExosuitArmorUseFraction
end
return damage, armorFractionUsed, healthPerArmor
end
local function ApplyDefaultHealthPerArmor(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
return damage, armorFractionUsed, kHealthPointsPerArmor
end
local function DoubleHealthPerArmor(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
return damage, armorFractionUsed, healthPerArmor * (kLightHealthPerArmor / kHealthPointsPerArmor)
end
local function HalfHealthPerArmor(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
return damage, armorFractionUsed, healthPerArmor * (kHeavyHealthPerArmor / kHealthPointsPerArmor)
end
local function ApplyAttackerModifiers(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
damage = NS2Gamerules_GetUpgradedDamage(attacker, doer, damage, damageType, hitPoint)
damage = damage * Gamerules_GetDamageMultiplier()
if attacker and attacker.ComputeDamageAttackerOverride then
damage = attacker:ComputeDamageAttackerOverride(attacker, damage, damageType, doer, hitPoint)
end
if doer and doer.ComputeDamageAttackerOverride then
damage = doer:ComputeDamageAttackerOverride(attacker, damage, damageType)
end
if attacker and attacker.ComputeDamageAttackerOverrideMixin then
damage = attacker:ComputeDamageAttackerOverrideMixin(attacker, damage, damageType, doer, hitPoint)
end
if doer and doer.ComputeDamageAttackerOverrideMixin then
damage = doer:ComputeDamageAttackerOverrideMixin(attacker, damage, damageType, doer, hitPoint)
end
return damage, armorFractionUsed, healthPerArmor
end
local function ApplyTargetModifiers(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
-- The host can provide an override for this function.
if target.ComputeDamageOverride then
damage = target:ComputeDamageOverride(attacker, damage, damageType, hitPoint)
end
-- Used by mixins.
if target.ComputeDamageOverrideMixin then
damage = target:ComputeDamageOverrideMixin(attacker, damage, damageType, hitPoint)
end
if target.GetArmorUseFractionOverride then
armorFractionUsed = target:GetArmorUseFractionOverride(damageType, armorFractionUsed, hitPoint)
end
if target.GetHealthPerArmorOverride then
healthPerArmor = target:GetHealthPerArmorOverride(damageType, healthPerArmor, hitPoint)
end
local damageTable = {}
damageTable.damage = damage
damageTable.armorFractionUsed = armorFractionUsed
damageTable.healthPerArmor = healthPerArmor
if target.ModifyDamageTaken then
target:ModifyDamageTaken(damageTable, attacker, doer, damageType, hitPoint)
end
return damageTable.damage, damageTable.armorFractionUsed, damageTable.healthPerArmor
end
local function ApplyFriendlyFireModifier(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
if target and attacker and target ~= attacker and HasMixin(target, "Team") and HasMixin(attacker, "Team") and target:GetTeamNumber() == attacker:GetTeamNumber() then
damage = damage * kFriendlyFireScalar
end
return damage, armorFractionUsed, healthPerArmor
end
local function IgnoreArmor(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
return damage, 0, healthPerArmor
end
local function MaximizeArmorUseFraction(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
return damage, 1, healthPerArmor
end
local function MultiplyForStructures(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
if target.GetReceivesStructuralDamage and target:GetReceivesStructuralDamage(damageType) then
if doer:isa("Flamethrower") then
damage = damage * kFTStructureDamage
else
damage = damage * kStructuralDamageScalar
end
end
return damage, armorFractionUsed, healthPerArmor
end
local function ReduceForPlayersDoubleStructure(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
if target.GetReceivesStructuralDamage and target:GetReceivesStructuralDamage(damageType) then
damage = damage * kStructuralDamageScalar
elseif target:isa("Player") then
damage = damage * kGLPlayerDamageReduction
end
return damage, armorFractionUsed, healthPerArmor
end
local function MultiplyForPlayers(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
return ConditionalValue(target:isa("Player") or target:isa("Exosuit"), damage * kPuncturePlayerDamageScalar, damage), armorFractionUsed, healthPerArmor
end
local function ReducedDamageAgainstSmall(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
if target.GetIsSmallTarget and target:GetIsSmallTarget() then
damage = damage * kSpreadingDamageScalar
end
return damage, armorFractionUsed, healthPerArmor
end
local function IgnoreHealthForPlayers(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
if target:isa("Player") then
local maxDamagePossible = healthPerArmor * target.armor
damage = math.min(damage, maxDamagePossible)
armorFractionUsed = 1
end
return damage, armorFractionUsed, healthPerArmor
end
local function IgnoreHealthForPlayersUnlessExo(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
if target:isa("Player") and not target:isa("Exo") then
local maxDamagePossible = healthPerArmor * target.armor
damage = math.min(damage, maxDamagePossible)
armorFractionUsed = 1
end
return damage, armorFractionUsed, healthPerArmor
end
local function IgnoreHealth(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
local maxDamagePossible = healthPerArmor * target.armor
damage = math.min(damage, maxDamagePossible)
return damage, 1, healthPerArmor
end
local function ReduceGreatlyForPlayers(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
if target:isa("Exo") or target:isa("Exosuit") then
damage = damage * kCorrodeDamageExoArmorScalar
elseif target:isa("Player") then
damage = damage * kCorrodeDamagePlayerArmorScalar
end
return damage, armorFractionUsed, healthPerArmor
end
local function IgnorePlayersUnlessExo(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
return ConditionalValue(target:isa("Player") and not target:isa("Exo") , 0, damage), armorFractionUsed, healthPerArmor
end
local function DamagePlayersOnly(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
return ConditionalValue(target:isa("Player") or target:isa("Exosuit"), damage, 0), armorFractionUsed, healthPerArmor
end
local function DamageAlienOnly(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
return ConditionalValue(HasMixin(target, "Team") and target:GetTeamType() == kAlienTeamType, damage, 0), armorFractionUsed, healthPerArmor
end
local function DamageStructuresOnly(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
if not target.GetReceivesStructuralDamage or not target:GetReceivesStructuralDamage(damageType) then
damage = 0
end
return damage, armorFractionUsed, healthPerArmor
end
local function IgnoreDoors(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
return ConditionalValue(target:isa("Door"), 0, damage), armorFractionUsed, healthPerArmor
end
local function DamageBiologicalOnly(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
if not target.GetReceivesBiologicalDamage or not target:GetReceivesBiologicalDamage(damageType) then
damage = 0
end
return damage, armorFractionUsed, healthPerArmor
end
local function DamageBreathingOnly(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
if not target.GetReceivesVaporousDamage or not target:GetReceivesVaporousDamage(damageType) then
damage = 0
end
return damage, armorFractionUsed, healthPerArmor
end
local function MultiplyFlameAble(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
if target.GetIsFlameAble and target:GetIsFlameAble(damageType) then
damage = damage * kFlameableMultiplier
end
return damage, armorFractionUsed, healthPerArmor
end
local function DoubleHealthPerArmorForStructures(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
if target.GetReceivesStructuralDamage and target:GetReceivesStructuralDamage(damageType) then
healthPerArmor = healthPerArmor * (kStructureLightHealthPerArmor / kHealthPointsPerArmor)
armorFractionUsed = kStructureLightArmorUseFraction
end
return damage, armorFractionUsed, healthPerArmor
end
local kMachineGunPlayerDamageScalar = 1.5
local function MultiplyForMachineGun(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
return ConditionalValue(target:isa("Player") or target:isa("Exosuit"), damage * kMachineGunPlayerDamageScalar, damage), armorFractionUsed, healthPerArmor
end
kDamageTypeGlobalRules = nil
kDamageTypeRules = nil
--[[
* Define any new damage type behavior in this function
--]]
local function BuildDamageTypeRules()
kDamageTypeGlobalRules = {}
kDamageTypeRules = {}
-- global rules
table.insert(kDamageTypeGlobalRules, ApplyDefaultArmorUseFraction)
table.insert(kDamageTypeGlobalRules, ApplyHighArmorUseFractionForExos)
table.insert(kDamageTypeGlobalRules, ApplyDefaultHealthPerArmor)
table.insert(kDamageTypeGlobalRules, ApplyAttackerModifiers)
table.insert(kDamageTypeGlobalRules, ApplyTargetModifiers)
table.insert(kDamageTypeGlobalRules, ApplyFriendlyFireModifier)
-- ------------------------------
-- normal damage rules
kDamageTypeRules[kDamageType.Normal] = {}
-- light damage rules
kDamageTypeRules[kDamageType.Light] = {}
table.insert(kDamageTypeRules[kDamageType.Light], DoubleHealthPerArmor)
-- ------------------------------
-- heavy damage rules
kDamageTypeRules[kDamageType.Heavy] = {}
table.insert(kDamageTypeRules[kDamageType.Heavy], HalfHealthPerArmor)
-- ------------------------------
-- Puncture damage rules
kDamageTypeRules[kDamageType.Puncture] = {}
table.insert(kDamageTypeRules[kDamageType.Puncture], MultiplyForPlayers)
-- ------------------------------
-- Spreading damage rules
kDamageTypeRules[kDamageType.Spreading] = {}
table.insert(kDamageTypeRules[kDamageType.Spreading], ReducedDamageAgainstSmall)
-- ------------------------------
-- structural rules
kDamageTypeRules[kDamageType.Structural] = {}
table.insert(kDamageTypeRules[kDamageType.Structural], MultiplyForStructures)
-- ------------------------------
-- Grenade Launcher rules
kDamageTypeRules[kDamageType.GrenadeLauncher] = {}
table.insert(kDamageTypeRules[kDamageType.GrenadeLauncher], ReduceForPlayersDoubleStructure)
-- ------------------------------
-- Machine Gun rules
kDamageTypeRules[kDamageType.MachineGun] = {}
table.insert(kDamageTypeRules[kDamageType.MachineGun], MultiplyForMachineGun)
-- ------------------------------
-- structural heavy rules
kDamageTypeRules[kDamageType.StructuralHeavy] = {}
table.insert(kDamageTypeRules[kDamageType.StructuralHeavy], HalfHealthPerArmor)
table.insert(kDamageTypeRules[kDamageType.StructuralHeavy], MultiplyForStructures)
-- ------------------------------
-- gas damage rules
kDamageTypeRules[kDamageType.Gas] = {}
table.insert(kDamageTypeRules[kDamageType.Gas], IgnoreArmor)
table.insert(kDamageTypeRules[kDamageType.Gas], DamageBreathingOnly)
-- ------------------------------
-- structures only rules
kDamageTypeRules[kDamageType.StructuresOnly] = {}
table.insert(kDamageTypeRules[kDamageType.StructuresOnly], DamageStructuresOnly)
-- ------------------------------
-- Splash rules
kDamageTypeRules[kDamageType.Splash] = {}
table.insert(kDamageTypeRules[kDamageType.Splash], DamageStructuresOnly)
-- ------------------------------
-- fall damage rules
kDamageTypeRules[kDamageType.Falling] = {}
table.insert(kDamageTypeRules[kDamageType.Falling], IgnoreArmor)
-- ------------------------------
-- Door damage rules
kDamageTypeRules[kDamageType.Door] = {}
table.insert(kDamageTypeRules[kDamageType.Door], MultiplyForStructures)
table.insert(kDamageTypeRules[kDamageType.Door], HalfHealthPerArmor)
-- ------------------------------
-- Flame damage rules
kDamageTypeRules[kDamageType.Flame] = {}
table.insert(kDamageTypeRules[kDamageType.Flame], MultiplyFlameAble)
table.insert(kDamageTypeRules[kDamageType.Flame], MultiplyForStructures)
-- ------------------------------
-- Corrode damage rules
kDamageTypeRules[kDamageType.Corrode] = {}
table.insert(kDamageTypeRules[kDamageType.Corrode], ReduceGreatlyForPlayers)
table.insert(kDamageTypeRules[kDamageType.Corrode], IgnoreHealthForPlayersUnlessExo)
-- ------------------------------
-- nerve gas rules
kDamageTypeRules[kDamageType.NerveGas] = {}
table.insert(kDamageTypeRules[kDamageType.NerveGas], DamageAlienOnly)
table.insert(kDamageTypeRules[kDamageType.NerveGas], IgnoreHealth)
-- ------------------------------
-- StructuresOnlyLight damage rules
kDamageTypeRules[kDamageType.StructuresOnlyLight] = {}
table.insert(kDamageTypeRules[kDamageType.StructuresOnlyLight], DoubleHealthPerArmorForStructures)
-- ------------------------------
-- ArmorOnly damage rules
kDamageTypeRules[kDamageType.ArmorOnly] = {}
table.insert(kDamageTypeRules[kDamageType.ArmorOnly], ReduceGreatlyForPlayers)
table.insert(kDamageTypeRules[kDamageType.ArmorOnly], IgnoreHealth)
-- ------------------------------
-- Biological damage rules
kDamageTypeRules[kDamageType.Biological] = {}
table.insert(kDamageTypeRules[kDamageType.Biological], DamageBiologicalOnly)
-- ------------------------------
end
-- applies all rules and returns damage, armorUsed, healthUsed
function GetDamageByType(target, attacker, doer, damage, damageType, hitPoint, weapon)
assert(target)
if not kDamageTypeGlobalRules or not kDamageTypeRules then
BuildDamageTypeRules()
end
-- at first check if damage is possible, if not we can skip the rest
if not CanEntityDoDamageTo(attacker, target, Shared.GetCheatsEnabled(), Shared.GetDevMode(), GetFriendlyFire(), damageType) then
return 0, 0, 0
end
local armorUsed = 0
local healthUsed = 0
local armorFractionUsed, healthPerArmor = 0
-- apply global rules at first
for _, rule in ipairs(kDamageTypeGlobalRules) do
damage, armorFractionUsed, healthPerArmor = rule(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
end
--Account for Alien Chamber Upgrades damage modifications (must be before damage-type rules)
if attacker:GetTeamType() == kAlienTeamType and attacker:isa("Player") then
damage, armorFractionUsed = NS2Gamerules_GetUpgradedAlienDamage( target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint, weapon )
end
-- apply damage type specific rules
for _, rule in ipairs(kDamageTypeRules[damageType]) do
damage, armorFractionUsed, healthPerArmor = rule(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
end
if damage > 0 and healthPerArmor > 0 then
-- Each point of armor blocks a point of health but is only destroyed at half that rate (like NS1)
-- Thanks Harimau!
local healthPointsBlocked = math.min(healthPerArmor * target.armor, armorFractionUsed * damage)
armorUsed = healthPointsBlocked / healthPerArmor
-- Anything left over comes off of health
healthUsed = damage - healthPointsBlocked
end
return damage, armorUsed, healthUsed
end |
local turtle = _G.turtle
local function doCommand(command, moves)
local function format(value)
if type(value) == 'boolean' then
if value then return 'true' end
return 'false'
end
if type(value) ~= 'table' then
return value
end
local str
for k,v in pairs(value) do
if not str then
str = '{ '
else
str = str .. ', '
end
str = str .. k .. '=' .. tostring(v)
end
if str then
str = str .. ' }'
else
str = '{ }'
end
return str
end
local function runCommand(fn, arg)
local r = { fn(arg) }
if r[2] then
print(format(r[1]) .. ': ' .. format(r[2]))
elseif r[1] then
print(format(r[1]))
end
return r[1]
end
local cmds = {
[ 's' ] = turtle.select,
[ 'rf' ] = turtle.refuel,
[ 'gh' ] = function() turtle.pathfind({ x = 0, y = 0, z = 0, heading = 0}) end,
}
local repCmds = {
[ 'u' ] = turtle.up,
[ 'd' ] = turtle.down,
[ 'f' ] = turtle.forward,
[ 'r' ] = turtle.turnRight,
[ 'l' ] = turtle.turnLeft,
[ 'ta' ] = turtle.turnAround,
[ 'el' ] = turtle.equipLeft,
[ 'er' ] = turtle.equipRight,
[ 'DD' ] = turtle.digDown,
[ 'DU' ] = turtle.digUp,
[ 'D' ] = turtle.dig,
[ 'p' ] = turtle.place,
[ 'pu' ] = turtle.placeUp,
[ 'pd' ] = turtle.placeDown,
[ 'b' ] = turtle.back,
[ 'gfl' ] = turtle.getFuelLevel,
[ 'gp' ] = turtle.getPoint,
[ 'R' ] = function() turtle.setPoint({x = 0, y = 0, z = 0, heading = 0}) return turtle.point end
}
if cmds[command] then
runCommand(cmds[command], moves)
elseif repCmds[command] then
for _ = 1, moves do
if not runCommand(repCmds[command]) then
break
end
end
end
end
local args = {...}
if #args > 0 then
doCommand(args[1], args[2] or 1)
else
print('Enter command (q to quit):')
while true do
local cmd = _G.read()
if cmd == 'q' then break
end
args = { }
cmd:gsub('%w+', function(w) table.insert(args, w) end)
doCommand(args[1], args[2] or 1)
end
end
|
local L = BigWigs:NewBossLocale("Neltharions Lair Trash", "koKR")
if not L then return end
if L then
L.breaker = "막돌 파괴자"
L.hulk = "악성수정 괴수"
L.gnasher = "돌가죽 뾰족니악어"
L.trapper = "돌갑옷 속박투사"
end
L = BigWigs:NewBossLocale("Rokmora", "koKR")
if L then
L.warmup_text = "로크모라 활성화"
L.warmup_trigger = "나바로그? 이 배신자! 감히 침입자들을 끌고 여기 오다니!"
L.warmup_trigger_2 = "어느 쪽이든, 매 순간을 다 즐겨 주지. 로크모라, 박살내라!"
end
L = BigWigs:NewBossLocale("Ularogg Cragshaper", "koKR")
if L then
L.totems = "토템"
L.bellow = "{193375} (토템)" -- Bellow of the Deeps (Totems)
end
|
local map = vim.api.nvim_buf_set_keymap
local file = vim.fn.expand('%')
--compile
map(0, "n", "<Leader>c", ":te pdflatex " .. file .. "<CR>", {noremap = true, silent = true})
--execute
map(0, "n", "<Leader>e", ":!zathura " .. file:gsub(".tex", ".pdf&<CR><CR>"), {noremap = true, silent = true})
|
Config = {}
local configFrame,
titleLabel,
versionLabel,
contributorsLabel,
separator,
generalOptionsLabel,
showWaitingRoomCheckbox,
showWaitingRoomLabel,
muteSoundsCheckbox,
muteSoundsLabel,
modulesFrame
local function UpdateConfigFrameValues()
showWaitingRoomCheckbox:SetChecked(REPORTED2_PREFS[REPORTED2_PREFS_SHOW_PANEL])
hideInCombatCheckbox:SetChecked(REPORTED2_PREFS[REPORTED2_PREFS_HIDE_IN_COMBAT])
hideWhenEmptyCheckbox:SetChecked(REPORTED2_PREFS[REPORTED2_PREFS_HIDE_WHEN_EMPTY])
showOnDetectionCheckbox:SetChecked(REPORTED2_PREFS[REPORTED2_PREFS_SHOW_ON_DETECTION])
muteSoundsCheckbox:SetChecked(REPORTED2_PREFS[REPORTED2_PREFS_MUTE_SOUNDS])
globalChannelsCheckbox:SetChecked(REPORTED2_PREFS[REPORTED2_CHAT_MSG_CHANNEL])
guildChannelCheckbox:SetChecked(REPORTED2_PREFS[REPORTED2_CHAT_MSG_GUILD])
instanceChannelCheckbox:SetChecked(REPORTED2_PREFS[REPORTED2_CHAT_MSG_INSTANCE_CHAT])
instanceLeaderChannelCheckbox:SetChecked(REPORTED2_PREFS[REPORTED2_CHAT_MSG_INSTANCE_CHAT_LEADER])
officerChannelCheckbox:SetChecked(REPORTED2_PREFS[REPORTED2_CHAT_MSG_OFFICER])
partyLeaderChannelCheckbox:SetChecked(REPORTED2_PREFS[REPORTED2_CHAT_MSG_PARTY])
partyChannelCheckbox:SetChecked(REPORTED2_PREFS[REPORTED2_CHAT_MSG_PARTY_LEADER])
raidLeaderChannelCheckbox:SetChecked(REPORTED2_PREFS[REPORTED2_CHAT_MSG_RAID])
raidChannelCheckbox:SetChecked(REPORTED2_PREFS[REPORTED2_CHAT_MSG_RAID_LEADER])
sayChannelCheckbox:SetChecked(REPORTED2_PREFS[REPORTED2_CHAT_MSG_SAY])
whisperChannelCheckbox:SetChecked(REPORTED2_PREFS[REPORTED2_CHAT_MSG_WHISPER])
yellChannelCheckbox:SetChecked(REPORTED2_PREFS[REPORTED2_CHAT_MSG_YELL])
for index, moduleName in ipairs(REPORTED2_PREFS[REPORTED2_PREFS_ENABLED_MODULES]) do
local checkbox = _G["REPORTED2_MODULE_CHECKBOX_" .. string.upper(moduleName)]
checkbox:SetChecked(true)
end
for index, moduleName in ipairs(REPORTED2_PREFS[REPORTED2_PREFS_DISABLED_MODULES]) do
local checkbox = _G["REPORTED2_MODULE_CHECKBOX_" .. string.upper(moduleName)]
checkbox:SetChecked(false)
end
end
local function CreateModulesPanel()
modulesFrame = Reported2.UI.Config.CreateModulesFrame(configFrame)
Reported2.UI.Config.CreateTitleLabel(modulesFrame)
Reported2.UI.Config.CreateVersionLabel(modulesFrame, titleLabel)
Reported2.UI.Config.CreateContributorsLabel(modulesFrame)
local separator = Reported2.UI.Config.CreateSeparator(modulesFrame)
local modulesLabel = Reported2.UI.Config.CreateOptionsLabel("Modules", modulesFrame, separator)
local scrollFrame =
CreateFrame(
"ScrollFrame",
"REPORTED2_MODULES_SCROLL_FRAME",
modulesFrame,
BackdropTemplateMixin and "BackdropTemplate"
)
scrollFrame:SetPoint("TOPLEFT", modulesLabel, 0, -modulesLabel:GetHeight() * 1.5)
scrollFrame:SetSize(
InterfaceOptionsFramePanelContainer:GetWidth() - Reported2.UI.Sizes.Padding * 2,
InterfaceOptionsFramePanelContainer:GetHeight() - Reported2.UI.Sizes.Padding * 12
)
scrollFrame:SetBackdrop(
{
bgFile = Reported2.FLAT_BG_TEXTURE,
edgeFile = Reported2.EDGE_TEXTURE,
edgeSize = 1
}
)
scrollFrame:SetBackdropColor(0, 0, 0, 0.3)
scrollFrame:SetBackdropBorderColor(0, 0, 0, 1)
scrollFrame:EnableMouseWheel(true)
scrollFrame:SetScript(
"OnMouseWheel",
function(self, delta)
local newValue = self:GetVerticalScroll() - (delta * 20)
if (newValue < 0) then
newValue = 0
elseif (newValue > self:GetVerticalScrollRange()) then
newValue = self:GetVerticalScrollRange()
end
self:SetVerticalScroll(newValue)
modulesFrame.scrollbar:SetValue(newValue)
end
)
local scrollChild = CreateFrame("Frame", nil, scrollFrame)
scrollChild:SetPoint("TOPLEFT")
scrollChild:SetSize(scrollFrame:GetWidth(), 480)
scrollFrame:SetScrollChild(scrollChild)
local scrollBar = CreateFrame("Slider", nil, scrollFrame)
scrollBar:SetFrameLevel(4)
scrollBar:SetPoint("TOPLEFT", scrollFrame, "TOPRIGHT", -(Reported2.UI.Sizes.Padding * 1.5), 0)
scrollBar:SetPoint("BOTTOMLEFT", scrollFrame, "BOTTOMRIGHT", Reported2.UI.Sizes.Padding * 0.5, 0)
scrollBar:SetMinMaxValues(1, InterfaceOptionsFramePanelContainer:GetHeight())
scrollBar:SetValueStep(1)
scrollBar.scrollStep = 1
scrollBar:SetValue(0)
scrollBar:SetWidth(Reported2.UI.Sizes.Padding * 1.5)
scrollBar:SetScript(
"OnValueChanged",
function(self, value)
self:GetParent():SetVerticalScroll(value)
end
)
local scrollbg =
CreateFrame("Frame", "MODULES_FRAME_SCROLLBAR_BG", scrollBar, BackdropTemplateMixin and "BackdropTemplate")
scrollbg:SetFrameLevel(3)
scrollbg:SetAllPoints(scrollBar)
scrollbg:SetBackdrop(
{
bgFile = Reported2.FLAT_BG_TEXTURE,
edgeFile = Reported2.EDGE_TEXTURE,
edgeSize = 1
}
)
scrollbg:SetBackdropBorderColor(
Reported2.Palette.RGB.BLACK.r,
Reported2.Palette.RGB.BLACK.g,
Reported2.Palette.RGB.BLACK.b,
1
)
scrollbg:SetBackdropColor(0, 0, 0, 0.45)
scrollBar:SetThumbTexture(Reported2.BUTTON_BG_TEXTURE)
local thumbTexture = scrollBar:GetThumbTexture()
thumbTexture:SetVertexColor(
Reported2.Palette.RGB.TEAL.r,
Reported2.Palette.RGB.TEAL.g,
Reported2.Palette.RGB.TEAL.b,
1
)
thumbTexture:SetWidth(scrollBar:GetWidth() - 2)
thumbTexture:SetHeight(Reported2.UI.Sizes.Padding * 2)
modulesFrame.scrollbar = scrollBar
local offset = Reported2.UI.Sizes.Padding
local sortedModules = Reported2.Utilities.GetSortedModuleNames(Reported2.Modules)
for index, moduleName in ipairs(sortedModules) do
local moduleContent = Reported2.Modules[moduleName]
local moduleNameText = moduleName
local moduleCreditText = moduleContent["Credit"]
local moduleDescriptionText = moduleContent["Description"]
local isLastModule = index == #sortedModules
local moduleCheckboxAndLabelFrame, moduleCheckbox, moduleLabel =
Reported2.UI.Config.CreateModuleCheckboxAndLabel(
moduleNameText,
moduleCreditText,
moduleDescriptionText,
scrollChild,
offset,
isLastModule
)
offset = offset + moduleCheckboxAndLabelFrame:GetHeight() + Reported2.UI.Sizes.Padding * 1.5
end
local enableAllButton = CreateFrame("BUTTON", nil, scrollFrame, BackdropTemplateMixin and "BackdropTemplate")
enableAllButton:SetBackdrop(
{
bgFile = Reported2.BUTTON_BG_TEXTURE,
edgeFile = Reported2.EDGE_TEXTURE,
edgeSize = 1
}
)
enableAllButton:SetSize(80, 30)
enableAllButton:SetPoint(
"BOTTOMRIGHT",
-(enableAllButton:GetWidth() + Reported2.UI.Sizes.Padding),
-(enableAllButton:GetHeight() + Reported2.UI.Sizes.Padding)
)
enableAllButton:SetBackdropColor(
Reported2.Palette.RGB.GREY.r,
Reported2.Palette.RGB.GREY.g,
Reported2.Palette.RGB.GREY.b,
1
)
enableAllButton:SetBackdropBorderColor(
Reported2.Palette.RGB.DARK_GREY.r,
Reported2.Palette.RGB.DARK_GREY.g,
Reported2.Palette.RGB.DARK_GREY.b,
1
)
local enableAllButtonText = enableAllButton:CreateFontString(nil, "OVERLAY", "GameFontNormal")
enableAllButtonText:SetPoint("CENTER", enableAllButton, "CENTER")
enableAllButtonText:SetText(
Reported2.Palette.START .. Reported2.Palette.TEAL .. "Enable all" .. Reported2.Palette.END
)
local disableAllButton = CreateFrame("BUTTON", nil, scrollFrame, BackdropTemplateMixin and "BackdropTemplate")
disableAllButton:SetBackdrop(
{
bgFile = Reported2.BUTTON_BG_TEXTURE,
edgeFile = Reported2.EDGE_TEXTURE,
edgeSize = 1
}
)
disableAllButton:SetSize(80, 30)
disableAllButton:SetPoint("BOTTOMRIGHT", 0, -(disableAllButton:GetHeight() + Reported2.UI.Sizes.Padding))
disableAllButton:SetBackdropColor(
Reported2.Palette.RGB.GREY.r,
Reported2.Palette.RGB.GREY.g,
Reported2.Palette.RGB.GREY.b,
1
)
disableAllButton:SetBackdropBorderColor(
Reported2.Palette.RGB.DARK_GREY.r,
Reported2.Palette.RGB.DARK_GREY.g,
Reported2.Palette.RGB.DARK_GREY.b,
1
)
local disableAllButtonText = disableAllButton:CreateFontString(nil, "OVERLAY", "GameFontNormal")
disableAllButtonText:SetPoint("CENTER", disableAllButton, "CENTER")
disableAllButtonText:SetText(
Reported2.Palette.START .. Reported2.Palette.RED .. "Disable all" .. Reported2.Palette.END
)
enableAllButton:SetScript(
"OnClick",
function()
local sortedModules = Reported2.Utilities.GetSortedModuleNames(Reported2.Modules)
for index, moduleName in ipairs(sortedModules) do
local checkbox = _G["REPORTED2_MODULE_CHECKBOX_" .. string.upper(moduleName)]
checkbox:SetChecked(true)
end
end
)
enableAllButton:SetScript(
"OnEnter",
function()
enableAllButtonText:SetText(
Reported2.Palette.START .. Reported2.Palette.WHITE .. "Enable all" .. Reported2.Palette.END
)
enableAllButton:SetBackdropBorderColor(
Reported2.Palette.RGB.TEAL.r,
Reported2.Palette.RGB.TEAL.g,
Reported2.Palette.RGB.TEAL.b,
1
)
end
)
enableAllButton:SetScript(
"OnLeave",
function()
enableAllButtonText:SetText(
Reported2.Palette.START .. Reported2.Palette.TEAL .. "Enable all" .. Reported2.Palette.END
)
enableAllButton:SetBackdropBorderColor(
Reported2.Palette.RGB.DARK_GREY.r,
Reported2.Palette.RGB.DARK_GREY.g,
Reported2.Palette.RGB.DARK_GREY.b,
1
)
end
)
disableAllButton:SetScript(
"OnClick",
function()
local sortedModules = Reported2.Utilities.GetSortedModuleNames(Reported2.Modules)
for index, moduleName in ipairs(sortedModules) do
local checkbox = _G["REPORTED2_MODULE_CHECKBOX_" .. string.upper(moduleName)]
checkbox:SetChecked(false)
end
end
)
disableAllButton:SetScript(
"OnEnter",
function()
disableAllButtonText:SetText(
Reported2.Palette.START .. Reported2.Palette.WHITE .. "Disable all" .. Reported2.Palette.END
)
disableAllButton:SetBackdropBorderColor(
Reported2.Palette.RGB.RED.r,
Reported2.Palette.RGB.RED.g,
Reported2.Palette.RGB.RED.b,
1
)
end
)
disableAllButton:SetScript(
"OnLeave",
function()
disableAllButtonText:SetText(
Reported2.Palette.START .. Reported2.Palette.RED .. "Disable all" .. Reported2.Palette.END
)
disableAllButton:SetBackdropBorderColor(
Reported2.Palette.RGB.DARK_GREY.r,
Reported2.Palette.RGB.DARK_GREY.g,
Reported2.Palette.RGB.DARK_GREY.b,
1
)
end
)
end
function Reported2.Config.CreatePanel()
configFrame = Reported2.UI.Config.CreateConfigFrame()
titleLabel = Reported2.UI.Config.CreateTitleLabel(configFrame)
versionLabel = Reported2.UI.Config.CreateVersionLabel(configFrame, titleLabel)
contributorsLabel = Reported2.UI.Config.CreateContributorsLabel(configFrame)
separator = Reported2.UI.Config.CreateSeparator(configFrame)
-- General Options
generalOptionsLabel = Reported2.UI.Config.CreateOptionsLabel("General Options", configFrame, separator)
local showWaitingRoomText = "Show Waiting Room"
local hideInCombatText = "Hide Waiting Room in combat"
local hideWhenEmptyText = "Hide Waiting Room when it is empty"
local showOnDetectionText = "Show Waiting Room on detection"
local showWaitingRoomShortcutText =
Reported2.Palette.START .. Reported2.Palette.GREY .. " — Shortcut: /r2 show & /r2 hide" .. Reported2.Palette.END
showWaitingRoomCheckbox, showWaitingRoomLabel =
Reported2.UI.Config.CreateCheckbox(
showWaitingRoomText .. showWaitingRoomShortcutText,
configFrame,
generalOptionsLabel
)
hideInCombatCheckbox, hideInCombatLabel =
Reported2.UI.Config.CreateCheckbox(hideInCombatText, configFrame, showWaitingRoomCheckbox)
hideWhenEmptyCheckbox, hideWhenEmptyLabel =
Reported2.UI.Config.CreateCheckbox(hideWhenEmptyText, configFrame, hideInCombatCheckbox)
showOnDetectionCheckbox, showOnDetectionCheckboxLabel =
Reported2.UI.Config.CreateCheckbox(showOnDetectionText, configFrame, hideWhenEmptyCheckbox)
muteSoundsCheckbox, muteSoundsLabel =
Reported2.UI.Config.CreateCheckbox("Mute sounds", configFrame, showOnDetectionCheckbox)
-- Channel Options
channelOptionsLabel =
Reported2.UI.Config.CreateOptionsLabel(
"Channel Options",
configFrame,
muteSoundsCheckbox,
Reported2.UI.Sizes.Padding * 3
)
channelOptionsSubLabel =
Reported2.UI.Config.CreateOptionsSubLabel("Select which channels to monitor:", configFrame, channelOptionsLabel)
-- Channels
Reported2.UI.Config.CreateChannelCheckboxes(configFrame)
CreateModulesPanel()
-- Config Frame - Form actions
configFrame:SetScript("OnShow", UpdateConfigFrameValues)
function configFrame.okay()
REPORTED2_PREFS[REPORTED2_PREFS_SHOW_PANEL] = showWaitingRoomCheckbox:GetChecked()
REPORTED2_PREFS[REPORTED2_PREFS_HIDE_IN_COMBAT] = hideInCombatCheckbox:GetChecked()
REPORTED2_PREFS[REPORTED2_PREFS_HIDE_WHEN_EMPTY] = hideWhenEmptyCheckbox:GetChecked()
REPORTED2_PREFS[REPORTED2_PREFS_SHOW_ON_DETECTION] = showOnDetectionCheckbox:GetChecked()
REPORTED2_PREFS[REPORTED2_PREFS_MUTE_SOUNDS] = muteSoundsCheckbox:GetChecked()
REPORTED2_PREFS[REPORTED2_CHAT_MSG_CHANNEL] = globalChannelsCheckbox:GetChecked()
REPORTED2_PREFS[REPORTED2_CHAT_MSG_GUILD] = guildChannelCheckbox:GetChecked()
REPORTED2_PREFS[REPORTED2_CHAT_MSG_INSTANCE_CHAT] = instanceChannelCheckbox:GetChecked()
REPORTED2_PREFS[REPORTED2_CHAT_MSG_INSTANCE_CHAT_LEADER] = instanceLeaderChannelCheckbox:GetChecked()
REPORTED2_PREFS[REPORTED2_CHAT_MSG_OFFICER] = officerChannelCheckbox:GetChecked()
REPORTED2_PREFS[REPORTED2_CHAT_MSG_PARTY] = partyLeaderChannelCheckbox:GetChecked()
REPORTED2_PREFS[REPORTED2_CHAT_MSG_PARTY_LEADER] = partyChannelCheckbox:GetChecked()
REPORTED2_PREFS[REPORTED2_CHAT_MSG_RAID] = raidLeaderChannelCheckbox:GetChecked()
REPORTED2_PREFS[REPORTED2_CHAT_MSG_RAID_LEADER] = raidChannelCheckbox:GetChecked()
REPORTED2_PREFS[REPORTED2_CHAT_MSG_SAY] = sayChannelCheckbox:GetChecked()
REPORTED2_PREFS[REPORTED2_CHAT_MSG_WHISPER] = whisperChannelCheckbox:GetChecked()
REPORTED2_PREFS[REPORTED2_CHAT_MSG_YELL] = yellChannelCheckbox:GetChecked()
REPORTED2_PREFS[REPORTED2_PREFS_ENABLED_MODULES] = {}
REPORTED2_PREFS[REPORTED2_PREFS_DISABLED_MODULES] = {}
local sortedModules = Reported2.Utilities.GetSortedModuleNames(Reported2.Modules)
for index, moduleName in ipairs(sortedModules) do
local checkbox = _G["REPORTED2_MODULE_CHECKBOX_" .. string.upper(moduleName)]
local isChecked = checkbox:GetChecked()
if isChecked then
table.insert(REPORTED2_PREFS[REPORTED2_PREFS_ENABLED_MODULES], moduleName)
else
table.insert(REPORTED2_PREFS[REPORTED2_PREFS_DISABLED_MODULES], moduleName)
end
end
if #REPORTED2_PREFS[REPORTED2_PREFS_ENABLED_MODULES] == 0 then
local indexOfDefaultModule
for index, value in pairs(REPORTED2_PREFS[REPORTED2_PREFS_DISABLED_MODULES]) do
if value == "Default" then
indexOfDefaultModule = index
end
end
table.remove(REPORTED2_PREFS[REPORTED2_PREFS_DISABLED_MODULES], indexOfDefaultModule)
table.insert(REPORTED2_PREFS[REPORTED2_PREFS_ENABLED_MODULES], "Default")
end
if REPORTED2_PREFS[REPORTED2_PREFS_SHOW_PANEL] then
Reported2.Panel.RenderOffenders()
Reported2.Panel.ShowPanel()
else
Reported2.Panel.HidePanel()
end
end
end
function Reported2.Config.OpenConfigMenu()
-- https://wowwiki.fandom.com/wiki/Using_the_Interface_Options_Addons_panel
-- ------------------------------------------------------------------------
-- Note: Call this function twice (in a row), there is a bug in Blizzard's code which makes the first call
-- (after login or /reload) fail. It opens interface options but not on the addon's interface options;
-- instead it opens the default interface options.
-- If you call it twice in a row, it works as intended.
InterfaceOptionsFrame_OpenToCategory(configFrame.name)
InterfaceOptionsFrame_OpenToCategory(configFrame.name)
end
|
RaidJobsTweakData = RaidJobsTweakData or class()
-- Lines: 5 to 17
function RaidJobsTweakData:init(tweak_data)
self.challenges = {}
self:_init_weapon_challenges(tweak_data)
self:_init_mask_challenges(tweak_data)
end
-- Lines: 21 to 90
function RaidJobsTweakData:_init_weapon_challenges(tweak_data)
table.insert(self.challenges, {
reward_id = "menu_aru_job_1_reward",
name_id = "menu_aru_job_1",
id = "aru_1",
desc_id = "menu_aru_job_1_desc",
show_progress = true,
objectives = {tweak_data.safehouse:_progress("aru_1", 0, {
name_id = "menu_aru_job_1_obj",
desc_id = "menu_aru_job_1_obj_desc"
})},
rewards = {
{
item_entry = "breech",
type_items = "weapon"
},
{
"safehouse_coins",
tweak_data.safehouse.rewards.challenge
}
}
})
table.insert(self.challenges, {
reward_id = "menu_aru_job_2_reward",
name_id = "menu_aru_job_2",
id = "aru_2",
desc_id = "menu_aru_job_2_desc",
show_progress = true,
objectives = {tweak_data.safehouse:_progress("aru_2", 0, {
name_id = "menu_aru_job_2_obj",
desc_id = "menu_aru_job_2_obj_desc"
})},
rewards = {
{
item_entry = "erma",
type_items = "weapon"
},
{
"safehouse_coins",
tweak_data.safehouse.rewards.challenge
}
}
})
table.insert(self.challenges, {
reward_id = "menu_aru_job_3_reward",
name_id = "menu_aru_job_3",
id = "aru_3",
desc_id = "menu_aru_job_3_desc",
show_progress = true,
objectives = {tweak_data.safehouse:_progress("aru_3", 0, {
name_id = "menu_aru_job_3_obj",
desc_id = "menu_aru_job_3_obj_desc"
})},
rewards = {
{
item_entry = "ching",
type_items = "weapon"
},
{
"safehouse_coins",
tweak_data.safehouse.rewards.challenge
}
}
})
table.insert(self.challenges, {
reward_id = "menu_aru_job_4_reward",
name_id = "menu_aru_job_4",
id = "aru_4",
desc_id = "menu_aru_job_4_desc",
show_progress = true,
objectives = {tweak_data.safehouse:_progress("aru_4", 0, {
name_id = "menu_aru_job_4_obj",
desc_id = "menu_aru_job_4_obj_desc"
})},
rewards = {{
"safehouse_coins",
tweak_data.safehouse.rewards.challenge
}}
})
end
-- Lines: 95 to 164
function RaidJobsTweakData:_init_mask_challenges(tweak_data)
table.insert(self.challenges, {
reward_id = "menu_jfr_job_1_reward",
name_id = "menu_jfr_job_1",
id = "jfr_1",
desc_id = "menu_jfr_job_1_desc",
show_progress = true,
objectives = {tweak_data.safehouse:_progress("aru_1", 0, {
name_id = "menu_jfr_job_1_case",
desc_id = "menu_jfr_job_1_case_desc"
})},
rewards = {{
item_entry = "jfr_03",
type_items = "masks"
}}
})
table.insert(self.challenges, {
reward_id = "menu_jfr_job_2_reward",
name_id = "menu_jfr_job_2",
id = "jfr_2",
desc_id = "menu_jfr_job_2_desc",
show_progress = true,
objectives = {tweak_data.safehouse:_progress("aru_1", 0, {
name_id = "menu_jfr_job_2_kills",
desc_id = "menu_jfr_job_2_kills_desc"
})},
rewards = {{
item_entry = "jfr_02",
type_items = "masks"
}}
})
table.insert(self.challenges, {
reward_id = "menu_jfr_job_3_reward",
name_id = "menu_jfr_job_3",
id = "jfr_3",
desc_id = "menu_jfr_job_3_desc",
show_progress = true,
objectives = {tweak_data.safehouse:_progress("aru_1", 0, {
name_id = "menu_jfr_job_3_wine",
desc_id = "menu_jfr_job_3_wine_desc"
})},
rewards = {{
item_entry = "jfr_01",
type_items = "masks"
}}
})
table.insert(self.challenges, {
reward_id = "menu_jfr_job_4_reward",
name_id = "menu_jfr_job_4",
id = "jfr_4",
desc_id = "menu_jfr_job_4_desc",
show_progress = true,
objectives = {tweak_data.safehouse:_progress("aru_1", 0, {
name_id = "menu_jfr_job_4_deposit",
desc_id = "menu_jfr_job_4_deposit_desc"
})},
rewards = {{
item_entry = "jfr_04",
type_items = "masks"
}}
})
end
|
yavin4_angler_giant_neutral_medium_boss_01 = Lair:new {
mobiles = {{"giant_angler",1}},
bossMobiles = {{"mad_angler",1}},
spawnLimit = 15,
buildingsVeryEasy = {"object/tangible/lair/base/antpile_dark.iff"},
buildingsEasy = {"object/tangible/lair/base/antpile_dark.iff"},
buildingsMedium = {"object/tangible/lair/base/antpile_dark.iff"},
buildingsHard = {"object/tangible/lair/base/antpile_dark.iff"},
buildingsVeryHard = {"object/tangible/lair/base/antpile_dark.iff"},
}
addLairTemplate("yavin4_angler_giant_neutral_medium_boss_01", yavin4_angler_giant_neutral_medium_boss_01)
|
main = {
love = {}
}
function main.load()
--requires--
dofile("app0:/controls.lua")
--dofile("app0:/gameB.lua")
--dofile("app0:/gameBmulti.lua")
--dofile("app0:/gameA.lua")
dofile("app0:/menu.lua")
dofile("app0:/failed.lua")
dofile("app0:/rocket.lua")
vsync = true
autosize()
suggestedscale = math.min(math.floor((desktopheight-50)/144), math.floor((desktopwidth-10)/160))
if suggestedscale > 5 then
suggestedscale = 5
end
loadoptions()
maxscale = math.min(math.floor(desktopheight/144), math.floor(desktopwidth/160))
maxmpscale = math.min(math.floor(desktopheight/144), math.floor(desktopwidth/274))
if fullscreen == false then
if scale ~= 5 then
love.graphics.setMode( 160*scale, 144*scale, false, vsync, 0 )
end
else
love.graphics.setMode( 0, 0, true, vsync, 0 )
love.mouse.setVisible( false )
desktopwidth, desktopheight = love.graphics.getWidth(), love.graphics.getHeight()
saveoptions()
suggestedscale = math.floor((desktopheight-50)/144)
if suggestedscale > 5 then
suggestedscale = 5
end
maxscale = math.min(math.floor(desktopheight/144), math.floor(desktopwidth/160))
scale = maxscale
fullscreenoffsetX = (desktopwidth-160*scale)/2
fullscreenoffsetY = (desktopheight-144*scale)/2
end
physicsscale = scale/4
--pieces--
tetriimages = {}
tetriimagedata = {}
----SOUND--
music = {}
music[1] = love.audio.newSource( "sounds/themeA.ogg", "stream")
music[1]:setVolume( 0.6 )
music[1]:setLooping( true )
music[2] = love.audio.newSource( "sounds/themeB.ogg", "stream")
music[2]:setVolume( 0.6 )
music[2]:setLooping( true )
music[3] = love.audio.newSource( "sounds/themeC.ogg", "stream")
music[3]:setVolume( 0.6 )
music[3]:setLooping( true )
musictitle = love.audio.newSource( "sounds/titlemusic.ogg", "stream")
musictitle:setVolume( 0.6 )
musictitle:setLooping( true )
musichighscore = love.audio.newSource( "sounds/highscoremusic.ogg", "stream")
musichighscore:setVolume( 0.6 )
musichighscore:setLooping( true )
musicrocket4 = love.audio.newSource( "sounds/rocket4.ogg", "stream")
musicrocket4:setVolume( 0.6 )
musicrocket4:setLooping( false )
musicrocket1to3 = love.audio.newSource( "sounds/rocket1to3.ogg", "stream")
musicrocket1to3:setVolume( 0.6 )
musicrocket1to3:setLooping( false )
musicresults = love.audio.newSource( "sounds/resultsmusic.ogg", "stream")
musicresults:setVolume( 1 )
musicresults:setLooping( false )
highscoreintro = love.audio.newSource( "sounds/highscoreintro.ogg", "stream")
highscoreintro:setVolume( 0.6 )
highscoreintro:setLooping( false )
musicoptions = love.audio.newSource( "sounds/musicoptions.ogg", "stream")
musicoptions:setVolume( 1 )
musicoptions:setLooping( true )
boot = love.audio.newSource( "sounds/boot.ogg")
blockfall = love.audio.newSource( "sounds/blockfall.ogg", "stream")
blockturn = love.audio.newSource( "sounds/turn.ogg", "stream")
blockmove = love.audio.newSource( "sounds/move.ogg", "stream")
lineclear = love.audio.newSource( "sounds/lineclear.ogg", "stream")
fourlineclear = love.audio.newSource( "sounds/4lineclear.ogg", "stream")
gameover1 = love.audio.newSource( "sounds/gameover1.ogg", "stream")
gameover2 = love.audio.newSource( "sounds/gameover2.ogg", "stream")
pausesound = love.audio.newSource( "sounds/pause.ogg", "stream")
highscorebeep = love.audio.newSource( "sounds/highscorebeep.ogg", "stream")
newlevel = love.audio.newSource( "sounds/newlevel.ogg", "stream")
newlevel:setVolume( 0.6 )
changevolume(volume)
----IMAGES THAT WON'T CHANGE HUE:
rainbowgradient = love.graphics.newImageFromFile("graphics/rainbow.png")rainbowgradient:setFilter("nearest", "nearest")
--Whitelist for highscorenames--
whitelist = {}
for i = 48, 57 do -- 0 - 9
whitelist[i] = true
end
for i = 65, 90 do -- A - Z
whitelist[i] = true
end
for i = 97, 122 do --a - z
whitelist[i] = true
end
whitelist[32] = true -- space
whitelist[44] = true -- ,
whitelist[45] = true -- -
whitelist[46] = true -- .
whitelist[95] = true -- _
-------------------------------
math.randomseed( os.time() )
math.random();math.random();math.random() --discarding some as they seem to tend to unrandomness.
love.graphics.setBackgroundColor( 255, 255, 255 )
p1wins = 0
p2wins = 0
skipupdate = true
soundenabled = true
startdelay = 1
logoduration = 1.5
logodelay = 1
creditsdelay = 2
selectblinkrate = 0.29
cursorblinkrate = 0.14
selectblink = true
cursorblink = true
playerselection = 1
musicno = 1 --
gameno = 1 --
selection = 1 --
colorizeduration = 3 --seconds
lineclearduration = 1.2 --seconds
lineclearblinks = 7 --i
linecleartreshold = 8.1 --in blocks
densityupdateinterval = 1/30 --in seconds
nextpiecerotspeed = 1 --rad per seconnd
minfps = 1/50 --dt doesn't go higher than this
scoreaddtime = 0.5
startdelaytime = 0
density = 0.1
blockstartY = -64 --where new blocks are created
losingY = 0 --lose if block 1 collides above this line
blockmass = 5 --probably obsolete because body:setMassFromShapes()
blockrot = 10
blockrestitution = 0.1
minmass = 1
optionschoices = {"volume", "color", "scale", "fullscrn"}
piececenter = {}
piececenter[1] = {17, 5}
piececenter[2] = {13, 9}
piececenter[3] = {13, 9}
piececenter[4] = { 9, 9}
piececenter[5] = {13, 9}
piececenter[6] = {13, 9}
piececenter[7] = {13, 9}
piececenterpreview = {}
piececenterpreview[1] = {17, 5}
piececenterpreview[2] = {15, 7}
piececenterpreview[3] = {11, 7}
piececenterpreview[4] = { 9, 9}
piececenterpreview[5] = {13, 9}
piececenterpreview[6] = {13, 7}
piececenterpreview[7] = {13, 9}
--
loadhighscores()
--
loadimages()
--
----all done!
--if startdelay == 0 then
-- menu_load()
--end
end
function start()
menu_load()
end
function loadimages()
--IMAGES--
--menu--
stabyourselflogo = newPaddedImage("graphics/stabyourselflogo.png")
logo = newPaddedImage("graphics/logo.png")
title = newPaddedImage("graphics/title.png")
gametype = newPaddedImage("graphics/gametype.png")
mpmenu = newPaddedImage("graphics/mpmenu.png")
optionsmenu = newPaddedImage("graphics/options.png")
volumeslider = newPaddedImage("graphics/volumeslider.png")
----game--
gamebackground = newPaddedImage("graphics/gamebackground.png")
gamebackgroundcutoff = newPaddedImage("graphics/gamebackgroundgamea.png")
gamebackgroundmulti = newPaddedImage("graphics/gamebackgroundmulti.png")
multiresults = newPaddedImage("graphics/multiresults.png")
number1 = newPaddedImage("graphics/versus/number1.png")
number2 = newPaddedImage("graphics/versus/number2.png")
number3 = newPaddedImage("graphics/versus/number3.png")
gameover = newPaddedImage("graphics/gameover.png")
gameovercutoff = newPaddedImage("graphics/gameovercutoff.png")
pausegraphic = newPaddedImage("graphics/pause.png")
pausegraphiccutoff = newPaddedImage("graphics/pausecutoff.png")
----figures--
marioidle = newPaddedImage("graphics/versus/marioidle.png")
mariojump = newPaddedImage("graphics/versus/mariojump.png")
mariocry1 = newPaddedImage("graphics/versus/mariocry1.png")
mariocry2 = newPaddedImage("graphics/versus/mariocry2.png")
luigiidle = newPaddedImage("graphics/versus/luigiidle.png")
luigijump = newPaddedImage("graphics/versus/luigijump.png")
luigicry1 = newPaddedImage("graphics/versus/luigicry1.png")
luigicry2 = newPaddedImage("graphics/versus/luigicry2.png")
--rockets--
rocket1 = newPaddedImage("graphics/rocket1.png");rocket1:setFilter( "nearest", "nearest" )
rocket2 = newPaddedImage("graphics/rocket2.png")
rocket3 = newPaddedImage("graphics/rocket3.png")
spaceshuttle = newPaddedImage("graphics/spaceshuttle.png")
rocketbackground = newPaddedImage("graphics/rocketbackground.png")
bigrocketbackground = newPaddedImage("graphics/bigrocketbackground.png")
bigrockettakeoffbackground = newPaddedImage("graphics/bigrockettakeoffbackground.png")
smoke1left = newPaddedImage("graphics/smoke1left.png")
smoke1right = newPaddedImage("graphics/smoke1right.png")
smoke2left = newPaddedImage("graphics/smoke2left.png")
smoke2right = newPaddedImage("graphics/smoke2right.png")
fire1 = newPaddedImage("graphics/fire1.png")
fire2 = newPaddedImage("graphics/fire2.png")
firebig1 = newPaddedImage("graphics/firebig1.png")
firebig2 = newPaddedImage("graphics/firebig2.png")
congratsline = newPaddedImage("graphics/congratsline.png")
----nextpiece
nextpieceimg = {}
for i = 1, 7 do
nextpieceimg[i] = newPaddedImage( "graphics/pieces/"..i..".png", scale )
end
----font--
---- original
----tetrisfont = newPaddedImageFont("graphics/font.png", "0123456789abcdefghijklmnopqrstTuvwxyz.,'C-#_>:<! ")
----whitefont = newPaddedImageFont("graphics/fontwhite.png", "0123456789abcdefghijklmnopqrstTuvwxyz.,'C-#_>:<!+ ")
--
---- modified font
--tetrisfont = love.graphics.newFont("graphics/font/Masaaki-Regular.ttf")
--whitefont = love.graphics.newFont("graphics/font/Masaaki-Regular.ttf")
--love.graphics.setFont(tetrisfont)
--
----filters!
--stabyourselflogo:setFilter("nearest", "nearest")
--logo:setFilter( "nearest", "nearest" )
--title:setFilter( "nearest", "nearest" )
--gametype:setFilter( "nearest", "nearest" )
--mpmenu:setFilter( "nearest", "nearest" )
--optionsmenu:setFilter( "nearest", "nearest" )
--volumeslider:setFilter( "nearest", "nearest" )
--gamebackground:setFilter( "nearest", "nearest" )
--gamebackgroundcutoff:setFilter( "nearest", "nearest" )
--gamebackgroundmulti:setFilter( "nearest", "nearest" )
--multiresults:setFilter( "nearest", "nearest" )
--number1:setFilter( "nearest", "nearest" )
--number2:setFilter( "nearest", "nearest" )
--number3:setFilter( "nearest", "nearest" )
--gameover:setFilter( "nearest", "nearest" )
--gameovercutoff:setFilter( "nearest", "nearest" )
--pausegraphic:setFilter( "nearest", "nearest" )
--pausegraphiccutoff:setFilter( "nearest", "nearest" )
--marioidle:setFilter( "nearest", "nearest" )
--mariojump:setFilter( "nearest", "nearest" )
--mariocry1:setFilter( "nearest", "nearest" )
--mariocry2:setFilter( "nearest", "nearest" )
--luigiidle:setFilter( "nearest", "nearest" )
--luigijump:setFilter( "nearest", "nearest" )
--luigicry1:setFilter( "nearest", "nearest" )
--luigicry2:setFilter( "nearest", "nearest" )
--rocket2:setFilter( "nearest", "nearest" )
--rocket3:setFilter( "nearest", "nearest" )
--spaceshuttle:setFilter( "nearest", "nearest" )
--rocketbackground:setFilter( "nearest", "nearest" )
--bigrocketbackground:setFilter( "nearest", "nearest" )
--bigrockettakeoffbackground:setFilter( "nearest", "nearest" )
--smoke1left:setFilter( "nearest", "nearest" )
--smoke1right:setFilter( "nearest", "nearest" )
--smoke2left:setFilter( "nearest", "nearest" )
--smoke2right:setFilter( "nearest", "nearest" )
--fire1:setFilter( "nearest", "nearest" )
--fire2:setFilter( "nearest", "nearest" )
--firebig1:setFilter( "nearest", "nearest" )
--firebig2:setFilter( "nearest", "nearest" )
--congratsline:setFilter( "nearest", "nearest" )
end
function love.update(dt)
if gamestate == nil then
startdelaytime = startdelaytime + dt
if startdelaytime >= startdelay then
start()
end
end
if skipupdate then
skipupdate = false
return
end
if cuttingtimer ~= 0 then
dt = math.min(dt, minfps)
end
if gamestate == "logo" or gamestate == "credits" or gamestate == "title" or gamestate == "menu" or gamestate == "multimenu" or gamestate == "highscoreentry" or gamestate == "options" then
menu_update(dt)
elseif gamestate == "gameA" or gamestate == "failingA" then
if pause == false then
gameA_update(dt)
end
elseif gamestate == "gameB" or gamestate == "failingB" then
if pause == false then
gameB_update(dt)
end
elseif gamestate == "gameBmulti" or gamestate == "failingBmulti" or gamestate == "failedBmulti" or gamestate == "gameBmulti_results" then
gameBmulti_update(dt)
elseif gamestate == "rocket1" or gamestate == "rocket2" or gamestate == "rocket3" or gamestate == "rocket4" then
rocket_update()
end
end
function love.draw()
if gamestate == "logo" or gamestate == "credits" or gamestate == "title" or gamestate == "menu" or gamestate == "multimenu" or gamestate == "highscoreentry" or gamestate == "options" then
menu_draw()
elseif gamestate == "gameA" or gamestate == "failingA" then
gameA_draw()
elseif gamestate == "gameB" or gamestate == "failingB" then
gameB_draw()
elseif gamestate == "gameBmulti" or gamestate == "failingBmulti" or gamestate == "failedBmulti" or gamestate == "gameBmulti_results" then
gameBmulti_draw()
elseif gamestate == "failed" then
failed_draw()
elseif gamestate == "rocket1" or gamestate == "rocket2" or gamestate == "rocket3" or gamestate == "rocket4" then
rocket_draw()
end
end
function newImageData(path, s)
local imagedata = love.image.newImageDataFromPath( path )
if s then
imagedata = scaleImagedata(imagedata, s)
end
local width, height = imagedata:getWidth(), imagedata:getHeight()
local rr, rg, rb = unpack(getrainbowcolor(hue))
for y = 0, height-1 do
for x = 0, width-1 do
local oldr, oldg, oldb, olda = imagedata:getPixel(x, y)
if olda ~= 0 then
if oldr > 203 and oldr < 213 then --lightgrey
local r = 145 + rr*64
local g = 145 + rg*64
local b = 145 + rb*64
imagedata:setPixel(x, y, r, g, b, olda)
elseif oldr > 107 and oldr < 117 then --darkgrey
local r = 73 + rr*43
local g = 73 + rg*43
local b = 73 + rb*43
imagedata:setPixel(x, y, r, g, b, olda)
end
end
end
end
return imagedata
end
function newPaddedImage(filename, s)
love.graphics.print(filename ,20, 60, 0, 1, 1)
local source = newImageData(filename)
love.graphics.print("new ,age", 20, 60, 0, 1, 1)
if s then
source = scaleImagedata(source, s)
end
local w, h = source:getWidth(), source:getHeight()
-- Find closest power-of-two.
local wp = math.pow(2, math.ceil(math.log(w)/math.log(2)))
local hp = math.pow(2, math.ceil(math.log(h)/math.log(2)))
love.graphics.print("math", 20, 60, 0, 1, 1)
-- Only pad if needed:
if wp ~= w or hp ~= h then
love.graphics.print(
"" .. wp .. " wp\n" .. w .. " w\n" ..
"" .. hp .. " hp\n" .. h .. " h\n"
, 20, 60, 0, 1, 1)
local padded = love.image.newImageDataFromDimensions(wp, hp)
love.graphics.print("before paste", 20, 60, 0, 1, 1)
padded:paste(source, 0, 0)
love.graphics.print("pasted", 20, 60, 0, 1, 1)
return love.graphics.newImageFromImageData(padded)
end
return love.graphics.newImageFromImageData(source)
end
function padImagedata(source) --returns image, not imagedata!
local w, h = source:getWidth(), source:getHeight()
-- Find closest power-of-two.
local wp = math.pow(2, math.ceil(math.log(w)/math.log(2)))
local hp = math.pow(2, math.ceil(math.log(h)/math.log(2)))
-- Only pad if needed:
if wp ~= w or hp ~= h then
local padded = love.image.newImageDataFromDimensions(wp, hp)
padded:paste(source, 0, 0)
return love.graphics.newImageFromImageData(padded)
end
return love.graphics.newImageFromImageData(source)
end
--function newPaddedImageFont(filename, glyphs)
-- local source = newImageData(filename)
-- local w, h = source:getWidth(), source:getHeight()
--
-- -- Find closest power-of-two.
-- local wp = math.pow(2, math.ceil(math.log(w)/math.log(2)))
-- local hp = math.pow(2, math.ceil(math.log(h)/math.log(2)))
--
-- -- Only pad if needed:
-- if wp ~= w or hp ~= h then
-- local padded = love.image.newImageData(wp, hp)
-- padded:paste(source, 0, 0)
-- local image = love.graphics.newImageFromImageData(padded)
-- image:setFilter("nearest", "nearest")
-- return love.graphics.newImageFont(image, glyphs)
-- end
--
-- return love.graphics.newImageFont(source, glyphs)
--end
function scaleImagedata(imagedata, i)
--local width, height = imagedata:getWidth(), imagedata:getHeight()
--love.graphics.print("width: " .. width .. ", height: " .. height, 20, 60, 0, 1, 1)
--local scaled = love.image.newImageDataFromDimensions(width*i, height*i)
--for y = 0, height*i-1 do
-- for x = 0, width*i-1 do
-- local r, g, b, a = imagedata:getPixel(math.floor(x/i), math.floor(y/i))
-- scaled:setPixel(x, y, r, g, b, a)
-- end
--end
--return scaled
end
function changevolume(i)
music[1]:setVolume( 0.6*i )
music[2]:setVolume( 0.6*i )
music[3]:setVolume( 0.6*i )
musictitle:setVolume( 0.6*i )
musichighscore:setVolume( 0.6*i )
musicrocket4:setVolume( 0.6*i )
musicrocket1to3:setVolume( 0.6*i )
musicresults:setVolume( i )
highscoreintro:setVolume( 0.6*i )
musicoptions:setVolume( i )
boot:setVolume( i )
blockfall:setVolume( i )
blockturn:setVolume( i )
blockmove:setVolume( i )
lineclear:setVolume( i )
fourlineclear:setVolume( i )
gameover1:setVolume( i )
gameover2:setVolume( i )
pausesound:setVolume( i )
highscorebeep:setVolume( i )
newlevel:setVolume( 0.6*i )
end
function loadoptions()
if love.filesystem.exists("options.txt") then
local s = love.filesystem.read("options.txt")
local split1 = s:split("\n")
for i = 1, #split1 do
local split2 = split1[i]:split("=")
if split2[1] == "volume" then
local v = tonumber(split2[2])
--clamp and round
if v < 0 then
v = 0
elseif v > 1 then
v = 1
end
v = math.floor(v*10)/10
volume = v
elseif split2[1] == "hue" then
hue = tonumber(split2[2])
elseif split2[1] == "scale" then
scale = tonumber(split2[2])
elseif split2[1] == "fullscreen" then
if split2[2] == "true" then
fullscreen = true
else
fullscreen = false
end
end
end
if volume == nil then
volume = 1
end
if hue == nil then
hue = 0.08
end
if fullscreen == nil then
fullscreen = false
end
if scale == nil then
scale = suggestedscale
end
else
volume = 1
hue = 0.08
autosize()
scale = suggestedscale
fullscreen = false
end
saveoptions()
end
function saveoptions()
local s = ""
s = s .. "volume=" .. volume .. "\n"
s = s .. "hue=" .. hue .. "\n"
s = s .. "scale=" .. scale .. "\n"
s = s .. "fullscreen=" .. tostring(fullscreen) .. "\n"
love.filesystem.write("options.txt", s)
end
function autosize()
local modes = love.graphics.getModes()
desktopwidth, desktopheight = modes[1]["width"], modes[1]["height"]
end
function togglefullscreen(fullscr)
fullscreen = fullscr
love.mouse.setVisible( not fullscreen )
if fullscr == false then
scale = suggestedscale
physicsscale = scale/4
love.graphics.setMode( 160*scale, 144*scale, false, vsync, 0 )
else
love.graphics.setMode( 0, 0, true, vsync, 16 )
desktopwidth, desktopheight = love.graphics.getWidth(), love.graphics.getHeight()
suggestedscale = math.min(math.floor((desktopheight-50)/144), math.floor((desktopwidth-10)/160))
suggestedscale = math.min(math.floor((desktopheight-50)/144), math.floor((desktopwidth-10)/160))
if suggestedscale > 5 then
suggestedscale = 5
end
maxscale = math.min(math.floor(desktopheight/144), math.floor(desktopwidth/160))
scale = maxscale
physicsscale = scale/4
fullscreenoffsetX = (desktopwidth-160*scale)/2
fullscreenoffsetY = (desktopheight-144*scale)/2
end
end
function loadhighscores()
if gameno == 1 then
fileloc = "highscoresA.txt"
else
fileloc = "highscoresB.txt"
end
if love.filesystem.exists( fileloc ) then
highdata = love.filesystem.read( fileloc )
highdata = highdata:split(";")
highscore = {}
highscorename = {}
for i = 1, 3 do
highscore[i] = tonumber(highdata[i*2])
highscorename[i] = string.lower(highdata[i*2-1])
end
else
highscore = {}
highscorename = {}
highscore[1] = 0
highscorename[1] = ""
highscore[2] = 0
highscorename[2] = ""
highscore[3] = 0
highscorename[3] = ""
savehighscores()
end
end
function newhighscores()
highscore = {}
highscorename = {}
highscore[1] = 0
highscorename[1] = ""
highscore[2] = 0
highscorename[2] = ""
highscore[3] = 0
highscorename[3] = ""
savehighscores()
end
function savehighscores()
if gameno == 1 then
fileloc = "highscoresA.txt"
else
fileloc = "highscoresB.txt"
end
highdata = ""
for i = 1, 3 do
highdata = highdata..highscorename[i]..";"..highscore[i]..";"
end
love.filesystem.write( fileloc, highdata.."\n" )
end
function changescale(i)
love.graphics.setMode( 160*i, 144*i, false, vsync, 0 )
nextpieceimg = {}
for j = 1, 7 do
nextpieceimg[j] = newPaddedImage( "graphics/pieces/"..j..".png", i )
end
physicsscale = i/4
end
function isElement(t, value)
for i, v in pairs(t) do
if v == value then
return true
end
end
return false
end
function string:split(delimiter)
local result = {}
local from = 1
local delim_from, delim_to = string.find( self, delimiter, from )
while delim_from do
table.insert( result, string.sub( self, from , delim_from-1 ) )
from = delim_to + 1
delim_from, delim_to = string.find( self, delimiter, from )
end
table.insert( result, string.sub( self, from ) )
return result
end
function pythagoras(a, b)
c = math.sqrt(a^2 + b^2)
if a < 0 or b < 0 then
c = -c
end
return c
end
function round(num, idp)
local mult = 10^(idp or 0)
return math.floor(num * mult + 0.5) / mult
end
function table2string(mytable)
output = {}
for i, v in pairs (mytable) do
output[i] = mytable[i]
end
return output
end
function getPoints2table(shape)
x1,y1,x2,y2,x3,y3,x4,y4,x5,y5,x6,y6,x7,y7,x8,y8 = shape:getPoints()
if x4 == nil then
return {x1,y1,x2,y2,x3,y3}
end
if x5 == nil then
return {x1,y1,x2,y2,x3,y3,x4,y4}
end
if x6 == nil then
return {x1,y1,x2,y2,x3,y3,x4,y4,x5,y5}
end
if x7 == nil then
return {x1,y1,x2,y2,x3,y3,x4,y4,x5,y5,x6,y6}
end
if x8 == nil then
return {x1,y1,x2,y2,x3,y3,x4,y4,x5,y5,x6,y6,x7,y7}
end
return {x1,y1,x2,y2,x3,y3,x4,y4,x5,y5,x6,y6,x7,y7,x8,y8}
end
function getrainbowcolor(i)
local r, g, b
if i < 1/6 then
r = 1
g = i*6
b = 0
elseif i >= 1/6 and i < 2/6 then
r = (1/6-(i-1/6))*6
g = 1
b = 0
elseif i >= 2/6 and i < 3/6 then
r = 0
g = 1
b = (i-2/6)*6
elseif i >= 3/6 and i < 4/6 then
r = 0
g = (1/6-(i-3/6))*6
b = 1
elseif i >= 4/6 and i < 5/6 then
r = (i-4/6)*6
g = 0
b = 1
else
r = 1
g = 0
b = (1/6-(i-5/6))*6
end
return {r, g, b}
end
-- TODO: Either remove any code that expects keyboard text input or use vita touch keyboard
function love.keypressed( key )
if gamestate == nil then
if controls.check("return", key) then
gamestate = "title"
love.graphics.setBackgroundColor( 0, 0, 0)
love.audio.play(musictitle)
oldtime = love.timer.getTime()
end
elseif gamestate == "logo" then
if controls.check("return", key) then
gamestate = "title"
love.graphics.setBackgroundColor( 0, 0, 0)
love.audio.play(musictitle)
oldtime = love.timer.getTime()
end
elseif gamestate == "credits" then
if controls.check("return", key) then
gamestate = "title"
love.graphics.setBackgroundColor( 0, 0, 0)
love.audio.play(musictitle)
oldtime = love.timer.getTime()
end
elseif gamestate == "title" then
if controls.check("return", key) then
if playerselection ~= 3 then
if soundenabled then
love.audio.stop(musictitle)
if musicno < 4 then
love.audio.play(music[musicno])
end
end
end
if playerselection == 1 then
gamestate = "menu"
elseif playerselection == 2 then
gamestate = "multimenu"
else
gamestate = "options"
if soundenabled then
love.audio.stop(musictitle)
love.audio.play(musicoptions)
end
optionsselection = 1
end
elseif controls.check("escape", key) then
love.event.push("q")
elseif controls.check("left", key) and playerselection > 1 then
playerselection = playerselection - 1
elseif controls.check("right", key) and playerselection < 3 then
playerselection = playerselection + 1
end
elseif gamestate == "menu" then
oldmusicno = musicno
if controls.check("escape", key) then
if musicno < 4 then
love.audio.stop(music[musicno])
end
gamestate = "title"
if soundenabled then
love.audio.stop(musictitle)
love.audio.play(musictitle)
end
elseif key == "backspace" then
newhighscores()
elseif controls.check("return", key) then
if gameno == 1 then
gameA_load()
else
gameB_load()
end
elseif controls.check("left", key) then
if selection == 2 or selection == 4 or selection == 6 then
selection = selection - 1
selectblink = true
oldtime = love.timer.getTime()
end
elseif controls.check("right", key) then
if selection == 1 or selection == 3 or selection == 5 then
selection = selection + 1
selectblink = true
oldtime = love.timer.getTime()
end
elseif controls.check("up", key) then
if selection == 3 or selection == 4 or selection == 5 or selection == 6 then
selection = selection - 2
selectblink = true
oldtime = love.timer.getTime()
if selection < 3 then
selection = gameno
selectblink = false
oldtime = love.timer.getTime()
end
elseif selection == 1 or selection == 2 then
selection = musicno + 2
selectblink = false
oldtime = love.timer.getTime()
end
elseif controls.check("down", key) then
if selection == 1 or selection == 2 or selection == 3 or selection == 4 then
selection = selection + 2
selectblink = true
oldtime = love.timer.getTime()
if selection > 2 and selection < 5 then
selection = musicno + 2
selectblink = false
oldtime = love.timer.getTime()
end
elseif selection == 5 or selection == 6 then
selection = gameno
selectblink = false
oldtime = love.timer.getTime()
end
end
if selection > 2 and not controls.check("escape", key) then
musicno = selection - 2
if oldmusicno ~= musicno and oldmusicno ~= 4 then
love.audio.stop(music[oldmusicno])
end
if musicno < 4 then
love.audio.play(music[musicno])
end
elseif not controls.check("escape", key) then
gameno = selection
loadhighscores()
end
elseif gamestate == "options" then
if controls.check("escape", key) then
if soundenabled then
love.audio.stop(musicoptions)
love.audio.stop(musictitle)
love.audio.play(musictitle)
end
saveoptions()
loadimages()
gamestate = "title"
elseif controls.check("down", key) then
optionsselection = optionsselection + 1
if optionsselection > #optionschoices then
optionsselection = 1
end
selectblink = true
oldtime = love.timer.getTime()
elseif controls.check("up", key) then
optionsselection = optionsselection - 1
if optionsselection == 0 then
optionsselection = #optionschoices
end
selectblink = true
oldtime = love.timer.getTime()
elseif controls.check("left", key) then
if optionsselection == 1 then
if volume >= 0.1 then
volume = volume - 0.1
if volume < 0.1 then
volume = 0
end
changevolume(volume)
end
elseif optionsselection == 3 then
if fullscreen == false then
if scale > 1 then
scale = scale - 1
changescale(scale)
end
end
elseif optionsselection == 4 then
if fullscreen == false then
togglefullscreen(true)
end
end
elseif controls.check("right", key) then
if optionsselection == 1 then
if volume <= 0.9 then
volume = volume + 0.1
changevolume(volume)
end
elseif optionsselection == 3 then
if fullscreen == false then
if scale < maxscale then
scale = scale + 1
changescale(scale)
end
end
elseif optionsselection == 4 then
if fullscreen == true then
togglefullscreen(false)
end
end
elseif controls.check("return", key) then
if optionsselection == 1 then
volume = 1
changevolume(volume)
elseif optionsselection == 2 then
hue = 0.08
optionsmenu = newPaddedImage("graphics/options.png");optionsmenu:setFilter( "nearest", "nearest" )
volumeslider = newPaddedImage("graphics/volumeslider.png");volumeslider:setFilter( "nearest", "nearest" )
elseif optionsselection == 3 then
if fullscreen == false then
if scale ~= suggestedscale then
scale = suggestedscale
changescale(scale)
end
end
elseif optionsselection == 4 then
if fullscreen == true then
togglefullscreen(false)
end
end
end
elseif gamestate == "multimenu" then
oldmusicno = musicno
if controls.check("escape", key) then
if musicno < 4 then
love.audio.stop(music[musicno])
end
gamestate = "title"
love.audio.stop(musictitle)
love.audio.play(musictitle)
elseif controls.check("return", key) then
gameBmulti_load()
elseif controls.check("left", key) then
if selection == 2 or selection == 4 or selection == 6 then
selection = selection - 1
selectblink = true
oldtime = love.timer.getTime()
end
elseif controls.check("right", key) then
if selection == 1 or selection == 3 or selection == 5 then
selection = selection + 1
selectblink = true
oldtime = love.timer.getTime()
end
elseif controls.check("up", key) then
if selection == 3 or selection == 4 or selection == 5 or selection == 6 then
selection = selection - 2
selectblink = true
oldtime = love.timer.getTime()
if selection < 3 then
selection = gameno
selectblink = false
oldtime = love.timer.getTime()
end
elseif selection == 1 or selection == 2 then
selection = musicno + 2
selectblink = false
oldtime = love.timer.getTime()
end
elseif controls.check("down", key) then
if selection == 1 or selection == 2 or selection == 3 or selection == 4 then
selection = selection + 2
selectblink = true
oldtime = love.timer.getTime()
if selection > 2 and selection < 5 then
selection = musicno + 2
selectblink = false
oldtime = love.timer.getTime()
end
elseif selection == 5 or selection == 6 then
selection = gameno
selectblink = false
oldtime = love.timer.getTime()
end
end
if selection > 2 and not controls.check("return", key) and not controls.check("escape", key) then
musicno = selection - 2
if oldmusicno ~= musicno and oldmusicno ~= 4 then
love.audio.stop(music[oldmusicno])
end
if musicno < 4 then
love.audio.play(music[musicno])
end
elseif not controls.check("return", key) and not controls.check("escape", key) then
gameno = selection
loadhighscores()
end
elseif gamestate == "gameA" or gamestate == "gameB" or gamestate == "failingA" or gamestate == "failingB" then
if controls.check("return", key) then
pause = not pause
if pause == true then
if musicno < 4 then
love.audio.pause(music[musicno])
end
love.audio.stop(pausesound)
love.audio.play(pausesound)
else
if musicno < 4 then
love.audio.resume(music[musicno])
end
end
end
if gamestate == "gameA" or gamestate == "gameB" then
if controls.check("escape", key) then
oldtime = love.timer.getTime()
gamestate = "menu"
end
if pause == false and (cuttingtimer == lineclearduration or gamestate == "gameB") then
--if key == "up" then --STOP ROTATION OF BLOCK (makes it too easy..)
-- tetribodies[counter]:setAngularVelocity(0)
--end
if controls.check("left", key) or controls.check("right", key) then
love.audio.stop(blockmove)
love.audio.play(blockmove)
elseif controls.check("rotateleft", key) or controls.check("rotateright", key) then
love.audio.stop(blockturn)
love.audio.play(blockturn)
end
end
end
elseif gamestate == "gameBmulti" and gamestarted == false then
if controls.check("escape", key) then
if not fullscreen then
love.graphics.setMode( 160*scale, 144*scale, false, vsync, 0 )
end
gamestate = "multimenu"
if musicno < 4 then
love.audio.play(music[musicno])
end
end
elseif gamestate == "gameBmulti" and gamestarted == true then
if controls.check("escape", key) then
if not fullscreen then
love.graphics.setMode( 160*scale, 144*scale, false, vsync, 0 )
end
gamestate = "multimenu"
end
if controls.check("left", key) or controls.check("right", key) or controls.check("leftp2", key) or controls.check("rightp2", key) then
love.audio.stop(blockmove)
love.audio.play(blockmove)
elseif controls.check("rotateleft", key) or controls.check("rotateright", key) or controls.check("rotaterightp2", key) or controls.check("rotateleftp2", key) then
love.audio.stop(blockturn)
love.audio.play(blockturn)
end
elseif gamestate == "gameBmulti_results" then
if controls.check("return", key) or controls.check("escape", key) then
if musicno < 4 then
love.audio.stop(musicresults)
love.audio.play(music[musicno])
end
if not fullscreen then
love.graphics.setMode( 160*scale, 144*scale, false, vsync, 0 )
end
gamestate = "multimenu"
end
elseif gamestate == "failed" then
if controls.check("return", key) or controls.check("escape", key) then
love.audio.stop(gameover2)
rocket_load()
end
elseif gamestate == "highscoreentry" then
if controls.check("return", key) then
gamestate = "menu"
savehighscores()
if musicchanged == true then
love.audio.stop(musichighscore)
else
love.audio.stop(highscoreintro)
end
if musicno < 4 then
love.audio.play(music[musicno])
end
elseif key == "backspace" then
if highscorename[highscoreno]:len() > 0 then
cursorblink = true
highscorename[highscoreno] = string.sub(highscorename[highscoreno], 1, highscorename[highscoreno]:len()-1)
end
end
elseif string.sub(gamestate, 1, 6) == "rocket" then
if controls.check("return", key) then
love.audio.stop(musicrocket1to3)
love.audio.stop(musicrocket4)
failed_checkhighscores()
end
end
end
|
local config = {}
function config.nvim_treesitter()
vim.api.nvim_command('set foldmethod=expr')
vim.api.nvim_command('set foldexpr=nvim_treesitter#foldexpr()')
require'nvim-treesitter.configs'.setup {
-- list install
ensure_installed = "maintained",
-- ensure_installed = { "bash", "c", "make", "cpp", "dart", "go", "gomod", "gowork", "java", "javascript", "jsdoc", "json", "json5", "kotlin", "llvm", "lua", "make" ,"markdown", "perl", "python", "regex", "rst", "rust", "toml", "typescript", "vim", "yaml" },
-- Must PackerCompile
sync_install = false,
highlight = {
enable = true,
},
-- ignore_install = { "javascript" },
textobjects = {
select = {
enable = true,
keymaps = {
["af"] = "@function.outer",
["if"] = "@function.inner",
["ac"] = "@class.outer",
["ic"] = "@class.inner",
},
},
},
}
-- require("nvim-treesitter.install").prefer_git = true
require("nvim-treesitter.install").command_extra_args = {
-- curl = { "--proxy", "https://192.168.1.112:1088" },
curl = { "--proxy", "http://192.168.1.112:8080" },
}
end
return config
|
csc = {}
csc.config = {}
include("cl_csc_config.lua")
net.Receive("csc.newMessage", function()
local id = net.ReadString()
local name = net.ReadString()
local text = net.ReadString()
chat.AddText(Color(25, 25, 220), "["..id.."] ", Color(25, 220, 25), name..": ", Color(235, 235, 235), text)
end) |
local finders = require('telescope.finders')
local previewers = require('telescope.previewers')
local pickers = require('telescope.pickers')
-- Create a new finder.
-- This finder, rather than taking a Lua list,
-- generates a shell command that should be run.
--
-- Each line of the shell command is converted to an entry,
-- and is possible to preview with builtin previews.
--
-- In this example, we use ripgrep to search over your entire directory
-- live as you type.
local live_grepper = finders.new_job(function(prompt)
if not prompt or prompt == "" then
return nil
end
return { 'rg', "--vimgrep", prompt}
end)
-- Create and run the Picker.
--
-- NOTE: No sorter is needed to be passed.
-- Results will be returned in the order they are received.
pickers.new({
prompt = 'Live Grep',
finder = live_grepper,
previewer = previewers.vimgrep,
}):find()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.