content
stringlengths
7
1.05M
sec = { # Security 1102: {"Descr": "The audit log was cleared", "Provider": "Microsoft-Windows-Eventlog", "SubjectUserSid": "SID", "SubjectUserName": "Username", "SubjectDomainName": "Domain", "SubjectLogonId": "LogonId"}, 4616: {"Descr": "The system time was changed", "Provider": "Microsoft-Windows-Security-Auditing", "SubjectUserSid": "SID", "SubjectUserName": "Username", "SubjectDomainName": "Domain", "SubjectLogonId": "LogonId", "PreviousTime": "PreviousTime", "NewTime": "NewTime", "ProcessId": "ProcessId", # Win 7+ "ProcessName": "ProcessPath"}, # Win 7+ 4624: {"Descr": "An account was successfully logged on", "Provider": "Microsoft-Windows-Security-Auditing", "SubjectUserSid": "SID", "SubjectUserName": "Username", "SubjectDomainName": "Domain", "SubjectLogonId": "LogonId", "TargetUserSid": "TargetSID", "TargetUserName": "TargetUsername", "TargetDomainName": "TargetDomain", "TargetLogonId": "TargetLogonId", "LogonType": "+LogonType", "WorkstationName": "WorkstationName", "LogonGuid": "LogonGUID", "TransmittedServices": "TransmittedServices", "IpAddress": "IP", "IpPort": "Port", "ProcessId": "ProcessId", "ProcessName": "ProcessPath", "AuthenticationPackageName": "AuthenticationPackage", "LogonProcessName": "LogonProcess", "KeyLength": "KeyLength", "RestrictedAdminMode": "RestrictedAdminMode", # Win 10+ "ElevatedToken": "ElevatedToken", # Win 10+ "TargetOutboundUserName": "TargetOutboundUsername", "TargetOutboundDomainName": "TargetOutboundDomain"}, 4625: {"Descr": "An account failed to log on", "Provider": "Microsoft-Windows-Security-Auditing", "SubjectUserSid": "SID", "SubjectUserName": "Username", "SubjectDomainName": "Domain", "SubjectLogonId": "LogonId", "TargetUserSid": "TargetSID", "TargetUserName": "TargetUsername", "TargetDomainName": "TargetDomain", "LogonType": "+LogonType", "WorkstationName": "WorkstationName", "IpAddress": "IP", "IpPort": "Port", "LogonProcessName": "LogonProcessName", "Status": "+Status", "FailureReason": "FailureReason", # %% format "SubStatus": "SubStatus", "ProcessId": "ProcessId", "ProcessName": "ProcessPath"}, 4627: {"Descr": "Group membership information", "Provider": "Microsoft-Windows-Security-Auditing", "SubjectUserSid": "SID", "SubjectUserName": "Username", "SubjectDomainName": "Domain", "SubjectLogonId": "LogonId", "TargetUserSid": "TargetSID", "TargetUserName": "TargetUsername", "TargetDomainName": "TargetDomain", "LogonType": "+LogonType", "GroupMembership": "GroupMembership"}, # to convert 4634: {"Descr": "An account was logged off", "Provider": "Microsoft-Windows-Security-Auditing", "TargetUserSid": "TargetSID", "TargetUserName": "TargetUsername", "TargetDomainName": "TargetDomain", "TargetLogonId": "TargetLogonId", "LogonType": "+LogonType"}, 4647: {"Descr": "User initiated logoff", "Provider": "Microsoft-Windows-Security-Auditing", "TargetUserSid": "TargetSID", "TargetUserName": "TargetUsername", "TargetDomainName": "TargetDomain", "TargetLogonId": "TargetLogonId"}, 4648: {"Descr": "A logon was attempted using explicit credentials", "Provider": "Microsoft-Windows-Security-Auditing", "SubjectUserSid": "SID", "SubjectUserName": "Username", "SubjectDomainName": "Domain", "SubjectLogonId": "LogonId", "LogonGuid": "LogonGUID", "TargetUserName": "TargetUsername", "TargetDomainName": "TargetDomain", "TargetLogonGuid": "TargetLogonGuid", "TargetServerName": "TargetServerName", "TargetInfo": "TargetInfo", "IpAddress": "IP", "IpPort": "Port", "ProcessId": "ProcessId", "ProcessName": "ProcessPath"}, 4657: {"Descr": "A registry value was modified", "Provider": "Microsoft-Windows-Security-Auditing", "SubjectUserSid": "SID", "SubjectUserName": "Username", "SubjectDomainName": "Domain", "SubjectLogonId": "LogonId", "ObjectName": "RegKey", "ObjectValueName": "RegValue", "OperationType": "OperationType", "OldValueType": "OldValueType", "OldValue": "OldValue", "NewValueType": "NewValueType", "NewValue": "NewValue", "ProcessId": "ProcessId", "ProcessName": "ProcessPath"}, 4661: {"Descr": "A handle to an object was requested", "Provider": "Microsoft-Windows-Security-Auditing", "SubjectUserSid": "SID", "SubjectUserName": "Username", "SubjectDomainName": "Domain", "SubjectLogonId": "LogonId", "ObjectServer": "ObjectServer", "ObjectType": "ObjectType", "ObjectName": "ObjectName", "HandleId": "HandleId", "TransactionId": "TransactionId", "AccessList": "AccessList", # %% format "AccessMask": "AccessMask", # alternate representation of AccessList "PrivilegeList": "PrivilegeList", "Properties": "Properties", "RestrictedSidCount": "RestrictedSidCount", "ProcessId": "ProcessId", "ProcessName": "ProcessPath"}, 4662: {"Descr": "An operation was performed on an object", "Provider": "Microsoft-Windows-Security-Auditing", "SubjectUserSid": "SID", "SubjectUserName": "Username", "SubjectDomainName": "Domain", "SubjectLogonId": "LogonId", "ObjectServer": "ObjectServer", "ObjectType": "ObjectType", "ObjectName": "ObjectName", "OperationType": "OperationType", "HandleId": "HandleId", "AccessList": "AccessList", # %% format "AccessMask": "AccessMask", # alternate representation of AccessList "Properties": "Properties"}, 4663: {"Descr": "An attempt was made to access an object", "Provider": "Microsoft-Windows-Security-Auditing", "SubjectUserSid": "SID", "SubjectUserName": "Username", "SubjectDomainName": "Domain", "SubjectLogonId": "LogonId", "ObjectServer": "ObjectServer", "ObjectType": "ObjectType", "ObjectName": "ObjectName", "HandleId": "HandleId", "AccessList": "AccessList", # %% format "AccessMask": "AccessMask", # alternate representation of AccessList "ProcessId": "ProcessId", "ProcessName": "ProcessPath", "ResourceAttributes": "ResourceAttributes"}, 4672: {"Descr": "Special privileges assigned to new logon", "Provider": "Microsoft-Windows-Security-Auditing", "SubjectUserSid": "TargetSID", "SubjectUserName": "TargetUsername", "SubjectDomainName": "TargetDomain", "SubjectLogonId": "TargetLogonId", "PrivilegeList": "PrivilegeList"}, 4673: {"Descr": "A privileged service was called", "Provider": "Microsoft-Windows-Security-Auditing", "SubjectUserSid": "SID", "SubjectUserName": "Username", "SubjectDomainName": "Domain", "SubjectLogonId": "LogonId", "ObjectServer": "ObjectServer", "Service": "Service", "PrivilegeList": "PrivilegeList", "ProcessId": "ProcessId", "ProcessName": "ProcessPath"}, 4688: {"Descr": "A new process has been created", "Provider": "Microsoft-Windows-Security-Auditing", "SubjectUserSid": "SID", "SubjectUserName": "Username", "SubjectDomainName": "Domain", "SubjectLogonId": "LogonId", "NewProcessId": "NewProcessId", "NewProcessName": "NewProcessPath", "TokenElevationType": "TokenElevationType", # %% format "CommandLine": "Command", # Win 8.1+ "ProcessId": "ProcessId", # Win 10+ "ParentProcessName": "ProcessPath", "MandatoryLabel": "+MandatoryLabel", "TargetUserSid": "TargetSID", "TargetUserName": "TargetUsername", "TargetDomainName": "TargetDomain", "TargetLogonId": "TargetLogonId"}, 4697: {"Descr": "A service was installed in the system", "Provider": "Microsoft-Windows-Security-Auditing", "SubjectUserSid": "SID", "SubjectUserName": "Username", "SubjectDomainName": "Domain", "SubjectLogonId": "LogonId", "ServiceName": "ServiceName", "ServiceFileName": "ServicePath", "ServiceType": "+ServiceType", "ServiceStartType": "+ServiceStartType", "ServiceAccount": "ServiceAccount"}, 4698: {"Descr": "A scheduled task was created", "Provider": "Microsoft-Windows-Security-Auditing", "SubjectUserSid": "SID", "SubjectUserName": "Username", "SubjectDomainName": "Domain", "SubjectLogonId": "LogonId", "TaskName": "TaskName", "TaskContent": "TaskContent"}, 4699: {"Descr": "A scheduled task was deleted", "Provider": "Microsoft-Windows-Security-Auditing", "SubjectUserSid": "SID", "SubjectUserName": "Username", "SubjectDomainName": "Domain", "SubjectLogonId": "LogonId", "TaskName": "TaskName", "TaskContent": "TaskContent"}, 4700: {"Descr": "A scheduled task was enabled", "Provider": "Microsoft-Windows-Security-Auditing", "SubjectUserSid": "SID", "SubjectUserName": "Username", "SubjectDomainName": "Domain", "SubjectLogonId": "LogonId", "TaskName": "TaskName", "TaskContent": "TaskContent"}, 4701: {"Descr": "A scheduled task was disabled", "Provider": "Microsoft-Windows-Security-Auditing", "SubjectUserSid": "SID", "SubjectUserName": "Username", "SubjectDomainName": "Domain", "SubjectLogonId": "LogonId", "TaskName": "TaskName", "TaskContent": "TaskContent"}, 4702: {"Descr": "A scheduled task was updated", "Provider": "Microsoft-Windows-Security-Auditing", "SubjectUserSid": "SID", "SubjectUserName": "Username", "SubjectDomainName": "Domain", "SubjectLogonId": "LogonId", "TaskName": "TaskName", "TaskContentNew": "TaskContent"}, 4717: {"Descr": "System security access was granted to an account", "Provider": "Microsoft-Windows-Security-Auditing", "SubjectUserSid": "SID", "SubjectUserName": "Username", "SubjectDomainName": "Domain", "SubjectLogonId": "LogonId", "TargetSid": "TargetSid", "AccessGranted": "AccessGranted"}, 4719: {"Descr": "System audit policy was changed", "Provider": "Microsoft-Windows-Security-Auditing", "SubjectUserSid": "SID", "SubjectUserName": "Username", "SubjectDomainName": "Domain", "SubjectLogonId": "LogonId", "CategoryId": "CategoryId", # %% format "SubcategoryId": "SubcategoryId", # %% format "SubcategoryGuid": "SubcategoryGuid", # %% format "AuditPolicyChanges": "AuditPolicyChanges"}, # %% format (multiple, joined with ', ') 4720: {"Descr": "A user account was created", "Provider": "Microsoft-Windows-Security-Auditing", "SubjectUserSid": "SID", "SubjectUserName": "Username", "SubjectDomainName": "Domain", "SubjectLogonId": "LogonId", "TargetUserSid": "TargetSID", "TargetUserName": "TargetUsername", "TargetDomainName": "TargetDomain", "PrivilegeList": "PrivilegeList", "SamAccountName": "SamAccountName", "DisplayName": "DisplayName", "UserPrincipalName": "UserPrincipalName", "HomeDirectory": "HomeDirectory", "HomePath": "HomePath", "ScriptPath": "ScriptPath", "ProfilePath": "ProfilePath", "UserWorkstations": "UserWorkstations", "PasswordLastSet": "PasswordLastSet", "AccountExpires": "AccountExpires", "PrimaryGroupId": "PrimaryGroupId", "AllowedToDelegateTo": "AllowedToDelegateTo", "OldUacValue": "+OldUacFlags", "SidHistory": "SIDHistory", "LogonHours": "LogonHours", "UserAccountControl": "UserAccountControl"}, # %% format (multiple, joined with ' ') 4722: {"Descr": "A user account was enabled", "Provider": "Microsoft-Windows-Security-Auditing", "SubjectUserSid": "SID", "SubjectUserName": "Username", "SubjectDomainName": "Domain", "SubjectLogonId": "LogonId", "TargetSid": "TargetSID", "TargetUserName": "TargetUsername", "TargetDomainName": "TargetDomain"}, 4723: {"Descr": "An attempt was made to change an account's password", "Provider": "Microsoft-Windows-Security-Auditing", "SubjectUserSid": "SID", "SubjectUserName": "Username", "SubjectDomainName": "Domain", "SubjectLogonId": "LogonId", "TargetSid": "TargetSID", "TargetUserName": "TargetUsername", "TargetDomainName": "TargetDomain", "PrivilegeList": "PrivilegeList"}, 4724: {"Descr": "An attempt to was made to reset an account's password", "Provider": "Microsoft-Windows-Security-Auditing", "SubjectUserSid": "SID", "SubjectUserName": "Username", "SubjectDomainName": "Domain", "SubjectLogonId": "LogonId", "TargetSid": "TargetSID", "TargetUserName": "TargetUsername", "TargetDomainName": "TargetDomain"}, 4725: {"Descr": "A user account was disabled", "Provider": "Microsoft-Windows-Security-Auditing", "SubjectUserSid": "SID", "SubjectUserName": "Username", "SubjectDomainName": "Domain", "SubjectLogonId": "LogonId", "TargetSid": "TargetSID", "TargetUserName": "TargetUsername", "TargetDomainName": "TargetDomain"}, 4726: {"Descr": "A user account was deleted", "Provider": "Microsoft-Windows-Security-Auditing", "SubjectUserSid": "SID", "SubjectUserName": "Username", "SubjectDomainName": "Domain", "SubjectLogonId": "LogonId", "TargetSid": "TargetSID", "TargetUserName": "TargetUsername", "TargetDomainName": "TargetDomain"}, 4728: {"Descr": "A member was added to a security-enabled global group", "Provider": "Microsoft-Windows-Security-Auditing", "SubjectUserSid": "SID", "SubjectUserName": "Username", "SubjectDomainName": "Domain", "SubjectLogonId": "LogonId", "MemberSid": "TargetSID", "MemberName": "TargetUsername", "TargetSid": "TargetGroupSID", "TargetUserName": "TargetGroup", "TargetDomainName": "TargetDomain", "PrivilegeList": "PrivilegeList"}, 4732: {"Descr": "A member was added to a security-enabled local group", "Provider": "Microsoft-Windows-Security-Auditing", "SubjectUserSid": "SID", "SubjectUserName": "Username", "SubjectDomainName": "Domain", "SubjectLogonId": "LogonId", "MemberSid": "TargetSID", "MemberName": "TargetUsername", "TargetSid": "TargetGroupSID", "TargetUserName": "TargetGroup", "TargetDomainName": "TargetDomain", "PrivilegeList": "PrivilegeList"}, 4738: {"Descr": "A user account was changed", # non-changed values are - "Provider": "Microsoft-Windows-Security-Auditing", "SubjectUserSid": "SID", "SubjectUserName": "Username", "SubjectDomainName": "Domain", "SubjectLogonId": "LogonId", "TargetSid": "TargetSID", "TargetUserName": "TargetUsername", "TargetDomainName": "TargetDomain", "PrivilegeList": "PrivilegeList", "SamAccountName": "SamAccountName", "DisplayName": "DisplayName", "UserPrincipalName": "UserPrincipalName", "HomeDirectory": "HomeDirectory", "HomePath": "HomePath", "ScriptPath": "ScriptPath", "ProfilePath": "ProfilePath", "UserWorkstations": "UserWorkstations", "PasswordLastSet": "PasswordLastSet", "AccountExpires": "AccountExpires", "PrimaryGroupId": "PrimaryGroupId", "AllowedToDelegateTo": "AllowedToDelegateTo", "OldUacValue": "+OldUacFlags", "NewUacValue": "+NewUacFlags", "UserParameters": "UserParameters", "SidHistory": "SIDHistory", "LogonHours": "LogonHours", "UserAccountControl": "UserAccountControl"}, # %% format 4740: {"Descr": "A user account was locked out", "Provider": "Microsoft-Windows-Security-Auditing", "SubjectUserSid": "SID", "SubjectUserName": "Username", "SubjectDomainName": "Domain", "SubjectLogonId": "LogonId", "TargetSid": "TargetSID", "TargetUserName": "TargetUsername", "TargetDomainName": "TargetDomain"}, 4741: {"Descr": "A computer account was created", "Provider": "Microsoft-Windows-Security-Auditing", "SubjectUserSid": "SID", "SubjectUserName": "Username", "SubjectDomainName": "Domain", "SubjectLogonId": "LogonId", "TargetSid": "TargetSID", "TargetUserName": "TargetUsername", "TargetDomainName": "TargetDomain", "PrivilegeList": "PrivilegeList", "SamAccountName": "SamAccountName", "DisplayName": "DisplayName", "UserPrincipalName": "UserPrincipalName", "HomeDirectory": "HomeDirectory", "HomePath": "HomePath", "ScriptPath": "ScriptPath", "ProfilePath": "ProfilePath", "UserWorkstations": "UserWorkstations", "PasswordLastSet": "PasswordLastSet", "AccountExpires": "AccountExpires", "PrimaryGroupId": "PrimaryGroupId", "AllowedToDelegateTo": "AllowedToDelegateTo", "OldUacValue": "+OldUacFlags", "NewUacValue": "+NewUacFlags", "UserParameters": "UserParameters", "SidHistory": "SIDHistory", "LogonHours": "LogonHours", "UserAccountControl": "UserAccountControl", # %% format "DnsHostName": "Hostname", "ServicePrincipalNames": "SPNs"}, 4742: {"Descr": "A computer account was changed", "Provider": "Microsoft-Windows-Security-Auditing", "ComputerAccountChange": "ComputerAccountChange", "SubjectUserSid": "SID", "SubjectUserName": "Username", "SubjectDomainName": "Domain", "SubjectLogonId": "LogonId", "TargetSid": "TargetSID", "TargetUserName": "TargetUsername", "TargetDomainName": "TargetDomain", "PrivilegeList": "PrivilegeList", "SamAccountName": "SamAccountName", "DisplayName": "DisplayName", "UserPrincipalName": "UserPrincipalName", "HomeDirectory": "HomeDirectory", "HomePath": "HomePath", "ScriptPath": "ScriptPath", "ProfilePath": "ProfilePath", "UserWorkstations": "UserWorkstations", "PasswordLastSet": "PasswordLastSet", "AccountExpires": "AccountExpires", "PrimaryGroupId": "PrimaryGroupId", "AllowedToDelegateTo": "AllowedToDelegateTo", "OldUacValue": "+OldUacFlags", "NewUacValue": "+NewUacFlags", "UserParameters": "UserParameters", "SidHistory": "SIDHistory", "LogonHours": "LogonHours", "UserAccountControl": "UserAccountControl", # %% format "DnsHostName": "Hostname", "ServicePrincipalNames": "SPNs"}, 4743: {"Descr": "A computer account was deleted", "Provider": "Microsoft-Windows-Security-Auditing", "SubjectUserSid": "SID", "SubjectUserName": "Username", "SubjectDomainName": "Domain", "SubjectLogonId": "LogonId", "TargetSid": "TargetSID", "TargetUserName": "TargetUsername", "TargetDomainName": "TargetDomain", "PrivilegeList": "PrivilegeList"}, 4746: {"Descr": "A member was added to a security-disabled local group", "Provider": "Microsoft-Windows-Security-Auditing", "SubjectUserSid": "SID", "SubjectUserName": "Username", "SubjectDomainName": "Domain", "SubjectLogonId": "LogonId", "MemberSid": "TargetSID", "MemberName": "TargetUsername", "TargetSid": "TargetGroupSID", "TargetUserName": "TargetGroup", "TargetDomainName": "TargetDomain", "PrivilegeList": "PrivilegeList"}, 4756: {"Descr": "A member was added to a security-enabled universal group", "Provider": "Microsoft-Windows-Security-Auditing", "SubjectUserSid": "SID", "SubjectUserName": "Username", "SubjectDomainName": "Domain", "SubjectLogonId": "LogonId", "MemberSid": "TargetSID", "MemberName": "TargetUsername", "TargetSid": "TargetGroupSID", "TargetUserName": "TargetGroup", "TargetDomainName": "TargetDomain", "PrivilegeList": "PrivilegeList"}, 4761: {"Descr": "A member was added to a security-disabled universal group", "Provider": "Microsoft-Windows-Security-Auditing", "SubjectUserSid": "SID", "SubjectUserName": "Username", "SubjectDomainName": "Domain", "SubjectLogonId": "LogonId", "MemberSid": "TargetSID", "MemberName": "TargetUsername", "TargetSid": "TargetGroupSID", "TargetUserName": "TargetGroup", "TargetDomainName": "TargetDomain", "PrivilegeList": "PrivilegeList"}, 4767: {"Descr": "A user account was unlocked", "Provider": "Microsoft-Windows-Security-Auditing", "SubjectUserSid": "SID", "SubjectUserName": "Username", "SubjectDomainName": "Domain", "SubjectLogonId": "LogonId", "TargetSid": "TargetGroupSID", "TargetUserName": "TargetGroup", "TargetDomainName": "TargetDomain"}, 4768: {"Descr": "A Kerberos authentication ticket (TGT) was requested", "Provider": "Microsoft-Windows-Security-Auditing", "TargetUserSid": "TargetSID", "TargetUserName": "TargetUsername", "TargetDomainName": "TargetDomain", "ServiceSid": "ServiceSID", "ServiceName": "ServiceName", "TicketOptions": "+TicketOptions", "Status": "+ResultCode", "TicketEncryptionType": "+TicketEncryptionType", "PreAuthType": "+PreAuthType", "IpAddress": "IP", "IpPort": "Port", "CertIssuerName": "CertIssuer", "CertSerialNumber": "CertSerialNumber", "CertThumbprint": "CertThumbprint"}, 4769: {"Descr": "A Kerberos service ticket was requested", "Provider": "Microsoft-Windows-Security-Auditing", "TargetUserName": "TargetUsername", "TargetDomainName": "TargetDomain", "ServiceSid": "ServiceSID", "ServiceName": "ServiceName", "TicketOptions": "+TicketOptions", "Status": "+ResultCode", "TicketEncryptionType": "+TicketEncryptionType", "PreAuthType": "+PreAuthType", "IpAddress": "IP", "IpPort": "Port", "LogonGuid": "LogonGUID", "TransmittedServices": "TransmittedServices"}, 4771: {"Descr": "Kerberos pre-authentication failed", "Provider": "Microsoft-Windows-Security-Auditing", "TargetUserName": "TargetUsername", "TargetSid": "TargetSID", "ServiceName": "ServiceName", "TicketOptions": "+TicketOptions", "Status": "+ResultCode", "PreAuthType": "+PreAuthType", "IpAddress": "IP", "IpPort": "Port"}, 4776: {"Descr": "The computer attempted to validate the credentials for an account", "Provider": "Microsoft-Windows-Security-Auditing", "TargetUserName": "TargetUsername", "Workstation": "WorkstationName", "PackageName": "AuthenticationPackage", "Status": "+ResultCode"}, 4778: {"Descr": "A session was reconnected to a Window Station", "Provider": "Microsoft-Windows-Security-Auditing", "AccountName": "TargetUsername", "AccountDomain": "TargetDomain", "LogonID": "TargetLogonId", "SessionName": "SessionName", "ClientName": "WorkstationName", "ClientAddress": "IP", "PackageName": "AuthenticationPackage"}, 4779: {"Descr": "A session was disconnected from a Window Station", "Provider": "Microsoft-Windows-Security-Auditing", "AccountName": "TargetUsername", "AccountDomain": "TargetDomain", "LogonID": "TargetLogonId", "SessionName": "SessionName", "ClientName": "WorkstationName", "ClientAddress": "IP"}, 4781: {"Descr": "The name of an account was changed", "Provider": "Microsoft-Windows-Security-Auditing", "SubjectUserSid": "SID", "SubjectUserName": "Username", "SubjectDomainName": "Domain", "SubjectLogonId": "LogonId", "OldTargetUserName": "OldTargetUsername", "NewTargetUserName": "NewTargetUsername", "TargetDomainName": "TargetDomain", "TargetSid": "TargetSID", "PrivilegeList": "PrivilegeList"}, 4798: {"Descr": "A user's local group membership was enumerated", "Provider": "Microsoft-Windows-Security-Auditing", "SubjectUserSid": "SID", "SubjectUserName": "Username", "SubjectDomainName": "Domain", "SubjectLogonId": "LogonId", "TargetUserName": "TargetUsername", "TargetDomainName": "TargetDomain", "TargetSid": "TargetSID", "CallerProcessId": "ProcessId", "CallerProcessName": "ProcessPath"}, 4799: {"Descr": "A security-enabled local group membership was enumerated", "Provider": "Microsoft-Windows-Security-Auditing", "SubjectUserSid": "SID", "SubjectUserName": "Username", "SubjectDomainName": "Domain", "SubjectLogonId": "LogonId", "TargetUserName": "TargetUsername", "TargetDomainName": "TargetDomain", "TargetSid": "TargetSID", "CallerProcessId": "ProcessId", "CallerProcessName": "ProcessPath"}, 4825: {"Descr": "A user was denied the access to Remote Desktop. By default, users are allowed to connect only " "if they are members of the Remote Desktop Users group or Administrators group", "Provider": "Microsoft-Windows-Security-Auditing", "AccountName": "TargetUsername", "AccountDomain": "TargetDomain", "LogonID": "TargetLogonId", "ClientAddress": "IP"}, 4912: {"Descr": "Per User Audit Policy was changed", "Provider": "Microsoft-Windows-Security-Auditing", "SubjectUserSid": "SID", "SubjectUserName": "Username", "SubjectDomainName": "Domain", "SubjectLogonId": "LogonId", "TargetUserSid": "TargetSID", "CategoryId": "CategoryId", # %% format "SubcategoryId": "SubcategoryId", # %% format "SubcategoryGuid": "SubcategoryGuid", # %% format "AuditPolicyChanges": "AuditPolicyChanges"}, # %% format (multiple, joined with ', ') 4964: {"Descr": "Special groups have been assigned to a new logon", "Provider": "Microsoft-Windows-Security-Auditing", "SubjectUserSid": "SID", "SubjectUserName": "Username", "SubjectDomainName": "Domain", "SubjectLogonId": "LogonId", "LogonGuid": "LogonGuid", "TargetUserName": "TargetUsername", "TargetDomainName": "TargetDomain", "TargetUserSid": "TargetSID", "TargetLogonId": "TargetLogonId", "TargetLogonGuid": "TargetLogonGuid", "SidList": "SidList"}, 5059: {"Descr": "Key migration operation", "Provider": "Microsoft-Windows-Security-Auditing", "SubjectUserSid": "SID", "SubjectUserName": "Username", "SubjectDomainName": "Domain", "SubjectLogonId": "LogonId", "ProviderName": "ProviderName", "AlgorithmName": "AlgorithmName", "KeyName": "KeyName", "KeyType": "KeyType", "Operation": "OperationType", "ReturnCode": "ResultCode"}, 5140: {"Descr": "A network share object was accessed", "Provider": "Microsoft-Windows-Security-Auditing", "SubjectUserSid": "SID", "SubjectUserName": "Username", "SubjectDomainName": "Domain", "SubjectLogonId": "LogonId", "ObjectType": "ObjectType", "ShareName": "ShareName", "ShareLocalPath": "ShareLocalPath", "IpAddress": "IP", "IpPort": "Port", "AccessList": "AccessList"}, # %% format 5142: {"Descr": "A network share object was added", "Provider": "Microsoft-Windows-Security-Auditing", "SubjectUserSid": "SID", "SubjectUserName": "Username", "SubjectDomainName": "Domain", "SubjectLogonId": "LogonId", "ShareName": "ShareName", "ShareLocalPath": "ShareLocalPath"}, 5144: {"Descr": "A network share object was deleted", "Provider": "Microsoft-Windows-Security-Auditing", "SubjectUserSid": "SID", "SubjectUserName": "Username", "SubjectDomainName": "Domain", "SubjectLogonId": "LogonId", "ShareName": "ShareName", "ShareLocalPath": "ShareLocalPath"}, 5145: {"Descr": "A network share object was checked to see whether client can be granted desired access", "Provider": "Microsoft-Windows-Security-Auditing", "SubjectUserSid": "SID", "SubjectUserName": "Username", "SubjectDomainName": "Domain", "SubjectLogonId": "LogonId", "ObjectType": "ObjectType", "ShareName": "ShareName", "ShareLocalPath": "ShareLocalPath", "RelativeTargetName": "RelativeTargetName", "IpAddress": "IP", "IpPort": "Port", "AccessList": "AccessList", # %% format "AccessMask": "AccessMask", # alternate representation of AccessList "AccessReason": "AccessReason"}, 5152: {"Descr": "The Windows Filtering Platform has blocked a packet", "Provider": "Microsoft-Windows-Security-Auditing", "ProcessId": "ProcessId", "Application": "ProcessPath", "Direction": "Direction", # %% format "SourceAddress": "IP", "SourcePort": "Port", "DestAddress": "TargetIP", "DestPort": "TargetPort", "Protocol": "+Protocol"}, 5156: {"Descr": "The Windows Filtering Platform has permitted a connection", "Provider": "Microsoft-Windows-Security-Auditing", "ProcessId": "ProcessId", "Application": "ProcessPath", "Direction": "Direction", # %% format "IpAddress": "IP", "IpPort": "Port", "DestAddress": "TargetIP", "DestPort": "TargetPort", "Protocol": "+Protocol", "RemoteUserID": "TargetSID", "RemoteMachineID": "TargetMachineSID"}, 5158: {"Descr": "The Windows Filtering Platform has permitted a bind to a local port", "Provider": "Microsoft-Windows-Security-Auditing", "ProcessId": "ProcessId", "Application": "ProcessPath", "Direction": "Direction", # %% format "SourceAddress": "IP", "SourcePort": "Port", "Protocol": "+Protocol"}, 6279: {"Descr": "Network Policy Server locked the user account due to repeated failed authentication attempts", "Provider": "Microsoft-Windows-Security-Auditing", "SubjectUserSid": "SID", "SubjectUserName": "Username", "SubjectDomainName": "Domain", "FullyQualifiedSubjectUserName": "UsernameFQN"}, 6280: {"Descr": "Network Policy Server unlocked the user account", "Provider": "Microsoft-Windows-Security-Auditing", "SubjectUserSid": "SID", "SubjectUserName": "Username", "SubjectDomainName": "Domain", "FullyQualifiedSubjectUserName": "UsernameFQN"}, 6416: {"Descr": "A new external device was recognized by the System", "Provider": "Microsoft-Windows-Security-Auditing", "SubjectUserSid": "SID", "SubjectUserName": "Username", "SubjectDomainName": "Domain", "SubjectLogonId": "LogonId", "DeviceId": "DeviceName", # Win10 v1511+ "DeviceDescription": "DeviceDescr", # Win10 v1511+ "ClassId": "ClassId", # Win10 v1511+ "ClassName": "ClassName", # Win10 v1511+ "VendorIds": "VendorId", "CompatibleIds": "CompatibleId", "LocationInformation": "Location"} } sys = { # System 2: {"Descr": "Possible detection of CVE: <CVEId>. This event is raised by a kernel mode driver", "Provider": "Microsoft-Windows-Audit-CVE", "CVEID": "CVEID", "AdditionalDetails": "AdditionalDetails"}, 104: {"Descr": "The <EventLogName> log file was cleared", "Provider": "Microsoft-Windows-Eventlog", "SubjectUserName": "Username", "SubjectDomainName": "Domain", "Channel": "EventLogName", "BackupPath": "BackupPath"}, 1014: {"Descr": "Name resolution for the <QueryName> timed out after none of the configured DNS servers responded", "Provider": "Microsoft-Windows-DNS-Client", "QueryName": "QueryName", "Address": "Address"}, 1074: {"Descr": "<ProcessPath> has initiated the <ShutdownType> of <Hostname> on behalf of <Username> for the " "following <Reason>", "Provider": "User32", "param1": "ProcessPath", "param2": "Hostname", "param3": "Reason", "param4": "ReasonCode", "param5": "ShutdownType", "param6": "Comment", "param7": "Username"}, 1076: {"Descr": "The reason supplied by <Username> for the last unexpected shutdown of this computer is <Reason>", "Provider": "User32", "param1": "Reason", "param2": "ReasonCode", "param5": "Comment", "param6": "Username"}, 6005: {"Descr": "The Event Log service was started", "Provider": "EventLog"}, 6006: {"Descr": "The Event Log service was stopped", "Provider": "EventLog"}, 6008: {"Descr": "The previous system shutdown at %1 on %2 was unexpected", "Provider": "EventLog"}, 6009: {"Descr": "Microsoft (R) Windows (R) %1 %2 %3 %4", "Provider": "EventLog"}, 6013: {"Descr": "The system uptime is %5 seconds", "Provider": "EventLog"}, 6100: {"Descr": "Details about Networking <HelperClassName> diagnosis:", "Provider": "Microsoft-Windows-Diagnostics-Networking", "HelperClassName": "HelperClassName", "EventDescription": "EventDescr", "EventVerbosity": "EventVerbosity"}, 7034: {"Descr": "The <ServiceName> terminated unexpectedly. It has done this <Count> time(s)", "Provider": "Service Control Manager", "param1": "ServiceName", "param2": "Count"}, 7035: {"Descr": "The <ServiceName> was successfully sent a <Control>", "Provider": "Service Control Manager", "param1": "ServiceName", "param2": "Control"}, 7036: {"Descr": "The <ServiceName> entered the <StatusAfter> state", "Provider": "Service Control Manager", "param1": "ServiceName", "param2": "StatusAfter"}, 7040: {"Descr": "The start type of <ServiceName> was changed from <StatusBefore> to <StatusAfter>", "Provider": "Service Control Manager", "param1": "ServiceName", "param2": "StatusBefore", "param3": "StatusAfter"}, 7045: {"Descr": "A service was installed on the system", "Provider": "Service Control Manager", "ServiceName": "ServiceName", "ImagePath": "ServicePath", "ServiceType": "ServiceType", "StartType": "ServiceStartType", "AccountName": "ServiceAccount"}, 9009: {"Descr": "The Desktop Window Manager has exited with code <ExitCode>", # classic event, incorrect channel? "Param1": "ExitCode"}, 10000: {"Descr": "A driver package which uses user-mode driver framework version <FrameworkVersion> is being " "installed on device <DeviceId>", "Provider": "Microsoft-Windows-DriverFrameworks-UserMode", "DeviceId": "DeviceId", "FrameworkVersion": "FrameworkVersion"}, 20001: {"Descr": "Driver Management concluded the process to install <DriverName> for <DeviceInstanceId> " "with <Status>", "Provider": "Microsoft-Windows-UserPnp", "DriverName": "DriverName", "DriverVersion": "DriverVersion", "DriverProvider": "DriverProvider", "DeviceInstanceID": "DeviceInstanceID", "DriverDescription": "DriverDescr", "SetupClass": "SetupClass", "RebootOption": "RebootOption", "UpgradeDevice": "UpgradeDevice", "IsDriverOEM": "IsDriverOEM", "InstallStatus": "Status"}, 20002: {"Descr": "Driver Management concluded the process to remove <DriverName> from <DeviceInstanceId> " "with <Status>", "Provider": "Microsoft-Windows-UserPnp", "DriverName": "DriverName", "DriverVersion": "DriverVersion", "DriverProvider": "DriverProvider", "DeviceInstanceID": "DeviceInstanceID", "DriverDescription": "DriverDescr", "SetupClass": "SetupClass", "RebootOption": "RebootOption", "UpgradeDevice": "UpgradeDevice", "IsDriverOEM": "IsDriverOEM", "InstallStatus": "Status"}, 20003: {"Descr": "Driver Management has concluded the process to add <ServiceName>> for <DeviceInstanceID> " "with <Status>", "Provider": "Microsoft-Windows-UserPnp", "ServiceName": "DriverName", "DriverFileName": "DriverPath", "DeviceInstanceID": "DeviceInstanceID", "PrimaryService": "IsPrimaryService", "UpdateService": "IsUpdateService", "AddServiceStatus": "AddServiceStatus"} } app = { # Application 1: {"Descr": "Possible detection of CVE: <CVEId>. This event is raised by a User mode process", "Provider": "Microsoft-Windows-Audit-CVE", "CVEID": "CVEID", "AdditionalDetails": "AdditionalDetails"}, 216: {"Descr": "%1 (%2) %3 A database location change was detected from %4 to %5", "Provider": "ESENT"}, # removed in Win10 v2004 325: {"Descr": "%1 (%2) %3 The database engine created a new database (%4, %5). (Time=%6 seconds)", "Provider": "ESENT"}, # removed in Win10 v2004 326: {"Descr": "%1 (%2) %3 The database engine attached a database (%4, %5). (Time=%6 seconds)", "Provider": "ESENT"}, # removed in Win10 v2004 327: {"Descr": "%1 (%2) %3 The database engine detached a database (%4, %5). (Time=%6 seconds)", "Provider": "ESENT"}, # removed in Win10 v2004 1001: {"Descr": "Fault bucket: %1, Type: %2. Event Name: %3, Response: %4, Cab Id: %5. Problem signature: %rest", "Provider": "Windows Error Reporting"}, 1033: {"Descr": "Windows Installer installed the product. Product Name: %1. Product Version: %2. " "Product Language: %3. Manufacturer: %5. Installation success or error status: %4.", "Provider": "MsiInstaller"}, 1034: {"Descr": "Windows Installer removed the product. Product Name: %1. Product Version: %2. " "Product Language: %3. Manufacturer: %5. Removal success or error status: %4.", "Provider": "MsiInstaller"}, 11707: {"Descr": "Installation completed successfully", "Provider": "MsiInstaller"}, 11708: {"Descr": "Installation operation failed", "Provider": "MsiInstaller"}, 11724: {"Descr": "Application removal completed successfully", "Provider": "MsiInstaller"}, } appexp1 = { # Microsoft-Windows-Application-Experience/Program-Inventory 800: {"Descr": "An instance of Program Data Updater (PDU) ran with the following information...", # Win7 - 8.1 "Provider": "Microsoft-Windows-Application-Experience", "StartTime": "StartTime", "StopTime": "StopTime", "ExitCode": "ExitCode", "NumNewPrograms": "NumNewPrograms", "NumRemovedPrograms": "NumRemovedPrograms", "NumUpdatedPrograms": "NumUpdatedPrograms", "NumInstalledPrograms": "NumInstalledPrograms", "NumNewOrphans": "NumNewOrphans", "NumNewAddOns": "NumNewAddOns", "NumRemovedAddOns": "NumRemovedAddOns", "NumUpdatedAddOns": "NumUpdatedAddOns", "NumInstalledAddOns": "NumInstalledAddOns", "NumNewInstallations": "NumNewInstallations"}, 903: {"Descr": "A program was installed on the system", "Provider": "Microsoft-Windows-Application-Experience", "Name": "AppName", "Version": "AppVersion", "Publisher": "AppPublisher", "Language": "Language", "Source": "Source", "ProgramID": "ProgramId", "FileInstanceID": "FileInstanceId"}, 904: {"Descr": "A program was installed on the system (MSI)", "Provider": "Microsoft-Windows-Application-Experience", "Name": "AppName", "Version": "AppVersion", "Publisher": "AppPublisher", "Language": "Language", "Source": "Source", "ProgramID": "ProgramId", "FileInstanceID": "FileInstanceId", "MsiProductCode": "MsiProductCode", "MsiPackageCode": "MsiPackageCode"}, 905: {"Descr": "A program was updated on the system", "Provider": "Microsoft-Windows-Application-Experience", "Name": "AppName", "Version": "AppVersion", "Publisher": "AppPublisher", "Language": "Language", "Source": "Source", "ProgramID": "ProgramId", "FileInstanceID": "FileInstanceId", "OldFileInstanceID": "OldFileInstanceId"}, 906: {"Descr": "A program was updated on the system (MSI)", "Provider": "Microsoft-Windows-Application-Experience", "Name": "AppName", "Version": "AppVersion", "Publisher": "AppPublisher", "Language": "Language", "Source": "Source", "ProgramID": "ProgramId", "FileInstanceID": "FileInstanceId", "OldFileInstanceID": "OldFileInstanceId", "MsiProductCode": "MsiProductCode", "OldMsiProductCode": "OldMsiProductCode", "MsiPackageCode": "MsiPackageCode", "OldMsiPackageCode": "OldMsiPackageCode"}, 907: {"Descr": "A program was removed on the system", "Provider": "Microsoft-Windows-Application-Experience", "Name": "AppName", "Version": "AppVersion", "Publisher": "AppPublisher", "Language": "Language", "Source": "Source", "ProgramID": "ProgramId", "FileInstanceID": "FileInstanceId"}, 908: {"Descr": "A program was removed on the system (MSI)", "Provider": "Microsoft-Windows-Application-Experience", "Name": "AppName", "Version": "AppVersion", "Publisher": "AppPublisher", "Language": "Language", "Source": "Source", "ProgramID": "ProgramId", "FileInstanceID": "FileInstanceId", "MsiProductCode": "MsiProductCode", "MsiPackageCode": "MsiPackageCode"} } appexp2 = { # Microsoft-Windows-Application-Experience/Program-Telemetry 500: {"Descr": "Compatibility fix applied to <ProcessPath>. Fix information: <FixName>, <FixId>, <Flags>", "Provider": "Microsoft-Windows-Application-Experience", "ProcessId": "ProcessId", "ExePath": "ProcessPath", "StartTime": "StartTime", "FixID": "FixId", "FixName": "FixName", "Flags": "Flags"}, 501: {"Descr": "Compatibility fix applied to <ProcessPath>. Fix information: <FixName>, <FixId>, <Flags>", "Provider": "Microsoft-Windows-Application-Experience", "ProcessId": "ProcessId", "ExePath": "ProcessPath", "StartTime": "StartTime", "FixID": "FixId", "FixName": "FixName", "Flags": "Flags"}, 502: {"Descr": "Compatibility fix applied to <MsiPath>. Fix information: <FixName>, <FixId>, <Flags>", "Provider": "Microsoft-Windows-Application-Experience", "ClientProcessId": "ProcessId", "ClientStartTime": "StartTime", "FixID": "FixId", "FixName": "FixName", "Flags": "Flags", "ProductCode": "ProductCode", "PackageCode": "PackageCode", "MsiPath": "MsiPath"}, 503: {"Descr": "Compatibility fix applied to <MsiPath>. Fix information: <FixName>, <FixId>, <Flags>", "Provider": "Microsoft-Windows-Application-Experience", "ClientProcessId": "ProcessId", "ClientStartTime": "StartTime", "FixID": "FixId", "FixName": "FixName", "Flags": "Flags", "ProductCode": "ProductCode", "PackageCode": "PackageCode", "MsiPath": "MsiPath"} } applocker = { # Microsoft-Windows-AppLocker/EXE and DLL 8004: {"Descr": "<FilePath> was prevented from running", "Provider": "Microsoft-Windows-AppLocker", "PolicyNameBuffer": "Policy", "RuleId": "RuleId", "RuleNameBuffer": "RuleName", "RuleSddlBuffer": "RuleSddl", "TargetUser": "TargetUsername", "TargetLogonId": "TargetLogonId", "TargetProcessId": "TargetProcessId", "FilePathBuffer": "FilePath", "FileHash": "FileHash", "Fqbn": "Fqbn"} } bits = { # Microsoft-Windows-Bits-Client/Operational 3: {"Descr": "The BITS service created a new job", "Provider": "Microsoft-Windows-Bits-Client", "jobTitle": "JobTitle", "jobId": "JobId", "jobOwner": "JobOwner", "processPath": "ProcessPath", "processId": "ProcessId"}, 4: {"Descr": "The transfer job is complete", "Provider": "Microsoft-Windows-Bits-Client", "User": "Username", "jobTitle": "JobTitle", "jobId": "JobId", "jobOwner": "JobOwner", "fileCount": "FileCount"}, 5: {"Descr": "Job cancelled", "Provider": "Microsoft-Windows-Bits-Client", "User": "Username", "jobTitle": "JobTitle", "jobId": "JobId", "jobOwner": "JobOwner", "fileCount": "FileCount"}, 59: {"Descr": "BITS started the <Name> transfer job that is associated with the <URL>", "Provider": "Microsoft-Windows-Bits-Client", "transferId": "TransferId", "name": "Name", "Id": "JobId", "url": "URL", "peer": "Peer", "fileTime": "FileTime", "fileLength": "FileSize"}, 60: {"Descr": "BITS stopped transferring the <Name> transfer job that is associated with the <URL>", "Provider": "Microsoft-Windows-Bits-Client", "transferId": "TransferId", "name": "Name", "Id": "JobId", "url": "URL", "peer": "Peer", "fileTime": "FileTime", "fileLength": "FileSize", "bytesTotal": "BytesTotal", "bytesTransferred": "BytesTransferred", "bytesTransferredFromPeer": "BytesTransferredFromPeer"} } codeinteg = { # Microsoft-Windows-CodeIntegrity/Operational 3001: {"Descr": "Code Integrity determined an unsigned kernel module <FileName> is loaded into the system", "Provider": "Microsoft-Windows-CodeIntegrity", "FileNameBuffer": "FileName"} } diag = { # Microsoft-Windows-Diagnostics-Performance/Operational 100: {"Descr": "Windows has started up", "Provider": "Microsoft-Windows-Diagnostics-Performance", "BootStartTime": "BootStartTime", "BootEndTime": "BootEndTime", "SystemBootInstance": "SystemBootInstance", "UserBootInstance": "UserBootInstance", "BootTime": "BootTime", # in milliseconds "UserLogonWaitDuration": "UserLogonWaitDuration"}, 200: {"Descr": "Windows has shutdown", "Provider": "Microsoft-Windows-Diagnostics-Performance", "ShutdownStartTime": "ShutdownStartTime", "ShutdownEndTime": "ShutdownEndTime", "ShutdownTime": "ShutdownTime"} # in milliseconds } dnsclient = { # Microsoft-Windows-DNS-Client/Operational (disabled by default) 1014: {"Descr": "Name resolution for the <QueryName> timed out after none of the configured " "DNS servers responded", "Provider": "Microsoft-Windows-DNS-Client", "QueryName": "QueryName", "Address": "Address"}, 3006: {"Descr": "DNS query is called for the <QueryName>, <QueryType>", "Provider": "Microsoft-Windows-DNS-Client", "QueryName": "QueryName", "QueryType": "+QueryType", "QueryOptions": "QueryOptions", "ServerList": "ServerList", "IsNetworkQuery": "IsNetworkQuery", "NetworkQueryIndex": "NetworkIndex", "InterfaceIndex": "InterfaceIndex", "IsAsyncQuery": "IsAsyncQuery"}, 3008: {"Descr": "DNS query is completed for the <QueryName>, <QueryType> with <ResponseCode> <QueryResults>", "Provider": "Microsoft-Windows-DNS-Client", "QueryName": "QueryName", "QueryType": "+QueryType", "QueryOptions": "QueryOptions", "QueryStatus": "ResponseCode", "QueryResults": "QueryResults"}, 3011: {"Descr": "Received response from <DnsServerIP> for <QueryName> and <QueryType> with <ResponseCode>", "Provider": "Microsoft-Windows-DNS-Client", "QueryName": "QueryName", "QueryType": "+QueryType", "DnsServerIpAddress": "DnsServerIP", "ResponseStatus": "Status"}, 3016: {"Descr": "Cache lookup called for <QueryName>, <QueryType>", "Provider": "Microsoft-Windows-DNS-Client", "QueryName": "QueryName", "QueryType": "+QueryType", "QueryOptions": "QueryOptions", "InterfaceIndex": "InterfaceIndex"}, 3018: {"Descr": "Cache lookup for <QueryName>, <QueryType> returned <ResponseCode> with <QueryResults>", "Provider": "Microsoft-Windows-DNS-Client", "QueryName": "QueryName", "QueryType": "+QueryType", "QueryOptions": "QueryOptions", "Status": "ResponseCode", "QueryResults": "QueryResults"}, 3019: {"Descr": "Query wire called for name <QueryName>, <QueryType>", "Provider": "Microsoft-Windows-DNS-Client", "QueryName": "QueryName", "QueryType": "+QueryType", "NetworkIndex": "NetworkIndex", "InterfaceIndex": "InterfaceIndex"}, 3020: {"Descr": "Query response for name <QueryName>, <QueryType> returned <ResponseCode> with <QueryResults>", "Provider": "Microsoft-Windows-DNS-Client", "QueryName": "QueryName", "QueryType": "+QueryType", "NetworkIndex": "NetworkIndex", "InterfaceIndex": "InterfaceIndex", "Status": "ResponseCode", "QueryResults": "QueryResults"} } dnsserver = { # Microsoft-Windows-DNSServer/Analytical (Windows Server 2016+) 256: {"Descr": "Query received", "Provider": "Microsoft-Windows-DNSServer", "TCP": "TCP", "InterfaceIP": "InterfaceIP", "Source": "Source", "RD": "RD", "QNAME": "QueryName", "QTYPE": "QueryType", "XID": "XID", "Port": "Port", "Flags": "Flags", "PacketData": "PacketData", "AdditionalInfo": "AdditionalInfo"}, 257: {"Descr": "Response success", "Provider": "Microsoft-Windows-DNSServer", "TCP": "TCP", "InterfaceIP": "InterfaceIP", "Destination": "Destination", "AA": "AA", "AD": "AD", "QNAME": "QueryName", "QTYPE": "QueryType", "XID": "XID", "DNSSEC": "DNSSEC", "RCODE": "RCode", "Port": "Port", "Flags": "Flags", "Scope": "Scope", "Zone": "Zone", "PolicyName": "Policy", "PacketData": "PacketData", "AdditionalInfo": "AdditionalInfo"}, 258: {"Descr": "Response failure", "Provider": "Microsoft-Windows-DNSServer", "TCP": "TCP", "InterfaceIP": "InterfaceIP", "Reason": "Reason", "Destination": "Destination", "QNAME": "QueryName", "QTYPE": "QueryType", "XID": "XID", "RCODE": "RCode", "Port": "Port", "Flags": "Flags", "Zone": "Zone", "PolicyName": "Policy", "PacketData": "PacketData", "AdditionalInfo": "AdditionalInfo"}, 259: {"Descr": "Ignored query", "Provider": "Microsoft-Windows-DNSServer", "TCP": "TCP", "InterfaceIP": "InterfaceIP", "Source": "Source", "Reason": "Reason", "QNAME": "QueryName", "QTYPE": "QueryType", "XID": "XID", "Zone": "Zone", "PolicyName": "Policy", "AdditionalInfo": "AdditionalInfo"}, 260: {"Descr": "Recurse query out", "Provider": "Microsoft-Windows-DNSServer", "TCP": "TCP", "InterfaceIP": "InterfaceIP", "Destination": "Destination", "RD": "RD", "QNAME": "QueryName", "QTYPE": "QueryType", "XID": "XID", "Port": "Port", "Flags": "Flags", "RecursionScope": "RecursionScope", "CacheScope": "CacheScope", "PolicyName": "Policy", "PacketData": "PacketData", "AdditionalInfo": "AdditionalInfo"}, 261: {"Descr": "Recurse response in", "Provider": "Microsoft-Windows-DNSServer", "TCP": "TCP", "InterfaceIP": "InterfaceIP", "Source": "Source", "AA": "AA", "AD": "AD", "QNAME": "QueryName", "QTYPE": "QueryType", "XID": "XID", "Port": "Port", "Flags": "Flags", "RecursionScope": "RecursionScope", "CacheScope": "CacheScope", "PacketData": "PacketData", "AdditionalInfo": "AdditionalInfo"}, 262: {"Descr": "Recurse query timeout", "Provider": "Microsoft-Windows-DNSServer", "TCP": "TCP", "InterfaceIP": "InterfaceIP", "Destination": "Destination", "QNAME": "QueryName", "QTYPE": "QueryType", "XID": "XID", "Port": "Port", "Flags": "Flags", "RecursionScope": "RecursionScope", "CacheScope": "CacheScope", "AdditionalInfo": "AdditionalInfo"} } driverfw = { # Microsoft-Windows-DriverFrameworks-UserMode/Operational 2003: {"Descr": "The UMDF Host Process (<HostProcessId>) has been asked to load drivers for device <DeviceId>", "Provider": "Microsoft-Windows-DriverFrameworks-UserMode", "LifetimeId": "HostProcessId", "InstanceId": "DeviceId"}, 2004: {"Descr": "The UMDF Host is loading <Driver> at <Level> for device <DeviceId>", "Provider": "Microsoft-Windows-DriverFrameworks-UserMode", "LifetimeId": "HostProcessId", "InstanceId": "DeviceId", "Level": "Level", "Service": "Driver", "ClsId": "DriverClassId"}, 2005: {"Descr": "The UMDF Host Process (<HostProcessId>) has loaded <ModulePath> while loading drivers for device " "<DeviceId>", "Provider": "Microsoft-Windows-DriverFrameworks-UserMode", "LifetimeId": "HostProcessId", "InstanceId": "DeviceId", "ModulePath": "ModulePath", "CompanyName": "CompanyName", "FileDescription": "FileDescr", "FileVersion": "FileVersion"}, 2010: {"Descr": "The UMDF Host Process (<HostProcessId>) has successfully loaded drivers for device <DeviceId>", "Provider": "Microsoft-Windows-DriverFrameworks-UserMode", "LifetimeId": "HostProcessId", "InstanceId": "DeviceId", "FinalStatus": "FinalStatus"}, 2100: {"Descr": "Received a Pnp or Power operation (<MajorCode>, <MinorCode>) for device <DeviceId>", "Provider": "Microsoft-Windows-DriverFrameworks-UserMode", "LifetimeId": "HostProcessId", "InstanceId": "DeviceId", "MajorCode": "MajorCode", "MinorCode": "MinorCode", "Status": "Status"}, 2102: {"Descr": "Forwarded a finished Pnp or Power operation (<MajorCode>, <MinorCode>) to the lower driver " "for device <DeviceId> with <Status>", "Provider": "Microsoft-Windows-DriverFrameworks-UserMode", "LifetimeId": "HostProcessId", "InstanceId": "DeviceId", "MajorCode": "MajorCode", "MinorCode": "MinorCode", "Status": "Status"}, 2105: {"Descr": "Forwarded a Pnp or Power operation (<MajorCode>, <MinorCode>) for device <DeviceId> to the " "lower driver with <Status>", "Provider": "Microsoft-Windows-DriverFrameworks-UserMode", "LifetimeId": "HostProcessId", "InstanceId": "DeviceId", "MajorCode": "MajorCode", "MinorCode": "MinorCode", "Status": "Status"} } fwall = { # Microsoft-Windows-Windows Firewall With Advanced Security/Firewall 2004: {"Descr": "A rule has been added to the Windows Firewall exception list", "Provider": "Microsoft-Windows-Windows Firewall With Advanced Security", "RuleId": "RuleId", "RuleName": "RuleName", "Origin": "+Origin", "ApplicationPath": "AppPath", "ServiceName": "ServiceName", "Direction": "+Direction", "Protocol": "+Protocol", "LocalPorts": "TargetPort", "RemotePorts": "RemotePorts", "Action": "+Action", "Profiles": "+Profiles", "LocalAddresses": "TargetIP", "EmbeddedContext": "EmbeddedContext", "Active": "+Active", "ModifyingUser": "SID", "ModifyingApplication": "ProcessPath"}, 2005: {"Descr": "A rule has been modified in the Windows Firewall exception list", "Provider": "Microsoft-Windows-Windows Firewall With Advanced Security", "RuleId": "RuleId", "RuleName": "RuleName", "Origin": "+Origin", "ApplicationPath": "AppPath", "ServiceName": "ServiceName", "Direction": "+Direction", "Protocol": "+Protocol", "LocalPorts": "TargetPort", "RemotePorts": "RemotePorts", "Action": "+Action", "Profiles": "+Profiles", "LocalAddresses": "TargetIP", "EmbeddedContext": "EmbeddedContext", "Active": "+Active", "ModifyingUser": "SID", "ModifyingApplication": "ProcessPath"}, 2006: {"Descr": "A rule has been deleted in the Windows Firewall exception list", "Provider": "Microsoft-Windows-Windows Firewall With Advanced Security", "RuleId": "RuleId", "RuleName": "RuleName", "ModifyingUser": "SID", "ModifyingApplication": "ProcessPath"} } kernelpnp = { # Microsoft-Windows-Kernel-PnP/Configuration 400: {"Descr": "<DeviceInstanceId> was configured", "Provider": "Microsoft-Windows-Kernel-PnP", "DeviceInstanceId": "DeviceInstanceId", "DriverName": "DriverName", "ClassGuid": "+ClassGuid", "DriverDate": "DriverDate", "DriverVersion": "DriverVersion", "DriverProvider": "DriverProvider", "DriverInbox": "IsDriverInbox", "DriverSection": "DriverSection", "DeviceId": "DeviceId", "OutrankedDrivers": "OutrankedDrivers", "DeviceUpdated": "IsDeviceUpdated", "Status": "Status", "ParentDeviceInstanceId": "ParentDeviceInstanceId"}, 410: {"Descr": "<DeviceInstanceId> was started", "Provider": "Microsoft-Windows-Kernel-PnP", "DeviceInstanceId": "DeviceInstanceId", "DriverName": "DriverName", "ClassGuid": "+ClassGuid", "ServiceName": "ServiceName", "LowerFilters": "LowerFilters", "UpperFilters": "UpperFilters", "Problem": "Problem", "Status": "Status"}, 430: {"Descr": "<DeviceInstanceId> requires further installation", "Provider": "Microsoft-Windows-Kernel-PnP", "DeviceInstanceId": "DeviceInstanceId"} } lsm = { # Microsoft-Windows-TerminalServices-LocalSessionManager/Operational 21: {"Descr": "Remote Desktop Services: Session logon succeeded", "Provider": "Microsoft-Windows-TerminalServices-LocalSessionManager", "User": "TargetUsername", "SessionID": "TargetSessionId", "Address": "IP"}, 22: {"Descr": "Remote Desktop Services: Shell start notification received", "Provider": "Microsoft-Windows-TerminalServices-LocalSessionManager", "User": "TargetUsername", "SessionID": "TargetSessionId", "Address": "IP"}, 23: {"Descr": "Remote Desktop Services: Session logoff succeeded", "Provider": "Microsoft-Windows-TerminalServices-LocalSessionManager", "User": "TargetUsername", "SessionID": "TargetSessionId"}, 24: {"Descr": "Remote Desktop Services: Session has been disconnected", "Provider": "Microsoft-Windows-TerminalServices-LocalSessionManager", "User": "TargetUsername", "SessionID": "TargetSessionId", "Address": "IP"}, 25: {"Descr": "Remote Desktop Services: Session reconnection succeeded", "Provider": "Microsoft-Windows-TerminalServices-LocalSessionManager", "User": "TargetUsername", "SessionID": "TargetSessionId", "Address": "IP"}, 39: {"Descr": "<TargetSessionId> has been disconnected by session <SessionId>", "Provider": "Microsoft-Windows-TerminalServices-LocalSessionManager", "TargetSession": "TargetSessionId", "Source": "SessionId"}, 40: {"Descr": "<TargetSessionId> has been disconnected, <Reason>", "Provider": "Microsoft-Windows-TerminalServices-LocalSessionManager", "Session": "TargetSessionId", "Reason": "+Reason"}, 41: {"Descr": "Begin session arbitration", # Win8.1+ "Provider": "Microsoft-Windows-TerminalServices-LocalSessionManager", "User": "TargetUsername", "SessionID": "TargetSessionId"} } networkp = { # Microsoft-Windows-NetworkProfile/Operational 10000: {"Descr": "Network connected", "Provider": "Microsoft-Windows-NetworkProfile", "Name": "ProfileName", "Guid": "Guid", "Type": "+Type", "State": "State", "Category": "Category"}, 10001: {"Descr": "Network disconnected", "Provider": "Microsoft-Windows-NetworkProfile", "Name": "ProfileName", "Guid": "Guid", "Type": "+Type", "State": "State", "Category": "Category"}, 10002: {"Descr": "Network category changed", "Provider": "Microsoft-Windows-NetworkProfile", "Name": "ProfileName", "Guid": "Guid", "Type": "+Type", "State": "State", "Category": "Category"}, } ntfs = { # Microsoft-Windows-Ntfs/Operational 142: {"Descr": "Summary of disk space usage, since last event", "Provider": "Microsoft-Windows-Ntfs", "VolumeGuid": "VolumeGuid", "VolumeName": "VolumeName", "LowestFreeSpaceInBytes": "LowestFreeSpaceInBytes", "HighestFreeSpaceInBytes": "HighestFreeSpaceInBytes", "IsBootVolume": "IsBootVolume"}, 145: {"Descr": "IO latency summary common data for volume", "Provider": "Microsoft-Windows-Ntfs", "VolumeCorrelationId": "VolumeGuid", "VolumeName": "VolumeName", "IsBootVolume": "IsBootVolume"}, 151: {"Descr": "In the past <SecondsElapsed> seconds <TotalCountDeleteFile> files were deleted", # Win10 v2004+ "Provider": "Microsoft-Windows-Ntfs", "VolumeCorrelationId": "VolumeGuid", "VolumeName": "VolumeName", "IsBootVolume": "IsBootVolume", "SecondsElapsed": "SecondsElapsed", "TotalCountDeleteFile": "TotalCountDeleteFile", "TotalCountDeleteFileLogged": "TotalCountDeleteFileLogged", "ProcessName": "ProcessName", "CountDeleteFile": "CountDeleteFile"}, 158: {"Descr": "IO latency summary common data for volume", # Win10 v2004+ "Provider": "Microsoft-Windows-Ntfs", "VolumeCorrelationId": "VolumeGuid", "VolumeName": "VolumeName", "UserFileReads": "UserFileReads", "UserFileReadBytes": "UserFileReadBytes", "UserDiskReads": "UserDiskReads", "UserFileWrites": "UserFileWrites", "UserFileWriteBytes": "UserFileWriteBytes", "UserDiskWrites": "UserDiskWrites"} } offlinef = { # Microsoft-Windows-OfflineFiles/Operational 7: {"Descr": "User logon detected: <Username> <Session>", "Provider": "Microsoft-Windows-OfflineFiles", "Account": "TargetUsername", "Session": "TargetSessionId"}, 8: {"Descr": "User logoff detected: <Username> <Session>", "Provider": "Microsoft-Windows-OfflineFiles", "Account": "TargetUsername", "Session": "TargetSessionId"} } oalerts = { # OAlerts 300: {"Descr": "Microsoft Office Alert"} } partition = { # Microsoft-Windows-Partition/Diagnostic; Win10 v1709+ 1006: {"Descr": "A device is connected or disconnected from the system", "Provider": "Microsoft-Windows-Partition", "Version": "Version", # removed in Win 10 v2004 "DiskNumber": "DiskNumber", "Flags": "Flags", "Characteristics": "Characteristics", "BytesPerSector": "BytesPerSector", "BytesPerLogicalSector": "BytesPerLogicalSector", "BytesPerPhysicalSector": "BytesPerPhysicalSector", "BytesOffsetForSectorAlignment": "BytesOffsetForSectorAlignment", "Capacity": "Capacity", "BusType": "+BusType", "Manufacturer": "Vendor", "Model": "Product", "Revision": "ProductRevision", "SerialNumber": "SerialNumber", "Location": "Location", "ParentId": "ParentId", "DiskId": "DiskId", "AdapterId": "AdapterId", "RegistryId": "RegistryId", "PoolId": "PoolId", "StorageIdType": "+StorageIdType", "StorageIdAssociation": "+StorageIdAssoc", "StorageId": "StorageId", "IsTrimSupported": "IsTrimSupported", "IsThinProvisioned": "IsThinProvisioned", "HybridSupported": "HybridSupported", "HybridCacheBytes": "HybridCacheBytes", "AdapterSerialNumber": "AdapterSerialNumber", "UserRemovalPolicy": "UserRemovalPolicy", "PartitionStyle": "+PartitionStyle", "PartitionCount": "PartitionCount", "PartitionTableBytes": "PartitionTableBytes", "MbrBytes": "MbrBytes", "Vbr0Bytes": "Vbr0Bytes", "Vbr1Bytes": "Vbr1Bytes", "Vbr2Bytes": "Vbr2Bytes", "Vbr3Size": "Vbr3Bytes"} } printsvc = { # Microsoft-Windows-PrintService/Operational 307: {"Descr": "Spooler operation succeeded", "Provider": "Microsoft-Windows-PrintService", "param1": "JobId", "param2": "JobName", "param3": "DocumentOwner", "param4": "Host", "param5": "PrinterName", "param6": "PrinterPort", "param7": "Size", "param8": "Pages"} } pshell1 = { # Windows PowerShell 400: {"Descr": "Engine state is changed from <PreviousEngineState> to <NewEngineState>"}, # start of session 403: {"Descr": "Engine state is changed from <PreviousEngineState> to <NewEngineState>"}, # end of session 500: {"Descr": "Command <CommandName> is <NewCommandState>"}, # start of execution 501: {"Descr": "Command <CommandName> is <NewCommandState>"}, # end of execution 600: {"Descr": "Provider <ProviderName> is <NewProviderState>"}, 800: {"Descr": "Pipeline execution details for command line: <CommandLine>"} } pshell2 = { # Microsoft-Windows-PowerShell/Operational 4100: {"Descr": "<Payload> Context: <ContextInfo>", # Error executing script "Provider": "Microsoft-Windows-PowerShell", "ContextInfo": "ContextInfo", "UserData": "UserData", "Payload": "Payload"}, 4103: {"Descr": "<Payload> Context: <ContextInfo>", # Module logging "Provider": "Microsoft-Windows-PowerShell", "ContextInfo": "ContextInfo", "UserData": "UserData", "Payload": "Payload"}, 4104: {"Descr": "Creating Scriptblock text (<MessageNumber> of <MessageTotal>)", # Scriptblock module logging "Provider": "Microsoft-Windows-PowerShell", "MessageNumber": "MessageNumber", "MessageTotal": "MessageTotal", "ScriptBlockText": "ScriptBlockText", "ScriptBlockId": "ScriptBlockId", "Path": "Path"}, 8193: {"Descr": "Creating Runspace object", # Session created "Provider": "Microsoft-Windows-PowerShell", "param1": "InstanceId"}, 8194: {"Descr": "Creating RunspacePool object", # Session created "Provider": "Microsoft-Windows-PowerShell", "InstanceId": "InstanceId", "MaxRunspaces": "MaxRunspaces", "MinRunspaces": "MinRunspaces"}, 8197: {"Descr": "Runspace state changed to <Status>", # Session status "Provider": "Microsoft-Windows-PowerShell", "param1": "Status"}, 24577: {"Descr": "Windows PowerShell ISE has started to run script file %1", "Provider": "Microsoft-Windows-PowerShell", "FileName": "FileName"}, 24578: {"Descr": "Windows PowerShell ISE has started to run a user-selected script from file %1", "Provider": "Microsoft-Windows-PowerShell", "FileName": "FileName"}, 40961: {"Descr": "PowerShell console is starting up", "Provider": "Microsoft-Windows-PowerShell"}, # empty 40962: {"Descr": "PowerShell console is ready for user input", "Provider": "Microsoft-Windows-PowerShell"}, # empty 53504: {"Descr": "Windows PowerShell has started an IPC listening thread on <ProcessPath> in <AppDomain>", "Provider": "Microsoft-Windows-PowerShell", "param1": "ProcessId", "param2": "AppDomain"} } rcm = { # Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operational 261: {"Descr": "Listener <ListenerName> received a connection", "Provider": "Microsoft-Windows-TerminalServices-RemoteConnectionManager", "listenerName": "ListenerName"}, 1149: {"Descr": "Remote Desktop Services: User authentication established", "Provider": "Microsoft-Windows-TerminalServices-RemoteConnectionManager", "Param1": "TargetUsername", "Param2": "TargetDomain", "Param3": "IP"} } rdpclient = { # Microsoft-Windows-TerminalServices-RDPClient/Operational 1024: {"Descr": "RDP ClientActiveX is trying to connect to <TargetHost>", "Provider": "Microsoft-Windows-TerminalServices-ClientActiveXCore", "Value": "TargetHost"}, 1026: {"Descr": "RDP ClientActiveX has been disconnected: <Reason>", "Provider": "Microsoft-Windows-TerminalServices-ClientActiveXCore", "Value": "Reason"}, 1027: {"Descr": "Connected to <TargetDomain> with <TargetSessionId>", "Provider": "Microsoft-Windows-TerminalServices-ClientActiveXCore", "DomainName": "TargetDomain", "SessionID": "TargetSessionId"}, 1029: {"Descr": "This event is raised during the connection process: Base64(SHA256(<TargetUsername))", "Provider": "Microsoft-Windows-TerminalServices-ClientActiveXCore", "TraceMessage": "TargetUsername"}, 1102: {"Descr": "This event is raised during the connection process", "Provider": "Microsoft-Windows-TerminalServices-ClientActiveXCore", "Value": "TargetIP"} } rdpcorets = { # Microsoft-Windows-RemoteDesktopServices-RdpCoreTS/Operational 98: {"Descr": "A TCP connection has been successfully established", "Provider": "Microsoft-Windows-RemoteDesktopServices-RdpCoreTS"}, 131: {"Descr": "The server accepted a new <Protocol> connection from <IPPort>", "Provider": "Microsoft-Windows-RemoteDesktopServices-RdpCoreTS", "ConnType": "Protocol", "ClientIP": "IPPort"}, 148: {"Descr": "<ChannelName> has been closed between the server and the client on transport tunnel <TunnelID>", "Provider": "Microsoft-Windows-RemoteDesktopServices-RdpCoreTS", "ChannelName": "ChannelName", "TunnelID": "TunnelID"} } scpnp = { # Microsoft-Windows-Storage-ClassPnP/Operational 507: {"Descr": "Completing a failed non-ReadWrite SCSI SRB request", "Provider": "Microsoft-Windows-StorDiag", "DeviceGUID": "DeviceGuid", "DeviceNumber": "DeviceNumber", "Vendor": "Vendor", "Model": "Product", "FirmwareVersion": "ProductRevision", "SerialNumber": "SerialNumber"} } sch = { # Microsoft-Windows-TaskScheduler/Operational 100: {"Descr": "Task Scheduler started <TaskInstanceId> of the <TaskName> task for user <Username>", "Provider": "Microsoft-Windows-TaskScheduler", "TaskName": "TaskName", "UserContext": "Username", "InstanceId": "TaskInstanceId"}, 101: {"Descr": "Task Scheduler failed to start <TaskName> task for user <Username>", "Provider": "Microsoft-Windows-TaskScheduler", "TaskName": "TaskName", "UserContext": "Username", "ResultCode": "ResultCode"}, 102: {"Descr": "Task Scheduler successfully finished <TaskInstanceId> of the <TaskName> task for user <Username>", "Provider": "Microsoft-Windows-TaskScheduler", "TaskName": "TaskName", "UserContext": "Username", "InstanceId": "TaskInstanceId"}, 106: {"Descr": "<Username> registered Task Scheduler <TaskName>", "Provider": "Microsoft-Windows-TaskScheduler", "TaskName": "TaskName", "UserContext": "Username"}, 118: {"Descr": "Task Scheduler launched <TaskInstanceId> of <TaskName> due to system startup", "Provider": "Microsoft-Windows-TaskScheduler", "TaskName": "TaskName", "InstanceId": "TaskInstanceId"}, 119: {"Descr": "Task Scheduler launched <TaskInstanceId of <TaskName> due to <Username> logon", "Provider": "Microsoft-Windows-TaskScheduler", "TaskName": "TaskName", "UserName": "Username", "InstanceId": "TaskInstanceId"}, 129: {"Descr": "Task Scheduler launch task <TaskName>, instance <ProcessPath> with process ID <ProcessId>", "Provider": "Microsoft-Windows-TaskScheduler", "TaskName": "TaskName", "Path": "ProcessPath", "ProcessID": "ProcessId", "Priority": "ProcessPriority"}, 140: {"Descr": "<Username> updated Task Scheduler <TaskName>", "Provider": "Microsoft-Windows-TaskScheduler", "TaskName": "TaskName", "UserName": "Username"}, 141: {"Descr": "<Username> deleted Task Scheduler <TaskName>", "Provider": "Microsoft-Windows-TaskScheduler", "TaskName": "TaskName", "UserName": "Username"}, } shell = { # Microsoft-Windows-Shell-Core/Operational 9707: {"Descr": "Started execution of <Command>", # from Run/RunOnce "Provider": "Microsoft-Windows-Shell-Core", "Command": "Command"}, 9708: {"Descr": "Finished execution of <Command> (PID <ProcessPid>)", # from Run/RunOnce "Provider": "Microsoft-Windows-Shell-Core", "Command": "Command", "PID": "ProcessId"}, 28115: {"Descr": "Shortcut for <AppName> with <AppID> and <Flags> is added to app resolver cache", "Provider": "Microsoft-Windows-Shell-Core", "Name": "AppName", "AppID": "AppID", "Flags": "Flags"} } smbclient = { # Microsoft-Windows-SmbClient/Security 31001: {"Descr": "Failed logon to <ServerName>", "Provider": "Microsoft-Windows-SmbClient", "Reason": "Reason", "Status": "Status", "SecurityStatus": "SecurityStatus", "TargetLogonId": "TargetLogonId", "UserName": "TargetUsername", "ServerName": "TargetHost", "PrincipalName": "PrincipalName"}, # TODO - change to SPN? 31010: {"Descr": "The SMB client failed to connect to the share.", "Provider": "Microsoft-Windows-SmbClient", "Reason": "Reason", "Status": "Status", "ShareName": "ShareName", "ObjectName": "ObjectName"} } smbserver1 = { # Microsoft-Windows-SMBServer/Analytic 551: {"Descr": "Smb Session Authentication Failure", "Provider": "Microsoft-Windows-SMBServer", "SessionGUID": "SessionGuid", "ConnectionGUID": "ConnectionGuid", "Status": "Status"}, 552: {"Descr": "SMB2 Session Authentication Success", "Provider": "Microsoft-Windows-SMBServer", "SessionGUID": "SessionGuid", "ConnectionGUID": "ConnectionGuid", "UserName": "TargetUsername", "DomainName": "TargetDomain"}, 553: {"Descr": "SMB2 Session Bound to Connection", "Provider": "Microsoft-Windows-SMBServer", "SessionGUID": "SessionGuid", "ConnectionGUID": "ConnectionGuid", "BindingSessionGUID": "BindingSessionGuid"}, 554: {"Descr": "Session Terminated", "Provider": "Microsoft-Windows-SMBServer", "SessionGUID": "SessionGuid", "Reason": "Reason"}, 600: {"Descr": "SMB2 TreeConnect Allocated", "Provider": "Microsoft-Windows-SMBServer", "TreeConnectGUID": "TreeConnectGuid", "SessionGUID": "SessionGuid", "ConnectionGUID": "ConnectionGuid", "ShareGUID": "ShareGuid", "ShareName": "ShareName", "ScopeName": "ScopeName", "ShareProperties": "ShareProperties"}, 601: {"Descr": "SMB2 TreeConnect Disconnected", "Provider": "Microsoft-Windows-SMBServer", "TreeConnectGUID": "TreeConnectGuid", "SessionGUID": "SessionGuid", "ConnectionGUID": "ConnectionGuid"}, 602: {"Descr": "SMB2 TreeConnect Terminated", "Provider": "Microsoft-Windows-SMBServer", "TreeConnectGUID": "TreeConnectGuid", "SessionGUID": "SessionGuid"}, 700: {"Descr": "SMB2 Share Added", "Provider": "Microsoft-Windows-SMBServer", "ShareName": "ShareName", "ServerName": "ServerName", "PathName": "PathName", "CSCState": "CSCState", "ClusterShareType": "ClusterShareType", "ShareProperties": "ShareProperties", "CaTimeOut": "CaTimeOut", "ShareState": "ShareState"}, 701: {"Descr": "SMB2 Share Modified", "Provider": "Microsoft-Windows-SMBServer", "ShareName": "ShareName", "ServerName": "ServerName", "PathName": "PathName", "CSCState": "CSCState", "ClusterShareType": "ClusterShareType", "ShareProperties": "ShareProperties", "CaTimeOut": "CaTimeOut", "ShareState": "ShareState"}, 702: {"Descr": "SMB2 Share Deleted", "Provider": "Microsoft-Windows-SMBServer", "ShareName": "ShareName", "ServerName": "ServerName"} } smbserver2 = { # Microsoft-Windows-SMBServer/Auditr 3000: {"Descr": "SMB1 access", "Provider": "Microsoft-Windows-SMBServer", "ClientName": "ClientName"} } smbserver3 = { # Microsoft-Windows-SMBServer/Connectivity 1022: {"Descr": "File and printer sharing firewall rule enabled", "Provider": "Microsoft-Windows-SMBServer"} } smbserver4 = { # Microsoft-Windows-SMBServer/Operational 1023: {"Descr": "One or more shares present on this server have access based enumeration enabled", "Provider": "Microsoft-Windows-SMBServer"}, 1024: {"Descr": "SMB2 and SMB3 have been disabled on this server", "Provider": "Microsoft-Windows-SMBServer"}, 1025: {"Descr": "One or more named pipes or shares have been marked for access by anonymous users", "Provider": "Microsoft-Windows-SMBServer"} } smbserver5 = { # Microsoft-Windows-SMBServer/Security 551: {"Descr": "SMB session authentication failure", "Provider": "Microsoft-Windows-SMBServer", "SessionGUID": "SessionGuid", "ConnectionGUID": "ConnectionGuid", "Status": "Status", "TranslatedStatus": "TranslatedStatus", "ClientAddress": "ClientAddress", "SessionId": "SessionId", "UserName": "Username", "ClientName": "ClientName"}, 1006: {"Descr": "The share denied access to the client", "Provider": "Microsoft-Windows-SMBServer", "ShareName": "ShareName", "SharePath": "SharePath", "ClientAddress": "ClientAddress", "UserName": "Username", "ClientName": "ClientName", "MappedAccess": "MappedAccess", "GrantedAccess": "GrantedAccess", "ShareSecurityDescriptor": "ShareSecurityDescriptor", "Status": "Status", "TranslatedStatus": "TranslatedStatus", "SessionID": "SessionID"}, 1007: {"Descr": "The share denied anonymous access to the client", "Provider": "Microsoft-Windows-SMBServer", "ShareName": "ShareName", "SharePath": "SharePath", "ClientAddress": "ClientAddress", "ClientName": "ClientName"}, 1009: {"Descr": "The share denied anonymous access to the client", "Provider": "Microsoft-Windows-SMBServer", "ClientAddress": "ClientAddress", "ClientName": "ClientName", "SessionID": "SessionId", "SessionGUID": "SessionGuid", "ConnectionGUID": "ConnectionGuid"}, 1021: {"Descr": "LmCompatibilityLevel value is different from the default", "Provider": "Microsoft-Windows-SMBServer", "ConfiguredLmCompatibilityLevel": "+ConfiguredLmCompatibilityLevel", "DefaultLmCompatibilityLevel": "+DefaultLmCompatibilityLevel"} } storspaces = { # Microsoft-Windows-StorageSpaces-Driver/Operational 207: {"Descr": "Physical disk <DriveId> arrived", # Win 10 v2004+ "Provider": "Microsoft-Windows-StorageSpaces-Driver", "DriveId": "DiskId", "PoolId": "PoolId", "DeviceNumber": "DiskNumber", "DriveManufacturer": "Vendor", "DriveModel": "Product", "DriveSerial": "SerialNumber"} } storsvc = { # Microsoft-Windows-Storsvc/Diagnostic 1001: {"Descr": "NIL", "Provider": "Microsoft-Windows-Storsvc", "Version": "Version", "DiskNumber": "DiskNumber", "VendorId": "Vendor", "ProductId": "Product", "ProductRevision": "ProductRevision", "SerialNumber": "SerialNumber", "ParentId": "ParentId", "FileSystem": "FileSystem", "BusType": "+BusType", "PartitionStyle": "+PartitionStyle", "VolumeCount": "VolumeCount", "ContainsRawVolumes": "ContainsRawVolumes", "Size": "Capacity"}, # Provider: Microsoft-Windows-Storsvc 1002: {"Descr": "NIL", "Provider": "Microsoft-Windows-Storsvc", "Version": "Version", "Epoch": "Epoch", "DiskIndex": "DiskIndex", "TotalDisks": "TotalDisks", "DiskNumber": "DiskNumber", "VendorId": "Vendor", "ProductId": "Product", "ProductRevision": "ProductRevision", "SerialNumber": "SerialNumber", "ParentId": "ParentId", "FileSystem": "FileSystem", "BusType": "+BusType", "PartitionStyle": "+PartitionStyle", "VolumeCount": "VolumeCount", "ContainsRawVolumes": "ContainsRawVolumes", "Size": "Capacity"} } symantec = { # Symantec Endpoint Protection Client 51: {"Descr": "Detection Finish"} # TODO } wdef = { # Microsoft-Windows-Windows Defender/Operational 1006: {"Descr": "<ProductName> has detected malware or other potentially unwanted software", "Provider": "Microsoft-Windows-Windows Defender", "Product Name": "ProductName", "Product Version": "ProductVersion", "Detection ID": "DetectionId", "Detection Source": "Source", "Process Name": "ProcessPath", "Domain": "Domain", "User": "Username", "SID": "SID", "Threat ID": "ThreatId", "Threat Name": "Threat", "Severity Name": "Severity", "Category Name": "Category", "FWLink": "Link", "Path Found": "Path", "Detection Origin": "Origin", "Execution Status": "ExecutionStatus", "Detection Type": "Type", "Signature Version": "SignatureVersion", "Engine Version": "EngineVersion"}, 1007: {"Descr": "<ProductName> has taken action to protect this machine from malware or " "other potentially unwanted software", "Provider": "Microsoft-Windows-Windows Defender", "Product Name": "ProductName", "Product Version": "ProductVersion", "Detection ID": "DetectionId", "Status Description": "Status", "Domain": "Domain", "User": "Username", "SID": "SID", "Threat ID": "ThreatId", "Threat Name": "Threat", "Severity Name": "Severity", "Category Name": "Category", "FWLink": "Link", "Path": "Path", "Cleaning Action": "Cleaning Action", "Signature Version": "SignatureVersion", "Engine Version": "EngineVersion"}, 1008: {"Descr": "<ProductName> has encountered an error when taking action on malware or " "other potentially unwanted software", "Provider": "Microsoft-Windows-Windows Defender", "Product Name": "ProductName", "Product Version": "ProductVersion", "Detection ID": "DetectionId", "Status Description": "Status", "Domain": "Domain", "User": "Username", "SID": "SID", "Threat ID": "ThreatId", "Threat Name": "Threat", "Severity Name": "Severity", "Category Name": "Category", "FWLink": "Link", "Path": "Path", "Error Code": "ErrorCode", "Error Description": "Error", "Signature Version": "SignatureVersion", "Engine Version": "EngineVersion"}, 1009: {"Descr": "<ProductName> has restored an item from quarantine", "Provider": "Microsoft-Windows-Windows Defender", "Product Name": "ProductName", "Product Version": "ProductVersion", "Domain": "Domain", "User": "Username", "SID": "SID", "Threat ID": "ThreatId", "Threat Name": "Threat", "Severity Name": "Severity", "Category Name": "Category", "FWLink": "Link", "Path": "Path", "Signature Version": "SignatureVersion", "Engine Version": "EngineVersion"}, 1010: {"Descr": "<ProductName> has encountered an error trying to restore an item from quarantine", "Provider": "Microsoft-Windows-Windows Defender", "Product Name": "ProductName", "Product Version": "ProductVersion", "Error Code": "ErrorCode", "Error Description": "Error", "Domain": "Domain", "User": "Username", "SID": "SID", "Threat ID": "ThreatId", "Threat Name": "Threat", "Severity Name": "Severity", "Category Name": "Category", "FWLink": "Link", "Path": "Path", "Signature Version": "SignatureVersion", "Engine Version": "EngineVersion"}, 1011: {"Descr": "<ProductName> has deleted an item from quarantine", "Provider": "Microsoft-Windows-Windows Defender", "Product Name": "ProductName", "Product Version": "ProductVersion", "Domain": "Domain", "User": "Username", "SID": "SID", "Threat ID": "ThreatId", "Threat Name": "Threat", "Severity Name": "Severity", "Category Name": "Category", "FWLink": "Link", "Path": "Path", "Signature Version": "SignatureVersion", "Engine Version": "EngineVersion"}, 1012: {"Descr": "<ProductName> has encountered an error trying to restore an item from quarantine", "Provider": "Microsoft-Windows-Windows Defender", "Product Name": "ProductName", "Product Version": "ProductVersion", "Error Code": "ErrorCode", "Error Description": "Error", "Domain": "Domain", "User": "Username", "SID": "SID", "Threat ID": "ThreatId", "Threat Name": "Threat", "Severity Name": "Severity", "Category Name": "Category", "FWLink": "Link", "Path": "Path", "Signature Version": "SignatureVersion", "Engine Version": "EngineVersion"}, 1015: {"Descr": "<ProductName> has detected a suspicious behavior", "Provider": "Microsoft-Windows-Windows Defender", "Product Name": "ProductName", "Product Version": "ProductVersion", "Detection ID": "DetectionId", "Detection Source": "Source", "Process Name": "ProcessPath", "Domain": "Domain", "User": "Username", "SID": "SID", "Threat ID": "ThreatId", "Threat Name": "Threat", "Severity Name": "Severity", "Category Name": "Category", "FWLink": "Link", "Path Found": "Path", "Detection Origin": "Origin", "Execution Status": "ExecutionStatus", "Detection Type": "Type", "Signature Version": "SignatureVersion", "Engine Version": "EngineVersion", "Process ID": "ProcessId", "Signature ID": "SignatureId", "FidelityValue": "FidelityValue", "FidelityLabel": "FidelityLabel", "Image File Hash": "ImageFileHash", "TargetFileName": "TargetFileName", "TargetFileHash": "TargetFileHash"}, 1116: {"Descr": "<ProductName> has detected malware or other potentially unwanted software", "Provider": "Microsoft-Windows-Windows Defender", "Product Name": "ProductName", "Product Version": "ProductVersion", "Detection ID": "DetectionId", "Detection Time": "DetectionTime", "Threat Name": "Threat", "Severity Name": "Severity", "Category Name": "Category", "FWLink": "Link", "Status Description": "Status", "Source Name": "Source", "Process Name": "ProcessPath", "Detection User": "DetectionUser", "Path": "Path", "Origin Name": "Origin", "Execution Name": "Execution", "Type Name": "Type", "Action Name": "Action", "Error Code": "ErrorCode", "Error Description": "Error", "Post Clean Status": "PostCleanStatus", "Additional Actions String": "AdditionalActions", "Remediation User": "RemediationUser", "Signature Version": "SignatureVersion", "Engine Version": "EngineVersion"}, 1117: {"Descr": "<ProductName> has taken action to protect this machine from malware or " "other potentially unwanted software", "Provider": "Microsoft-Windows-Windows Defender", "Product Name": "ProductName", "Product Version": "ProductVersion", "Detection ID": "DetectionId", "Detection Time": "DetectionTime", "Threat Name": "Threat", "Severity Name": "Severity", "Category Name": "Category", "FWLink": "Link", "Status Description": "Status", "Source Name": "Source", "Process Name": "ProcessPath", "Detection User": "DetectionUser", "Path": "Path", "Origin Name": "Origin", "Execution Name": "Execution", "Type Name": "Type", "Action Name": "Action", "Error Code": "ErrorCode", "Error Description": "Error", "Post Clean Status": "PostCleanStatus", "Additional Actions String": "AdditionalActions", "Remediation User": "RemediationUser", "Signature Version": "SignatureVersion", "Engine Version": "EngineVersion"}, 1118: {"Descr": "<ProductName> has encountered a non-critical error when taking action on malware or " "other potentially unwanted software", "Provider": "Microsoft-Windows-Windows Defender", "Product Name": "ProductName", "Product Version": "ProductVersion", "Detection ID": "DetectionId", "Detection Time": "DetectionTime", "Threat Name": "Threat", "Severity Name": "Severity", "Category Name": "Category", "FWLink": "Link", "Status Description": "Status", "Source Name": "Source", "Process Name": "ProcessPath", "Detection User": "DetectionUser", "Path": "Path", "Origin Name": "Origin", "Execution Name": "Execution", "Type Name": "Type", "Action Name": "Action", "Error Code": "ErrorCode", "Error Description": "Error", "Post Clean Status": "PostCleanStatus", "Additional Actions String": "AdditionalActions", "Remediation User": "RemediationUser", "Signature Version": "SignatureVersion", "Engine Version": "EngineVersion"}, 1119: {"Descr": "<ProductName> has encountered a critical error when taking action on malware or " "other potentially unwanted software", "Provider": "Microsoft-Windows-Windows Defender", "Product Name": "ProductName", "Product Version": "ProductVersion", "Detection ID": "DetectionId", "Detection Time": "DetectionTime", "Threat Name": "Threat", "Severity Name": "Severity", "Category Name": "Category", "FWLink": "Link", "Status Description": "Status", "Source Name": "Source", "Process Name": "ProcessPath", "Detection User": "DetectionUser", "Path": "Path", "Origin Name": "Origin", "Execution Name": "Execution", "Type Name": "Type", "Action Name": "Action", "Error Code": "ErrorCode", "Error Description": "Error", "Post Clean Status": "PostCleanStatus", "Additional Actions String": "AdditionalActions", "Remediation User": "RemediationUser", "Signature Version": "SignatureVersion", "Engine Version": "EngineVersion"}, 1160: {"Descr": "<ProductName has detected potentially unwanted application (PUA)", "Provider": "Microsoft-Windows-Windows Defender", "Product Name": "ProductName", "Product Version": "ProductVersion", "Detection ID": "DetectionId", "Detection Time": "DetectionTime", "Threat Name": "Threat", "Severity Name": "Severity", "Category Name": "Category", "FWLink": "Link", "Status Description": "Status", "Source Name": "Source", "Process Name": "ProcessPath", "Detection User": "DetectionUser", "Path": "Path", "Origin Name": "Origin", "Execution Name": "Execution", "Type Name": "Type", "Action Name": "Action", "Error Code": "ErrorCode", "Error Description": "Error", "Post Clean Status": "PostCleanStatus", "Additional Actions String": "AdditionalActions", "Remediation User": "RemediationUser", "Signature Version": "SignatureVersion", "Engine Version": "EngineVersion"}, 2050: {"Descr": "<ProductName> has uploaded a file for further analysis", "Provider": "Microsoft-Windows-Windows Defender", "Product Name": "ProductName", "Product Version": "ProductVersion", "Filename": "FileName", "Sha256": "FileHash"}, 2051: {"Descr": "<ProductName> has encountered an error trying to upload a suspicious file for further analysis", "Provider": "Microsoft-Windows-Windows Defender", "Product Name": "ProductName", "Product Version": "ProductVersion", "Filename": "FileName", "Sha256": "FileHash", "Signature Version": "SignatureVersion", "Engine Version": "EngineVersion", "Error Code": "ErrorCode"}, 3002: {"Descr": "<ProductName> Real-Time Protection feature has encountered an error and failed", "Provider": "Microsoft-Windows-Windows Defender", "Product Name": "ProductName", "Product Version": "ProductVersion", "Feature Name": "Feature", "Reason": "Reason", "Error Code": "ErrorCode", "Error Description": "ErrorDescr", "Feature ID": "FeatureId"}, 3007: {"Descr": "<ProductName> Real-time Protection feature has restarted", "Provider": "Microsoft-Windows-Windows Defender", "Product Name": "ProductName", "Product Version": "ProductVersion", "Feature Name": "Feature", "Reason": "Reason", "Feature ID": "FeatureId"}, 5000: {"Descr": "<ProductName> Real-time Protection scanning for malware and " "other potentially unwanted software was enabled", "Provider": "Microsoft-Windows-Windows Defender", "Product Name": "ProductName", "Product Version": "ProductVersion"}, 5001: {"Descr": "<ProductName> Real-time Protection scanning for malware and " "other potentially unwanted software was disabled", "Provider": "Microsoft-Windows-Windows Defender", "Product Name": "ProductName", "Product Version": "ProductVersion"}, 5004: {"Descr": "<ProductName> Real-time Protection feature configuration has changed", "Provider": "Microsoft-Windows-Windows Defender", "Product Name": "ProductName", "Product Version": "ProductVersion", "Feature Name": "Feature", "Feature ID": "FeatureId"}, 5007: {"Descr": "<ProductName> Configuration has changed. " "If this is unexpected, you should review the settings as this may be the result of malware", "Provider": "Microsoft-Windows-Windows Defender", "Product Name": "ProductName", "Product Version": "ProductVersion", "Old Value": "OldValue", "New Value": "NewValue"}, 5008: {"Descr": "<ProductName> engine has been terminated due to an unexpected error", "Provider": "Microsoft-Windows-Windows Defender", "Product Name": "ProductName", "Product Version": "ProductVersion", "Resource": "Resource", "Failure Type": "FailureType", "Exception Code": "ExceptionCode"}, 5009: {"Descr": "<ProductName> scanning for spyware and other potentially unwanted software has been enabled", "Provider": "Microsoft-Windows-Windows Defender", "Product Name": "ProductName", "Product Version": "ProductVersion"}, 5010: {"Descr": "<ProductName> scanning for spyware and other potentially unwanted software is disabled", "Provider": "Microsoft-Windows-Windows Defender", "Product Name": "ProductName", "Product Version": "ProductVersion"}, 5011: {"Descr": "<ProductName> scanning for viruses has been enabled", "Provider": "Microsoft-Windows-Windows Defender", "Product Name": "ProductName", "Product Version": "ProductVersion"}, 5012: {"Descr": "<ProductName> scanning for viruses is disabled", "Provider": "Microsoft-Windows-Windows Defender", "Product Name": "ProductName", "Product Version": "ProductVersion"}, 5013: {"Descr": "Tamper Protection <ChangedType> to <Value>", # Win10 v2004+ "Provider": "Microsoft-Windows-Windows Defender", "Product Name": "ProductName", "Product Version": "ProductVersion", "Changed Type": "ChangedType", "Value": "Value"} } winrm = { # Microsoft-Windows-WinRM/Operational 6: {"Descr": "Creating WSMan session. The connection string is <Connection>", "Provider": "Microsoft-Windows-WinRM", "connection": "Connection"}, 8: {"Descr": "Closing WSMan session", "Provider": "Microsoft-Windows-WinRM"}, # empty 15: {"Descr": "Closing WSMan command", "Provider": "Microsoft-Windows-WinRM"}, # empty 16: {"Descr": "Closing WSMan shell", "Provider": "Microsoft-Windows-WinRM"}, # empty 33: {"Descr": "Closing WSMan session completed successfully", "Provider": "Microsoft-Windows-WinRM"}, # empty 91: {"Descr": "Creating WSMan shell on server with <ResourceUri>", "Provider": "Microsoft-Windows-WinRM", "resourceUri": "ResourceUri", "shellId": "ShellId"}, 169: {"Descr": "<TargetUsername> authenticated successfully using <AuthMechanism>", # Win7 only? "Provider": "Microsoft-Windows-WinRM", "username": "TargetUsername", "authenticationMechanism": "AuthMechanism"} } wlan = { # Microsoft-Windows-WLAN-AutoConfig/Operational 8001: {"Descr": "WLAN AutoConfig service has successfully connected to a wireless network", "Provider": "Microsoft-Windows-WLAN-AutoConfig", "InterfaceGuid": "InterfaceGuid", "InterfaceDescription": "InterfaceDescr", "ConnectionMode": "ConnectionMode", "ProfileName": "ProfileName", "SSID": "SSID", "BSSType": "BSSType", "PHYType": "PHYType", "AuthenticationAlgorithm": "AuthAlgo", "CipherAlgorithm": "CipherAlgo", "OnexEnabled": "IsOnexEnabled", "ConnectionId": "ConnectionId", "NonBroadcast": "IsNonBroadcast"}, 8002: {"Descr": "WLAN AutoConfig service failed to connect to a wireless network", "Provider": "Microsoft-Windows-WLAN-AutoConfig", "InterfaceGuid": "InterfaceGuid", "InterfaceDescription": "InterfaceDescr", "ConnectionMode": "ConnectionMode", "ProfileName": "ProfileName", "SSID": "SSID", "BSSType": "BSSType", "FailureReason": "FailureReason", "ReasonCode": "ReasonCode", "ConnectionId": "ConnectionId", "RSSI": "RSSI"}, 8003: {"Descr": "WLAN AutoConfig service has successfully disconnected from a wireless network", "Provider": "Microsoft-Windows-WLAN-AutoConfig", "InterfaceGuid": "InterfaceGuid", "InterfaceDescription": "InterfaceDescr", "ConnectionMode": "ConnectionMode", "ProfileName": "ProfileName", "SSID": "SSID", "BSSType": "BSSType", "Reason": "Reason", "ConnectionId": "ConnectionId", "ReasonCode": "ReasonCode"}, 11000: {"Descr": "Wireless network association started", "Provider": "Microsoft-Windows-WLAN-AutoConfig", "DeviceGuid": "InterfaceGuid", "Adapter": "InterfaceDescr", "LocalMac": "LocalMac", "SSID": "SSID", "BSSType": "BSSType", "Auth": "AuthAlgo", "Cipher": "CipherAlgo", "OnexEnabled": "IsOnexEnabled", "ConnectionId": "ConnectionId", "IhvConnectivitySetting": "IhvConnectivitySetting"}, 11001: {"Descr": "Wireless network association succeeded", "Provider": "Microsoft-Windows-WLAN-AutoConfig", "DeviceGuid": "InterfaceGuid", "Adapter": "InterfaceDescr", "LocalMac": "LocalMac", "SSID": "SSID", "BSSType": "BSSType", "ConnectionId": "ConnectionId", "MgmtFrameProtection": "MgmtFrameProtection"}, 11002: {"Descr": "Wireless network association failed", "Provider": "Microsoft-Windows-WLAN-AutoConfig", "DeviceGuid": "InterfaceGuid", "Adapter": "InterfaceDescr", "LocalMac": "LocalMac", "SSID": "SSID", "BSSType": "BSSType", "FailureReason": "FailureReason", "ReasonCode": "ReasonCode", "Dot11StatusCode": "Dot11StatusCode", "ConnectionId": "ConnectionId", "RSSI": "RSSI"} } wmi = { # Microsoft-Windows-WMI-Activity/Operational (Win8+) 5857: {"Descr": "<ProviderName> started with <ResultCode>", # wmiprvse execution "ProviderName": "ProviderName", "Code": "ResultCode", "HostProcess": "ProcessName", "ProcessID": "ProcessID", "ProviderPath": "ProviderPath"}, 5858: {"Descr": "WMI execution error", "Provider": "Microsoft-Windows-WMI-Activity", "ClientMachine": "Hostname", "User": "Username", "ClientProcessId": "ProcessId", "Component": "Component", "Operation": "Operation", "ResultCode": "ResultCode", "PossibleCause": "PossibleCause"}, 5860: {"Descr": "Registration of temporary event consumer", # Win10 v1511+ "Provider": "Microsoft-Windows-WMI-Activity", "NamespaceName": "Namespace", "Query": "Query", "User": "Username", "processid": "ProcessId", # < Win10 v1803 "Processid": "ProcessId", # Win10 v1803+ "MachineName": "Hostname", # < Win10 v1803 "ClientMachine": "Hostname", # Win10 v1803+ "PossibleCause": "PossibleCause"}, 5861: {"Descr": "Registration of permanent event consumer", # Win10 v1607+ "Provider": "Microsoft-Windows-WMI-Activity", "Namespace": "Namespace", "ESS": "ESS", "CONSUMER": "Consumer", "PossibleCause": "PossibleCause"} }
"""Exceptions.py Define exceptions used by the library.""" class ResponseError(Exception): """Own class for exceptions related to response errors. Currently only present in two places.""" pass #Don't do anything else than just define the function
def get_friendly_dict(friend_list): """ Accept a list of reciprocal friendship links between individuals and return a dictionary of degree-one friends of each individual in a social network. """ # first, we'll get all the individuals name using union set and put it into # unique_name list unique_name_list = set() for friend in range(1, len(friend_list)): unique_name = set(friend_list[friend - 1]) | set(friend_list[friend]) if unique_name not in unique_name_list: unique_name_list.update(unique_name) # second, we'll get the 1st degree friend by iterating in the tuple of a # list and then add them into a set (new_friend_set) if it is not the given # individual before adding into a dicitionary. new_bestie_friend_dict = {} for name in unique_name_list: new_friend_set = set() for name_friend_list in range(len(friend_list)): if name in friend_list[name_friend_list]: for inside_friend in friend_list[name_friend_list]: if inside_friend != name: new_friend_set.add(inside_friend) new_bestie_friend_dict[name] = new_friend_set return new_bestie_friend_dict
class Solution: def arrayRankTransform(self, arr2: List[int]) -> List[int]: d = {} if len(arr2)==0: return [] ct = 1 arr = sorted(arr2) d[arr[0]] = 1 for i in range(1,len(arr)): if arr[i]>arr[i-1]: ct+=1 d[arr[i]] = ct res = [1] *len(arr) for ind,i in enumerate(arr2): if i in d: res[ind] = d[i] return res
# Our server roles: config.rdbms = ['127.0.0.1'] config.httpd = ['localhost'] def production(): # this would set `rdbms` and `httpd` to prod. values. # for now we just switch them around in order to observe the effect config.rdbms, config.httpd = config.httpd, config.rdbms def build(): local('echo Building project') @roles('rdbms') def prepare_db(): run("echo Preparing database for deployment") @roles('httpd') def prepare_web(): run("echo Preparing web servers for deployment") @depends(prepare_db, prepare_web) @roles('httpd') def deploy(): run("echo Doing final deployment things to $(fab_host)")
''' - DESAFIO 03 - Crie um script Python que leia dois números e tente mostrar a soma entre eles ''' n1 = int(input('\033[33mPrimeiro número:\033[m ')) n2 = int(input('\033[34mSegundo número:\033[m ')) print('\033[35mA soma entre\033[m \033[31m{}\033[m \033[35me\033[m \033[31m{}\033[m \033[35mé igual a\033[m' ' \033[34m{}\033[m'.format(n1, n2, n1 + n2))
class Conto: def __init__(self, numero_conto, cliente, saldo=0.00): self.__numero_conto = numero_conto self.__cliente = cliente self.__saldo = saldo # Definizione di getter e setter # @property def numero_conto(self): return self.__numero_conto @numero_conto.setter def numero_conto(self, numero_conto): self.__numero_conto = numero_conto @property def cliente(self): return self.__cliente @cliente.setter def cliente(self, cliente): self.__cliente = cliente @property def saldo(self): return self.__saldo @saldo.setter def saldo(self, saldo): self.__saldo = saldo def __repr__(self): return "Conto " + self.numero_conto + " intestato a cliente " + self.cliente.nome_cliente + " con saldo " + str(self.saldo) + "€"
# -------------- ##File path for the file file_path #Code starts here #Function to read file def read_file(path): #Opening of the file located in the path in 'read' mode file = open(path, 'r') #Reading of the first line of the file and storing it in a variable sentence=file.readline() #Closing of the file file.close() #Returning the first line of the file return sentence #Calling the function to read file sample_message=read_file(file_path) #Printing the line of the file print(sample_message) #Code ends here #Code starts here # -------------- #Code starts here ##File path for the file file_path_1, file_path_2 #Code starts here #Function to read file def read_file1(file1): #Opening of the file located in the path in 'read' mode file1 = open(file_path_1, 'r') #Reading of the first line of the file and storing it in a variable sentence1=file1.readline() #Closing of the file file1.close() #Returning the first line of the file return sentence1 def read_file2(file2): file2 = open(file_path_2,'r') sentence2=file2.readline() file2.close() return sentence2 #Calling the function to read file message_1=str(read_file1(file_path_1)) message_2=str(read_file2(file_path_2)) #Code ends here def fuse_msg(message_a,message_b): quotient=(int(message_b)//int(message_a)) return str(quotient) secret_msg_1=fuse_msg(message_1,message_2) #Code starts here # -------------- #Code starts here file_path_3 #Code starts here #Function to read file def read_file(file3): #Opening of the file located in the path in 'read' mode file3 = open(file_path_3, 'r') #Reading of the first line of the file and storing it in a variable sentence3=file3.readline() #Closing of the file file3.close() #Returning the first line of the file return sentence3 #Calling the function to read file message_3=read_file(file_path_3) #Printing the line of the file print(message_3) def substitute_msg(message_c): if message_c =='Red': sub=('Army General') elif message_c == 'Green': sub=('Data Scientist') elif message_c == 'Blue': sub=('Marine Biologist') return sub secret_msg_2=substitute_msg(message_3) # -------------- # File path for message 4 and message 5 file_path_4 file_path_5 def compare_msg(message_d,message_e): a_list=message_d.split(' ') b_list=message_e.split(' ') c_list=[i for i in a_list if i not in b_list] final_msg=" ".join(c_list) return final_msg #Code starts here message_4='I hope you are good now' message_5='I hope good things happen in your life.' print(message_4) print(message_5) secret_msg_3='you are now' # -------------- #Code starts here file_path_6 file6= open(file_path_6,'r') message_6= file6.readline() print(message_6) def extract_msg(message_f): a_list= message_f.split() even_word = lambda message_f: len(message_f)%2==0 b_list=filter(even_word,a_list) final_msg=' '.join(b_list) return final_msg secret_msg_4=extract_msg(message_6) secret_msg_4 = str(secret_msg_4) secret_msg_4 # -------------- #Secret message parts in the correct order message_parts=[secret_msg_3, secret_msg_1, secret_msg_4, secret_msg_2] secret_msg = ' '.join(message_parts) print(secret_msg) final_path= user_data_dir + '/secret_message.txt' #Code starts here def write_file(secret_msg,path): g = open(final_path,'a+') g.write(secret_msg) g.close() write_file(secret_msg,final_path)
def decompose(n): return helper(n, n**2) def helper(n, sum, arr=[]): if sum==0: return arr[::-1] for i in range(n-1, -1, -1): if i**2<=sum: return helper(i, sum-i**2, arr+[i]) or helper(i, sum, arr)
""" Given three sorted arrays A, B and C of not necessarily same sizes. Calculate the minimum absolute difference between the maximum and minimum number from the triplet a, b, c such that a, b, c belongs arrays A, B, C respectively. i.e. minimize | max(a,b,c) - min(a,b,c) |. Example : Input: A : [ 1, 4, 5, 8, 10 ] B : [ 6, 9, 15 ] C : [ 2, 3, 6, 6 ] Output: 1 Explanation: We get the minimum difference for a=5, b=6, c=6 as | max(a,b,c) - min(a,b,c) | = |6-5| = 1. """ class Solution: def min_abs_diff(self, a, b, c): m, n, p = len(a), len(b), len(c) i, j, k = 0, 0, 0 abs_min = 10000000000 curr_min = -1 while i < m and j < n and k < p: curr_min = abs(max(a[i], b[j], c[k]) - min(a[i], b[j], c[k])) if curr_min < abs_min: abs_min = curr_min if abs_min == 0: break if a[i] == min(a[i], b[j], c[k]): i += 1 elif b[j] == min(a[i], b[j], c[k]): j += 1 else: k += 1 return abs_min s = Solution() a = [36, 58, 64, 76, 111, 131, 131, 132, 166, 174, 192, 223, 235, 243, 248, 296, 325, 335, 372, 389, 426, 446, 448, 472, 506, 508, 550, 585, 614, 628, 665, 672, 720, 744, 765, 799, 822, 853, 897, 932, 950, 964, 992, 1025, 1049, 1093, 1114, 1140, 1148, 1174, 1209, 1255, 1273, 1275, 1285, 1293, 1340, 1361, 1401, 1440, 1474, 1489, 1501, 1522, 1549, 1550, 1555, 1564, 1605, 1640, 1645, 1666, 1668, 1688, 1702, 1722, 1732, 1776, 1799, 1806, 1810, 1813, 1831, 1866] b = [-373, -334, -322, -299, -267, -237, -190, -175, -153, -122, -118, -79, -55, -37, -20, -19, 20, 32, 40, 67, 116, 129, 132, 137, 176, 198, 214, 230, 271, 314, 341, 353, 379, 381, 386, 397, 402, 408, 426, 429, 431, 432, 452, 500, 543, 590, 597, 631, 660, 668, 684, 722, 762, 778, 826, 831, 834, 841, 888, 898, 940, 956, 996, 998, 1047, 1064, 1084, 1096, 1121, 1159, 1176, 1178, 1191, 1239, 1283, 1305, 1347, 1353, 1401, 1416, 1459, 1469, 1504, 1517, 1548, 1574, 1598, 1619, 1623, 1627, 1675, 1681, 1710, 1723, 1731, 1737, 1779, 1823, 1825, 1832, 1834, 1860, 1873, 1881, 1888, 1923, 1938, 1957, 2000, 2042, 2081, 2090, 2133, 2135, 2145, 2187, 2205, 2226, 2272, 2315, 2349, 2382, 2397, 2431, 2457] c = [24, 31, 49, 59, 90, 120, 129, 157, 205, 242, 287, 311, 355, 402, 413, 413, 427, 461, 486, 493, 520, 529, 553, 560, 596, 620, 631, 654, 674, 705, 705, 706, 751, 790, 837, 872, 918, 965, 987, 996, 1039, 1045, 1079, 1109, 1136, 1179, 1183, 1232, 1256, 1283, 1316, 1346] print(s.min_abs_diff(a, b, c))
""" Check BinaryTree section This question is also in the SDE Sheet Learn : The Height can be defined over a binary tree, but depth is defined over a node, ie there is a dept of each node """
def filterTags(attrs): """ Convert some ShapeVIS attributes to OSM. """ result = {} if 'HAALPLTSMN' in attrs: result['name'] = attrs['HAALPLTSMN'] result['bus'] = 'yes' # Default result['public_transport'] = 'stop_position' if 'station' in result['name'].lower() and\ 'centrum' in result['name'].lower(): result['public_transport'] = 'station' return result
# Exercício Python 62: Melhore o DESAFIO 61, perguntando para o usuário se ele quer mostrar mais alguns termos. # O programa encerrará quando ele disser que quer mostrar 0 termos. print('GERADOR DE PA') print('-=' * 10) num = int(input('Primeiro termo: ')) razao = int(input('Razão da PA: ')) print('-=' * 10) cont = 1 total = 0 mais = 10 print() while mais != 0: total += mais while cont <= total: print('{} -> '.format(num), end='') num += razao cont += 1 print('PAUSA\n') mais = int(input('Quantos termos dessa PA você quer ver mais (0 para sair): ')) print('\nProgressão finalizada com {} termos mostrados.'.format(total))
class person: def __init__(self, first_name, last_name): self.first_name = first_name self.last_name = last_name def fullname(self): return f"{self.first_name} {self.last_name}" def email(self): return f"{self.first_name}{self.last_name}@gmail.com"
class Blood(object): """ Most characters will have ordinary blood but some could have acidic blood or with other properties. """ def __init__(self, uid, name): self.uid = uid self.name = name
class WorksharingUtils(object,IDisposable): """ A static class that contains utility functions related to worksharing. """ @staticmethod def CheckoutElements(document,elementsToCheckout,options=None): """ CheckoutElements(document: Document,elementsToCheckout: ICollection[ElementId]) -> ICollection[ElementId] CheckoutElements(document: Document,elementsToCheckout: ISet[ElementId],options: TransactWithCentralOptions) -> ISet[ElementId] """ pass @staticmethod def CheckoutWorksets(document,worksetsToCheckout,options=None): """ CheckoutWorksets(document: Document,worksetsToCheckout: ICollection[WorksetId]) -> ICollection[WorksetId] CheckoutWorksets(document: Document,worksetsToCheckout: ISet[WorksetId],options: TransactWithCentralOptions) -> ISet[WorksetId] """ pass @staticmethod def CreateNewLocal(sourcePath,targetPath): """ CreateNewLocal(sourcePath: ModelPath,targetPath: ModelPath) Takes a path to a central model and copies the model into a new local file for the current user. sourcePath: The path to the central model. targetPath: The path to put the new local file. """ pass def Dispose(self): """ Dispose(self: WorksharingUtils) """ pass @staticmethod def GetCheckoutStatus(document,elementId,owner=None): """ GetCheckoutStatus(document: Document,elementId: ElementId) -> (CheckoutStatus,str) Gets the ownership status and outputs the owner of an element. document: The document containing the element. elementId: The id of the element. Returns: An indication of whether the element is unowned,owned by the current user,or owned by another user. GetCheckoutStatus(document: Document,elementId: ElementId) -> CheckoutStatus Gets the ownership status of an element. document: The document containing the element. elementId: The id of the element. Returns: A summary of whether the element is unowned,owned by the current user,or owned by another user. """ pass @staticmethod def GetModelUpdatesStatus(document,elementId): """ GetModelUpdatesStatus(document: Document,elementId: ElementId) -> ModelUpdatesStatus Gets the status of a single element in the central model. document: The document containing the element. elementId: The id of the element. Returns: The status of the element in the local session versus the central model. """ pass @staticmethod def GetUserWorksetInfo(path): """ GetUserWorksetInfo(path: ModelPath) -> IList[WorksetPreview] Gets information about user worksets in a workshared model file,without fully opening the file. path: The path to the workshared model. Returns: Information about all the user worksets in the model. The list is sorted by workset id. """ pass @staticmethod def GetWorksharingTooltipInfo(document,elementId): """ GetWorksharingTooltipInfo(document: Document,elementId: ElementId) -> WorksharingTooltipInfo Gets worksharing information about an element to display in an in-canvas tooltip. document: The document containing the element elementId: The id of the element in question Returns: Worksharing information about the specified element. """ pass def ReleaseUnmanagedResources(self,*args): """ ReleaseUnmanagedResources(self: WorksharingUtils,disposing: bool) """ pass @staticmethod def RelinquishOwnership(document,generalCategories,options): """ RelinquishOwnership(document: Document,generalCategories: RelinquishOptions,options: TransactWithCentralOptions) -> RelinquishedItems Relinquishes ownership by the current user of as many specified elements and worksets as possible, and grants element ownership requested by other users on a first-come,first-served basis. document: The document containing the elements and worksets. generalCategories: General categories of items to relinquish. See RelinquishOptions for details. options: Options to customize access to the central model. ll is allowed and means no customization. Returns: The elements and worksets that were relinquished. """ pass def __enter__(self,*args): """ __enter__(self: IDisposable) -> object """ pass def __exit__(self,*args): """ __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) """ pass def __init__(self,*args): """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass def __repr__(self,*args): """ __repr__(self: object) -> str """ pass IsValidObject=property(lambda self: object(),lambda self,v: None,lambda self: None) """Specifies whether the .NET object represents a valid Revit entity. Get: IsValidObject(self: WorksharingUtils) -> bool """
''' Set Matrix Zeros Asked in: Oracle, Amazon https://www.interviewbit.com/problems/set-matrix-zeros/ Given a matrix, A of size M x N of 0s and 1s. If an element is 0, set its entire row and column to 0. Note: This will be evaluated on the extra memory used. Try to minimize the space and time complexity. Input Format: The first and the only argument of input contains a 2-d integer matrix, A, of size M x N. Output Format: Return a 2-d matrix that satisfies the given conditions. Constraints: 1 <= N, M <= 1000 0 <= A[i][j] <= 1 Examples: Input 1: [ [1, 0, 1], [1, 1, 1], [1, 1, 1] ] Output 1: [ [0, 0, 0], [1, 0, 1], [1, 0, 1] ] Input 2: [ [1, 0, 1], [1, 1, 1], [1, 0, 1] ] Output 2: [ [0, 0, 0], [1, 0, 1], [0, 0, 0] ] ''' # @param A : list of list of integers # @return the same list modified def setZeroes(A): if not A: return A m = len(A) n = len(A[0]) rows = [False] * m cols = [False] * n for i in range(m): for j in range(n): if A[i][j]==0: rows[i] = True cols[j] = True for i in range(m): for j in range(n): if rows[i] or cols[j]: A[i][j] = 0 return A if __name__ == "__main__": data = [ [ [[1, 0, 1], [1, 1, 1], [1, 1, 1]], [[0, 0, 0], [1, 0, 1], [1, 0, 1]] ] ] for d in data: print('input', d[0], 'output', setZeroes(d[0]))
# -*- coding: utf-8 -*- """ Crie um programa que leia o nome e o preço de vários produtos. O programa deverá perguntar se o usuário vai continuar. No final, mostre. A) Qual é o total gasto na compra B) Quantos produtos custam mais de R$1000. C) Qual é o nome do produto mais barato """ barato = total = quant_prod1000 = preco = soma = i = 0 n = produto = prod_barato = '' print('Carrinho de compras', '-0'* 20) while True: if n == 'n': break produto = str(input('Digite o nome do produto: ')) preco = float(input('Digite o preço do produto: ')) if i == 0: barato = preco if preco > 1000 : quant_prod1000 += 1 if preco <= barato: barato = preco prod_barato = produto soma += preco i+= 1 n = str(input('Deseja continuar[S/N]? ')).lower() print(f'O total gasto na compra foi de R${soma:.2f}') print(f'hà {quant_prod1000} produtos acima de R$1000.00 ') print(f'O produto mais barato foi o {prod_barato} que custa R${barato:.2f}')
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html class MoviePipeline(object): def process_item(self, item, spider): with open('out/my_meiju.txt', 'a', encoding='UTF-8') as fp: fp.write(str(item['name'].strip()) + '\n')
""" Covid-19 is spreading fast! There are N cities, numbered from 0 to (N−1), arranged in a circular manner. City 0 is connected to city 1, 1 to 2, …, city (N−2) to city (N−1), and city (N−1) to city 0. The virus is currently at city X. Each day, it jumps from its current city, to the city K to its right, i.e., from city X to the city (X+K)%N. As the virus jumps, the cities in between don't get infected. Cities once infected stay infected. You live in city Y. Find if it will reach your city eventually. If it will, print YES, else print NO. Input: The first line of the input consists of an integer T, the number of test cases. The first and only line of each test case contains four space-separated integers - N, K, X and Y, denoting the number of cities, the size of jumps, Covid's current city, and the city that you live in, respectively. Output: For each test case, in a new line, print YES if Covid shall reach your city after a finite number of days, else print NO. Constraints 1≤T≤100 1≤N≤1000 0≤X,Y≤N−1 0≤K≤1000 """
number = int(input()) synonyms_dict = dict() for num in range (number): word = input() synonym = input() if word not in synonyms_dict.keys(): synonyms_dict[word] = list() synonyms_dict[word].append(synonym) for word in synonyms_dict: synonyms = ", ".join(synonyms_dict[word]) print(f"{word} - {synonyms}")
# Copyright 2014 Modelling, Simulation and Design Lab (MSDL) at # McGill University and the University of Antwerp (http://msdl.cs.mcgill.ca/) # # 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. """ Relocator for user-provided relocation directives """ class MyRelocator(object): """ Main class """ def __init__(self): """ Initialize the relocator """ pass def setController(self, controller): """ Sets the controller """ pass def getRelocations(self, gvt, activities, horizon): """ Fetch the relocations that are pending for the current GVT :param gvt: current GVT :param activities: the activities being passed on the GVT ring :returns: dictionary containing all relocations """ # Perform a relocation, for example move the model with ID 1 to node 2, and the model with ID 3 to node 0 # Remaps are allowed to happen to the current location, as they will simply be discarded by the actual relocator relocate = {1: 2, 3: 0} return relocate def lastStateOnly(self): """ Should the sum of all activities within this horizon be used, or simply the activity from the last state? This has no effect on performance, but defines which activities the relocator can read. Use 'last state only' if you require an abstracted view of the activities at a single timestep (equal to the GVT). Use 'all states' if you require all information to be merged, such as in activity tracking. """ # "all states" return False
""" django_ocr_server/tests/__init__.py +++++++++++++++++++++++++++++++++++ | Author: shmakovpn <[email protected]> | Date: 2021-01-07 """
class Person: # allocate space for only these attributes so we don't need to create a __dict__ property in the class and we save space when parsing large files __slots__ = ["lastName", "firstName", "middleInitial", "gender", "favoriteColor", "dateOfBirth"] def __init__(self, lastName, firstName, middleInitial, gender, favoriteColor, dateOfBirth): self.lastName = lastName self.firstName = firstName self.middleInitial = middleInitial self.gender = gender self.favoriteColor = favoriteColor self.dateOfBirth = dateOfBirth def getGenderString(self): if self.gender == "M" or self.gender == "Male": return "Male" elif self.gender == "F" or self.gender == "Female": return "Female"
expected_output = { '10.1.1.2': { 'conn_capability': 'IPv4-IPv6-Subnet', 'conn_inst': 1, 'conn_status': 'On (Speaker) :: On (Listener)', 'conn_version': 5, 'duration': '0:00:00:57 (dd:hr:mm:sec) :: 0:00:00:55 (dd:hr:mm:sec)', 'local_mode': 'Both', 'peer_ip': '10.1.1.2', 'source_ip': '10.1.1.1', 'tcp_conn_fd': '1(Speaker) 2(Listener)', 'speaker_conn_hold_time': 120, 'listener_conn_hold_time': 120, 'tcp_conn_pwd': 'default SXP password' }, 'default_key_chain': 'Not Set', 'default_key_chain_name': 'Not Applicable', 'default_pwd': 'Set', 'default_source_ip': 'Not Set', 'export_traverse_limit': 'Not Set', 'highest_version': 5, 'import_traverse_limit': 'Not Set', 'reconcile_period': 120, 'retry_period': 120, 'retry_timer': 'not running', 'sxp_status': 'Enabled', 'total_sxp_connections': 1 }
class Stack: def __init__(self): self.list = [] def push(self, element): self.list.append(element) def pop(self): assert len(self.list) > 0, "Stack is empty" return self.list.pop() def isEmpty(self): return len(self.list) == 0
""" Class that implements K stacks in an array """ class KStacks: def __init__(self, cap, k): self.tops = [-1] * k self.arr = [0] * cap self.next = [-1] * cap self.free_top = 0 for i in range(cap-1): self.next[i] = i+1 self.capacity = cap def push(self, ele, stack): i = self.free_top self.free_top = self.next[i] self.arr[i] = ele self.next[i] = self.tops[stack] self.tops[stack] = i def pop(self, stack): i = self.tops[stack] self.tops[stack] = self.next[i] self.next[i] = self.free_top self.free_top = i return self.arr[i] def main(): k_obj = KStacks(6, 3) k_obj.push(100, 0) k_obj.push(200, 0) k_obj.push(300, 0) k_obj.push(400, 1) # Using the special variable # __name__ if __name__ == "__main__": main()
#!/usr/bin/python # Calculer la somme des valeurs du tableau def somme_tab(tab): somme = 0 for i in range(len(tab)): somme += tab[i] return somme tab = [5, 18.5, 13.2, 8.75, 2, 15, 13.5, 6, 17] print(somme_tab(tab))
# Creating a Dictionary # with Integer Keys Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'} print("\nDictionary with the use of Integer Keys: ") print(Dict) # Creating a Dictionary # with Mixed keys Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]} print("\nDictionary with the use of Mixed Keys: ") print(Dict) # Creating an empty Dictionary Dict = {} print("Empty Dictionary: ") print(Dict) # Creating a Dictionary # with dict() method Dict = dict({1: 'Geeks', 2: 'For', 3: 'Geeks'}) print("\nDictionary with the use of dict(): ") print(Dict) # Creating a Dictionary # with each item as a Pair Dict = dict([(1, 'Geeks'), (2, 'For')]) print("\nDictionary with each item as a pair: ") print(Dict) # Creating a Nested Dictionary # as shown in the below image Dict = {1: 'Geeks', 2: 'For', 3: {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'}} print(Dict) # Creating an empty Dictionary Dict = {} print("Empty Dictionary: ") print(Dict) # Adding elements one at a time Dict[0] = 'Geeks' Dict[2] = 'For' Dict[3] = 1 print("\nDictionary after adding 3 elements: ") print(Dict) # Adding set of values # to a single Key Dict['Value_set'] = 2, 3, 4 print("\nDictionary after adding 3 elements: ") print(Dict) # Updating existing Key's Value Dict[2] = 'Welcome' print("\nUpdated key value: ") print(Dict) # Adding Nested Key value to Dictionary Dict[5] = {'Nested': {'1': 'Life', '2': 'Geeks'}} print("\nAdding a Nested Key: ") print(Dict) # Python program to demonstrate # accessing a element from a Dictionary # Creating a Dictionary Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'} # accessing a element using key print("Accessing a element using key:") print(Dict['name']) # accessing a element using key print("Accessing a element using key:") print(Dict[1]) # Creating a Dictionary Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'} # accessing a element using get() # method print("Accessing a element using get:") print(Dict.get(3)) # Creating a Dictionary Dict = {'Dict1': {1: 'Geeks'}, 'Dict2': {'Name': 'For'}} # Accessing element using key print(Dict['Dict1']) print(Dict['Dict1'][1]) print(Dict['Dict2']['Name']) # Initial Dictionary Dict = {5: 'Welcome', 6: 'To', 7: 'Geeks', 'A': {1: 'Geeks', 2: 'For', 3: 'Geeks'}, 'B': {1: 'Geeks', 2: 'Life'}} print("Initial Dictionary: ") print(Dict) # Deleting a Key value del Dict[6] print("\nDeleting a specific key: ") print(Dict) # Deleting a Key from # Nested Dictionary del Dict['A'][2] print("\nDeleting a key from Nested Dictionary: ") print(Dict) # Creating a Dictionary Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'} # Deleting a key # using pop() method pop_ele = Dict.pop(1) print('\nDictionary after deletion: ' + str(Dict)) print('Value associated to poped key is: ' + str(pop_ele)) # Creating Dictionary Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'} # Deleting an arbitrary key # using popitem() function pop_ele = Dict.popitem() print("\nDictionary after deletion: " + str(Dict)) print("The arbitrary pair returned is: " + str(pop_ele)) # Creating a Dictionary Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'} # Deleting entire Dictionary Dict.clear() print("\nDeleting Entire Dictionary: ") print(Dict)
class Solution(object): def twoSumLessThanK(self, A, K): """ :type A: List[int] :type K: int :rtype: int """ # Guard if not A or not K or len(A) <= 1: return -1 # Sort inputs inputs_sorted = sorted(A) # Two pointers through sorted input min_pointer = 0 max_pointer = len(A)-1 closest = -1 # Keep updating pointers to keep getting as close to K as possible while min_pointer < max_pointer: cur_sum = inputs_sorted[min_pointer] + inputs_sorted[max_pointer] if cur_sum < K: closest = max(closest, cur_sum) min_pointer+=1 elif cur_sum >= K: max_pointer-=1 return closest z = Solution() A = [10,20,30] K = 16 print(z.twoSumLessThanK(A, K))
def threeSum(nums): s = set() nums.sort() for i in range(len(nums)): m = {} for j in range(i+1, len(nums)): x = -nums[i] - nums[j] if x not in m: m[nums[j]] = j else: s.add((x,nums[i],nums[j])) return list(s)
array = [54, 26, 93, 17, 77, 31, 44, 55, 20] def bubble_sort(nums: list): for i in range(len(nums)): for j in range(len(nums) - 1, i, -1): if nums[j - 1] > nums[j]: nums[j - 1], nums[j] = nums[j], nums[j - 1] print(array) bubble_sort(array) print(array)
# 题意:判断树的子结构:输入两棵二叉树A和B,判断B是不是A的子结构。(约定空树不是任意一个树的子结构)。B是A的子结构, 即 A中有出现和B相同的结构和节点值。 # 题解:递归。 # 本题属于匹配类二叉树题目,一般做法就是递归。可以分为两个步骤,首先是找到匹配的跟节点,其次是对于根节点接着匹配下去看是否能匹配成功 # 在本题,找到根节点需要递归调用自身,找到根节点后用自定义的递归函数递归地匹配。整个过程用or and 等bool算子来拼凑成最后结果。 # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isSubStructure(self, A, B) -> bool: # inputs: A: TreeNode, B: TreeNode # outpus: bool if not B or not A: return False def recur(A, B): if not A and not B: return True elif not A: return False elif not B: return True else: # 值不相等 if A.val != B.val: return False # 值相等 else: return recur(A.left, B.left) and recur(A.right, B.right) return recur(A, B) or self.isSubStructure(A.left,B) or self.isSubStructure(A.right, B) # 简介写法 class Solution_2: def isSubStructure(self, A, B): if not A or not B: return False def recur(A, B): # 如果无B if not B: return True # 如果有B if not A: return False # 如果有B有A return (recur(A.left, B.left) and recur(A.right, B.right)) if A.val == B.val else False return recur(A,B) or self.isSubStructure(A.left,B) or self.isSubStructure(A.right, B)
""" This package contains the following entities: 1) Protocol 2) Attack Suite 3) Attack 4) Input Format In this module, we have the backend entities to represent and structure our code And these entities have the following relations in between: (Connection endpoints represent cardinality of entity) - Protocol 1----------* Attack Suite - Attack suite 1----------* Attack - Attack 1----------* Input format """
BLKNUM_OFFSET = 1000000000 TXINDEX_OFFSET = 10000 def decode_utxo_id(utxo_id): blknum = utxo_id // BLKNUM_OFFSET txindex = (utxo_id % BLKNUM_OFFSET) // TXINDEX_OFFSET oindex = utxo_id % TXINDEX_OFFSET return blknum, txindex, oindex def encode_utxo_id(blknum, txindex, oindex): return (blknum * BLKNUM_OFFSET) + (txindex * TXINDEX_OFFSET) + (oindex * 1) def decode_tx_id(utxo_id): (blknum, txindex, _) = decode_utxo_id(utxo_id) return encode_utxo_id(blknum, txindex, 0)
#!/usr/bin/python isValueAccepted = True largeur = int(input("Largeur >> ")) longueur = int(input("Longueur >> ")) while isValueAccepted: unite = str(input("En quelle unité souhaitez vous obtenir le périmètre(m ou cm) >> ")) if unite == "m" or unite == "cm": isValueAccepted = False print("Nous calculons le perimètre grâce à la formula (L + l) * 2") if unite == "m": perimetre = ((largeur + longueur) * 2) else: perimetre = ((largeur + longueur) * 2) * 100 print("Perimetre >>", perimetre, unite)
#!/usr/bin/env python3 # Copyright © 2012-13 Qtrac Ltd. All rights reserved. # This program or module is free software: you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. It is provided for # educational purposes and 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. ABOUT = "About" ALIGN_CENTER = "Align Center" ALIGNCENTER = "AlignCenter" ALIGN_LEFT = "Align Left" ALIGNLEFT = "AlignLeft" ALIGNMENT_TOOLBAR = "Alignment Toolbar" ALIGN_RIGHT = "Align Right" ALIGNRIGHT = "AlignRight" APPNAME = "Text Editor" BLINK = "blink" BOLD = "Bold" COPY = "Copy" CUT = "Cut" DEFAULT_TOOLBAR_HEIGHT = 34 EDIT_TOOLBAR = "Edit Toolbar" ELLIPSIS = "..." FAMILY = "family" FILE_TOOLBAR = "File Toolbar" FILE_TYPES = (("Text Files", ".txt"), ("All Files", "*")) # Tcl syntax FIND = "Find" FIND_TAG = "__FIND__" FONT = "Font" FONT_SIZE = "size" FORMAT_TOOLBAR = "Format Toolbar" GENERAL = "General" GEOMETRY = "geometry" HELP = "Help" ITALIC = "Italic" LAST_FILE = "lastfile" MAX_RECENT_FILES = 9 NEW = "New" OPEN = "Open" OPEN_RECENT = "Open Recent" PAD = "0.75m" PASTE = "Paste" PREFERENCES = "Preferences" QUIT = "Quit" RECENT_FILES = "Recent Files" REDO = "Redo" REPLACE_TAG = "__REPLACE__" RESTORE_FONT = 0 RESTORE_LAST_FILE = "restorelastfile" RESTORE = "restore" RESTORE_SESSION = 1 RESTORE_WINDOW = 2 SAVE_AS = "Save As" SAVEAS = "SaveAs" SAVE = "Save" SHAKE = 7 STATUS_SHOW_TIME = 10000 # milliseconds TOOLBARMENU = "ToolbarMenu" UNDO = "Undo" VERSION = "1.0.0" VISIBLE = "visible" EXTEND = "Extend" UNEXTEND = "Unextend"
""" Note: Moved to umpyre (pip install umpyre) Get stats about packages. Your own, or other's. Things like... # >>> import collections # >>> modules_info_df(collections) # lines empty_lines ... num_of_functions num_of_classes # collections.__init__ 1273 189 ... 1 9 # collections.abc 3 1 ... 0 25 # <BLANKLINE> # [2 rows x 7 columns] # >>> modules_info_df_stats(collections.abc) # lines 1276.000000 # empty_lines 190.000000 # comment_lines 73.000000 # docs_lines 133.000000 # function_lines 138.000000 # num_of_functions 1.000000 # num_of_classes 34.000000 # empty_lines_ratio 0.148903 # comment_lines_ratio 0.057210 # function_lines_ratio 0.108150 # mean_lines_per_function 138.000000 # dtype: float64 # >>> stats_of(['urllib', 'json', 'collections']) # urllib json collections # empty_lines_ratio 0.157034 0.136818 0.148903 # comment_lines_ratio 0.074142 0.038432 0.057210 # function_lines_ratio 0.213907 0.449654 0.108150 # mean_lines_per_function 13.463768 41.785714 138.000000 # lines 4343.000000 1301.000000 1276.000000 # empty_lines 682.000000 178.000000 190.000000 # comment_lines 322.000000 50.000000 73.000000 # docs_lines 425.000000 218.000000 133.000000 # function_lines 929.000000 585.000000 138.000000 # num_of_functions 69.000000 14.000000 1.000000 # num_of_classes 55.000000 3.000000 34.000000 """
# OAuth app keys DROPBOX_KEY = None DROPBOX_SECRET = None DROPBOX_AUTH_CSRF_TOKEN = 'dropbox-auth-csrf-token' # Max file size permitted by frontend in megabytes MAX_UPLOAD_SIZE = 150
ALLOWED_HOSTS = ['localhost', '127.0.0.1', '[::1]', 'jobs.harenconstruction.com', 'www.harenconstruction.com', 'harenconstruction.com' '104.236.59.248'] # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = '/home/applicant/' #os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False # Database # https://docs.djangoproject.com/en/1.9/ref/settings/#databases # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'applicant', 'USER': 'applicant', 'PASSWORD': 's34vZuhX&ChX@Lre0%kL', 'HOST': 'localhost', 'PORT': '', } } TEMPLATE_PATH = os.path.join('/home/applicant/applicant/applicant/', 'templates') TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_PATH], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.media', ], }, }, ] # Media (user uploaded files) MEDIA_ROOT = os.path.join('/home/applicant/', 'media') MEDIA_URL = '/media/' # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.9/howto/static-files/ STATIC_PATH = os.path.join('/home/applicant/', 'static') STATIC_ROOT = STATIC_PATH STATICFILES_DIRS = [ os.path.join('/home/applicant/applicant/applicant/', "static"), ] STATIC_URL = '/static/' # Fixtures for developer data. FIXTURE_DIRS = [ os.path.join('/home/applicant/applicant/applicant/', "fixtures"), ] # temporary path for wizard assisted file uploads TEMP_PATH = os.path.join('/home/applicant/', 'tmp') # logging LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'ERROR', 'class': 'logging.FileHandler', 'filename': '/home/applicant/applicant.log', }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'ERROR', 'propagate': True, }, }, }
# # PySNMP MIB module ZhoneDsl-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZhoneDsl-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:52:33 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsUnion, ValueSizeConstraint, ValueRangeConstraint, ConstraintsIntersection, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsIntersection", "SingleValueConstraint") ifIndex, = mibBuilder.importSymbols("IF-MIB", "ifIndex") SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") Counter64, Gauge32, IpAddress, NotificationType, Integer32, Counter32, MibScalar, MibTable, MibTableRow, MibTableColumn, Unsigned32, Bits, ObjectIdentity, iso, ModuleIdentity, TimeTicks, MibIdentifier = mibBuilder.importSymbols("SNMPv2-SMI", "Counter64", "Gauge32", "IpAddress", "NotificationType", "Integer32", "Counter32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Unsigned32", "Bits", "ObjectIdentity", "iso", "ModuleIdentity", "TimeTicks", "MibIdentifier") VariablePointer, TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "VariablePointer", "TextualConvention", "DisplayString") zhoneDsl, zhoneModules = mibBuilder.importSymbols("Zhone", "zhoneDsl", "zhoneModules") ZhoneRowStatus, ZhoneAdminString = mibBuilder.importSymbols("Zhone-TC", "ZhoneRowStatus", "ZhoneAdminString") zhoneDsl_MIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 5504, 6, 3)).setLabel("zhoneDsl-MIB") zhoneDsl_MIB.setRevisions(('2000-04-26 17:53',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: zhoneDsl_MIB.setRevisionsDescriptions(('strawman structure',)) if mibBuilder.loadTexts: zhoneDsl_MIB.setLastUpdated('200005111753Z') if mibBuilder.loadTexts: zhoneDsl_MIB.setOrganization('Zhone') if mibBuilder.loadTexts: zhoneDsl_MIB.setContactInfo(' Postal: xxx Zhone Technologies, Inc. xxx address. Fremont, Ca. Toll-Free: 877-ZHONE20 (+1 877-946-6320) Tel: +1 978-452-0571 Fax: +1 978-xxx-xxxx E-mail: [email protected] ') if mibBuilder.loadTexts: zhoneDsl_MIB.setDescription('The MIB module to describe the Zhone specific implementation of HDSL, HDSL2, SDSL and G.SHDSL') zhoneDslLineTable = MibTable((1, 3, 6, 1, 4, 1, 5504, 5, 4, 1), ) if mibBuilder.loadTexts: zhoneDslLineTable.setStatus('current') if mibBuilder.loadTexts: zhoneDslLineTable.setDescription('This table contains common attributes describing DSL physical line interfaces for DSLs without a MIB standard.') zhoneDslLineEntry = MibTableRow((1, 3, 6, 1, 4, 1, 5504, 5, 4, 1, 1), ).setIndexNames((0, "IF-MIB", "ifIndex")) if mibBuilder.loadTexts: zhoneDslLineEntry.setStatus('current') if mibBuilder.loadTexts: zhoneDslLineEntry.setDescription('An entry in the zhoneDslLine Table.') zhoneDslLineType = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 4, 1, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 96))).clone(namedValues=NamedValues(("hdsl", 1), ("hdsl2", 2), ("shdsl", 3), ("sdsl", 96))).clone('hdsl2')).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneDslLineType.setStatus('current') if mibBuilder.loadTexts: zhoneDslLineType.setDescription('The DSL type. Many modem vendors allow software selection between HDSL, HDSL2, SDSL and SHDSL. Using zhoneDslLineTypeSupported the user can see what dsl option is available on this interface.') zhoneDslLineCapabilities = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 4, 1, 1, 2), Bits().clone(namedValues=NamedValues(("hdsl", 1), ("hdsl2", 2), ("shdsl", 4), ("sdsl", 8)))).setMaxAccess("readonly") if mibBuilder.loadTexts: zhoneDslLineCapabilities.setStatus('current') if mibBuilder.loadTexts: zhoneDslLineCapabilities.setDescription('The DSL types supported on this interface. This is a bit-map of possible types. This variable can be used to determine zhoneDslLineType.') zhoneDslLineStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 4, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("down", 1), ("downloading", 2), ("activated", 3), ("training", 4), ("up", 5)))).setMaxAccess("readonly") if mibBuilder.loadTexts: zhoneDslLineStatus.setStatus('current') if mibBuilder.loadTexts: zhoneDslLineStatus.setDescription('The DSL modem status. Detailed modem state maybe available in the status table. ') zhoneDslUpLineRate = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 4, 1, 1, 4), Gauge32()).setUnits('bps').setMaxAccess("readonly") if mibBuilder.loadTexts: zhoneDslUpLineRate.setStatus('current') if mibBuilder.loadTexts: zhoneDslUpLineRate.setDescription('The DSL upstream (cpe->co) line rate on this interface.') zhoneDslDownLineRate = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 4, 1, 1, 5), Gauge32()).setUnits('bps').setMaxAccess("readonly") if mibBuilder.loadTexts: zhoneDslDownLineRate.setStatus('current') if mibBuilder.loadTexts: zhoneDslDownLineRate.setDescription('The DSL downstream (co->cpe) line rate on this interface.') zhoneDslLineConfigProfile = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 4, 1, 1, 6), ZhoneAdminString()).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneDslLineConfigProfile.setStatus('current') if mibBuilder.loadTexts: zhoneDslLineConfigProfile.setDescription("The value of this object identifies the row in the respective dsl configuration profile table. (Ex: if zhoneDslLineType is HDSL2, then the profile identifies an HDSL2 configuration profile.) It is assumed that all profile names are unique to the system. In the case which the configuration profile has not been set, the value will be set to `ZhoneDefault'. This is a profile (by type) which will be persisted and then able to be modified by a management station in order to modify the DEFAULT values. ") zhoneDslLineAlarmProfile = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 4, 1, 1, 7), ZhoneAdminString()).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneDslLineAlarmProfile.setStatus('current') if mibBuilder.loadTexts: zhoneDslLineAlarmProfile.setDescription("The value of this object identifies the row in the respective dsl alarm profile table. (Ex: if zhoneDslLineType is HDSL2 then the profile identifies an HDSL2 alarm profile.) It is assumed that all profile names are unique to the system. In the case where the configuration profile has not been set, the value will be set to `ZhoneDefault'. ") zhoneDslLineRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 4, 1, 1, 8), ZhoneRowStatus()).setMaxAccess("readwrite") if mibBuilder.loadTexts: zhoneDslLineRowStatus.setStatus('current') if mibBuilder.loadTexts: zhoneDslLineRowStatus.setDescription('Row status in order to add an entry in this table. The required fields to be added are: (ARE ALL THE DEFAULTS OKAY) ') zhoneHdsl2ConfigProfileTable = MibTable((1, 3, 6, 1, 4, 1, 5504, 5, 4, 3), ) if mibBuilder.loadTexts: zhoneHdsl2ConfigProfileTable.setStatus('current') if mibBuilder.loadTexts: zhoneHdsl2ConfigProfileTable.setDescription('This table contains information for HDSL2 configuration.') zhoneHdsl2ConfigProfileEntry = MibTableRow((1, 3, 6, 1, 4, 1, 5504, 5, 4, 3, 1), ).setIndexNames((1, "ZhoneDsl-MIB", "zhoneHdsl2ConfigProfileName")) if mibBuilder.loadTexts: zhoneHdsl2ConfigProfileEntry.setStatus('current') if mibBuilder.loadTexts: zhoneHdsl2ConfigProfileEntry.setDescription('An entry in the zhoneHdsl2ConfigProfile Table.') zhoneHdsl2ConfigProfileName = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 4, 3, 1, 1), ZhoneAdminString()) if mibBuilder.loadTexts: zhoneHdsl2ConfigProfileName.setStatus('current') if mibBuilder.loadTexts: zhoneHdsl2ConfigProfileName.setDescription("Configuration profile name. Used by the zhoneHdsl2LineConfigProfile entry to map zhoneDslLine Entry to the appropriate profile. When `dynamic' profiles are implemented, the profile name is user specified. Also, the system will always provide a default profile whose name is `DEFVAL'. When `static' profiles are implemented, there is an one-to-one relationship between each line and its profile. In which case, the profile name will need to algorithmically represent the Line's ifIndex. Therefore, the profile's name is a decimal zed string of the ifIndex that is fixed-length (i.e., 10) with leading zero(s). For example, the profile name for ifIndex which equals '15' will be '0000000015'.") zhoneHdsl2ConfigUnitMode = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 4, 3, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("co", 1), ("cpe", 2))).clone('co')).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneHdsl2ConfigUnitMode.setStatus('current') if mibBuilder.loadTexts: zhoneHdsl2ConfigUnitMode.setDescription('Unit is configured as the CO(central office)or CPE (customer premise)side.') zhoneHdsl2ConfigTransmitPowerbackoffMode = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 4, 3, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("backoff-disable", 1), ("backoff-enable", 2), ("no-change-backoff", 3))).clone('backoff-disable')).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneHdsl2ConfigTransmitPowerbackoffMode.setStatus('current') if mibBuilder.loadTexts: zhoneHdsl2ConfigTransmitPowerbackoffMode.setDescription('Determines if the transmit power backoff defined in HDSL2 standard is used.') zhoneHdsl2ConfigDecoderCoeffA = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 4, 3, 1, 4), Integer32().clone(970752)).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneHdsl2ConfigDecoderCoeffA.setStatus('current') if mibBuilder.loadTexts: zhoneHdsl2ConfigDecoderCoeffA.setDescription('21 bit value corresponding to the decoder coefficient A. The default is the ANSI HDSL2 default.') zhoneHdsl2ConfigDecoderCoeffB = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 4, 3, 1, 5), Integer32().clone(970752)).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneHdsl2ConfigDecoderCoeffB.setStatus('current') if mibBuilder.loadTexts: zhoneHdsl2ConfigDecoderCoeffB.setDescription('21 bit value corresponding to the decoder coefficient A. The default is the ANSI HDSL2 default.') zhoneHdsl2ConfigFrameSyncWord = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 4, 3, 1, 6), Integer32().clone(45)).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneHdsl2ConfigFrameSyncWord.setStatus('current') if mibBuilder.loadTexts: zhoneHdsl2ConfigFrameSyncWord.setDescription('10 bit frame sync word. The default is the HDSL2 standard.') zhoneHdsl2ConfigStuffBits = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 4, 3, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 15)).clone(15)).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneHdsl2ConfigStuffBits.setStatus('current') if mibBuilder.loadTexts: zhoneHdsl2ConfigStuffBits.setDescription('4 bit stuff pattern. The default is the HDSL2 standard.') zhoneHdsl2ConfigRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 4, 3, 1, 8), ZhoneRowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneHdsl2ConfigRowStatus.setStatus('current') if mibBuilder.loadTexts: zhoneHdsl2ConfigRowStatus.setDescription('Status in order to create/delete rows. For creation the following fields are required:') zhoneHdsl2StatusTable = MibTable((1, 3, 6, 1, 4, 1, 5504, 5, 4, 4), ) if mibBuilder.loadTexts: zhoneHdsl2StatusTable.setStatus('current') if mibBuilder.loadTexts: zhoneHdsl2StatusTable.setDescription('This table contains HDSL2 specific line status information. An entry into this table is automatically created whenever a zhoneDslLineEntry is created and the type is HDSL2.') zhoneHdsl2StatusEntry = MibTableRow((1, 3, 6, 1, 4, 1, 5504, 5, 4, 4, 1), ) ifIndex.registerAugmentions(("ZhoneDsl-MIB", "zhoneHdsl2StatusEntry")) zhoneHdsl2StatusEntry.setIndexNames(*ifIndex.getIndexNames()) if mibBuilder.loadTexts: zhoneHdsl2StatusEntry.setStatus('current') if mibBuilder.loadTexts: zhoneHdsl2StatusEntry.setDescription('An entry in the zhoneHdsl2Status Table.') zhoneHdsl2DriftAlarm = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 4, 4, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("rx-clk-alarm", 1), ("tx-clk-alarm", 2), ("tx-rx-clk-alarm", 3), ("no-drift-alarm", 4), ("not-applicable", 5)))).setMaxAccess("readonly") if mibBuilder.loadTexts: zhoneHdsl2DriftAlarm.setStatus('current') if mibBuilder.loadTexts: zhoneHdsl2DriftAlarm.setDescription(' Indicates that the framer automatically attempted to adjust for clock drift. This is not applicable for ATM.') zhoneHdsl2FramerIBStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 4, 4, 1, 2), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 1)).setFixedLength(1)).setMaxAccess("readonly") if mibBuilder.loadTexts: zhoneHdsl2FramerIBStatus.setStatus('current') if mibBuilder.loadTexts: zhoneHdsl2FramerIBStatus.setDescription('Returns the segd,sega,uib and losd bits. The format of the octet is: x x x x segd sega uib losd.') zhoneHdsl2LocalPSDMaskStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 4, 4, 1, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: zhoneHdsl2LocalPSDMaskStatus.setStatus('current') if mibBuilder.loadTexts: zhoneHdsl2LocalPSDMaskStatus.setDescription('Returns a number corresponding to the transmit power backoff requested by the local unit.') zhoneHdsl2LoopAttenuation = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 4, 4, 1, 4), Integer32()).setUnits('tenth DB').setMaxAccess("readonly") if mibBuilder.loadTexts: zhoneHdsl2LoopAttenuation.setStatus('current') if mibBuilder.loadTexts: zhoneHdsl2LoopAttenuation.setDescription('Estimation of the loop attenuation in tenths of a DB. by the local unit.') zhoneHdsl2LossWordStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 4, 4, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("no-lossw-defect", 1), ("lossw-defect", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: zhoneHdsl2LossWordStatus.setStatus('current') if mibBuilder.loadTexts: zhoneHdsl2LossWordStatus.setDescription('This indicates loss of sync.') zhoneHdsl2RmtPSDMaskStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 4, 4, 1, 6), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: zhoneHdsl2RmtPSDMaskStatus.setStatus('current') if mibBuilder.loadTexts: zhoneHdsl2RmtPSDMaskStatus.setDescription('Returns a number corresponding to the transmit power backoff requested by the remote unit.') zhoneHdsl2RmtCountryCode = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 4, 4, 1, 7), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: zhoneHdsl2RmtCountryCode.setStatus('current') if mibBuilder.loadTexts: zhoneHdsl2RmtCountryCode.setDescription('ANSI HDSL2 Country code of the remote unit.') zhoneHdsl2RmtVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 4, 4, 1, 8), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: zhoneHdsl2RmtVersion.setStatus('current') if mibBuilder.loadTexts: zhoneHdsl2RmtVersion.setDescription('HDSL2 version of the remote unit.') zhoneHdsl2RmtProviderCode = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 4, 4, 1, 9), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: zhoneHdsl2RmtProviderCode.setStatus('current') if mibBuilder.loadTexts: zhoneHdsl2RmtProviderCode.setDescription('Provider word of the remote unit.') zhoneHdsl2RmtVendorData = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 4, 4, 1, 10), OctetString().subtype(subtypeSpec=ValueSizeConstraint(8, 8)).setFixedLength(8)).setMaxAccess("readonly") if mibBuilder.loadTexts: zhoneHdsl2RmtVendorData.setStatus('current') if mibBuilder.loadTexts: zhoneHdsl2RmtVendorData.setDescription("The remote unit's vendor-provided data.") zhoneHdsl2RmtTxEncoderA = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 4, 4, 1, 11), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: zhoneHdsl2RmtTxEncoderA.setStatus('current') if mibBuilder.loadTexts: zhoneHdsl2RmtTxEncoderA.setDescription("The remote unit's 21 bit encoder coefficient A") zhoneHdsl2RmtTxEncoderB = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 4, 4, 1, 12), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: zhoneHdsl2RmtTxEncoderB.setStatus('current') if mibBuilder.loadTexts: zhoneHdsl2RmtTxEncoderB.setDescription("The remote unit's 21 bit encoder coefficient B") zhoneHdsl2TipRingStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 4, 4, 1, 13), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("normal", 1), ("reverse", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: zhoneHdsl2TipRingStatus.setStatus('current') if mibBuilder.loadTexts: zhoneHdsl2TipRingStatus.setDescription('Indicates whether the tip and ring points from the local unit match the tip and ring points of the remote.') zhoneHdsl2FrameSyncWord = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 4, 4, 1, 14), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: zhoneHdsl2FrameSyncWord.setStatus('current') if mibBuilder.loadTexts: zhoneHdsl2FrameSyncWord.setDescription('A 10 bit number indicating the frame sync word used. LSB justified') zhoneHdsl2StuffBits = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 4, 4, 1, 15), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: zhoneHdsl2StuffBits.setStatus('current') if mibBuilder.loadTexts: zhoneHdsl2StuffBits.setDescription('A 4 bit number for the stuff bits. LSB justified.') zhoneDslPerfDataTable = MibTable((1, 3, 6, 1, 4, 1, 5504, 5, 4, 5), ) if mibBuilder.loadTexts: zhoneDslPerfDataTable.setStatus('current') if mibBuilder.loadTexts: zhoneDslPerfDataTable.setDescription('This table provides one row for each modem interface.') zhoneDslPerfDataEntry = MibTableRow((1, 3, 6, 1, 4, 1, 5504, 5, 4, 5, 1), ) zhoneDslLineEntry.registerAugmentions(("ZhoneDsl-MIB", "zhoneDslPerfDataEntry")) zhoneDslPerfDataEntry.setIndexNames(*zhoneDslLineEntry.getIndexNames()) if mibBuilder.loadTexts: zhoneDslPerfDataEntry.setStatus('current') if mibBuilder.loadTexts: zhoneDslPerfDataEntry.setDescription('An entry in zhoneDslPerfDataTable.') zhoneDslPerfLofs = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 4, 5, 1, 1), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: zhoneDslPerfLofs.setStatus('current') if mibBuilder.loadTexts: zhoneDslPerfLofs.setDescription('Count of the number of Loss of Framing failures since agent reset.') zhoneDslPerfLoss = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 4, 5, 1, 2), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: zhoneDslPerfLoss.setStatus('current') if mibBuilder.loadTexts: zhoneDslPerfLoss.setDescription('Count of the number of Loss of Signal failures since agent reset.') zhoneDslPerfLols = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 4, 5, 1, 3), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: zhoneDslPerfLols.setStatus('current') if mibBuilder.loadTexts: zhoneDslPerfLols.setDescription('Count of the number of Loss of Link failures since agent reset.') zhoneDslPerfInits = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 4, 5, 1, 4), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: zhoneDslPerfInits.setStatus('current') if mibBuilder.loadTexts: zhoneDslPerfInits.setDescription('Count of the line initialization attempts since agent reset. Includes both successful and failed attempts.') zhoneDslPerfCur15MinTimeElapsed = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 4, 5, 1, 5), Gauge32()).setUnits('seconds').setMaxAccess("readonly") if mibBuilder.loadTexts: zhoneDslPerfCur15MinTimeElapsed.setStatus('current') if mibBuilder.loadTexts: zhoneDslPerfCur15MinTimeElapsed.setDescription('The number of seconds elapsed since the start of the current measurement period.') zhoneDslPerfCur15MinLofs = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 4, 5, 1, 6), Gauge32()).setUnits('seconds').setMaxAccess("readonly") if mibBuilder.loadTexts: zhoneDslPerfCur15MinLofs.setStatus('current') if mibBuilder.loadTexts: zhoneDslPerfCur15MinLofs.setDescription('Count of the number of Loss of Framing failures in the current 15 minute interval.') zhoneDslPerfCur15MinLoss = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 4, 5, 1, 7), Gauge32()).setUnits('seconds').setMaxAccess("readonly") if mibBuilder.loadTexts: zhoneDslPerfCur15MinLoss.setStatus('current') if mibBuilder.loadTexts: zhoneDslPerfCur15MinLoss.setDescription('Count of seconds in the current 15 minute interval when there was a Loss of Signal.') zhoneDslPerfCur15MinLols = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 4, 5, 1, 8), Gauge32()).setUnits('seconds').setMaxAccess("readonly") if mibBuilder.loadTexts: zhoneDslPerfCur15MinLols.setStatus('current') if mibBuilder.loadTexts: zhoneDslPerfCur15MinLols.setDescription('Count of seconds in the current 15 minute interval when there was of Loss of Link.') zhoneDslPerfCur15MinInits = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 4, 5, 1, 9), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: zhoneDslPerfCur15MinInits.setStatus('current') if mibBuilder.loadTexts: zhoneDslPerfCur15MinInits.setDescription('Count of the line initialization attempts in the current 15 minute interval. Includes both successful and failed attempts.') zhoneDslAlarmProfileTable = MibTable((1, 3, 6, 1, 4, 1, 5504, 5, 4, 6), ) if mibBuilder.loadTexts: zhoneDslAlarmProfileTable.setStatus('current') if mibBuilder.loadTexts: zhoneDslAlarmProfileTable.setDescription('This table contains information for Alarm conditions. One entry in this table reflects a profile defined by a manager which can be used to define alarm conditions for a modem.') zhoneDslAlarmProfileEntry = MibTableRow((1, 3, 6, 1, 4, 1, 5504, 5, 4, 6, 1), ).setIndexNames((1, "ZhoneDsl-MIB", "zhoneDslAlarmProfileName")) if mibBuilder.loadTexts: zhoneDslAlarmProfileEntry.setStatus('current') if mibBuilder.loadTexts: zhoneDslAlarmProfileEntry.setDescription('An entry in the zhoneDslAlarmProfile Table.') zhoneDslAlarmProfileName = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 4, 6, 1, 1), ZhoneAdminString()) if mibBuilder.loadTexts: zhoneDslAlarmProfileName.setStatus('current') if mibBuilder.loadTexts: zhoneDslAlarmProfileName.setDescription("Configuration profile name. Used by the zhoneDslLineConfigProfile entry to map zhoneDslLine Entry to the appropriate profile. When `dynamic' profiles are implemented, the profile name is user specified. Also, the system will always provide a default profile whose name is `DEFVAL'. When `static' profiles are implemented, there is an one-to-one relationship between each line and its profile. In which case, the profile name will need to algorithmically represent the Line's ifIndex. Therefore, the profile's name is a decimal zed string of the ifIndex that is fixed-length (i.e., 10) with leading zero(s). For example, the profile name for ifIndex which equals '15' will be '0000000015'.") zhoneDslThreshold15MinLoss = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 4, 6, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 900))).setUnits('seconds').setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneDslThreshold15MinLoss.setStatus('current') if mibBuilder.loadTexts: zhoneDslThreshold15MinLoss.setDescription('The number of Loss of signal seconds on a DSL interface within any given 15 minutes performance data collection period, which causes the SNMP agent to send a TRAP. 0 will disable the trap.') zhoneDslThreshold15MinLols = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 4, 6, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 900))).setUnits('seconds').setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneDslThreshold15MinLols.setStatus('current') if mibBuilder.loadTexts: zhoneDslThreshold15MinLols.setDescription('The number of Loss of link seconds on a DSL interface within any given 15 minutes performance data collection period, which causes the SNMP agent to send a TRAP. 0 will disable the trap.') zhoneDslThreshold15MinLofs = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 4, 6, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 900))).setUnits('seconds').setMaxAccess("readcreate") if mibBuilder.loadTexts: zhoneDslThreshold15MinLofs.setStatus('current') if mibBuilder.loadTexts: zhoneDslThreshold15MinLofs.setDescription('The number of Loss of framing seconds on a DSL interface within any given 15 minutes performance data collection period, which causes the SNMP agent to send a TRAP. 0 will disable the trap.') zhoneDslAlarmProfileRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 4, 6, 1, 5), ZhoneAdminString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: zhoneDslAlarmProfileRowStatus.setStatus('current') if mibBuilder.loadTexts: zhoneDslAlarmProfileRowStatus.setDescription("RowStatus field to control deletion/addition of entries in this table. Minimal fields to be 'set' for a creation is:") mibBuilder.exportSymbols("ZhoneDsl-MIB", zhoneDslLineType=zhoneDslLineType, zhoneDslPerfCur15MinLoss=zhoneDslPerfCur15MinLoss, zhoneHdsl2LocalPSDMaskStatus=zhoneHdsl2LocalPSDMaskStatus, zhoneDslThreshold15MinLofs=zhoneDslThreshold15MinLofs, zhoneHdsl2ConfigProfileName=zhoneHdsl2ConfigProfileName, zhoneDslLineRowStatus=zhoneDslLineRowStatus, zhoneDslLineConfigProfile=zhoneDslLineConfigProfile, zhoneDslPerfCur15MinLofs=zhoneDslPerfCur15MinLofs, zhoneHdsl2RmtProviderCode=zhoneHdsl2RmtProviderCode, zhoneHdsl2ConfigDecoderCoeffA=zhoneHdsl2ConfigDecoderCoeffA, zhoneDslPerfLoss=zhoneDslPerfLoss, zhoneDslPerfLols=zhoneDslPerfLols, zhoneDslAlarmProfileEntry=zhoneDslAlarmProfileEntry, zhoneHdsl2RmtTxEncoderA=zhoneHdsl2RmtTxEncoderA, PYSNMP_MODULE_ID=zhoneDsl_MIB, zhoneDslPerfCur15MinLols=zhoneDslPerfCur15MinLols, zhoneHdsl2StatusTable=zhoneHdsl2StatusTable, zhoneDslPerfLofs=zhoneDslPerfLofs, zhoneDslPerfCur15MinTimeElapsed=zhoneDslPerfCur15MinTimeElapsed, zhoneHdsl2ConfigProfileEntry=zhoneHdsl2ConfigProfileEntry, zhoneHdsl2ConfigFrameSyncWord=zhoneHdsl2ConfigFrameSyncWord, zhoneDslPerfDataEntry=zhoneDslPerfDataEntry, zhoneDslPerfCur15MinInits=zhoneDslPerfCur15MinInits, zhoneDslAlarmProfileTable=zhoneDslAlarmProfileTable, zhoneHdsl2ConfigRowStatus=zhoneHdsl2ConfigRowStatus, zhoneDslLineTable=zhoneDslLineTable, zhoneHdsl2ConfigUnitMode=zhoneHdsl2ConfigUnitMode, zhoneDslPerfInits=zhoneDslPerfInits, zhoneHdsl2FramerIBStatus=zhoneHdsl2FramerIBStatus, zhoneHdsl2DriftAlarm=zhoneHdsl2DriftAlarm, zhoneHdsl2RmtPSDMaskStatus=zhoneHdsl2RmtPSDMaskStatus, zhoneDslLineEntry=zhoneDslLineEntry, zhoneHdsl2ConfigTransmitPowerbackoffMode=zhoneHdsl2ConfigTransmitPowerbackoffMode, zhoneHdsl2RmtCountryCode=zhoneHdsl2RmtCountryCode, zhoneHdsl2RmtVersion=zhoneHdsl2RmtVersion, zhoneDslDownLineRate=zhoneDslDownLineRate, zhoneHdsl2ConfigProfileTable=zhoneHdsl2ConfigProfileTable, zhoneDslAlarmProfileRowStatus=zhoneDslAlarmProfileRowStatus, zhoneHdsl2StuffBits=zhoneHdsl2StuffBits, zhoneHdsl2ConfigStuffBits=zhoneHdsl2ConfigStuffBits, zhoneDsl_MIB=zhoneDsl_MIB, zhoneDslPerfDataTable=zhoneDslPerfDataTable, zhoneDslLineStatus=zhoneDslLineStatus, zhoneHdsl2RmtVendorData=zhoneHdsl2RmtVendorData, zhoneHdsl2RmtTxEncoderB=zhoneHdsl2RmtTxEncoderB, zhoneHdsl2LossWordStatus=zhoneHdsl2LossWordStatus, zhoneDslLineCapabilities=zhoneDslLineCapabilities, zhoneDslUpLineRate=zhoneDslUpLineRate, zhoneHdsl2LoopAttenuation=zhoneHdsl2LoopAttenuation, zhoneHdsl2StatusEntry=zhoneHdsl2StatusEntry, zhoneHdsl2FrameSyncWord=zhoneHdsl2FrameSyncWord, zhoneDslLineAlarmProfile=zhoneDslLineAlarmProfile, zhoneDslThreshold15MinLoss=zhoneDslThreshold15MinLoss, zhoneHdsl2TipRingStatus=zhoneHdsl2TipRingStatus, zhoneHdsl2ConfigDecoderCoeffB=zhoneHdsl2ConfigDecoderCoeffB, zhoneDslAlarmProfileName=zhoneDslAlarmProfileName, zhoneDslThreshold15MinLols=zhoneDslThreshold15MinLols)
def is_on(S, j): return (S & (1 << j)) >> j def set_all(n): return (1 << n) - 1 def low_bit(S): return (S & (-S)).bit_length() - 1 def clear_bit(S, j): return S & ~(1 << j)
""" practice test cases for testing plugin """ def test_iequals1(): """ practice test case 1 for testing plugin """ i = 1 assert i == 1 def test_iequals2(): """ practice test case 2 for testing plugin """ i = 2 assert i == 2
def histogram(s): """Use get to write histogram more concisely""" d = dict() for c in s: d[c] = d.get(c, 0) + 1 return d print(histogram('brontosaurus'))
class core50(): def __init__(self, paradigm, run): self.batch_num = 5 self.rootdir = '/home/rushikesh/code/core50_dataloaders/dataloaders/task_filelists/' self.train_data = [] self.train_labels = [] self.train_groups = [[],[],[],[],[]] for b in range(self.batch_num): with open( self.rootdir + paradigm + '/run' + str(run) + '/stream/train_task_' + str(b).zfill(2) + '_filelist.txt','r') as f: for i, line in enumerate(f): if line.strip(): path, label = line.split() self.train_groups[b].append((path, int(label))) self.train_data.append(path) self.train_labels.append(int(label)) self.train = {'data': self.train_data,'fine_labels': self.train_labels} self.val_groups = self.train_groups.copy() self.test_data = [] self.test_labels = [] self.test_groups = [[],[],[],[],[]] groupsid = {'0':0,'1':0, '2':1,'3':1, '4':2,'5':2, '6':3,'7':3, '8':4,'9':4} with open( self.rootdir + paradigm + '/run' + str(run) + '/stream/test_filelist.txt','r') as f: for i, line in enumerate(f): if line.strip(): path, label = line.split() gp = groupsid[label] #print("label, gp") #print(label, gp) self.test_groups[gp].append((path, int(label))) self.test_data.append(path) self.test_labels.append(int(label)) self.test = {'data': self.test_data,'fine_labels': self.test_labels} def getNextClasses(self, test_id): return self.train_groups[test_id], self.val_groups[test_id], self.test_groups[test_id] #self.test_grps #
def romanToInt(s): """Calculates value of Roman numeral string Args: s (string): String of Roman numeral characters being analyzed Returns: int: integer value of Roman numeral string """ sum = 0 i = 0 while i < len(s): if s[i] == 'M': sum += 1000 elif s[i] == 'D': sum += 500 elif s[i] == 'L': sum += 50 elif s[i] == 'V': sum += 5 elif s[i] == 'C': if i < len(s) - 1: if s[i + 1] == 'M': sum += 900 i += 1 elif s[i + 1] == 'D': sum += 400 i += 1 else: sum += 100 else: sum += 100 elif s[i] == 'X': if i < len(s) - 1: if s[i + 1] == 'C': sum += 90 i += 1 elif s[i + 1] == 'L': sum += 40 i += 1 else: sum += 10 else: sum += 10 elif s[i] == 'I': if i < len(s) - 1: if s[i + 1] == 'X': sum += 9 i += 1 elif s[i + 1] == 'V': sum += 4 i += 1 else: sum += 1 else: sum += 1 else: return "Something went wrong" i += 1 return sum def main(): print( format("%-10s %-10s %10s" % ("Test", "String", "Integer")) + "\n" + "-" * 32 + "\n" + format("%-10s %-10s %10d" % ("Test 1:", "III", romanToInt("III"))) + "\n" + format("%-10s %-10s %10d" % ("Test 2:", "IV", romanToInt("IV"))) + "\n" + format("%-10s %-10s %10d" % ("Test 3:", "IX", romanToInt("IX"))) + "\n" + format("%-10s %-10s %10d" % ("Test 4:", "LVIII", romanToInt("LVIII"))) + "\n" + format("%-10s %-10s %10d" % ("Test 5:", "MCMXCIV", romanToInt("MCMXCIV"))) ) main()
User_name = input("What is your name? ") User_age = input("How old are you? ") User_liveplace = input("Where are you live? ") print ( "This is", User_name) print ( "It is" , User_age) print ( "(S)he live in", User_liveplace)
def includes(doc, path, title=3, **args): j = doc.docsite._j spath = j.sal.fs.processPathForDoubleDots(j.sal.fs.joinPaths(j.sal.fs.getDirName(doc.path), path)) if not j.sal.fs.exists(spath, followlinks=True): doc.raiseError("Cannot find path for macro includes:%s" % spath) docNames = [j.sal.fs.getBaseName(item)[:-3] for item in j.sal.fs.listFilesInDir(spath, filter="*.md")] docNames = [j.sal.fs.joinPaths(path, name) for name in docNames] docNames.sort() titleprefix = "#" * title out = "" for docName in docNames: doc2 = doc.docsite.doc_get(docName, die=False) if doc2 is None: msg = "cannot execute macro includes, could not find doc:\n%s" % docName doc.raiseError(msg) return "```\n%s\n```\n" % msg out += "%s %s\n\n" % (titleprefix, docName) out += "%s\n\n" % doc2.markdown_source.rstrip("\n") return out
#!/usr/bin/env python lista=[2,3,4,1] lista2=lista[:] #Copia lista.sort() if lista == lista2: print("Lista ordenada") else: print("Lista no ordenada")
__author__ = "Andre Merzky" __copyright__ = "Copyright 2012-2013, The SAGA Project" __license__ = "MIT" # ------------------------------------------------------------------------------ # FIXME: OS enums, ARCH enums # resource type enum COMPUTE = 1 # resource accepting jobs STORAGE = 2 # storage resource (duh) NETWORK = 4 # connects compute and storage resources # resource state enum UNKNOWN = None # wut? NEW = 1 # requsted, not accepting jobs, yet; # initial state PENDING = 2 # accepting jobs, will become active eventually ACTIVE = 4 # accepting jobs, jobs can run CANCELED = 8 # released by user; final state EXPIRED = 16 # released by system; final state DONE = EXPIRED # alias FAILED = 32 # released unexpectedly by system or internally; # final state FINAL = CANCELED | DONE | FAILED # resource attributes ID = 'Id' # url identifying a resource instance RTYPE = 'Rtype' # type enum, identifying the resource type STATE = 'State' # state enum, identifying the rsource state STATE_DETAIL = 'StateDetail' # string, representing the native backend state MANAGER = 'Manager' # url, pointing to the resource's manager DESCRIPTION = 'Description' # dict, containing resource attributes # generic resource description attributes TEMPLATE = 'Template' # string, template to which the resource # was created IMAGE = 'Image' # FIXME: # resource lifetime attributes DYNAMIC = 'Dynamic' # bool, enables/disables on-demand # resource # resizing START = 'Start' # time, expected time at which resource # becomes ACTIVE END = 'End' # time, expected time at which resource # will EXPIRE DURATION = 'Duration' # time, expected time span between ACTIVE # and EXPIRED # resource type specific (non-generic) attributes MACHINE_OS = 'MachineOS' # enum, identifying the resource's operating # system MACHINE_ARCH = 'MachineArch' # enum, identifying the machine architecture SIZE = 'Size' # int, identifying No. of slots / size in # MB / No. of IPs MEMORY = 'Memory' # int, identifying memory size in MegaByte ACCESS = 'Access' # string, identifying the hostname/ip, mount # point or provisioning URL to access the # resource # ------------------------------------------------------------------------------
############################################################################## # # Copyright (c) 2002 Zope Foundation and Contributors. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE # ############################################################################## """The webdav package provides WebDAV capability for common Zope objects. Current WebDAV support in Zope provides for the correct handling of HTTP GET, HEAD, POST, PUT, DELETE, OPTIONS, TRACE, PROPFIND, PROPPATCH, MKCOL, COPY and MOVE methods, as appropriate for the object that is the target of the operation. Objects which do not support a given operation should respond appropriately with a "405 Method Not Allowed" response. Note that the ability of a Zope installation to support WebDAV HTTP methods depends on the willingness of the web server to defer handling of those methods to the Zope process. In most cases, servers will allow the process to handle any request, so the Zope portion of your url namespace may well be able to handle WebDAV operations even though your web server software is not WebDAV-aware itself. Zope installations which use bundled server implementations such as ZopeHTTPServer or ZServer should fully support WebDAV functions. References: [WebDAV] Y. Y. Goland, E. J. Whitehead, Jr., A. Faizi, S. R. Carter, D. Jensen, "HTTP Extensions for Distributed Authoring - WebDAV." RFC 2518. Microsoft, U.C. Irvine, Netscape, Novell. February, 1999.""" enable_ms_public_header = False
""" lab 8 """ #3.1 #def calcwords(input_str): # return len(input_str.split()) #3.2 #demo_str = 'hello world!' #print(calcwords(demo_str)) #3.3 def calnum(input_list): min_item = input_list[0] for eachnum in input_list: if type(eachnum) is not str: if min_item >= eachnum: min_item = eachnum return min_item #3.4 num_list = [1,2,3,4,5,6] print(calnum(num_list)) #3.5 mix_list = [1,2,3,4,'a',5,6] print(calnum(mix_list))
def is_zigzag(numbers: list): if len(numbers) != 3: raise ValueError('must be 3 elements {}'.format(numbers)) return 1 if (numbers[0] < numbers[1] > numbers[2]) or (numbers[0] > numbers[1] < numbers[2]) else 0 if __name__ == "__main__": #numbers = [1, 2, 1] numbers = [1, 2, 1, 3, 4] numbers = [1, 3, 4, 5, 6, 14, 14] result = list() for i in range(len(numbers)): if i + 2 < len(numbers): result.append( is_zigzag(numbers[i: i + 3]) ) print(result)
def ext_here(props): props['ext_ui']['filedir2']=props['ext_ui']['filedir'] props['music'].clickSon() #print(filedir2) decomp(props) def ext_to(props): filedir=props['ext_ui']['filedir'] root=props['root'] filedialog=props['filedialog'] props['music'].clickSon() root.filename =filedialog.askdirectory(title="select folder") filedir2=root.filename if filedir2=='': return 0 #print(filedir2) props['ext_ui']['filedir2']=filedir2 decomp(props) def decomp(props): p1open=props['env']['main']['p1open'] music=props['music'] not_err=0 finish=props['finish'] try: myzip=props['zipfile'].PyZipFile(props['ext_ui']['filedir']) myzip.extractall(path=props['ext_ui']['filedir2']) except none: not_err=1 if not_err==0: finish(1,props) music.sucSon() else: finish(0,props) music.errorSon() p1open+=1 if p1open>=3: #lab2.destroy() pass
def funcaoDocumentada(a,b): """ Dá a soma de dois números. :param int a: Um valor numérico :param int b: Um valor numérico :return: A soma de a e b """ return a+b def paramOpcional(a=0,b=0,c=0): return a+b+c def paramSilencioso(): # valorNoEscopo é global. print(f'Fora do escopo, {valorNoEscopo}') # Mas se eu desse valorNoEscopo = 5, # aí haveria uma variavel local com esse mesmo nome por aqui, # porque conta como uma nova definição. A não ser que eu faça isso: global valorNoEscopo valorNoEscopo = 8 # help(print) print(print.__doc__) # help(funcaoDocumentada) print(funcaoDocumentada.__doc__) print(f'Soma: {paramOpcional(c=1,a=2)}') valorNoEscopo = 6 print(f'No escopo, {valorNoEscopo}') paramSilencioso()
class CartItem(object): def __init__(self, url, title=None, abstract=None, mime_type=None, dataset=None): self.url = url self._title = title self._abstract = abstract self.mime_type = mime_type or 'application/x-netcdf' self.dataset = dataset @property def title(self): return self._title or self.filename @property def abstract(self): return self._abstract or "No Summary" @property def filename(self): return self.url.split('/')[-1] def is_service(self): return self.is_opendap() or self.is_thredds_catalog() def is_opendap(self): return self.mime_type == 'application/x-ogc-dods' def is_thredds_catalog(self): return self.mime_type == 'application/x-thredds-catalog' def to_json(self): return dict(url=self.url, title=self._title, abstract=self._abstract, mime_type=self.mime_type, dataset=self.dataset) class Cart(object): def __init__(self, request): self.request = request self.session = request.session # TODO: loading stored items needs to be improved self.items = None self.load() def __iter__(self): """ Allow the cart to be iterated giving access to the cart's items. """ for key in self.items: yield self.items[key] def __contains__(self, url): """ Returns: True if cart item with given url is in cart, otherwise False. """ return url in self.items def add_item(self, url, title=None, abstract=None, mime_type=None): """ Add cart item. """ if url and self.request.has_permission('edit'): item = CartItem(url, title=title, abstract=abstract, mime_type=mime_type) self.items[url] = item self.save() else: item = None return item def remove_item(self, url): """ Remove cart item with given url. """ if url and url in self.items: item = self.items[url] del self.items[url] self.save() else: item = None return item def count(self): """ Returns: number of cart items. """ return len(self.items) def has_items(self): """ Returns: True if cart items available, otherwise False. """ return self.count() > 0 def clear(self): """ Removes all items of cart and updates session. """ self.items = {} self.session['cart'] = [] self.session.changed() def save(self): """ Store cart items in session. """ self.session['cart'] = self.to_json() self.session.changed() def load(self): """ Load cart items from session. """ items_as_json = self.session.get('cart') self.items = {} if items_as_json: for item in items_as_json: self.items[item['url']] = CartItem(**item) def to_json(self): """ Returns: json representation of all cart items. """ return [self.items[key].to_json() for key in self.items]
class Node: """ A Circular linked node. """ def __init__(self, data=None): self.data = data self.next = None class CircularList: def __init__ (self): self.tail = None self.head = None self.size = 0 def append(self, data): node = Node(data) if self.head: self.head.next = node self.head = node else: self.head = node self.tail = node self.head.next = self.tail self.size += 1 def delete(self, data): current = self.tail prev = self.tail while prev == current or prev != self.head: if current.data == data: if current == self.tail: self.tail = current.next self.head.next = self.tail else: prev.next = current.next self.size -= 1 return prev = current current = current.next def iter(self): current = self.tail while current: val = current.data current = current.next yield val words = CircularList() words.append('eggs') words.append('ham') words.append('spam') counter = 0 for word in words.iter(): print(word) counter += 1 if counter > 10: break words.append('foo') words.append('bar') words.append('bim') words.append('baz') words.append('quux') words.append('duux') print("Done iterating. Now we try to delete something that isn't there.") words.delete('socks') print('back to iterating') counter = 0 for item in words.iter(): print(item) counter += 1 if counter > 2: break print('Let us delete something that is there.') words.delete('foo') print('back to iterating') counter = 0 for item in words.iter(): print(item) counter += 1 if counter > 2: break
""" Session: 10 Topic: A positive integer greater than 1 which has no other factors except 1 and the number itself is called a prime number. """ num = int(input("How many terms? ")) # prime numbers are greater than 1 if num > 1: # check for factors for i in range(2, num): if (num % i) == 0: print(num, "is not a prime number") print(i, "times", num // i, "is", num) break else: print(num, "is a prime number") # if input number is less than # or equal to 1, it is not prime else: print(num, "is not a prime number")
class UserDoesNotExist(Exception): pass class PasswordDoesNotMatch(Exception): pass class EmailAlreadyRegistered(Exception): pass
try: basestring except NameError: basestring = str # Python 2 -> 3 alias """ Exposes decorator class.""" __all__ = ["DocInheritDecorator"] class DocInheritDecorator(object): """ A decorator that merges provided parent docstring with the docstring of the decorated function/method/property. Methods ------- doc_merger(prnt_attr_doc, child_doc) Merges the parent and child docstrings into a single docstring. Notes ----- When utilized as the inner-most decorator, this decorator can be used on functions decorated functions, methods, properties, static methods, class methods, and their abstract counterparts.""" def __init__(self, prnt_doc): """ Parameters ---------- prnt_doc : Union[str, Any] The docstring, or object of which the docstring is utilized as the parent docstring during the docstring merge.""" self.prnt_doc = ( prnt_doc if isinstance(prnt_doc, basestring) else prnt_doc.__doc__ ) def __call__(self, func): """ Parameters ---------- func : FunctionType The function/method/property to be decorated Returns ------- FunctionType The decorated function/method/property whose docstring is given by DocInheritDecorator.doc_merger(prnt_attr_doc, child_doc)""" func.__doc__ = self.doc_merger(self.prnt_doc, func.__doc__) return func @staticmethod def doc_merger(prnt_attr_doc, child_doc): """ Merges the parent and child docstrings into a single docstring. Parameters ---------- prnt_attr_doc: Union[None, str] child_doc: Union[None, str] Raises ------ NotImplementedError""" raise NotImplementedError
""" Albert is playing with text. Instead of writing sentences as they should be, he decided to randomly swap pairs of letters in them. But not even in the whole text, only from some place in the middle of the text onward. At least he marked the places in the text, where each substitution starts, and what two letters are swapped. But the text is still hard to read. Could you please decode it back to its original form? Beginning of each substitution is marked by the sequence "[A<->B]" in the input text. It means that the letters A and B are swapped from now on. The sequence itself should be removed from the text. Caveat - swaps are transitive but not commutative. Given two swaps [A<->B] and [B<->C], the string "ABC" should be decoded as "BCA". Given the same swaps in opposite order, [B<->C], [A<->B], the string "ABC" should be decoded as "CAB". Example For text = "Once upon a[e<->r] timr threr [a<->l]wls l alnd whrer King Labret euard.", the output should be swappingLetters(text) = "Once upon a time there was a land where King Albert ruled.". The first three words remain the same because the first swap mark comes only after the third word. From then on, every letter 'E' is replaced by 'R' and vice versa. After two more words, there is another swap - this time, 'A' is replaced by 'L' and vice versa. But keep in mind that 'E' and 'R' are still being swapped, too. """ def swappingLetters(t): # by rgtichy p = len(t) - 1 o = "" while p >= 0: if t[p] == ']' and t[p - 3] == '-': B = t[p - 1] B += B.upper() A = t[p - 5] A += A.upper() o = o.translate(o.maketrans(A + B, B + A)) p -= 7 else: o += t[p] p -= 1 return o[::-1]
""" NAME: DIBANSA, RAHMANI P. COURSE-YEAR LEVEL-SECTION: BSCPE 2-2 SUBJECT: SOFTWARE DEVELOPMENT PROGRAM DESCRIPTION: A PYTHON PROGRAM THAT SORTS A LIST THROUGH MERGE SORT FUNCTION """ # THIS FUNCTION TAKES A THE USER'S INPUTTED LIST, A START VARIABLE THAT # MARKS WHERE THE FUNCTION WOULD START ITS PROCESS, AND THE END VARIABLE # THAT IS EQUAL TO THE TOTAL NUMBER OF ELEMENTS INSIDE THE USER'S INPUTTED # LIST. # MERGE SORT WILL START SORTING FROM THE INDEX START UP TO THE INDEX # END - 1. def merge_sort(user_input, start, end): m_list = user_input # IF THE END SUBTRACTED BY START IS NOT GREATER THAN ONE, # THEN THE FUNCTION WILL RETURN THE RESULT if end - start > 1: mid = ( start + end ) // 2 merge_sort( m_list, start, mid ) merge_sort( m_list, mid, end ) MergeList( m_list, start, mid, end ) return m_list # THE MergeList FUNCTION WILL TAKING FOUR VARIABLE INPUTS, THESE ARE: # *list_input : THE PRE-PROCESSED USER INPUT # *start : THE INDEX WHERE THE FUNCTION WILL START FURTHER PROCESSING # THE INPUTTED LIST. # *mid : THE INDEX THAT DENOTES THE MIDDLE INDEX OF THE CURRENT PROCESS # *end : THE INDEX THAT DENOTES THE END INDEX OF THE CURRENT PROCESS def MergeList( list_input, start, mid, end): # THE VARIABLES USED IN PROCESSING THE INPUTTED LIST m_list = list_input left = m_list[ start:mid ] right = m_list[ mid:end ] i = 0 # LEFT ITERATION ii = 0 # RIGHT ITERATION s = start # WHILE START VARIABLE PLUS THE LEFT ITERATION IS LESS THAN THE MID # VARIABKE, AND MID VARIABLE PLUS THE RIGHT ITERATION IS LESS THAN # THE END VARIABLE, THE LOOP WILL CONTINUE. while start + i < mid and mid + ii < end: # IF THE nth(i) ELEMENT OF LEFT VARIABLE IS LESS THAN THE # nth(ii) ELEMENT OF THE RIGHT VARIABLE, THEN THE LEFT ELEMENT # WILL BE PLUGGED INTO m_list. # OTHERWISE, THE RIGHT ELEMENT WILL BE PLUGGED INTO m_list. if left[i] <= right[ii]: m_list[s] = left[i] i = i + 1 else: m_list[s] = right[ii] ii = ii + 1 s = s + 1 # THIS WILL TAKE CARE OF THE ELEMENTS THAT ARE STILL NOT PLACED AT THE # RIGHT INDEX/ORDER. if start + i < mid: while s < end: m_list[s] = left[i] i = i + 1 s = s + 1 else: while s < end: m_list[s] = right[ii] ii = ii + 1 s = s + 1 # HERE THE PROGRAM WILL ASK FOR THE USER'S INPUT AND PROCESS THE # LIST GATHERED THROUGH THE merge_sort FUNCTION. ONCE DONE, THE # PROGRAM WILL PRINT THE RESULTS. user_input = input( " Enter the list you would like to merge sort: " ).split() user_input = [ int(n) for n in user_input ] m_list = merge_sort(user_input, 0, len(user_input)) print ( " Sorted list: " , end = "" ) print ( m_list )
class TestData(): BROWSER_PATH="C:/Python/Python37-32/chromedriver.exe" BASE_URL = "https://www.amazon.com" SEARCH_TERM = "adidas backpack men" HOME_PAGE_TITLE = "Amazon.com" NO_RESULTS_TEXT = "No results found."
class Vec3(): def __init__(self, x=0, y=0, z=0): self.x = x self.y = y self.z = z def length(self): return (self.x * self.x + self.y * self.y + self.z * self.z)**0.5 def __add__(self, other): return Vec3(self.x + other.x, self.y + other.y, self.z + other.z) def __sub__(self, other): return Vec3(self.x - other.x, self.y - other.y, self.z - other.z) def __mul__(self, other): return Vec3(self.x * other.x, self.y * other.y, self.z * other.z) def __truediv__(self, other): return Vec3(self.x / other.x, self.y / other.y, self.z / other.z) def __neg__(self): return Vec3(-self.x, -self.y, -self.z) def __gt__(self, other): return self.length() > other.length() def __lt__(self, other): return self.length() < other.length() def normalized(self): if self.length() == 0: return Vec3(0, 0, 0) return self / toVec3(self.length()) def toVec2(x): return Vec3(x, x, 0) def toVec3(x): return Vec3(x, x, x)
def dp(height, max_steps, memo): if height == 0: return 1 if memo[height] > 0: return memo[height] ways = 0 for i in range(max(height - max_steps, 0), height): ways += dp(i, max_steps, memo) memo[height] = ways return ways def staircaseTraversal(height, maxSteps): memo = [-1] * (height + 1) dp(height, maxSteps, memo) return memo[height]
#Question 1342: #Given a non-negative integer num, return the number of steps to reduce it to zero. # If the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it. #Example: #Input: num = 14 #Output: 6 #Explanation: #Step 1) 14 is even; divide by 2 and obtain 7. #Step 2) 7 is odd; subtract 1 and obtain 6. #Step 3) 6 is even; divide by 2 and obtain 3. #Step 4) 3 is odd; subtract 1 and obtain 2. #Step 5) 2 is even; divide by 2 and obtain 1. #Step 6) 1 is odd; subtract 1 and obtain 0. #Solution: def numberOfSteps(num): no_of_steps=0 #Counter for tracking the number of steps required to perform the operation while num>0: #Perform computation till we reduce num to zero if num & 1 == 0: #Check if num is an odd number #Performing And Operation of the number and one in 1 binary form # 101 (say number is 3) # 001 (1 in binary form) # + # ------ # 001(This is 1 in binary form) # ------- # On similar computation with other numbers we can conclude that on Performing And Operation of any number with 1 # If the result is 1->It is an odd number # Otherwise it is an even number num-=1 #Reduce it by one else: #If num is an even number num//=2 #Divide it by 2 no_of_steps += 1 return(no_of_steps) num = int(input("Enter a number: ")) print("Number of steps required to reduce: {}".format(numberOfSteps(num)))
# Escreva um programa que converta uma temperatura digitada em °C e converta para °F.# c = float(input('Informe a temperatura em °C: ')) f = ((9 * c) / 5) + 32 print(f'A temperatura de {c}°C corresponde a {f}°F')
class Variable(object): BOOLEAN = 1 def __init__(self, name, type, value): self.name = name self.type = type self.value = value def __repr__(self): return "Variable(%s, %s, %s)" % (self.name, self.type, self.value)
# Copyright 2016 The Bazel Authors. 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. load(":common.bzl", "make_dart_context", "package_spec_action") load(":dart_vm_snapshot.bzl", "dart_vm_snapshot_action") def _dart_vm_binary_action( ctx, script_file, srcs, deps, data = [], snapshot = True, script_args = [], generated_srcs = [], vm_flags = [], pub_pkg_name = ""): dart_ctx = make_dart_context( ctx, srcs = srcs, generated_srcs = generated_srcs, data = data, deps = deps, package = pub_pkg_name, ) if snapshot: out_snapshot = ctx.actions.declare_file(ctx.label.name + ".snapshot") dart_vm_snapshot_action( ctx = ctx, dart_ctx = dart_ctx, output = out_snapshot, vm_flags = vm_flags, script_file = script_file, script_args = script_args, ) script_file = out_snapshot # Emit package spec. package_spec = ctx.actions.declare_file(ctx.label.name + ".packages") package_spec_action( ctx = ctx, dart_ctx = dart_ctx, output = package_spec, ) # Emit entrypoint script. ctx.template_action( output = ctx.outputs.executable, template = ctx.file._entrypoint_template, executable = True, substitutions = { "%workspace%": ctx.workspace_name, "%dart_vm%": ctx.executable._dart_vm.short_path, "%package_spec%": package_spec.short_path, "%vm_flags%": " ".join(vm_flags), "%script_file%": script_file.short_path, "%script_args%": " ".join(script_args), }, ) # Compute runfiles. runfiles_files = dart_ctx.transitive_data.files + [ ctx.executable._dart_vm, ctx.outputs.executable, package_spec, ] if snapshot: runfiles_files += [out_snapshot] else: runfiles_files += dart_ctx.transitive_srcs.files return ctx.runfiles( files = list(runfiles_files), collect_data = True, ) _default_binary_attrs = { "_dart_vm": attr.label( allow_files = True, single_file = True, executable = True, cfg = "host", default = Label("@dart_sdk//:dart_vm"), ), "_entrypoint_template": attr.label( single_file = True, default = Label("//dart/build_rules/templates:dart_vm_binary"), ), } internal_dart_vm = struct( binary_action = _dart_vm_binary_action, common_attrs = _default_binary_attrs, )
print("CONVERSOR DE DECIMALES A OTRA BASE") number = input("Ingresa un numero de base decimal: ") base = input("Ingresa la base: ") numbers = [] def residuo(number, base, iteration = 0): cociente = number // base res = number % base print(" " * iteration, res, cociente) numbers.append(res) if (cociente < base): numbers.append(cociente) return else: return residuo(cociente, base, iteration + 1) base = int(base) residuo(int(number), base) print("El resultante base", base, "es: ", end='') for i in range(len(numbers) - 1, -1, -1): print(numbers[i], end='') print()
""" * * Author: Juarez Paulino(coderemite) * Email: [email protected] * """ for _ in '0'*int(input()): a,b,k=map(int,input().split()) print(k//2*(a-b)+k%2*a)
def draw(n): for i in range(1, n+1): for k in range(0,n-i): print(" ", end=" ") for j in range(0,i): print("*", end=" ") print("\n") draw(4)
i = 0 while i < 10: print(i) i = i + 1 i = 1 while i <= 2 ** 32: print(i) i *= 2 done = False while not done: quit = input("Do you want to quit? ") if quit == "y": done = True attack = input("Does your elf attack the dragon? ") if attack == "y": print("Bad choice, you died.") done = True value = 0 increment = 0.5 while value < 0.999: value += increment increment *= 0.5 print(value)
class Solution: def reformatDate(self, date: str) -> str: clean = date.split() month = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", ] day, month, year = str(clean[0])[:-2], month.index(clean[1]) + 1, clean[2] if len(day) == 1: day = f"0{day}" if len(str(month)) == 1: month = f"0{month}" return f"{year}-{month}-{day}"
# Crie um programa que converta graus Celsius em Fahrenheit # C/5=F-32/9 # F = C * 1.8 + 32 print('Conversor de Temperatura\n C em F') c = int(input('Digite a temperatura em Graus Celcios: ')) f = c * 1.8 + 32 print('{}ºC = {:.1f}ºF'.format(c, f,))
class Solution(object): def plusOne(self, digits): """ :type digits: List[int] :rtype: List[int] """ result = [] flag = 0 temp = digits[-1] if temp < 9: result = digits result[-1] = result[-1] + 1 else: result = [0] flag = 1 for i in digits[0:-1][::-1]: if i < 9 and flag == 1: flag = 0 result = [i+1] + result elif i < 9 and flag == 0: result = [i] + result elif i == 9 and flag == 1: flag = 1 result = [0] + result else: flag = 0 result = [i] + result if flag == 1: result = [1] + result return result sol = Solution() print(sol.plusOne([0]))
class Solution: def XXX(self, height: List[int]) -> int: area=0 i=0 j=len(height)-1 while i!=j: # 双指针,最小高度的指针移动 max_height=min(height[i],height[j]) area=max(max_height*(j-i),area) if height[i]<height[j]: i=i+1 else: j=j-1 return(area)
# -*- coding: utf-8 -*- """Top-level package for {{ cookiecutter.project }}.""" __author__ = """{{ cookiecutter.author }}""" __version__ = '{{ cookiecutter.version }}'
#Page 202, Figure 13.2 class Field(object): def __init__(self): self.drunks = {} def addDrunk(self, drunk, loc): if drunk in self.drunks: raise ValueError('Duplicate drunk') else: self.drunks[drunk] = loc def moveDrunk(self, drunk): if drunk not in self.drunks: raise ValueError('Drunk not in field') xDist, yDist = drunk.takeStep() currentLocation = self.drunks[drunk] # Loaction クラスの move メソッドを用いて, 新しい位置情報を得る self.drunks[drunk] = currentLocation.move(xDist, yDist) def getLoc(self, drunk): if drunk not in self.drunks: raise ValueError('Drunk not in field') return self.drunks[drunk]
# Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # This is a mixture of the javadoc_library rule in # https://github.com/google/bazel-common and the one in # https://github.com/stackb/rules_proto. # The main two factors for why we need this are # 1. We only have a source jar for java_proto_library. # The rules in bazel-common do not support this. # 2. We need to get the source jar via the JavaInfo provider. # The rules in rules_proto do not support this. # We probably want to clean this up and upstream it at some point. def _javadoc_library(ctx): transitive_deps = [] for dep in ctx.attr.deps: if JavaInfo in dep: transitive_deps.append(dep[JavaInfo].transitive_deps) elif hasattr(dep, "java"): transitive_deps.append(dep.java.transitive_deps) classpath = depset([], transitive = transitive_deps).to_list() java_home = str(ctx.attr._jdk[java_common.JavaRuntimeInfo].java_home) javadoc_command = [ java_home + "/bin/javadoc", # this is an ugly hack to provide all directories ending with `java` as a "source root" '-sourcepath $(find . -type d -name "*java" -printf "%P:").', " ".join(ctx.attr.root_packages), "-use", "-subpackages", ":".join(ctx.attr.root_packages), "-encoding UTF8", "-classpath", ":".join([jar.path for jar in classpath]), "-notimestamp", "-d tmp", "-Xdoclint:-missing", "-quiet", ] if ctx.attr.doctitle: javadoc_command.append('-doctitle "%s"' % ctx.attr.doctitle) if ctx.attr.exclude_packages: javadoc_command.append("-exclude %s" % ":".join(ctx.attr.exclude_packages)) for link in ctx.attr.external_javadoc_links: javadoc_command.append("-linkoffline {0} {0}".format(link)) if ctx.attr.bottom_text: javadoc_command.append("-bottom '%s'" % ctx.attr.bottom_text) jar_command = "%s/bin/jar cf %s -C tmp ." % (java_home, ctx.outputs.jar.path) unjar_params = [] srcs = [] for src in ctx.attr.srcs: # this is for when the provided src is a java_library target if JavaInfo in src: for jar in src[JavaInfo].source_jars: unjar_params.append(jar.path) srcs.append(jar) elif DefaultInfo in src: srcs.extend(src[DefaultInfo].files.to_list()) unjar_command = "%s/bin/jar xf %s" % (java_home, " ".join(unjar_params)) ctx.actions.run_shell( inputs = srcs + classpath + ctx.files._jdk, command = "%s && %s && %s" % (unjar_command, " ".join(javadoc_command), jar_command), outputs = [ctx.outputs.jar], ) javadoc_library = rule( attrs = { "srcs": attr.label_list( allow_empty = False, allow_files = True, ), "deps": attr.label_list(), "doctitle": attr.string(default = ""), "root_packages": attr.string_list(), "exclude_packages": attr.string_list(), "android_api_level": attr.int(default = -1), "bottom_text": attr.string(default = ""), "external_javadoc_links": attr.string_list(), "_jdk": attr.label( default = Label("@bazel_tools//tools/jdk:current_java_runtime"), providers = [java_common.JavaRuntimeInfo], ), }, outputs = {"jar": "%{name}.jar"}, implementation = _javadoc_library, )
# Notation for direction will be as follows: # 0 # 3 1 # 2 # Turning to the rights = (d+1)%4 # Turning to the left = (d-1)%4 def move(d, cX, cY): if (d == 0): cX = cX-1 if (d == 1): cY = cY+1 if (d == 2): cX = cX+1 if (d == 3): cY = cY-1 return cX, cY def work(mp, d, x, y): #print("Current Pos = ", mp[x][y]) if (mp[x][y] == '#'): d = (d+1)%4 mp[x][y] = '.' else: d = (d-1)%4 global becameInfected becameInfected += 1 mp[x][y] = '#' return mp, d def expandMap(mp, cX, cY): # If they are at the top of the map if (cX == 0): # Generate a new top line of clean nodes. topLine = [] for i in range(len(mp[0])): topLine.append('.') mp.insert(0, topLine) cX = 1 # If they are at the bottom of the map if (cX == len(mp)): # Generate a new bottom line of clean nodes. bottomLine = [] for i in range(len(mp[0])): bottomLine.append('.') mp.insert(0, bottomLine) # cX stays the same. # If they are at the left of the map if (cY == 0): # Add a clean node to the start every line. for i in range(len(mp)): mp[i].insert(0, '.') cY = 1 # If they are at the right of the map if (cY == len(mp[0])): # Add a clean node to the end every line for i in range(len(mp)): mp[i].append('.') # cY stays in the same place. return mp, cX, cY def mapPrint(mp, cX, cY): outStr = "" for i in range(len(mp)): for j in range(len(mp[0])): if (i == cX and j == cY): outStr += "@" else: outStr += mp[i][j] outStr += "\n" print(outStr) mp = [\ [".",".",".","#","#",".","#",".","#",".","#","#","#","#",".",".",".","#","#","#",".",".",".",".","."],\ [".",".","#",".",".","#","#",".","#",".",".",".","#",".","#","#",".","#","#",".","#",".",".","#","."],\ [".","#",".","#",".","#",".","#","#","#",".",".",".",".","#",".",".",".","#","#","#",".",".",".","."],\ [".","#",".",".",".",".","#",".",".","#","#","#","#",".",".",".",".",".","#","#",".","#",".",".","#"],\ ["#","#",".","#",".","#",".","#",".","#",".",".","#",".",".","#",".",".",".",".",".","#","#","#","."],\ ["#",".",".",".","#","#",".",".",".",".","#","#",".","#","#",".","#",".","#","#",".","#","#",".","."],\ [".",".",".",".",".","#","#","#",".",".","#","#","#",".","#","#","#",".",".",".","#","#","#","#","#"],\ ["#","#","#","#","#","#",".","#","#","#","#",".",".","#",".","#",".",".",".",".",".",".","#","#","."],\ ["#",".",".","#","#","#",".","#","#","#","#",".",".","#","#","#","#",".",".",".",".",".",".",".","."],\ ["#",".",".","#","#","#","#","#","#",".","#","#",".",".",".",".","#","#","#","#",".",".",".","#","#"],\ [".",".",".","#",".","#","#",".","#",".",".",".","#",".","#",".","#",".","#",".",".","#","#",".","#"],\ ["#","#","#","#",".","#","#","#",".",".","#","#","#","#","#",".",".",".",".",".","#","#","#","#","."],\ ["#",".","#",".","#",".",".",".",".","#",".","#","#","#","#",".",".",".","#","#","#","#",".",".","."],\ ["#","#",".",".",".","#",".",".","#","#",".","#","#",".",".",".",".","#",".",".",".","#",".",".","."],\ [".",".",".",".",".",".","#","#",".",".","#","#",".",".","#",".",".","#",".",".","#","#","#","#","."],\ [".","#","#",".",".","#","#",".","#","#",".",".","#","#","#","#",".",".","#","#",".",".",".",".","#"],\ [".","#",".",".","#",".",".","#","#",".","#",".",".","#","#",".",".","#",".",".",".","#",".",".","."],\ ["#",".","#",".","#","#",".",".",".",".",".","#","#",".",".","#","#",".","#","#","#","#","#",".","."],\ ["#","#",".","#",".",".",".",".",".",".",".","#",".",".",".",".","#",".",".","#","#","#",".","#","."],\ ["#","#",".",".",".","#",".",".",".","#",".",".",".",".","#","#","#",".",".","#",".","#",".","#","."],\ ["#",".",".",".",".","#","#",".",".",".","#",".","#",".","#",".","#","#",".",".","#",".",".","#","#"],\ ["#",".",".","#",".",".",".",".","#","#","#","#","#",".",".",".",".",".","#",".","#","#",".","#","."],\ [".","#",".",".",".","#",".",".","#",".",".","#","#","#",".",".",".",".","#","#","#",".",".","#","."],\ [".",".","#","#",".","#","#","#",".","#",".","#",".",".",".",".",".","#","#","#",".",".",".",".","."],\ ["#",".","#",".","#",".","#",".","#",".","#","#",".","#","#",".",".",".","#","#",".","#","#",".","#"]] #mp = [[".", ".", "#"], ["#", ".", "."], [".", ".", "."]] direction = 0 becameInfected = 0 cX = len(mp)//2 cY = len(mp[0])//2 for i in range(10001): mapPrint(mp, cX, cY) if (i % 100 == 0): print("Tick", i) mp, direction = work(mp, direction, cX, cY) cX, cY = move(direction, cX, cY) mp, cX, cY = expandMap(mp, cX, cY) print("Total nodes that became infected =", becameInfected-1) # 5069 is too low...
class Constants: # Common Constants mail: str = "[email protected]" version: str = "1.0.0" # Production Constants productionDescription: str = "Handles the ProDCube Backend Server. Currently in Production. " \ "Please change to development mode while development." productionTitle: str = "ProDCube Backend Server - Production" # Development Constants developmentDescription: str = "Handles the ProDCube Backend Server. Currently in Development. " \ "Please change to production mode while hosting." developmentTitle: str = "ProDCube Backend Server - Development" # Testing Constants testingTitle: str = "ProDCube Backend Server - Testing" testingDescription: str = "Handles the ProDCube Backend Server. Currently in Testing. " \ "Please change to development or production mode when needed."
def mergeSort(arr:[int]): mid:int = 0 L:[int] = None R:[int] = None i:int = 0 j:int = 0 k:int = 0 if len(arr) > 1: # Finding the mid of the array mid = len(arr)//2 # Dividing the array elements L=[] while (i<mid): L = L + [arr[i]] i = i + 1 # into 2 halves R = [] while (i<len(arr)): R = R + [arr[i]] i = i + 1 # Sorting the first half mergeSort(L) # Sorting the second half mergeSort(R) i = 0 j = 0 k = 0 # Copy data to temp arrays L[] and R[] while(i < len(L) and j < len(R)): if L[i] < R[j]: arr[k] = L[i] i = i+ 1 else: arr[k] = R[j] j = j+ 1 k = k+ 1 # Checking if any element was left while i < len(L): arr[k] = L[i] i = i+ 1 k = k+ 1 while j < len(R): arr[k] = R[j] j =j + 1 k =k + 1 # Code to print the list def printList(arr:[int]): x:int = 0 for x in arr: print(x) # Driver Code arr:[int] = None arr = [12, 11, 13, 5, 6, 7] print("Given array is") printList(arr) mergeSort(arr) print("Sorted array is: ") printList(arr) # This code is contributed by Mayank Khanna
#Desafio: Crie um programa quue vai ler vários números e colocar em uma lista. Depois disso mostre: #A) Quantos números foram digitados. #B) A lista de valores, ordenada de forma decrescente. #C) Se o valor 5 foi digitado e está ou não na lista. num = list() while True: num.append(int(input('Digite um número: '))) continua = input('Quer continuar: [S/N]').upper().strip()[0] if continua == 'N': break num.sort(reverse=True) print('-=' * 40) print(f'Você digitou {len(num)} números') print(f'Os valores em ordem decrescente são {num}') if num.count(5): print('O valor 5 faz parte da lista') else: print('O valor 5 não foi encontrado')
""" This class implements common methods for all solving methods """ class BaseMethod: """ """ def __init__(self): """ """ self.time = None def get_time(self): """ """ return self.time def show(self): """ """ pass def get_best(self): """ """ pass
# -*- coding: UTF-8 -*- RULES = { u'muriend': u'muerte', u'querid': u'querer', u'mirando': u'mirar', u'miradit': u'mirar', u'pudier': u'poder', u'horas': u'hora', u'gasta': u'gasto', u'gasta': u'gasto', u'mostró': u'mostrar', u'destine': u'destinar', u'presentó': u'presentar', u'dudo': u'dudar', u'lanzó': u'lanzar', u'matan': u'matar', u'escribe': u'escribir', u'veremos': u'ver', u'interna': u'interno', u'anunciado': u'anuncio', u'veriamos': u'ver', u'esperaba': u'esperar', u'tomen': u'tomar', u'adoptados': u'adoptado', u'cómo': u'como', u'cumplan': u'cumplir', u'cumplieron': u'cumplir', u'acordamos': u'acordar', u'esperan': u'esperar', u'realizadas': u'realizado', u'decida': u'decidir', u'investigaba': u'investigar', u'ayuden': u'ayudar', u'darán': u'dar', u'meses': u'mes', u'salgas': u'salir', u'queman': u'quemar', u'esperando': u'esperar', u'esperamos': u'esperar', u'peores': u'peor', u'parques': u'parque', u'defendió': u'defender', u'soles': u'sol', u'calles': u'calle', u'voces': u'voz', u'postulaban': u'postulante', u'debió': u'deber', u'long': u'long', u'menores': u'menor', u'aguas': u'agua', u'susan': u'susan', u'creciendo': u'crecer', u'presentamos': u'presentar', u'espacios': u'espacio', }
"""Constants for integration_blueprint.""" # Base component constants NAME = "Duolinguist" DOMAIN = "duolingo" VERSION = "0.1.0" ISSUE_URL = "https://github.com/sphanley/duolinguist/issues" # Platforms BINARY_SENSOR = "binary_sensor" PLATFORMS = [BINARY_SENSOR] # Configuration and options CONF_USERNAME = "username" CONF_PASSWORD = "password" STARTUP_MESSAGE = f""" ------------------------------------------------------------------- {NAME} Version: {VERSION} This is a custom integration! If you have any issues with this you need to open an issue here: {ISSUE_URL} ------------------------------------------------------------------- """
class Solution: ''' 给定一个经过编码的字符串,返回它解码后的字符串。 编码规则为: k[encoded_string],表示其中方括号内部的 encoded_string 正好重复 k 次。注意 k 保证为正整数。 你可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。 此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 k ,例如不会出现像 3a 或 2[4] 的输入。 示例: s = "3[a]2[bc]", 返回 "aaabcbc". s = "3[a2[c]]", 返回 "accaccacc". s = "2[abc]3[cd]ef", 返回 "abcabccdcdcdef". ''' def decodeString_(self, s: str) -> str: char, num, chars, nums = '', 0, [], [] for c in s: if c.isdigit(): num = num * 10 + int(c) elif c == '[': nums.append(num) # 压栈[前解码的字符串 chars.append(char) num = 0 char = '' elif c == ']': char = chars.pop() + char * nums.pop() else: char += c return char def decodeString(self, s: str) -> str: n = len(s) if n == 0: return n nums, chars = [], [] num, char, ans = 0, '', '' for c in s: # 最外层的[] if len(nums) == 0: ans += char char = '' if c.isdigit(): num = num * 10 + int(c) elif c.isalpha(): char = char + c elif c == '[': nums.append(num) # 压栈 3[a2[c]] 中的a chars.append(char) num = 0 char = '' elif c == ']': # a + 2 * c char = chars.pop() + nums.pop() * char return ans + char if __name__ == "__main__": s = Solution() print(s.decodeString_("3[a2[c]d]zxc4[ef]gh"))
n=int(input()) arr=[] c=0 for _ in range(n): arr.append(list(map(int,input().split()))) for i in range(len(arr)): co=0 for j in range(len(arr[i])): if(arr[i][j]==1): co+=1 if(co>=2): c+=1 print(c)
# 21302 - [Job Adv] (Lv.60) Aran sm.setSpeakerID(1201002) sm.sendNext("Oh, isn't that... Hey, did you remember how to make the Red Jade? You may be a dummy who has amnesia, but this is why I can't leave you. Now hurry, give me the gem!") if sm.sendAskYesNo("Okay, now that I have the power of Red Jade, I'll restore more of your abilities. Your level has gotten much higher since the last time we met, so I'm sure I can work my magic a bit more this time!"): if not sm.canHold(1142131): sm.sendSayOkay("Please make some space in your equipment inventory.") sm.dispose() sm.completeQuest(parentID) sm.giveItem(1142131) sm.jobAdvance(2111) sm.consumeItem(4032312) sm.sendNext("Please get back all of your abilities soon. I want to explore with you like we did in the good old days.")
""" Class for server to store client types and data etc. """ class Client: """ Client class """ def __init__(self, controlled, conn): """ Constructor Args: controlled (boolean): Whether or not this client is being controlled conn (socket.socket): the connection for this client """ self.controlled = controlled self.conn = conn def is_controlled(self): """ Whether or not the client is controlled Returns: boolean: True if controlled, False if controller """ return self.controlled def get_connection(self): """ Gets the connection Returns: socket.socket: the connection where everything happens """ return self.conn def send(self, msg): """ Sends a message Args: msg (string): message to send """ self.conn.send(msg.encode())
test = { 'name': 'switch', 'points': 1, 'suites': [ { 'cases': [ { 'code': r""" scm> (switch 1 ((1 (print 'a)) .... (2 (print 'b)) .... (3 (print 'c)))) a scm> (switch (+ 1 1) ((1 (print 'a)) .... (2 (print 'b)) .... (3 (print 'c)))) b scm> (define x 'b) x scm> (switch x ((a (print 1)) .... (b (print 2)) .... (c (print 3)))) 2 """, 'hidden': False, 'locked': False } ], 'scored': False, 'setup': r""" scm> (load-all ".") """, 'teardown': '', 'type': 'scheme' } ] }
class Prunner(object): def __init__(self): pass def fit(self, ensemble, X, y): return self def get(self, p=0.1): return self.ensemble[:int(p * len(self.ensemble))]
# -*- coding: utf-8 -*- ''' Author: Hannibal Data: Desc: local data config NOTE: Don't modify this file, it's build by xml-to-python!!! ''' simpleskillpassive_map = {}; simpleskillpassive_map[2001] = {"id":2001,"skilldata":[{"lv":1,"effect":"actor['atk']*=1.2","group":1,},{"lv":2,"effect":"actor['atk']*=1.3","group":1,},{"lv":3,"effect":"actor['atk']*=1.4","group":1,},],}; simpleskillpassive_map[2002] = {"id":2002,"skilldata":[{"lv":1,"effect":"actor['spd']+=20","group":1,},{"lv":2,"effect":"actor['spd']+=30","group":1,},],}; simpleskillpassive_map[2003] = {"id":2003,"skilldata":[{"lv":1,"effect":"actor['hpmax']*=1.2","group":1,},],}; class Simpleskillpassive: def __init__(self, key): config = simpleskillpassive_map.get(key); for k, v in config.items(): setattr(self, k, v); return def create_Simpleskillpassive(key): config = simpleskillpassive_map.get(key); if not config: return return Simpleskillpassive(key)
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Mytree: def maketree(self, arr: list): root = TreeNode(arr[0]) mystack = [] mystack.append(root) nl = [] i = 0 while len(mystack) > 0: node = mystack.pop(0) i += 1 if i < len(arr): if arr[i] != "null": node.left = TreeNode(arr[i]) mystack.append(node.left) else: break i += 1 if i < len(arr): if arr[i] != "null": node.right = TreeNode(arr[i]) mystack.append(node.right) else: break # print(root.left.val) return root arr = [20, 8, 22, 4, 12, "null", "null", "null", "null", 10, 14] s = Mytree() root = s.maketree(arr) print(root.val)
""" 缺省函数,就是参数可以有默认值,跟kotlin一样 返回值也可以简写,省略 -> int: """ def print_info(name, age=20): print("姓名:%s, 年龄:%s" % (name, age)) print_info("张三", 28) print_info("李四") """ 元组[]不定长参数,参数的数量不确定, 调用类似于位置参数 参数名之前加上*表示这个星号表明参数的类型为元祖,但是传入实参的时候不需要中括号[] """ def my_func01(*args): print(type(args)) print(args[0]) my_func01(1, 3, 5) my_func01(1, 3, 5, 7) """ 字典类型{}的不定长参数, 调用类似于关键字参数name=的形式 参数名前面加上**两个星号,表明这个参数为一个字典,传入的时候不需要写{},但是只能传入一个字典 """ def my_func02(**kwargs): print(type(kwargs)) print(kwargs["name"]) print(kwargs["age"]) my_func02(name="小明", age=12) """ 一个函数的包含多return个 """ def my_func03(score: int) -> str: if score >= 70: return "优秀" elif score >= 30: return "中性" else: return "差" print(my_func03(50)) """ 处理多个返回值的方式 1- return ["小明", 28] 2- return {"name":"小明","age":28] 2- return 返回值1, 返回值2 """ def my_func04(name, age): return name, age print(my_func04("张三",28)[0]) print(my_func04("张三",28)[1]) """ python中的拆包(列表,字典,多个返回值): 一次性初始化多个变量的值 如果返回值是列表,字典,或者多个返回值,可以直接用来赋值多个变量的方式就叫做拆包,简化代码量 """ num01, num02, num03, num04 = 1, 3.14, True, "Hello World" num05, num06, num07, num08 = [1, 3.14, True, "Hello World"] name, age = my_func04("李四", 28) print(name, "-->", age) """ 拆包中python快速交换两个变量的值, 免去了temp中间值 """ a, b = 4, 5 a, b = b, a # b的引用给a, a的引用给b,快速交换值
# MTK GPS Command Sentence Generator for Python # Copyright (c) 2015 Calvin McCoy ([email protected]) # 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. __valid_baudrates = [4800, 9600, 14400, 19200, 38400, 57600, 115200] # ##### Fixed Command Strings ######## # Set Sentence Output to default sentences and frequencies default_sentences = '$PMTK314,-1*04\r\n' # Restart Receiver using all available data hot_start = '$PMTK101*32\r\n' # Restart Receiver without Ephemeris data warm_start = '$PMTK102*31\r\n' # Restart Receiver with no initial data cold_start = '$PMTK103*30\r\n' # Restart Receiver with no initial data and reset receiver to factory defaults full_cold_start = '$PMTK104*37\r\n' # Set Receiver into Standby Mode standby = '$PMTK161,0*28\r\n' def crc_calc(input_string): """ Calculates cumulative XOR CRC of inputted string :param input_string: Str to CRC :return: 2 char CRC str """ crc = 0 for next_char in input_string: ascii_val = ord(next_char) crc ^= ascii_val hex_crc = hex(crc) if crc <= 0xF: crc_byte = '0' + hex_crc[2] else: crc_byte = hex_crc[2:4] return crc_byte def update_nmea_rate(nmearate): """ Returns a valid MTK command sentence that sets the update interval of the reciever :param nmearate: float value of update rate in Hertz; must be between 1 and 10 :return: MTK command str """ if 1 > nmearate > 10: return None milli_value = int(1000 / nmearate) cmd_body = 'PMTK220,' + str(milli_value) crc = crc_calc(cmd_body) full_string = '$' + cmd_body + '*' + crc + '\r\n' return full_string def update_baudrate(baudrate): """ Returns a valid MTK command sentence that sets the baud rate of serial output of the receiver :param baudrate: Int corresponding to valid baud rate :return: MTK command string """ if baudrate not in __valid_baudrates: return None cmd_body = 'PMTK251,' + str(baudrate) crc = crc_calc(cmd_body) full_string = '$' + cmd_body + '*' + crc + '\r\n' return full_string def update_sentences(en_gll=True, en_rmc=True, en_vtg=True, en_gga=True, en_gsa=True, en_gsv=True, en_mchn=False, gll_int=1, rmc_int=1, vtg_int=1, gga_int=1, gsa_int=1, gsv_int=3, mchn_int=0): """ Returns a valid MTK command sentence that can set the update rate for each of the available NMEA sentence types. :param en_gll: Boolean to enable GLL sentences :param en_rmc: Boolean to enable RMC sentences :param en_vtg: Boolean to enable VTG sentences :param en_gga: Boolean to enable GGA sentences :param en_gsa: Boolean to enable GSA sentences :param en_gsv: Boolean to enable GSV sentences :param en_mchn: Boolean to enable MCHN sentences :param gll_int: Int for number of update intervals between updates for GLL :param rmc_int: Int for number of update intervals between updates for RMC :param vtg_int: Int for number of update intervals between updates for VTG :param gga_int: Int for number of update intervals between updates for GGA :param gsa_int: Int for number of update intervals between updates for GSA :param gsv_int: Int for number of update intervals between updates for GSV :param mchn_int: Int for number of update intervals between updates for MCHN :return: MTK command str """ if en_gll: gll_str = str(gll_int) else: gll_str = '0' if en_rmc: rmc_str = str(rmc_int) else: rmc_str = '0' if en_vtg: vtg_str = str(vtg_int) else: vtg_str = '0' if en_gga: gga_str = str(gga_int) else: gga_str = '0' if en_gsa: gsa_str = str(gsa_int) else: gsa_str = '0' if en_gsv: gsv_str = str(gsv_int) else: gsv_str = '0' if en_mchn: mchn_str = str(mchn_int) else: mchn_str = '0' cmd_body = 'PMTK314,' + gll_str + ',' + rmc_str + ',' + vtg_str + ',' + gga_str + ',' + gsa_str + ',' + \ gsv_str + ',0,0,0,0,0,0,0,0,0,0,0,0,' + mchn_str crc = crc_calc(cmd_body) full_string = '$' + cmd_body + '*' + crc + '\r\n' return full_string class MtkCommandRx(object): """Parser for MTK command sentences. Can be used to find status and acknowledgment PMTK sentences in a GPS output stream. After init, supply the object with all received characters via update() to find a valid MTK sentence""" # Max Number of Characters a valid sentence can be SENTENCE_LIMIT = 76 def __init__(self): """Setup MTK Commnad Object Status Flags, Internal Data Registers, etc""" self.mtk_string = '' self.sentence_active = True self.mtk_sentence = False self.star_found = False self.char_count = 0 def new_sentence(self): """Adjust Object Flags in Preparation for a New Sentence""" self.mtk_string = '' self.sentence_active = True self.mtk_sentence = False self.star_found = False self.char_count = 0 def update(self, new_char): """Process a new input char and update MTK object. Returns MTK command string if found""" # Validate new_char is a printable char ascii_char = ord(new_char) if 33 <= ascii_char <= 126: self.char_count += 1 # Check if a new string is starting ($) if new_char == '$': self.new_sentence() return None elif self.sentence_active: # Check if sentence is near ending (*) if new_char == '*': self.mtk_string += new_char self.star_found = True # Store All Other printable character and check CRC when ready else: # Append New Character Character self.mtk_string += new_char # Check if Sentence is MTK Command Sentence if self.char_count == 4: if self.mtk_string == 'PMTK': self.mtk_sentence = True # Abort this sentence if it's longer than any valid sentence if self.char_count >= self.SENTENCE_LIMIT: self.sentence_active = False # Check if sentence is complete elif new_char == '\r': # Check all the validation flags for an MTK sentence have been tripped if self.sentence_active and self.mtk_sentence and self.star_found: # Test CRC Integrity if int(crc_calc(self.mtk_string[:-3]), 16) == int(self.mtk_string[-2:], 16): self.sentence_active = False return self.mtk_string # Standard Fall Through Empty Return return None
asdasdfgs = 1 def add(x, y): return x + y print(add(asdasdfgs, 2)) print(add(asdasdfgs, 3)) print(add(asdasdfgs, 5))
''' Desenvolva um programa que leia o primeiro termo e a razão de uma "PA". No final, mostre as 10 primeiros termos dessa progressão. ''' termo = int(input('Digite o primeiro termo: ')) razao = int(input('Digite a razão: ')) decimo = termo + (10 - 1) * razao for c in range(termo, decimo + razao, razao): print(f'{c} ', end='-> ')
#!/usr/bin/python #coding=utf-8 class List(list): def __getattr__(self, attr): tmp = List() for l in self: tmp.append(l.__getattr__(attr)) return tmp def equal(self, value, attr='class'): tmp = List() for l in self: if hasattr(l, 'equal'): flag = l.equal(value, attr) if flag: tmp.append(l) return tmp def contains(self, value, attr='html'): tmp = List() for l in self: if hasattr(l, 'contains'): flag = l.contains(value, attr) if flag: tmp.append(l) return tmp def containsOr(self, value, attr='html'): tmp = List() for l in self: if hasattr(l, 'containsOr'): flag = l.containsOr(value, attr) if flag: tmp.append(l) return tmp def notContains(self, value, attr='html'): tmp = List() for l in self: if hasattr(l, 'notContains'): flag = l.notContains(value, attr) if flag: tmp.append(l) return tmp def containsReg(self, value, attr='html'): tmp = [] for l in self: if hasattr(l, 'containsReg'): flag = l.containsReg(value, attr) if flag: tmp.append(l) return tmp def nextText(self, end=None): tmp = List() for l in self: tmp.append(l.nextText(end)) return tmp def previousText(self): tmp = List() for l in self: tmp.append(l.previousText()) return tmp def select(self, value, start=None, end=None, before=None): tmp = List() for l in self: tmp.append(l.select(value, start, end, before)) return tmp def selects(self, value, start=None, end=None, before=None): tmp = List() for l in self: tmp.append(l.selects(value, start, end, before)) return tmp def getElement(self, tag, attr='class', value=None, start=None, end=None, before=None): tmp = List() for l in self: tmp.append(l.getElement(tag, attr, value, start, end, before)) return tmp def getElements(self, tag, attr='class', value=None, start=None, end=None, before=None): tmp = List() for l in self: tmp.append(l.getElements(tag, attr, value, start, end, before)) return tmp def getTable(self, body='tbody', columns=None, rowReg=None, colReg=None, start=None, end=None, before=None): tmp = List() for l in self: tmp.append( l.getTable(body, columns, rowReg, colReg, start=start, end=end, before=before)) return tmp def getNext(self, tag=None): tmp = List() for l in self: tmp.append(l.getNext(tag)) return tmp