text
stringlengths
12
215k
b'Evaluate -58 - (-73 + 40) - -11.\n'
b'What is the value of -12 + 30 + 13 + -8 + -6?\n'
# -*- coding: utf8 -*- # Copyright (c) 2017-2021 THL A29 Limited, a Tencent company. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # 操作失败。 FAILEDOPERATION = 'FailedOperation' # API网关触发器创建失败。 FAILEDOPERATION_APIGATEWAY = 'FailedOperation.ApiGateway' # 创建触发器失败。 FAILEDOPERATION_APIGW = 'FailedOperation.Apigw' # 获取Apm InstanceId失败。 FAILEDOPERATION_APMCONFIGINSTANCEID = 'FailedOperation.ApmConfigInstanceId' # 当前异步事件状态不支持此操作,请稍后重试。 FAILEDOPERATION_ASYNCEVENTSTATUS = 'FailedOperation.AsyncEventStatus' # 复制函数失败。 FAILEDOPERATION_COPYFAILED = 'FailedOperation.CopyFailed' # 不支持复制到该地域。 FAILEDOPERATION_COPYFUNCTION = 'FailedOperation.CopyFunction' # 操作COS资源失败。 FAILEDOPERATION_COS = 'FailedOperation.Cos' # 创建别名失败。 FAILEDOPERATION_CREATEALIAS = 'FailedOperation.CreateAlias' # 操作失败。 FAILEDOPERATION_CREATEFUNCTION = 'FailedOperation.CreateFunction' # 创建命名空间失败。 FAILEDOPERATION_CREATENAMESPACE = 'FailedOperation.CreateNamespace' # 当前函数状态无法进行此操作。 FAILEDOPERATION_CREATETRIGGER = 'FailedOperation.CreateTrigger' # 当前调试状态无法执行此操作。 FAILEDOPERATION_DEBUGMODESTATUS = 'FailedOperation.DebugModeStatus' # 调试状态下无法更新执行超时时间。 FAILEDOPERATION_DEBUGMODEUPDATETIMEOUTFAIL = 'FailedOperation.DebugModeUpdateTimeOutFail' # 删除别名失败。 FAILEDOPERATION_DELETEALIAS = 'FailedOperation.DeleteAlias' # 当前函数状态无法进行此操作,请在函数状态正常时重试。 FAILEDOPERATION_DELETEFUNCTION = 'FailedOperation.DeleteFunction' # 删除layer版本失败。 FAILEDOPERATION_DELETELAYERVERSION = 'FailedOperation.DeleteLayerVersion' # 无法删除默认Namespace。 FAILEDOPERATION_DELETENAMESPACE = 'FailedOperation.DeleteNamespace' # 删除触发器失败。 FAILEDOPERATION_DELETETRIGGER = 'FailedOperation.DeleteTrigger' # 当前函数状态无法更新代码,请在状态为正常时更新。 FAILEDOPERATION_FUNCTIONNAMESTATUSERROR = 'FailedOperation.FunctionNameStatusError' # 函数在部署中,无法做此操作。 FAILEDOPERATION_FUNCTIONSTATUSERROR = 'FailedOperation.FunctionStatusError' # 当前函数版本状态无法进行此操作,请在版本状态为正常时重试。 FAILEDOPERATION_FUNCTIONVERSIONSTATUSNOTACTIVE = 'FailedOperation.FunctionVersionStatusNotActive' # 获取别名信息失败。 FAILEDOPERATION_GETALIAS = 'FailedOperation.GetAlias' # 获取函数代码地址失败。 FAILEDOPERATION_GETFUNCTIONADDRESS = 'FailedOperation.GetFunctionAddress' # 当前账号或命名空间处于欠费状态,请在可用时重试。 FAILEDOPERATION_INSUFFICIENTBALANCE = 'FailedOperation.InsufficientBalance' # 调用函数失败。 FAILEDOPERATION_INVOKEFUNCTION = 'FailedOperation.InvokeFunction' # 命名空间已存在,请勿重复创建。 FAILEDOPERATION_NAMESPACE = 'FailedOperation.Namespace' # 服务开通失败。 FAILEDOPERATION_OPENSERVICE = 'FailedOperation.OpenService' # 操作冲突。 FAILEDOPERATION_OPERATIONCONFLICT = 'FailedOperation.OperationConflict' # 创建定时预置任务失败。 FAILEDOPERATION_PROVISIONCREATETIMER = 'FailedOperation.ProvisionCreateTimer' # 删除定时预置任务失败。 FAILEDOPERATION_PROVISIONDELETETIMER = 'FailedOperation.ProvisionDeleteTimer' # 当前函数版本已有预置任务处于进行中,请稍后重试。 FAILEDOPERATION_PROVISIONEDINPROGRESS = 'FailedOperation.ProvisionedInProgress' # 发布layer版本失败。 FAILEDOPERATION_PUBLISHLAYERVERSION = 'FailedOperation.PublishLayerVersion' # 当前函数状态无法发布版本,请在状态为正常时发布。 FAILEDOPERATION_PUBLISHVERSION = 'FailedOperation.PublishVersion' # 角色不存在。 FAILEDOPERATION_QCSROLENOTFOUND = 'FailedOperation.QcsRoleNotFound' # 当前函数已有保留并发设置任务处于进行中,请稍后重试。 FAILEDOPERATION_RESERVEDINPROGRESS = 'FailedOperation.ReservedInProgress' # Topic不存在。 FAILEDOPERATION_TOPICNOTEXIST = 'FailedOperation.TopicNotExist' # 用户并发内存配额设置任务处于进行中,请稍后重试。 FAILEDOPERATION_TOTALCONCURRENCYMEMORYINPROGRESS = 'FailedOperation.TotalConcurrencyMemoryInProgress' # 指定的服务未开通,可以提交工单申请开通服务。 FAILEDOPERATION_UNOPENEDSERVICE = 'FailedOperation.UnOpenedService' # 更新别名失败。 FAILEDOPERATION_UPDATEALIAS = 'FailedOperation.UpdateAlias' # 当前函数状态无法更新代码,请在状态为正常时更新。 FAILEDOPERATION_UPDATEFUNCTIONCODE = 'FailedOperation.UpdateFunctionCode' # UpdateFunctionConfiguration操作失败。 FAILEDOPERATION_UPDATEFUNCTIONCONFIGURATION = 'FailedOperation.UpdateFunctionConfiguration' # 内部错误。 INTERNALERROR = 'InternalError' # 创建apigw触发器内部错误。 INTERNALERROR_APIGATEWAY = 'InternalError.ApiGateway' # ckafka接口失败。 INTERNALERROR_CKAFKA = 'InternalError.Ckafka' # 删除cmq触发器失败。 INTERNALERROR_CMQ = 'InternalError.Cmq' # 更新触发器失败。 INTERNALERROR_COS = 'InternalError.Cos' # ES错误。 INTERNALERROR_ES = 'InternalError.ES' # 内部服务异常。 INTERNALERROR_EXCEPTION = 'InternalError.Exception' # 内部服务错误。 INTERNALERROR_GETROLEERROR = 'InternalError.GetRoleError' # 内部系统错误。 INTERNALERROR_SYSTEM = 'InternalError.System' # 内部服务错误。 INTERNALERROR_SYSTEMERROR = 'InternalError.SystemError' # FunctionName取值与规范不符,请修正后再试。可参考:https://tencentcs.com/5jXKFnBW。 INVALIDPARAMETER_FUNCTIONNAME = 'InvalidParameter.FunctionName' # 请求参数不合法。 INVALIDPARAMETER_PAYLOAD = 'InvalidParameter.Payload' # RoutingConfig参数传入错误。 INVALIDPARAMETER_ROUTINGCONFIG = 'InvalidParameter.RoutingConfig' # 参数取值错误。 INVALIDPARAMETERVALUE = 'InvalidParameterValue' # Action取值与规范不符,请修正后再试。可参考:https://tencentcs.com/5jXKFnBW。 INVALIDPARAMETERVALUE_ACTION = 'InvalidParameterValue.Action' # AdditionalVersionWeights参数传入错误。 INVALIDPARAMETERVALUE_ADDITIONALVERSIONWEIGHTS = 'InvalidParameterValue.AdditionalVersionWeights' # 不支持删除默认别名,请修正后重试。 INVALIDPARAMETERVALUE_ALIAS = 'InvalidParameterValue.Alias' # ApiGateway参数错误。 INVALIDPARAMETERVALUE_APIGATEWAY = 'InvalidParameterValue.ApiGateway' # ApmConfig参数传入错误。 INVALIDPARAMETERVALUE_APMCONFIG = 'InvalidParameterValue.ApmConfig' # ApmConfigInstanceId参数传入错误。 INVALIDPARAMETERVALUE_APMCONFIGINSTANCEID = 'InvalidParameterValue.ApmConfigInstanceId' # ApmConfigRegion参数传入错误。 INVALIDPARAMETERVALUE_APMCONFIGREGION = 'InvalidParameterValue.ApmConfigRegion' # Args 参数值有误。 INVALIDPARAMETERVALUE_ARGS = 'InvalidParameterValue.Args' # 函数异步重试配置参数无效。 INVALIDPARAMETERVALUE_ASYNCTRIGGERCONFIG = 'InvalidParameterValue.AsyncTriggerConfig' # Cdn传入错误。 INVALIDPARAMETERVALUE_CDN = 'InvalidParameterValue.Cdn' # cfs配置项重复。 INVALIDPARAMETERVALUE_CFSPARAMETERDUPLICATE = 'InvalidParameterValue.CfsParameterDuplicate' # cfs配置项取值与规范不符。 INVALIDPARAMETERVALUE_CFSPARAMETERERROR = 'InvalidParameterValue.CfsParameterError' # cfs参数格式与规范不符。 INVALIDPARAMETERVALUE_CFSSTRUCTIONERROR = 'InvalidParameterValue.CfsStructionError' # Ckafka传入错误。 INVALIDPARAMETERVALUE_CKAFKA = 'InvalidParameterValue.Ckafka' # 运行函数时的参数传入有误。 INVALIDPARAMETERVALUE_CLIENTCONTEXT = 'InvalidParameterValue.ClientContext' # Cls传入错误。 INVALIDPARAMETERVALUE_CLS = 'InvalidParameterValue.Cls' # 修改Cls配置需要传入Role参数,请修正后重试。 INVALIDPARAMETERVALUE_CLSROLE = 'InvalidParameterValue.ClsRole' # Cmq传入错误。 INVALIDPARAMETERVALUE_CMQ = 'InvalidParameterValue.Cmq' # Code传入错误。 INVALIDPARAMETERVALUE_CODE = 'InvalidParameterValue.Code' # CodeSecret传入错误。 INVALIDPARAMETERVALUE_CODESECRET = 'InvalidParameterValue.CodeSecret' # CodeSource传入错误。 INVALIDPARAMETERVALUE_CODESOURCE = 'InvalidParameterValue.CodeSource' # Command[Entrypoint] 参数值有误。 INVALIDPARAMETERVALUE_COMMAND = 'InvalidParameterValue.Command' # CompatibleRuntimes参数传入错误。 INVALIDPARAMETERVALUE_COMPATIBLERUNTIMES = 'InvalidParameterValue.CompatibleRuntimes' # Content参数传入错误。 INVALIDPARAMETERVALUE_CONTENT = 'InvalidParameterValue.Content' # Cos传入错误。 INVALIDPARAMETERVALUE_COS = 'InvalidParameterValue.Cos' # CosBucketName不符合规范。 INVALIDPARAMETERVALUE_COSBUCKETNAME = 'InvalidParameterValue.CosBucketName' # CosBucketRegion取值与规范不符,请修正后再试。可参考:https://tencentcs.com/5jXKFnBW。 INVALIDPARAMETERVALUE_COSBUCKETREGION = 'InvalidParameterValue.CosBucketRegion' # CosObjectName不符合规范。 INVALIDPARAMETERVALUE_COSOBJECTNAME = 'InvalidParameterValue.CosObjectName' # CustomArgument参数长度超限。 INVALIDPARAMETERVALUE_CUSTOMARGUMENT = 'InvalidParameterValue.CustomArgument' # DateTime传入错误。 INVALIDPARAMETERVALUE_DATETIME = 'InvalidParameterValue.DateTime' # DeadLetterConfig取值与规范不符,请修正后再试。可参考:https://tencentcs.com/5jXKFnBW。 INVALIDPARAMETERVALUE_DEADLETTERCONFIG = 'InvalidParameterValue.DeadLetterConfig' # 默认Namespace无法创建。 INVALIDPARAMETERVALUE_DEFAULTNAMESPACE = 'InvalidParameterValue.DefaultNamespace' # Description传入错误。 INVALIDPARAMETERVALUE_DESCRIPTION = 'InvalidParameterValue.Description' # 环境变量DNS[OS_NAMESERVER]配置有误。 INVALIDPARAMETERVALUE_DNSINFO = 'InvalidParameterValue.DnsInfo' # EipConfig参数错误。 INVALIDPARAMETERVALUE_EIPCONFIG = 'InvalidParameterValue.EipConfig' # Enable取值与规范不符,请修正后再试。可参考:https://tencentcs.com/5jXKFnBW。 INVALIDPARAMETERVALUE_ENABLE = 'InvalidParameterValue.Enable' # Environment传入错误。 INVALIDPARAMETERVALUE_ENVIRONMENT = 'InvalidParameterValue.Environment' # 环境变量大小超限,请保持在 4KB 以内。 INVALIDPARAMETERVALUE_ENVIRONMENTEXCEEDEDLIMIT = 'InvalidParameterValue.EnvironmentExceededLimit' # 不支持修改函数系统环境变量和运行环境变量。 INVALIDPARAMETERVALUE_ENVIRONMENTSYSTEMPROTECT = 'InvalidParameterValue.EnvironmentSystemProtect' # Filters参数错误。 INVALIDPARAMETERVALUE_FILTERS = 'InvalidParameterValue.Filters' # Function取值与规范不符,请修正后再试。可参考:https://tencentcs.com/5jXKFnBW。 INVALIDPARAMETERVALUE_FUNCTION = 'InvalidParameterValue.Function' # 函数不存在。 INVALIDPARAMETERVALUE_FUNCTIONNAME = 'InvalidParameterValue.FunctionName' # GitBranch不符合规范。 INVALIDPARAMETERVALUE_GITBRANCH = 'InvalidParameterValue.GitBranch' # GitCommitId取值与规范不符,请修正后再试。可参考:https://tencentcs.com/5jXKFnBW。 INVALIDPARAMETERVALUE_GITCOMMITID = 'InvalidParameterValue.GitCommitId' # GitDirectory不符合规范。 INVALIDPARAMETERVALUE_GITDIRECTORY = 'InvalidParameterValue.GitDirectory' # GitPassword不符合规范。 INVALIDPARAMETERVALUE_GITPASSWORD = 'InvalidParameterValue.GitPassword' # GitUrl不符合规范。 INVALIDPARAMETERVALUE_GITURL = 'InvalidParameterValue.GitUrl' # GitUserName不符合规范。 INVALIDPARAMETERVALUE_GITUSERNAME = 'InvalidParameterValue.GitUserName' # Handler传入错误。 INVALIDPARAMETERVALUE_HANDLER = 'InvalidParameterValue.Handler' # IdleTimeOut参数传入错误。 INVALIDPARAMETERVALUE_IDLETIMEOUT = 'InvalidParameterValue.IdleTimeOut' # imageUri 传入有误。 INVALIDPARAMETERVALUE_IMAGEURI = 'InvalidParameterValue.ImageUri' # InlineZipFile非法。 INVALIDPARAMETERVALUE_INLINEZIPFILE = 'InvalidParameterValue.InlineZipFile' # InvokeType取值与规范不符,请修正后再试。 INVALIDPARAMETERVALUE_INVOKETYPE = 'InvalidParameterValue.InvokeType' # L5Enable取值与规范不符,请修正后再试。 INVALIDPARAMETERVALUE_L5ENABLE = 'InvalidParameterValue.L5Enable' # LayerName参数传入错误。 INVALIDPARAMETERVALUE_LAYERNAME = 'InvalidParameterValue.LayerName' # Layers参数传入错误。 INVALIDPARAMETERVALUE_LAYERS = 'InvalidParameterValue.Layers' # Limit传入错误。 INVALIDPARAMETERVALUE_LIMIT = 'InvalidParameterValue.Limit' # 参数超出长度限制。 INVALIDPARAMETERVALUE_LIMITEXCEEDED = 'InvalidParameterValue.LimitExceeded' # Memory取值与规范不符,请修正后再试。可参考:https://tencentcs.com/5jXKFnBW。 INVALIDPARAMETERVALUE_MEMORY = 'InvalidParameterValue.Memory' # MemorySize错误。 INVALIDPARAMETERVALUE_MEMORYSIZE = 'InvalidParameterValue.MemorySize' # MinCapacity 参数传入错误。 INVALIDPARAMETERVALUE_MINCAPACITY = 'InvalidParameterValue.MinCapacity' # Name参数传入错误。 INVALIDPARAMETERVALUE_NAME = 'InvalidParameterValue.Name' # Namespace参数传入错误。 INVALIDPARAMETERVALUE_NAMESPACE = 'InvalidParameterValue.Namespace' # 规则不正确,Namespace为英文字母、数字、-_ 符号组成,长度30。 INVALIDPARAMETERVALUE_NAMESPACEINVALID = 'InvalidParameterValue.NamespaceInvalid' # NodeSpec 参数传入错误。 INVALIDPARAMETERVALUE_NODESPEC = 'InvalidParameterValue.NodeSpec' # NodeType 参数传入错误。 INVALIDPARAMETERVALUE_NODETYPE = 'InvalidParameterValue.NodeType' # 偏移量不合法。 INVALIDPARAMETERVALUE_OFFSET = 'InvalidParameterValue.Offset' # Order传入错误。 INVALIDPARAMETERVALUE_ORDER = 'InvalidParameterValue.Order' # OrderBy取值与规范不符,请修正后再试。可参考:https://tencentcs.com/5jXKFnBW。 INVALIDPARAMETERVALUE_ORDERBY = 'InvalidParameterValue.OrderBy' # 入参不是标准的json。 INVALIDPARAMETERVALUE_PARAM = 'InvalidParameterValue.Param' # ProtocolType参数传入错误。 INVALIDPARAMETERVALUE_PROTOCOLTYPE = 'InvalidParameterValue.ProtocolType' # 定时预置的cron配置重复。 INVALIDPARAMETERVALUE_PROVISIONTRIGGERCRONCONFIGDUPLICATE = 'InvalidParameterValue.ProvisionTriggerCronConfigDuplicate' # TriggerName参数传入错误。 INVALIDPARAMETERVALUE_PROVISIONTRIGGERNAME = 'InvalidParameterValue.ProvisionTriggerName' # TriggerName重复。 INVALIDPARAMETERVALUE_PROVISIONTRIGGERNAMEDUPLICATE = 'InvalidParameterValue.ProvisionTriggerNameDuplicate' # ProvisionType 参数传入错误。 INVALIDPARAMETERVALUE_PROVISIONTYPE = 'InvalidParameterValue.ProvisionType' # PublicNetConfig参数错误。 INVALIDPARAMETERVALUE_PUBLICNETCONFIG = 'InvalidParameterValue.PublicNetConfig' # 不支持的函数版本。 INVALIDPARAMETERVALUE_QUALIFIER = 'InvalidParameterValue.Qualifier' # 企业版镜像实例ID[RegistryId]传值错误。 INVALIDPARAMETERVALUE_REGISTRYID = 'InvalidParameterValue.RegistryId' # RetCode不合法。 INVALIDPARAMETERVALUE_RETCODE = 'InvalidParameterValue.RetCode' # RoutingConfig取值与规范不符,请修正后再试。可参考:https://tencentcs.com/5jXKFnBW。 INVALIDPARAMETERVALUE_ROUTINGCONFIG = 'InvalidParameterValue.RoutingConfig' # Runtime传入错误。 INVALIDPARAMETERVALUE_RUNTIME = 'InvalidParameterValue.Runtime' # searchkey 不是 Keyword,Tag 或者 Runtime。 INVALIDPARAMETERVALUE_SEARCHKEY = 'InvalidParameterValue.SearchKey' # SecretInfo错误。 INVALIDPARAMETERVALUE_SECRETINFO = 'InvalidParameterValue.SecretInfo' # ServiceName命名不规范。 INVALIDPARAMETERVALUE_SERVICENAME = 'InvalidParameterValue.ServiceName' # Stamp取值与规范不符,请修正后再试。 INVALIDPARAMETERVALUE_STAMP = 'InvalidParameterValue.Stamp' # 起始时间传入错误。 INVALIDPARAMETERVALUE_STARTTIME = 'InvalidParameterValue.StartTime' # 需要同时指定开始日期与结束日期。 INVALIDPARAMETERVALUE_STARTTIMEORENDTIME = 'InvalidParameterValue.StartTimeOrEndTime' # Status取值与规范不符,请修正后再试。 INVALIDPARAMETERVALUE_STATUS = 'InvalidParameterValue.Status' # 系统环境变量错误。 INVALIDPARAMETERVALUE_SYSTEMENVIRONMENT = 'InvalidParameterValue.SystemEnvironment' # 非法的TempCosObjectName。 INVALIDPARAMETERVALUE_TEMPCOSOBJECTNAME = 'InvalidParameterValue.TempCosObjectName' # TraceEnable取值与规范不符,请修正后再试。 INVALIDPARAMETERVALUE_TRACEENABLE = 'InvalidParameterValue.TraceEnable' # TrackingTarget 参数输入错误。 INVALIDPARAMETERVALUE_TRACKINGTARGET = 'InvalidParameterValue.TrackingTarget' # TriggerCronConfig参数传入错误。 INVALIDPARAMETERVALUE_TRIGGERCRONCONFIG = 'InvalidParameterValue.TriggerCronConfig' # TriggerCronConfig参数定时触发间隔小于指定值。 INVALIDPARAMETERVALUE_TRIGGERCRONCONFIGTIMEINTERVAL = 'InvalidParameterValue.TriggerCronConfigTimeInterval' # TriggerDesc传入参数错误。 INVALIDPARAMETERVALUE_TRIGGERDESC = 'InvalidParameterValue.TriggerDesc' # TriggerName传入错误。 INVALIDPARAMETERVALUE_TRIGGERNAME = 'InvalidParameterValue.TriggerName' # TriggerProvisionedConcurrencyNum参数传入错误。 INVALIDPARAMETERVALUE_TRIGGERPROVISIONEDCONCURRENCYNUM = 'InvalidParameterValue.TriggerProvisionedConcurrencyNum' # Type传入错误。 INVALIDPARAMETERVALUE_TYPE = 'InvalidParameterValue.Type' # 开启cfs配置的同时必须开启vpc。 INVALIDPARAMETERVALUE_VPCNOTSETWHENOPENCFS = 'InvalidParameterValue.VpcNotSetWhenOpenCfs' # WebSocketsParams参数传入错误。 INVALIDPARAMETERVALUE_WEBSOCKETSPARAMS = 'InvalidParameterValue.WebSocketsParams' # 检测到不是标准的zip文件,请重新压缩后再试。 INVALIDPARAMETERVALUE_ZIPFILE = 'InvalidParameterValue.ZipFile' # 压缩文件base64解码失败: `Incorrect padding`,请修正后再试。 INVALIDPARAMETERVALUE_ZIPFILEBASE64BINASCIIERROR = 'InvalidParameterValue.ZipFileBase64BinasciiError' # 别名个数超过最大限制。 LIMITEXCEEDED_ALIAS = 'LimitExceeded.Alias' # Cdn使用超过最大限制。 LIMITEXCEEDED_CDN = 'LimitExceeded.Cdn' # eip资源超限。 LIMITEXCEEDED_EIP = 'LimitExceeded.Eip' # 函数数量超出最大限制 ,可通过[提交工单](https://cloud.tencent.com/act/event/Online_service?from=scf%7Cindex)申请提升限制。 LIMITEXCEEDED_FUNCTION = 'LimitExceeded.Function' # 同一个主题下的函数超过最大限制。 LIMITEXCEEDED_FUNCTIONONTOPIC = 'LimitExceeded.FunctionOnTopic' # FunctionProvisionedConcurrencyMemory数量达到限制,可提交工单申请提升限制:https://tencentcs.com/7Fixwt63。 LIMITEXCEEDED_FUNCTIONPROVISIONEDCONCURRENCYMEMORY = 'LimitExceeded.FunctionProvisionedConcurrencyMemory' # 函数保留并发内存超限。 LIMITEXCEEDED_FUNCTIONRESERVEDCONCURRENCYMEMORY = 'LimitExceeded.FunctionReservedConcurrencyMemory' # FunctionTotalProvisionedConcurrencyMemory达到限制,可提交工单申请提升限制:https://tencentcs.com/7Fixwt63。 LIMITEXCEEDED_FUNCTIONTOTALPROVISIONEDCONCURRENCYMEMORY = 'LimitExceeded.FunctionTotalProvisionedConcurrencyMemory' # 函数预置并发总数达到限制。 LIMITEXCEEDED_FUNCTIONTOTALPROVISIONEDCONCURRENCYNUM = 'LimitExceeded.FunctionTotalProvisionedConcurrencyNum' # InitTimeout达到限制,可提交工单申请提升限制:https://tencentcs.com/7Fixwt63。 LIMITEXCEEDED_INITTIMEOUT = 'LimitExceeded.InitTimeout' # layer版本数量超出最大限制。 LIMITEXCEEDED_LAYERVERSIONS = 'LimitExceeded.LayerVersions' # layer数量超出最大限制。 LIMITEXCEEDED_LAYERS = 'LimitExceeded.Layers' # 内存超出最大限制。 LIMITEXCEEDED_MEMORY = 'LimitExceeded.Memory' # 函数异步重试配置消息保留时间超过限制。 LIMITEXCEEDED_MSGTTL = 'LimitExceeded.MsgTTL' # 命名空间数量超过最大限制,可通过[提交工单](https://cloud.tencent.com/act/event/Online_service?from=scf%7Cindex)申请提升限制。 LIMITEXCEEDED_NAMESPACE = 'LimitExceeded.Namespace' # Offset超出限制。 LIMITEXCEEDED_OFFSET = 'LimitExceeded.Offset' # 定时预置数量超过最大限制。 LIMITEXCEEDED_PROVISIONTRIGGERACTION = 'LimitExceeded.ProvisionTriggerAction' # 定时触发间隔小于最大限制。 LIMITEXCEEDED_PROVISIONTRIGGERINTERVAL = 'LimitExceeded.ProvisionTriggerInterval' # 配额超限。 LIMITEXCEEDED_QUOTA = 'LimitExceeded.Quota' # 函数异步重试配置异步重试次数超过限制。 LIMITEXCEEDED_RETRYNUM = 'LimitExceeded.RetryNum' # Timeout超出最大限制。 LIMITEXCEEDED_TIMEOUT = 'LimitExceeded.Timeout' # 用户并发内存配额超限。 LIMITEXCEEDED_TOTALCONCURRENCYMEMORY = 'LimitExceeded.TotalConcurrencyMemory' # 触发器数量超出最大限制,可通过[提交工单](https://cloud.tencent.com/act/event/Online_service?from=scf%7Cindex)申请提升限制。 LIMITEXCEEDED_TRIGGER = 'LimitExceeded.Trigger' # UserTotalConcurrencyMemory达到限制,可提交工单申请提升限制:https://tencentcs.com/7Fixwt63。 LIMITEXCEEDED_USERTOTALCONCURRENCYMEMORY = 'LimitExceeded.UserTotalConcurrencyMemory' # 缺少参数错误。 MISSINGPARAMETER = 'MissingParameter' # Code没有传入。 MISSINGPARAMETER_CODE = 'MissingParameter.Code' # 缺失 Runtime 字段。 MISSINGPARAMETER_RUNTIME = 'MissingParameter.Runtime' # 资源被占用。 RESOURCEINUSE = 'ResourceInUse' # Alias已被占用。 RESOURCEINUSE_ALIAS = 'ResourceInUse.Alias' # Cdn已被占用。 RESOURCEINUSE_CDN = 'ResourceInUse.Cdn' # Cmq已被占用。 RESOURCEINUSE_CMQ = 'ResourceInUse.Cmq' # Cos已被占用。 RESOURCEINUSE_COS = 'ResourceInUse.Cos' # 函数已存在。 RESOURCEINUSE_FUNCTION = 'ResourceInUse.Function' # FunctionName已存在。 RESOURCEINUSE_FUNCTIONNAME = 'ResourceInUse.FunctionName' # Layer版本正在使用中。 RESOURCEINUSE_LAYERVERSION = 'ResourceInUse.LayerVersion' # Namespace已存在。 RESOURCEINUSE_NAMESPACE = 'ResourceInUse.Namespace' # TriggerName已存在。 RESOURCEINUSE_TRIGGER = 'ResourceInUse.Trigger' # TriggerName已存在。 RESOURCEINUSE_TRIGGERNAME = 'ResourceInUse.TriggerName' # COS资源不足。 RESOURCEINSUFFICIENT_COS = 'ResourceInsufficient.COS' # 资源不存在。 RESOURCENOTFOUND = 'ResourceNotFound' # 别名不存在。 RESOURCENOTFOUND_ALIAS = 'ResourceNotFound.Alias' # 未找到指定的AsyncEvent,请创建后再试。 RESOURCENOTFOUND_ASYNCEVENT = 'ResourceNotFound.AsyncEvent' # Cdn不存在。 RESOURCENOTFOUND_CDN = 'ResourceNotFound.Cdn' # 指定的cfs下未找到您所指定的挂载点。 RESOURCENOTFOUND_CFSMOUNTINSNOTMATCH = 'ResourceNotFound.CfsMountInsNotMatch' # 检测cfs状态为不可用。 RESOURCENOTFOUND_CFSSTATUSERROR = 'ResourceNotFound.CfsStatusError' # cfs与云函数所处vpc不一致。 RESOURCENOTFOUND_CFSVPCNOTMATCH = 'ResourceNotFound.CfsVpcNotMatch' # Ckafka不存在。 RESOURCENOTFOUND_CKAFKA = 'ResourceNotFound.Ckafka' # Cmq不存在。 RESOURCENOTFOUND_CMQ = 'ResourceNotFound.Cmq' # Cos不存在。 RESOURCENOTFOUND_COS = 'ResourceNotFound.Cos' # 不存在的Demo。 RESOURCENOTFOUND_DEMO = 'ResourceNotFound.Demo' # 函数不存在。 RESOURCENOTFOUND_FUNCTION = 'ResourceNotFound.Function' # 函数不存在。 RESOURCENOTFOUND_FUNCTIONNAME = 'ResourceNotFound.FunctionName' # 函数版本不存在。 RESOURCENOTFOUND_FUNCTIONVERSION = 'ResourceNotFound.FunctionVersion' # 获取cfs挂载点信息错误。 RESOURCENOTFOUND_GETCFSMOUNTINSERROR = 'ResourceNotFound.GetCfsMountInsError' # 获取cfs信息错误。 RESOURCENOTFOUND_GETCFSNOTMATCH = 'ResourceNotFound.GetCfsNotMatch' # 未找到指定的ImageConfig,请创建后再试。 RESOURCENOTFOUND_IMAGECONFIG = 'ResourceNotFound.ImageConfig' # layer不存在。 RESOURCENOTFOUND_LAYER = 'ResourceNotFound.Layer' # Layer版本不存在。 RESOURCENOTFOUND_LAYERVERSION = 'ResourceNotFound.LayerVersion' # Namespace不存在。 RESOURCENOTFOUND_NAMESPACE = 'ResourceNotFound.Namespace' # 版本不存在。 RESOURCENOTFOUND_QUALIFIER = 'ResourceNotFound.Qualifier' # 角色不存在。 RESOURCENOTFOUND_ROLE = 'ResourceNotFound.Role' # Role不存在。 RESOURCENOTFOUND_ROLECHECK = 'ResourceNotFound.RoleCheck' # Timer不存在。 RESOURCENOTFOUND_TIMER = 'ResourceNotFound.Timer' # 并发内存配额资源未找到。 RESOURCENOTFOUND_TOTALCONCURRENCYMEMORY = 'ResourceNotFound.TotalConcurrencyMemory' # 触发器不存在。 RESOURCENOTFOUND_TRIGGER = 'ResourceNotFound.Trigger' # 版本不存在。 RESOURCENOTFOUND_VERSION = 'ResourceNotFound.Version' # VPC或子网不存在。 RESOURCENOTFOUND_VPC = 'ResourceNotFound.Vpc' # 余额不足,请先充值。 RESOURCEUNAVAILABLE_INSUFFICIENTBALANCE = 'ResourceUnavailable.InsufficientBalance' # Namespace不可用。 RESOURCEUNAVAILABLE_NAMESPACE = 'ResourceUnavailable.Namespace' # 未授权操作。 UNAUTHORIZEDOPERATION = 'UnauthorizedOperation' # CAM鉴权失败。 UNAUTHORIZEDOPERATION_CAM = 'UnauthorizedOperation.CAM' # 无访问代码权限。 UNAUTHORIZEDOPERATION_CODESECRET = 'UnauthorizedOperation.CodeSecret' # 没有权限。 UNAUTHORIZEDOPERATION_CREATETRIGGER = 'UnauthorizedOperation.CreateTrigger' # 没有权限的操作。 UNAUTHORIZEDOPERATION_DELETEFUNCTION = 'UnauthorizedOperation.DeleteFunction' # 没有权限。 UNAUTHORIZEDOPERATION_DELETETRIGGER = 'UnauthorizedOperation.DeleteTrigger' # 不是从控制台调用的该接口。 UNAUTHORIZEDOPERATION_NOTMC = 'UnauthorizedOperation.NotMC' # Region错误。 UNAUTHORIZEDOPERATION_REGION = 'UnauthorizedOperation.Region' # 没有权限访问您的Cos资源。 UNAUTHORIZEDOPERATION_ROLE = 'UnauthorizedOperation.Role' # TempCos的Appid和请求账户的APPID不一致。 UNAUTHORIZEDOPERATION_TEMPCOSAPPID = 'UnauthorizedOperation.TempCosAppid' # 无法进行此操作。 UNAUTHORIZEDOPERATION_UPDATEFUNCTIONCODE = 'UnauthorizedOperation.UpdateFunctionCode' # 操作不支持。 UNSUPPORTEDOPERATION = 'UnsupportedOperation' # 资源还有别名绑定,不支持当前操作,请解绑别名后重试。 UNSUPPORTEDOPERATION_ALIASBIND = 'UnsupportedOperation.AliasBind' # 指定的配置AsyncRunEnable暂不支持,请修正后再试。 UNSUPPORTEDOPERATION_ASYNCRUNENABLE = 'UnsupportedOperation.AsyncRunEnable' # Cdn不支持。 UNSUPPORTEDOPERATION_CDN = 'UnsupportedOperation.Cdn' # Cos操作不支持。 UNSUPPORTEDOPERATION_COS = 'UnsupportedOperation.Cos' # 指定的配置EipFixed暂不支持。 UNSUPPORTEDOPERATION_EIPFIXED = 'UnsupportedOperation.EipFixed' # 不支持此地域。 UNSUPPORTEDOPERATION_REGION = 'UnsupportedOperation.Region' # Trigger操作不支持。 UNSUPPORTEDOPERATION_TRIGGER = 'UnsupportedOperation.Trigger' # 指定的配置暂不支持,请修正后再试。 UNSUPPORTEDOPERATION_UPDATEFUNCTIONEVENTINVOKECONFIG = 'UnsupportedOperation.UpdateFunctionEventInvokeConfig' # 指定的配置VpcConfig暂不支持。 UNSUPPORTEDOPERATION_VPCCONFIG = 'UnsupportedOperation.VpcConfig'
b'What is -5 - -1 - (-95 - -110)?\n'
// make a linked list that has one member // then make 5 nodes - with each node having 1,2,3,4,5 as data // then print them out // then work out how to reverse the list by only changing the pointers // then print again #include <stdio.h> #include <stdlib.h> // Including this header to use malloc struct node { int num; struct node *next; }; struct node *head = NULL; struct node *p = NULL; void insert(int num) { struct node *point = (struct node*) malloc(sizeof(struct node)); point->num = num; point->next = NULL; if(head==NULL) { head = point; head->next = point; return; } p = head; while(p->next != head){ p = p->next; } p->next = point; point->next = head; } void printNum() { struct node *pntr = head; printf("\nhead:"); while(pntr->next != head) { printf(" %d ", pntr->num); pntr = pntr->next; } printf(" %d ", pntr->num); printf("\n"); } int main() { insert(1); insert(2); insert(3); insert(4); insert(5); printNum(); }
b'Evaluate -12 + (-5 - ((10 - 10) + 11)).\n'
b'Evaluate 3 + (-12 - (-1 + (-34 - -1))).\n'
*** View in [[English](README-en.md)][[中文](README.md)] *** # gocaptcha go语言验证码服务器 Feature ------- * 支持中文验证码 * 支持自定义词库、字库 * 支持自定义滤镜机制,通过滤镜来增加干扰,加大识别难度 * 当前的滤镜包括: * 支持干扰点 * 支持干扰线 * 支持其他模式的干扰 * 更多模式,可实现imagefilter接口来扩展 * 支持自定义存储引擎,存储引擎可扩展 * 目前支持的存储引擎包括: * 内置(buildin) * memcache * redis (from https://github.com/dtynn/gocaptcha) * 如需扩展存储引擎,可实现StoreInterface接口 Useage ------ **安装** go get github.com/hanguofeng/gocaptcha **Quick Start** 参考 [captcha_test.go](captcha_test.go) 参考 [samples/gocaptcha-server](samples/gocaptcha-server) [Demo](http://hanguofeng-gocaptcha.daoapp.io/) **文档** [[captcha.go Wiki](https://github.com/hanguofeng/gocaptcha/wiki)] TODO ---- * 运维管理工具 LICENCE ------- gocaptcha使用[[MIT许可协议](LICENSE)] 使用的开源软件列表,表示感谢 * https://github.com/dchest/captcha * https://github.com/golang/freetype * https://github.com/bradfitz/gomemcache * https://code.google.com/p/zpix/
require 'spec_helper' describe ZK::Threadpool do before do @threadpool = ZK::Threadpool.new end after do @threadpool.shutdown end describe :new do it %[should be running] do @threadpool.should be_running end it %[should use the default size] do @threadpool.size.should == ZK::Threadpool.default_size end end describe :defer do it %[should run the given block on a thread in the threadpool] do @th = nil @threadpool.defer { @th = Thread.current } wait_until(2) { @th } @th.should_not == Thread.current end it %[should barf if the argument is not callable] do bad_obj = flexmock(:not_callable) bad_obj.should_not respond_to(:call) lambda { @threadpool.defer(bad_obj) }.should raise_error(ArgumentError) end it %[should not barf if the threadpool is not running] do @threadpool.shutdown lambda { @threadpool.defer { "hai!" } }.should_not raise_error end end describe :on_exception do it %[should register a callback that will be called if an exception is raised on the threadpool] do @ary = [] @threadpool.on_exception { |exc| @ary << exc } @threadpool.defer { raise "ZOMG!" } wait_while(2) { @ary.empty? } @ary.length.should == 1 e = @ary.shift e.should be_kind_of(RuntimeError) e.message.should == 'ZOMG!' end end describe :shutdown do it %[should set running to false] do @threadpool.shutdown @threadpool.should_not be_running end end describe :start! do it %[should be able to start a threadpool that had previously been shutdown (reuse)] do @threadpool.shutdown @threadpool.start!.should be_true @threadpool.should be_running @rval = nil @threadpool.defer do @rval = true end wait_until(2) { @rval } @rval.should be_true end end describe :on_threadpool? do it %[should return true if we're currently executing on one of the threadpool threads] do @a = [] @threadpool.defer { @a << @threadpool.on_threadpool? } wait_while(2) { @a.empty? } @a.should_not be_empty @a.first.should be_true end end describe :pause_before_fork_in_parent do it %[should stop all running threads] do @threadpool.should be_running @threadpool.should be_alive @threadpool.pause_before_fork_in_parent @threadpool.should_not be_alive end it %[should raise InvalidStateError if already paused] do @threadpool.pause_before_fork_in_parent lambda { @threadpool.pause_before_fork_in_parent }.should raise_error(ZK::Exceptions::InvalidStateError) end end describe :resume_after_fork_in_parent do before do @threadpool.pause_before_fork_in_parent end it %[should start all threads running again] do @threadpool.resume_after_fork_in_parent @threadpool.should be_alive end it %[should raise InvalidStateError if not in paused state] do @threadpool.shutdown lambda { @threadpool.resume_after_fork_in_parent }.should raise_error(ZK::Exceptions::InvalidStateError) end it %[should run callbacks deferred while paused] do calls = [] num = 5 latch = Latch.new(num) num.times do |n| @threadpool.defer do calls << n latch.release end end @threadpool.resume_after_fork_in_parent latch.await(2) calls.should_not be_empty end end end
package com.gmail.hexragon.gn4rBot.command.ai; import com.gmail.hexragon.gn4rBot.managers.commands.CommandExecutor; import com.gmail.hexragon.gn4rBot.managers.commands.annotations.Command; import com.gmail.hexragon.gn4rBot.util.GnarMessage; import com.google.code.chatterbotapi.ChatterBot; import com.google.code.chatterbotapi.ChatterBotFactory; import com.google.code.chatterbotapi.ChatterBotSession; import com.google.code.chatterbotapi.ChatterBotType; import net.dv8tion.jda.entities.User; import org.apache.commons.lang3.StringUtils; import java.util.Map; import java.util.WeakHashMap; @Command( aliases = {"cbot", "cleverbot"}, usage = "(query)", description = "Talk to Clever-Bot." ) public class PrivateCleverbotCommand extends CommandExecutor { private ChatterBotFactory factory = new ChatterBotFactory(); private ChatterBotSession session = null; private Map<User, ChatterBotSession> sessionMap = new WeakHashMap<>(); @Override public void execute(GnarMessage message, String[] args) { try { if (!sessionMap.containsKey(message.getAuthor())) { ChatterBot bot = factory.create(ChatterBotType.CLEVERBOT); sessionMap.put(message.getAuthor(), bot.createSession()); } message.replyRaw(sessionMap.get(message.getAuthor()).think(StringUtils.join(args, " "))); } catch (Exception e) { message.reply("Chat Bot encountered an exception. Restarting. `:[`"); sessionMap.remove(message.getAuthor()); } } }
b'-6 - (2 - 10 - -4 - -2)\n'
b'Calculate (24 - -1) + -1 + 1699 + -1711.\n'
b'Calculate (8 - 8 - -4) + -6 - 0 - 5.\n'
function simulated_annealing(tuning_run::Run, channel::RemoteChannel; temperature::Function = log_temperature) iteration = 1 function iterate(tuning_run::Run) p = temperature(iteration) iteration += 1 return probabilistic_improvement(tuning_run, threshold = p) end technique(tuning_run, channel, iterate, name = "Simulated Annealing") end
b'What is the value of (-24 - -15) + (-13 - -10) + -7 + 1?\n'
#!/bin/sh # # Verifies that go code passes go fmt, go vet, golint, and go test. # lintignore=golintignore o=$(tempfile) fail() { echo Failed cat $o exit 1 } echo Formatting gofmt -l $(find . -name '*.go') 2>&1 > $o test $(wc -l $o | awk '{ print $1 }') = "0" || fail echo Vetting go vet ./... 2>&1 > $o || fail echo Linting if [ ! -e $lintignore ]; then touch $lintignore fi t=$(tempfile) golint . 2>&1 > $t diff $lintignore $t 2>&1 > $o || fail echo Testing go test ./... 2>&1 > $o || fail
// Copyright (c) 2012 Pieter Wuille // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "addrman.h" #include "hash.h" #include "serialize.h" #include "streams.h" int CAddrInfo::GetTriedBucket(const uint256& nKey) const { uint64_t hash1 = (CHashWriter(SER_GETHASH, 0) << nKey << GetKey()).GetHash().GetCheapHash(); uint64_t hash2 = (CHashWriter(SER_GETHASH, 0) << nKey << GetGroup() << (hash1 % ADDRMAN_TRIED_BUCKETS_PER_GROUP)).GetHash().GetCheapHash(); return hash2 % ADDRMAN_TRIED_BUCKET_COUNT; } int CAddrInfo::GetNewBucket(const uint256& nKey, const CNetAddr& src) const { std::vector<unsigned char> vchSourceGroupKey = src.GetGroup(); uint64_t hash1 = (CHashWriter(SER_GETHASH, 0) << nKey << GetGroup() << vchSourceGroupKey).GetHash().GetCheapHash(); uint64_t hash2 = (CHashWriter(SER_GETHASH, 0) << nKey << vchSourceGroupKey << (hash1 % ADDRMAN_NEW_BUCKETS_PER_SOURCE_GROUP)).GetHash().GetCheapHash(); return hash2 % ADDRMAN_NEW_BUCKET_COUNT; } int CAddrInfo::GetBucketPosition(const uint256 &nKey, bool fNew, int nBucket) const { uint64_t hash1 = (CHashWriter(SER_GETHASH, 0) << nKey << (fNew ? 'N' : 'K') << nBucket << GetKey()).GetHash().GetCheapHash(); return hash1 % ADDRMAN_BUCKET_SIZE; } bool CAddrInfo::IsTerrible(int64_t nNow) const { if (nLastTry && nLastTry >= nNow - 60) // never remove things tried in the last minute return false; if (nTime > nNow + 10 * 60) // came in a flying DeLorean return true; if (nTime == 0 || nNow - nTime > ADDRMAN_HORIZON_DAYS * 24 * 60 * 60) // not seen in recent history return true; if (nLastSuccess == 0 && nAttempts >= ADDRMAN_RETRIES) // tried N times and never a success return true; if (nNow - nLastSuccess > ADDRMAN_MIN_FAIL_DAYS * 24 * 60 * 60 && nAttempts >= ADDRMAN_MAX_FAILURES) // N successive failures in the last week return true; return false; } double CAddrInfo::GetChance(int64_t nNow) const { double fChance = 1.0; int64_t nSinceLastSeen = nNow - nTime; int64_t nSinceLastTry = nNow - nLastTry; if (nSinceLastSeen < 0) nSinceLastSeen = 0; if (nSinceLastTry < 0) nSinceLastTry = 0; // deprioritize very recent attempts away if (nSinceLastTry < 60 * 10) fChance *= 0.01; // deprioritize 66% after each failed attempt, but at most 1/28th to avoid the search taking forever or overly penalizing outages. fChance *= pow(0.66, std::min(nAttempts, 8)); return fChance; } CAddrInfo* CAddrMan::Find(const CNetAddr& addr, int* pnId) { std::map<CNetAddr, int>::iterator it = mapAddr.find(addr); if (it == mapAddr.end()) return NULL; if (pnId) *pnId = (*it).second; std::map<int, CAddrInfo>::iterator it2 = mapInfo.find((*it).second); if (it2 != mapInfo.end()) return &(*it2).second; return NULL; } CAddrInfo* CAddrMan::Create(const CAddress& addr, const CNetAddr& addrSource, int* pnId) { int nId = nIdCount++; mapInfo[nId] = CAddrInfo(addr, addrSource); mapAddr[addr] = nId; mapInfo[nId].nRandomPos = vRandom.size(); vRandom.push_back(nId); if (pnId) *pnId = nId; return &mapInfo[nId]; } void CAddrMan::SwapRandom(unsigned int nRndPos1, unsigned int nRndPos2) { if (nRndPos1 == nRndPos2) return; assert(nRndPos1 < vRandom.size() && nRndPos2 < vRandom.size()); int nId1 = vRandom[nRndPos1]; int nId2 = vRandom[nRndPos2]; assert(mapInfo.count(nId1) == 1); assert(mapInfo.count(nId2) == 1); mapInfo[nId1].nRandomPos = nRndPos2; mapInfo[nId2].nRandomPos = nRndPos1; vRandom[nRndPos1] = nId2; vRandom[nRndPos2] = nId1; } void CAddrMan::Delete(int nId) { assert(mapInfo.count(nId) != 0); CAddrInfo& info = mapInfo[nId]; assert(!info.fInTried); assert(info.nRefCount == 0); SwapRandom(info.nRandomPos, vRandom.size() - 1); vRandom.pop_back(); mapAddr.erase(info); mapInfo.erase(nId); nNew--; } void CAddrMan::ClearNew(int nUBucket, int nUBucketPos) { // if there is an entry in the specified bucket, delete it. if (vvNew[nUBucket][nUBucketPos] != -1) { int nIdDelete = vvNew[nUBucket][nUBucketPos]; CAddrInfo& infoDelete = mapInfo[nIdDelete]; assert(infoDelete.nRefCount > 0); infoDelete.nRefCount--; vvNew[nUBucket][nUBucketPos] = -1; if (infoDelete.nRefCount == 0) { Delete(nIdDelete); } } } void CAddrMan::MakeTried(CAddrInfo& info, int nId) { // remove the entry from all new buckets for (int bucket = 0; bucket < ADDRMAN_NEW_BUCKET_COUNT; bucket++) { int pos = info.GetBucketPosition(nKey, true, bucket); if (vvNew[bucket][pos] == nId) { vvNew[bucket][pos] = -1; info.nRefCount--; } } nNew--; assert(info.nRefCount == 0); // which tried bucket to move the entry to int nKBucket = info.GetTriedBucket(nKey); int nKBucketPos = info.GetBucketPosition(nKey, false, nKBucket); // first make space to add it (the existing tried entry there is moved to new, deleting whatever is there). if (vvTried[nKBucket][nKBucketPos] != -1) { // find an item to evict int nIdEvict = vvTried[nKBucket][nKBucketPos]; assert(mapInfo.count(nIdEvict) == 1); CAddrInfo& infoOld = mapInfo[nIdEvict]; // Remove the to-be-evicted item from the tried set. infoOld.fInTried = false; vvTried[nKBucket][nKBucketPos] = -1; nTried--; // find which new bucket it belongs to int nUBucket = infoOld.GetNewBucket(nKey); int nUBucketPos = infoOld.GetBucketPosition(nKey, true, nUBucket); ClearNew(nUBucket, nUBucketPos); assert(vvNew[nUBucket][nUBucketPos] == -1); // Enter it into the new set again. infoOld.nRefCount = 1; vvNew[nUBucket][nUBucketPos] = nIdEvict; nNew++; } assert(vvTried[nKBucket][nKBucketPos] == -1); vvTried[nKBucket][nKBucketPos] = nId; nTried++; info.fInTried = true; } void CAddrMan::Good_(const CService& addr, int64_t nTime) { int nId; CAddrInfo* pinfo = Find(addr, &nId); // if not found, bail out if (!pinfo) return; CAddrInfo& info = *pinfo; // check whether we are talking about the exact same CService (including same port) if (info != addr) return; // update info info.nLastSuccess = nTime; info.nLastTry = nTime; info.nAttempts = 0; // nTime is not updated here, to avoid leaking information about // currently-connected peers. // if it is already in the tried set, don't do anything else if (info.fInTried) return; // find a bucket it is in now int nRnd = RandomInt(ADDRMAN_NEW_BUCKET_COUNT); int nUBucket = -1; for (unsigned int n = 0; n < ADDRMAN_NEW_BUCKET_COUNT; n++) { int nB = (n + nRnd) % ADDRMAN_NEW_BUCKET_COUNT; int nBpos = info.GetBucketPosition(nKey, true, nB); if (vvNew[nB][nBpos] == nId) { nUBucket = nB; break; } } // if no bucket is found, something bad happened; // TODO: maybe re-add the node, but for now, just bail out if (nUBucket == -1) return; LogPrint("addrman", "Moving %s to tried\n", addr.ToString()); // move nId to the tried tables MakeTried(info, nId); } bool CAddrMan::Add_(const CAddress& addr, const CNetAddr& source, int64_t nTimePenalty) { if (!addr.IsRoutable()) return false; bool fNew = false; int nId; CAddrInfo* pinfo = Find(addr, &nId); if (pinfo) { // periodically update nTime bool fCurrentlyOnline = (GetAdjustedTime() - addr.nTime < 24 * 60 * 60); int64_t nUpdateInterval = (fCurrentlyOnline ? 60 * 60 : 24 * 60 * 60); if (addr.nTime && (!pinfo->nTime || pinfo->nTime < addr.nTime - nUpdateInterval - nTimePenalty)) pinfo->nTime = std::max((int64_t)0, addr.nTime - nTimePenalty); // add services pinfo->nServices |= addr.nServices; // do not update if no new information is present if (!addr.nTime || (pinfo->nTime && addr.nTime <= pinfo->nTime)) return false; // do not update if the entry was already in the "tried" table if (pinfo->fInTried) return false; // do not update if the max reference count is reached if (pinfo->nRefCount == ADDRMAN_NEW_BUCKETS_PER_ADDRESS) return false; // stochastic test: previous nRefCount == N: 2^N times harder to increase it int nFactor = 1; for (int n = 0; n < pinfo->nRefCount; n++) nFactor *= 2; if (nFactor > 1 && (RandomInt(nFactor) != 0)) return false; } else { pinfo = Create(addr, source, &nId); pinfo->nTime = std::max((int64_t)0, (int64_t)pinfo->nTime - nTimePenalty); nNew++; fNew = true; } int nUBucket = pinfo->GetNewBucket(nKey, source); int nUBucketPos = pinfo->GetBucketPosition(nKey, true, nUBucket); if (vvNew[nUBucket][nUBucketPos] != nId) { bool fInsert = vvNew[nUBucket][nUBucketPos] == -1; if (!fInsert) { CAddrInfo& infoExisting = mapInfo[vvNew[nUBucket][nUBucketPos]]; if (infoExisting.IsTerrible() || (infoExisting.nRefCount > 1 && pinfo->nRefCount == 0)) { // Overwrite the existing new table entry. fInsert = true; } } if (fInsert) { ClearNew(nUBucket, nUBucketPos); pinfo->nRefCount++; vvNew[nUBucket][nUBucketPos] = nId; } else { if (pinfo->nRefCount == 0) { Delete(nId); } } } return fNew; } void CAddrMan::Attempt_(const CService& addr, int64_t nTime) { CAddrInfo* pinfo = Find(addr); // if not found, bail out if (!pinfo) return; CAddrInfo& info = *pinfo; // check whether we are talking about the exact same CService (including same port) if (info != addr) return; // update info info.nLastTry = nTime; info.nAttempts++; } CAddrInfo CAddrMan::Select_(bool newOnly) { if (size() == 0) return CAddrInfo(); if (newOnly && nNew == 0) return CAddrInfo(); // Use a 50% chance for choosing between tried and new table entries. if (!newOnly && (nTried > 0 && (nNew == 0 || RandomInt(2) == 0))) { // use a tried node double fChanceFactor = 1.0; while (1) { int nKBucket = RandomInt(ADDRMAN_TRIED_BUCKET_COUNT); int nKBucketPos = RandomInt(ADDRMAN_BUCKET_SIZE); while (vvTried[nKBucket][nKBucketPos] == -1) { nKBucket = (nKBucket + insecure_rand()) % ADDRMAN_TRIED_BUCKET_COUNT; nKBucketPos = (nKBucketPos + insecure_rand()) % ADDRMAN_BUCKET_SIZE; } int nId = vvTried[nKBucket][nKBucketPos]; assert(mapInfo.count(nId) == 1); CAddrInfo& info = mapInfo[nId]; if (RandomInt(1 << 30) < fChanceFactor * info.GetChance() * (1 << 30)) return info; fChanceFactor *= 1.2; } } else { // use a new node double fChanceFactor = 1.0; while (1) { int nUBucket = RandomInt(ADDRMAN_NEW_BUCKET_COUNT); int nUBucketPos = RandomInt(ADDRMAN_BUCKET_SIZE); while (vvNew[nUBucket][nUBucketPos] == -1) { nUBucket = (nUBucket + insecure_rand()) % ADDRMAN_NEW_BUCKET_COUNT; nUBucketPos = (nUBucketPos + insecure_rand()) % ADDRMAN_BUCKET_SIZE; } int nId = vvNew[nUBucket][nUBucketPos]; assert(mapInfo.count(nId) == 1); CAddrInfo& info = mapInfo[nId]; if (RandomInt(1 << 30) < fChanceFactor * info.GetChance() * (1 << 30)) return info; fChanceFactor *= 1.2; } } } #ifdef DEBUG_ADDRMAN int CAddrMan::Check_() { std::set<int> setTried; std::map<int, int> mapNew; if (vRandom.size() != nTried + nNew) return -7; for (std::map<int, CAddrInfo>::iterator it = mapInfo.begin(); it != mapInfo.end(); it++) { int n = (*it).first; CAddrInfo& info = (*it).second; if (info.fInTried) { if (!info.nLastSuccess) return -1; if (info.nRefCount) return -2; setTried.insert(n); } else { if (info.nRefCount < 0 || info.nRefCount > ADDRMAN_NEW_BUCKETS_PER_ADDRESS) return -3; if (!info.nRefCount) return -4; mapNew[n] = info.nRefCount; } if (mapAddr[info] != n) return -5; if (info.nRandomPos < 0 || info.nRandomPos >= vRandom.size() || vRandom[info.nRandomPos] != n) return -14; if (info.nLastTry < 0) return -6; if (info.nLastSuccess < 0) return -8; } if (setTried.size() != nTried) return -9; if (mapNew.size() != nNew) return -10; for (int n = 0; n < ADDRMAN_TRIED_BUCKET_COUNT; n++) { for (int i = 0; i < ADDRMAN_BUCKET_SIZE; i++) { if (vvTried[n][i] != -1) { if (!setTried.count(vvTried[n][i])) return -11; if (mapInfo[vvTried[n][i]].GetTriedBucket(nKey) != n) return -17; if (mapInfo[vvTried[n][i]].GetBucketPosition(nKey, false, n) != i) return -18; setTried.erase(vvTried[n][i]); } } } for (int n = 0; n < ADDRMAN_NEW_BUCKET_COUNT; n++) { for (int i = 0; i < ADDRMAN_BUCKET_SIZE; i++) { if (vvNew[n][i] != -1) { if (!mapNew.count(vvNew[n][i])) return -12; if (mapInfo[vvNew[n][i]].GetBucketPosition(nKey, true, n) != i) return -19; if (--mapNew[vvNew[n][i]] == 0) mapNew.erase(vvNew[n][i]); } } } if (setTried.size()) return -13; if (mapNew.size()) return -15; if (nKey.IsNull()) return -16; return 0; } #endif void CAddrMan::GetAddr_(std::vector<CAddress>& vAddr) { unsigned int nNodes = ADDRMAN_GETADDR_MAX_PCT * vRandom.size() / 100; if (nNodes > ADDRMAN_GETADDR_MAX) nNodes = ADDRMAN_GETADDR_MAX; // gather a list of random nodes, skipping those of low quality for (unsigned int n = 0; n < vRandom.size(); n++) { if (vAddr.size() >= nNodes) break; int nRndPos = RandomInt(vRandom.size() - n) + n; SwapRandom(n, nRndPos); assert(mapInfo.count(vRandom[n]) == 1); const CAddrInfo& ai = mapInfo[vRandom[n]]; if (!ai.IsTerrible()) vAddr.push_back(ai); } } void CAddrMan::Connected_(const CService& addr, int64_t nTime) { CAddrInfo* pinfo = Find(addr); // if not found, bail out if (!pinfo) return; CAddrInfo& info = *pinfo; // check whether we are talking about the exact same CService (including same port) if (info != addr) return; // update info int64_t nUpdateInterval = 20 * 60; if (nTime - info.nTime > nUpdateInterval) info.nTime = nTime; } int CAddrMan::RandomInt(int nMax){ return GetRandInt(nMax); }
import test from 'ava'; import { spawn } from 'child_process'; test.cb('app should boot without exiting', (t) => { const cli = spawn('node', [ './cli' ]); cli.stderr.on('data', (param) => { console.log(param.toString()); }); cli.on('close', (code) => { t.fail(`app failed to boot ${code}`); }); setTimeout(() => { t.pass(); t.end(); cli.kill(); }, 500); });
## ![](Common/DeviceInfoPlugin/component/DeviceInfoPlugin_128x128.png) Device Info Plugin for Xamarin Simple way of getting common device information. ### Setup * Available on NuGet: http://www.nuget.org/packages/Xam.Plugin.DeviceInfo [![NuGet](https://img.shields.io/nuget/v/Xam.Plugin.DeviceInfo.svg?label=NuGet)](https://www.nuget.org/packages/Xam.Plugin.DeviceInfo/) * Install into your PCL project and Client projects. **Platform Support** |Platform|Supported|Version| | ------------------- | :-----------: | :------------------: | |Xamarin.iOS|Yes|iOS 7+| |Xamarin.iOS Unified|Yes|iOS 7+| |Xamarin.Android|Yes|API 10+| |Windows Phone Silverlight|Yes|8.0+| |Windows Phone RT|Yes|8.1+| |Windows Store RT|Yes|8.1+| |Windows 10 UWP|Yes|10+| |Xamarin.Mac|No|| ### API Usage Call **CrossDeviceInfo.Current** from any project or PCL to gain access to APIs. **GenerateAppId** Used to generate a unique Id for your app. ```csharp /// <summary> /// Generates a an AppId optionally using the PhoneId a prefix and a suffix and a Guid to ensure uniqueness /// /// The AppId format is as follows {prefix}guid{phoneid}{suffix}, where parts in {} are optional. /// </summary> /// <param name="usingPhoneId">Setting this to true adds the device specific id to the AppId (remember to give the app the correct permissions)</param> /// <param name="prefix">Sets the prefix of the AppId</param> /// <param name="suffix">Sets the suffix of the AppId</param> /// <returns></returns> string GenerateAppId(bool usingPhoneId = false, string prefix = null, string suffix = null); ``` **Id** ```csharp /// <summary> /// This is the device specific Id (remember the correct permissions in your app to use this) /// </summary> string Id { get; } ``` Important: Windows Phone: Permissions to add: ID_CAP_IDENTITY_DEVICE **Device Model** ```csharp /// <summary> /// Get the model of the device /// </summary> string Model { get; } ``` **Version** ```csharp /// <summary> /// Get the version of the Operating System /// </summary> string Version { get; } ``` Returns the specific version number of the OS such as: * iOS: 8.1 * Android: 4.4.4 * Windows Phone: 8.10.14219.0 * WinRT: always 8.1 until there is a work around **Platform** ```csharp /// <summary> /// Get the platform of the device /// </summary> Platform Platform { get; } ``` Returns the Platform Enum of: ```csharp public enum Platform { Android, iOS, WindowsPhone, Windows } ``` #### Contributors * [jamesmontemagno](https://github.com/jamesmontemagno) Thanks! #### License Dirived from: [@Cheesebaron](http://www.github.com/cheesebaron) //--------------------------------------------------------------------------------- // Copyright 2013 Tomasz Cielecki ([email protected]) // Licensed under the Apache License, Version 2.0 (the "License"); // You may not use this file except in compliance with the License. // You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, // INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR // CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // See the Apache 2 License for the specific language governing // permissions and limitations under the License. //---------------------------------------------------------------------------------
b'What is the value of (-50 - -30) + -11 - (-12 - -2)?\n'
match x: | it?(): true
namespace CSharpGL { partial class FormPropertyGrid { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.propertyGrid1 = new System.Windows.Forms.PropertyGrid(); this.SuspendLayout(); // // propertyGrid1 // this.propertyGrid1.Dock = System.Windows.Forms.DockStyle.Fill; this.propertyGrid1.Font = new System.Drawing.Font("宋体", 12F); this.propertyGrid1.Location = new System.Drawing.Point(0, 0); this.propertyGrid1.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); this.propertyGrid1.Name = "propertyGrid1"; this.propertyGrid1.Size = new System.Drawing.Size(534, 545); this.propertyGrid1.TabIndex = 0; // // FormProperyGrid // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(534, 545); this.Controls.Add(this.propertyGrid1); this.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); this.Name = "FormProperyGrid"; this.Text = "FormPropertyGrid"; this.ResumeLayout(false); } #endregion private System.Windows.Forms.PropertyGrid propertyGrid1; } }
b'What is 4 + -16 + 24 + (1 - 5) + -2?\n'
import { gql } from '@apollo/client' import avatarFragment from 'v2/components/AvatarUploader/fragments/avatar' export default gql` query AvatarCheck { me { ...Avatar } } ${avatarFragment} `
var express = require('../') , Router = express.Router , request = require('./support/http') , methods = require('methods') , assert = require('assert'); describe('Router', function(){ var router, app; beforeEach(function(){ router = new Router; app = express(); }) describe('.match(method, url, i)', function(){ it('should match based on index', function(){ router.route('get', '/foo', function(){}); router.route('get', '/foob?', function(){}); router.route('get', '/bar', function(){}); var method = 'GET'; var url = '/foo?bar=baz'; var route = router.match(method, url, 0); route.constructor.name.should.equal('Route'); route.method.should.equal('get'); route.path.should.equal('/foo'); var route = router.match(method, url, 1); route.path.should.equal('/foob?'); var route = router.match(method, url, 2); assert(!route); url = '/bar'; var route = router.match(method, url); route.path.should.equal('/bar'); }) }) describe('.matchRequest(req, i)', function(){ it('should match based on index', function(){ router.route('get', '/foo', function(){}); router.route('get', '/foob?', function(){}); router.route('get', '/bar', function(){}); var req = { method: 'GET', url: '/foo?bar=baz' }; var route = router.matchRequest(req, 0); route.constructor.name.should.equal('Route'); route.method.should.equal('get'); route.path.should.equal('/foo'); var route = router.matchRequest(req, 1); req._route_index.should.equal(1); route.path.should.equal('/foob?'); var route = router.matchRequest(req, 2); assert(!route); req.url = '/bar'; var route = router.matchRequest(req); route.path.should.equal('/bar'); }) }) describe('.middleware', function(){ it('should dispatch', function(done){ router.route('get', '/foo', function(req, res){ res.send('foo'); }); app.use(router.middleware); request(app) .get('/foo') .expect('foo', done); }) }) describe('.multiple callbacks', function(){ it('should throw if a callback is null', function(){ assert.throws(function () { router.route('get', '/foo', null, function(){}); }) }) it('should throw if a callback is undefined', function(){ assert.throws(function () { router.route('get', '/foo', undefined, function(){}); }) }) it('should throw if a callback is not a function', function(){ assert.throws(function () { router.route('get', '/foo', 'not a function', function(){}); }) }) it('should not throw if all callbacks are functions', function(){ router.route('get', '/foo', function(){}, function(){}); }) }) describe('.all', function() { it('should support using .all to capture all http verbs', function() { var router = new Router(); router.all('/foo', function(){}); var url = '/foo?bar=baz'; methods.forEach(function testMethod(method) { var route = router.match(method, url); route.constructor.name.should.equal('Route'); route.method.should.equal(method); route.path.should.equal('/foo'); }); }) }) })
async function test(object) { for (var key in object) { await key; } }
b'What is 0 - -19 - (-7 + 16) - 13?\n'
b'Evaluate 42 + 0 + 0 + (252 - 259).\n'
b'What is the value of (-2 - 4) + (2 - ((-1 - 7) + 1))?\n'
--- title: A List of the White Rabbit Mechanics We Are Considering author: all date: 15/01/11 tags: [concept, summary, gamemechanics, whiterabbit] layout: post --- The white rabbit. Here is a list of some of the rabbits we could pull out of our designer's magical top hat. ## Cooperative Rope Walking ### Summary One scenario is while one person crawls across a cable to breach the hull of another ship, the other must move the ship in sync with the other ship to ensure the crawling player doesn't fall. Could further add elements of wind and obstacles. ### Pros + Very explicit cooperative components + Leaves room for interesting use of physics + Fits well as minigame between core hack and slash ### Cons + Direct cooperation between players requires very fast and accurate network syncing + Can be frustrating if your partner is very poor at this minigame ## Ghost with Visibility Goggles ### Summary While one player only sees shimmers of an enemy or an important object, the other can see it very clearly. They must cooperate ### Pros ### Cons ## Building Blocks with Imbuement > Originally by me but I find the gravitational singularities to be more interesting and probably even easier to implement. This could be interesting regardless and could be considered in another light where one player can imbue the weaponry of the others. - Calem ### Summary ### Pros ### Cons ## Cooperative Gravitational Singularities ### Summary Players get a singularity tool that can produce singularities that either push or pull all objects within a sphere of influence. The map would preferably be prepared to be interactive with this weapon. For the ice planet, this could be as simple as pre-subdividing the terrain mesh into large icy chunks and into ice shards that can damage enemies. Interesting physics based puzzles become available. In the prototype, this was used to traverse a bridge of objects trapped between to singularities. Another mode is allowing a double jump by jumping onto the top of a singularity, which pushes the character up or allows them to walk on top of the sphere of influence depending on the gravitational factor. ![Little dude traversing a bridge between singularities](http://i.imgur.com/FKQWq0h.png) ![Low framerate gif from proof of concept](http://i.gyazo.com/e228c30c5427656a8d0034d4c99f2f6e.gif) (note this image has a low framerate as it is a low quality gif :-) actual prototype is very smooth) Mesh collision can greatly improve the look and feel, but will dramatically reduce performance. Smooth performance with mesh collision limited to some 250 cubes. ![Mesh collision rather than box collision](http://i.imgur.com/H5u0owO.png) A bridge can be formed with 25 sheets if optimising for few objects with convex collision meshes. ![Flatter sheets bridge](http://i.imgur.com/sq5tF9N.png) ### Pros + Very easy to implemented if the prototyping is any indication + Adds more interesting components to level design + Purely physics based cooperation and problem solving, which should be very intuitive, deterministic (like Portal) + No particularly special considerations for AI + Concept has been tested for resource usage and does well without optimisations + Particle effects can be used to hide unrealistic collision a bit and make sense in the context of the singularity + Cooperative elements are less contrived, and if friendly fire is enabled accidentally sucking your partner into a singularity could be very amusing given the appropriate sound effects and cues ### Cons + Would require level design considerations beyond normal puzzle making (subdivisions) + Fine control of singularity location may be awkward (though could be easy if both joysticks used in fine control mode?) + Syncing physics of multiple bodies between players may be difficult and needs to be tested. + Approximated collision has to be used for the objects in the sphere of influence if there are going to be more than a couple hundred objects ## Transition into spirit with different environmental interactions ### Summary ### Pros ### Cons ## Time travelling with effects on past ### Summary ### Pros ### Cons ## Collector and defender with pinging for resource collection ### Summary ### Pros ### Cons ## Single item to share ### Summary > The mechanics of this need to be fleshed out more, I think. - Calem ### Pros ### Cons ## One player can transform the other, changing their abilities ### Summary ### Pros ### Cons
b'What is the value of 25 - (22 + -8 + -4)?\n'
package com.facetime.spring.support; import java.util.ArrayList; import java.util.List; import com.facetime.core.conf.ConfigUtils; import com.facetime.core.utils.StringUtils; /** * 分页类 * * @author yufei * @param <T> */ public class Page<T> { private static int BEGIN_PAGE_SIZE = 20; /** 下拉分页列表的递增数量级 */ private static int ADD_PAGE_SIZE_RATIO = 10; public static int DEFAULT_PAGE_SIZE = 10; private static int MAX_PAGE_SIZE = 200; private QueryInfo<T> queryInfo = null; private List<T> queryResult = null; public Page() { this(new QueryInfo<T>()); } public Page(QueryInfo<T> queryInfo) { this.queryInfo = queryInfo; this.queryResult = new ArrayList<T>(15); } /** * @return 下拉分页列表的递增数量级 */ public final static int getAddPageSize() { String addPageSizeRatio = ConfigUtils.getProperty("add_page_size_ratio"); if (StringUtils.isValid(addPageSizeRatio)) ADD_PAGE_SIZE_RATIO = Integer.parseInt(addPageSizeRatio); return ADD_PAGE_SIZE_RATIO; } /** * @return 默认分页下拉列表的开始值 */ public final static int getBeginPageSize() { String beginPageSize = ConfigUtils.getProperty("begin_page_size"); if (StringUtils.isValid(beginPageSize)) BEGIN_PAGE_SIZE = Integer.parseInt(beginPageSize); return BEGIN_PAGE_SIZE; } /** * 默认列表记录显示条数 */ public static final int getDefaultPageSize() { String defaultPageSize = ConfigUtils.getProperty("default_page_size"); if (StringUtils.isValid(defaultPageSize)) DEFAULT_PAGE_SIZE = Integer.parseInt(defaultPageSize); return DEFAULT_PAGE_SIZE; } /** * 默认分页列表显示的最大记录条数 */ public static final int getMaxPageSize() { String maxPageSize = ConfigUtils.getProperty("max_page_size"); if (StringUtils.isValid(maxPageSize)) { MAX_PAGE_SIZE = Integer.parseInt(maxPageSize); } return MAX_PAGE_SIZE; } public String getBeanName() { return this.queryInfo.getBeanName(); } public int getCurrentPageNo() { return this.queryInfo.getCurrentPageNo(); } public String getKey() { return this.queryInfo.getKey(); } public Integer getNeedRowNum() { return this.getPageSize() - this.getQueryResult().size(); } public long getNextPage() { return this.queryInfo.getNextPage(); } public int getPageCount() { return this.queryInfo.getPageCount(); } public int getPageSize() { return this.queryInfo.getPageSize(); } public List<T> getParams() { return this.queryInfo.getParams(); } public int getPreviousPage() { return this.queryInfo.getPreviousPage(); } public String[] getProperties() { return this.queryInfo.getProperties(); } public List<T> getQueryResult() { return this.queryResult; } public int getRecordCount() { return this.queryInfo.getRecordCount(); } public String getSql() { return this.queryInfo.getSql(); } public boolean isHasResult() { return this.queryResult != null && this.queryResult.size() > 0; } public void setBeanName(String beanNameValue) { this.queryInfo.setBeanName(beanNameValue); } public void setCurrentPageNo(int currentPageNo) { this.queryInfo.setCurrentPageNo(currentPageNo); } public void setKey(String keyValue) { this.queryInfo.setKey(keyValue); } public void setPageCount(int pageCount) { this.queryInfo.setPageCount(pageCount); } public void setPageSize(int pageSize) { this.queryInfo.setPageSize(pageSize); } public void setParams(List<T> paramsValue) { this.queryInfo.setParams(paramsValue); } public void setProperties(String[] propertiesValue) { this.queryInfo.setProperties(propertiesValue); } public void setQueryResult(List<T> list) { this.queryResult = list; } public void setRecordCount(int count) { this.queryInfo.setRecordCount(count); } public void setSql(String sql) { this.queryInfo.setSql(sql); } }
b'What is the value of 1 - -2 - (-1 + -4 + -13 + 20)?\n'
# Amaretti.js [![Join the chat at https://gitter.im/VincentCasse/amaretti.js](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/VincentCasse/amaretti.js?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![Build Status](https://travis-ci.org/VincentCasse/amaretti.js.svg)](https://travis-ci.org/VincentCasse/amaretti.js.svg) [![Coverage Status](https://coveralls.io/repos/VincentCasse/amaretti.js/badge.svg?branch=master&service=github)](https://coveralls.io/github/VincentCasse/amaretti.js?branch=master) Amaretti.js is a library to encrypt and decrypt message into the browser. They use native implementation (WebCrypto APIs) when available, or SJCL library when not. ## Getting started ### Installation This library can be installed with npm or bower, as you prefer: ```bash bower install amaretti ``` ```bash npm install amaretti ``` ### How to use it Just import the javascript file and require the library. Require system is included into amaretti library ```html <script src="public/vendor.js"></script> <script src="public/amaretti.js"></script> var Amaretti = require('amaretti').init(); ``` ### Generate a salt Salt are used into key generation and to randomize the encryption of a message. You can get a base64 salt using this `Amaretti.getSalt()` ```javascript Amaretti.getSalt().then(function(salt) { // Manipulate your salt }, function (error) { // There was an error }); ``` ### Generate a key To encrypt or decrypt messages, you need to use a key. You can generate a key usable with a passphrase (like a password). Key generated is returned as base64. To randomize the generation, you need to give a salt and a hash algorithm ```javascript Amaretti.generateKey(passphrase, salt, hash).then(function(key) { // Manipulate your key }, function (error) { // There was an error }); ``` * __passphrase__: is the passphrase used to encrypt or decrypt messages * __salt__: is the salt, base64 encoded, used to randomize the key generator * __hash__: is the name of algorithm used to hash the key. It could be _SHA-1_ or _SHA-256_ ### Encrypt a message You can encrypt a message with your key. Amaretti use AES-GCM to encrypt data. To avoid brut-force attack agains the encrypted data, each data had to be encrypt with a different and random nonce. You can use a salt as nonce. Don't lose this nonce, you will need it to decrypt the message. ```javascript Amaretti.encrypt(key, message, nonce).then(function(encrypted) { // Manipulate your encrypted message }, function (error) { // There was an error }); ``` * __key__: is the base64 used to encrypt message * __message__: is the message to encrypt * __nonce__: is a random value, in base64 format, use to avoid attacks ### Decrypt a message ```javascript Amaretti..decrypt(key, encrypted, nonce).then(function(decrypted) { // Manipulate your encrypted message }, function (error) { // There was an error }); ``` * __key__: is the base64 used to encrypt message * __encrypted: is the encrypted message to decrypt, in base64 format * __nonce__: is a random value, in base64 format, use to avoid attacks ## License MIT ## How to contribute Hum ... on github :) ### To build library ```bash npm install bower install brunch build ``` ### To run tests ```bash npm run test ``` ## Ideas for a roadmap * Return key and crypted data with JOSE standard (JWE and JWT) * Check sha-256 for firefox and sha-1 for SJCL ito key generation
# Limit rozbieżności **Ostrzeżenie! Ustawienie granicy rozbieżności nie powinno być zmieniane.** Zwiększenie granicy rozbieżności może spowodować znaczny spadek wydajności. Limit rozbieżności określa ilość adresów, które portfel wygeneruje i przeprowadzi prognozy, aby określić wykorzystanie. Domyślnie, limit rozbieżności jest ustawiony na 20. Oznacza to 2 rzeczy. 1. Kiedy portfel ładuje się po raz pierwszy, skanuje w poszukiwaniu adresów w użycia i oczekuje, że największa przerwa między adresami będzie wynosić 20; 2. Kiedy użytkownik otrzymuje nowo wygenerowane adresy, ich liczba wynosi tylko 20, następnie portfel wykonuje tą operację ponownie co powoduje, że luki pomiędzy adresami nie są większe niż 20. Tak naprawdę są tylko dwa przypadki w których należy zmienić tę wartość: 1. Jeśli twój portfel został stworzony i używany intensywnie przed v1.0, może mieć duże luki adresowe. Jeśli przywracasz portfel z seeda i zauważysz, że brakuje funduszy, możesz zwiększyć ustawienie do 100 (następnie 1000 jeśli problem wciąż występuje), a następnie ponownie uruchom Decrediton. Po przywróceniu funduszy możesz powrócić do 20. 2. Jeśli chcesz być w stanie wygenerować więcej niż 20 adresów na raz, bez kolejkowania.
b'0 + (-1 - 4) + 54 + -56\n'
# coding: utf-8 from sqlalchemy.testing import eq_, assert_raises, assert_raises_message, \ config, is_ import re from sqlalchemy.testing.util import picklers from sqlalchemy.interfaces import ConnectionProxy from sqlalchemy import MetaData, Integer, String, INT, VARCHAR, func, \ bindparam, select, event, TypeDecorator, create_engine, Sequence from sqlalchemy.sql import column, literal from sqlalchemy.testing.schema import Table, Column import sqlalchemy as tsa from sqlalchemy import testing from sqlalchemy.testing import engines from sqlalchemy import util from sqlalchemy.testing.engines import testing_engine import logging.handlers from sqlalchemy.dialects.oracle.zxjdbc import ReturningParam from sqlalchemy.engine import result as _result, default from sqlalchemy.engine.base import Engine from sqlalchemy.testing import fixtures from sqlalchemy.testing.mock import Mock, call, patch from contextlib import contextmanager users, metadata, users_autoinc = None, None, None class ExecuteTest(fixtures.TestBase): __backend__ = True @classmethod def setup_class(cls): global users, users_autoinc, metadata metadata = MetaData(testing.db) users = Table('users', metadata, Column('user_id', INT, primary_key=True, autoincrement=False), Column('user_name', VARCHAR(20)), ) users_autoinc = Table('users_autoinc', metadata, Column('user_id', INT, primary_key=True, test_needs_autoincrement=True), Column('user_name', VARCHAR(20)), ) metadata.create_all() @engines.close_first def teardown(self): testing.db.execute(users.delete()) @classmethod def teardown_class(cls): metadata.drop_all() @testing.fails_on("postgresql+pg8000", "pg8000 still doesn't allow single % without params") def test_no_params_option(self): stmt = "SELECT '%'" + testing.db.dialect.statement_compiler( testing.db.dialect, None).default_from() conn = testing.db.connect() result = conn.\ execution_options(no_parameters=True).\ scalar(stmt) eq_(result, '%') @testing.fails_on_everything_except('firebird', 'sqlite', '+pyodbc', '+mxodbc', '+zxjdbc', 'mysql+oursql') def test_raw_qmark(self): def go(conn): conn.execute('insert into users (user_id, user_name) ' 'values (?, ?)', (1, 'jack')) conn.execute('insert into users (user_id, user_name) ' 'values (?, ?)', [2, 'fred']) conn.execute('insert into users (user_id, user_name) ' 'values (?, ?)', [3, 'ed'], [4, 'horse']) conn.execute('insert into users (user_id, user_name) ' 'values (?, ?)', (5, 'barney'), (6, 'donkey')) conn.execute('insert into users (user_id, user_name) ' 'values (?, ?)', 7, 'sally') res = conn.execute('select * from users order by user_id') assert res.fetchall() == [ (1, 'jack'), (2, 'fred'), (3, 'ed'), (4, 'horse'), (5, 'barney'), (6, 'donkey'), (7, 'sally'), ] for multiparam, param in [ (("jack", "fred"), {}), ((["jack", "fred"],), {}) ]: res = conn.execute( "select * from users where user_name=? or " "user_name=? order by user_id", *multiparam, **param) assert res.fetchall() == [ (1, 'jack'), (2, 'fred') ] res = conn.execute("select * from users where user_name=?", "jack" ) assert res.fetchall() == [(1, 'jack')] conn.execute('delete from users') go(testing.db) conn = testing.db.connect() try: go(conn) finally: conn.close() # some psycopg2 versions bomb this. @testing.fails_on_everything_except('mysql+mysqldb', 'mysql+pymysql', 'mysql+cymysql', 'mysql+mysqlconnector', 'postgresql') @testing.fails_on('postgresql+zxjdbc', 'sprintf not supported') def test_raw_sprintf(self): def go(conn): conn.execute('insert into users (user_id, user_name) ' 'values (%s, %s)', [1, 'jack']) conn.execute('insert into users (user_id, user_name) ' 'values (%s, %s)', [2, 'ed'], [3, 'horse']) conn.execute('insert into users (user_id, user_name) ' 'values (%s, %s)', 4, 'sally') conn.execute('insert into users (user_id) values (%s)', 5) res = conn.execute('select * from users order by user_id') assert res.fetchall() == [(1, 'jack'), (2, 'ed'), (3, 'horse'), (4, 'sally'), (5, None)] for multiparam, param in [ (("jack", "ed"), {}), ((["jack", "ed"],), {}) ]: res = conn.execute( "select * from users where user_name=%s or " "user_name=%s order by user_id", *multiparam, **param) assert res.fetchall() == [ (1, 'jack'), (2, 'ed') ] res = conn.execute("select * from users where user_name=%s", "jack" ) assert res.fetchall() == [(1, 'jack')] conn.execute('delete from users') go(testing.db) conn = testing.db.connect() try: go(conn) finally: conn.close() # pyformat is supported for mysql, but skipping because a few driver # versions have a bug that bombs out on this test. (1.2.2b3, # 1.2.2c1, 1.2.2) @testing.skip_if(lambda : testing.against('mysql+mysqldb'), 'db-api flaky') @testing.fails_on_everything_except('postgresql+psycopg2', 'postgresql+pypostgresql', 'mysql+mysqlconnector', 'mysql+pymysql', 'mysql+cymysql') def test_raw_python(self): def go(conn): conn.execute('insert into users (user_id, user_name) ' 'values (%(id)s, %(name)s)', {'id': 1, 'name' : 'jack'}) conn.execute('insert into users (user_id, user_name) ' 'values (%(id)s, %(name)s)', {'id': 2, 'name' : 'ed'}, {'id': 3, 'name': 'horse'}) conn.execute('insert into users (user_id, user_name) ' 'values (%(id)s, %(name)s)', id=4, name='sally' ) res = conn.execute('select * from users order by user_id') assert res.fetchall() == [(1, 'jack'), (2, 'ed'), (3, 'horse'), (4, 'sally')] conn.execute('delete from users') go(testing.db) conn = testing.db.connect() try: go(conn) finally: conn.close() @testing.fails_on_everything_except('sqlite', 'oracle+cx_oracle') def test_raw_named(self): def go(conn): conn.execute('insert into users (user_id, user_name) ' 'values (:id, :name)', {'id': 1, 'name': 'jack' }) conn.execute('insert into users (user_id, user_name) ' 'values (:id, :name)', {'id': 2, 'name': 'ed' }, {'id': 3, 'name': 'horse'}) conn.execute('insert into users (user_id, user_name) ' 'values (:id, :name)', id=4, name='sally') res = conn.execute('select * from users order by user_id') assert res.fetchall() == [(1, 'jack'), (2, 'ed'), (3, 'horse'), (4, 'sally')] conn.execute('delete from users') go(testing.db) conn= testing.db.connect() try: go(conn) finally: conn.close() @testing.engines.close_open_connections def test_exception_wrapping_dbapi(self): conn = testing.db.connect() for _c in testing.db, conn: assert_raises_message( tsa.exc.DBAPIError, r"not_a_valid_statement", _c.execute, 'not_a_valid_statement' ) @testing.requires.sqlite def test_exception_wrapping_non_dbapi_error(self): e = create_engine('sqlite://') e.dialect.is_disconnect = is_disconnect = Mock() with e.connect() as c: c.connection.cursor = Mock( return_value=Mock( execute=Mock( side_effect=TypeError("I'm not a DBAPI error") )) ) assert_raises_message( TypeError, "I'm not a DBAPI error", c.execute, "select " ) eq_(is_disconnect.call_count, 0) def test_exception_wrapping_non_dbapi_statement(self): class MyType(TypeDecorator): impl = Integer def process_bind_param(self, value, dialect): raise Exception("nope") def _go(conn): assert_raises_message( tsa.exc.StatementError, r"nope \(original cause: Exception: nope\) u?'SELECT 1 ", conn.execute, select([1]).\ where( column('foo') == literal('bar', MyType()) ) ) _go(testing.db) conn = testing.db.connect() try: _go(conn) finally: conn.close() def test_stmt_exception_non_ascii(self): name = util.u('méil') with testing.db.connect() as conn: assert_raises_message( tsa.exc.StatementError, util.u( "A value is required for bind parameter 'uname'" r'.*SELECT users.user_name AS .m\\xe9il.') if util.py2k else util.u( "A value is required for bind parameter 'uname'" '.*SELECT users.user_name AS .méil.') , conn.execute, select([users.c.user_name.label(name)]).where( users.c.user_name == bindparam("uname")), {'uname_incorrect': 'foo'} ) def test_stmt_exception_pickleable_no_dbapi(self): self._test_stmt_exception_pickleable(Exception("hello world")) @testing.crashes("postgresql+psycopg2", "Older versions don't support cursor pickling, newer ones do") @testing.fails_on("mysql+oursql", "Exception doesn't come back exactly the same from pickle") @testing.fails_on("mysql+mysqlconnector", "Exception doesn't come back exactly the same from pickle") @testing.fails_on("oracle+cx_oracle", "cx_oracle exception seems to be having " "some issue with pickling") def test_stmt_exception_pickleable_plus_dbapi(self): raw = testing.db.raw_connection() the_orig = None try: try: cursor = raw.cursor() cursor.execute("SELECTINCORRECT") except testing.db.dialect.dbapi.DatabaseError as orig: # py3k has "orig" in local scope... the_orig = orig finally: raw.close() self._test_stmt_exception_pickleable(the_orig) def _test_stmt_exception_pickleable(self, orig): for sa_exc in ( tsa.exc.StatementError("some error", "select * from table", {"foo":"bar"}, orig), tsa.exc.InterfaceError("select * from table", {"foo":"bar"}, orig), tsa.exc.NoReferencedTableError("message", "tname"), tsa.exc.NoReferencedColumnError("message", "tname", "cname"), tsa.exc.CircularDependencyError("some message", [1, 2, 3], [(1, 2), (3, 4)]), ): for loads, dumps in picklers(): repickled = loads(dumps(sa_exc)) eq_(repickled.args[0], sa_exc.args[0]) if isinstance(sa_exc, tsa.exc.StatementError): eq_(repickled.params, {"foo":"bar"}) eq_(repickled.statement, sa_exc.statement) if hasattr(sa_exc, "connection_invalidated"): eq_(repickled.connection_invalidated, sa_exc.connection_invalidated) eq_(repickled.orig.args[0], orig.args[0]) def test_dont_wrap_mixin(self): class MyException(Exception, tsa.exc.DontWrapMixin): pass class MyType(TypeDecorator): impl = Integer def process_bind_param(self, value, dialect): raise MyException("nope") def _go(conn): assert_raises_message( MyException, "nope", conn.execute, select([1]).\ where( column('foo') == literal('bar', MyType()) ) ) _go(testing.db) conn = testing.db.connect() try: _go(conn) finally: conn.close() def test_empty_insert(self): """test that execute() interprets [] as a list with no params""" testing.db.execute(users_autoinc.insert(). values(user_name=bindparam('name', None)), []) eq_(testing.db.execute(users_autoinc.select()).fetchall(), [(1, None)]) @testing.requires.ad_hoc_engines def test_engine_level_options(self): eng = engines.testing_engine(options={'execution_options': {'foo': 'bar'}}) with eng.contextual_connect() as conn: eq_(conn._execution_options['foo'], 'bar') eq_(conn.execution_options(bat='hoho')._execution_options['foo' ], 'bar') eq_(conn.execution_options(bat='hoho')._execution_options['bat' ], 'hoho') eq_(conn.execution_options(foo='hoho')._execution_options['foo' ], 'hoho') eng.update_execution_options(foo='hoho') conn = eng.contextual_connect() eq_(conn._execution_options['foo'], 'hoho') @testing.requires.ad_hoc_engines def test_generative_engine_execution_options(self): eng = engines.testing_engine(options={'execution_options': {'base': 'x1'}}) eng1 = eng.execution_options(foo="b1") eng2 = eng.execution_options(foo="b2") eng1a = eng1.execution_options(bar="a1") eng2a = eng2.execution_options(foo="b3", bar="a2") eq_(eng._execution_options, {'base': 'x1'}) eq_(eng1._execution_options, {'base': 'x1', 'foo': 'b1'}) eq_(eng2._execution_options, {'base': 'x1', 'foo': 'b2'}) eq_(eng1a._execution_options, {'base': 'x1', 'foo': 'b1', 'bar': 'a1'}) eq_(eng2a._execution_options, {'base': 'x1', 'foo': 'b3', 'bar': 'a2'}) is_(eng1a.pool, eng.pool) # test pool is shared eng2.dispose() is_(eng1a.pool, eng2.pool) is_(eng.pool, eng2.pool) @testing.requires.ad_hoc_engines def test_generative_engine_event_dispatch(self): canary = [] def l1(*arg, **kw): canary.append("l1") def l2(*arg, **kw): canary.append("l2") def l3(*arg, **kw): canary.append("l3") eng = engines.testing_engine(options={'execution_options': {'base': 'x1'}}) event.listen(eng, "before_execute", l1) eng1 = eng.execution_options(foo="b1") event.listen(eng, "before_execute", l2) event.listen(eng1, "before_execute", l3) eng.execute(select([1])).close() eng1.execute(select([1])).close() eq_(canary, ["l1", "l2", "l3", "l1", "l2"]) @testing.requires.ad_hoc_engines def test_generative_engine_event_dispatch_hasevents(self): def l1(*arg, **kw): pass eng = create_engine(testing.db.url) assert not eng._has_events event.listen(eng, "before_execute", l1) eng2 = eng.execution_options(foo='bar') assert eng2._has_events def test_unicode_test_fails_warning(self): class MockCursor(engines.DBAPIProxyCursor): def execute(self, stmt, params=None, **kw): if "test unicode returns" in stmt: raise self.engine.dialect.dbapi.DatabaseError("boom") else: return super(MockCursor, self).execute(stmt, params, **kw) eng = engines.proxying_engine(cursor_cls=MockCursor) assert_raises_message( tsa.exc.SAWarning, "Exception attempting to detect unicode returns", eng.connect ) assert eng.dialect.returns_unicode_strings in (True, False) eng.dispose() def test_works_after_dispose(self): eng = create_engine(testing.db.url) for i in range(3): eq_(eng.scalar(select([1])), 1) eng.dispose() def test_works_after_dispose_testing_engine(self): eng = engines.testing_engine() for i in range(3): eq_(eng.scalar(select([1])), 1) eng.dispose() class ConvenienceExecuteTest(fixtures.TablesTest): __backend__ = True @classmethod def define_tables(cls, metadata): cls.table = Table('exec_test', metadata, Column('a', Integer), Column('b', Integer), test_needs_acid=True ) def _trans_fn(self, is_transaction=False): def go(conn, x, value=None): if is_transaction: conn = conn.connection conn.execute(self.table.insert().values(a=x, b=value)) return go def _trans_rollback_fn(self, is_transaction=False): def go(conn, x, value=None): if is_transaction: conn = conn.connection conn.execute(self.table.insert().values(a=x, b=value)) raise Exception("breakage") return go def _assert_no_data(self): eq_( testing.db.scalar(self.table.count()), 0 ) def _assert_fn(self, x, value=None): eq_( testing.db.execute(self.table.select()).fetchall(), [(x, value)] ) def test_transaction_engine_ctx_commit(self): fn = self._trans_fn() ctx = testing.db.begin() testing.run_as_contextmanager(ctx, fn, 5, value=8) self._assert_fn(5, value=8) def test_transaction_engine_ctx_begin_fails(self): engine = engines.testing_engine() mock_connection = Mock( return_value=Mock( begin=Mock(side_effect=Exception("boom")) ) ) engine._connection_cls = mock_connection assert_raises( Exception, engine.begin ) eq_( mock_connection.return_value.close.mock_calls, [call()] ) def test_transaction_engine_ctx_rollback(self): fn = self._trans_rollback_fn() ctx = testing.db.begin() assert_raises_message( Exception, "breakage", testing.run_as_contextmanager, ctx, fn, 5, value=8 ) self._assert_no_data() def test_transaction_tlocal_engine_ctx_commit(self): fn = self._trans_fn() engine = engines.testing_engine(options=dict( strategy='threadlocal', pool=testing.db.pool)) ctx = engine.begin() testing.run_as_contextmanager(ctx, fn, 5, value=8) self._assert_fn(5, value=8) def test_transaction_tlocal_engine_ctx_rollback(self): fn = self._trans_rollback_fn() engine = engines.testing_engine(options=dict( strategy='threadlocal', pool=testing.db.pool)) ctx = engine.begin() assert_raises_message( Exception, "breakage", testing.run_as_contextmanager, ctx, fn, 5, value=8 ) self._assert_no_data() def test_transaction_connection_ctx_commit(self): fn = self._trans_fn(True) conn = testing.db.connect() ctx = conn.begin() testing.run_as_contextmanager(ctx, fn, 5, value=8) self._assert_fn(5, value=8) def test_transaction_connection_ctx_rollback(self): fn = self._trans_rollback_fn(True) conn = testing.db.connect() ctx = conn.begin() assert_raises_message( Exception, "breakage", testing.run_as_contextmanager, ctx, fn, 5, value=8 ) self._assert_no_data() def test_connection_as_ctx(self): fn = self._trans_fn() ctx = testing.db.connect() testing.run_as_contextmanager(ctx, fn, 5, value=8) # autocommit is on self._assert_fn(5, value=8) @testing.fails_on('mysql+oursql', "oursql bug ? getting wrong rowcount") def test_connect_as_ctx_noautocommit(self): fn = self._trans_fn() self._assert_no_data() ctx = testing.db.connect().execution_options(autocommit=False) testing.run_as_contextmanager(ctx, fn, 5, value=8) # autocommit is off self._assert_no_data() def test_transaction_engine_fn_commit(self): fn = self._trans_fn() testing.db.transaction(fn, 5, value=8) self._assert_fn(5, value=8) def test_transaction_engine_fn_rollback(self): fn = self._trans_rollback_fn() assert_raises_message( Exception, "breakage", testing.db.transaction, fn, 5, value=8 ) self._assert_no_data() def test_transaction_connection_fn_commit(self): fn = self._trans_fn() conn = testing.db.connect() conn.transaction(fn, 5, value=8) self._assert_fn(5, value=8) def test_transaction_connection_fn_rollback(self): fn = self._trans_rollback_fn() conn = testing.db.connect() assert_raises( Exception, conn.transaction, fn, 5, value=8 ) self._assert_no_data() class CompiledCacheTest(fixtures.TestBase): __backend__ = True @classmethod def setup_class(cls): global users, metadata metadata = MetaData(testing.db) users = Table('users', metadata, Column('user_id', INT, primary_key=True, test_needs_autoincrement=True), Column('user_name', VARCHAR(20)), ) metadata.create_all() @engines.close_first def teardown(self): testing.db.execute(users.delete()) @classmethod def teardown_class(cls): metadata.drop_all() def test_cache(self): conn = testing.db.connect() cache = {} cached_conn = conn.execution_options(compiled_cache=cache) ins = users.insert() cached_conn.execute(ins, {'user_name':'u1'}) cached_conn.execute(ins, {'user_name':'u2'}) cached_conn.execute(ins, {'user_name':'u3'}) assert len(cache) == 1 eq_(conn.execute("select count(*) from users").scalar(), 3) class MockStrategyTest(fixtures.TestBase): def _engine_fixture(self): buf = util.StringIO() def dump(sql, *multiparams, **params): buf.write(util.text_type(sql.compile(dialect=engine.dialect))) engine = create_engine('postgresql://', strategy='mock', executor=dump) return engine, buf def test_sequence_not_duped(self): engine, buf = self._engine_fixture() metadata = MetaData() t = Table('testtable', metadata, Column('pk', Integer, Sequence('testtable_pk_seq'), primary_key=True) ) t.create(engine) t.drop(engine) eq_( re.findall(r'CREATE (\w+)', buf.getvalue()), ["SEQUENCE", "TABLE"] ) eq_( re.findall(r'DROP (\w+)', buf.getvalue()), ["SEQUENCE", "TABLE"] ) class ResultProxyTest(fixtures.TestBase): __backend__ = True def test_nontuple_row(self): """ensure the C version of BaseRowProxy handles duck-type-dependent rows.""" from sqlalchemy.engine import RowProxy class MyList(object): def __init__(self, l): self.l = l def __len__(self): return len(self.l) def __getitem__(self, i): return list.__getitem__(self.l, i) proxy = RowProxy(object(), MyList(['value']), [None], {'key' : (None, None, 0), 0: (None, None, 0)}) eq_(list(proxy), ['value']) eq_(proxy[0], 'value') eq_(proxy['key'], 'value') @testing.provide_metadata def test_no_rowcount_on_selects_inserts(self): """assert that rowcount is only called on deletes and updates. This because cursor.rowcount may can be expensive on some dialects such as Firebird, however many dialects require it be called before the cursor is closed. """ metadata = self.metadata engine = engines.testing_engine() t = Table('t1', metadata, Column('data', String(10)) ) metadata.create_all(engine) with patch.object(engine.dialect.execution_ctx_cls, "rowcount") as mock_rowcount: mock_rowcount.__get__ = Mock() engine.execute(t.insert(), {'data': 'd1'}, {'data': 'd2'}, {'data': 'd3'}) eq_(len(mock_rowcount.__get__.mock_calls), 0) eq_( engine.execute(t.select()).fetchall(), [('d1', ), ('d2', ), ('d3', )] ) eq_(len(mock_rowcount.__get__.mock_calls), 0) engine.execute(t.update(), {'data': 'd4'}) eq_(len(mock_rowcount.__get__.mock_calls), 1) engine.execute(t.delete()) eq_(len(mock_rowcount.__get__.mock_calls), 2) def test_rowproxy_is_sequence(self): import collections from sqlalchemy.engine import RowProxy row = RowProxy(object(), ['value'], [None], {'key' : (None, None, 0), 0: (None, None, 0)}) assert isinstance(row, collections.Sequence) @testing.requires.cextensions def test_row_c_sequence_check(self): import csv import collections metadata = MetaData() metadata.bind = 'sqlite://' users = Table('users', metadata, Column('id', Integer, primary_key=True), Column('name', String(40)), ) users.create() users.insert().execute(name='Test') row = users.select().execute().fetchone() s = util.StringIO() writer = csv.writer(s) # csv performs PySequenceCheck call writer.writerow(row) assert s.getvalue().strip() == '1,Test' @testing.requires.selectone def test_empty_accessors(self): statements = [ ( "select 1", [ lambda r: r.last_inserted_params(), lambda r: r.last_updated_params(), lambda r: r.prefetch_cols(), lambda r: r.postfetch_cols(), lambda r : r.inserted_primary_key ], "Statement is not a compiled expression construct." ), ( select([1]), [ lambda r: r.last_inserted_params(), lambda r : r.inserted_primary_key ], r"Statement is not an insert\(\) expression construct." ), ( select([1]), [ lambda r: r.last_updated_params(), ], r"Statement is not an update\(\) expression construct." ), ( select([1]), [ lambda r: r.prefetch_cols(), lambda r : r.postfetch_cols() ], r"Statement is not an insert\(\) " r"or update\(\) expression construct." ), ] for stmt, meths, msg in statements: r = testing.db.execute(stmt) try: for meth in meths: assert_raises_message( tsa.exc.InvalidRequestError, msg, meth, r ) finally: r.close() class ExecutionOptionsTest(fixtures.TestBase): def test_dialect_conn_options(self): engine = testing_engine("sqlite://", options=dict(_initialize=False)) engine.dialect = Mock() conn = engine.connect() c2 = conn.execution_options(foo="bar") eq_( engine.dialect.set_connection_execution_options.mock_calls, [call(c2, {"foo": "bar"})] ) def test_dialect_engine_options(self): engine = testing_engine("sqlite://") engine.dialect = Mock() e2 = engine.execution_options(foo="bar") eq_( engine.dialect.set_engine_execution_options.mock_calls, [call(e2, {"foo": "bar"})] ) def test_dialect_engine_construction_options(self): dialect = Mock() engine = Engine(Mock(), dialect, Mock(), execution_options={"foo": "bar"}) eq_( dialect.set_engine_execution_options.mock_calls, [call(engine, {"foo": "bar"})] ) def test_propagate_engine_to_connection(self): engine = testing_engine("sqlite://", options=dict(execution_options={"foo": "bar"})) conn = engine.connect() eq_(conn._execution_options, {"foo": "bar"}) def test_propagate_option_engine_to_connection(self): e1 = testing_engine("sqlite://", options=dict(execution_options={"foo": "bar"})) e2 = e1.execution_options(bat="hoho") c1 = e1.connect() c2 = e2.connect() eq_(c1._execution_options, {"foo": "bar"}) eq_(c2._execution_options, {"foo": "bar", "bat": "hoho"}) class AlternateResultProxyTest(fixtures.TestBase): __requires__ = ('sqlite', ) @classmethod def setup_class(cls): from sqlalchemy.engine import base, default cls.engine = engine = testing_engine('sqlite://') m = MetaData() cls.table = t = Table('test', m, Column('x', Integer, primary_key=True), Column('y', String(50, convert_unicode='force')) ) m.create_all(engine) engine.execute(t.insert(), [ {'x':i, 'y':"t_%d" % i} for i in range(1, 12) ]) def _test_proxy(self, cls): class ExcCtx(default.DefaultExecutionContext): def get_result_proxy(self): return cls(self) self.engine.dialect.execution_ctx_cls = ExcCtx rows = [] r = self.engine.execute(select([self.table])) assert isinstance(r, cls) for i in range(5): rows.append(r.fetchone()) eq_(rows, [(i, "t_%d" % i) for i in range(1, 6)]) rows = r.fetchmany(3) eq_(rows, [(i, "t_%d" % i) for i in range(6, 9)]) rows = r.fetchall() eq_(rows, [(i, "t_%d" % i) for i in range(9, 12)]) r = self.engine.execute(select([self.table])) rows = r.fetchmany(None) eq_(rows[0], (1, "t_1")) # number of rows here could be one, or the whole thing assert len(rows) == 1 or len(rows) == 11 r = self.engine.execute(select([self.table]).limit(1)) r.fetchone() eq_(r.fetchone(), None) r = self.engine.execute(select([self.table]).limit(5)) rows = r.fetchmany(6) eq_(rows, [(i, "t_%d" % i) for i in range(1, 6)]) def test_plain(self): self._test_proxy(_result.ResultProxy) def test_buffered_row_result_proxy(self): self._test_proxy(_result.BufferedRowResultProxy) def test_fully_buffered_result_proxy(self): self._test_proxy(_result.FullyBufferedResultProxy) def test_buffered_column_result_proxy(self): self._test_proxy(_result.BufferedColumnResultProxy) class EngineEventsTest(fixtures.TestBase): __requires__ = 'ad_hoc_engines', __backend__ = True def tearDown(self): Engine.dispatch._clear() Engine._has_events = False def _assert_stmts(self, expected, received): orig = list(received) for stmt, params, posn in expected: if not received: assert False, "Nothing available for stmt: %s" % stmt while received: teststmt, testparams, testmultiparams = \ received.pop(0) teststmt = re.compile(r'[\n\t ]+', re.M).sub(' ', teststmt).strip() if teststmt.startswith(stmt) and (testparams == params or testparams == posn): break def test_per_engine_independence(self): e1 = testing_engine(config.db_url) e2 = testing_engine(config.db_url) canary = Mock() event.listen(e1, "before_execute", canary) s1 = select([1]) s2 = select([2]) e1.execute(s1) e2.execute(s2) eq_( [arg[1][1] for arg in canary.mock_calls], [s1] ) event.listen(e2, "before_execute", canary) e1.execute(s1) e2.execute(s2) eq_([arg[1][1] for arg in canary.mock_calls], [s1, s1, s2]) def test_per_engine_plus_global(self): canary = Mock() event.listen(Engine, "before_execute", canary.be1) e1 = testing_engine(config.db_url) e2 = testing_engine(config.db_url) event.listen(e1, "before_execute", canary.be2) event.listen(Engine, "before_execute", canary.be3) e1.connect() e2.connect() e1.execute(select([1])) eq_(canary.be1.call_count, 1) eq_(canary.be2.call_count, 1) e2.execute(select([1])) eq_(canary.be1.call_count, 2) eq_(canary.be2.call_count, 1) eq_(canary.be3.call_count, 2) def test_per_connection_plus_engine(self): canary = Mock() e1 = testing_engine(config.db_url) event.listen(e1, "before_execute", canary.be1) conn = e1.connect() event.listen(conn, "before_execute", canary.be2) conn.execute(select([1])) eq_(canary.be1.call_count, 1) eq_(canary.be2.call_count, 1) conn._branch().execute(select([1])) eq_(canary.be1.call_count, 2) eq_(canary.be2.call_count, 2) def test_add_event_after_connect(self): # new feature as of #2978 canary = Mock() e1 = create_engine(config.db_url) assert not e1._has_events conn = e1.connect() event.listen(e1, "before_execute", canary.be1) conn.execute(select([1])) eq_(canary.be1.call_count, 1) conn._branch().execute(select([1])) eq_(canary.be1.call_count, 2) def test_force_conn_events_false(self): canary = Mock() e1 = create_engine(config.db_url) assert not e1._has_events event.listen(e1, "before_execute", canary.be1) conn = e1._connection_cls(e1, connection=e1.raw_connection(), _has_events=False) conn.execute(select([1])) eq_(canary.be1.call_count, 0) conn._branch().execute(select([1])) eq_(canary.be1.call_count, 0) def test_cursor_events_ctx_execute_scalar(self): canary = Mock() e1 = testing_engine(config.db_url) event.listen(e1, "before_cursor_execute", canary.bce) event.listen(e1, "after_cursor_execute", canary.ace) stmt = str(select([1]).compile(dialect=e1.dialect)) with e1.connect() as conn: dialect = conn.dialect ctx = dialect.execution_ctx_cls._init_statement( dialect, conn, conn.connection, stmt, {}) ctx._execute_scalar(stmt, Integer()) eq_(canary.bce.mock_calls, [call(conn, ctx.cursor, stmt, ctx.parameters[0], ctx, False)]) eq_(canary.ace.mock_calls, [call(conn, ctx.cursor, stmt, ctx.parameters[0], ctx, False)]) def test_cursor_events_execute(self): canary = Mock() e1 = testing_engine(config.db_url) event.listen(e1, "before_cursor_execute", canary.bce) event.listen(e1, "after_cursor_execute", canary.ace) stmt = str(select([1]).compile(dialect=e1.dialect)) with e1.connect() as conn: result = conn.execute(stmt) ctx = result.context eq_(canary.bce.mock_calls, [call(conn, ctx.cursor, stmt, ctx.parameters[0], ctx, False)]) eq_(canary.ace.mock_calls, [call(conn, ctx.cursor, stmt, ctx.parameters[0], ctx, False)]) def test_argument_format_execute(self): def before_execute(conn, clauseelement, multiparams, params): assert isinstance(multiparams, (list, tuple)) assert isinstance(params, dict) def after_execute(conn, clauseelement, multiparams, params, result): assert isinstance(multiparams, (list, tuple)) assert isinstance(params, dict) e1 = testing_engine(config.db_url) event.listen(e1, 'before_execute', before_execute) event.listen(e1, 'after_execute', after_execute) e1.execute(select([1])) e1.execute(select([1]).compile(dialect=e1.dialect).statement) e1.execute(select([1]).compile(dialect=e1.dialect)) e1._execute_compiled(select([1]).compile(dialect=e1.dialect), (), {}) @testing.fails_on('firebird', 'Data type unknown') def test_execute_events(self): stmts = [] cursor_stmts = [] def execute(conn, clauseelement, multiparams, params ): stmts.append((str(clauseelement), params, multiparams)) def cursor_execute(conn, cursor, statement, parameters, context, executemany): cursor_stmts.append((str(statement), parameters, None)) for engine in [ engines.testing_engine(options=dict(implicit_returning=False)), engines.testing_engine(options=dict(implicit_returning=False, strategy='threadlocal')), engines.testing_engine(options=dict(implicit_returning=False)).\ connect() ]: event.listen(engine, 'before_execute', execute) event.listen(engine, 'before_cursor_execute', cursor_execute) m = MetaData(engine) t1 = Table('t1', m, Column('c1', Integer, primary_key=True), Column('c2', String(50), default=func.lower('Foo'), primary_key=True) ) m.create_all() try: t1.insert().execute(c1=5, c2='some data') t1.insert().execute(c1=6) eq_(engine.execute('select * from t1').fetchall(), [(5, 'some data'), (6, 'foo')]) finally: m.drop_all() compiled = [('CREATE TABLE t1', {}, None), ('INSERT INTO t1 (c1, c2)', {'c2': 'some data', 'c1': 5}, None), ('INSERT INTO t1 (c1, c2)', {'c1': 6}, None), ('select * from t1', {}, None), ('DROP TABLE t1', {}, None)] # or engine.dialect.preexecute_pk_sequences: if not testing.against('oracle+zxjdbc'): cursor = [ ('CREATE TABLE t1', {}, ()), ('INSERT INTO t1 (c1, c2)', { 'c2': 'some data', 'c1': 5}, (5, 'some data')), ('SELECT lower', {'lower_2': 'Foo'}, ('Foo', )), ('INSERT INTO t1 (c1, c2)', {'c2': 'foo', 'c1': 6}, (6, 'foo')), ('select * from t1', {}, ()), ('DROP TABLE t1', {}, ()), ] else: insert2_params = 6, 'Foo' if testing.against('oracle+zxjdbc'): insert2_params += (ReturningParam(12), ) cursor = [('CREATE TABLE t1', {}, ()), ('INSERT INTO t1 (c1, c2)', {'c2': 'some data', 'c1': 5}, (5, 'some data')), ('INSERT INTO t1 (c1, c2)', {'c1': 6, 'lower_2': 'Foo'}, insert2_params), ('select * from t1', {}, ()), ('DROP TABLE t1', {}, ())] # bind param name 'lower_2' might # be incorrect self._assert_stmts(compiled, stmts) self._assert_stmts(cursor, cursor_stmts) def test_options(self): canary = [] def execute(conn, *args, **kw): canary.append('execute') def cursor_execute(conn, *args, **kw): canary.append('cursor_execute') engine = engines.testing_engine() event.listen(engine, 'before_execute', execute) event.listen(engine, 'before_cursor_execute', cursor_execute) conn = engine.connect() c2 = conn.execution_options(foo='bar') eq_(c2._execution_options, {'foo':'bar'}) c2.execute(select([1])) c3 = c2.execution_options(bar='bat') eq_(c3._execution_options, {'foo':'bar', 'bar':'bat'}) eq_(canary, ['execute', 'cursor_execute']) def test_retval_flag(self): canary = [] def tracker(name): def go(conn, *args, **kw): canary.append(name) return go def execute(conn, clauseelement, multiparams, params): canary.append('execute') return clauseelement, multiparams, params def cursor_execute(conn, cursor, statement, parameters, context, executemany): canary.append('cursor_execute') return statement, parameters engine = engines.testing_engine() assert_raises( tsa.exc.ArgumentError, event.listen, engine, "begin", tracker("begin"), retval=True ) event.listen(engine, "before_execute", execute, retval=True) event.listen(engine, "before_cursor_execute", cursor_execute, retval=True) engine.execute(select([1])) eq_( canary, ['execute', 'cursor_execute'] ) def test_engine_connect(self): engine = engines.testing_engine() tracker = Mock() event.listen(engine, "engine_connect", tracker) c1 = engine.connect() c2 = c1._branch() c1.close() eq_( tracker.mock_calls, [call(c1, False), call(c2, True)] ) def test_execution_options(self): engine = engines.testing_engine() engine_tracker = Mock() conn_tracker = Mock() event.listen(engine, "set_engine_execution_options", engine_tracker) event.listen(engine, "set_connection_execution_options", conn_tracker) e2 = engine.execution_options(e1='opt_e1') c1 = engine.connect() c2 = c1.execution_options(c1='opt_c1') c3 = e2.connect() c4 = c3.execution_options(c3='opt_c3') eq_( engine_tracker.mock_calls, [call(e2, {'e1': 'opt_e1'})] ) eq_( conn_tracker.mock_calls, [call(c2, {"c1": "opt_c1"}), call(c4, {"c3": "opt_c3"})] ) @testing.requires.sequences @testing.provide_metadata def test_cursor_execute(self): canary = [] def tracker(name): def go(conn, cursor, statement, parameters, context, executemany): canary.append((statement, context)) return go engine = engines.testing_engine() t = Table('t', self.metadata, Column('x', Integer, Sequence('t_id_seq'), primary_key=True), implicit_returning=False ) self.metadata.create_all(engine) with engine.begin() as conn: event.listen(conn, 'before_cursor_execute', tracker('cursor_execute')) conn.execute(t.insert()) # we see the sequence pre-executed in the first call assert "t_id_seq" in canary[0][0] assert "INSERT" in canary[1][0] # same context is_( canary[0][1], canary[1][1] ) def test_transactional(self): canary = [] def tracker(name): def go(conn, *args, **kw): canary.append(name) return go engine = engines.testing_engine() event.listen(engine, 'before_execute', tracker('execute')) event.listen(engine, 'before_cursor_execute', tracker('cursor_execute')) event.listen(engine, 'begin', tracker('begin')) event.listen(engine, 'commit', tracker('commit')) event.listen(engine, 'rollback', tracker('rollback')) conn = engine.connect() trans = conn.begin() conn.execute(select([1])) trans.rollback() trans = conn.begin() conn.execute(select([1])) trans.commit() eq_(canary, [ 'begin', 'execute', 'cursor_execute', 'rollback', 'begin', 'execute', 'cursor_execute', 'commit', ]) @testing.requires.savepoints @testing.requires.two_phase_transactions def test_transactional_advanced(self): canary1 = [] def tracker1(name): def go(*args, **kw): canary1.append(name) return go canary2 = [] def tracker2(name): def go(*args, **kw): canary2.append(name) return go engine = engines.testing_engine() for name in ['begin', 'savepoint', 'rollback_savepoint', 'release_savepoint', 'rollback', 'begin_twophase', 'prepare_twophase', 'commit_twophase']: event.listen(engine, '%s' % name, tracker1(name)) conn = engine.connect() for name in ['begin', 'savepoint', 'rollback_savepoint', 'release_savepoint', 'rollback', 'begin_twophase', 'prepare_twophase', 'commit_twophase']: event.listen(conn, '%s' % name, tracker2(name)) trans = conn.begin() trans2 = conn.begin_nested() conn.execute(select([1])) trans2.rollback() trans2 = conn.begin_nested() conn.execute(select([1])) trans2.commit() trans.rollback() trans = conn.begin_twophase() conn.execute(select([1])) trans.prepare() trans.commit() eq_(canary1, ['begin', 'savepoint', 'rollback_savepoint', 'savepoint', 'release_savepoint', 'rollback', 'begin_twophase', 'prepare_twophase', 'commit_twophase'] ) eq_(canary2, ['begin', 'savepoint', 'rollback_savepoint', 'savepoint', 'release_savepoint', 'rollback', 'begin_twophase', 'prepare_twophase', 'commit_twophase'] ) class HandleErrorTest(fixtures.TestBase): __requires__ = 'ad_hoc_engines', __backend__ = True def tearDown(self): Engine.dispatch._clear() Engine._has_events = False def test_legacy_dbapi_error(self): engine = engines.testing_engine() canary = Mock() event.listen(engine, "dbapi_error", canary) with engine.connect() as conn: try: conn.execute("SELECT FOO FROM I_DONT_EXIST") assert False except tsa.exc.DBAPIError as e: eq_(canary.mock_calls[0][1][5], e.orig) eq_(canary.mock_calls[0][1][2], "SELECT FOO FROM I_DONT_EXIST") def test_legacy_dbapi_error_no_ad_hoc_context(self): engine = engines.testing_engine() listener = Mock(return_value=None) event.listen(engine, 'dbapi_error', listener) nope = Exception("nope") class MyType(TypeDecorator): impl = Integer def process_bind_param(self, value, dialect): raise nope with engine.connect() as conn: assert_raises_message( tsa.exc.StatementError, r"nope \(original cause: Exception: nope\) u?'SELECT 1 ", conn.execute, select([1]).where( column('foo') == literal('bar', MyType())) ) # no legacy event eq_(listener.mock_calls, []) def test_legacy_dbapi_error_non_dbapi_error(self): engine = engines.testing_engine() listener = Mock(return_value=None) event.listen(engine, 'dbapi_error', listener) nope = TypeError("I'm not a DBAPI error") with engine.connect() as c: c.connection.cursor = Mock( return_value=Mock( execute=Mock( side_effect=nope )) ) assert_raises_message( TypeError, "I'm not a DBAPI error", c.execute, "select " ) # no legacy event eq_(listener.mock_calls, []) def test_handle_error(self): engine = engines.testing_engine() canary = Mock(return_value=None) event.listen(engine, "handle_error", canary) with engine.connect() as conn: try: conn.execute("SELECT FOO FROM I_DONT_EXIST") assert False except tsa.exc.DBAPIError as e: ctx = canary.mock_calls[0][1][0] eq_(ctx.original_exception, e.orig) is_(ctx.sqlalchemy_exception, e) eq_(ctx.statement, "SELECT FOO FROM I_DONT_EXIST") def test_exception_event_reraise(self): engine = engines.testing_engine() class MyException(Exception): pass @event.listens_for(engine, 'handle_error', retval=True) def err(context): stmt = context.statement exception = context.original_exception if "ERROR ONE" in str(stmt): return MyException("my exception") elif "ERROR TWO" in str(stmt): return exception else: return None conn = engine.connect() # case 1: custom exception assert_raises_message( MyException, "my exception", conn.execute, "SELECT 'ERROR ONE' FROM I_DONT_EXIST" ) # case 2: return the DBAPI exception we're given; # no wrapping should occur assert_raises( conn.dialect.dbapi.Error, conn.execute, "SELECT 'ERROR TWO' FROM I_DONT_EXIST" ) # case 3: normal wrapping assert_raises( tsa.exc.DBAPIError, conn.execute, "SELECT 'ERROR THREE' FROM I_DONT_EXIST" ) def test_exception_event_reraise_chaining(self): engine = engines.testing_engine() class MyException1(Exception): pass class MyException2(Exception): pass class MyException3(Exception): pass @event.listens_for(engine, 'handle_error', retval=True) def err1(context): stmt = context.statement if "ERROR ONE" in str(stmt) or "ERROR TWO" in str(stmt) \ or "ERROR THREE" in str(stmt): return MyException1("my exception") elif "ERROR FOUR" in str(stmt): raise MyException3("my exception short circuit") @event.listens_for(engine, 'handle_error', retval=True) def err2(context): stmt = context.statement if ("ERROR ONE" in str(stmt) or "ERROR FOUR" in str(stmt)) \ and isinstance(context.chained_exception, MyException1): raise MyException2("my exception chained") elif "ERROR TWO" in str(stmt): return context.chained_exception else: return None conn = engine.connect() with patch.object(engine. dialect.execution_ctx_cls, "handle_dbapi_exception") as patched: assert_raises_message( MyException2, "my exception chained", conn.execute, "SELECT 'ERROR ONE' FROM I_DONT_EXIST" ) eq_(patched.call_count, 1) with patch.object(engine. dialect.execution_ctx_cls, "handle_dbapi_exception") as patched: assert_raises( MyException1, conn.execute, "SELECT 'ERROR TWO' FROM I_DONT_EXIST" ) eq_(patched.call_count, 1) with patch.object(engine. dialect.execution_ctx_cls, "handle_dbapi_exception") as patched: # test that non None from err1 isn't cancelled out # by err2 assert_raises( MyException1, conn.execute, "SELECT 'ERROR THREE' FROM I_DONT_EXIST" ) eq_(patched.call_count, 1) with patch.object(engine. dialect.execution_ctx_cls, "handle_dbapi_exception") as patched: assert_raises( tsa.exc.DBAPIError, conn.execute, "SELECT 'ERROR FIVE' FROM I_DONT_EXIST" ) eq_(patched.call_count, 1) with patch.object(engine. dialect.execution_ctx_cls, "handle_dbapi_exception") as patched: assert_raises_message( MyException3, "my exception short circuit", conn.execute, "SELECT 'ERROR FOUR' FROM I_DONT_EXIST" ) eq_(patched.call_count, 1) def test_exception_event_ad_hoc_context(self): """test that handle_error is called with a context in cases where _handle_dbapi_error() is normally called without any context. """ engine = engines.testing_engine() listener = Mock(return_value=None) event.listen(engine, 'handle_error', listener) nope = Exception("nope") class MyType(TypeDecorator): impl = Integer def process_bind_param(self, value, dialect): raise nope with engine.connect() as conn: assert_raises_message( tsa.exc.StatementError, r"nope \(original cause: Exception: nope\) u?'SELECT 1 ", conn.execute, select([1]).where( column('foo') == literal('bar', MyType())) ) ctx = listener.mock_calls[0][1][0] assert ctx.statement.startswith("SELECT 1 ") is_(ctx.is_disconnect, False) is_(ctx.original_exception, nope) def test_exception_event_non_dbapi_error(self): """test that dbapi_error is called with a context in cases where DBAPI raises an exception that is not a DBAPI exception, e.g. internal errors or encoding problems. """ engine = engines.testing_engine() listener = Mock(return_value=None) event.listen(engine, 'handle_error', listener) nope = TypeError("I'm not a DBAPI error") with engine.connect() as c: c.connection.cursor = Mock( return_value=Mock( execute=Mock( side_effect=nope )) ) assert_raises_message( TypeError, "I'm not a DBAPI error", c.execute, "select " ) ctx = listener.mock_calls[0][1][0] eq_(ctx.statement, "select ") is_(ctx.is_disconnect, False) is_(ctx.original_exception, nope) def _test_alter_disconnect(self, orig_error, evt_value): engine = engines.testing_engine() @event.listens_for(engine, "handle_error") def evt(ctx): ctx.is_disconnect = evt_value with patch.object(engine.dialect, "is_disconnect", Mock(return_value=orig_error)): with engine.connect() as c: try: c.execute("SELECT x FROM nonexistent") assert False except tsa.exc.StatementError as st: eq_(st.connection_invalidated, evt_value) def test_alter_disconnect_to_true(self): self._test_alter_disconnect(False, True) self._test_alter_disconnect(True, True) def test_alter_disconnect_to_false(self): self._test_alter_disconnect(True, False) self._test_alter_disconnect(False, False) class ProxyConnectionTest(fixtures.TestBase): """These are the same tests as EngineEventsTest, except using the deprecated ConnectionProxy interface. """ __requires__ = 'ad_hoc_engines', __prefer_requires__ = 'two_phase_transactions', @testing.uses_deprecated(r'.*Use event.listen') @testing.fails_on('firebird', 'Data type unknown') def test_proxy(self): stmts = [] cursor_stmts = [] class MyProxy(ConnectionProxy): def execute( self, conn, execute, clauseelement, *multiparams, **params ): stmts.append((str(clauseelement), params, multiparams)) return execute(clauseelement, *multiparams, **params) def cursor_execute( self, execute, cursor, statement, parameters, context, executemany, ): cursor_stmts.append((str(statement), parameters, None)) return execute(cursor, statement, parameters, context) def assert_stmts(expected, received): for stmt, params, posn in expected: if not received: assert False, "Nothing available for stmt: %s" % stmt while received: teststmt, testparams, testmultiparams = \ received.pop(0) teststmt = re.compile(r'[\n\t ]+', re.M).sub(' ', teststmt).strip() if teststmt.startswith(stmt) and (testparams == params or testparams == posn): break for engine in \ engines.testing_engine(options=dict(implicit_returning=False, proxy=MyProxy())), \ engines.testing_engine(options=dict(implicit_returning=False, proxy=MyProxy(), strategy='threadlocal')): m = MetaData(engine) t1 = Table('t1', m, Column('c1', Integer, primary_key=True), Column('c2', String(50), default=func.lower('Foo'), primary_key=True) ) m.create_all() try: t1.insert().execute(c1=5, c2='some data') t1.insert().execute(c1=6) eq_(engine.execute('select * from t1').fetchall(), [(5, 'some data'), (6, 'foo')]) finally: m.drop_all() engine.dispose() compiled = [('CREATE TABLE t1', {}, None), ('INSERT INTO t1 (c1, c2)', {'c2': 'some data', 'c1': 5}, None), ('INSERT INTO t1 (c1, c2)', {'c1': 6}, None), ('select * from t1', {}, None), ('DROP TABLE t1', {}, None)] if not testing.against('oracle+zxjdbc'): # or engine.dialect.pr # eexecute_pk_sequence # s: cursor = [ ('CREATE TABLE t1', {}, ()), ('INSERT INTO t1 (c1, c2)', {'c2': 'some data', 'c1' : 5}, (5, 'some data')), ('SELECT lower', {'lower_2': 'Foo'}, ('Foo', )), ('INSERT INTO t1 (c1, c2)', {'c2': 'foo', 'c1': 6}, (6, 'foo')), ('select * from t1', {}, ()), ('DROP TABLE t1', {}, ()), ] else: insert2_params = 6, 'Foo' if testing.against('oracle+zxjdbc'): insert2_params += (ReturningParam(12), ) cursor = [('CREATE TABLE t1', {}, ()), ('INSERT INTO t1 (c1, c2)', {'c2': 'some data' , 'c1': 5}, (5, 'some data')), ('INSERT INTO t1 (c1, c2)', {'c1': 6, 'lower_2': 'Foo'}, insert2_params), ('select * from t1', {}, ()), ('DROP TABLE t1' , {}, ())] # bind param name 'lower_2' might # be incorrect assert_stmts(compiled, stmts) assert_stmts(cursor, cursor_stmts) @testing.uses_deprecated(r'.*Use event.listen') def test_options(self): canary = [] class TrackProxy(ConnectionProxy): def __getattribute__(self, key): fn = object.__getattribute__(self, key) def go(*arg, **kw): canary.append(fn.__name__) return fn(*arg, **kw) return go engine = engines.testing_engine(options={'proxy':TrackProxy()}) conn = engine.connect() c2 = conn.execution_options(foo='bar') eq_(c2._execution_options, {'foo':'bar'}) c2.execute(select([1])) c3 = c2.execution_options(bar='bat') eq_(c3._execution_options, {'foo':'bar', 'bar':'bat'}) eq_(canary, ['execute', 'cursor_execute']) @testing.uses_deprecated(r'.*Use event.listen') def test_transactional(self): canary = [] class TrackProxy(ConnectionProxy): def __getattribute__(self, key): fn = object.__getattribute__(self, key) def go(*arg, **kw): canary.append(fn.__name__) return fn(*arg, **kw) return go engine = engines.testing_engine(options={'proxy':TrackProxy()}) conn = engine.connect() trans = conn.begin() conn.execute(select([1])) trans.rollback() trans = conn.begin() conn.execute(select([1])) trans.commit() eq_(canary, [ 'begin', 'execute', 'cursor_execute', 'rollback', 'begin', 'execute', 'cursor_execute', 'commit', ]) @testing.uses_deprecated(r'.*Use event.listen') @testing.requires.savepoints @testing.requires.two_phase_transactions def test_transactional_advanced(self): canary = [] class TrackProxy(ConnectionProxy): def __getattribute__(self, key): fn = object.__getattribute__(self, key) def go(*arg, **kw): canary.append(fn.__name__) return fn(*arg, **kw) return go engine = engines.testing_engine(options={'proxy':TrackProxy()}) conn = engine.connect() trans = conn.begin() trans2 = conn.begin_nested() conn.execute(select([1])) trans2.rollback() trans2 = conn.begin_nested() conn.execute(select([1])) trans2.commit() trans.rollback() trans = conn.begin_twophase() conn.execute(select([1])) trans.prepare() trans.commit() canary = [t for t in canary if t not in ('cursor_execute', 'execute')] eq_(canary, ['begin', 'savepoint', 'rollback_savepoint', 'savepoint', 'release_savepoint', 'rollback', 'begin_twophase', 'prepare_twophase', 'commit_twophase'] ) class DialectEventTest(fixtures.TestBase): @contextmanager def _run_test(self, retval): m1 = Mock() m1.do_execute.return_value = retval m1.do_executemany.return_value = retval m1.do_execute_no_params.return_value = retval e = engines.testing_engine(options={"_initialize": False}) event.listen(e, "do_execute", m1.do_execute) event.listen(e, "do_executemany", m1.do_executemany) event.listen(e, "do_execute_no_params", m1.do_execute_no_params) e.dialect.do_execute = m1.real_do_execute e.dialect.do_executemany = m1.real_do_executemany e.dialect.do_execute_no_params = m1.real_do_execute_no_params def mock_the_cursor(cursor, *arg): arg[-1].get_result_proxy = Mock(return_value=Mock(context=arg[-1])) return retval m1.real_do_execute.side_effect = m1.do_execute.side_effect = mock_the_cursor m1.real_do_executemany.side_effect = m1.do_executemany.side_effect = mock_the_cursor m1.real_do_execute_no_params.side_effect = m1.do_execute_no_params.side_effect = mock_the_cursor with e.connect() as conn: yield conn, m1 def _assert(self, retval, m1, m2, mock_calls): eq_(m1.mock_calls, mock_calls) if retval: eq_(m2.mock_calls, []) else: eq_(m2.mock_calls, mock_calls) def _test_do_execute(self, retval): with self._run_test(retval) as (conn, m1): result = conn.execute("insert into table foo", {"foo": "bar"}) self._assert( retval, m1.do_execute, m1.real_do_execute, [call( result.context.cursor, "insert into table foo", {"foo": "bar"}, result.context)] ) def _test_do_executemany(self, retval): with self._run_test(retval) as (conn, m1): result = conn.execute("insert into table foo", [{"foo": "bar"}, {"foo": "bar"}]) self._assert( retval, m1.do_executemany, m1.real_do_executemany, [call( result.context.cursor, "insert into table foo", [{"foo": "bar"}, {"foo": "bar"}], result.context)] ) def _test_do_execute_no_params(self, retval): with self._run_test(retval) as (conn, m1): result = conn.execution_options(no_parameters=True).\ execute("insert into table foo") self._assert( retval, m1.do_execute_no_params, m1.real_do_execute_no_params, [call( result.context.cursor, "insert into table foo", result.context)] ) def _test_cursor_execute(self, retval): with self._run_test(retval) as (conn, m1): dialect = conn.dialect stmt = "insert into table foo" params = {"foo": "bar"} ctx = dialect.execution_ctx_cls._init_statement( dialect, conn, conn.connection, stmt, [params]) conn._cursor_execute(ctx.cursor, stmt, params, ctx) self._assert( retval, m1.do_execute, m1.real_do_execute, [call( ctx.cursor, "insert into table foo", {"foo": "bar"}, ctx)] ) def test_do_execute_w_replace(self): self._test_do_execute(True) def test_do_execute_wo_replace(self): self._test_do_execute(False) def test_do_executemany_w_replace(self): self._test_do_executemany(True) def test_do_executemany_wo_replace(self): self._test_do_executemany(False) def test_do_execute_no_params_w_replace(self): self._test_do_execute_no_params(True) def test_do_execute_no_params_wo_replace(self): self._test_do_execute_no_params(False) def test_cursor_execute_w_replace(self): self._test_cursor_execute(True) def test_cursor_execute_wo_replace(self): self._test_cursor_execute(False)
package endpoints.algebra.circe import io.circe.{Decoder => CirceDecoder, Encoder => CirceEncoder} /** * Combines both an [[io.circe.Encoder]] and a [[io.circe.Decoder]] into a single type class. * * You don’t need to define instances by yourself as they can be derived from an existing pair * of an [[io.circe.Encoder]] and a [[io.circe.Decoder]]. * * @see https://github.com/travisbrown/circe/issues/301 */ trait CirceCodec[A] { def encoder: CirceEncoder[A] def decoder: CirceDecoder[A] } object CirceCodec { @inline def apply[A](implicit codec: CirceCodec[A]): CirceCodec[A] = codec implicit def fromEncoderAndDecoder[A](implicit enc: CirceEncoder[A], dec: CirceDecoder[A]): CirceCodec[A] = new CirceCodec[A] { val decoder = dec val encoder = enc } }
b'What is -6 + -3 - (-4 + 0 + -1 + 7)?\n'
var fs = require('fs') var d3 = require('d3') var request = require('request') var cheerio = require('cheerio') var queue = require('queue-async') var _ = require('underscore') var glob = require("glob") var games = [] glob.sync(__dirname + "/raw-series/*").forEach(scrape) function scrape(dir, i){ var series = dir.split('/raw-series/')[1] process.stdout.write("parsing " + i + " " + series + "\r") var html = fs.readFileSync(dir, 'utf-8') var $ = cheerio.load(html) $('a').each(function(i){ var str = $(this).text() var href = $(this).attr('href') if (str == 'box scores' || !~href.indexOf('/boxscores/') || i % 2) return games.push({series: series, boxLink: $(this).attr('href').replace('/boxscores/', '')}) }) } fs.writeFileSync(__dirname + '/playoffGames.csv', d3.csv.format(games)) var q = queue(1) var downloaded = glob.sync(__dirname + '/raw-box/*.html').map(d => d.split('/raw-box/')[1]) games .map(d => d.boxLink) .filter(d => !_.contains(downloaded, d)) .forEach(d => q.defer(downloadBox, d)) function downloadBox(d, cb){ process.stdout.write("downloading " + d + "\r"); var url = 'http://www.basketball-reference.com/boxscores/' + d // console.log(url) setTimeout(cb, 1000) request(url, function(error, response, html){ var path = __dirname + '/raw-box/' + d fs.writeFileSync(path, html) }) }
b'What is -28 + 37 + -23 - (1 - 1)?\n'
b'Calculate 7 + -1 + (17 - (19 - 16)) - 2.\n'
b'What is the value of -9 - (-6 - -4 - -2) - (-51 + 14)?\n'
b'-41 - (-22 + 10 + -1)\n'
b'Calculate 44 - 47 - (-3 + (7 - (4 + 24))).\n'
b'(-4 - -8) + -12 - (-60 - -50)\n'
#region License // Distributed under the MIT License // ============================================================ // Copyright (c) 2019 Hotcakes Commerce, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, publish, distribute, // sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #endregion using System; using DotNetNuke.Entities.Host; using Hotcakes.Commerce.Configuration; namespace Hotcakes.Commerce.Dnn { [Serializable] public class DnnConfigurationManager : IConfigurationManager { public SmtpSettings SmtpSettings { get { var smtpSettings = new SmtpSettings(); var smtpHostParts = Host.SMTPServer.Split(':'); smtpSettings.Host = smtpHostParts[0]; if (smtpHostParts.Length > 1) { smtpSettings.Port = smtpHostParts[1]; } switch (Host.SMTPAuthentication) { case "": case "0": //anonymous smtpSettings.UseAuth = false; break; case "1": //basic smtpSettings.UseAuth = true; break; case "2": //NTLM smtpSettings.UseAuth = false; break; } smtpSettings.EnableSsl = Host.EnableSMTPSSL; smtpSettings.Username = Host.SMTPUsername; smtpSettings.Password = Host.SMTPPassword; return smtpSettings; } } } }
b'What is -18 + -11 + -1 - -2?\n'
b'What is 5 + -11 + 2 - -18?\n'
var groove = require('groove'); var semver = require('semver'); var EventEmitter = require('events').EventEmitter; var util = require('util'); var mkdirp = require('mkdirp'); var fs = require('fs'); var uuid = require('./uuid'); var path = require('path'); var Pend = require('pend'); var DedupedQueue = require('./deduped_queue'); var findit = require('findit2'); var shuffle = require('mess'); var mv = require('mv'); var MusicLibraryIndex = require('music-library-index'); var keese = require('keese'); var safePath = require('./safe_path'); var PassThrough = require('stream').PassThrough; var url = require('url'); var dbIterate = require('./db_iterate'); var log = require('./log'); var importUrlFilters = require('./import_url_filters'); var youtubeSearch = require('./youtube_search'); var yauzl = require('yauzl'); var importFileFilters = [ { name: 'zip', fn: importFileAsZip, }, { name: 'song', fn: importFileAsSong, }, ]; module.exports = Player; ensureGrooveVersionIsOk(); var cpuCount = 1; var PLAYER_KEY_PREFIX = "Player."; var LIBRARY_KEY_PREFIX = "Library."; var LIBRARY_DIR_PREFIX = "LibraryDir."; var QUEUE_KEY_PREFIX = "Playlist."; var PLAYLIST_KEY_PREFIX = "StoredPlaylist."; var LABEL_KEY_PREFIX = "Label."; var PLAYLIST_META_KEY_PREFIX = "StoredPlaylistMeta."; // db: store in the DB var DB_PROPS = { key: { db: true, clientVisible: true, clientCanModify: false, type: 'string', }, name: { db: true, clientVisible: true, clientCanModify: true, type: 'string', }, artistName: { db: true, clientVisible: true, clientCanModify: true, type: 'string', }, albumArtistName: { db: true, clientVisible: true, clientCanModify: true, type: 'string', }, albumName: { db: true, clientVisible: true, clientCanModify: true, type: 'string', }, compilation: { db: true, clientVisible: true, clientCanModify: true, type: 'boolean', }, track: { db: true, clientVisible: true, clientCanModify: true, type: 'integer', }, trackCount: { db: true, clientVisible: true, clientCanModify: true, type: 'integer', }, disc: { db: true, clientVisible: true, clientCanModify: true, type: 'integer', }, discCount: { db: true, clientVisible: true, clientCanModify: true, type: 'integer', }, duration: { db: true, clientVisible: true, clientCanModify: false, type: 'float', }, year: { db: true, clientVisible: true, clientCanModify: true, type: 'integer', }, genre: { db: true, clientVisible: true, clientCanModify: true, type: 'string', }, file: { db: true, clientVisible: true, clientCanModify: false, type: 'string', }, mtime: { db: true, clientVisible: false, clientCanModify: false, type: 'integer', }, replayGainAlbumGain: { db: true, clientVisible: false, clientCanModify: false, type: 'float', }, replayGainAlbumPeak: { db: true, clientVisible: false, clientCanModify: false, type: 'float', }, replayGainTrackGain: { db: true, clientVisible: false, clientCanModify: false, type: 'float', }, replayGainTrackPeak: { db: true, clientVisible: false, clientCanModify: false, type: 'float', }, composerName: { db: true, clientVisible: true, clientCanModify: true, type: 'string', }, performerName: { db: true, clientVisible: true, clientCanModify: true, type: 'string', }, lastQueueDate: { db: true, clientVisible: false, clientCanModify: false, type: 'date', }, fingerprint: { db: true, clientVisible: false, clientCanModify: false, type: 'array_of_integer', }, playCount: { db: true, clientVisible: false, clientCanModify: false, type: 'integer', }, labels: { db: true, clientVisible: true, clientCanModify: false, type: 'set', }, }; var PROP_TYPE_PARSERS = { 'string': function(value) { return value ? String(value) : ""; }, 'date': function(value) { if (!value) return null; var date = new Date(value); if (isNaN(date.getTime())) return null; return date; }, 'integer': parseIntOrNull, 'float': parseFloatOrNull, 'boolean': function(value) { return value == null ? null : !!value; }, 'array_of_integer': function(value) { if (!Array.isArray(value)) return null; value = value.map(parseIntOrNull); for (var i = 0; i < value.length; i++) { if (value[i] == null) return null; } return value; }, 'set': function(value) { var result = {}; for (var key in value) { result[key] = 1; } return result; }, }; var labelColors = [ "#e11d21", "#eb6420", "#fbca04", "#009800", "#006b75", "#207de5", "#0052cc", "#5319e7", "#f7c6c7", "#fad8c7", "#fef2c0", "#bfe5bf", "#bfdadc", "#bfd4f2", "#c7def8", "#d4c5f9", ]; // how many GrooveFiles to keep open, ready to be decoded var OPEN_FILE_COUNT = 8; var PREV_FILE_COUNT = Math.floor(OPEN_FILE_COUNT / 2); var NEXT_FILE_COUNT = OPEN_FILE_COUNT - PREV_FILE_COUNT; var DB_SCALE = Math.log(10.0) * 0.05; var REPLAYGAIN_PREAMP = 0.75; var REPLAYGAIN_DEFAULT = 0.25; Player.REPEAT_OFF = 0; Player.REPEAT_ALL = 1; Player.REPEAT_ONE = 2; Player.trackWithoutIndex = trackWithoutIndex; Player.setGrooveLoggingLevel = setGrooveLoggingLevel; util.inherits(Player, EventEmitter); function Player(db, config) { EventEmitter.call(this); this.setMaxListeners(0); this.db = db; this.musicDirectory = config.musicDirectory; this.dbFilesByPath = {}; this.dbFilesByLabel = {}; this.libraryIndex = new MusicLibraryIndex({ searchFields: MusicLibraryIndex.defaultSearchFields.concat('file'), }); this.addQueue = new DedupedQueue({ processOne: this.addToLibrary.bind(this), // limit to 1 async operation because we're blocking on the hard drive, // it's faster to read one file at a time. maxAsync: 1, }); this.dirs = {}; this.dirScanQueue = new DedupedQueue({ processOne: this.refreshFilesIndex.bind(this), // only 1 dir scanning can happen at a time // we'll pass the dir to scan as the ID so that not more than 1 of the // same dir can queue up maxAsync: 1, }); this.dirScanQueue.on('error', function(err) { log.error("library scanning error:", err.stack); }); this.disableFsRefCount = 0; this.playlist = {}; this.playlists = {}; this.currentTrack = null; this.tracksInOrder = []; // another way to look at playlist this.grooveItems = {}; // maps groove item id to track this.seekRequestPos = -1; // set to >= 0 when we want to seek this.invalidPaths = {}; // files that could not be opened this.playlistItemDeleteQueue = []; this.dontBelieveTheEndOfPlaylistSentinelItsATrap = false; this.queueClearEncodedBuffers = false; this.repeat = Player.REPEAT_OFF; this.desiredPlayerHardwareState = null; // true: normal hardware playback. false: dummy this.pendingPlayerAttachDetach = null; this.isPlaying = false; this.trackStartDate = null; this.pausedTime = 0; this.autoDjOn = false; this.autoDjHistorySize = 10; this.autoDjFutureSize = 10; this.ongoingScans = {}; this.scanQueue = new DedupedQueue({ processOne: this.performScan.bind(this), maxAsync: cpuCount, }); this.headerBuffers = []; this.recentBuffers = []; this.newHeaderBuffers = []; this.openStreamers = []; this.expectHeaders = true; // when a streaming client connects we send them many buffers quickly // in order to get the stream started, then we slow down. this.encodeQueueDuration = config.encodeQueueDuration; this.groovePlaylist = groove.createPlaylist(); this.groovePlayer = null; this.grooveEncoder = groove.createEncoder(); this.grooveEncoder.encodedBufferSize = 128 * 1024; this.detachEncoderTimeout = null; this.pendingEncoderAttachDetach = false; this.desiredEncoderAttachState = false; this.flushEncodedInterval = null; this.groovePlaylist.pause(); this.volume = this.groovePlaylist.gain; this.grooveEncoder.formatShortName = "mp3"; this.grooveEncoder.codecShortName = "mp3"; this.grooveEncoder.bitRate = config.encodeBitRate * 1000; this.importProgress = {}; this.lastImportProgressEvent = new Date(); // tracking playCount this.previousIsPlaying = false; this.playingStart = new Date(); this.playingTime = 0; this.lastPlayingItem = null; this.googleApiKey = config.googleApiKey; this.ignoreExtensions = config.ignoreExtensions.map(makeLower); } Player.prototype.initialize = function(cb) { var self = this; var startupTrackInfo = null; initLibrary(function(err) { if (err) return cb(err); cacheTracksArray(self); self.requestUpdateDb(); cacheAllOptions(function(err) { if (err) return cb(err); setInterval(doPersistCurrentTrack, 10000); if (startupTrackInfo) { self.seek(startupTrackInfo.id, startupTrackInfo.pos); } else { playlistChanged(self); } lazyReplayGainScanPlaylist(self); cb(); }); }); function initLibrary(cb) { var pend = new Pend(); pend.go(cacheAllDb); pend.go(cacheAllDirs); pend.go(cacheAllQueue); pend.go(cacheAllPlaylists); pend.go(cacheAllLabels); pend.wait(cb); } function cacheAllPlaylists(cb) { cacheAllPlaylistMeta(function(err) { if (err) return cb(err); cacheAllPlaylistItems(cb); }); function cacheAllPlaylistMeta(cb) { dbIterate(self.db, PLAYLIST_META_KEY_PREFIX, processOne, cb); function processOne(key, value) { var playlist = deserializePlaylist(value); self.playlists[playlist.id] = playlist; } } function cacheAllPlaylistItems(cb) { dbIterate(self.db, PLAYLIST_KEY_PREFIX, processOne, cb); function processOne(key, value) { var playlistIdEnd = key.indexOf('.', PLAYLIST_KEY_PREFIX.length); var playlistId = key.substring(PLAYLIST_KEY_PREFIX.length, playlistIdEnd); var playlistItem = JSON.parse(value); self.playlists[playlistId].items[playlistItem.id] = playlistItem; } } } function cacheAllLabels(cb) { dbIterate(self.db, LABEL_KEY_PREFIX, processOne, cb); function processOne(key, value) { var labelId = key.substring(LABEL_KEY_PREFIX.length); var labelEntry = JSON.parse(value); self.libraryIndex.addLabel(labelEntry); } } function cacheAllQueue(cb) { dbIterate(self.db, QUEUE_KEY_PREFIX, processOne, cb); function processOne(key, value) { var plEntry = JSON.parse(value); self.playlist[plEntry.id] = plEntry; } } function cacheAllOptions(cb) { var options = { repeat: null, autoDjOn: null, autoDjHistorySize: null, autoDjFutureSize: null, hardwarePlayback: null, volume: null, currentTrackInfo: null, }; var pend = new Pend(); for (var name in options) { pend.go(makeGetFn(name)); } pend.wait(function(err) { if (err) return cb(err); if (options.repeat != null) { self.setRepeat(options.repeat); } if (options.autoDjOn != null) { self.setAutoDjOn(options.autoDjOn); } if (options.autoDjHistorySize != null) { self.setAutoDjHistorySize(options.autoDjHistorySize); } if (options.autoDjFutureSize != null) { self.setAutoDjFutureSize(options.autoDjFutureSize); } if (options.volume != null) { self.setVolume(options.volume); } startupTrackInfo = options.currentTrackInfo; var hardwarePlaybackValue = options.hardwarePlayback == null ? true : options.hardwarePlayback; // start the hardware player first // fall back to dummy self.setHardwarePlayback(hardwarePlaybackValue, function(err) { if (err) { log.error("Unable to attach hardware player, falling back to dummy.", err.stack); self.setHardwarePlayback(false); } cb(); }); }); function makeGetFn(name) { return function(cb) { self.db.get(PLAYER_KEY_PREFIX + name, function(err, value) { if (!err && value != null) { try { options[name] = JSON.parse(value); } catch (err) { cb(err); return; } } cb(); }); }; } } function cacheAllDirs(cb) { dbIterate(self.db, LIBRARY_DIR_PREFIX, processOne, cb); function processOne(key, value) { var dirEntry = JSON.parse(value); self.dirs[dirEntry.dirName] = dirEntry; } } function cacheAllDb(cb) { var scrubCmds = []; dbIterate(self.db, LIBRARY_KEY_PREFIX, processOne, scrubAndCb); function processOne(key, value) { var dbFile = deserializeFileData(value); // scrub duplicates if (self.dbFilesByPath[dbFile.file]) { scrubCmds.push({type: 'del', key: key}); } else { self.libraryIndex.addTrack(dbFile); self.dbFilesByPath[dbFile.file] = dbFile; for (var labelId in dbFile.labels) { var files = self.dbFilesByLabel[labelId]; if (files == null) files = self.dbFilesByLabel[labelId] = {}; files[dbFile.key] = dbFile; } } } function scrubAndCb() { if (scrubCmds.length === 0) return cb(); log.warn("Scrubbing " + scrubCmds.length + " duplicate db entries"); self.db.batch(scrubCmds, function(err) { if (err) log.error("Unable to scrub duplicate tracks from db:", err.stack); cb(); }); } } function doPersistCurrentTrack() { if (self.isPlaying) { self.persistCurrentTrack(); } } }; function startEncoderAttach(self, cb) { if (self.desiredEncoderAttachState) return; self.desiredEncoderAttachState = true; if (self.pendingEncoderAttachDetach) return; self.pendingEncoderAttachDetach = true; self.grooveEncoder.attach(self.groovePlaylist, function(err) { self.pendingEncoderAttachDetach = false; if (err) { self.desiredEncoderAttachState = false; cb(err); } else if (!self.desiredEncoderAttachState) { startEncoderDetach(self, cb); } }); } function startEncoderDetach(self, cb) { if (!self.desiredEncoderAttachState) return; self.desiredEncoderAttachState = false; if (self.pendingEncoderAttachDetach) return; self.pendingEncoderAttachDetach = true; self.grooveEncoder.detach(function(err) { self.pendingEncoderAttachDetach = false; if (err) { self.desiredEncoderAttachState = true; cb(err); } else if (self.desiredEncoderAttachState) { startEncoderAttach(self, cb); } }); } Player.prototype.getBufferedSeconds = function() { if (this.recentBuffers.length < 2) return 0; var firstPts = this.recentBuffers[0].pts; var lastPts = this.recentBuffers[this.recentBuffers.length - 1].pts; var frameCount = lastPts - firstPts; var sampleRate = this.grooveEncoder.actualAudioFormat.sampleRate; return frameCount / sampleRate; }; Player.prototype.attachEncoder = function(cb) { var self = this; cb = cb || logIfError; if (self.flushEncodedInterval) return cb(); log.debug("first streamer connected - attaching encoder"); self.flushEncodedInterval = setInterval(flushEncoded, 100); startEncoderAttach(self, cb); function flushEncoded() { if (!self.desiredEncoderAttachState || self.pendingEncoderAttachDetach) return; var playHead = self.groovePlayer.position(); if (!playHead.item) return; var plItems = self.groovePlaylist.items(); // get rid of old items var buf; while (buf = self.recentBuffers[0]) { /* log.debug(" buf.item " + buf.item.file.filename + "\n" + "playHead.item " + playHead.item.file.filename + "\n" + " playHead.pos " + playHead.pos + "\n" + " buf.pos " + buf.pos); */ if (isBufOld(buf)) { self.recentBuffers.shift(); } else { break; } } // poll the encoder for more buffers until either there are no buffers // available or we get enough buffered while (self.getBufferedSeconds() < self.encodeQueueDuration) { buf = self.grooveEncoder.getBuffer(); if (!buf) break; if (buf.buffer) { if (buf.item) { if (self.expectHeaders) { log.debug("encoder: got first non-header"); self.headerBuffers = self.newHeaderBuffers; self.newHeaderBuffers = []; self.expectHeaders = false; } self.recentBuffers.push(buf); for (var i = 0; i < self.openStreamers.length; i += 1) { self.openStreamers[i].write(buf.buffer); } } else if (self.expectHeaders) { // this is a header log.debug("encoder: got header"); self.newHeaderBuffers.push(buf.buffer); } else { // it's a footer, ignore the fuck out of it log.debug("ignoring encoded audio footer"); } } else { // end of playlist sentinel log.debug("encoder: end of playlist sentinel"); if (self.queueClearEncodedBuffers) { self.queueClearEncodedBuffers = false; self.clearEncodedBuffer(); self.emit('seek'); } self.expectHeaders = true; } } function isBufOld(buf) { // typical case if (buf.item.id === playHead.item.id) { return playHead.pos > buf.pos; } // edge case var playHeadIndex = -1; var bufItemIndex = -1; for (var i = 0; i < plItems.length; i += 1) { var plItem = plItems[i]; if (plItem.id === playHead.item.id) { playHeadIndex = i; } else if (plItem.id === buf.item.id) { bufItemIndex = i; } } return playHeadIndex > bufItemIndex; } } function logIfError(err) { if (err) { log.error("Unable to attach encoder:", err.stack); } } }; Player.prototype.detachEncoder = function(cb) { cb = cb || logIfError; this.clearEncodedBuffer(); this.queueClearEncodedBuffers = false; clearInterval(this.flushEncodedInterval); this.flushEncodedInterval = null; startEncoderDetach(this, cb); this.grooveEncoder.removeAllListeners(); function logIfError(err) { if (err) { log.error("Unable to detach encoder:", err.stack); } } }; Player.prototype.deleteDbMtimes = function(cb) { cb = cb || logIfDbError; var updateCmds = []; for (var key in this.libraryIndex.trackTable) { var dbFile = this.libraryIndex.trackTable[key]; delete dbFile.mtime; persistDbFile(dbFile, updateCmds); } this.db.batch(updateCmds, cb); }; Player.prototype.requestUpdateDb = function(dirName, cb) { var fullPath = path.resolve(this.musicDirectory, dirName || ""); this.dirScanQueue.add(fullPath, { dir: fullPath, }, cb); }; Player.prototype.refreshFilesIndex = function(args, cb) { var self = this; var dir = args.dir; var dirWithSlash = ensureSep(dir); var walker = findit(dirWithSlash, {followSymlinks: true}); var thisScanId = uuid(); var delCmds = []; walker.on('directory', function(fullDirPath, stat, stop, linkPath) { var usePath = linkPath || fullDirPath; var dirName = path.relative(self.musicDirectory, usePath); var baseName = path.basename(dirName); if (isFileIgnored(baseName)) { stop(); return; } var dirEntry = self.getOrCreateDir(dirName, stat); if (usePath === dirWithSlash) return; // ignore root search path var parentDirName = path.dirname(dirName); if (parentDirName === '.') parentDirName = ''; var parentDirEntry = self.getOrCreateDir(parentDirName); parentDirEntry.dirEntries[baseName] = thisScanId; }); walker.on('file', function(fullPath, stat, linkPath) { var usePath = linkPath || fullPath; var relPath = path.relative(self.musicDirectory, usePath); var dirName = path.dirname(relPath); if (dirName === '.') dirName = ''; var baseName = path.basename(relPath); if (isFileIgnored(baseName)) return; var extName = path.extname(relPath); if (isExtensionIgnored(self, extName)) return; var dirEntry = self.getOrCreateDir(dirName); dirEntry.entries[baseName] = thisScanId; var fileMtime = stat.mtime.getTime(); onAddOrChange(self, relPath, fileMtime); }); walker.on('error', function(err) { walker.stop(); cleanupAndCb(err); }); walker.on('end', function() { var dirName = path.relative(self.musicDirectory, dir); checkDirEntry(self.dirs[dirName]); cleanupAndCb(); function checkDirEntry(dirEntry) { if (!dirEntry) return; var id; var baseName; var i; var deletedFiles = []; var deletedDirs = []; for (baseName in dirEntry.entries) { id = dirEntry.entries[baseName]; if (id !== thisScanId) deletedFiles.push(baseName); } for (i = 0; i < deletedFiles.length; i += 1) { baseName = deletedFiles[i]; delete dirEntry.entries[baseName]; onFileMissing(dirEntry, baseName); } for (baseName in dirEntry.dirEntries) { id = dirEntry.dirEntries[baseName]; var childEntry = self.dirs[path.join(dirEntry.dirName, baseName)]; checkDirEntry(childEntry); if (id !== thisScanId) deletedDirs.push(baseName); } for (i = 0; i < deletedDirs.length; i += 1) { baseName = deletedDirs[i]; delete dirEntry.dirEntries[baseName]; onDirMissing(dirEntry, baseName); } self.persistDirEntry(dirEntry); } }); function cleanupAndCb(err) { if (delCmds.length > 0) { self.db.batch(delCmds, logIfDbError); self.emit('deleteDbTrack'); } cb(err); } function onDirMissing(parentDirEntry, baseName) { var dirName = path.join(parentDirEntry.dirName, baseName); log.debug("directory deleted:", dirName); var dirEntry = self.dirs[dirName]; var watcher = dirEntry.watcher; if (watcher) watcher.close(); delete self.dirs[dirName]; delete parentDirEntry.dirEntries[baseName]; } function onFileMissing(parentDirEntry, baseName) { var relPath = path.join(parentDirEntry.dirName, baseName); log.debug("file deleted:", relPath); delete parentDirEntry.entries[baseName]; var dbFile = self.dbFilesByPath[relPath]; if (dbFile) { // batch up some db delete commands to run after walking the file system delDbEntryCmds(self, dbFile, delCmds); } } }; Player.prototype.watchDirEntry = function(dirEntry) { var self = this; var changeTriggered = null; var fullDirPath = path.join(self.musicDirectory, dirEntry.dirName); var watcher; try { watcher = fs.watch(fullDirPath, onChange); watcher.on('error', onWatchError); } catch (err) { log.warn("Unable to fs.watch:", err.stack); watcher = null; } dirEntry.watcher = watcher; function onChange(eventName) { if (changeTriggered) clearTimeout(changeTriggered); changeTriggered = setTimeout(function() { changeTriggered = null; log.debug("dir updated:", dirEntry.dirName); self.dirScanQueue.add(fullDirPath, { dir: fullDirPath }); }, 100); } function onWatchError(err) { log.error("watch error:", err.stack); } }; Player.prototype.getOrCreateDir = function (dirName, stat) { var dirEntry = this.dirs[dirName]; if (!dirEntry) { dirEntry = this.dirs[dirName] = { dirName: dirName, entries: {}, dirEntries: {}, watcher: null, // will be set just below mtime: stat && stat.mtime, }; } else if (stat && dirEntry.mtime !== stat.mtime) { dirEntry.mtime = stat.mtime; } if (!dirEntry.watcher) this.watchDirEntry(dirEntry); return dirEntry; }; Player.prototype.getCurPos = function() { return this.isPlaying ? ((new Date() - this.trackStartDate) / 1000.0) : this.pausedTime; }; function startPlayerSwitchDevice(self, wantHardware, cb) { self.desiredPlayerHardwareState = wantHardware; if (self.pendingPlayerAttachDetach) return; self.pendingPlayerAttachDetach = true; if (self.groovePlayer) { self.groovePlayer.removeAllListeners(); self.groovePlayer.detach(onDetachComplete); } else { onDetachComplete(); } function onDetachComplete(err) { if (err) return cb(err); self.groovePlayer = groove.createPlayer(); self.groovePlayer.deviceIndex = wantHardware ? null : groove.DUMMY_DEVICE; self.groovePlayer.attach(self.groovePlaylist, function(err) { self.pendingPlayerAttachDetach = false; if (err) return cb(err); if (self.desiredPlayerHardwareState !== wantHardware) { startPlayerSwitchDevice(self, self.desiredPlayerHardwareState, cb); } else { cb(); } }); } } Player.prototype.setHardwarePlayback = function(value, cb) { var self = this; cb = cb || logIfError; value = !!value; if (value === self.desiredPlayerHardwareState) return cb(); startPlayerSwitchDevice(self, value, function(err) { if (err) return cb(err); self.clearEncodedBuffer(); self.emit('seek'); self.groovePlayer.on('nowplaying', onNowPlaying); self.persistOption('hardwarePlayback', self.desiredPlayerHardwareState); self.emit('hardwarePlayback', self.desiredPlayerHardwareState); cb(); }); function onNowPlaying() { var playHead = self.groovePlayer.position(); var decodeHead = self.groovePlaylist.position(); if (playHead.item) { var nowMs = (new Date()).getTime(); var posMs = playHead.pos * 1000; self.trackStartDate = new Date(nowMs - posMs); self.currentTrack = self.grooveItems[playHead.item.id]; playlistChanged(self); self.currentTrackChanged(); } else if (!decodeHead.item) { if (!self.dontBelieveTheEndOfPlaylistSentinelItsATrap) { // both play head and decode head are null. end of playlist. log.debug("end of playlist"); self.currentTrack = null; playlistChanged(self); self.currentTrackChanged(); } } } function logIfError(err) { if (err) { log.error("Unable to set hardware playback mode:", err.stack); } } }; Player.prototype.startStreaming = function(resp) { this.headerBuffers.forEach(function(headerBuffer) { resp.write(headerBuffer); }); this.recentBuffers.forEach(function(recentBuffer) { resp.write(recentBuffer.buffer); }); this.cancelDetachEncoderTimeout(); this.attachEncoder(); this.openStreamers.push(resp); this.emit('streamerConnect', resp.client); }; Player.prototype.stopStreaming = function(resp) { for (var i = 0; i < this.openStreamers.length; i += 1) { if (this.openStreamers[i] === resp) { this.openStreamers.splice(i, 1); this.emit('streamerDisconnect', resp.client); break; } } }; Player.prototype.lastStreamerDisconnected = function() { log.debug("last streamer disconnected"); this.startDetachEncoderTimeout(); if (!this.desiredPlayerHardwareState && this.isPlaying) { this.emit("autoPause"); this.pause(); } }; Player.prototype.cancelDetachEncoderTimeout = function() { if (this.detachEncoderTimeout) { clearTimeout(this.detachEncoderTimeout); this.detachEncoderTimeout = null; } }; Player.prototype.startDetachEncoderTimeout = function() { var self = this; self.cancelDetachEncoderTimeout(); // we use encodeQueueDuration for the encoder timeout so that we are // guaranteed to have audio available for the encoder in the case of // detaching and reattaching the encoder. self.detachEncoderTimeout = setTimeout(timeout, self.encodeQueueDuration * 1000); function timeout() { if (self.openStreamers.length === 0 && self.isPlaying) { log.debug("detaching encoder"); self.detachEncoder(); } } }; Player.prototype.deleteFiles = function(keys) { var self = this; var delCmds = []; for (var i = 0; i < keys.length; i += 1) { var key = keys[i]; var dbFile = self.libraryIndex.trackTable[key]; if (!dbFile) continue; var fullPath = path.join(self.musicDirectory, dbFile.file); delDbEntryCmds(self, dbFile, delCmds); fs.unlink(fullPath, logIfError); } if (delCmds.length > 0) { self.emit('deleteDbTrack'); self.db.batch(delCmds, logIfError); } function logIfError(err) { if (err) { log.error("Error deleting files:", err.stack); } } }; function delDbEntryCmds(self, dbFile, dbCmds) { // delete items from the queue that are being deleted from the library var deleteQueueItems = []; for (var queueId in self.playlist) { var queueItem = self.playlist[queueId]; if (queueItem.key === dbFile.key) { deleteQueueItems.push(queueId); } } self.removeQueueItems(deleteQueueItems); // delete items from playlists that are being deleted from the library var playlistRemovals = {}; for (var playlistId in self.playlists) { var playlist = self.playlists[playlistId]; var removals = []; playlistRemovals[playlistId] = removals; for (var playlistItemId in playlist.items) { var playlistItem = playlist.items[playlistItemId]; if (playlistItem.key === dbFile.key) { removals.push(playlistItemId); } } } self.playlistRemoveItems(playlistRemovals); self.libraryIndex.removeTrack(dbFile.key); delete self.dbFilesByPath[dbFile.file]; var baseName = path.basename(dbFile.file); var parentDirName = path.dirname(dbFile.file); if (parentDirName === '.') parentDirName = ''; var parentDirEntry = self.dirs[parentDirName]; if (parentDirEntry) delete parentDirEntry[baseName]; dbCmds.push({type: 'del', key: LIBRARY_KEY_PREFIX + dbFile.key}); } Player.prototype.setVolume = function(value) { value = Math.min(2.0, value); value = Math.max(0.0, value); this.volume = value; this.groovePlaylist.setGain(value); this.persistOption('volume', this.volume); this.emit("volumeUpdate"); }; Player.prototype.importUrl = function(urlString, cb) { var self = this; cb = cb || logIfError; var filterIndex = 0; tryImportFilter(); function tryImportFilter() { var importFilter = importUrlFilters[filterIndex]; if (!importFilter) return cb(); importFilter.fn(urlString, callNextFilter); function callNextFilter(err, dlStream, filenameHintWithoutPath, size) { if (err || !dlStream) { if (err) { log.error(importFilter.name + " import filter error, skipping:", err.stack); } filterIndex += 1; tryImportFilter(); return; } self.importStream(dlStream, filenameHintWithoutPath, size, cb); } } function logIfError(err) { if (err) { log.error("Unable to import by URL.", err.stack, "URL:", urlString); } } }; Player.prototype.importNames = function(names, cb) { var self = this; var pend = new Pend(); var allDbFiles = []; names.forEach(function(name) { pend.go(function(cb) { youtubeSearch(name, self.googleApiKey, function(err, videoUrl) { if (err) { log.error("YouTube search error, skipping " + name + ": " + err.stack); cb(); return; } self.importUrl(videoUrl, function(err, dbFiles) { if (err) { log.error("Unable to import from YouTube: " + err.stack); } else if (!dbFiles) { log.error("Unrecognized YouTube URL: " + videoUrl); } else if (dbFiles.length > 0) { allDbFiles = allDbFiles.concat(dbFiles); } cb(); }); }); }); }); pend.wait(function() { cb(null, allDbFiles); }); }; Player.prototype.importStream = function(readStream, filenameHintWithoutPath, size, cb) { var self = this; var ext = path.extname(filenameHintWithoutPath); var tmpDir = path.join(self.musicDirectory, '.tmp'); var id = uuid(); var destPath = path.join(tmpDir, id + ext); var calledCallback = false; var writeStream = null; var progressTimer = null; var importEvent = { id: id, filenameHintWithoutPath: filenameHintWithoutPath, bytesWritten: 0, size: size, date: new Date(), }; readStream.on('error', cleanAndCb); self.importProgress[importEvent.id] = importEvent; self.emit('importStart', importEvent); mkdirp(tmpDir, function(err) { if (calledCallback) return; if (err) return cleanAndCb(err); writeStream = fs.createWriteStream(destPath); readStream.pipe(writeStream); progressTimer = setInterval(checkProgress, 100); writeStream.on('close', onClose); writeStream.on('error', cleanAndCb); function checkProgress() { importEvent.bytesWritten = writeStream.bytesWritten; self.maybeEmitImportProgress(); } function onClose(){ if (calledCallback) return; checkProgress(); self.importFile(destPath, filenameHintWithoutPath, function(err, dbFiles) { if (calledCallback) return; if (err) { cleanAndCb(err); } else { calledCallback = true; cleanTimer(); delete self.importProgress[importEvent.id]; self.emit('importEnd', importEvent); cb(null, dbFiles); } }); } }); function cleanTimer() { if (progressTimer) { clearInterval(progressTimer); progressTimer = null; } } function cleanAndCb(err) { if (writeStream) { fs.unlink(destPath, onUnlinkDone); writeStream = null; } cleanTimer(); if (calledCallback) return; calledCallback = true; delete self.importProgress[importEvent.id]; self.emit('importAbort', importEvent); cb(err); function onUnlinkDone(err) { if (err) { log.warn("Unable to clean up temp file:", err.stack); } } } }; Player.prototype.importFile = function(srcFullPath, filenameHintWithoutPath, cb) { var self = this; cb = cb || logIfError; var filterIndex = 0; log.debug("importFile open file:", srcFullPath); disableFsListenRef(self, tryImportFilter); function tryImportFilter() { var importFilter = importFileFilters[filterIndex]; if (!importFilter) return cleanAndCb(); importFilter.fn(self, srcFullPath, filenameHintWithoutPath, callNextFilter); function callNextFilter(err, dbFiles) { if (err || !dbFiles) { if (err) { log.debug(importFilter.name + " import filter error, skipping:", err.message); } filterIndex += 1; tryImportFilter(); return; } cleanAndCb(null, dbFiles); } } function cleanAndCb(err, dbFiles) { if (!dbFiles) { fs.unlink(srcFullPath, logIfUnlinkError); } disableFsListenUnref(self); cb(err, dbFiles); } function logIfUnlinkError(err) { if (err) { log.error("unable to unlink file:", err.stack); } } function logIfError(err) { if (err) { log.error("unable to import file:", err.stack); } } }; Player.prototype.maybeEmitImportProgress = function() { var now = new Date(); var passedTime = now - this.lastImportProgressEvent; if (passedTime > 500) { this.lastImportProgressEvent = now; this.emit("importProgress"); } }; Player.prototype.persistDirEntry = function(dirEntry, cb) { cb = cb || logIfError; this.db.put(LIBRARY_DIR_PREFIX + dirEntry.dirName, serializeDirEntry(dirEntry), cb); function logIfError(err) { if (err) { log.error("unable to persist db entry:", dirEntry, err.stack); } } }; Player.prototype.persistDbFile = function(dbFile, updateCmds) { this.libraryIndex.addTrack(dbFile); this.dbFilesByPath[dbFile.file] = dbFile; persistDbFile(dbFile, updateCmds); }; Player.prototype.persistOneDbFile = function(dbFile, cb) { cb = cb || logIfDbError; var updateCmds = []; this.persistDbFile(dbFile, updateCmds); this.db.batch(updateCmds, cb); }; Player.prototype.persistOption = function(name, value, cb) { this.db.put(PLAYER_KEY_PREFIX + name, JSON.stringify(value), cb || logIfError); function logIfError(err) { if (err) { log.error("unable to persist player option:", err.stack); } } }; Player.prototype.addToLibrary = function(args, cb) { var self = this; var relPath = args.relPath; var mtime = args.mtime; var fullPath = path.join(self.musicDirectory, relPath); log.debug("addToLibrary open file:", fullPath); groove.open(fullPath, function(err, file) { if (err) { self.invalidPaths[relPath] = err.message; cb(); return; } var dbFile = self.dbFilesByPath[relPath]; var filenameHintWithoutPath = path.basename(relPath); var newDbFile = grooveFileToDbFile(file, filenameHintWithoutPath, dbFile); newDbFile.file = relPath; newDbFile.mtime = mtime; var pend = new Pend(); pend.go(function(cb) { log.debug("addToLibrary close file:", file.filename); file.close(cb); }); pend.go(function(cb) { self.persistOneDbFile(newDbFile, function(err) { if (err) log.error("Error saving", relPath, "to db:", err.stack); cb(); }); }); self.emit('updateDb'); pend.wait(cb); }); }; Player.prototype.updateTags = function(obj) { var updateCmds = []; for (var key in obj) { var dbFile = this.libraryIndex.trackTable[key]; if (!dbFile) continue; var props = obj[key]; for (var propName in DB_PROPS) { var prop = DB_PROPS[propName]; if (! prop.clientCanModify) continue; if (! (propName in props)) continue; var parser = PROP_TYPE_PARSERS[prop.type]; dbFile[propName] = parser(props[propName]); } this.persistDbFile(dbFile, updateCmds); } if (updateCmds.length > 0) { this.db.batch(updateCmds, logIfDbError); this.emit('updateDb'); } }; Player.prototype.insertTracks = function(index, keys, tagAsRandom) { if (keys.length === 0) return []; if (index < 0) index = 0; if (index > this.tracksInOrder.length) index = this.tracksInOrder.length; var trackBeforeIndex = this.tracksInOrder[index - 1]; var trackAtIndex = this.tracksInOrder[index]; var prevSortKey = trackBeforeIndex ? trackBeforeIndex.sortKey : null; var nextSortKey = trackAtIndex ? trackAtIndex.sortKey : null; var items = {}; var ids = []; var sortKeys = keese(prevSortKey, nextSortKey, keys.length); keys.forEach(function(key, i) { var id = uuid(); var sortKey = sortKeys[i]; items[id] = { key: key, sortKey: sortKey, }; ids.push(id); }); this.addItems(items, tagAsRandom); return ids; }; Player.prototype.appendTracks = function(keys, tagAsRandom) { return this.insertTracks(this.tracksInOrder.length, keys, tagAsRandom); }; // items looks like {id: {key, sortKey}} Player.prototype.addItems = function(items, tagAsRandom) { var self = this; tagAsRandom = !!tagAsRandom; var updateCmds = []; for (var id in items) { var item = items[id]; var dbFile = self.libraryIndex.trackTable[item.key]; if (!dbFile) continue; dbFile.lastQueueDate = new Date(); self.persistDbFile(dbFile, updateCmds); var queueItem = { id: id, key: item.key, sortKey: item.sortKey, isRandom: tagAsRandom, grooveFile: null, pendingGrooveFile: false, deleted: false, }; self.playlist[id] = queueItem; persistQueueItem(queueItem, updateCmds); } if (updateCmds.length > 0) { self.db.batch(updateCmds, logIfDbError); playlistChanged(self); lazyReplayGainScanPlaylist(self); } }; Player.prototype.playlistCreate = function(id, name) { if (this.playlists[id]) { log.warn("tried to create playlist with same id as existing"); return; } var playlist = { id: id, name: name, mtime: new Date().getTime(), items: {}, }; this.playlists[playlist.id] = playlist; this.persistPlaylist(playlist); this.emit('playlistCreate', playlist); return playlist; }; Player.prototype.playlistRename = function(playlistId, newName) { var playlist = this.playlists[playlistId]; if (!playlist) return; playlist.name = newName; playlist.mtime = new Date().getTime(); this.persistPlaylist(playlist); this.emit('playlistUpdate', playlist); }; Player.prototype.playlistDelete = function(playlistIds) { var delCmds = []; for (var i = 0; i < playlistIds.length; i += 1) { var playlistId = playlistIds[i]; var playlist = this.playlists[playlistId]; if (!playlist) continue; for (var id in playlist.items) { var item = playlist.items[id]; if (!item) continue; delCmds.push({type: 'del', key: playlistItemKey(playlist, item)}); delete playlist.items[id]; } delCmds.push({type: 'del', key: playlistKey(playlist)}); delete this.playlists[playlistId]; } if (delCmds.length > 0) { this.db.batch(delCmds, logIfDbError); this.emit('playlistDelete'); } }; Player.prototype.playlistAddItems = function(playlistId, items) { var playlist = this.playlists[playlistId]; if (!playlist) return; var updateCmds = []; for (var id in items) { var item = items[id]; var dbFile = this.libraryIndex.trackTable[item.key]; if (!dbFile) continue; var playlistItem = { id: id, key: item.key, sortKey: item.sortKey, }; playlist.items[id] = playlistItem; updateCmds.push({ type: 'put', key: playlistItemKey(playlist, playlistItem), value: serializePlaylistItem(playlistItem), }); } if (updateCmds.length > 0) { playlist.mtime = new Date().getTime(); updateCmds.push({ type: 'put', key: playlistKey(playlist), value: serializePlaylist(playlist), }); this.db.batch(updateCmds, logIfDbError); this.emit('playlistUpdate', playlist); } }; Player.prototype.playlistRemoveItems = function(removals) { var updateCmds = []; for (var playlistId in removals) { var playlist = this.playlists[playlistId]; if (!playlist) continue; var ids = removals[playlistId]; var dirty = false; for (var i = 0; i < ids.length; i += 1) { var id = ids[i]; var item = playlist.items[id]; if (!item) continue; dirty = true; updateCmds.push({type: 'del', key: playlistItemKey(playlist, item)}); delete playlist.items[id]; } if (dirty) { playlist.mtime = new Date().getTime(); updateCmds.push({ type: 'put', key: playlistKey(playlist), value: serializePlaylist(playlist), }); } } if (updateCmds.length > 0) { this.db.batch(updateCmds, logIfDbError); this.emit('playlistUpdate'); } }; // items looks like {playlistId: {id: {sortKey}}} Player.prototype.playlistMoveItems = function(updates) { var updateCmds = []; for (var playlistId in updates) { var playlist = this.playlists[playlistId]; if (!playlist) continue; var playlistDirty = false; var update = updates[playlistId]; for (var id in update) { var playlistItem = playlist.items[id]; if (!playlistItem) continue; var updateItem = update[id]; playlistItem.sortKey = updateItem.sortKey; playlistDirty = true; updateCmds.push({ type: 'put', key: playlistItemKey(playlist, playlistItem), value: serializePlaylistItem(playlistItem), }); } if (playlistDirty) { playlist.mtime = new Date().getTime(); updateCmds.push({ type: 'put', key: playlistKey(playlist), value: serializePlaylist(playlist), }); } } if (updateCmds.length > 0) { this.db.batch(updateCmds, logIfDbError); this.emit('playlistUpdate'); } }; Player.prototype.persistPlaylist = function(playlist, cb) { cb = cb || logIfDbError; var key = playlistKey(playlist); var payload = serializePlaylist(playlist); this.db.put(key, payload, cb); }; Player.prototype.labelCreate = function(id, name) { if (id in this.libraryIndex.labelTable) { log.warn("tried to create label that already exists"); return; } var color = labelColors[Math.floor(Math.random() * labelColors.length)]; var labelEntry = {id: id, name: name, color: color}; this.libraryIndex.addLabel(labelEntry); var key = LABEL_KEY_PREFIX + id; this.db.put(key, JSON.stringify(labelEntry), logIfDbError); this.emit('labelCreate'); }; Player.prototype.labelRename = function(id, name) { var labelEntry = this.libraryIndex.labelTable[id]; if (!labelEntry) return; labelEntry.name = name; this.libraryIndex.addLabel(labelEntry); var key = LABEL_KEY_PREFIX + id; this.db.put(key, JSON.stringify(labelEntry), logIfDbError); this.emit('labelRename'); }; Player.prototype.labelColorUpdate = function(id, color) { var labelEntry = this.libraryIndex.labelTable[id]; if (!labelEntry) return; labelEntry.color = color; this.libraryIndex.addLabel(labelEntry); var key = LABEL_KEY_PREFIX + id; this.db.put(key, JSON.stringify(labelEntry), logIfDbError); this.emit('labelColorUpdate'); }; Player.prototype.labelDelete = function(ids) { var updateCmds = []; var libraryChanged = false; for (var i = 0; i < ids.length; i++) { var labelId = ids[i]; if (!(labelId in this.libraryIndex.labelTable)) continue; this.libraryIndex.removeLabel(labelId); var key = LABEL_KEY_PREFIX + labelId; updateCmds.push({type: 'del', key: key}); // clean out references from the library var files = this.dbFilesByLabel[labelId]; for (var fileId in files) { var dbFile = files[fileId]; delete dbFile.labels[labelId]; persistDbFile(dbFile, updateCmds); libraryChanged = true; } delete this.dbFilesByLabel[labelId]; } if (updateCmds.length === 0) return; this.db.batch(updateCmds, logIfDbError); if (libraryChanged) { this.emit('updateDb'); } this.emit('labelDelete'); }; Player.prototype.labelAdd = function(additions) { this.changeLabels(additions, true); }; Player.prototype.labelRemove = function(removals) { this.changeLabels(removals, false); }; Player.prototype.changeLabels = function(changes, isAdd) { var self = this; var updateCmds = []; for (var id in changes) { var labelIds = changes[id]; var dbFile = this.libraryIndex.trackTable[id]; if (!dbFile) continue; if (labelIds.length === 0) continue; var changedTrack = false; for (var i = 0; i < labelIds.length; i++) { var labelId = labelIds[i]; var filesByThisLabel = self.dbFilesByLabel[labelId]; if (isAdd) { if (labelId in dbFile.labels) continue; // already got it dbFile.labels[labelId] = 1; if (filesByThisLabel == null) filesByThisLabel = self.dbFilesByLabel[labelId] = {}; filesByThisLabel[dbFile.key] = dbFile; } else { if (!(labelId in dbFile.labels)) continue; // already gone delete dbFile.labels[labelId]; delete filesByThisLabel[dbFile.key]; } changedTrack = true; } if (changedTrack) { this.persistDbFile(dbFile, updateCmds); } } if (updateCmds.length === 0) return; this.db.batch(updateCmds, logIfDbError); this.emit('updateDb'); }; Player.prototype.clearQueue = function() { this.removeQueueItems(Object.keys(this.playlist)); }; Player.prototype.removeAllRandomQueueItems = function() { var idsToRemove = []; for (var i = 0; i < this.tracksInOrder.length; i += 1) { var track = this.tracksInOrder[i]; if (track.isRandom && track !== this.currentTrack) { idsToRemove.push(track.id); } } return this.removeQueueItems(idsToRemove); }; Player.prototype.shufflePlaylist = function() { if (this.tracksInOrder.length === 0) return; if (this.autoDjOn) return this.removeAllRandomQueueItems(); var sortKeys = this.tracksInOrder.map(function(track) { return track.sortKey; }); shuffle(sortKeys); // fix sortKey and index properties var updateCmds = []; for (var i = 0; i < this.tracksInOrder.length; i += 1) { var track = this.tracksInOrder[i]; track.index = i; track.sortKey = sortKeys[i]; persistQueueItem(track, updateCmds); } this.db.batch(updateCmds, logIfDbError); playlistChanged(this); }; Player.prototype.removeQueueItems = function(ids) { if (ids.length === 0) return; var delCmds = []; var currentTrackChanged = false; for (var i = 0; i < ids.length; i += 1) { var id = ids[i]; var item = this.playlist[id]; if (!item) continue; delCmds.push({type: 'del', key: QUEUE_KEY_PREFIX + id}); if (item.grooveFile) this.playlistItemDeleteQueue.push(item); if (item === this.currentTrack) { var nextPos = this.currentTrack.index + 1; for (;;) { var nextTrack = this.tracksInOrder[nextPos]; var nextTrackId = nextTrack && nextTrack.id; this.currentTrack = nextTrackId && this.playlist[nextTrack.id]; if (!this.currentTrack && nextPos < this.tracksInOrder.length) { nextPos += 1; continue; } break; } if (this.currentTrack) { this.seekRequestPos = 0; } currentTrackChanged = true; } delete this.playlist[id]; } if (delCmds.length > 0) this.db.batch(delCmds, logIfDbError); playlistChanged(this); if (currentTrackChanged) { this.currentTrackChanged(); } }; // items looks like {id: {sortKey}} Player.prototype.moveQueueItems = function(items) { var updateCmds = []; for (var id in items) { var track = this.playlist[id]; if (!track) continue; // race conditions, etc. track.sortKey = items[id].sortKey; persistQueueItem(track, updateCmds); } if (updateCmds.length > 0) { this.db.batch(updateCmds, logIfDbError); playlistChanged(this); } }; Player.prototype.moveRangeToPos = function(startPos, endPos, toPos) { var ids = []; for (var i = startPos; i < endPos; i += 1) { var track = this.tracksInOrder[i]; if (!track) continue; ids.push(track.id); } this.moveIdsToPos(ids, toPos); }; Player.prototype.moveIdsToPos = function(ids, toPos) { var trackBeforeIndex = this.tracksInOrder[toPos - 1]; var trackAtIndex = this.tracksInOrder[toPos]; var prevSortKey = trackBeforeIndex ? trackBeforeIndex.sortKey : null; var nextSortKey = trackAtIndex ? trackAtIndex.sortKey : null; var sortKeys = keese(prevSortKey, nextSortKey, ids.length); var updateCmds = []; for (var i = 0; i < ids.length; i += 1) { var id = ids[i]; var queueItem = this.playlist[id]; if (!queueItem) continue; queueItem.sortKey = sortKeys[i]; persistQueueItem(queueItem, updateCmds); } if (updateCmds.length > 0) { this.db.batch(updateCmds, logIfDbError); playlistChanged(this); } }; Player.prototype.pause = function() { if (!this.isPlaying) return; this.isPlaying = false; this.pausedTime = (new Date() - this.trackStartDate) / 1000; this.groovePlaylist.pause(); this.cancelDetachEncoderTimeout(); playlistChanged(this); this.currentTrackChanged(); }; Player.prototype.play = function() { if (!this.currentTrack) { this.currentTrack = this.tracksInOrder[0]; } else if (!this.isPlaying) { this.trackStartDate = new Date(new Date() - this.pausedTime * 1000); } this.groovePlaylist.play(); this.startDetachEncoderTimeout(); this.isPlaying = true; playlistChanged(this); this.currentTrackChanged(); }; // This function should be avoided in favor of seek. Note that it is called by // some MPD protocol commands, because the MPD protocol is stupid. Player.prototype.seekToIndex = function(index, pos) { var track = this.tracksInOrder[index]; if (!track) return null; this.currentTrack = track; this.seekRequestPos = pos; playlistChanged(this); this.currentTrackChanged(); return track; }; Player.prototype.seek = function(id, pos) { var track = this.playlist[id]; if (!track) return null; this.currentTrack = this.playlist[id]; this.seekRequestPos = pos; playlistChanged(this); this.currentTrackChanged(); return track; }; Player.prototype.next = function() { return this.skipBy(1); }; Player.prototype.prev = function() { return this.skipBy(-1); }; Player.prototype.skipBy = function(amt) { var defaultIndex = amt > 0 ? -1 : this.tracksInOrder.length; var currentIndex = this.currentTrack ? this.currentTrack.index : defaultIndex; var newIndex = currentIndex + amt; return this.seekToIndex(newIndex, 0); }; Player.prototype.setRepeat = function(value) { value = Math.floor(value); if (value !== Player.REPEAT_ONE && value !== Player.REPEAT_ALL && value !== Player.REPEAT_OFF) { return; } if (value === this.repeat) return; this.repeat = value; this.persistOption('repeat', this.repeat); playlistChanged(this); this.emit('repeatUpdate'); }; Player.prototype.setAutoDjOn = function(value) { value = !!value; if (value === this.autoDjOn) return; this.autoDjOn = value; this.persistOption('autoDjOn', this.autoDjOn); this.emit('autoDjOn'); this.checkAutoDj(); }; Player.prototype.setAutoDjHistorySize = function(value) { value = Math.floor(value); if (value === this.autoDjHistorySize) return; this.autoDjHistorySize = value; this.persistOption('autoDjHistorySize', this.autoDjHistorySize); this.emit('autoDjHistorySize'); this.checkAutoDj(); }; Player.prototype.setAutoDjFutureSize = function(value) { value = Math.floor(value); if (value === this.autoDjFutureSize) return; this.autoDjFutureSize = value; this.persistOption('autoDjFutureSize', this.autoDjFutureSize); this.emit('autoDjFutureSize'); this.checkAutoDj(); }; Player.prototype.stop = function() { this.isPlaying = false; this.cancelDetachEncoderTimeout(); this.groovePlaylist.pause(); this.seekRequestPos = 0; this.pausedTime = 0; playlistChanged(this); }; Player.prototype.clearEncodedBuffer = function() { while (this.recentBuffers.length > 0) { this.recentBuffers.shift(); } }; Player.prototype.getSuggestedPath = function(track, filenameHint) { var p = ""; if (track.albumArtistName) { p = path.join(p, safePath(track.albumArtistName)); } else if (track.compilation) { p = path.join(p, safePath(this.libraryIndex.variousArtistsName)); } else if (track.artistName) { p = path.join(p, safePath(track.artistName)); } if (track.albumName) { p = path.join(p, safePath(track.albumName)); } var t = ""; if (track.track != null) { t += safePath(zfill(track.track, 2)) + " "; } t += safePath(track.name + path.extname(filenameHint)); return path.join(p, t); }; Player.prototype.queueScan = function(dbFile) { var self = this; var scanKey, scanType; if (dbFile.albumName) { scanType = 'album'; scanKey = self.libraryIndex.getAlbumKey(dbFile); } else { scanType = 'track'; scanKey = dbFile.key; } if (self.scanQueue.idInQueue(scanKey)) { return; } self.scanQueue.add(scanKey, { type: scanType, key: scanKey, }); }; Player.prototype.performScan = function(args, cb) { var self = this; var scanType = args.type; var scanKey = args.key; // build list of files we want to open var dbFilesToOpen; if (scanType === 'album') { var albumKey = scanKey; self.libraryIndex.rebuildTracks(); var album = self.libraryIndex.albumTable[albumKey]; if (!album) { log.warn("wanted to scan album with key", JSON.stringify(albumKey), "but no longer exists."); cb(); return; } log.debug("Scanning album for loudness:", JSON.stringify(albumKey)); dbFilesToOpen = album.trackList; } else if (scanType === 'track') { var trackKey = scanKey; var dbFile = self.libraryIndex.trackTable[trackKey]; if (!dbFile) { log.warn("wanted to scan track with key", JSON.stringify(trackKey), "but no longer exists."); cb(); return; } log.debug("Scanning track for loudness:", JSON.stringify(trackKey)); dbFilesToOpen = [dbFile]; } else { throw new Error("unexpected scan type: " + scanType); } // open all the files in the list var pend = new Pend(); // we're already doing multiple parallel scans. within each scan let's // read one thing at a time to avoid slamming the system. pend.max = 1; var grooveFileList = []; var files = {}; dbFilesToOpen.forEach(function(dbFile) { pend.go(function(cb) { var fullPath = path.join(self.musicDirectory, dbFile.file); log.debug("performScan open file:", fullPath); groove.open(fullPath, function(err, file) { if (err) { log.error("Error opening", fullPath, "in order to scan:", err.stack); } else { var fileInfo; files[file.id] = fileInfo = { dbFile: dbFile, loudnessDone: false, fingerprintDone: false, }; self.ongoingScans[dbFile.key] = fileInfo; grooveFileList.push(file); } cb(); }); }); }); var scanPlaylist; var endOfPlaylistPend = new Pend(); var scanDetector; var scanDetectorAttached = false; var endOfDetectorCb; var scanFingerprinter; var scanFingerprinterAttached = false; var endOfFingerprinterCb; pend.wait(function() { // emit this because we updated ongoingScans self.emit('scanProgress'); scanPlaylist = groove.createPlaylist(); scanPlaylist.setFillMode(groove.ANY_SINK_FULL); scanDetector = groove.createLoudnessDetector(); scanFingerprinter = groove.createFingerprinter(); scanDetector.on('info', onLoudnessInfo); scanFingerprinter.on('info', onFingerprinterInfo); var pend = new Pend(); pend.go(attachLoudnessDetector); pend.go(attachFingerprinter); pend.wait(onEverythingAttached); }); function onEverythingAttached(err) { if (err) { log.error("Error attaching:", err.stack); cleanupAndCb(); return; } grooveFileList.forEach(function(file) { scanPlaylist.insert(file); }); endOfPlaylistPend.wait(function() { for (var fileId in files) { var fileInfo = files[fileId]; var dbFile = fileInfo.dbFile; self.persistOneDbFile(dbFile); self.emit('scanComplete', dbFile); } cleanupAndCb(); }); } function attachLoudnessDetector(cb) { scanDetector.attach(scanPlaylist, function(err) { if (err) return cb(err); scanDetectorAttached = true; endOfPlaylistPend.go(function(cb) { endOfDetectorCb = cb; }); cb(); }); } function attachFingerprinter(cb) { scanFingerprinter.attach(scanPlaylist, function(err) { if (err) return cb(err); scanFingerprinterAttached = true; endOfPlaylistPend.go(function(cb) { endOfFingerprinterCb = cb; }); cb(); }); } function onLoudnessInfo() { var info; while (info = scanDetector.getInfo()) { var gain = groove.loudnessToReplayGain(info.loudness); var dbFile; var fileInfo; if (info.item) { fileInfo = files[info.item.file.id]; fileInfo.loudnessDone = true; dbFile = fileInfo.dbFile; log.info("loudness scan file complete:", dbFile.name, "gain", gain, "duration", info.duration); dbFile.replayGainTrackGain = gain; dbFile.replayGainTrackPeak = info.peak; dbFile.duration = info.duration; checkUpdateGroovePlaylist(self); self.emit('scanProgress'); } else { log.debug("loudness scan complete:", JSON.stringify(scanKey), "gain", gain); for (var fileId in files) { fileInfo = files[fileId]; dbFile = fileInfo.dbFile; dbFile.replayGainAlbumGain = gain; dbFile.replayGainAlbumPeak = info.peak; } checkUpdateGroovePlaylist(self); if (endOfDetectorCb) { endOfDetectorCb(); endOfDetectorCb = null; } return; } } } function onFingerprinterInfo() { var info; while (info = scanFingerprinter.getInfo()) { if (info.item) { var fileInfo = files[info.item.file.id]; fileInfo.fingerprintDone = true; var dbFile = fileInfo.dbFile; log.info("fingerprint scan file complete:", dbFile.name); dbFile.fingerprint = info.fingerprint; self.emit('scanProgress'); } else { log.debug("fingerprint scan complete:", JSON.stringify(scanKey)); if (endOfFingerprinterCb) { endOfFingerprinterCb(); endOfFingerprinterCb = null; } return; } } } function cleanupAndCb() { grooveFileList.forEach(function(file) { pend.go(function(cb) { var fileInfo = files[file.id]; var dbFile = fileInfo.dbFile; delete self.ongoingScans[dbFile.key]; log.debug("performScan close file:", file.filename); file.close(cb); }); }); if (scanDetectorAttached) pend.go(detachLoudnessScanner); if (scanFingerprinterAttached) pend.go(detachFingerprinter); pend.wait(function(err) { // emit this because we changed ongoingScans above self.emit('scanProgress'); cb(err); }); } function detachLoudnessScanner(cb) { scanDetector.detach(cb); } function detachFingerprinter(cb) { scanFingerprinter.detach(cb); } }; Player.prototype.checkAutoDj = function() { var self = this; if (!self.autoDjOn) return; // if no track is playing, assume the first track is about to be var currentIndex = self.currentTrack ? self.currentTrack.index : 0; var deleteCount = Math.max(currentIndex - self.autoDjHistorySize, 0); if (self.autoDjHistorySize < 0) deleteCount = 0; var addCount = Math.max(self.autoDjFutureSize + 1 - (self.tracksInOrder.length - currentIndex), 0); var idsToDelete = []; for (var i = 0; i < deleteCount; i += 1) { idsToDelete.push(self.tracksInOrder[i].id); } var keys = getRandomSongKeys(addCount); self.removeQueueItems(idsToDelete); self.appendTracks(keys, true); function getRandomSongKeys(count) { if (count === 0) return []; var neverQueued = []; var sometimesQueued = []; for (var key in self.libraryIndex.trackTable) { var dbFile = self.libraryIndex.trackTable[key]; if (dbFile.lastQueueDate == null) { neverQueued.push(dbFile); } else { sometimesQueued.push(dbFile); } } // backwards by time sometimesQueued.sort(function(a, b) { return b.lastQueueDate - a.lastQueueDate; }); // distribution is a triangle for ever queued, and a rectangle for never queued // ___ // /| | // / | | // /__|_| var maxWeight = sometimesQueued.length; var triangleArea = Math.floor(maxWeight * maxWeight / 2); if (maxWeight === 0) maxWeight = 1; var rectangleArea = maxWeight * neverQueued.length; var totalSize = triangleArea + rectangleArea; if (totalSize === 0) return []; // decode indexes through the distribution shape var keys = []; for (var i = 0; i < count; i += 1) { var index = Math.random() * totalSize; if (index < triangleArea) { // triangle keys.push(sometimesQueued[Math.floor(Math.sqrt(index))].key); } else { keys.push(neverQueued[Math.floor((index - triangleArea) / maxWeight)].key); } } return keys; } }; Player.prototype.currentTrackChanged = function() { this.persistCurrentTrack(); this.emit('currentTrack'); }; Player.prototype.persistCurrentTrack = function(cb) { // save the current track and time to db var currentTrackInfo = { id: this.currentTrack && this.currentTrack.id, pos: this.getCurPos(), }; this.persistOption('currentTrackInfo', currentTrackInfo, cb); }; Player.prototype.sortAndQueueTracks = function(tracks) { // given an array of tracks, sort them according to the library sorting // and then queue them in the best place if (!tracks.length) return; var sortedTracks = sortTracks(tracks); this.queueTracks(sortedTracks); }; Player.prototype.sortAndQueueTracksInPlaylist = function(playlist, tracks, previousKey, nextKey) { if (!tracks.length) return; var sortedTracks = sortTracks(tracks); var items = {}; var sortKeys = keese(previousKey, nextKey, tracks.length); for (var i = 0; i < tracks.length; i += 1) { var track = tracks[i]; var sortKey = sortKeys[i]; var id = uuid(); items[id] = { key: track.key, sortKey: sortKey, }; } this.playlistAddItems(playlist.id, items); }; Player.prototype.queueTrackKeys = function(trackKeys, previousKey, nextKey) { if (!trackKeys.length) return; if (previousKey == null && nextKey == null) { var defaultPos = this.getDefaultQueuePosition(); previousKey = defaultPos.previousKey; nextKey = defaultPos.nextKey; } var items = {}; var sortKeys = keese(previousKey, nextKey, trackKeys.length); for (var i = 0; i < trackKeys.length; i += 1) { var trackKey = trackKeys[i]; var sortKey = sortKeys[i]; var id = uuid(); items[id] = { key: trackKey, sortKey: sortKey, }; } this.addItems(items, false); }; Player.prototype.queueTracks = function(tracks, previousKey, nextKey) { // given an array of tracks, and a previous sort key and a next sort key, // call addItems correctly var trackKeys = tracks.map(function(track) { return track.key; }).filter(function(key) { return !!key; }); return this.queueTrackKeys(trackKeys, previousKey, nextKey); }; Player.prototype.getDefaultQueuePosition = function() { var previousKey = this.currentTrack && this.currentTrack.sortKey; var nextKey = null; var startPos = this.currentTrack ? this.currentTrack.index + 1 : 0; for (var i = startPos; i < this.tracksInOrder.length; i += 1) { var track = this.tracksInOrder[i]; var sortKey = track.sortKey; if (track.isRandom) { nextKey = sortKey; break; } previousKey = sortKey; } return { previousKey: previousKey, nextKey: nextKey }; }; function persistDbFile(dbFile, updateCmds) { updateCmds.push({ type: 'put', key: LIBRARY_KEY_PREFIX + dbFile.key, value: serializeFileData(dbFile), }); } function persistQueueItem(item, updateCmds) { updateCmds.push({ type: 'put', key: QUEUE_KEY_PREFIX + item.id, value: serializeQueueItem(item), }); } function onAddOrChange(self, relPath, fileMtime, cb) { cb = cb || logIfError; // check the mtime against the mtime of the same file in the db var dbFile = self.dbFilesByPath[relPath]; if (dbFile) { var dbMtime = dbFile.mtime; if (dbMtime >= fileMtime) { // the info we have in our db for this file is fresh cb(null, dbFile); return; } } self.addQueue.add(relPath, { relPath: relPath, mtime: fileMtime, }); self.addQueue.waitForId(relPath, function(err) { var dbFile = self.dbFilesByPath[relPath]; cb(err, dbFile); }); function logIfError(err) { if (err) { log.error("Unable to add to queue:", err.stack); } } } function checkPlayCount(self) { if (self.isPlaying && !self.previousIsPlaying) { self.playingStart = new Date(new Date() - self.playingTime); self.previousIsPlaying = true; } self.playingTime = new Date() - self.playingStart; if (self.currentTrack === self.lastPlayingItem) return; if (self.lastPlayingItem) { var dbFile = self.libraryIndex.trackTable[self.lastPlayingItem.key]; if (dbFile) { var minAmt = 15 * 1000; var maxAmt = 4 * 60 * 1000; var halfAmt = dbFile.duration / 2 * 1000; if (self.playingTime >= minAmt && (self.playingTime >= maxAmt || self.playingTime >= halfAmt)) { dbFile.playCount += 1; self.persistOneDbFile(dbFile); self.emit('play', self.lastPlayingItem, dbFile, self.playingStart); self.emit('updateDb'); } } } self.lastPlayingItem = self.currentTrack; self.previousIsPlaying = self.isPlaying; self.playingStart = new Date(); self.playingTime = 0; } function disableFsListenRef(self, fn) { self.disableFsRefCount += 1; if (self.disableFsRefCount === 1) { log.debug("pause dirScanQueue"); self.dirScanQueue.setPause(true); self.dirScanQueue.waitForProcessing(fn); } else { fn(); } } function disableFsListenUnref(self) { self.disableFsRefCount -= 1; if (self.disableFsRefCount === 0) { log.debug("unpause dirScanQueue"); self.dirScanQueue.setPause(false); } else if (self.disableFsRefCount < 0) { throw new Error("disableFsListenUnref called too many times"); } } function operatorCompare(a, b) { return a < b ? -1 : a > b ? 1 : 0; } function disambiguateSortKeys(self) { var previousUniqueKey = null; var previousKey = null; self.tracksInOrder.forEach(function(track, i) { if (track.sortKey === previousKey) { // move the repeat back track.sortKey = keese(previousUniqueKey, track.sortKey); previousUniqueKey = track.sortKey; } else { previousUniqueKey = previousKey; previousKey = track.sortKey; } }); } // generate self.tracksInOrder from self.playlist function cacheTracksArray(self) { self.tracksInOrder = Object.keys(self.playlist).map(trackById); self.tracksInOrder.sort(asc); self.tracksInOrder.forEach(function(track, index) { track.index = index; }); function asc(a, b) { return operatorCompare(a.sortKey, b.sortKey); } function trackById(id) { return self.playlist[id]; } } function lazyReplayGainScanPlaylist(self) { // clear the queue since we're going to completely rebuild it anyway // this allows the following priority code to work. self.scanQueue.clear(); // prioritize the currently playing track, followed by the next tracks, // followed by the previous tracks var albumGain = {}; var start1 = self.currentTrack ? self.currentTrack.index : 0; var i; for (i = start1; i < self.tracksInOrder.length; i += 1) { checkScan(self.tracksInOrder[i]); } for (i = 0; i < start1; i += 1) { checkScan(self.tracksInOrder[i]); } function checkScan(track) { var dbFile = self.libraryIndex.trackTable[track.key]; if (!dbFile) return; var albumKey = self.libraryIndex.getAlbumKey(dbFile); var needScan = dbFile.fingerprint == null || dbFile.replayGainAlbumGain == null || dbFile.replayGainTrackGain == null || (dbFile.albumName && albumGain[albumKey] && albumGain[albumKey] !== dbFile.replayGainAlbumGain); if (needScan) { self.queueScan(dbFile); } else { albumGain[albumKey] = dbFile.replayGainAlbumGain; } } } function playlistChanged(self) { cacheTracksArray(self); disambiguateSortKeys(self); if (self.currentTrack) { self.tracksInOrder.forEach(function(track, index) { var prevDiff = self.currentTrack.index - index; var nextDiff = index - self.currentTrack.index; var withinPrev = prevDiff <= PREV_FILE_COUNT && prevDiff >= 0; var withinNext = nextDiff <= NEXT_FILE_COUNT && nextDiff >= 0; var shouldHaveGrooveFile = withinPrev || withinNext; var hasGrooveFile = track.grooveFile != null || track.pendingGrooveFile; if (hasGrooveFile && !shouldHaveGrooveFile) { self.playlistItemDeleteQueue.push(track); } else if (!hasGrooveFile && shouldHaveGrooveFile) { preloadFile(self, track); } }); } else { self.isPlaying = false; self.cancelDetachEncoderTimeout(); self.trackStartDate = null; self.pausedTime = 0; } checkUpdateGroovePlaylist(self); performGrooveFileDeletes(self); self.checkAutoDj(); checkPlayCount(self); self.emit('queueUpdate'); } function performGrooveFileDeletes(self) { while (self.playlistItemDeleteQueue.length) { var item = self.playlistItemDeleteQueue.shift(); // we set this so that any callbacks that return which were trying to // set the grooveItem can check if the item got deleted item.deleted = true; if (!item.grooveFile) continue; log.debug("performGrooveFileDeletes close file:", item.grooveFile.filename); var grooveFile = item.grooveFile; item.grooveFile = null; closeFile(grooveFile); } } function preloadFile(self, track) { var relPath = self.libraryIndex.trackTable[track.key].file; var fullPath = path.join(self.musicDirectory, relPath); track.pendingGrooveFile = true; log.debug("preloadFile open file:", fullPath); // set this so that we know we want the file preloaded track.deleted = false; groove.open(fullPath, function(err, file) { track.pendingGrooveFile = false; if (err) { log.error("Error opening", relPath, err.stack); return; } if (track.deleted) { log.debug("preloadFile close file (already deleted):", file.filename); closeFile(file); return; } track.grooveFile = file; checkUpdateGroovePlaylist(self); }); } function checkUpdateGroovePlaylist(self) { if (!self.currentTrack) { self.groovePlaylist.clear(); self.grooveItems = {}; return; } var groovePlaylist = self.groovePlaylist.items(); var playHead = self.groovePlayer.position(); var playHeadItemId = playHead.item && playHead.item.id; var groovePlIndex = 0; var grooveItem; if (playHeadItemId) { while (groovePlIndex < groovePlaylist.length) { grooveItem = groovePlaylist[groovePlIndex]; if (grooveItem.id === playHeadItemId) break; // this groove playlist item is before the current playhead. delete it! self.groovePlaylist.remove(grooveItem); delete self.grooveItems[grooveItem.id]; groovePlIndex += 1; } } var plItemIndex = self.currentTrack.index; var plTrack; var currentGrooveItem = null; // might be different than playHead.item var groovePlItemCount = 0; var gainAndPeak; while (groovePlIndex < groovePlaylist.length) { grooveItem = groovePlaylist[groovePlIndex]; var grooveTrack = self.grooveItems[grooveItem.id]; // now we have deleted all items before the current track. we are now // comparing the libgroove playlist and the groovebasin playlist // side by side. plTrack = self.tracksInOrder[plItemIndex]; if (grooveTrack === plTrack) { // if they're the same, we advance // but we might have to correct the gain gainAndPeak = calcGainAndPeak(plTrack); self.groovePlaylist.setItemGain(grooveItem, gainAndPeak.gain); self.groovePlaylist.setItemPeak(grooveItem, gainAndPeak.peak); currentGrooveItem = currentGrooveItem || grooveItem; groovePlIndex += 1; incrementPlIndex(); continue; } // this groove track is wrong. delete it. self.groovePlaylist.remove(grooveItem); delete self.grooveItems[grooveItem.id]; groovePlIndex += 1; } // we still need to add more libgroove playlist items, but this one has // not yet finished loading from disk. We must take note of this so that // if we receive the end of playlist sentinel, we start playback again // once this track has finished loading. self.dontBelieveTheEndOfPlaylistSentinelItsATrap = true; while (groovePlItemCount < NEXT_FILE_COUNT) { plTrack = self.tracksInOrder[plItemIndex]; if (!plTrack) { // we hit the end of the groove basin playlist. we're done adding tracks // to the libgroove playlist. self.dontBelieveTheEndOfPlaylistSentinelItsATrap = false; break; } if (!plTrack.grooveFile) { break; } // compute the gain adjustment gainAndPeak = calcGainAndPeak(plTrack); grooveItem = self.groovePlaylist.insert(plTrack.grooveFile, gainAndPeak.gain, gainAndPeak.peak); self.grooveItems[grooveItem.id] = plTrack; currentGrooveItem = currentGrooveItem || grooveItem; incrementPlIndex(); } if (currentGrooveItem && self.seekRequestPos >= 0) { var seekPos = self.seekRequestPos; // we want to clear encoded buffers after the seek completes, e.g. after // we get the end of playlist sentinel self.clearEncodedBuffer(); self.queueClearEncodedBuffers = true; self.groovePlaylist.seek(currentGrooveItem, seekPos); self.seekRequestPos = -1; if (self.isPlaying) { var nowMs = (new Date()).getTime(); var posMs = seekPos * 1000; self.trackStartDate = new Date(nowMs - posMs); } else { self.pausedTime = seekPos; } self.currentTrackChanged(); } function calcGainAndPeak(plTrack) { // if the previous item is the previous item from the album, or the // next item is the next item from the album, use album replaygain. // else, use track replaygain. var dbFile = self.libraryIndex.trackTable[plTrack.key]; var albumMode = albumInfoMatch(-1) || albumInfoMatch(1); var gain = REPLAYGAIN_PREAMP; var peak; if (dbFile.replayGainAlbumGain != null && albumMode) { gain *= dBToFloat(dbFile.replayGainAlbumGain); peak = dbFile.replayGainAlbumPeak || 1.0; } else if (dbFile.replayGainTrackGain != null) { gain *= dBToFloat(dbFile.replayGainTrackGain); peak = dbFile.replayGainTrackPeak || 1.0; } else { gain *= REPLAYGAIN_DEFAULT; peak = 1.0; } return {gain: gain, peak: peak}; function albumInfoMatch(dir) { var otherPlTrack = self.tracksInOrder[plTrack.index + dir]; if (!otherPlTrack) return false; var otherDbFile = self.libraryIndex.trackTable[otherPlTrack.key]; if (!otherDbFile) return false; var albumMatch = self.libraryIndex.getAlbumKey(dbFile) === self.libraryIndex.getAlbumKey(otherDbFile); if (!albumMatch) return false; // if there are no track numbers then it's hardly an album, is it? if (dbFile.track == null || otherDbFile.track == null) { return false; } var trackMatch = dbFile.track + dir === otherDbFile.track; if (!trackMatch) return false; return true; } } function incrementPlIndex() { groovePlItemCount += 1; if (self.repeat !== Player.REPEAT_ONE) { plItemIndex += 1; if (self.repeat === Player.REPEAT_ALL && plItemIndex >= self.tracksInOrder.length) { plItemIndex = 0; } } } } function isFileIgnored(basename) { return (/^\./).test(basename) || (/~$/).test(basename); } function isExtensionIgnored(self, extName) { var extNameLower = extName.toLowerCase(); for (var i = 0; i < self.ignoreExtensions.length; i += 1) { if (self.ignoreExtensions[i] === extNameLower) { return true; } } return false; } function deserializeFileData(dataStr) { var dbFile = JSON.parse(dataStr); for (var propName in DB_PROPS) { var propInfo = DB_PROPS[propName]; if (!propInfo) continue; var parser = PROP_TYPE_PARSERS[propInfo.type]; dbFile[propName] = parser(dbFile[propName]); } return dbFile; } function serializeQueueItem(item) { return JSON.stringify({ id: item.id, key: item.key, sortKey: item.sortKey, isRandom: item.isRandom, }); } function serializePlaylistItem(item) { return JSON.stringify({ id: item.id, key: item.key, sortKey: item.sortKey, }); } function trackWithoutIndex(category, dbFile) { var out = {}; for (var propName in DB_PROPS) { var prop = DB_PROPS[propName]; if (!prop[category]) continue; // save space by leaving out null and undefined values var value = dbFile[propName]; if (value == null) continue; if (prop.type === 'set') { out[propName] = copySet(value); } else { out[propName] = value; } } return out; } function serializeFileData(dbFile) { return JSON.stringify(trackWithoutIndex('db', dbFile)); } function serializeDirEntry(dirEntry) { return JSON.stringify({ dirName: dirEntry.dirName, entries: dirEntry.entries, dirEntries: dirEntry.dirEntries, mtime: dirEntry.mtime, }); } function filenameWithoutExt(filename) { var ext = path.extname(filename); return filename.substring(0, filename.length - ext.length); } function closeFile(file) { file.close(function(err) { if (err) { log.error("Error closing", file, err.stack); } }); } function parseTrackString(trackStr) { if (!trackStr) return {}; var parts = trackStr.split('/'); if (parts.length > 1) { return { value: parseIntOrNull(parts[0]), total: parseIntOrNull(parts[1]), }; } return { value: parseIntOrNull(parts[0]), }; } function parseIntOrNull(n) { n = parseInt(n, 10); if (isNaN(n)) return null; return n; } function parseFloatOrNull(n) { n = parseFloat(n); if (isNaN(n)) return null; return n; } function grooveFileToDbFile(file, filenameHintWithoutPath, object) { object = object || {key: uuid()}; var parsedTrack = parseTrackString(file.getMetadata("track")); var parsedDisc = parseTrackString( file.getMetadata("disc") || file.getMetadata("TPA") || file.getMetadata("TPOS")); object.name = (file.getMetadata("title") || filenameWithoutExt(filenameHintWithoutPath) || "").trim(); object.artistName = (file.getMetadata("artist") || "").trim(); object.composerName = (file.getMetadata("composer") || file.getMetadata("TCM") || "").trim(); object.performerName = (file.getMetadata("performer") || "").trim(); object.albumArtistName = (file.getMetadata("album_artist") || "").trim(); object.albumName = (file.getMetadata("album") || "").trim(); object.compilation = !!(parseInt(file.getMetadata("TCP"), 10) || parseInt(file.getMetadata("TCMP"), 10) || file.getMetadata("COMPILATION") || file.getMetadata("Compilation") || file.getMetadata("cpil") || file.getMetadata("WM/IsCompilation")); object.track = parsedTrack.value; object.trackCount = parsedTrack.total; object.disc = parsedDisc.value; object.discCount = parsedDisc.total; object.duration = file.duration(); object.year = parseIntOrNull(file.getMetadata("date")); object.genre = file.getMetadata("genre"); object.replayGainTrackGain = parseFloatOrNull(file.getMetadata("REPLAYGAIN_TRACK_GAIN")); object.replayGainTrackPeak = parseFloatOrNull(file.getMetadata("REPLAYGAIN_TRACK_PEAK")); object.replayGainAlbumGain = parseFloatOrNull(file.getMetadata("REPLAYGAIN_ALBUM_GAIN")); object.replayGainAlbumPeak = parseFloatOrNull(file.getMetadata("REPLAYGAIN_ALBUM_PEAK")); object.labels = {}; return object; } function uniqueFilename(filename) { // break into parts var dirname = path.dirname(filename); var basename = path.basename(filename); var extname = path.extname(filename); var withoutExt = basename.substring(0, basename.length - extname.length); var match = withoutExt.match(/_(\d+)$/); var withoutMatch; var number; if (match) { number = parseInt(match[1], 10); if (!number) number = 0; withoutMatch = withoutExt.substring(0, match.index); } else { number = 0; withoutMatch = withoutExt; } number += 1; // put it back together var newBasename = withoutMatch + "_" + number + extname; return path.join(dirname, newBasename); } function dBToFloat(dB) { return Math.exp(dB * DB_SCALE); } function ensureSep(dir) { return (dir[dir.length - 1] === path.sep) ? dir : (dir + path.sep); } function ensureGrooveVersionIsOk() { var ver = groove.getVersion(); var verStr = ver.major + '.' + ver.minor + '.' + ver.patch; var reqVer = '>=4.1.1'; if (semver.satisfies(verStr, reqVer)) return; log.fatal("Found libgroove", verStr, "need", reqVer); process.exit(1); } function playlistItemKey(playlist, item) { return PLAYLIST_KEY_PREFIX + playlist.id + '.' + item.id; } function playlistKey(playlist) { return PLAYLIST_META_KEY_PREFIX + playlist.id; } function serializePlaylist(playlist) { return JSON.stringify({ id: playlist.id, name: playlist.name, mtime: playlist.mtime, }); } function deserializePlaylist(str) { var playlist = JSON.parse(str); playlist.items = {}; return playlist; } function zfill(number, size) { number = String(number); while (number.length < size) number = "0" + number; return number; } function setGrooveLoggingLevel() { switch (log.level) { case log.levels.Fatal: case log.levels.Error: case log.levels.Info: case log.levels.Warn: groove.setLogging(groove.LOG_QUIET); break; case log.levels.Debug: groove.setLogging(groove.LOG_INFO); break; } } function importFileAsSong(self, srcFullPath, filenameHintWithoutPath, cb) { groove.open(srcFullPath, function(err, file) { if (err) return cb(err); var newDbFile = grooveFileToDbFile(file, filenameHintWithoutPath); var suggestedPath = self.getSuggestedPath(newDbFile, filenameHintWithoutPath); var pend = new Pend(); pend.go(function(cb) { log.debug("importFileAsSong close file:", file.filename); file.close(cb); }); pend.go(function(cb) { tryMv(suggestedPath, cb); }); pend.wait(function(err) { if (err) return cb(err); cb(null, [newDbFile]); }); function tryMv(destRelPath, cb) { var destFullPath = path.join(self.musicDirectory, destRelPath); // before importFileAsSong is called, file system watching is disabled. // So we can safely move files into the library without triggering an // update db. mv(srcFullPath, destFullPath, {mkdirp: true, clobber: false}, function(err) { if (err) { if (err.code === 'EEXIST') { tryMv(uniqueFilename(destRelPath), cb); } else { cb(err); } return; } onAddOrChange(self, destRelPath, (new Date()).getTime(), function(err, dbFile) { if (err) return cb(err); newDbFile = dbFile; cb(); }); }); } }); } function importFileAsZip(self, srcFullPath, filenameHintWithoutPath, cb) { yauzl.open(srcFullPath, function(err, zipfile) { if (err) return cb(err); var allDbFiles = []; var pend = new Pend(); zipfile.on('error', handleError); zipfile.on('entry', onEntry); zipfile.on('end', onEnd); function onEntry(entry) { if (/\/$/.test(entry.fileName)) { // ignore directories return; } pend.go(function(cb) { zipfile.openReadStream(entry, function(err, readStream) { if (err) { log.warn("Error reading zip file:", err.stack); cb(); return; } var entryBaseName = path.basename(entry.fileName); self.importStream(readStream, entryBaseName, entry.uncompressedSize, function(err, dbFiles) { if (err) { log.warn("unable to import entry from zip file:", err.stack); } else if (dbFiles) { allDbFiles = allDbFiles.concat(dbFiles); } cb(); }); }); }); } function onEnd() { pend.wait(function() { unlinkZipFile(); cb(null, allDbFiles); }); } function handleError(err) { unlinkZipFile(); cb(err); } function unlinkZipFile() { fs.unlink(srcFullPath, function(err) { if (err) { log.error("Unable to remove zip file after importing:", err.stack); } }); } }); } // sort keys according to how they appear in the library function sortTracks(tracks) { var lib = new MusicLibraryIndex(); tracks.forEach(function(track) { lib.addTrack(track); }); lib.rebuildTracks(); var results = []; lib.artistList.forEach(function(artist) { artist.albumList.forEach(function(album) { album.trackList.forEach(function(track) { results.push(track); }); }); }); return results; } function logIfDbError(err) { if (err) { log.error("Unable to update DB:", err.stack); } } function makeLower(str) { return str.toLowerCase(); } function copySet(set) { var out = {}; for (var key in set) { out[key] = 1; } return out; }
b'What is 22 + 7 + 13 + -29 - 16?\n'
<?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>File: calculations.rb</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <meta http-equiv="Content-Script-Type" content="text/javascript" /> <link rel="stylesheet" href="../../../../../../../../../../../.././rdoc-style.css" type="text/css" media="screen" /> <script type="text/javascript"> // <![CDATA[ function popupCode( url ) { window.open(url, "Code", "resizable=yes,scrollbars=yes,toolbar=no,status=no,height=150,width=400") } function toggleCode( id ) { if ( document.getElementById ) elem = document.getElementById( id ); else if ( document.all ) elem = eval( "document.all." + id ); else return false; elemStyle = elem.style; if ( elemStyle.display != "block" ) { elemStyle.display = "block" } else { elemStyle.display = "none" } return true; } // Make codeblocks hidden by default document.writeln( "<style type=\"text/css\">div.method-source-code { display: none }</style>" ) // ]]> </script> </head> <body> <div id="fileHeader"> <h1>calculations.rb</h1> <table class="header-table"> <tr class="top-aligned-row"> <td><strong>Path:</strong></td> <td>/usr/lib/ruby/gems/1.8/gems/activesupport-3.0.0.beta4/lib/active_support/core_ext/time/calculations.rb </td> </tr> <tr class="top-aligned-row"> <td><strong>Last Update:</strong></td> <td>Sun Jun 20 17:19:12 -0600 2010</td> </tr> </table> </div> <!-- banner header --> <div id="bodyContent"> <div id="contextContent"> <div id="requires-list"> <h3 class="section-bar">Required files</h3> <div class="name-list"> active_support/duration&nbsp;&nbsp; active_support/core_ext/date/acts_like&nbsp;&nbsp; active_support/core_ext/date/calculations&nbsp;&nbsp; active_support/core_ext/date_time/conversions&nbsp;&nbsp; </div> </div> </div> </div> <!-- if includes --> <div id="section"> <!-- if method_list --> </div> <div id="validator-badges"> <p><small><a href="http://validator.w3.org/check/referer">[Validate]</a></small></p> </div> </body> </html>
<?xml version="1.0" ?><!DOCTYPE TS><TS language="zh_TW" version="2.0"> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About GulfCoin</source> <translation>關於位元幣</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;GulfCoin&lt;/b&gt; version</source> <translation>&lt;b&gt;位元幣&lt;/b&gt;版本</translation> </message> <message> <location line="+57"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source> <translation> 這是一套實驗性的軟體. 此軟體是依據 MIT/X11 軟體授權條款散布, 詳情請見附帶的 COPYING 檔案, 或是以下網站: http://www.opensource.org/licenses/mit-license.php. 此產品也包含了由 OpenSSL Project 所開發的 OpenSSL Toolkit (http://www.openssl.org/) 軟體, 由 Eric Young ([email protected]) 撰寫的加解密軟體, 以及由 Thomas Bernard 所撰寫的 UPnP 軟體.</translation> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation>版權</translation> </message> <message> <location line="+0"/> <source>The GulfCoin developers</source> <translation>位元幣開發人員</translation> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>位址簿</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>點兩下來修改位址或標記</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>產生新位址</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>複製目前選取的位址到系統剪貼簿</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation>新增位址</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your GulfCoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation>這些是你用來收款的位元幣位址. 你可以提供不同的位址給不同的付款人, 來追蹤是誰支付給你.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation>複製位址</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation>顯示 &amp;QR 條碼</translation> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a GulfCoin address</source> <translation>簽署訊息是用來證明位元幣位址是你的</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>訊息簽署</translation> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation>從列表中刪除目前選取的位址</translation> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation>將目前分頁的資料匯出存成檔案</translation> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation>匯出</translation> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified GulfCoin address</source> <translation>驗證訊息是用來確認訊息是用指定的位元幣位址簽署的</translation> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation>訊息驗證</translation> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>刪除</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your GulfCoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation>這是你用來付款的位元幣位址. 在付錢之前, 務必要檢查金額和收款位址是否正確.</translation> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation>複製標記</translation> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation>編輯</translation> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation>付錢</translation> </message> <message> <location line="+265"/> <source>Export Address Book Data</source> <translation>匯出位址簿資料</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>逗號區隔資料檔 (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>匯出失敗</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>無法寫入檔案 %1.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>標記</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>位址</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(沒有標記)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation>密碼對話視窗</translation> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>輸入密碼</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>新的密碼</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>重複新密碼</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+33"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>輸入錢包的新密碼.&lt;br/&gt;請用&lt;b&gt;10個以上的字元&lt;/b&gt;, 或是&lt;b&gt;8個以上的單字&lt;/b&gt;.</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>錢包加密</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>這個動作需要用你的錢包密碼來解鎖</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>錢包解鎖</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>這個動作需要用你的錢包密碼來解密</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>錢包解密</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>變更密碼</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>輸入錢包的新舊密碼.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>錢包加密確認</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR BITCOINS&lt;/b&gt;!</source> <translation>警告: 如果將錢包加密後忘記密碼, 你會&lt;b&gt;失去其中所有的位元幣&lt;/b&gt;!</translation> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>你確定要將錢包加密嗎?</translation> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation>重要: 請改用新產生有加密的錢包檔, 來取代之前錢包檔的備份. 為了安全性的理由, 當你開始使用新的有加密的錢包時, 舊錢包的備份就不能再使用了.</translation> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation>警告: 大寫字母鎖定作用中!</translation> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>錢包已加密</translation> </message> <message> <location line="-56"/> <source>GulfCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your gulfcoins from being stolen by malware infecting your computer.</source> <translation>位元幣現在要關閉以完成加密程序. 請記住, 加密錢包無法完全防止入侵電腦的惡意程式偷取你的位元幣.</translation> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>錢包加密失敗</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>錢包加密因程式內部錯誤而失敗. 你的錢包還是沒有加密.</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>提供的密碼不符.</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>錢包解鎖失敗</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>用來解密錢包的密碼輸入錯誤.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>錢包解密失敗</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>錢包密碼變更成功.</translation> </message> </context> <context> <name>GulfCoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+254"/> <source>Sign &amp;message...</source> <translation>訊息簽署...</translation> </message> <message> <location line="+246"/> <source>Synchronizing with network...</source> <translation>網路同步中...</translation> </message> <message> <location line="-321"/> <source>&amp;Overview</source> <translation>總覽</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>顯示錢包一般總覽</translation> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>交易</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>瀏覽交易紀錄</translation> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels</source> <translation>編輯位址與標記的儲存列表</translation> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation>顯示收款位址的列表</translation> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation>結束</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>結束應用程式</translation> </message> <message> <location line="+7"/> <source>Show information about GulfCoin</source> <translation>顯示位元幣相關資訊</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>關於 &amp;Qt</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>顯示有關於 Qt 的資訊</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>選項...</translation> </message> <message> <location line="+9"/> <source>&amp;Encrypt Wallet...</source> <translation>錢包加密...</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>錢包備份...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>密碼變更...</translation> </message> <message> <location line="+251"/> <source>Importing blocks from disk...</source> <translation>從磁碟匯入區塊中...</translation> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation>重建磁碟區塊索引中...</translation> </message> <message> <location line="-319"/> <source>Send coins to a GulfCoin address</source> <translation>付錢到位元幣位址</translation> </message> <message> <location line="+52"/> <source>Modify configuration options for GulfCoin</source> <translation>修改位元幣的設定選項</translation> </message> <message> <location line="+12"/> <source>Backup wallet to another location</source> <translation>將錢包備份到其它地方</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>變更錢包加密用的密碼</translation> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation>除錯視窗</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>開啓除錯與診斷主控台</translation> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation>驗證訊息...</translation> </message> <message> <location line="-183"/> <location line="+6"/> <location line="+508"/> <source>GulfCoin</source> <translation>位元幣</translation> </message> <message> <location line="-514"/> <location line="+6"/> <source>Wallet</source> <translation>錢包</translation> </message> <message> <location line="+107"/> <source>&amp;Send</source> <translation>付出</translation> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation>收受</translation> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation>位址</translation> </message> <message> <location line="+23"/> <location line="+2"/> <source>&amp;About GulfCoin</source> <translation>關於位元幣</translation> </message> <message> <location line="+10"/> <location line="+2"/> <source>&amp;Show / Hide</source> <translation>顯示或隱藏</translation> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation>顯示或隱藏主視窗</translation> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation>將屬於你的錢包的密鑰加密</translation> </message> <message> <location line="+7"/> <source>Sign messages with your GulfCoin addresses to prove you own them</source> <translation>用位元幣位址簽署訊息來證明那是你的</translation> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified GulfCoin addresses</source> <translation>驗證訊息來確認是用指定的位元幣位址簽署的</translation> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation>檔案</translation> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation>設定</translation> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation>求助</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>分頁工具列</translation> </message> <message> <location line="-228"/> <location line="+288"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> <message> <location line="-5"/> <location line="+5"/> <source>GulfCoin client</source> <translation>位元幣客戶端軟體</translation> </message> <message numerus="yes"> <location line="+121"/> <source>%n active connection(s) to GulfCoin network</source> <translation><numerusform>與位元幣網路有 %n 個連線在使用中</numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation>目前沒有區塊來源...</translation> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation>已處理了估計全部 %2 個中的 %1 個區塊的交易紀錄.</translation> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation>已處理了 %1 個區塊的交易紀錄.</translation> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation><numerusform>%n 個小時</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation><numerusform>%n 天</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation><numerusform>%n 個星期</numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation>落後 %1</translation> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation>最近收到的區塊是在 %1 之前生產出來.</translation> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation>會看不見在這之後的交易.</translation> </message> <message> <location line="+22"/> <source>Error</source> <translation>錯誤</translation> </message> <message> <location line="+3"/> <source>Warning</source> <translation>警告</translation> </message> <message> <location line="+3"/> <source>Information</source> <translation>資訊</translation> </message> <message> <location line="+70"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation>這筆交易的資料大小超過限制了. 你還是可以付出 %1 的費用來傳送, 這筆費用會付給處理你的交易的節點, 並幫助維持整個網路. 你願意支付這項費用嗎?</translation> </message> <message> <location line="-140"/> <source>Up to date</source> <translation>最新狀態</translation> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation>進度追趕中...</translation> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation>確認交易手續費</translation> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation>付款交易</translation> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation>收款交易</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>日期: %1 金額: %2 類別: %3 位址: %4</translation> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation>URI 處理</translation> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid GulfCoin address or malformed URI parameters.</source> <translation>無法解析 URI! 也許位元幣位址無效或 URI 參數有誤.</translation> </message> <message> <location line="+17"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>錢包&lt;b&gt;已加密&lt;/b&gt;並且正&lt;b&gt;解鎖中&lt;/b&gt;</translation> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>錢包&lt;b&gt;已加密&lt;/b&gt;並且正&lt;b&gt;上鎖中&lt;/b&gt;</translation> </message> <message> <location filename="../bitcoin.cpp" line="+110"/> <source>A fatal error occurred. GulfCoin can no longer continue safely and will quit.</source> <translation>發生了致命的錯誤. 位元幣程式無法再繼續安全執行, 只好結束.</translation> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+105"/> <source>Network Alert</source> <translation>網路警報</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>編輯位址</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>標記</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation>與這個位址簿項目關聯的標記</translation> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>位址</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation>與這個位址簿項目關聯的位址. 付款位址才能被更改.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation>新收款位址</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>新增付款位址</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>編輯收款位址</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>編輯付款位址</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>輸入的位址&quot;%1&quot;已存在於位址簿中.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid GulfCoin address.</source> <translation>輸入的位址 &quot;%1&quot; 並不是有效的位元幣位址.</translation> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>無法將錢包解鎖.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>新密鑰產生失敗.</translation> </message> </context> <context> <name>FreespaceChecker</name> <message> <location filename="../intro.cpp" line="+61"/> <source>A new data directory will be created.</source> <translation>將會建立新的資料目錄.</translation> </message> <message> <location line="+22"/> <source>name</source> <translation>名稱</translation> </message> <message> <location line="+2"/> <source>Directory already exists. Add %1 if you intend to create a new directory here.</source> <translation>目錄已經存在了. 如果你要在裡面建立新目錄的話, 請加上 %1.</translation> </message> <message> <location line="+3"/> <source>Path already exists, and is not a directory.</source> <translation>已經存在該路徑了, 並且不是一個目錄.</translation> </message> <message> <location line="+7"/> <source>Cannot create data directory here.</source> <translation>無法在這裡新增資料目錄</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+517"/> <location line="+13"/> <source>GulfCoin-Qt</source> <translation>位元幣-Qt</translation> </message> <message> <location line="-13"/> <source>version</source> <translation>版本</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>用法:</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation>命令列選項</translation> </message> <message> <location line="+4"/> <source>UI options</source> <translation>使用界面選項</translation> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation>設定語言, 比如說 &quot;de_DE&quot; (預設: 系統語系)</translation> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation>啓動時最小化 </translation> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation>顯示啓動畫面 (預設: 1)</translation> </message> <message> <location line="+1"/> <source>Choose data directory on startup (default: 0)</source> <translation>啓動時選擇資料目錄 (預設值: 0)</translation> </message> </context> <context> <name>Intro</name> <message> <location filename="../forms/intro.ui" line="+14"/> <source>Welcome</source> <translation>歡迎</translation> </message> <message> <location line="+9"/> <source>Welcome to GulfCoin-Qt.</source> <translation>歡迎使用&quot;位元幣-Qt&quot;</translation> </message> <message> <location line="+26"/> <source>As this is the first time the program is launched, you can choose where GulfCoin-Qt will store its data.</source> <translation>由於這是程式第一次啓動, 你可以選擇&quot;位元幣-Qt&quot;儲存資料的地方.</translation> </message> <message> <location line="+10"/> <source>GulfCoin-Qt will download and store a copy of the GulfCoin block chain. At least %1GB of data will be stored in this directory, and it will grow over time. The wallet will also be stored in this directory.</source> <translation>位元幣-Qt 會下載並儲存一份位元幣區塊鏈結的拷貝. 至少有 %1GB 的資料會儲存到這個目錄中, 並且還會持續增長. 另外錢包資料也會儲存在這個目錄.</translation> </message> <message> <location line="+10"/> <source>Use the default data directory</source> <translation>用預設的資料目錄</translation> </message> <message> <location line="+7"/> <source>Use a custom data directory:</source> <translation>用自定的資料目錄:</translation> </message> <message> <location filename="../intro.cpp" line="+100"/> <source>Error</source> <translation>錯誤</translation> </message> <message> <location line="+9"/> <source>GB of free space available</source> <translation>GB 可用空間</translation> </message> <message> <location line="+3"/> <source>(of %1GB needed)</source> <translation>(需要 %1GB)</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>選項</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>主要</translation> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation>非必要的交易手續費, 以 kB 為計費單位, 且有助於縮短你的交易處理時間. 大部份交易資料的大小是 1 kB.</translation> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>付交易手續費</translation> </message> <message> <location line="+31"/> <source>Automatically start GulfCoin after logging in to the system.</source> <translation>在登入系統後自動啓動位元幣.</translation> </message> <message> <location line="+3"/> <source>&amp;Start GulfCoin on system login</source> <translation>系統登入時啟動位元幣</translation> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation>回復所有客戶端軟體選項成預設值.</translation> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation>選項回復</translation> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation>網路</translation> </message> <message> <location line="+6"/> <source>Automatically open the GulfCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>自動在路由器上開啟 GulfCoin 的客戶端通訊埠. 只有在你的路由器支援 UPnP 且開啟時才有作用.</translation> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>用 &amp;UPnP 設定通訊埠對應</translation> </message> <message> <location line="+7"/> <source>Connect to the GulfCoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation>透過 SOCKS 代理伺服器連線至位元幣網路 (比如說要透過 Tor 連線).</translation> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation>透過 SOCKS 代理伺服器連線:</translation> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation>代理伺服器位址:</translation> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation>代理伺服器的網際網路位址 (比如說 127.0.0.1)</translation> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation>通訊埠:</translation> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation>代理伺服器的通訊埠 (比如說 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation>SOCKS 協定版本:</translation> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation>代理伺服器的 SOCKS 協定版本 (比如說 5)</translation> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation>視窗</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>最小化視窗後只在通知區域顯示圖示</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>最小化至通知區域而非工作列</translation> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation>當視窗關閉時將其最小化, 而非結束應用程式. 當勾選這個選項時, 應用程式只能用選單中的結束來停止執行.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>關閉時最小化</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>顯示</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>使用界面語言</translation> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting GulfCoin.</source> <translation>可以在這裡設定使用者介面的語言. 這個設定在位元幣程式重啓後才會生效.</translation> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>金額顯示單位:</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>選擇操作界面與付錢時預設顯示的細分單位.</translation> </message> <message> <location line="+9"/> <source>Whether to show GulfCoin addresses in the transaction list or not.</source> <translation>是否要在交易列表中顯示位元幣位址.</translation> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation>在交易列表顯示位址</translation> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>好</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>取消</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation>套用</translation> </message> <message> <location filename="../optionsdialog.cpp" line="+54"/> <source>default</source> <translation>預設</translation> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation>確認回復選項</translation> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation>有些設定可能需要重新啓動客戶端軟體才會生效.</translation> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation>你想要就做下去嗎?</translation> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation>警告</translation> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting GulfCoin.</source> <translation>這個設定會在位元幣程式重啓後生效.</translation> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation>提供的代理伺服器位址無效</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>表單</translation> </message> <message> <location line="+50"/> <location line="+202"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the GulfCoin network after a connection is established, but this process has not completed yet.</source> <translation>顯示的資訊可能是過期的. 與位元幣網路的連線建立後, 你的錢包會自動和網路同步, 但這個步驟還沒完成.</translation> </message> <message> <location line="-131"/> <source>Unconfirmed:</source> <translation>未確認金額:</translation> </message> <message> <location line="-78"/> <source>Wallet</source> <translation>錢包</translation> </message> <message> <location line="+49"/> <source>Confirmed:</source> <translation>已確認金額:</translation> </message> <message> <location line="+16"/> <source>Your current spendable balance</source> <translation>目前可用餘額</translation> </message> <message> <location line="+29"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the spendable balance</source> <translation>尚未確認的交易的總金額, 可用餘額不包含此金額</translation> </message> <message> <location line="+13"/> <source>Immature:</source> <translation>未熟成</translation> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation>尚未熟成的開採金額</translation> </message> <message> <location line="+13"/> <source>Total:</source> <translation>總金額:</translation> </message> <message> <location line="+16"/> <source>Your current total balance</source> <translation>目前全部餘額</translation> </message> <message> <location line="+53"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;最近交易&lt;/b&gt;</translation> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation>沒同步</translation> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+108"/> <source>Cannot start gulfcoin: click-to-pay handler</source> <translation>無法啟動 gulfcoin 隨按隨付處理器</translation> </message> </context> <context> <name>QObject</name> <message> <location filename="../bitcoin.cpp" line="+92"/> <location filename="../intro.cpp" line="-32"/> <source>GulfCoin</source> <translation>位元幣</translation> </message> <message> <location line="+1"/> <source>Error: Specified data directory &quot;%1&quot; does not exist.</source> <translation>錯誤: 不存在指定的資料目錄 &quot;%1&quot;.</translation> </message> <message> <location filename="../intro.cpp" line="+1"/> <source>Error: Specified data directory &quot;%1&quot; can not be created.</source> <translation>錯誤: 無法新增指定的資料目錄 &quot;%1&quot;.</translation> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation>QR 條碼對話視窗</translation> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation>付款單</translation> </message> <message> <location line="+56"/> <source>Amount:</source> <translation>金額:</translation> </message> <message> <location line="-44"/> <source>Label:</source> <translation>標記:</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation>訊息:</translation> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation>儲存為...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="+64"/> <source>Error encoding URI into QR Code.</source> <translation>將 URI 編碼成 QR 條碼失敗</translation> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation>輸入的金額無效, 請檢查看看.</translation> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>造出的網址太長了,請把標籤或訊息的文字縮短再試看看.</translation> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation>儲存 QR 條碼</translation> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation>PNG 圖檔 (*.png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>客戶端軟體名稱</translation> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+345"/> <source>N/A</source> <translation>無</translation> </message> <message> <location line="-217"/> <source>Client version</source> <translation>客戶端軟體版本</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>資訊</translation> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation>使用 OpenSSL 版本</translation> </message> <message> <location line="+49"/> <source>Startup time</source> <translation>啓動時間</translation> </message> <message> <location line="+29"/> <source>Network</source> <translation>網路</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>連線數</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation>位於測試網路</translation> </message> <message> <location line="+23"/> <source>Block chain</source> <translation>區塊鎖鏈</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>目前區塊數</translation> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation>估算總區塊數</translation> </message> <message> <location line="+23"/> <source>Last block time</source> <translation>最近區塊時間</translation> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>開啓</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation>命令列選項</translation> </message> <message> <location line="+7"/> <source>Show the GulfCoin-Qt help message to get a list with possible GulfCoin command-line options.</source> <translation>顯示&quot;位元幣-Qt&quot;的求助訊息, 來取得可用的命令列選項列表.</translation> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation>顯示</translation> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>主控台</translation> </message> <message> <location line="-260"/> <source>Build date</source> <translation>建置日期</translation> </message> <message> <location line="-104"/> <source>GulfCoin - Debug window</source> <translation>位元幣 - 除錯視窗</translation> </message> <message> <location line="+25"/> <source>GulfCoin Core</source> <translation>位元幣核心</translation> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation>除錯紀錄檔</translation> </message> <message> <location line="+7"/> <source>Open the GulfCoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation>從目前的資料目錄下開啓位元幣的除錯紀錄檔. 當紀錄檔很大時可能要花好幾秒的時間.</translation> </message> <message> <location line="+102"/> <source>Clear console</source> <translation>清主控台</translation> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the GulfCoin RPC console.</source> <translation>歡迎使用位元幣 RPC 主控台.</translation> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation>請用上下游標鍵來瀏覽歷史指令, 且可用 &lt;b&gt;Ctrl-L&lt;/b&gt; 來清理畫面.</translation> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>請打 &lt;b&gt;help&lt;/b&gt; 來看可用指令的簡介.</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+128"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>付錢</translation> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation>一次付給多個人</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>加收款人</translation> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation>移除所有交易欄位</translation> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>全部清掉</translation> </message> <message> <location line="+22"/> <source>Balance:</source> <translation>餘額:</translation> </message> <message> <location line="+10"/> <source>123.456 ABC</source> <translation>123.456 ABC</translation> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>確認付款動作</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>付出</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-62"/> <location line="+2"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt; 給 %2 (%3)</translation> </message> <message> <location line="+6"/> <source>Confirm send coins</source> <translation>確認要付錢</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation>確定要付出 %1 嗎?</translation> </message> <message> <location line="+0"/> <source> and </source> <translation>和</translation> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation>無效的收款位址, 請再檢查看看.</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>付款金額必須大於 0.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>金額超過餘額了.</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>包含 %1 的交易手續費後, 總金額超過你的餘額了.</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>發現有重複的位址. 每個付款動作中, 只能付給個別的位址一次.</translation> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation>錯誤: 交易產生失敗!</translation> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>錯誤: 交易被拒絕. 有時候會發生這種錯誤, 是因為你錢包中的一些錢已經被花掉了. 比如說你複製了錢包檔 wallet.dat, 然後用複製的錢包花掉了錢, 你現在所用的原來的錢包中卻沒有該筆交易紀錄.</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation>表單</translation> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>金額:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>付給:</translation> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>付款的目標位址 (比如說 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation>輸入一個標記給這個位址, 並加到位址簿中</translation> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>標記:</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation>從位址簿中選一個位址</translation> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>從剪貼簿貼上位址</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation>去掉這個收款人</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a GulfCoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>輸入位元幣位址 (比如說 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation>簽章 - 簽署或驗證訊息</translation> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation>訊息簽署</translation> </message> <message> <location line="+6"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation>你可以用自己的位址來簽署訊息, 以證明你對它的所有權. 但是請小心, 不要簽署語意含糊不清的內容, 因為釣魚式詐騙可能會用騙你簽署的手法來冒充是你. 只有在語句中的細節你都同意時才簽署.</translation> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>用來簽署訊息的位址 (比如說 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation>從位址簿選一個位址</translation> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation>從剪貼簿貼上位址</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation>在這裡輸入你想簽署的訊息</translation> </message> <message> <location line="+7"/> <source>Signature</source> <translation>簽章</translation> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation>複製目前的簽章到系統剪貼簿</translation> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this GulfCoin address</source> <translation>簽署訊息是用來證明這個位元幣位址是你的</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>訊息簽署</translation> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation>重置所有訊息簽署欄位</translation> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>全部清掉</translation> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation>訊息驗證</translation> </message> <message> <location line="+6"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation>請在下面輸入簽署的位址, 訊息(請確認完整複製了所包含的換行, 空格, 跳位符號等等), 與簽章, 以驗證該訊息. 請小心, 除了訊息內容外, 不要對簽章本身過度解讀, 以避免被用&quot;中間人攻擊法&quot;詐騙.</translation> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>簽署該訊息的位址 (比如說 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified GulfCoin address</source> <translation>驗證訊息是用來確認訊息是用指定的位元幣位址簽署的</translation> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation>訊息驗證</translation> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation>重置所有訊息驗證欄位</translation> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a GulfCoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>輸入位元幣位址 (比如說 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>按&quot;訊息簽署&quot;來產生簽章</translation> </message> <message> <location line="+3"/> <source>Enter GulfCoin signature</source> <translation>輸入位元幣簽章</translation> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation>輸入的位址無效.</translation> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation>請檢查位址是否正確後再試一次.</translation> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation>輸入的位址沒有指到任何密鑰.</translation> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation>錢包解鎖已取消.</translation> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation>沒有所輸入位址的密鑰.</translation> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation>訊息簽署失敗.</translation> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation>訊息已簽署.</translation> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation>無法將這個簽章解碼.</translation> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation>請檢查簽章是否正確後再試一次.</translation> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation>這個簽章與訊息的數位摘要不符.</translation> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation>訊息驗證失敗.</translation> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation>訊息已驗證.</translation> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>The GulfCoin developers</source> <translation>位元幣開發人員</translation> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation>在 %1 前未定</translation> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation>%1/離線中</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/未確認</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>經確認 %1 次</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation>狀態</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation><numerusform>, 已公告至 %n 個節點</numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>日期</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation>來源</translation> </message> <message> <location line="+0"/> <source>Generated</source> <translation>生產出</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>來處</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>目的</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation>自己的位址</translation> </message> <message> <location line="-2"/> <source>label</source> <translation>標籤</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>入帳</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation><numerusform>將在 %n 個區塊產出後熟成</numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>不被接受</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>出帳</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>交易手續費</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>淨額</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>訊息</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>附註</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>交易識別碼</translation> </message> <message> <location line="+3"/> <source>Generated coins must mature 1 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation>生產出來的錢要再等 1 個區塊熟成之後, 才能夠花用. 當你產出區塊時, 它會被公布到網路上, 以被串連至區塊鎖鏈. 如果串連失敗了, 它的狀態就會變成&quot;不被接受&quot;, 且不能被花用. 當你產出區塊的幾秒鐘內, 也有其他節點產出區塊的話, 有時候就會發生這種情形.</translation> </message> <message> <location line="+7"/> <source>Debug information</source> <translation>除錯資訊</translation> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>交易</translation> </message> <message> <location line="+3"/> <source>Inputs</source> <translation>輸入</translation> </message> <message> <location line="+23"/> <source>Amount</source> <translation>金額</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>是</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>否</translation> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation>, 尚未成功公告出去</translation> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation><numerusform>在接下來 %n 個區塊產出前未定</numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation>未知</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>交易明細</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>此版面顯示交易的詳細說明</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+225"/> <source>Date</source> <translation>日期</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>種類</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>位址</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>金額</translation> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation><numerusform>在接下來 %n 個區塊產出前未定</numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation>在 %1 前未定</translation> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation>離線中 (經確認 %1 次)</translation> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>未確認 (經確認 %1 次, 應確認 %2 次)</translation> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation>已確認 (經確認 %1 次)</translation> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation><numerusform>開採金額將可在 %n 個區塊熟成後可用</numerusform></translation> </message> <message> <location line="+5"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>沒有其他節點收到這個區塊, 也許它不被接受!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>生產出但不被接受</translation> </message> <message> <location line="+43"/> <source>Received with</source> <translation>收受於</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>收受自</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>付出至</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>付給自己</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>開採所得</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(不適用)</translation> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>交易狀態. 移動游標至欄位上方來顯示確認次數.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>收到交易的日期與時間.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>交易的種類.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>交易的目標位址.</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>減去或加入至餘額的金額</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation>全部</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>今天</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>這週</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>這個月</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>上個月</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>今年</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>指定範圍...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>收受於</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>付出至</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>給自己</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>開採所得</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>其他</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>輸入位址或標記來搜尋</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>最小金額</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>複製位址</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>複製標記</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>複製金額</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation>複製交易識別碼</translation> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>編輯標記</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation>顯示交易明細</translation> </message> <message> <location line="+143"/> <source>Export Transaction Data</source> <translation>匯出交易資料</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>逗號分隔資料檔 (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>已確認</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>日期</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>種類</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>標記</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>位址</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>金額</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>識別碼</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>匯出失敗</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>無法寫入至 %1 檔案.</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation>範圍:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>至</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation>付錢</translation> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+46"/> <source>&amp;Export</source> <translation>匯出</translation> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation>將目前分頁的資料匯出存成檔案</translation> </message> <message> <location line="+197"/> <source>Backup Wallet</source> <translation>錢包備份</translation> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation>錢包資料檔 (*.dat)</translation> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation>備份失敗</translation> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation>儲存錢包資料到新的地方失敗</translation> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation>備份成功</translation> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation>錢包的資料已經成功儲存到新的地方了.</translation> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+98"/> <source>GulfCoin version</source> <translation>位元幣版本</translation> </message> <message> <location line="+104"/> <source>Usage:</source> <translation>用法:</translation> </message> <message> <location line="-30"/> <source>Send command to -server or gulfcoind</source> <translation>送指令給 -server 或 gulfcoind </translation> </message> <message> <location line="-23"/> <source>List commands</source> <translation>列出指令 </translation> </message> <message> <location line="-13"/> <source>Get help for a command</source> <translation>取得指令說明 </translation> </message> <message> <location line="+25"/> <source>Options:</source> <translation>選項: </translation> </message> <message> <location line="+24"/> <source>Specify configuration file (default: gulfcoin.conf)</source> <translation>指定設定檔 (預設: gulfcoin.conf) </translation> </message> <message> <location line="+3"/> <source>Specify pid file (default: gulfcoind.pid)</source> <translation>指定行程識別碼檔案 (預設: gulfcoind.pid) </translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>指定資料目錄 </translation> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>設定資料庫快取大小為多少百萬位元組(MB, 預設: 25)</translation> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 12401 or testnet: 22401)</source> <translation>在通訊埠 &lt;port&gt; 聽候連線 (預設: 12401, 或若為測試網路: 22401)</translation> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>維持與節點連線數的上限為 &lt;n&gt; 個 (預設: 125)</translation> </message> <message> <location line="-49"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>連線到某個節點以取得其它節點的位址, 然後斷線</translation> </message> <message> <location line="+84"/> <source>Specify your own public address</source> <translation>指定自己公開的位址</translation> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>與亂搞的節點斷線的臨界值 (預設: 100)</translation> </message> <message> <location line="-136"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>避免與亂搞的節點連線的秒數 (預設: 86400)</translation> </message> <message> <location line="-33"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation>在 IPv4 網路上以通訊埠 %u 聽取 RPC 連線時發生錯誤: %s</translation> </message> <message> <location line="+31"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 12402 or testnet: 22402)</source> <translation>在通訊埠 &lt;port&gt; 聽候 JSON-RPC 連線 (預設: 12402, 或若為測試網路: 22402)</translation> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation>接受命令列與 JSON-RPC 指令 </translation> </message> <message> <location line="+77"/> <source>Run in the background as a daemon and accept commands</source> <translation>以背景程式執行並接受指令</translation> </message> <message> <location line="+38"/> <source>Use the test network</source> <translation>使用測試網路 </translation> </message> <message> <location line="-114"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation>是否接受外來連線 (預設: 當沒有 -proxy 或 -connect 時預設為 1)</translation> </message> <message> <location line="-84"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=gulfcoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;GulfCoin Alert&quot; [email protected] </source> <translation>%s, 你必須要在以下設定檔中設定 RPC 密碼(rpcpassword): %s 建議你使用以下隨機產生的密碼: rpcuser=gulfcoinrpc rpcpassword=%s (你不用記住這個密碼) 使用者名稱(rpcuser)和密碼(rpcpassword)不可以相同! 如果設定檔還不存在, 請在新增時, 設定檔案權限為&quot;只有主人才能讀取&quot;. 也建議你設定警示通知, 發生問題時你才會被通知到; 比如說設定為: alertnotify=echo %%s | mail -s &quot;GulfCoin Alert&quot; [email protected] </translation> </message> <message> <location line="+17"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation>設定在 IPv6 網路的通訊埠 %u 上聽候 RPC 連線失敗, 退而改用 IPv4 網路: %s</translation> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation>和指定的位址繫結, 並總是在該位址聽候連線. IPv6 請用 &quot;[主機]:通訊埠&quot; 這種格式</translation> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. GulfCoin is probably already running.</source> <translation>無法鎖定資料目錄 %s. 也許位元幣已經在執行了.</translation> </message> <message> <location line="+3"/> <source>Enter regression test mode, which uses a special chain in which blocks can be solved instantly. This is intended for regression testing tools and app development.</source> <translation>進入回歸測試模式, 特別的區塊鎖鏈使用中, 可以立即解出區塊. 目的是用來做回歸測試, 以及配合應用程式的開發.</translation> </message> <message> <location line="+4"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>錯誤: 交易被拒絕了! 有時候會發生這種錯誤, 是因為你錢包中的一些錢已經被花掉了. 比如說你複製了錢包檔 wallet.dat, 然後用複製的錢包花掉了錢, 你現在所用的原來的錢包中卻沒有該筆交易紀錄.</translation> </message> <message> <location line="+4"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation>錯誤: 這筆交易需要至少 %s 的手續費! 因為它的金額太大, 或複雜度太高, 或是使用了最近才剛收到的款項.</translation> </message> <message> <location line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation>當收到相關警示時所要執行的指令 (指令中的 %s 會被取代為警示訊息)</translation> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation>當錢包有交易改變時所要執行的指令 (指令中的 %s 會被取代為交易識別碼)</translation> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation>設定高優先權或低手續費的交易資料大小上限為多少位元組 (預設: 27000)</translation> </message> <message> <location line="+6"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation>這是尚未發表的測試版本 - 使用請自負風險 - 請不要用於開採或商業應用</translation> </message> <message> <location line="+5"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>警告: -paytxfee 設定了很高的金額! 這可是你交易付款所要付的手續費.</translation> </message> <message> <location line="+3"/> <source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source> <translation>警告: 顯示的交易可能不正確! 你可能需要升級, 或者需要等其它的節點升級.</translation> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong GulfCoin will not work properly.</source> <translation>警告: 請檢查電腦時間與日期是否正確! 位元幣無法在時鐘不準的情況下正常運作.</translation> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation>警告: 讀取錢包檔 wallet.dat 失敗了! 所有的密鑰都正確讀取了, 但是交易資料或位址簿資料可能會缺少或不正確.</translation> </message> <message> <location line="+3"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation>警告: 錢包檔 wallet.dat 壞掉, 但資料被拯救回來了! 原來的 wallet.dat 會改儲存在 %s, 檔名為 wallet.{timestamp}.bak. 如果餘額或交易資料有誤, 你應該要用備份資料復原回來.</translation> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation>嘗試從壞掉的錢包檔 wallet.dat 復原密鑰</translation> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation>區塊產生選項:</translation> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation>只連線至指定節點(可多個)</translation> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation>發現區塊資料庫壞掉了</translation> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation>找出自己的網際網路位址 (預設: 當有聽候連線且沒有 -externalip 時為 1)</translation> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation>你要現在重建區塊資料庫嗎?</translation> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation>初始化區塊資料庫失敗</translation> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation>錢包資料庫環境 %s 初始化錯誤!</translation> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation>載入區塊資料庫失敗</translation> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation>打開區塊資料庫檔案失敗</translation> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation>錯誤: 磁碟空間很少!</translation> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation>錯誤: 錢包被上鎖了, 無法產生新的交易!</translation> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation>錯誤: 系統錯誤:</translation> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation>在任意的通訊埠聽候失敗. 如果你想的話可以用 -listen=0.</translation> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation>讀取區塊資訊失敗</translation> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation>讀取區塊失敗</translation> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation>同步區塊索引失敗</translation> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation>寫入區塊索引失敗</translation> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation>寫入區塊資訊失敗</translation> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation>寫入區塊失敗</translation> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation>寫入檔案資訊失敗</translation> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation>寫入位元幣資料庫失敗</translation> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation>寫入交易索引失敗</translation> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation>寫入回復資料失敗</translation> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation>是否允許在找節點時使用域名查詢 (預設: 當沒用 -connect 時為 1)</translation> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation>生產位元幣 (預設值: 0)</translation> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation>啓動時檢查的區塊數 (預設: 288, 指定 0 表示全部)</translation> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation>區塊檢查的仔細程度 (0 至 4, 預設: 3)</translation> </message> <message> <location line="+2"/> <source>Incorrect or no genesis block found. Wrong datadir for network?</source> <translation>創世區塊不正確或找不到. 資料目錄錯了嗎?</translation> </message> <message> <location line="+18"/> <source>Not enough file descriptors available.</source> <translation>檔案描述器不足.</translation> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation>從目前的區塊檔 blk000??.dat 重建鎖鏈索引</translation> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation>設定處理 RPC 服務請求的執行緒數目 (預設為 4)</translation> </message> <message> <location line="+7"/> <source>Specify wallet file (within data directory)</source> <translation>指定錢包檔(會在資料目錄中)</translation> </message> <message> <location line="+20"/> <source>Verifying blocks...</source> <translation>驗證區塊資料中...</translation> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation>驗證錢包資料中...</translation> </message> <message> <location line="+1"/> <source>Wallet %s resides outside data directory %s</source> <translation>錢包檔 %s 沒有在資料目錄 %s 裡面</translation> </message> <message> <location line="+4"/> <source>You need to rebuild the database using -reindex to change -txindex</source> <translation>改變 -txindex 參數後, 必須要用 -reindex 參數來重建資料庫</translation> </message> <message> <location line="-76"/> <source>Imports blocks from external blk000??.dat file</source> <translation>從其它來源的 blk000??.dat 檔匯入區塊</translation> </message> <message> <location line="-76"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation>設定指令碼驗證的執行緒數目 (最多為 16, 若為 0 表示程式自動決定, 小於 0 表示保留不用的處理器核心數目, 預設為 0)</translation> </message> <message> <location line="+78"/> <source>Information</source> <translation>資訊</translation> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation>無效的 -tor 位址: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>設定 -minrelaytxfee=&lt;金額&gt; 的金額無效: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>設定 -mintxfee=&lt;amount&gt; 的金額無效: &apos;%s&apos;</translation> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation>維護全部交易的索引 (預設為 0)</translation> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation>每個連線的接收緩衝區大小上限為 &lt;n&gt;*1000 個位元組 (預設: 5000)</translation> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation>每個連線的傳送緩衝區大小上限為 &lt;n&gt;*1000 位元組 (預設: 1000)</translation> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation>只接受與內建的檢查段點吻合的區塊鎖鏈 (預設: 1)</translation> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation>只和 &lt;net&gt; 網路上的節點連線 (IPv4, IPv6, 或 Tor)</translation> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation>輸出額外的除錯資訊. 包含了其它所有的 -debug* 選項</translation> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation>輸出額外的網路除錯資訊</translation> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation>在除錯輸出內容前附加時間</translation> </message> <message> <location line="+5"/> <source>SSL options: (see the GulfCoin Wiki for SSL setup instructions)</source> <translation>SSL 選項: (SSL 設定程序請見 GulfCoin Wiki)</translation> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation>選擇 SOCKS 代理伺服器的協定版本(4 或 5, 預設: 5)</translation> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>在終端機顯示追蹤或除錯資訊, 而非寫到 debug.log 檔</translation> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation>輸出追蹤或除錯資訊給除錯器</translation> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation>設定區塊大小上限為多少位元組 (預設: 250000)</translation> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation>設定區塊大小下限為多少位元組 (預設: 0)</translation> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>客戶端軟體啓動時將 debug.log 檔縮小 (預設: 當沒有 -debug 時為 1)</translation> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation>簽署交易失敗</translation> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>指定連線在幾毫秒後逾時 (預設: 5000)</translation> </message> <message> <location line="+5"/> <source>System error: </source> <translation>系統錯誤:</translation> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation>交易金額太小</translation> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation>交易金額必須是正的</translation> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation>交易位元量太大</translation> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation>是否使用通用即插即用(UPnP)協定來設定聽候連線的通訊埠 (預設: 0)</translation> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>是否使用通用即插即用(UPnP)協定來設定聽候連線的通訊埠 (預設: 當有聽候連線為 1)</translation> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation>透過代理伺服器來使用 Tor 隱藏服務 (預設: 同 -proxy)</translation> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation>JSON-RPC 連線使用者名稱</translation> </message> <message> <location line="+5"/> <source>Warning</source> <translation>警告</translation> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation>警告: 這個版本已經被淘汰掉了, 必須要升級!</translation> </message> <message> <location line="+2"/> <source>wallet.dat corrupt, salvage failed</source> <translation>錢包檔 weallet.dat 壞掉了, 拯救失敗</translation> </message> <message> <location line="-52"/> <source>Password for JSON-RPC connections</source> <translation>JSON-RPC 連線密碼</translation> </message> <message> <location line="-68"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>只允許從指定網路位址來的 JSON-RPC 連線</translation> </message> <message> <location line="+77"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>送指令給在 &lt;ip&gt; 的節點 (預設: 127.0.0.1) </translation> </message> <message> <location line="-121"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>當最新區塊改變時所要執行的指令 (指令中的 %s 會被取代為區塊的雜湊值)</translation> </message> <message> <location line="+149"/> <source>Upgrade wallet to latest format</source> <translation>將錢包升級成最新的格式</translation> </message> <message> <location line="-22"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>設定密鑰池大小為 &lt;n&gt; (預設: 100) </translation> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>重新掃描區塊鎖鏈, 以尋找錢包所遺漏的交易.</translation> </message> <message> <location line="+36"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>於 JSON-RPC 連線使用 OpenSSL (https) </translation> </message> <message> <location line="-27"/> <source>Server certificate file (default: server.cert)</source> <translation>伺服器憑證檔 (預設: server.cert) </translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>伺服器密鑰檔 (預設: server.pem) </translation> </message> <message> <location line="-156"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>可以接受的加密法 (預設: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH) </translation> </message> <message> <location line="+171"/> <source>This help message</source> <translation>此協助訊息 </translation> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>無法和這台電腦上的 %s 繫結 (繫結回傳錯誤 %d, %s)</translation> </message> <message> <location line="-93"/> <source>Connect through socks proxy</source> <translation>透過 SOCKS 代理伺服器連線</translation> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>允許對 -addnode, -seednode, -connect 的參數使用域名查詢 </translation> </message> <message> <location line="+56"/> <source>Loading addresses...</source> <translation>載入位址中...</translation> </message> <message> <location line="-36"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>載入檔案 wallet.dat 失敗: 錢包壞掉了</translation> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of GulfCoin</source> <translation>載入檔案 wallet.dat 失敗: 此錢包需要新版的 GulfCoin</translation> </message> <message> <location line="+96"/> <source>Wallet needed to be rewritten: restart GulfCoin to complete</source> <translation>錢包需要重寫: 請重啟位元幣來完成</translation> </message> <message> <location line="-98"/> <source>Error loading wallet.dat</source> <translation>載入檔案 wallet.dat 失敗</translation> </message> <message> <location line="+29"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>無效的 -proxy 位址: &apos;%s&apos;</translation> </message> <message> <location line="+57"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>在 -onlynet 指定了不明的網路別: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation>在 -socks 指定了不明的代理協定版本: %i</translation> </message> <message> <location line="-98"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation>無法解析 -bind 位址: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation>無法解析 -externalip 位址: &apos;%s&apos;</translation> </message> <message> <location line="+45"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>設定 -paytxfee=&lt;金額&gt; 的金額無效: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation>無效的金額</translation> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation>累積金額不足</translation> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation>載入區塊索引中...</translation> </message> <message> <location line="-58"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>加入一個要連線的節線, 並試著保持對它的連線暢通</translation> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. GulfCoin is probably already running.</source> <translation>無法和這台電腦上的 %s 繫結. 也許位元幣已經在執行了.</translation> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation>交易付款時每 KB 的交易手續費</translation> </message> <message> <location line="+20"/> <source>Loading wallet...</source> <translation>載入錢包中...</translation> </message> <message> <location line="-53"/> <source>Cannot downgrade wallet</source> <translation>無法將錢包格式降級</translation> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation>無法寫入預設位址</translation> </message> <message> <location line="+65"/> <source>Rescanning...</source> <translation>重新掃描中...</translation> </message> <message> <location line="-58"/> <source>Done loading</source> <translation>載入完成</translation> </message> <message> <location line="+84"/> <source>To use the %s option</source> <translation>為了要使用 %s 選項</translation> </message> <message> <location line="-76"/> <source>Error</source> <translation>錯誤</translation> </message> <message> <location line="-31"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation>你必須在下列設定檔中設定 RPC 密碼(rpcpassword=&lt;password&gt;): %s 如果這個檔案還不存在, 請在新增時, 設定檔案權限為&quot;只有主人才能讀取&quot;.</translation> </message> </context> </TS>
--- layout: post title: Mughal Empire categories: - Learning --- [Mughal Empire](http://en.wikipedia.org/wiki/Mughal_Empire) (1526 – 1857) rulers... - 1526-1530 [Babur ](http://en.wikipedia.org/wiki/Babur) - 1530–1539 and after restoration 1555–1556 [Humayun ](http://en.wikipedia.org/wiki/Humayun) - 1556–1605 [Akbar ](http://en.wikipedia.org/wiki/Akbar) - 1605–1627 [Jahangir ](http://en.wikipedia.org/wiki/Jahangir) - 1628–1658 [Shah Jahan ](http://en.wikipedia.org/wiki/Shah_Jahan) - 1659–1707   [Aurangzeb ](http://en.wikipedia.org/wiki/Aurangzeb) - Later Emperors = 1707-1857
using Foundation; using System; using System.Linq; using UIKit; namespace UICatalog { public partial class BaseSearchController : UITableViewController, IUISearchResultsUpdating { private const string CellIdentifier = "searchResultsCell"; private readonly string[] allItems = { "Here's", "to", "the", "crazy", "ones.", "The", "misfits.", "The", "rebels.", "The", "troublemakers.", "The", "round", "pegs", "in", "the", "square", "holes.", "The", "ones", "who", "see", "things", "differently.", "They're", "not", "fond", "of", @"rules.", "And", "they", "have", "no", "respect", "for", "the", "status", "quo.", "You", "can", "quote", "them,", "disagree", "with", "them,", "glorify", "or", "vilify", "them.", "About", "the", "only", "thing", "you", "can't", "do", "is", "ignore", "them.", "Because", "they", "change", "things.", "They", "push", "the", "human", "race", "forward.", "And", "while", "some", "may", "see", "them", "as", "the", "crazy", "ones,", "we", "see", "genius.", "Because", "the", "people", "who", "are", "crazy", "enough", "to", "think", "they", "can", "change", "the", "world,", "are", "the", "ones", "who", "do." }; private string[] items; private string query; public BaseSearchController(IntPtr handle) : base(handle) { } public override void ViewDidLoad() { base.ViewDidLoad(); items = allItems; } protected void ApplyFilter(string filter) { query = filter; items = string.IsNullOrEmpty(query) ? allItems : allItems.Where(s => s.Contains(query)).ToArray(); TableView.ReloadData(); } public override nint RowsInSection(UITableView tableView, nint section) { return items.Length; } public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) { var cell = tableView.DequeueReusableCell(CellIdentifier, indexPath); cell.TextLabel.Text = items[indexPath.Row]; return cell; } #region IUISearchResultsUpdating [Export("updateSearchResultsForSearchController:")] public void UpdateSearchResultsForSearchController(UISearchController searchController) { // UpdateSearchResultsForSearchController is called when the controller is being dismissed // to allow those who are using the controller they are search as the results controller a chance to reset their state. // No need to update anything if we're being dismissed. if (searchController.Active) { ApplyFilter(searchController.SearchBar.Text); } } #endregion } }
// // LightningSendDownView.h // TNTLoveFreshBee // // Created by apple on 16/10/14. // Copyright © 2016年 LiDan. All rights reserved. // #import <UIKit/UIKit.h> @protocol didLightningSendDownViewCommitDelegate <NSObject> @optional - (void)didLightningSendDownViewCommit; @end @interface LightningSendDownView : UIView @property(weak,nonatomic) id<didLightningSendDownViewCommitDelegate>delegate; @end
module V1 class EventUserSchedulesController < ApplicationController before_action :set_event_session, only: [:create] # POST /event_user_schedules def create @event_user_schedule = current_user.add_session_to_my_schedule(@event_session) if @event_user_schedule.save render json: @event_user_schedule, serializer: EventUserScheduleShortSerializer, root: "event_user_schedule", status: :created else render json: @event_user_schedule.errors, status: :unprocessable_entity end end # DELETE /event_user_schedules/:id def destroy @event_user_schedule = EventUserSchedule.find(params[:id]) if @event_user_schedule.event_user.user == current_user @event_user_schedule.destroy head :no_content else head :forbidden end end private # Never trust parameters from the scary internet, only allow the white list through. def event_user_schedule_params params.require(:event_user_schedule).permit(:event_session_id) end def set_event_session @event_session = EventSession.find(event_user_schedule_params[:event_session_id]) end end end
/** * This program 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 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * **/ #include "stateengine/AtomicState.h" #include "stateengine/Defines.h" //-------------------------------------------------------------------- // TAtomicState //-------------------------------------------------------------------- //-------------------------------------------------------------------- namespace donut { typedef void (*TUpdaterFunction)(const TStateEngineId&, double); typedef void (*TStateCallBack)(const TStateEngineId&, TStateData *); //-------------------------------------------------------------------- TAtomicState::TAtomicState(TStateEngineId parStateEngineId, TStateId parId, TStateData (* parTStateData), void (* parEnterCallBack), void (* parLeaveCallBack), void (* parUpdater)) : FStateEngineId (parStateEngineId) { FEnterCallBack = parEnterCallBack; FLeaveCallBack = parLeaveCallBack; FStateData = parTStateData; FUpdater = parUpdater; FId = parId; } TAtomicState::~TAtomicState() { // assert_msg_NO_RELEASE(FStateData!=NULL, "The state data has been already deleted. you do not need to.") delete FStateData; } void TAtomicState::AddTransition(TTransitionId parId, TTransition * parTransition) { FOutTransitions[parId] = parTransition; } #if _DEBUG void TAtomicState::AddInTransition(const TTransition * parTransition) { // FInTransitions.push_back(parTransition) } #endif void TAtomicState::Update(double parDt) { void (*updater)( const TStateEngineId&, double) = *((TUpdaterFunction*) (&FUpdater)); updater(FStateEngineId , parDt); } void TAtomicState::Enter() { void (*enter)(const TStateEngineId&, TStateData *) = *((TStateCallBack*) (&FEnterCallBack)); enter(FStateEngineId, FStateData); } void TAtomicState::Leave() { void (*leave)(const TStateEngineId&, TStateData *) = *((TStateCallBack*) (&FLeaveCallBack)); leave(FStateEngineId, FStateData); } void TAtomicState::TransitionCallBack() { } } // End namestate StateEngine
b'Calculate 1 + (3 - -1 - (5 + -3 + -2)).\n'
b'What is the value of (-2 - (-1 + -5 + 11)) + 31?\n'
b'6 + 7 + -7 + -10 + -1 + 7\n'
//----------------------------------------------------------------------- // <copyright file="LocalizableFormBase.cs" company="Hyperar"> // Copyright (c) Hyperar. All rights reserved. // </copyright> // <author>Matías Ezequiel Sánchez</author> //----------------------------------------------------------------------- namespace Hyperar.HattrickUltimate.UserInterface { using System; using System.Windows.Forms; using Interface; /// <summary> /// ILocalizableForm base implementation. /// </summary> public partial class LocalizableFormBase : Form, ILocalizableForm { #region Public Methods /// <summary> /// Populates controls' properties with the corresponding localized string. /// </summary> public virtual void PopulateLanguage() { } #endregion Public Methods #region Protected Methods /// <summary> /// Raises the System.Windows.Forms.Form.Load event. /// </summary> /// <param name="e">An System.EventArgs that contains the event data.</param> protected override void OnLoad(EventArgs e) { base.OnLoad(e); this.PopulateLanguage(); } #endregion Protected Methods } }
import { createSelector } from 'reselect'; import * as movie from './../actions/movie'; import { Movie } from './../models'; import * as _ from 'lodash'; import { AsyncOperation, AsyncStatus, makeAsyncOp } from "./../utils"; export interface State { entities: { [movieId: string]: Movie }; mapMovieToCinema: { [cinemaId: string]: { releasedIds: string[] otherIds: string[], loadingOp: AsyncOperation, } }; selectedId: string; } export const initialState: State = { entities: {}, mapMovieToCinema: {}, selectedId: null, }; export function reducer(state: State = initialState, actionRaw: movie.Actions): State { switch (actionRaw.type) { case movie.ActionTypes.LOAD: { let action = <movie.LoadAction>actionRaw; let cinemaId = action.payload.cinemaId; return { ...state, mapMovieToCinema: { ...state.mapMovieToCinema, [cinemaId]: { ...state.mapMovieToCinema[cinemaId], releasedIds: [], otherIds: [], loadingOp: makeAsyncOp(AsyncStatus.Pending), }, }, }; } case movie.ActionTypes.LOAD_SUCCESS: { let action = <movie.LoadSuccessAction>actionRaw; let entities = _.flatten([action.payload.released, action.payload.other]) .reduce((entities, movie) => { return { ...entities, [movie.id]: movie, }; }, state.entities); let map = { releasedIds: action.payload.released.map(m => m.id), otherIds: action.payload.other.map(m => m.id), loadingOp: makeAsyncOp(AsyncStatus.Success), }; return { ...state, entities: entities, mapMovieToCinema: { ...state.mapMovieToCinema, [action.payload.cinemaId]: map }, }; } case movie.ActionTypes.LOAD_FAIL: { let action = <movie.LoadFailAction>actionRaw; let cinemaId = action.payload.cinemaId; return { ...state, mapMovieToCinema: { ...state.mapMovieToCinema, [cinemaId]: { ...state.mapMovieToCinema[cinemaId], loadingOp: makeAsyncOp(AsyncStatus.Fail, action.payload.errorMessage), }, }, }; } case movie.ActionTypes.SELECT: { var action = <movie.SelectAction>actionRaw; return { ...state, selectedId: action.payload, }; } default: return state; } } export const getEntities = (state: State) => state.entities; export const getMapToCinema = (state: State) => state.mapMovieToCinema; export const getSelectedId = (state: State) => state.selectedId; export const getSelected = createSelector(getEntities, getSelectedId, (entities, id) => { return entities[id]; });
b'-4 + (6 + (-13 - -14) - 4)\n'
// Multiprocessor support // mist32 is not supported multiprocessor #include "types.h" #include "defs.h" #include "param.h" #include "memlayout.h" #include "mmu.h" #include "proc.h" struct cpu cpus[NCPU]; int ismp; int ncpu; void mpinit(void) { ismp = 0; ncpu = 1; lapic = 0; cpus[ncpu].id = ncpu; ncpu++; return; }
b'Evaluate 16 + -15 + 11 + -6.\n'
--- layout: page title: Donald Singh's 31st Birthday date: 2016-05-24 author: Teresa Mcdaniel tags: weekly links, java status: published summary: Nam finibus mollis massa eget venenatis. Maecenas suscipit cursus. banner: images/banner/leisure-01.jpg booking: startDate: 10/08/2018 endDate: 10/13/2018 ctyhocn: TCCHHHX groupCode: DS3B published: true --- Pellentesque lacinia, tellus id ornare luctus, nunc libero pellentesque mi, lobortis tincidunt lectus libero vel tellus. Quisque tincidunt erat eget odio viverra congue. Sed eu ipsum nec tortor aliquet dapibus id id eros. Aliquam non cursus justo. Suspendisse faucibus arcu in sapien ullamcorper, eget sollicitudin quam euismod. Nulla venenatis purus sit amet volutpat volutpat. Sed felis ante, placerat id congue vel, suscipit volutpat enim. Curabitur fermentum scelerisque luctus. Morbi convallis risus vel ornare ullamcorper. Nulla facilisi. Sed malesuada faucibus varius. Nulla scelerisque eros at nisi imperdiet elementum. Vivamus fringilla ligula non pulvinar sollicitudin. Praesent sit amet hendrerit metus. Proin vel tristique erat. Integer neque sem, gravida posuere lacus et, commodo ullamcorper eros. Pellentesque at euismod libero. In hac habitasse platea dictumst. 1 Pellentesque accumsan risus ut nisi convallis rutrum 1 Pellentesque vel eros at nisi tempus vehicula 1 Nam eget tellus eu est mattis iaculis vel quis leo 1 Mauris et nisl non orci consectetur feugiat 1 Donec eget massa ac justo malesuada pellentesque ut egestas tortor. Donec velit urna, lacinia nec laoreet sed, semper a lacus. In fermentum congue turpis vitae faucibus. Nulla semper felis id ultricies cursus. Nulla vel nulla tincidunt, blandit eros ultrices, eleifend risus. Integer maximus neque at magna finibus varius. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vivamus quis velit eu odio sagittis commodo ut sollicitudin dui. Praesent id libero ac eros consectetur faucibus. Fusce mattis id sem vitae ornare. Quisque a ipsum vel elit interdum auctor sit amet ut ante.
b'-3 + (-6 - -7) + 12 + -21\n'
import asyncio import discord import datetime import pytz from discord.ext import commands from Cogs import FuzzySearch from Cogs import Settings from Cogs import DisplayName from Cogs import Message from Cogs import Nullify class Time: # Init with the bot reference, and a reference to the settings var def __init__(self, bot, settings): self.bot = bot self.settings = settings @commands.command(pass_context=True) async def settz(self, ctx, *, tz : str = None): """Sets your TimeZone - Overrides your UTC offset - and accounts for DST.""" usage = 'Usage: `{}settz [Region/City]`\nYou can get a list of available TimeZones with `{}listtz`'.format(ctx.prefix, ctx.prefix) if not tz: self.settings.setGlobalUserStat(ctx.author, "TimeZone", None) await ctx.channel.send("*{}*, your TimeZone has been removed!".format(DisplayName.name(ctx.author))) return # Let's get the timezone list tz_list = FuzzySearch.search(tz, pytz.all_timezones, None, 3) if not tz_list[0]['Ratio'] == 1: # We didn't find a complete match msg = "I couldn't find that TimeZone!\n\nMaybe you meant one of the following?\n```" for tz in tz_list: msg += tz['Item'] + "\n" msg += '```' await ctx.channel.send(msg) return # We got a time zone self.settings.setGlobalUserStat(ctx.author, "TimeZone", tz_list[0]['Item']) await ctx.channel.send("TimeZone set to *{}!*".format(tz_list[0]['Item'])) @commands.command(pass_context=True) async def listtz(self, ctx, *, tz_search = None): """List all the supported TimeZones in PM.""" if not tz_search: msg = "__Available TimeZones:__\n\n" for tz in pytz.all_timezones: msg += tz + "\n" else: tz_list = FuzzySearch.search(tz_search, pytz.all_timezones) msg = "__Top 3 TimeZone Matches:__\n\n" for tz in tz_list: msg += tz['Item'] + "\n" await Message.say(self.bot, msg, ctx.channel, ctx.author, 1) @commands.command(pass_context=True) async def tz(self, ctx, *, member = None): """See a member's TimeZone.""" # Check if we're suppressing @here and @everyone mentions if self.settings.getServerStat(ctx.message.guild, "SuppressMentions").lower() == "yes": suppress = True else: suppress = False if member == None: member = ctx.message.author if type(member) == str: # Try to get a user first memberName = member member = DisplayName.memberForName(memberName, ctx.message.guild) if not member: msg = 'Couldn\'t find user *{}*.'.format(memberName) # Check for suppress if suppress: msg = Nullify.clean(msg) await ctx.channel.send(msg) return # We got one timezone = self.settings.getGlobalUserStat(member, "TimeZone") if timezone == None: msg = '*{}* hasn\'t set their TimeZone yet - they can do so with the `{}settz [Region/City]` command.'.format(DisplayName.name(member), ctx.prefix) await ctx.channel.send(msg) return msg = '*{}\'s* TimeZone is *{}*'.format(DisplayName.name(member), timezone) await ctx.channel.send(msg) @commands.command(pass_context=True) async def setoffset(self, ctx, *, offset : str = None): """Set your UTC offset.""" if offset == None: self.settings.setGlobalUserStat(ctx.message.author, "UTCOffset", None) msg = '*{}*, your UTC offset has been removed!'.format(DisplayName.name(ctx.message.author)) await ctx.channel.send(msg) return offset = offset.replace('+', '') # Split time string by : and get hour/minute values try: hours, minutes = map(int, offset.split(':')) except Exception: try: hours = int(offset) minutes = 0 except Exception: await ctx.channel.send('Offset has to be in +-H:M!') return off = "{}:{}".format(hours, minutes) self.settings.setGlobalUserStat(ctx.message.author, "UTCOffset", off) msg = '*{}*, your UTC offset has been set to *{}!*'.format(DisplayName.name(ctx.message.author), off) await ctx.channel.send(msg) @commands.command(pass_context=True) async def offset(self, ctx, *, member = None): """See a member's UTC offset.""" # Check if we're suppressing @here and @everyone mentions if self.settings.getServerStat(ctx.message.guild, "SuppressMentions").lower() == "yes": suppress = True else: suppress = False if member == None: member = ctx.message.author if type(member) == str: # Try to get a user first memberName = member member = DisplayName.memberForName(memberName, ctx.message.guild) if not member: msg = 'Couldn\'t find user *{}*.'.format(memberName) # Check for suppress if suppress: msg = Nullify.clean(msg) await ctx.channel.send(msg) return # We got one offset = self.settings.getGlobalUserStat(member, "UTCOffset") if offset == None: msg = '*{}* hasn\'t set their offset yet - they can do so with the `{}setoffset [+-offset]` command.'.format(DisplayName.name(member), ctx.prefix) await ctx.channel.send(msg) return # Split time string by : and get hour/minute values try: hours, minutes = map(int, offset.split(':')) except Exception: try: hours = int(offset) minutes = 0 except Exception: await ctx.channel.send('Offset has to be in +-H:M!') return msg = 'UTC' # Apply offset if hours > 0: # Apply positive offset msg += '+{}'.format(offset) elif hours < 0: # Apply negative offset msg += '{}'.format(offset) msg = '*{}\'s* offset is *{}*'.format(DisplayName.name(member), msg) await ctx.channel.send(msg) @commands.command(pass_context=True) async def time(self, ctx, *, offset : str = None): """Get UTC time +- an offset.""" timezone = None if offset == None: member = ctx.message.author else: # Try to get a user first member = DisplayName.memberForName(offset, ctx.message.guild) if member: # We got one # Check for timezone first offset = self.settings.getGlobalUserStat(member, "TimeZone") if offset == None: offset = self.settings.getGlobalUserStat(member, "UTCOffset") if offset == None: msg = '*{}* hasn\'t set their TimeZone or offset yet - they can do so with the `{}setoffset [+-offset]` or `{}settz [Region/City]` command.\nThe current UTC time is *{}*.'.format(DisplayName.name(member), ctx.prefix, ctx.prefix, datetime.datetime.utcnow().strftime("%I:%M %p")) await ctx.channel.send(msg) return # At this point - we need to determine if we have an offset - or possibly a timezone passed t = self.getTimeFromTZ(offset) if t == None: # We did not get an offset t = self.getTimeFromOffset(offset) if t == None: await ctx.channel.send("I couldn't find that TimeZone or offset!") return if member: msg = '{}; where *{}* is, it\'s currently *{}*'.format(t["zone"], DisplayName.name(member), t["time"]) else: msg = '{} is currently *{}*'.format(t["zone"], t["time"]) # Say message await ctx.channel.send(msg) def getTimeFromOffset(self, offset): offset = offset.replace('+', '') # Split time string by : and get hour/minute values try: hours, minutes = map(int, offset.split(':')) except Exception: try: hours = int(offset) minutes = 0 except Exception: return None # await ctx.channel.send('Offset has to be in +-H:M!') # return msg = 'UTC' # Get the time t = datetime.datetime.utcnow() # Apply offset if hours > 0: # Apply positive offset msg += '+{}'.format(offset) td = datetime.timedelta(hours=hours, minutes=minutes) newTime = t + td elif hours < 0: # Apply negative offset msg += '{}'.format(offset) td = datetime.timedelta(hours=(-1*hours), minutes=(-1*minutes)) newTime = t - td else: # No offset newTime = t return { "zone" : msg, "time" : newTime.strftime("%I:%M %p") } def getTimeFromTZ(self, tz): # Assume sanitized zones - as they're pulled from pytz # Let's get the timezone list tz_list = FuzzySearch.search(tz, pytz.all_timezones, None, 3) if not tz_list[0]['Ratio'] == 1: # We didn't find a complete match return None zone = pytz.timezone(tz_list[0]['Item']) zone_now = datetime.datetime.now(zone) return { "zone" : tz_list[0]['Item'], "time" : zone_now.strftime("%I:%M %p") }
get '/user' do if logged_in? redirect '/' end erb :create_account end post '/user' do user = User.create(params[:user]) redirect '/' end post '/login' do if user = User.login(params[:user]) session[:permissions] = '3' end redirect '/' end get '/logout' do session.clear session[:permissions] = '0' redirect '/' end
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>T837185195841212416</title> <link rel="stylesheet" href="//fonts.googleapis.com/css?family=Source+Sans+Pro:300,300i,600"> <link rel="stylesheet" href="/style.css"> <link rel="stylesheet" href="/custom.css"> <link rel="alternate" type="application/rss+xml" title="Curt Clifton" href="http://curt.micro.blog/feed.xml" /> <link rel="alternate" type="application/json" title="Curt Clifton" href="http://curt.micro.blog/feed.json" /> <link rel="EditURI" type="application/rsd+xml" href="/rsd.xml" /> <link rel="me" href="https://micro.blog/curt" /> <link rel="me" href="https://twitter.com/curtclifton" /> <link rel="authorization_endpoint" href="https://indieauth.com/auth" /> <link rel="token_endpoint" href="https://tokens.indieauth.com/token" /> <link rel="micropub" href="https://micro.blog/micropub" /> <link rel="webmention" href="https://micro.blog/webmention" /> </head> <body> <div class="container"> <header class="masthead"> <h1 class="masthead-title--small"> <a href="/">Curt Clifton</a> </h1> </header> <div class="content post h-entry"> <div class="post-date"> <time class="dt-published" datetime="2017-03-02 06:17:00 +0000">02 Mar 2017</time> </div> <div class="e-content"> <p>Whoever, owing allegiance to [U.S.],… adheres to their enemies… is guilty of treason and shall suffer death… #fb <a href="https://t.co/Uid0RAMMs1">https://t.co/Uid0RAMMs1</a></p> </div> </div> </div> </body> </html>
b'What is (-11 + 40 - 4) + -23?\n'
b'Calculate -1 - (19 - -13 - 22).\n'
require 'spec_helper' describe Webpack::Rails do it 'has a version number' do expect(Webpack::Rails::VERSION).not_to be nil end end
<?php $hostname = "localhost"; $user = "root"; $password = "admin"; $database = "employees"; mysql_connect($hostname, $user, $password); mysql_set_charset('utf8'); @mysql_select_db($database) or die( "Unable to select database"); mysql_query("SET NAMES 'utf8'"); $mysqli = new mysqli($hostname, $user, $password, $database); if ($mysqli->connect_errno) { echo "Failed to connect to MySQL: " . $mysqli->connect_error; exit; } if (!$mysqli->set_charset("utf8")) { printf("Error loading character set utf8: %s\n", $mysqli->error); exit; }
b'(-520 - -550) + (-2 - 41)\n'
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. #pragma warning disable CA1801 // Remove unused parameter #pragma warning disable IDE0060 // Remove unused parameter using System; using System.Linq; using System.Text; namespace OtherDll { /// <summary> /// Aids with testing dataflow analysis _not_ doing interprocedural DFA. /// </summary> /// <remarks> /// Since Roslyn doesn't support cross-binary DFA, and this class is /// defined in a different binary, using this class from test source code /// is a way to test handling of non-interprocedural results in dataflow /// analysis implementations. /// </remarks> public class OtherDllClass<T> where T : class { public OtherDllClass(T? constructedInput) { this.ConstructedInput = constructedInput; } public T? ConstructedInput { get; set; } public T? Default { get => default; set { } } public string RandomString { get { Random r = new Random(); byte[] bytes = new byte[r.Next(20) + 10]; r.NextBytes(bytes); bytes = bytes.Where(b => b is >= ((byte)' ') and <= ((byte)'~')).ToArray(); return Encoding.ASCII.GetString(bytes); } set { } } public T? ReturnsConstructedInput() { return this.ConstructedInput; } public T? ReturnsDefault() { return default; } public T? ReturnsInput(T? input) { return input; } public T? ReturnsDefault(T? input) { return default; } public string ReturnsRandom(string input) { Random r = new Random(); byte[] bytes = new byte[r.Next(20) + 10]; r.NextBytes(bytes); bytes = bytes.Where(b => b is >= ((byte)' ') and <= ((byte)'~')).ToArray(); return Encoding.ASCII.GetString(bytes); } public void SetsOutputToConstructedInput(out T? output) { output = this.ConstructedInput; } public void SetsOutputToDefault(out T? output) { output = default; } public void SetsOutputToInput(T? input, out T? output) { output = input; } public void SetsOutputToDefault(T? input, out T? output) { output = default; } public void SetsOutputToRandom(string input, out string output) { Random r = new Random(); byte[] bytes = new byte[r.Next(20) + 10]; r.NextBytes(bytes); bytes = bytes.Where(b => b is >= ((byte)' ') and <= ((byte)'~')).ToArray(); output = Encoding.ASCII.GetString(bytes); } public void SetsReferenceToConstructedInput(ref T? output) { output = this.ConstructedInput; } public void SetsReferenceToDefault(ref T? output) { output = default; } public void SetsReferenceToInput(T? input, ref T? output) { output = input; } public void SetsReferenceToDefault(T? input, ref T? output) { output = default; } public void SetsReferenceToRandom(string input, ref string output) { Random r = new Random(); byte[] bytes = new byte[r.Next(20) + 10]; r.NextBytes(bytes); bytes = bytes.Where(b => b is >= ((byte)' ') and <= ((byte)'~')).ToArray(); output = Encoding.ASCII.GetString(bytes); } } }
b'Calculate (-2 + -5 - -12) + -1.\n'
b'Evaluate 8 - -5 - (-19 + 23).\n'
b'(-15 + 4 - (-6 + (1 - -5))) + 23\n'
b'Calculate 29 + (10 - 20) - (32 + -23).\n'
// // RCWorkspaceCache.h // // Created by Mark Lilback on 12/12/11. // Copyright (c) 2011 . All rights reserved. // #import "_RCWorkspaceCache.h" @interface RCWorkspaceCache : _RCWorkspaceCache //if multiple values are to be set, it best to get properties, set them, and then call setProperties //each call to setProperties serializes a plist @property (nonatomic, strong) NSMutableDictionary *properties; -(id)propertyForKey:(NSString*)key; //removes property if value is nil -(void)setProperty:(id)value forKey:(NSString*)key; -(BOOL)boolPropertyForKey:(NSString*)key; -(void)setBoolProperty:(BOOL)val forKey:(NSString*)key; @end
/** * Copyright (C) 2013 Tobias P. Becker * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * More information at: https://dslib.assembla.com/ * */ #pragma once #include <core/patterns/Derivable.h> #include <core/collection/containers/Set.h> #include <core/Comparator.h> namespace nspace { /** * \brief Node. */ template<typename Derived> class Node : public Derivable<Derived>, public ObservableCollection<Derived*>, public ObservableCollection<Derived*>::Observer { private: /** * \brief The predecessors. */ Set<Derived*> _predecessors; /** * \brief The successors. */ Set<Derived*> _successors; public: /** * \brief Default constructor. */ Node(); /** * \brief Destructor. removes all successors and predecessors */ virtual ~Node(); /** * \brief callback when an element is added to the node. makes sure that the nodes are connected in * both directions. * * \param [in,out] sender If non-null, the sender. * \param [in,out] node If non-null, the node. */ void elementAdded(ObservableCollection<Derived*> * sender, Derived * node); /** * \brief callback when an element is removed from the node. makes sure the nodes are removed. * * \param [in,out] sender If non-null, the sender. * \param [in,out] node If non-null, the node. */ void elementRemoved(ObservableCollection<Derived*> * sender, Derived * node); /** * \brief all connected nodes (union of predecessors and successors) * * \return null if it fails, else. */ Set<Derived*> neighbors() const; /** * \brief read access to predecessors. * * \return null if it fails, else. */ const Set<Derived*> & predecessors() const; /** * \brief read write access to predecessors. * * \return null if it fails, else. */ Set<Derived*> & predecessors(); /** * \brief read write access to successor by index. * * \param i Zero-based index of the. * * \return null if it fails, else. */ Derived * successor(uint i); /** * \brief read access to successor by index. * * \param i Zero-based index of the. * * \return null if it fails, else. */ const Derived * successor(uint i) const; /** * \brief read / write access to predecessor by index. * * \param i Zero-based index of the. * * \return null if it fails, else. */ Derived * predecessor(uint i); /** * \brief read access to predecessor by index. * * \param i Zero-based index of the. * * \return null if it fails, else. */ const Derived * predecessor(uint i) const; /** * \brief read access tot first successor. * * \return null if it fails, else. */ const Derived * firstSuccessor() const; /** * \brief read write access to first successor. * * \return null if it fails, else. */ Derived * firstSuccessor(); /** * \brief returns the first predecessor (const) * * \return null if it fails, else. */ const Derived * firstPredecessor() const; /** * \brief returns the first predecessor. * * \return null if it fails, else. */ Derived * firstPredecessor(); /** * \brief allows const access to the successors. * * \return null if it fails, else. */ const Set<Derived*> & successors() const; /** * \brief allows access to the successors. * * \return null if it fails, else. */ Set<Derived*> & successors(); /** * \brief adds a set of predecessors (arrows indicate direction of connection. * * \param nodes The nodes. * * \return The shifted result. */ Derived & operator <<(const Set<Derived*> &nodes); /** * \brief adds a set of successors. * * \param nodes The nodes. * * \return The shifted result. */ Derived & operator >>(const Set<Derived*> &nodes); /** * \brief adds a single predecessor. * * \param [in,out] node The node. * * \return The shifted result. */ Derived & operator <<(Derived & node); /** * \brief adds a single successor. * * \param [in,out] node The node. * * \return The shifted result. */ Derived & operator >>(Derived & node); /** * \brief adds a single predecessor (by pointer) * * \param [in,out] node If non-null, the node. * * \return The shifted result. */ Derived & operator <<(Derived * node); /** * \brief adds a single successor (by pointer) * * \param [in,out] node If non-null, the node. * * \return The shifted result. */ Derived & operator >>(Derived * node); /** * \brief removes the node from successors and predecessors. * * \param [in,out] node If non-null, the node to remove. */ void remove(Derived * node); /** * \brief iterates the neighbors. * * \param [in,out] action If non-null, the action. */ void foreachNeighbor(std::function<void (Derived*)> action) const; /** * \brief iterates the predecessors. * * \param [in,out] action If non-null, the action. */ void foreachPredecessor(std::function<void (Derived*)> action) const; /** * \brief iterates the successors. * * \param [in,out] action If non-null, the action. */ void foreachSuccessor(std::function<void (Derived*)> action) const; /** * \brief does a depth first search calling action on every node and also passing the path to the * node as a parameter to action. * * \param [in,out] action If non-null, the action. * \param currentpath (optional) [in,out] If non-null, the currentpath. */ void dfsWithPath(std::function<void (Derived *, Set<Derived * > )> action, Set<Derived * > currentpath = Set<Derived*>()); /** * \brief Dfs the given action. * * \param [in,out] action If non-null, the action. */ void dfs(std::function<void (Derived * )> action); /** * \brief really bad implementation of dfs, it is slow and will crash (stack overflow ) if there * are cycles in the graph. * * \param [in,out] f [in,out] If non-null, the std::function&lt;void(bool&amp;,Derived*)&gt; to * process. * \param successors The successors. */ void dfs(std::function<void (bool &, Derived *)> f, std::function<void (Set<Derived*> &, const Derived &) > successors); /** * \brief also a realy bad implemention. this time of bfs (performancewise). it does not crash if * cycles are contained and returns the number of cycles found. * * \param [in,out] f [in,out] If non-null, the std::function&lt;void(bool&amp;,Derived*)&gt; to * process. * \param successors The successors. * * \return . */ int bfs(std::function<void (bool&,Derived*)> f,std::function<void (Set<Derived*> &, const Derived &) > successors); /** * \brief overload. * * \param [in,out] f [in,out] If non-null, the std::function&lt;void(bool&amp;,Derived*)&gt; to * process. * * \return . */ int bfs(std::function<void (bool&,Derived*)> f); /** * \brief Executes the predecessor added action. * * \param [in,out] predecessor If non-null, the predecessor. */ virtual void onPredecessorAdded(Derived * predecessor){} /** * \brief Executes the successor added action. * * \param [in,out] successor If non-null, the successor. */ virtual void onSuccessorAdded(Derived * successor){} /** * \brief Executes the predecessor removed action. * * \param [in,out] predecessor If non-null, the predecessor. */ virtual void onPredecessorRemoved(Derived* predecessor){} /** * \brief Executes the successor removed action. * * \param [in,out] predecessor If non-null, the predecessor. */ virtual void onSuccessorRemoved(Derived * predecessor){} }; // implementation of node template<typename Derived> void Node<Derived>::remove(Derived * node){ successors()/=node; predecessors()/=node; } template<typename Derived> void Node<Derived>::foreachNeighbor(std::function<void (Derived*)> action) const { neighbors().foreachElement(action); } template<typename Derived> void Node<Derived>::foreachPredecessor(std::function<void (Derived*)> action) const { predecessors().foreachElement(action); } template<typename Derived> void Node<Derived>::foreachSuccessor(std::function<void (Derived*)> action) const { successors().foreachElement(action); } template<typename Derived> Node<Derived>::Node(){ _predecessors.addObserver(this); _successors.addObserver(this); } template<typename Derived> Node<Derived>::~Node(){ _predecessors.clear(); _successors.clear(); } // callback when an element is added to the node. makes sure that the nodes are connected in both directions template<typename Derived> void Node<Derived>::elementAdded(ObservableCollection<Derived*> * sender, Derived * node){ if(sender==&_predecessors) { onPredecessorAdded(node); node->successors() |= &this->derived(); } if(sender==&_successors) { onSuccessorAdded(node); node->predecessors()|=&this->derived(); } } // callback when an element is removed from the node. makes sure the nodes are removed template<typename Derived> void Node<Derived>::elementRemoved(ObservableCollection<Derived*> * sender, Derived * node){ if(sender==&_predecessors) { onPredecessorRemoved(node); node->successors() /=&this->derived(); } if(sender==&_successors) { onSuccessorRemoved(node); node->predecessors()/=&this->derived(); } } // all connected nodes (union of predecessors and successors) template<typename Derived> Set<Derived*> Node<Derived>::neighbors() const { return predecessors()|successors(); } // read access to predecessors template<typename Derived> const Set<Derived*> & Node<Derived>::predecessors() const { return _predecessors; } // read write access to predecessors template<typename Derived> Set<Derived*> & Node<Derived>::predecessors(){ return _predecessors; } // read write access to successor by index template<typename Derived> Derived * Node<Derived>::successor(uint i){ return successors().at(i); } // read access to successor by index template<typename Derived> const Derived * Node<Derived>::successor(uint i) const { return successors().at(i); } //read / write access to predecessor by index template<typename Derived> Derived * Node<Derived>::predecessor(uint i){ return predecessors().at(i); } // read access to predecessor by index template<typename Derived> const Derived * Node<Derived>::predecessor(uint i) const { return predecessors().at(i); } // read access tot first successor template<typename Derived> const Derived * Node<Derived>::firstSuccessor() const { return successors().first(); } //read write access to first successor template<typename Derived> Derived * Node<Derived>::firstSuccessor(){ return successors().first(); } // returns the first predecessor (const) template<typename Derived> const Derived * Node<Derived>::firstPredecessor() const { return predecessors().first(); } // returns the first predecessor template<typename Derived> Derived * Node<Derived>::firstPredecessor(){ return predecessors().first(); } // allows const access to the successors template<typename Derived> const Set<Derived*> & Node<Derived>::successors() const { return _successors; } //allows access to the successors template<typename Derived> Set<Derived*> & Node<Derived>::successors(){ return _successors; } // adds a set of predecessors (arrows indicate direction of connection template<typename Derived> Derived & Node<Derived>::operator <<(const Set<Derived*> &nodes){ predecessors() |= nodes; return this->derived(); } // adds a set of successors template<typename Derived> Derived & Node<Derived>::operator >>(const Set<Derived*> &nodes){ successors() |= nodes; return this->derived(); } // adds a single predecessor template<typename Derived> Derived & Node<Derived>::operator <<(Derived & node){ predecessors().add(&node); return this->derived(); } //adds a single successor template<typename Derived> Derived & Node<Derived>::operator >>(Derived & node){ successors().add(&node); return this->derived(); } // adds a single predecessor (by pointer) template<typename Derived> Derived & Node<Derived>::operator <<(Derived * node){ predecessors().add(node); return this->derived(); } // adds a single successor (by pointer) template<typename Derived> Derived & Node<Derived>::operator >>(Derived * node){ successors().add(node); return this->derived(); } template<typename Derived> void Node<Derived>::dfsWithPath(std::function<void (Derived *, Set<Derived * > )> action, Set<Derived * > currentpath){ action(&this->derived(),currentpath); successors().foreachElement([action,this,&currentpath](Derived * next){ next->dfsWithPath(action,currentpath|&this->derived()); }); } template<typename Derived> void Node<Derived>::dfs(std::function<void (Derived * )> action){ auto a = [action](bool& b, Derived * d){action(d); }; auto b = [] (Set<Derived * > &successors, const Derived &current){successors |= current.successors(); }; dfs(a,b ); } // really bad implementation of dfs, it is slow and will crash (stack overflow ) if there are cycles in the graph template<typename Derived> void Node<Derived>::dfs(std::function<void (bool &, Derived *)> f, std::function<void (Set<Derived*> &, const Derived &) > successors){ Set<Derived* > next; successors(next,this->derived()); bool cont=true; f(cont,&this->derived()); if(!cont) return; next.foreachElement([f,successors](Derived * n){ n->dfs(f,successors); }); } // also a realy bad implemention. this time of bfs (performancewise). it does not crash if cycles are contained and returns the number of cycles found template<typename Derived> int Node<Derived>::bfs(std::function<void (bool&,Derived*)> f,std::function<void (Set<Derived*> &, const Derived &) > successors){ Set<Derived *> list = &this->derived(); int cycles =0; while(list) { // get first element Derived * current = list.first(); // remove first element list /= current; //execute function bool cont = true; f(cont,current); if(!cont) return cycles; // add successors of current; successors(list,*current); } return cycles; } // overload template<typename Derived> int Node<Derived>::bfs(std::function<void (bool&,Derived*)> f){ std::function<void (Set<Derived*> &, const Derived &) > sfunc = [] (Set<Node *>&successors,const Derived &node){ successors |= node.successors(); }; return bfs(f,sfunc); } }
Copyright 2013 Romens Team http://romens.ru/ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
<?php use Symfony\Component\HttpKernel\Kernel; use Symfony\Component\Config\Loader\LoaderInterface; class AppKernel extends Kernel { public function registerBundles() { $bundles = array( new Symfony\Bundle\FrameworkBundle\FrameworkBundle(), new Symfony\Bundle\SecurityBundle\SecurityBundle(), new Symfony\Bundle\TwigBundle\TwigBundle(), new Symfony\Bundle\MonologBundle\MonologBundle(), new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(), new Symfony\Bundle\DoctrineBundle\DoctrineBundle(), new Symfony\Bundle\AsseticBundle\AsseticBundle(), new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(), new JMS\SecurityExtraBundle\JMSSecurityExtraBundle(), //Bundle ajouté new FOS\UserBundle\FOSUserBundle(), new Psa\PageBundle\PsaPageBundle(), //new Psa\UserBundle\PsaUserBundle(), new Psa\AdminBundle\PsaAdminBundle(), new Psa\CommonBundle\PsaCommonBundle(), //Forum Bundles new EWZ\Bundle\TimeBundle\EWZTimeBundle(), new WhiteOctober\PagerfantaBundle\WhiteOctoberPagerfantaBundle(), new CCDNComponent\CommonBundle\CCDNComponentCommonBundle(), new CCDNComponent\BBCodeBundle\CCDNComponentBBCodeBundle(), new CCDNComponent\CrumbTrailBundle\CCDNComponentCrumbTrailBundle(), new CCDNComponent\DashboardBundle\CCDNComponentDashboardBundle(), new CCDNComponent\AttachmentBundle\CCDNComponentAttachmentBundle(), new CCDNComponent\MenuBundle\CCDNComponentMenuBundle(), new CCDNForum\KarmaBundle\CCDNForumKarmaBundle(), new CCDNUser\UserBundle\CCDNUserUserBundle(), new CCDNForum\AdminBundle\CCDNForumAdminBundle(), new CCDNForum\ForumBundle\CCDNForumForumBundle(), new CCDNUser\AdminBundle\CCDNUserAdminBundle(), new EWZ\Bundle\RecaptchaBundle\EWZRecaptchaBundle(), new CCDNUser\ProfileBundle\CCDNUserProfileBundle(), new CCDNForum\ModeratorBundle\CCDNForumModeratorBundle(), new CCDNUser\MemberBundle\CCDNUserMemberBundle(), new CCDNMessage\MessageBundle\CCDNMessageMessageBundle(), ); if (in_array($this->getEnvironment(), array('dev', 'test'))) { $bundles[] = new Acme\DemoBundle\AcmeDemoBundle(); $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle(); $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle(); $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle(); $bundles[] = new CoreSphere\ConsoleBundle\CoreSphereConsoleBundle(); } return $bundles; } public function registerContainerConfiguration(LoaderInterface $loader) { $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml'); } }
package com.mauriciotogneri.apply.compiler.syntactic.nodes.arithmetic; import com.mauriciotogneri.apply.compiler.lexical.Token; import com.mauriciotogneri.apply.compiler.syntactic.TreeNode; import com.mauriciotogneri.apply.compiler.syntactic.nodes.ExpressionBinaryNode; public class ArithmeticModuleNode extends ExpressionBinaryNode { public ArithmeticModuleNode(Token token, TreeNode left, TreeNode right) { super(token, left, right); } @Override public String sourceCode() { return String.format("mod(%s, %s)", left.sourceCode(), right.sourceCode()); } }
enum asmop { ASNOP = 0, ASSTB, ASSTH, ASSTW, ASSTL, ASSTM, ASSTS, ASSTD, ASLDSB, ASLDUB, ASLDSH, ASLDUH, ASLDSW, ASLDUW, ASLDL, ASLDS, ASLDD, ASADDW, ASSUBW, ASMULW, ASMODW, ASUMODW, ASDIVW, ASUDIVW, ASSHLW, ASSHRW, ASUSHRW, ASLTW, ASULTW, ASGTW, ASUGTW, ASLEW, ASULEW, ASGEW, ASUGEW, ASEQW, ASNEW, ASBANDW, ASBORW, ASBXORW, ASADDL, ASSUBL, ASMULL, ASMODL, ASUMODL, ASDIVL, ASUDIVL, ASSHLL, ASSHRL, ASUSHRL, ASLTL, ASULTL, ASGTL, ASUGTL, ASLEL, ASULEL, ASGEL, ASUGEL, ASEQL, ASNEL, ASBANDL, ASBORL, ASBXORL, ASADDS, ASSUBS, ASMULS, ASDIVS, ASLTS, ASGTS, ASLES, ASGES, ASEQS, ASNES, ASADDD, ASSUBD, ASMULD, ASDIVD, ASLTD, ASGTD, ASLED, ASGED, ASEQD, ASNED, ASEXTBW, ASUEXTBW, ASEXTBL, ASUEXTBL, ASEXTHW, ASUEXTHW, ASEXTHL, ASUEXTHL, ASEXTWL, ASUEXTWL, ASSTOL, ASSTOW, ASDTOL, ASDTOW, ASSWTOD, ASSWTOS, ASSLTOD, ASSLTOS, ASEXTS, ASTRUNCD, ASJMP, ASBRANCH, ASRET, ASCALL, ASCALLE, ASCALLEX, ASPAR, ASPARE, ASALLOC, ASFORM, ASCOPYB, ASCOPYH, ASCOPYW, ASCOPYL, ASCOPYS, ASCOPYD, ASVSTAR, ASVARG, };
<?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <!-- /fasttmp/mkdist-qt-4.3.5-1211793125/qtopia-core-opensource-src-4.3.5/tools/qdbus/src/qdbusabstractadaptor.cpp --> <head> <title>Qt 4.3: List of All Members for QDBusAbstractAdaptor</title> <link href="classic.css" rel="stylesheet" type="text/css" /> </head> <body> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr> <td align="left" valign="top" width="32"><a href="http://www.trolltech.com/products/qt"><img src="images/qt-logo.png" align="left" width="32" height="32" border="0" /></a></td> <td width="1">&nbsp;&nbsp;</td><td class="postheader" valign="center"><a href="index.html"><font color="#004faf">Home</font></a>&nbsp;&middot; <a href="classes.html"><font color="#004faf">All&nbsp;Classes</font></a>&nbsp;&middot; <a href="mainclasses.html"><font color="#004faf">Main&nbsp;Classes</font></a>&nbsp;&middot; <a href="groups.html"><font color="#004faf">Grouped&nbsp;Classes</font></a>&nbsp;&middot; <a href="modules.html"><font color="#004faf">Modules</font></a>&nbsp;&middot; <a href="functions.html"><font color="#004faf">Functions</font></a></td> <td align="right" valign="top" width="230"><a href="http://www.trolltech.com"><img src="images/trolltech-logo.png" align="right" width="203" height="32" border="0" /></a></td></tr></table><h1 align="center">List of All Members for QDBusAbstractAdaptor</h1> <p>This is the complete list of members for <a href="qdbusabstractadaptor.html">QDBusAbstractAdaptor</a>, including inherited members.</p> <p><table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr><td width="45%" valign="top"><ul> <li><div class="fn"/><a href="qdbusabstractadaptor.html#QDBusAbstractAdaptor">QDBusAbstractAdaptor</a> ( QObject * )</li> <li><div class="fn"/><a href="qdbusabstractadaptor.html#dtor.QDBusAbstractAdaptor">~QDBusAbstractAdaptor</a> ()</li> <li><div class="fn"/><a href="qdbusabstractadaptor.html#autoRelaySignals">autoRelaySignals</a> () const : bool</li> <li><div class="fn"/><a href="qobject.html#blockSignals">blockSignals</a> ( bool ) : bool</li> <li><div class="fn"/><a href="qobject.html#childEvent">childEvent</a> ( QChildEvent * )</li> <li><div class="fn"/><a href="qobject.html#children">children</a> () const : const QObjectList &amp;</li> <li><div class="fn"/><a href="qobject.html#connect">connect</a> ( const QObject *, const char *, const QObject *, const char *, Qt::ConnectionType ) : bool</li> <li><div class="fn"/><a href="qobject.html#connect-2">connect</a> ( const QObject *, const char *, const char *, Qt::ConnectionType ) const : bool</li> <li><div class="fn"/><a href="qobject.html#connectNotify">connectNotify</a> ( const char * )</li> <li><div class="fn"/><a href="qobject.html#customEvent">customEvent</a> ( QEvent * )</li> <li><div class="fn"/><a href="qobject.html#deleteLater">deleteLater</a> ()</li> <li><div class="fn"/><a href="qobject.html#destroyed">destroyed</a> ( QObject * )</li> <li><div class="fn"/><a href="qobject.html#disconnect">disconnect</a> ( const QObject *, const char *, const QObject *, const char * ) : bool</li> <li><div class="fn"/><a href="qobject.html#disconnect-2">disconnect</a> ( const char *, const QObject *, const char * ) : bool</li> <li><div class="fn"/><a href="qobject.html#disconnect-3">disconnect</a> ( const QObject *, const char * ) : bool</li> <li><div class="fn"/><a href="qobject.html#disconnectNotify">disconnectNotify</a> ( const char * )</li> <li><div class="fn"/><a href="qobject.html#dumpObjectInfo">dumpObjectInfo</a> ()</li> <li><div class="fn"/><a href="qobject.html#dumpObjectTree">dumpObjectTree</a> ()</li> <li><div class="fn"/><a href="qobject.html#dynamicPropertyNames">dynamicPropertyNames</a> () const : QList&lt;QByteArray&gt;</li> <li><div class="fn"/><a href="qobject.html#event">event</a> ( QEvent * ) : bool</li> <li><div class="fn"/><a href="qobject.html#eventFilter">eventFilter</a> ( QObject *, QEvent * ) : bool</li> <li><div class="fn"/><a href="qobject.html#findChild">findChild</a> ( const QString &amp; ) const : T</li> <li><div class="fn"/><a href="qobject.html#findChildren">findChildren</a> ( const QString &amp; ) const : QList&lt;T&gt;</li> <li><div class="fn"/><a href="qobject.html#findChildren-2">findChildren</a> ( const QRegExp &amp; ) const : QList&lt;T&gt;</li> <li><div class="fn"/><a href="qobject.html#inherits">inherits</a> ( const char * ) const : bool</li> </ul></td><td valign="top"><ul> <li><div class="fn"/><a href="qobject.html#installEventFilter">installEventFilter</a> ( QObject * )</li> <li><div class="fn"/><a href="qobject.html#isWidgetType">isWidgetType</a> () const : bool</li> <li><div class="fn"/><a href="qobject.html#killTimer">killTimer</a> ( int )</li> <li><div class="fn"/><a href="qobject.html#metaObject">metaObject</a> () const : const QMetaObject *</li> <li><div class="fn"/><a href="qobject.html#moveToThread">moveToThread</a> ( QThread * )</li> <li><div class="fn"/><a href="qobject.html#objectName-prop">objectName</a> () const : QString</li> <li><div class="fn"/><a href="qobject.html#parent">parent</a> () const : QObject *</li> <li><div class="fn"/><a href="qobject.html#property">property</a> ( const char * ) const : QVariant</li> <li><div class="fn"/><a href="qobject.html#receivers">receivers</a> ( const char * ) const : int</li> <li><div class="fn"/><a href="qobject.html#removeEventFilter">removeEventFilter</a> ( QObject * )</li> <li><div class="fn"/><a href="qobject.html#sender">sender</a> () const : QObject *</li> <li><div class="fn"/><a href="qdbusabstractadaptor.html#setAutoRelaySignals">setAutoRelaySignals</a> ( bool )</li> <li><div class="fn"/><a href="qobject.html#objectName-prop">setObjectName</a> ( const QString &amp; )</li> <li><div class="fn"/><a href="qobject.html#setParent">setParent</a> ( QObject * )</li> <li><div class="fn"/><a href="qobject.html#setProperty">setProperty</a> ( const char *, const QVariant &amp; ) : bool</li> <li><div class="fn"/><a href="qobject.html#signalsBlocked">signalsBlocked</a> () const : bool</li> <li><div class="fn"/><a href="qobject.html#startTimer">startTimer</a> ( int ) : int</li> <li><div class="fn"/><a href="qobject.html#staticMetaObject-var">staticMetaObject</a> : const QMetaObject</li> <li><div class="fn"/><a href="qobject.html#thread">thread</a> () const : QThread *</li> <li><div class="fn"/><a href="qobject.html#timerEvent">timerEvent</a> ( QTimerEvent * )</li> <li><div class="fn"/><a href="qobject.html#tr">tr</a> ( const char *, const char *, int ) : QString</li> <li><div class="fn"/><a href="qobject.html#trUtf8">trUtf8</a> ( const char *, const char *, int ) : QString</li> </ul> </td></tr> </table></p> <p /><address><hr /><div align="center"> <table width="100%" cellspacing="0" border="0"><tr class="address"> <td width="30%">Copyright &copy; 2008 <a href="trolltech.html">Trolltech</a></td> <td width="40%" align="center"><a href="trademarks.html">Trademarks</a></td> <td width="30%" align="right"><div align="right">Qt 4.3.5</div></td> </tr></table></div></address></body> </html>
b'Calculate 11 - ((2 - (27 + -16)) + (0 - -2)).\n'
b'-2 - (16 + -6 - 6) - -3\n'
<!DOCTYPE html> <html> <head> <meta charset='UTF-8'> <script src='matrices.js'></script> <style> .indent { padding-left: 2em; } </style> </head> <body> <h3>Color space:</h3> Spec: <select id='e_color_space'> <option value='rec601' selected>Rec601</option> <option value='rec709'>Rec709</option> <option value='rec2020'>Rec2020/Rec2100</option> </select> <div class='indent'> Kr: <input id='e_kr'> <br> Kg: <input id='e_kg'> <br> Kb: <input id='e_kb'> </div> <br>Array order: <select id='e_array_major'> <option value='row' selected>Row-major (common)</option> <option value='column'>Column-major (for OpenGL)</option> </select> <br>Precision: <input id='e_precision' value='5'> <pre id='e_color_space_output'>-</pre> <hr> <h3>Quantization</h3> Bits: <input id='e_bits'> <br>Range: <select id='e_range_type'> <option value='narrow' selected>Narrow</option> <option value='full'>Full</option> </select> <div class='indent'> Yquant: [ <input id='e_yq_min'> , <input id='e_yq_max'> ] <br> Cb, Cr: [ <input id='e_uvq_min'> , <input id='e_uvq_max'> ] (<span id='e_uvq_info'></span>) </div> <pre id='e_quant_output'>-</pre> <hr> <h3>Conversion:</h3> <pre id='e_matrix_output'>-</pre> YCbCr: <input id='e_y' value=100> <input id='e_cb' value=100> <input id='e_cr' value=100> <br> RGB: <input id='e_r'> <input id='e_g'> <input id='e_b'> <script> 'use strict'; function round(x) { const precision = parseInt(e_precision.value); const pointsPow = Math.pow(10, precision); return Math.round(x * pointsPow) / pointsPow; } function matToOutputVar(var_name, x) { const precision = parseInt(e_precision.value); if (e_array_major.value === 'column') { x = matTrans(x); } return var_name + ' =\n' + matString(x, precision); }; // - function getRangeInfo() { const bits = parseInt(e_bits.value); const normalizer = (1 << bits) - 1; const cbcr_neg_1 = parseFloat(e_uvq_min.value); const cbcr_pos_1 = parseFloat(e_uvq_max.value); const cbcr0 = (cbcr_neg_1 + cbcr_pos_1) / 2; return { y0: parseFloat(e_yq_min.value) / normalizer, y1: parseFloat(e_yq_max.value) / normalizer, cbcr0: cbcr0 / normalizer, cbcr1: cbcr_pos_1 / normalizer, }; } // - // Make these easy to use in console: let yuvFromRgb, rgbFromYuv; let ycbcrFromYuv; let ycbcrFromRgb, rgbFromYcbcr; function refreshQuant() { const r = getRangeInfo(); ycbcrFromYuv = [ [r.y1-r.y0, 0, 0, r.y0], [0, r.cbcr1-r.cbcr0, 0, r.cbcr0], [0, 0, r.cbcr1-r.cbcr0, r.cbcr0] ]; const yuvFromRgb_4x4 = matResized(yuvFromRgb, 4, 4); ycbcrFromRgb = matMul(ycbcrFromYuv, yuvFromRgb_4x4); rgbFromYcbcr = matInv(ycbcrFromRgb); //const back = matInv(rgbFromYcbcr); //console.log('ycbcrFromRgb-1-1', fnMatToString(back)); const bits = parseInt(e_bits.value); const normalizer = (1 << bits) - 1; const cbcrDiff = r.cbcr1 - r.cbcr0; function roundNorm(x) { return round(x*normalizer); } e_quant_output.textContent = [ `Yq: [${roundNorm(r.y0)}, ${roundNorm(r.y1)}]`, `Cb, Cr: ${roundNorm(r.cbcr0)} +/- ${roundNorm(cbcrDiff)}` + ` => [${roundNorm(r.cbcr0-cbcrDiff)}, ${roundNorm(r.cbcr0+cbcrDiff)}]`, '', `Y: [${round(r.y0)}, ${round(r.y1)}]`, `U, V: ${round(r.cbcr0)} +/- ${round(cbcrDiff)}` + ` => [${round(r.cbcr0-cbcrDiff)}, ${round(r.cbcr0+cbcrDiff)}]`, '', matToOutputVar('ycbcrFromYuv', ycbcrFromYuv) ].join('\n'); e_matrix_output.textContent = [ matToOutputVar('ycbcrFromRgb', ycbcrFromRgb), '', matToOutputVar('rgbFromYcbcr', rgbFromYcbcr), ].join('\n'); lastConvertFunc(); } [ e_yq_min, e_yq_max, e_uvq_min, e_uvq_max, ].forEach(e => { e.addEventListener('change', refreshQuant); }); // - function refreshUvqInfo() { const r = getRangeInfo(); const bits = parseInt(e_bits.value); const normalizer = (1 << bits) - 1; const cbcr0 = r.cbcr0 * normalizer; const cbcrDiff = (r.cbcr1 - r.cbcr0) * normalizer; e_uvq_info.textContent = `${round(cbcr0)} +/- ${round(cbcrDiff)}`; } e_uvq_min.addEventListener('change', refreshUvqInfo); e_uvq_max.addEventListener('change', refreshUvqInfo); // - function refreshRangeInfo() { const bits = parseInt(e_bits.value); const normalizer = (1 << bits) - 1; if (e_range_type.value == 'full') { // rec2020 defines these: // Y: D = Round((2^n-1) * E) | E = [0.0, 1.0] // AKA Dy = 255*Ey + 0 // Cb,Cr: D = Round((2^n-1) * E + 2^(n-1)) | E = [-0.5, 0.5] // AKA Dcb,Dcr = 255*Ey + 128, or 128 +/- 127.5. (512 +/- 511.5) // Next, it then specifies peak/achrome/peak as 1/512/1023, // but by its formulas, +0.5 => round(1023*0.5+512) = round(512+511.5) // = round(1023.5) = *1024*. Uhh, oops! // It seems to me what they wanted instead was 512 +/- 511, or: // Cb,Cr: D = Round((2^n-2) * E + 2^(n-1)) e_yq_min.value = 0; e_yq_max.value = normalizer; e_uvq_min.value = 1; e_uvq_max.value = normalizer; } else { let y0 = 16; let y1 = 235; // 16+219 let cbcr0 = 128; let cbcr1 = 240; // 128+224/2 // 10- and 12-bit narrow are just scaled 8-bit narrow. y0 <<= bits - 8; y1 <<= bits - 8; cbcr0 <<= bits - 8; cbcr1 <<= bits - 8; e_yq_min.value = y0; e_yq_max.value = y1; e_uvq_min.value = cbcr0 - (cbcr1 - cbcr0); e_uvq_max.value = cbcr1; } refreshUvqInfo(); refreshQuant(); } e_bits.addEventListener('change', refreshRangeInfo); e_range_type.addEventListener('change', refreshRangeInfo); // - function refreshColorSpace() { const kr = parseFloat(e_kr.value); const kg = parseFloat(e_kg.value); const kb = parseFloat(e_kb.value); const uRange = 1-kb; const vRange = 1-kr; yuvFromRgb = [ [kr, kg, kb], [-kr/uRange, -kg/uRange, (1-kb)/uRange], [(1-kr)/vRange, -kg/vRange, -kb/vRange] ]; rgbFromYuv = matInv(yuvFromRgb); e_color_space_output.textContent = [ matToOutputVar('yuvFromRgb', yuvFromRgb), '', matToOutputVar('rgbFromYuv', rgbFromYuv), ].join('\n'); refreshRangeInfo(); } e_kr.addEventListener('change', refreshColorSpace); e_kg.addEventListener('change', refreshColorSpace); e_kb.addEventListener('change', refreshColorSpace); // - function presetColorSpace() { const colorSpace = e_color_space.value; if (colorSpace === 'rec601') { e_kr.value = 0.299; e_kg.value = 0.587; e_kb.value = 0.114; e_bits.value = 8; } else if (colorSpace === 'rec709') { e_kr.value = 0.2126; e_kg.value = 0.7152; e_kb.value = 0.0722; e_bits.value = 8; } else if (colorSpace === 'rec2020') { e_kr.value = 0.2627; e_kg.value = '0.6780'; // String to preserve the trailing zero. e_kb.value = 0.0593; e_bits.value = 10; } refreshColorSpace(); } e_color_space.addEventListener('change', presetColorSpace); // - [e_array_major, e_precision].forEach(e => { e.addEventListener('change', () => { refreshColorSpace(); refreshQuant(); }); }); // - function convert(srcElems, destFromSrc, destElems) { const bits = parseInt(e_bits.value); const normalizer = (1 << bits) - 1; const src = srcElems.map(e => parseFloat(e.value) / normalizer); src.push(1); const dest = matMulVec(destFromSrc, src); for (let i = 0; i < 3; i++) { let val = dest[i]; //val = Math.max(0, Math.min(val, 1)); // clamp to [0,1] destElems[i].value = round(val*normalizer); } } // - const RGB_ELEMS = [e_r, e_g, e_b]; const YCBCR_ELEMS = [e_y, e_cb, e_cr]; function fromRgb() { convert(RGB_ELEMS, ycbcrFromRgb, YCBCR_ELEMS); lastConvertFunc = fromRgb; } function fromYcbcr() { convert(YCBCR_ELEMS, rgbFromYcbcr, RGB_ELEMS); lastConvertFunc = fromYcbcr; } let lastConvertFunc = fromYcbcr; RGB_ELEMS.forEach(e => e.addEventListener('change', fromRgb)); YCBCR_ELEMS.forEach(e => e.addEventListener('change', fromYcbcr)); // - presetColorSpace(); refreshQuant(); </script> </body> </html>
/* * Read and write JSON. * * Copyright (c) 2014 Marko Kreen * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <usual/json.h> #include <usual/cxextra.h> #include <usual/cbtree.h> #include <usual/misc.h> #include <usual/utf8.h> #include <usual/ctype.h> #include <usual/bytemap.h> #include <usual/string.h> #include <math.h> #define TYPE_BITS 3 #define TYPE_MASK ((1 << TYPE_BITS) - 1) #define UNATTACHED ((struct JsonValue *)(1 << TYPE_BITS)) #define JSON_MAX_KEY (1024*1024) #define NUMBER_BUF 100 #define JSON_MAXINT ((1LL << 53) - 1) #define JSON_MININT (-(1LL << 53) + 1) /* * Common struct for all JSON values */ struct JsonValue { /* actual value for simple types */ union { double v_float; /* float */ int64_t v_int; /* int */ bool v_bool; /* bool */ size_t v_size; /* str/list/dict */ } u; /* pointer to next elem and type in low bits */ uintptr_t v_next_and_type; }; /* * List container. */ struct ValueList { struct JsonValue *first; struct JsonValue *last; struct JsonValue **array; }; /* * Extra data for list/dict. */ struct JsonContainer { /* parent container */ struct JsonValue *c_parent; /* main context for child alloc */ struct JsonContext *c_ctx; /* child elements */ union { struct CBTree *c_dict; struct ValueList c_list; } u; }; #define DICT_EXTRA (offsetof(struct JsonContainer, u.c_dict) + sizeof(struct CBTree *)) #define LIST_EXTRA (sizeof(struct JsonContainer)) /* * Allocation context. */ struct JsonContext { CxMem *pool; unsigned int options; /* parse state */ struct JsonValue *parent; struct JsonValue *cur_key; struct JsonValue *top; const char *lasterr; char errbuf[128]; int64_t linenr; }; struct RenderState { struct MBuf *dst; unsigned int options; }; /* * Parser states */ enum ParseState { S_INITIAL_VALUE = 1, S_LIST_VALUE, S_LIST_VALUE_OR_CLOSE, S_LIST_COMMA_OR_CLOSE, S_DICT_KEY, S_DICT_KEY_OR_CLOSE, S_DICT_COLON, S_DICT_VALUE, S_DICT_COMMA_OR_CLOSE, S_PARENT, S_DONE, MAX_STATES, }; /* * Tokens that change state. */ enum TokenTypes { T_STRING, T_OTHER, T_COMMA, T_COLON, T_OPEN_DICT, T_OPEN_LIST, T_CLOSE_DICT, T_CLOSE_LIST, MAX_TOKENS }; /* * 4-byte ints for small string tokens. */ #define C_NULL FOURCC('n','u','l','l') #define C_TRUE FOURCC('t','r','u','e') #define C_ALSE FOURCC('a','l','s','e') /* * Signature for render functions. */ typedef bool (*render_func_t)(struct RenderState *rs, struct JsonValue *jv); static bool render_any(struct RenderState *rs, struct JsonValue *jv); /* * Header manipulation */ static inline enum JsonValueType get_type(struct JsonValue *jv) { return jv->v_next_and_type & TYPE_MASK; } static inline bool has_type(struct JsonValue *jv, enum JsonValueType type) { if (!jv) return false; return get_type(jv) == type; } static inline struct JsonValue *get_next(struct JsonValue *jv) { return (struct JsonValue *)(jv->v_next_and_type & ~(uintptr_t)TYPE_MASK); } static inline void set_next(struct JsonValue *jv, struct JsonValue *next) { jv->v_next_and_type = (uintptr_t)next | get_type(jv); } static inline bool is_unattached(struct JsonValue *jv) { return get_next(jv) == UNATTACHED; } static inline void *get_extra(struct JsonValue *jv) { return (void *)(jv + 1); } static inline char *get_cstring(struct JsonValue *jv) { enum JsonValueType type = get_type(jv); if (type != JSON_STRING) return NULL; return get_extra(jv); } /* * Collection header manipulation. */ static inline struct JsonContainer *get_container(struct JsonValue *jv) { enum JsonValueType type = get_type(jv); if (type != JSON_DICT && type != JSON_LIST) return NULL; return get_extra(jv); } static inline void set_parent(struct JsonValue *jv, struct JsonValue *parent) { struct JsonContainer *c = get_container(jv); if (c) c->c_parent = parent; } static inline struct JsonContext *get_context(struct JsonValue *jv) { struct JsonContainer *c = get_container(jv); return c ? c->c_ctx : NULL; } static inline struct CBTree *get_dict_tree(struct JsonValue *jv) { struct JsonContainer *c; if (has_type(jv, JSON_DICT)) { c = get_container(jv); return c->u.c_dict; } return NULL; } static inline struct ValueList *get_list_vlist(struct JsonValue *jv) { struct JsonContainer *c; if (has_type(jv, JSON_LIST)) { c = get_container(jv); return &c->u.c_list; } return NULL; } /* * Random helpers */ /* copy and return final pointer */ static inline char *plain_copy(char *dst, const char *src, const char *endptr) { if (src < endptr) { memcpy(dst, src, endptr - src); return dst + (endptr - src); } return dst; } /* error message on context */ _PRINTF(2,0) static void format_err(struct JsonContext *ctx, const char *errmsg, va_list ap) { char buf[119]; if (ctx->lasterr) return; vsnprintf(buf, sizeof(buf), errmsg, ap); snprintf(ctx->errbuf, sizeof(ctx->errbuf), "Line #%" PRIi64 ": %s", ctx->linenr, buf); ctx->lasterr = ctx->errbuf; } /* set message and return false */ _PRINTF(2,3) static bool err_false(struct JsonContext *ctx, const char *errmsg, ...) { va_list ap; va_start(ap, errmsg); format_err(ctx, errmsg, ap); va_end(ap); return false; } /* set message and return NULL */ _PRINTF(2,3) static void *err_null(struct JsonContext *ctx, const char *errmsg, ...) { va_list ap; va_start(ap, errmsg); format_err(ctx, errmsg, ap); va_end(ap); return NULL; } /* callback for cbtree, returns key bytes */ static size_t get_key_data_cb(void *dictptr, void *keyptr, const void **dst_p) { struct JsonValue *key = keyptr; *dst_p = get_cstring(key); return key->u.v_size; } /* add elemnt to list */ static void real_list_append(struct JsonValue *list, struct JsonValue *elem) { struct ValueList *vlist; vlist = get_list_vlist(list); if (vlist->last) { set_next(vlist->last, elem); } else { vlist->first = elem; } vlist->last = elem; vlist->array = NULL; list->u.v_size++; } /* add key to tree */ static bool real_dict_add_key(struct JsonContext *ctx, struct JsonValue *dict, struct JsonValue *key) { struct CBTree *tree; tree = get_dict_tree(dict); if (!tree) return err_false(ctx, "Expect dict"); if (json_value_size(key) > JSON_MAX_KEY) return err_false(ctx, "Too large key"); dict->u.v_size++; if (!cbtree_insert(tree, key)) return err_false(ctx, "Key insertion failed"); return true; } /* create basic value struct, link to stuctures */ static struct JsonValue *mk_value(struct JsonContext *ctx, enum JsonValueType type, size_t extra, bool attach) { struct JsonValue *val; struct JsonContainer *col = NULL; if (!ctx) return NULL; val = cx_alloc(ctx->pool, sizeof(struct JsonValue) + extra); if (!val) return err_null(ctx, "No memory"); if ((uintptr_t)val & TYPE_MASK) return err_null(ctx, "Unaligned pointer"); /* initial value */ val->v_next_and_type = type; val->u.v_int = 0; if (type == JSON_DICT || type == JSON_LIST) { col = get_container(val); col->c_ctx = ctx; col->c_parent = NULL; if (type == JSON_DICT) { col->u.c_dict = cbtree_create(get_key_data_cb, NULL, val, ctx->pool); if (!col->u.c_dict) return err_null(ctx, "No memory"); } else { memset(&col->u.c_list, 0, sizeof(col->u.c_list)); } } /* independent JsonValue? */ if (!attach) { set_next(val, UNATTACHED); return val; } /* attach to parent */ if (col) col->c_parent = ctx->parent; /* attach to previous value */ if (has_type(ctx->parent, JSON_DICT)) { if (ctx->cur_key) { set_next(ctx->cur_key, val); ctx->cur_key = NULL; } else { ctx->cur_key = val; } } else if (has_type(ctx->parent, JSON_LIST)) { real_list_append(ctx->parent, val); } else if (!ctx->top) { ctx->top = val; } else { return err_null(ctx, "Only one top element is allowed"); } return val; } static void prepare_array(struct JsonValue *list) { struct JsonContainer *c; struct JsonValue *val; struct ValueList *vlist; size_t i; vlist = get_list_vlist(list); if (vlist->array) return; c = get_container(list); vlist->array = cx_alloc(c->c_ctx->pool, list->u.v_size * sizeof(struct JsonValue *)); if (!vlist->array) return; val = vlist->first; for (i = 0; i < list->u.v_size && val; i++) { vlist->array[i] = val; val = get_next(val); } } /* * Parsing code starts */ /* create and change context */ static bool open_container(struct JsonContext *ctx, enum JsonValueType type, unsigned int extra) { struct JsonValue *jv; jv = mk_value(ctx, type, extra, true); if (!jv) return false; ctx->parent = jv; ctx->cur_key = NULL; return true; } /* close and change context */ static enum ParseState close_container(struct JsonContext *ctx, enum ParseState state) { struct JsonContainer *c; if (state != S_PARENT) return (int)err_false(ctx, "close_container bug"); c = get_container(ctx->parent); if (!c) return (int)err_false(ctx, "invalid parent"); ctx->parent = c->c_parent; ctx->cur_key = NULL; if (has_type(ctx->parent, JSON_DICT)) { return S_DICT_COMMA_OR_CLOSE; } else if (has_type(ctx->parent, JSON_LIST)) { return S_LIST_COMMA_OR_CLOSE; } return S_DONE; } /* parse 4-char token */ static bool parse_char4(struct JsonContext *ctx, const char **src_p, const char *end, uint32_t t_exp, enum JsonValueType type, bool val) { const char *src; uint32_t t_got; struct JsonValue *jv; src = *src_p; if (src + 4 > end) return err_false(ctx, "Unexpected end of token"); memcpy(&t_got, src, 4); if (t_exp != t_got) return err_false(ctx, "Invalid token"); jv = mk_value(ctx, type, 0, true); if (!jv) return false; jv->u.v_bool = val; *src_p += 4; return true; } /* parse int or float */ static bool parse_number(struct JsonContext *ctx, const char **src_p, const char *end) { const char *start, *src; enum JsonValueType type = JSON_INT; char *tokend = NULL; char buf[NUMBER_BUF]; size_t len; struct JsonValue *jv; double v_float = 0; int64_t v_int = 0; /* scan & copy */ start = src = *src_p; for (; src < end; src++) { if (*src >= '0' && *src <= '9') { } else if (*src == '+' || *src == '-') { } else if (*src == '.' || *src == 'e' || *src == 'E') { type = JSON_FLOAT; } else { break; } } len = src - start; if (len >= NUMBER_BUF) goto failed; memcpy(buf, start, len); buf[len] = 0; /* now parse */ errno = 0; tokend = buf; if (type == JSON_FLOAT) { v_float = strtod_dot(buf, &tokend); if (*tokend != 0 || errno || !isfinite(v_float)) goto failed; } else if (len < 8) { v_int = strtol(buf, &tokend, 10); if (*tokend != 0 || errno) goto failed; } else { v_int = strtoll(buf, &tokend, 10); if (*tokend != 0 || errno || v_int < JSON_MININT || v_int > JSON_MAXINT) goto failed; } /* create value struct */ jv = mk_value(ctx, type, 0, true); if (!jv) return false; if (type == JSON_FLOAT) { jv->u.v_float = v_float; } else { jv->u.v_int = v_int; } *src_p = src; return true; failed: if (!errno) errno = EINVAL; return err_false(ctx, "Number parse failed"); } /* * String parsing */ static int parse_hex(const char *s, const char *end) { int v = 0, c, i, x; if (s + 4 > end) return -1; for (i = 0; i < 4; i++) { c = s[i]; if (c >= '0' && c <= '9') { x = c - '0'; } else if (c >= 'a' && c <= 'f') { x = c - 'a' + 10; } else if (c >= 'A' && c <= 'F') { x = c - 'A' + 10; } else { return -1; } v = (v << 4) | x; } return v; } /* process \uXXXX escapes, merge surrogates */ static bool parse_uescape(struct JsonContext *ctx, char **dst_p, char *dstend, const char **src_p, const char *end) { int c, c2; const char *src = *src_p; c = parse_hex(src, end); if (c <= 0) return err_false(ctx, "Invalid hex escape"); src += 4; if (c >= 0xD800 && c <= 0xDFFF) { /* first surrogate */ if (c >= 0xDC00) return err_false(ctx, "Invalid UTF16 escape"); if (src + 6 > end) return err_false(ctx, "Invalid UTF16 escape"); /* second surrogate */ if (src[0] != '\\' || src[1] != 'u') return err_false(ctx, "Invalid UTF16 escape"); c2 = parse_hex(src + 2, end); if (c2 < 0xDC00 || c2 > 0xDFFF) return err_false(ctx, "Invalid UTF16 escape"); c = 0x10000 + ((c & 0x3FF) << 10) + (c2 & 0x3FF); src += 6; } /* now write char */ if (!utf8_put_char(c, dst_p, dstend)) return err_false(ctx, "Invalid UTF16 escape"); *src_p = src; return true; } #define meta_string(c) (((c) == '"' || (c) == '\\' || (c) == '\0' || \ (c) == '\n' || ((c) & 0x80) != 0) ? 1 : 0) static const uint8_t string_examine_chars[] = INTMAP256_CONST(meta_string); /* look for string end, validate contents */ static bool scan_string(struct JsonContext *ctx, const char *src, const char *end, const char **str_end_p, bool *hasesc_p, int64_t *nlines_p) { bool hasesc = false; int64_t lines = 0; unsigned int n; bool check_utf8 = true; if (ctx->options & JSON_PARSE_IGNORE_ENCODING) check_utf8 = false; while (src < end) { if (!string_examine_chars[(uint8_t)*src]) { src++; } else if (*src == '"') { /* string end */ *hasesc_p = hasesc; *str_end_p = src; *nlines_p = lines; return true; } else if (*src == '\\') { hasesc = true; src++; if (src < end && (*src == '\\' || *src == '"')) src++; } else if (*src & 0x80) { n = utf8_validate_seq(src, end); if (n) { src += n; } else if (check_utf8) { goto badutf; } else { src++; } } else if (*src == '\n') { lines++; src++; } else { goto badutf; } } return err_false(ctx, "Unexpected end of string"); badutf: return err_false(ctx, "Invalid UTF8 sequence"); } /* string boundaries are known, copy and unescape */ static char *process_escapes(struct JsonContext *ctx, const char *src, const char *end, char *dst, char *dstend) { const char *esc; /* process escapes */ while (src < end) { esc = memchr(src, '\\', end - src); if (!esc) { dst = plain_copy(dst, src, end); break; } dst = plain_copy(dst, src, esc); src = esc + 1; switch (*src++) { case '"': *dst++ = '"'; break; case '\\': *dst++ = '\\'; break; case '/': *dst++ = '/'; break; case 'b': *dst++ = '\b'; break; case 'f': *dst++ = '\f'; break; case 'n': *dst++ = '\n'; break; case 'r': *dst++ = '\r'; break; case 't': *dst++ = '\t'; break; case 'u': if (!parse_uescape(ctx, &dst, dstend, &src, end)) return NULL; break; default: return err_null(ctx, "Invalid escape code"); } } return dst; } /* 2-phase string processing */ static bool parse_string(struct JsonContext *ctx, const char **src_p, const char *end) { const char *start, *strend = NULL; bool hasesc = false; char *dst, *dstend; size_t len; struct JsonValue *jv; int64_t lines = 0; /* find string boundaries, validate */ start = *src_p; if (!scan_string(ctx, start, end, &strend, &hasesc, &lines)) return false; /* create value struct */ len = strend - start; jv = mk_value(ctx, JSON_STRING, len + 1, true); if (!jv) return false; dst = get_cstring(jv); dstend = dst + len; /* copy & process escapes */ if (hasesc) { dst = process_escapes(ctx, start, strend, dst, dstend); if (!dst) return false; } else { dst = plain_copy(dst, start, strend); } *dst = '\0'; jv->u.v_size = dst - get_cstring(jv); ctx->linenr += lines; *src_p = strend + 1; return true; } /* * Helpers for relaxed parsing */ static bool skip_comment(struct JsonContext *ctx, const char **src_p, const char *end) { const char *s, *start; char c; size_t lnr; s = start = *src_p; if (s >= end) return false; c = *s++; if (c == '/') { s = memchr(s, '\n', end - s); if (s) { ctx->linenr++; *src_p = s + 1; } else { *src_p = end; } return true; } else if (c == '*') { for (lnr = 0; s + 2 <= end; s++) { if (s[0] == '*' && s[1] == '/') { ctx->linenr += lnr; *src_p = s + 2; return true; } else if (s[0] == '\n') { lnr++; } } } return false; } static bool skip_extra_comma(struct JsonContext *ctx, const char **src_p, const char *end, enum ParseState state) { bool skip = false; const char *src = *src_p; while (src < end && isspace(*src)) { if (*src == '\n') ctx->linenr++; src++; } if (src < end) { if (*src == '}') { if (state == S_DICT_COMMA_OR_CLOSE || state == S_DICT_KEY_OR_CLOSE) skip = true; } else if (*src == ']') { if (state == S_LIST_COMMA_OR_CLOSE || state == S_LIST_VALUE_OR_CLOSE) skip = true; } } *src_p = src; return skip; } /* * Main parser */ /* oldstate + token -> newstate */ static const unsigned char STATE_STEPS[MAX_STATES][MAX_TOKENS] = { [S_INITIAL_VALUE] = { [T_OPEN_LIST] = S_LIST_VALUE_OR_CLOSE, [T_OPEN_DICT] = S_DICT_KEY_OR_CLOSE, [T_STRING] = S_DONE, [T_OTHER] = S_DONE }, [S_LIST_VALUE] = { [T_OPEN_LIST] = S_LIST_VALUE_OR_CLOSE, [T_OPEN_DICT] = S_DICT_KEY_OR_CLOSE, [T_STRING] = S_LIST_COMMA_OR_CLOSE, [T_OTHER] = S_LIST_COMMA_OR_CLOSE }, [S_LIST_VALUE_OR_CLOSE] = { [T_OPEN_LIST] = S_LIST_VALUE_OR_CLOSE, [T_OPEN_DICT] = S_DICT_KEY_OR_CLOSE, [T_STRING] = S_LIST_COMMA_OR_CLOSE, [T_OTHER] = S_LIST_COMMA_OR_CLOSE, [T_CLOSE_LIST] = S_PARENT }, [S_LIST_COMMA_OR_CLOSE] = { [T_COMMA] = S_LIST_VALUE, [T_CLOSE_LIST] = S_PARENT }, [S_DICT_KEY] = { [T_STRING] = S_DICT_COLON }, [S_DICT_KEY_OR_CLOSE] = { [T_STRING] = S_DICT_COLON, [T_CLOSE_DICT] = S_PARENT }, [S_DICT_COLON] = { [T_COLON] = S_DICT_VALUE }, [S_DICT_VALUE] = { [T_OPEN_LIST] = S_LIST_VALUE_OR_CLOSE, [T_OPEN_DICT] = S_DICT_KEY_OR_CLOSE, [T_STRING] = S_DICT_COMMA_OR_CLOSE, [T_OTHER] = S_DICT_COMMA_OR_CLOSE }, [S_DICT_COMMA_OR_CLOSE] = { [T_COMMA] = S_DICT_KEY, [T_CLOSE_DICT] = S_PARENT }, }; #define MAPSTATE(state, tok) do { \ int newstate = STATE_STEPS[state][tok]; \ if (!newstate) \ return err_false(ctx, "Unexpected symbol: '%c'", c); \ state = newstate; \ } while (0) /* actual parser */ static bool parse_tokens(struct JsonContext *ctx, const char *src, const char *end) { char c; enum ParseState state = S_INITIAL_VALUE; bool relaxed = ctx->options & JSON_PARSE_RELAXED; while (src < end) { c = *src++; switch (c) { case '\n': ctx->linenr++; case ' ': case '\t': case '\r': case '\f': case '\v': /* common case - many spaces */ while (src < end && *src == ' ') src++; break; case '"': MAPSTATE(state, T_STRING); if (!parse_string(ctx, &src, end)) goto failed; break; case 'n': MAPSTATE(state, T_OTHER); src--; if (!parse_char4(ctx, &src, end, C_NULL, JSON_NULL, 0)) goto failed; continue; case 't': MAPSTATE(state, T_OTHER); src--; if (!parse_char4(ctx, &src, end, C_TRUE, JSON_BOOL, 1)) goto failed; break; case 'f': MAPSTATE(state, T_OTHER); if (!parse_char4(ctx, &src, end, C_ALSE, JSON_BOOL, 0)) goto failed; break; case '-': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': MAPSTATE(state, T_OTHER); src--; if (!parse_number(ctx, &src, end)) goto failed; break; case '[': MAPSTATE(state, T_OPEN_LIST); if (!open_container(ctx, JSON_LIST, LIST_EXTRA)) goto failed; break; case '{': MAPSTATE(state, T_OPEN_DICT); if (!open_container(ctx, JSON_DICT, DICT_EXTRA)) goto failed; break; case ']': MAPSTATE(state, T_CLOSE_LIST); state = close_container(ctx, state); if (!state) goto failed; break; case '}': MAPSTATE(state, T_CLOSE_DICT); state = close_container(ctx, state); if (!state) goto failed; break; case ':': MAPSTATE(state, T_COLON); if (!real_dict_add_key(ctx, ctx->parent, ctx->cur_key)) goto failed; break; case ',': if (relaxed && skip_extra_comma(ctx, &src, end, state)) continue; MAPSTATE(state, T_COMMA); break; case '/': if (relaxed && skip_comment(ctx, &src, end)) continue; /* fallthrough */ default: return err_false(ctx, "Invalid symbol: '%c'", c); } } if (state != S_DONE) return err_false(ctx, "Container still open"); return true; failed: return false; } /* parser public api */ struct JsonValue *json_parse(struct JsonContext *ctx, const char *json, size_t len) { const char *end = json + len; /* reset parser */ ctx->linenr = 1; ctx->parent = NULL; ctx->cur_key = NULL; ctx->lasterr = NULL; ctx->top = NULL; if (!parse_tokens(ctx, json, end)) return NULL; return ctx->top; } /* * Render value as JSON string. */ static bool render_null(struct RenderState *rs, struct JsonValue *jv) { return mbuf_write(rs->dst, "null", 4); } static bool render_bool(struct RenderState *rs, struct JsonValue *jv) { if (jv->u.v_bool) return mbuf_write(rs->dst, "true", 4); return mbuf_write(rs->dst, "false", 5); } static bool render_int(struct RenderState *rs, struct JsonValue *jv) { char buf[NUMBER_BUF]; int len; len = snprintf(buf, sizeof(buf), "%" PRIi64, jv->u.v_int); if (len < 0 || len >= NUMBER_BUF) return false; return mbuf_write(rs->dst, buf, len); } static bool render_float(struct RenderState *rs, struct JsonValue *jv) { char buf[NUMBER_BUF + 2]; int len; len = dtostr_dot(buf, NUMBER_BUF, jv->u.v_float); if (len < 0 || len >= NUMBER_BUF) return false; if (!memchr(buf, '.', len) && !memchr(buf, 'e', len)) { buf[len++] = '.'; buf[len++] = '0'; } return mbuf_write(rs->dst, buf, len); } static bool escape_char(struct MBuf *dst, unsigned int c) { char ec; char buf[10]; /* start escape */ if (!mbuf_write_byte(dst, '\\')) return false; /* escape same char */ if (c == '"' || c == '\\') return mbuf_write_byte(dst, c); /* low-ascii mess */ switch (c) { case '\b': ec = 'b'; break; case '\f': ec = 'f'; break; case '\n': ec = 'n'; break; case '\r': ec = 'r'; break; case '\t': ec = 't'; break; default: snprintf(buf, sizeof(buf), "u%04x", c); return mbuf_write(dst, buf, 5); } return mbuf_write_byte(dst, ec); } static bool render_string(struct RenderState *rs, struct JsonValue *jv) { const char *s, *last; const char *val = get_cstring(jv); size_t len = jv->u.v_size; const char *end = val + len; unsigned int c; /* start quote */ if (!mbuf_write_byte(rs->dst, '"')) return false; for (s = last = val; s < end; s++) { if (*s == '"' || *s == '\\' || (unsigned char)*s < 0x20 || /* Valid in JSON, but not in JS: \u2028 - Line separator \u2029 - Paragraph separator */ ((unsigned char)s[0] == 0xE2 && (unsigned char)s[1] == 0x80 && ((unsigned char)s[2] == 0xA8 || (unsigned char)s[2] == 0xA9))) { /* flush */ if (last < s) { if (!mbuf_write(rs->dst, last, s - last)) return false; } if ((unsigned char)s[0] == 0xE2) { c = 0x2028 + ((unsigned char)s[2] - 0xA8); last = s + 3; } else { c = (unsigned char)*s; last = s + 1; } /* output escaped char */ if (!escape_char(rs->dst, c)) return false; } } /* flush */ if (last < s) { if (!mbuf_write(rs->dst, last, s - last)) return false; } /* final quote */ if (!mbuf_write_byte(rs->dst, '"')) return false; return true; } /* * Render complex values */ struct ElemWriterState { struct RenderState *rs; char sep; }; static bool list_elem_writer(void *arg, struct JsonValue *elem) { struct ElemWriterState *state = arg; if (state->sep && !mbuf_write_byte(state->rs->dst, state->sep)) return false; state->sep = ','; return render_any(state->rs, elem); } static bool render_list(struct RenderState *rs, struct JsonValue *list) { struct ElemWriterState state; state.rs = rs; state.sep = 0; if (!mbuf_write_byte(rs->dst, '[')) return false; if (!json_list_iter(list, list_elem_writer, &state)) return false; if (!mbuf_write_byte(rs->dst, ']')) return false; return true; } static bool dict_elem_writer(void *ctx, struct JsonValue *key, struct JsonValue *val) { struct ElemWriterState *state = ctx; if (state->sep && !mbuf_write_byte(state->rs->dst, state->sep)) return false; state->sep = ','; if (!render_any(state->rs, key)) return false; if (!mbuf_write_byte(state->rs->dst, ':')) return false; return render_any(state->rs, val); } static bool render_dict(struct RenderState *rs, struct JsonValue *dict) { struct ElemWriterState state; state.rs = rs; state.sep = 0; if (!mbuf_write_byte(rs->dst, '{')) return false; if (!json_dict_iter(dict, dict_elem_writer, &state)) return false; if (!mbuf_write_byte(rs->dst, '}')) return false; return true; } static bool render_invalid(struct RenderState *rs, struct JsonValue *jv) { return false; } /* * Public api */ static bool render_any(struct RenderState *rs, struct JsonValue *jv) { static const render_func_t rfunc_map[] = { render_invalid, render_null, render_bool, render_int, render_float, render_string, render_list, render_dict, }; return rfunc_map[get_type(jv)](rs, jv); } bool json_render(struct MBuf *dst, struct JsonValue *jv) { struct RenderState rs; rs.dst = dst; rs.options = 0; return render_any(&rs, jv); } /* * Examine single value */ enum JsonValueType json_value_type(struct JsonValue *jv) { return get_type(jv); } size_t json_value_size(struct JsonValue *jv) { if (has_type(jv, JSON_STRING) || has_type(jv, JSON_LIST) || has_type(jv, JSON_DICT)) return jv->u.v_size; return 0; } bool json_value_as_bool(struct JsonValue *jv, bool *dst_p) { if (!has_type(jv, JSON_BOOL)) return false; *dst_p = jv->u.v_bool; return true; } bool json_value_as_int(struct JsonValue *jv, int64_t *dst_p) { if (!has_type(jv, JSON_INT)) return false; *dst_p = jv->u.v_int; return true; } bool json_value_as_float(struct JsonValue *jv, double *dst_p) { if (!has_type(jv, JSON_FLOAT)) { if (has_type(jv, JSON_INT)) { *dst_p = jv->u.v_int; return true; } return false; } *dst_p = jv->u.v_float; return true; } bool json_value_as_string(struct JsonValue *jv, const char **dst_p, size_t *size_p) { if (!has_type(jv, JSON_STRING)) return false; *dst_p = get_cstring(jv); if (size_p) *size_p = jv->u.v_size; return true; } /* * Load value from dict. */ static int dict_getter(struct JsonValue *dict, const char *key, unsigned int klen, struct JsonValue **val_p, enum JsonValueType req_type, bool req_value) { struct JsonValue *val, *kjv; struct CBTree *tree; tree = get_dict_tree(dict); if (!tree) return false; kjv = cbtree_lookup(tree, key, klen); if (!kjv) { if (req_value) return false; *val_p = NULL; return true; } val = get_next(kjv); if (!req_value && json_value_is_null(val)) { *val_p = NULL; return true; } if (!has_type(val, req_type)) return false; *val_p = val; return true; } bool json_dict_get_value(struct JsonValue *dict, const char *key, struct JsonValue **val_p) { struct CBTree *tree; struct JsonValue *kjv; size_t klen; tree = get_dict_tree(dict); if (!tree) return false; klen = strlen(key); kjv = cbtree_lookup(tree, key, klen); if (!kjv) return false; *val_p = get_next(kjv); return true; } bool json_dict_is_null(struct JsonValue *dict, const char *key) { struct JsonValue *val; if (!json_dict_get_value(dict, key, &val)) return true; return has_type(val, JSON_NULL); } bool json_dict_get_bool(struct JsonValue *dict, const char *key, bool *dst_p) { struct JsonValue *val; if (!dict_getter(dict, key, strlen(key), &val, JSON_BOOL, true)) return false; return json_value_as_bool(val, dst_p); } bool json_dict_get_int(struct JsonValue *dict, const char *key, int64_t *dst_p) { struct JsonValue *val; if (!dict_getter(dict, key, strlen(key), &val, JSON_INT, true)) return false; return json_value_as_int(val, dst_p); } bool json_dict_get_float(struct JsonValue *dict, const char *key, double *dst_p) { struct JsonValue *val; if (!dict_getter(dict, key, strlen(key), &val, JSON_FLOAT, true)) return false; return json_value_as_float(val, dst_p); } bool json_dict_get_string(struct JsonValue *dict, const char *key, const char **dst_p, size_t *len_p) { struct JsonValue *val; if (!dict_getter(dict, key, strlen(key), &val, JSON_STRING, true)) return false; return json_value_as_string(val, dst_p, len_p); } bool json_dict_get_list(struct JsonValue *dict, const char *key, struct JsonValue **dst_p) { return dict_getter(dict, key, strlen(key), dst_p, JSON_LIST, true); } bool json_dict_get_dict(struct JsonValue *dict, const char *key, struct JsonValue **dst_p) { return dict_getter(dict, key, strlen(key), dst_p, JSON_DICT, true); } /* * Load optional dict element. */ bool json_dict_get_opt_bool(struct JsonValue *dict, const char *key, bool *dst_p) { struct JsonValue *val; if (!dict_getter(dict, key, strlen(key), &val, JSON_BOOL, false)) return false; return !val || json_value_as_bool(val, dst_p); } bool json_dict_get_opt_int(struct JsonValue *dict, const char *key, int64_t *dst_p) { struct JsonValue *val; if (!dict_getter(dict, key, strlen(key), &val, JSON_INT, false)) return false; return !val || json_value_as_int(val, dst_p); } bool json_dict_get_opt_float(struct JsonValue *dict, const char *key, double *dst_p) { struct JsonValue *val; if (!dict_getter(dict, key, strlen(key), &val, JSON_FLOAT, false)) return false; return !val || json_value_as_float(val, dst_p); } bool json_dict_get_opt_string(struct JsonValue *dict, const char *key, const char **dst_p, size_t *len_p) { struct JsonValue *val; if (!dict_getter(dict, key, strlen(key), &val, JSON_STRING, false)) return false; return !val || json_value_as_string(val, dst_p, len_p); } bool json_dict_get_opt_list(struct JsonValue *dict, const char *key, struct JsonValue **dst_p) { struct JsonValue *val; if (!dict_getter(dict, key, strlen(key), &val, JSON_LIST, false)) return false; if (val) *dst_p = val; return true; } bool json_dict_get_opt_dict(struct JsonValue *dict, const char *key, struct JsonValue **dst_p) { struct JsonValue *val; if (!dict_getter(dict, key, strlen(key), &val, JSON_DICT, false)) return false; if (val) *dst_p = val; return true; } /* * Load value from list. */ bool json_list_get_value(struct JsonValue *list, size_t index, struct JsonValue **val_p) { struct JsonValue *val; struct ValueList *vlist; size_t i; vlist = get_list_vlist(list); if (!vlist) return false; if (index >= list->u.v_size) return false; if (!vlist->array && list->u.v_size > 10) prepare_array(list); /* direct fetch */ if (vlist->array) { *val_p = vlist->array[index]; return true; } /* walk */ val = vlist->first; for (i = 0; val; i++) { if (i == index) { *val_p = val; return true; } val = get_next(val); } return false; } bool json_list_is_null(struct JsonValue *list, size_t n) { struct JsonValue *jv; if (!json_list_get_value(list, n, &jv)) return true; return has_type(jv, JSON_NULL); } bool json_list_get_bool(struct JsonValue *list, size_t index, bool *val_p) { struct JsonValue *jv; if (!json_list_get_value(list, index, &jv)) return false; return json_value_as_bool(jv, val_p); } bool json_list_get_int(struct JsonValue *list, size_t index, int64_t *val_p) { struct JsonValue *jv; if (!json_list_get_value(list, index, &jv)) return false; return json_value_as_int(jv, val_p); } bool json_list_get_float(struct JsonValue *list, size_t index, double *val_p) { struct JsonValue *jv; if (!json_list_get_value(list, index, &jv)) return false; return json_value_as_float(jv, val_p); } bool json_list_get_string(struct JsonValue *list, size_t index, const char **val_p, size_t *len_p) { struct JsonValue *jv; if (!json_list_get_value(list, index, &jv)) return false; return json_value_as_string(jv, val_p, len_p); } bool json_list_get_list(struct JsonValue *list, size_t index, struct JsonValue **val_p) { struct JsonValue *jv; if (!json_list_get_value(list, index, &jv)) return false; if (!has_type(jv, JSON_LIST)) return false; *val_p = jv; return true; } bool json_list_get_dict(struct JsonValue *list, size_t index, struct JsonValue **val_p) { struct JsonValue *jv; if (!json_list_get_value(list, index, &jv)) return false; if (!has_type(jv, JSON_DICT)) return false; *val_p = jv; return true; } /* * Iterate over list and dict values. */ struct DictIterState { json_dict_iter_callback_f cb_func; void *cb_arg; }; static bool dict_iter_helper(void *arg, void *jv) { struct DictIterState *state = arg; struct JsonValue *key = jv; struct JsonValue *val = get_next(key); return state->cb_func(state->cb_arg, key, val); } bool json_dict_iter(struct JsonValue *dict, json_dict_iter_callback_f cb_func, void *cb_arg) { struct DictIterState state; struct CBTree *tree; tree = get_dict_tree(dict); if (!tree) return false; state.cb_func = cb_func; state.cb_arg = cb_arg; return cbtree_walk(tree, dict_iter_helper, &state); } bool json_list_iter(struct JsonValue *list, json_list_iter_callback_f cb_func, void *cb_arg) { struct JsonValue *elem; struct ValueList *vlist; vlist = get_list_vlist(list); if (!vlist) return false; for (elem = vlist->first; elem; elem = get_next(elem)) { if (!cb_func(cb_arg, elem)) return false; } return true; } /* * Create new values. */ struct JsonValue *json_new_null(struct JsonContext *ctx) { return mk_value(ctx, JSON_NULL, 0, false); } struct JsonValue *json_new_bool(struct JsonContext *ctx, bool val) { struct JsonValue *jv; jv = mk_value(ctx, JSON_BOOL, 0, false); if (jv) jv->u.v_bool = val; return jv; } struct JsonValue *json_new_int(struct JsonContext *ctx, int64_t val) { struct JsonValue *jv; if (val < JSON_MININT || val > JSON_MAXINT) { errno = ERANGE; return NULL; } jv = mk_value(ctx, JSON_INT, 0, false); if (jv) jv->u.v_int = val; return jv; } struct JsonValue *json_new_float(struct JsonContext *ctx, double val) { struct JsonValue *jv; /* check if value survives JSON roundtrip */ if (!isfinite(val)) return false; jv = mk_value(ctx, JSON_FLOAT, 0, false); if (jv) jv->u.v_float = val; return jv; } struct JsonValue *json_new_string(struct JsonContext *ctx, const char *val) { struct JsonValue *jv; size_t len; len = strlen(val); if (!utf8_validate_string(val, val + len)) return NULL; jv = mk_value(ctx, JSON_STRING, len + 1, false); if (jv) { memcpy(get_cstring(jv), val, len + 1); jv->u.v_size = len; } return jv; } struct JsonValue *json_new_list(struct JsonContext *ctx) { return mk_value(ctx, JSON_LIST, LIST_EXTRA, false); } struct JsonValue *json_new_dict(struct JsonContext *ctx) { return mk_value(ctx, JSON_DICT, DICT_EXTRA, false); } /* * Add to containers */ bool json_list_append(struct JsonValue *list, struct JsonValue *val) { if (!val) return false; if (!has_type(list, JSON_LIST)) return false; if (!is_unattached(val)) return false; set_parent(val, list); set_next(val, NULL); real_list_append(list, val); return true; } bool json_list_append_null(struct JsonValue *list) { struct JsonValue *v; v = json_new_null(get_context(list)); return json_list_append(list, v); } bool json_list_append_bool(struct JsonValue *list, bool val) { struct JsonValue *v; v = json_new_bool(get_context(list), val); return json_list_append(list, v); } bool json_list_append_int(struct JsonValue *list, int64_t val) { struct JsonValue *v; v = json_new_int(get_context(list), val); return json_list_append(list, v); } bool json_list_append_float(struct JsonValue *list, double val) { struct JsonValue *v; v = json_new_float(get_context(list), val); return json_list_append(list, v); } bool json_list_append_string(struct JsonValue *list, const char *val) { struct JsonValue *v; v = json_new_string(get_context(list), val); return json_list_append(list, v); } bool json_dict_put(struct JsonValue *dict, const char *key, struct JsonValue *val) { struct JsonValue *kjv; struct JsonContainer *c; if (!key || !val) return false; if (!has_type(dict, JSON_DICT)) return false; if (!is_unattached(val)) return false; c = get_container(dict); kjv = json_new_string(c->c_ctx, key); if (!kjv) return false; if (!real_dict_add_key(c->c_ctx, dict, kjv)) return false; set_next(kjv, val); set_next(val, NULL); set_parent(val, dict); return true; } bool json_dict_put_null(struct JsonValue *dict, const char *key) { struct JsonValue *v; v = json_new_null(get_context(dict)); return json_dict_put(dict, key, v); } bool json_dict_put_bool(struct JsonValue *dict, const char *key, bool val) { struct JsonValue *v; v = json_new_bool(get_context(dict), val); return json_dict_put(dict, key, v); } bool json_dict_put_int(struct JsonValue *dict, const char *key, int64_t val) { struct JsonValue *v; v = json_new_int(get_context(dict), val); return json_dict_put(dict, key, v); } bool json_dict_put_float(struct JsonValue *dict, const char *key, double val) { struct JsonValue *v; v = json_new_float(get_context(dict), val); return json_dict_put(dict, key, v); } bool json_dict_put_string(struct JsonValue *dict, const char *key, const char *val) { struct JsonValue *v; v = json_new_string(get_context(dict), val); return json_dict_put(dict, key, v); } /* * Main context management */ struct JsonContext *json_new_context(const void *cx, size_t initial_mem) { struct JsonContext *ctx; CxMem *pool; pool = cx_new_pool(cx, initial_mem, 8); if (!pool) return NULL; ctx = cx_alloc0(pool, sizeof(*ctx)); if (!ctx) { cx_destroy(pool); return NULL; } ctx->pool = pool; return ctx; } void json_free_context(struct JsonContext *ctx) { if (ctx) { CxMem *pool = ctx->pool; memset(ctx, 0, sizeof(*ctx)); cx_destroy(pool); } } const char *json_strerror(struct JsonContext *ctx) { return ctx->lasterr; } void json_set_options(struct JsonContext *ctx, unsigned int options) { ctx->options = options; }
$js.module({ prerequisite:[ '/{$jshome}/modules/splice.module.extensions.js' ], imports:[ { Inheritance : '/{$jshome}/modules/splice.inheritance.js' }, {'SpliceJS.UI':'../splice.ui.js'}, 'splice.controls.pageloader.html' ], definition:function(){ var scope = this; var imports = scope.imports ; var Class = imports.Inheritance.Class , UIControl = imports.SpliceJS.UI.UIControl ; var PageLoader = Class(function PageLoaderController(){ this.base(); }).extend(UIControl); scope.exports( PageLoader ); } })
<h1><?=$title?></h1> <h5>Ordered by Points</h5> <?php foreach ($users as $user) : ?> <div class="mini-profile left"> <img class="gravatar left" src="<?= $this->mzHelpers->get_gravatar($user->email, 128); ?>" alt=""> <div class="info"> <a href="<?= $this->url->create('users/id/' . $user->id ); ?>"><?= $user->username ?></a> <br> Points: <?= $user->points ?> </div> </div> <?php endforeach; ?>
b'Calculate (49 - (52 - 3)) + 2 + 0.\n'
b'13 + (-8 - (-7 + -11) - 8)\n'
b'-14 - (-13 - (0 - -4))\n'
b'-20 + (0 - (-1 - (-6 + 14)))\n'
b'Calculate 3 + -10 - -4 - (-60 - -51).\n'
var PassThrough = require('stream').PassThrough describe('Object Streams', function () { it('should be supported', function (done) { var app = koala() app.use(function* (next) { var body = this.body = new PassThrough({ objectMode: true }) body.write({ message: 'a' }) body.write({ message: 'b' }) body.end() }) request(app.listen()) .get('/') .expect(200) .expect([{ message: 'a' }, { message: 'b' }], done) }) })