code stringlengths 2 1.05M | repo_name stringlengths 5 104 | path stringlengths 4 251 | language stringclasses 1 value | license stringclasses 15 values | size int32 2 1.05M |
|---|---|---|---|---|---|
from mitra import db
class Entry(db.Model):
id = db.Column(db.Integer, primary_key=True)
category_name = db.Column(db.String(120), db.ForeignKey('category.name'))
userid = db.Column(db.Integer, db.ForeignKey('user.id'))
date = db.Column(db.Date)
name = db.Column(db.String(120))
amount = db.Column(db.Integer)
def __init__(self, userid, category, date, name, amount):
self.userid = userid
self.category_name = category
self.date = date
self.name = name
self.amount = amount
| Nukesor/mitra | mitra/models/entry.py | Python | mit | 545 |
try:
from urllib.parse import quote, urljoin
except ImportError:
from urllib import quote
from urlparse import urljoin
import requests
class BandsintownError(Exception):
def __init__(self, message, response=None):
self.message = message
self.response = response
def __str__(self):
return self.message
class BandsintownInvalidAppIdError(BandsintownError):
pass
class BandsintownInvalidDateFormatError(BandsintownError):
pass
class Client(object):
api_base_url = 'https://rest.bandsintown.com'
def __init__(self, app_id):
"""
Args:
app_id: Required app id, can be any string
"""
self.app_id = app_id
self.default_params = {'app_id': self.app_id}
def request(self, path, params={}):
"""
Executes a request to the Bandsintown API and returns the response
object from `requests`
Args:
path: The API path to append to the base API URL for the request
params: Optional dict to tack on query string parameters to request
Returns:
Response object from `requests`
"""
url = urljoin(self.api_base_url, path)
request_params = self.default_params.copy()
request_params.update(params)
response = requests.get(
url,
headers={'Accept': 'application/json'},
params=request_params
)
data = response.json()
if 'message' in data and data['message'] == 'Missing required request parameters: [app_id]':
message = 'Missing required API key, which must be a single string argument to Client instantiation, e.g.: client = Client("my-app-id")'
raise BandsintownInvalidAppIdError(message, response)
else:
return data
def artists(self, artistname):
"""
Searches for a single artist using this endpoint:
https://app.swaggerhub.com/apis/Bandsintown/PublicAPI/3.0.0#/single_artist_information/artist
Args:
artistname: Artist name to search for
Returns:
A dict of artist data when the artist is found, and returns
None when not found
Usage:
client = Client(app_id='my-app-id')
client.artists('Bad Religion')
"""
try:
return self.request('artists/%s' % quote(artistname))
except ValueError:
# Currently the API's response when the artist doesn't exist is
# badly formed JSON. In such a case, we're catching the exception
# and returning None
return None
def artists_events(self, artistname, date=None):
"""
Searches for events for a single artist, with an optional date range,
using this endpoint:
https://app.swaggerhub.com/apis/Bandsintown/PublicAPI/3.0.0#/upcoming_artist_events/artistEvents
Args:
artistname: Artist name to search for
date: Optional date string filter, can be a specific date in the
format: "yyyy-mm-dd", a range "yyyy-mm-dd,yyyy-mm-dd", or can be a
few keyword values like "upcoming" or "all"
Returns:
A list of event data, which could be empty, None if artist not
found, raises `BandsintownInvalidDateFormatError` for bad `date`
param, or raises `BandsintownError` for other unknown error
Usage:
client = Client(app_id=1234)
client.artists_events('Bad Religion')
client.artists_events('Bad Religion', date='2018-02-01,2018-02-28')
"""
params = {}
if date:
params['date'] = date
data = self.request('artists/%s/events' % quote(artistname), params)
if 'errors' in data:
if data['errors'][0] == 'Invalid date format':
raise BandsintownInvalidDateFormatError(
'Invalid date parameter: "%s", must be in the format: "yyyy-mm-dd", or "yyyy-mm-dd,yyyy-mm-dd" for a range, or keywords "upcoming" or "all"' % date
)
elif data['errors'][0] == 'Unknown Artist':
return None
else:
raise BandsintownError('Unknown error with request', data)
return data
| jolbyandfriends/python-bandsintown | bandsintown/client.py | Python | mit | 4,358 |
# Constant indices within mmap buffers.
_POS_VALUE_LEN = 8
_READ_POS_IDX = 0
_WRITE_POS_IDX = _POS_VALUE_LEN
_HEADER_LEN = _POS_VALUE_LEN * 2
# Item size constants.
_ITEM_SIZE_LEN = 4
# struct.[un]pack format string for length fields
_POS_VALUE_FORMAT = "q"
_ITEM_SIZE_FORMAT = "i"
| whiskerlabs/mmringbuffer | mmringbuffer/constants.py | Python | mit | 292 |
##
## this file autogenerated
## 8.0(3)6
##
jmp_esp_offset = "191.143.24.9"
saferet_offset = "28.158.161.8"
fix_ebp = "88"
pmcheck_bounds = "0.0.11.9"
pmcheck_offset = "224.1.11.9"
pmcheck_code = "85.49.192.137"
admauth_bounds = "0.96.6.8"
admauth_offset = "112.101.6.8"
admauth_code = "85.137.229.87"
# "8.0(3)6" = ["191.143.24.9","28.158.161.8","88","0.0.11.9","224.1.11.9","85.49.192.137","0.96.6.8","112.101.6.8","85.137.229.87"], | RiskSense-Ops/CVE-2016-6366 | extrabacon-2.0/improved/shellcode_8_0(3)6.py | Python | mit | 437 |
#
# Jasy - Web Tooling Framework
# Copyright 2010-2012 Zynga Inc.
#
import os
import jasy.core.Console as Console
import jasy.core.Util as Util
import jasy.vcs.Git as Git
import jasy.vcs.Svn as Svn
def isUrl(url):
"""
Figures out whether the given string is a valid Git repository URL.
:param url: URL to the repository
:type url: string
"""
return Git.isUrl(url)
def getType(url):
"""
Returns repository type of the given URL.
:param url: URL to the repository
:type url: string
"""
if Git.isUrl(url):
return "git"
else:
return None
def getTargetFolder(url, version=None):
"""
Returns the target folder name based on the URL and version using SHA1 checksums.
:param url: URL to the repository
:type url: string
:param version: Version to use
:type url: string
"""
if Git.isUrl(url):
version = Git.expandVersion(version)
folder = url[url.rindex("/") + 1:]
if folder.endswith(".git"):
folder = folder[:-4]
identifier = "%s@%s" % (url, version)
version = version[version.rindex("/") + 1:]
hash = Util.generateChecksum(identifier)
return "%s-%s-%s" % (folder, version, hash)
def update(url, version=None, path=None, update=True):
"""
Clones the given repository URL (optionally with overriding/update features)
:param url: URL to the repository
:type url: string
:param version: Version to clone
:type url: string
:param version: Destination path
:type url: string
:param version: Eneable/disable update functionality
:type url: string
"""
revision = None
if Git.isUrl(url):
version = Git.expandVersion(version)
revision = Git.update(url, version, path, update)
return revision
def getRevision(path=None):
"""Returns the current revision of the repository in the given path."""
old = os.getcwd()
revision = None
if path is not None:
os.chdir(path)
while True:
if os.path.exists(".git"):
revision = Git.getBranch(path) + "-" + Git.getShortRevision(path)
break
elif os.path.exists(".svn"):
revision = Svn.getBranch(path) + "-" + Svn.getRevision(path)
break
cur = os.getcwd()
os.chdir(os.pardir)
if cur == os.getcwd():
break
os.chdir(old)
return revision
def clean(path=None):
"""
Cleans repository from untracked files.
:param url: Path to the local repository
:type url: string
"""
old = os.getcwd()
Console.info("Cleaning repository (clean)...")
Console.indent()
if path:
os.chdir(path)
if os.path.exists(".git"):
Git.cleanRepository()
os.chdir(old)
Console.outdent()
def distclean(path=None):
"""
Cleans repository from untracked and ignored files. This method is pretty agressive in a way that it deletes all non
repository managed files e.g. external folder, uncommitted changes, unstaged files, etc.
:param url: Path to the local repository
:type url: string
"""
old = os.getcwd()
Console.info("Cleaning repository (distclean)...")
Console.indent()
if path:
os.chdir(path)
if os.path.exists(".git"):
Git.distcleanRepository()
os.chdir(old)
Console.outdent()
| sebastian-software/jasy | jasy/vcs/Repository.py | Python | mit | 3,416 |
from plone import api
from plone.app.controlpanel.security import ISecuritySchema
def setup_workspaces(portal):
mp = api.portal.get_tool(name='portal_membership')
# set type to custom member type
mp.setMemberAreaType('wigo.workspaces.workspace')
# set member folder name
mp.setMembersFolderById('sqa')
def setup_security(portal):
""" Add security controlpanel settings.
"""
site = api.portal.get()
#site security setup!
security = ISecuritySchema(site)
security.set_enable_user_folders(True)
security.use_uuid_as_userid(True)
def setupVarious(context):
if context.readDataFile('wigo.statusapp-various.txt') is None:
return
portal = api.portal.get()
setup_workspaces(portal)
# call update security
setup_security(portal)
| ade25/wigo | src/wigo.statusapp/wigo/statusapp/setuphandlers.py | Python | mit | 802 |
"""
The Plaid API
The Plaid REST API. Please see https://plaid.com/docs/api for more details. # noqa: E501
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
import sys # noqa: F401
from plaid.model_utils import ( # noqa: F401
ApiTypeError,
ModelComposed,
ModelNormal,
ModelSimple,
cached_property,
change_keys_js_to_python,
convert_js_args_to_python_args,
date,
datetime,
file_type,
none_type,
validate_get_composed_info,
)
class RecurringTransactionFrequency(ModelSimple):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
Attributes:
allowed_values (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
with a capitalized key describing the allowed value and an allowed
value. These dicts store the allowed enum values.
validations (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
"""
allowed_values = {
('value',): {
'UNKNOWN': "UNKNOWN",
'WEEKLY': "WEEKLY",
'BIWEEKLY': "BIWEEKLY",
'SEMI_MONTHLY': "SEMI_MONTHLY",
'MONTHLY': "MONTHLY",
},
}
validations = {
}
additional_properties_type = None
_nullable = False
@cached_property
def openapi_types():
"""
This must be a method because a model may have properties that are
of type self, this must run after the class is loaded
Returns
openapi_types (dict): The key is attribute name
and the value is attribute type.
"""
return {
'value': (str,),
}
@cached_property
def discriminator():
return None
attribute_map = {}
_composed_schemas = None
required_properties = set([
'_data_store',
'_check_type',
'_spec_property_naming',
'_path_to_item',
'_configuration',
'_visited_composed_classes',
])
@convert_js_args_to_python_args
def __init__(self, *args, **kwargs):
"""RecurringTransactionFrequency - a model defined in OpenAPI
Note that value can be passed either in args or in kwargs, but not in both.
Args:
args[0] (str): describes the frequency of the transaction stream.., must be one of ["UNKNOWN", "WEEKLY", "BIWEEKLY", "SEMI_MONTHLY", "MONTHLY", ] # noqa: E501
Keyword Args:
value (str): describes the frequency of the transaction stream.., must be one of ["UNKNOWN", "WEEKLY", "BIWEEKLY", "SEMI_MONTHLY", "MONTHLY", ] # noqa: E501
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_spec_property_naming (bool): True if the variable names in the input data
are serialized names, as specified in the OpenAPI document.
False if the variable names in the input data
are pythonic names, e.g. snake case (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
_visited_composed_classes (tuple): This stores a tuple of
classes that we have traveled through so that
if we see that class again we will not use its
discriminator again.
When traveling through a discriminator, the
composed schema that is
is traveled through is added to this set.
For example if Animal has a discriminator
petType and we pass in "Dog", and the class Dog
allOf includes Animal, we move through Animal
once using the discriminator, and pick Dog.
Then in Dog, we will make an instance of the
Animal class but this time we won't travel
through its discriminator because we passed in
_visited_composed_classes = (Animal,)
"""
# required up here when default value is not given
_path_to_item = kwargs.pop('_path_to_item', ())
if 'value' in kwargs:
value = kwargs.pop('value')
elif args:
args = list(args)
value = args.pop(0)
else:
raise ApiTypeError(
"value is required, but not passed in args or kwargs and doesn't have default",
path_to_item=_path_to_item,
valid_classes=(self.__class__,),
)
_check_type = kwargs.pop('_check_type', True)
_spec_property_naming = kwargs.pop('_spec_property_naming', False)
_configuration = kwargs.pop('_configuration', None)
_visited_composed_classes = kwargs.pop('_visited_composed_classes', ())
if args:
raise ApiTypeError(
"Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % (
args,
self.__class__.__name__,
),
path_to_item=_path_to_item,
valid_classes=(self.__class__,),
)
self._data_store = {}
self._check_type = _check_type
self._spec_property_naming = _spec_property_naming
self._path_to_item = _path_to_item
self._configuration = _configuration
self._visited_composed_classes = _visited_composed_classes + (self.__class__,)
self.value = value
if kwargs:
raise ApiTypeError(
"Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % (
kwargs,
self.__class__.__name__,
),
path_to_item=_path_to_item,
valid_classes=(self.__class__,),
)
| plaid/plaid-python | plaid/model/recurring_transaction_frequency.py | Python | mit | 7,155 |
# -*- coding: utf8 -*-
# Copyright (c) 2017-2021 THL A29 Limited, a Tencent company. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import warnings
from tencentcloud.common.abstract_model import AbstractModel
class AbnormalProcessChildRuleInfo(AbstractModel):
"""容器运行时安全,子策略信息
"""
def __init__(self):
r"""
:param RuleMode: 策略模式, RULE_MODE_RELEASE: 放行
RULE_MODE_ALERT: 告警
RULE_MODE_HOLDUP:拦截
:type RuleMode: str
:param ProcessPath: 进程路径
:type ProcessPath: str
:param RuleId: 子策略id
注意:此字段可能返回 null,表示取不到有效值。
:type RuleId: str
"""
self.RuleMode = None
self.ProcessPath = None
self.RuleId = None
def _deserialize(self, params):
self.RuleMode = params.get("RuleMode")
self.ProcessPath = params.get("ProcessPath")
self.RuleId = params.get("RuleId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class AbnormalProcessEventDescription(AbstractModel):
"""运行时容器访问控制事件描述信息
"""
def __init__(self):
r"""
:param Description: 事件规则
:type Description: str
:param Solution: 解决方案
:type Solution: str
:param Remark: 事件备注信息
注意:此字段可能返回 null,表示取不到有效值。
:type Remark: str
:param MatchRule: 命中规则详细信息
:type MatchRule: :class:`tencentcloud.tcss.v20201101.models.AbnormalProcessChildRuleInfo`
:param RuleName: 命中规则名字
:type RuleName: str
:param RuleId: 命中规则的id
:type RuleId: str
"""
self.Description = None
self.Solution = None
self.Remark = None
self.MatchRule = None
self.RuleName = None
self.RuleId = None
def _deserialize(self, params):
self.Description = params.get("Description")
self.Solution = params.get("Solution")
self.Remark = params.get("Remark")
if params.get("MatchRule") is not None:
self.MatchRule = AbnormalProcessChildRuleInfo()
self.MatchRule._deserialize(params.get("MatchRule"))
self.RuleName = params.get("RuleName")
self.RuleId = params.get("RuleId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class AbnormalProcessEventInfo(AbstractModel):
"""容器运行时安全异常进程信息
"""
def __init__(self):
r"""
:param ProcessPath: 进程目录
:type ProcessPath: str
:param EventType: 事件类型,MALICE_PROCESS_START:恶意进程启动
:type EventType: str
:param MatchRuleName: 命中规则
:type MatchRuleName: str
:param FoundTime: 生成时间
:type FoundTime: str
:param ContainerName: 容器名
:type ContainerName: str
:param ImageName: 镜像名
:type ImageName: str
:param Behavior: 动作执行结果, BEHAVIOR_NONE: 无
BEHAVIOR_ALERT: 告警
BEHAVIOR_RELEASE:放行
BEHAVIOR_HOLDUP_FAILED:拦截失败
BEHAVIOR_HOLDUP_SUCCESSED:拦截失败
:type Behavior: str
:param Status: 状态,EVENT_UNDEAL:事件未处理
EVENT_DEALED:事件已经处理
EVENT_INGNORE:事件已经忽略
:type Status: str
:param Id: 事件记录的唯一id
:type Id: str
:param ImageId: 镜像id,用于跳转
:type ImageId: str
:param ContainerId: 容器id,用于跳转
:type ContainerId: str
:param Solution: 事件解决方案
:type Solution: str
:param Description: 事件详细描述
:type Description: str
:param MatchRuleId: 命中策略id
:type MatchRuleId: str
:param MatchAction: 命中规则行为:
RULE_MODE_RELEASE 放行
RULE_MODE_ALERT 告警
RULE_MODE_HOLDUP 拦截
:type MatchAction: str
:param MatchProcessPath: 命中规则进程信息
:type MatchProcessPath: str
:param RuleExist: 规则是否存在
:type RuleExist: bool
:param EventCount: 事件数量
:type EventCount: int
:param LatestFoundTime: 最近生成时间
:type LatestFoundTime: str
:param RuleId: 规则组Id
:type RuleId: str
"""
self.ProcessPath = None
self.EventType = None
self.MatchRuleName = None
self.FoundTime = None
self.ContainerName = None
self.ImageName = None
self.Behavior = None
self.Status = None
self.Id = None
self.ImageId = None
self.ContainerId = None
self.Solution = None
self.Description = None
self.MatchRuleId = None
self.MatchAction = None
self.MatchProcessPath = None
self.RuleExist = None
self.EventCount = None
self.LatestFoundTime = None
self.RuleId = None
def _deserialize(self, params):
self.ProcessPath = params.get("ProcessPath")
self.EventType = params.get("EventType")
self.MatchRuleName = params.get("MatchRuleName")
self.FoundTime = params.get("FoundTime")
self.ContainerName = params.get("ContainerName")
self.ImageName = params.get("ImageName")
self.Behavior = params.get("Behavior")
self.Status = params.get("Status")
self.Id = params.get("Id")
self.ImageId = params.get("ImageId")
self.ContainerId = params.get("ContainerId")
self.Solution = params.get("Solution")
self.Description = params.get("Description")
self.MatchRuleId = params.get("MatchRuleId")
self.MatchAction = params.get("MatchAction")
self.MatchProcessPath = params.get("MatchProcessPath")
self.RuleExist = params.get("RuleExist")
self.EventCount = params.get("EventCount")
self.LatestFoundTime = params.get("LatestFoundTime")
self.RuleId = params.get("RuleId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class AbnormalProcessRuleInfo(AbstractModel):
"""运行时安全,异常进程检测策略
"""
def __init__(self):
r"""
:param IsEnable: true:策略启用,false:策略禁用
:type IsEnable: bool
:param ImageIds: 生效镜像id,空数组代表全部镜像
:type ImageIds: list of str
:param ChildRules: 用户策略的子策略数组
:type ChildRules: list of AbnormalProcessChildRuleInfo
:param RuleName: 策略名字
:type RuleName: str
:param RuleId: 策略id
注意:此字段可能返回 null,表示取不到有效值。
:type RuleId: str
:param SystemChildRules: 系统策略的子策略数组
:type SystemChildRules: list of AbnormalProcessSystemChildRuleInfo
"""
self.IsEnable = None
self.ImageIds = None
self.ChildRules = None
self.RuleName = None
self.RuleId = None
self.SystemChildRules = None
def _deserialize(self, params):
self.IsEnable = params.get("IsEnable")
self.ImageIds = params.get("ImageIds")
if params.get("ChildRules") is not None:
self.ChildRules = []
for item in params.get("ChildRules"):
obj = AbnormalProcessChildRuleInfo()
obj._deserialize(item)
self.ChildRules.append(obj)
self.RuleName = params.get("RuleName")
self.RuleId = params.get("RuleId")
if params.get("SystemChildRules") is not None:
self.SystemChildRules = []
for item in params.get("SystemChildRules"):
obj = AbnormalProcessSystemChildRuleInfo()
obj._deserialize(item)
self.SystemChildRules.append(obj)
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class AbnormalProcessSystemChildRuleInfo(AbstractModel):
"""异常进程系统策略的子策略信息
"""
def __init__(self):
r"""
:param RuleId: 子策略Id
:type RuleId: str
:param IsEnable: 子策略状态,true为开启,false为关闭
:type IsEnable: bool
:param RuleMode: 策略模式, RULE_MODE_RELEASE: 放行
RULE_MODE_ALERT: 告警
RULE_MODE_HOLDUP:拦截
:type RuleMode: str
:param RuleType: 子策略检测的行为类型
PROXY_TOOL: 代理软件
TRANSFER_CONTROL:横向渗透
ATTACK_CMD: 恶意命令
REVERSE_SHELL:反弹shell
FILELESS:无文件程序执行
RISK_CMD:高危命令
ABNORMAL_CHILD_PROC: 敏感服务异常子进程启动
:type RuleType: str
"""
self.RuleId = None
self.IsEnable = None
self.RuleMode = None
self.RuleType = None
def _deserialize(self, params):
self.RuleId = params.get("RuleId")
self.IsEnable = params.get("IsEnable")
self.RuleMode = params.get("RuleMode")
self.RuleType = params.get("RuleType")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class AccessControlChildRuleInfo(AbstractModel):
"""容器运行时安全,访问控制子策略信息
"""
def __init__(self):
r"""
:param RuleMode: 策略模式, RULE_MODE_RELEASE: 放行
RULE_MODE_ALERT: 告警
RULE_MODE_HOLDUP:拦截
:type RuleMode: str
:param ProcessPath: 进程路径
:type ProcessPath: str
:param TargetFilePath: 被访问文件路径,仅仅在访问控制生效
:type TargetFilePath: str
:param RuleId: 子策略id
注意:此字段可能返回 null,表示取不到有效值。
:type RuleId: str
"""
self.RuleMode = None
self.ProcessPath = None
self.TargetFilePath = None
self.RuleId = None
def _deserialize(self, params):
self.RuleMode = params.get("RuleMode")
self.ProcessPath = params.get("ProcessPath")
self.TargetFilePath = params.get("TargetFilePath")
self.RuleId = params.get("RuleId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class AccessControlEventDescription(AbstractModel):
"""运行时容器访问控制事件描述信息
"""
def __init__(self):
r"""
:param Description: 事件规则
:type Description: str
:param Solution: 解决方案
:type Solution: str
:param Remark: 事件备注信息
注意:此字段可能返回 null,表示取不到有效值。
:type Remark: str
:param MatchRule: 命中规则详细信息
:type MatchRule: :class:`tencentcloud.tcss.v20201101.models.AccessControlChildRuleInfo`
:param RuleName: 命中规则名字
:type RuleName: str
:param RuleId: 命中规则id
:type RuleId: str
"""
self.Description = None
self.Solution = None
self.Remark = None
self.MatchRule = None
self.RuleName = None
self.RuleId = None
def _deserialize(self, params):
self.Description = params.get("Description")
self.Solution = params.get("Solution")
self.Remark = params.get("Remark")
if params.get("MatchRule") is not None:
self.MatchRule = AccessControlChildRuleInfo()
self.MatchRule._deserialize(params.get("MatchRule"))
self.RuleName = params.get("RuleName")
self.RuleId = params.get("RuleId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class AccessControlEventInfo(AbstractModel):
"""容器运行时安全访问控制事件信息
"""
def __init__(self):
r"""
:param ProcessName: 进程名称
:type ProcessName: str
:param MatchRuleName: 命中规则名称
:type MatchRuleName: str
:param FoundTime: 生成时间
:type FoundTime: str
:param ContainerName: 容器名
:type ContainerName: str
:param ImageName: 镜像名
:type ImageName: str
:param Behavior: 动作执行结果, BEHAVIOR_NONE: 无
BEHAVIOR_ALERT: 告警
BEHAVIOR_RELEASE:放行
BEHAVIOR_HOLDUP_FAILED:拦截失败
BEHAVIOR_HOLDUP_SUCCESSED:拦截失败
:type Behavior: str
:param Status: 状态0:未处理 “EVENT_UNDEAL”:事件未处理
"EVENT_DEALED":事件已经处理
"EVENT_INGNORE":事件已经忽略
:type Status: str
:param Id: 事件记录的唯一id
:type Id: str
:param FileName: 文件名称
:type FileName: str
:param EventType: 事件类型, FILE_ABNORMAL_READ:文件异常读取
:type EventType: str
:param ImageId: 镜像id, 用于跳转
:type ImageId: str
:param ContainerId: 容器id, 用于跳转
:type ContainerId: str
:param Solution: 事件解决方案
:type Solution: str
:param Description: 事件详细描述
:type Description: str
:param MatchRuleId: 命中策略id
:type MatchRuleId: str
:param MatchAction: 命中规则行为:
RULE_MODE_RELEASE 放行
RULE_MODE_ALERT 告警
RULE_MODE_HOLDUP 拦截
:type MatchAction: str
:param MatchProcessPath: 命中规则进程信息
:type MatchProcessPath: str
:param MatchFilePath: 命中规则文件信息
:type MatchFilePath: str
:param FilePath: 文件路径,包含名字
:type FilePath: str
:param RuleExist: 规则是否存在
:type RuleExist: bool
:param EventCount: 事件数量
:type EventCount: int
:param LatestFoundTime: 最近生成时间
:type LatestFoundTime: str
:param RuleId: 规则组id
:type RuleId: str
"""
self.ProcessName = None
self.MatchRuleName = None
self.FoundTime = None
self.ContainerName = None
self.ImageName = None
self.Behavior = None
self.Status = None
self.Id = None
self.FileName = None
self.EventType = None
self.ImageId = None
self.ContainerId = None
self.Solution = None
self.Description = None
self.MatchRuleId = None
self.MatchAction = None
self.MatchProcessPath = None
self.MatchFilePath = None
self.FilePath = None
self.RuleExist = None
self.EventCount = None
self.LatestFoundTime = None
self.RuleId = None
def _deserialize(self, params):
self.ProcessName = params.get("ProcessName")
self.MatchRuleName = params.get("MatchRuleName")
self.FoundTime = params.get("FoundTime")
self.ContainerName = params.get("ContainerName")
self.ImageName = params.get("ImageName")
self.Behavior = params.get("Behavior")
self.Status = params.get("Status")
self.Id = params.get("Id")
self.FileName = params.get("FileName")
self.EventType = params.get("EventType")
self.ImageId = params.get("ImageId")
self.ContainerId = params.get("ContainerId")
self.Solution = params.get("Solution")
self.Description = params.get("Description")
self.MatchRuleId = params.get("MatchRuleId")
self.MatchAction = params.get("MatchAction")
self.MatchProcessPath = params.get("MatchProcessPath")
self.MatchFilePath = params.get("MatchFilePath")
self.FilePath = params.get("FilePath")
self.RuleExist = params.get("RuleExist")
self.EventCount = params.get("EventCount")
self.LatestFoundTime = params.get("LatestFoundTime")
self.RuleId = params.get("RuleId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class AccessControlRuleInfo(AbstractModel):
"""容器运行时,访问控制策略信息
"""
def __init__(self):
r"""
:param IsEnable: 开关,true:开启,false:禁用
:type IsEnable: bool
:param ImageIds: 生效惊现id,空数组代表全部镜像
:type ImageIds: list of str
:param ChildRules: 用户策略的子策略数组
:type ChildRules: list of AccessControlChildRuleInfo
:param RuleName: 策略名字
:type RuleName: str
:param RuleId: 策略id
注意:此字段可能返回 null,表示取不到有效值。
:type RuleId: str
:param SystemChildRules: 系统策略的子策略数组
:type SystemChildRules: list of AccessControlSystemChildRuleInfo
"""
self.IsEnable = None
self.ImageIds = None
self.ChildRules = None
self.RuleName = None
self.RuleId = None
self.SystemChildRules = None
def _deserialize(self, params):
self.IsEnable = params.get("IsEnable")
self.ImageIds = params.get("ImageIds")
if params.get("ChildRules") is not None:
self.ChildRules = []
for item in params.get("ChildRules"):
obj = AccessControlChildRuleInfo()
obj._deserialize(item)
self.ChildRules.append(obj)
self.RuleName = params.get("RuleName")
self.RuleId = params.get("RuleId")
if params.get("SystemChildRules") is not None:
self.SystemChildRules = []
for item in params.get("SystemChildRules"):
obj = AccessControlSystemChildRuleInfo()
obj._deserialize(item)
self.SystemChildRules.append(obj)
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class AccessControlSystemChildRuleInfo(AbstractModel):
"""容器运行时安全,访问控制系统策略的子策略信息
"""
def __init__(self):
r"""
:param RuleId: 子策略Id
:type RuleId: str
:param RuleMode: 策略模式, RULE_MODE_RELEASE: 放行
RULE_MODE_ALERT: 告警
RULE_MODE_HOLDUP:拦截
:type RuleMode: str
:param IsEnable: 子策略状态,true为开启,false为关闭
:type IsEnable: bool
:param RuleType: 子策略检测的入侵行为类型
CHANGE_CRONTAB:篡改计划任务
CHANGE_SYS_BIN:篡改系统程序
CHANGE_USRCFG:篡改用户配置
:type RuleType: str
"""
self.RuleId = None
self.RuleMode = None
self.IsEnable = None
self.RuleType = None
def _deserialize(self, params):
self.RuleId = params.get("RuleId")
self.RuleMode = params.get("RuleMode")
self.IsEnable = params.get("IsEnable")
self.RuleType = params.get("RuleType")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class AddAssetImageRegistryRegistryDetailRequest(AbstractModel):
"""AddAssetImageRegistryRegistryDetail请求参数结构体
"""
def __init__(self):
r"""
:param Name: 仓库名
:type Name: str
:param Username: 用户名
:type Username: str
:param Password: 密码
:type Password: str
:param Url: 仓库url
:type Url: str
:param RegistryType: 仓库类型,列表:harbor
:type RegistryType: str
:param NetType: 网络类型,列表:public(公网)
:type NetType: str
:param RegistryVersion: 仓库版本
:type RegistryVersion: str
:param RegistryRegion: 区域,列表:default(默认)
:type RegistryRegion: str
:param SpeedLimit: 限速
:type SpeedLimit: int
:param Insecure: 安全模式(证书校验):0(默认) 非安全模式(跳过证书校验):1
:type Insecure: int
"""
self.Name = None
self.Username = None
self.Password = None
self.Url = None
self.RegistryType = None
self.NetType = None
self.RegistryVersion = None
self.RegistryRegion = None
self.SpeedLimit = None
self.Insecure = None
def _deserialize(self, params):
self.Name = params.get("Name")
self.Username = params.get("Username")
self.Password = params.get("Password")
self.Url = params.get("Url")
self.RegistryType = params.get("RegistryType")
self.NetType = params.get("NetType")
self.RegistryVersion = params.get("RegistryVersion")
self.RegistryRegion = params.get("RegistryRegion")
self.SpeedLimit = params.get("SpeedLimit")
self.Insecure = params.get("Insecure")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class AddAssetImageRegistryRegistryDetailResponse(AbstractModel):
"""AddAssetImageRegistryRegistryDetail返回参数结构体
"""
def __init__(self):
r"""
:param HealthCheckErr: 连接错误信息
注意:此字段可能返回 null,表示取不到有效值。
:type HealthCheckErr: str
:param NameRepeatErr: 名称错误信息
注意:此字段可能返回 null,表示取不到有效值。
:type NameRepeatErr: str
:param RegistryId: 仓库唯一id
注意:此字段可能返回 null,表示取不到有效值。
:type RegistryId: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.HealthCheckErr = None
self.NameRepeatErr = None
self.RegistryId = None
self.RequestId = None
def _deserialize(self, params):
self.HealthCheckErr = params.get("HealthCheckErr")
self.NameRepeatErr = params.get("NameRepeatErr")
self.RegistryId = params.get("RegistryId")
self.RequestId = params.get("RequestId")
class AddCompliancePolicyItemToWhitelistRequest(AbstractModel):
"""AddCompliancePolicyItemToWhitelist请求参数结构体
"""
def __init__(self):
r"""
:param CustomerPolicyItemIdSet: 要忽略的检测项的ID的列表
:type CustomerPolicyItemIdSet: list of int non-negative
"""
self.CustomerPolicyItemIdSet = None
def _deserialize(self, params):
self.CustomerPolicyItemIdSet = params.get("CustomerPolicyItemIdSet")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class AddCompliancePolicyItemToWhitelistResponse(AbstractModel):
"""AddCompliancePolicyItemToWhitelist返回参数结构体
"""
def __init__(self):
r"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RequestId = None
def _deserialize(self, params):
self.RequestId = params.get("RequestId")
class AddEditAbnormalProcessRuleRequest(AbstractModel):
"""AddEditAbnormalProcessRule请求参数结构体
"""
def __init__(self):
r"""
:param RuleInfo: 增加策略信息,策略id为空,编辑策略是id不能为空
:type RuleInfo: :class:`tencentcloud.tcss.v20201101.models.AbnormalProcessRuleInfo`
:param EventId: 仅在加白的时候带上
:type EventId: str
"""
self.RuleInfo = None
self.EventId = None
def _deserialize(self, params):
if params.get("RuleInfo") is not None:
self.RuleInfo = AbnormalProcessRuleInfo()
self.RuleInfo._deserialize(params.get("RuleInfo"))
self.EventId = params.get("EventId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class AddEditAbnormalProcessRuleResponse(AbstractModel):
"""AddEditAbnormalProcessRule返回参数结构体
"""
def __init__(self):
r"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RequestId = None
def _deserialize(self, params):
self.RequestId = params.get("RequestId")
class AddEditAccessControlRuleRequest(AbstractModel):
"""AddEditAccessControlRule请求参数结构体
"""
def __init__(self):
r"""
:param RuleInfo: 增加策略信息,策略id为空,编辑策略是id不能为空
:type RuleInfo: :class:`tencentcloud.tcss.v20201101.models.AccessControlRuleInfo`
:param EventId: 仅在白名单时候使用
:type EventId: str
"""
self.RuleInfo = None
self.EventId = None
def _deserialize(self, params):
if params.get("RuleInfo") is not None:
self.RuleInfo = AccessControlRuleInfo()
self.RuleInfo._deserialize(params.get("RuleInfo"))
self.EventId = params.get("EventId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class AddEditAccessControlRuleResponse(AbstractModel):
"""AddEditAccessControlRule返回参数结构体
"""
def __init__(self):
r"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RequestId = None
def _deserialize(self, params):
self.RequestId = params.get("RequestId")
class AddEditReverseShellWhiteListRequest(AbstractModel):
"""AddEditReverseShellWhiteList请求参数结构体
"""
def __init__(self):
r"""
:param WhiteListInfo: 增加或编辑白名单信息。新增白名单时WhiteListInfo.id为空,编辑白名单WhiteListInfo.id不能为空。
:type WhiteListInfo: :class:`tencentcloud.tcss.v20201101.models.ReverseShellWhiteListInfo`
:param EventId: 仅在添加事件白名单时候使用
:type EventId: str
"""
self.WhiteListInfo = None
self.EventId = None
def _deserialize(self, params):
if params.get("WhiteListInfo") is not None:
self.WhiteListInfo = ReverseShellWhiteListInfo()
self.WhiteListInfo._deserialize(params.get("WhiteListInfo"))
self.EventId = params.get("EventId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class AddEditReverseShellWhiteListResponse(AbstractModel):
"""AddEditReverseShellWhiteList返回参数结构体
"""
def __init__(self):
r"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RequestId = None
def _deserialize(self, params):
self.RequestId = params.get("RequestId")
class AddEditRiskSyscallWhiteListRequest(AbstractModel):
"""AddEditRiskSyscallWhiteList请求参数结构体
"""
def __init__(self):
r"""
:param EventId: 仅在添加白名单时候使用
:type EventId: str
:param WhiteListInfo: 增加白名单信息,白名单id为空,编辑白名单id不能为空
:type WhiteListInfo: :class:`tencentcloud.tcss.v20201101.models.RiskSyscallWhiteListInfo`
"""
self.EventId = None
self.WhiteListInfo = None
def _deserialize(self, params):
self.EventId = params.get("EventId")
if params.get("WhiteListInfo") is not None:
self.WhiteListInfo = RiskSyscallWhiteListInfo()
self.WhiteListInfo._deserialize(params.get("WhiteListInfo"))
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class AddEditRiskSyscallWhiteListResponse(AbstractModel):
"""AddEditRiskSyscallWhiteList返回参数结构体
"""
def __init__(self):
r"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RequestId = None
def _deserialize(self, params):
self.RequestId = params.get("RequestId")
class AddEditWarningRulesRequest(AbstractModel):
"""AddEditWarningRules请求参数结构体
"""
def __init__(self):
r"""
:param WarningRules: 告警开关策略
:type WarningRules: list of WarningRule
"""
self.WarningRules = None
def _deserialize(self, params):
if params.get("WarningRules") is not None:
self.WarningRules = []
for item in params.get("WarningRules"):
obj = WarningRule()
obj._deserialize(item)
self.WarningRules.append(obj)
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class AddEditWarningRulesResponse(AbstractModel):
"""AddEditWarningRules返回参数结构体
"""
def __init__(self):
r"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RequestId = None
def _deserialize(self, params):
self.RequestId = params.get("RequestId")
class AffectedNodeItem(AbstractModel):
"""受影响的节点类型结构体
"""
def __init__(self):
r"""
:param ClusterId: 集群ID
:type ClusterId: str
:param ClusterName: 集群名字
:type ClusterName: str
:param InstanceId: 实例id
:type InstanceId: str
:param PrivateIpAddresses: 内网ip地址
:type PrivateIpAddresses: str
:param InstanceRole: 节点的角色,Master、Work等
:type InstanceRole: str
:param ClusterVersion: k8s版本
:type ClusterVersion: str
:param ContainerRuntime: 运行时组件,docker或者containerd
:type ContainerRuntime: str
:param Region: 区域
:type Region: str
:param VerifyInfo: 检查结果的验证信息
:type VerifyInfo: str
"""
self.ClusterId = None
self.ClusterName = None
self.InstanceId = None
self.PrivateIpAddresses = None
self.InstanceRole = None
self.ClusterVersion = None
self.ContainerRuntime = None
self.Region = None
self.VerifyInfo = None
def _deserialize(self, params):
self.ClusterId = params.get("ClusterId")
self.ClusterName = params.get("ClusterName")
self.InstanceId = params.get("InstanceId")
self.PrivateIpAddresses = params.get("PrivateIpAddresses")
self.InstanceRole = params.get("InstanceRole")
self.ClusterVersion = params.get("ClusterVersion")
self.ContainerRuntime = params.get("ContainerRuntime")
self.Region = params.get("Region")
self.VerifyInfo = params.get("VerifyInfo")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class AffectedWorkloadItem(AbstractModel):
"""集群安全检查受影响的工作负载Item
"""
def __init__(self):
r"""
:param ClusterId: 集群Id
:type ClusterId: str
:param ClusterName: 集群名字
:type ClusterName: str
:param WorkloadName: 工作负载名称
:type WorkloadName: str
:param WorkloadType: 工作负载类型
:type WorkloadType: str
:param Region: 区域
:type Region: str
:param VerifyInfo: 检测结果的验证信息
:type VerifyInfo: str
"""
self.ClusterId = None
self.ClusterName = None
self.WorkloadName = None
self.WorkloadType = None
self.Region = None
self.VerifyInfo = None
def _deserialize(self, params):
self.ClusterId = params.get("ClusterId")
self.ClusterName = params.get("ClusterName")
self.WorkloadName = params.get("WorkloadName")
self.WorkloadType = params.get("WorkloadType")
self.Region = params.get("Region")
self.VerifyInfo = params.get("VerifyInfo")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class AssetFilters(AbstractModel):
"""容器安全
描述键值对过滤器,用于条件过滤查询。例如过滤ID、名称、状态等
若存在多个Filter时,Filter间的关系为逻辑与(AND)关系。
若同一个Filter存在多个Values,同一Filter下Values间的关系为逻辑或(OR)关系。
"""
def __init__(self):
r"""
:param Name: 过滤键的名称
:type Name: str
:param Values: 一个或者多个过滤值。
:type Values: list of str
:param ExactMatch: 是否模糊查询
:type ExactMatch: bool
"""
self.Name = None
self.Values = None
self.ExactMatch = None
def _deserialize(self, params):
self.Name = params.get("Name")
self.Values = params.get("Values")
self.ExactMatch = params.get("ExactMatch")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class AssetSimpleImageInfo(AbstractModel):
"""容器安全资产镜像简略信息
"""
def __init__(self):
r"""
:param ImageID: 镜像ID
:type ImageID: str
:param ImageName: 镜像名称
:type ImageName: str
:param ContainerCnt: 关联容器个数
:type ContainerCnt: int
:param ScanTime: 最后扫描时间
:type ScanTime: str
:param Size: 镜像大小
:type Size: int
"""
self.ImageID = None
self.ImageName = None
self.ContainerCnt = None
self.ScanTime = None
self.Size = None
def _deserialize(self, params):
self.ImageID = params.get("ImageID")
self.ImageName = params.get("ImageName")
self.ContainerCnt = params.get("ContainerCnt")
self.ScanTime = params.get("ScanTime")
self.Size = params.get("Size")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class CheckRepeatAssetImageRegistryRequest(AbstractModel):
"""CheckRepeatAssetImageRegistry请求参数结构体
"""
def __init__(self):
r"""
:param Name: 仓库名
:type Name: str
"""
self.Name = None
def _deserialize(self, params):
self.Name = params.get("Name")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class CheckRepeatAssetImageRegistryResponse(AbstractModel):
"""CheckRepeatAssetImageRegistry返回参数结构体
"""
def __init__(self):
r"""
:param IsRepeat: 是否重复
注意:此字段可能返回 null,表示取不到有效值。
:type IsRepeat: bool
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.IsRepeat = None
self.RequestId = None
def _deserialize(self, params):
self.IsRepeat = params.get("IsRepeat")
self.RequestId = params.get("RequestId")
class ClusterCheckItem(AbstractModel):
"""表示一条集群安全检测项的详细信息
"""
def __init__(self):
r"""
:param CheckItemId: 唯一的检测项的ID
注意:此字段可能返回 null,表示取不到有效值。
:type CheckItemId: int
:param Name: 风险项的名称
:type Name: str
:param ItemDetail: 检测项详细描述。
注意:此字段可能返回 null,表示取不到有效值。
:type ItemDetail: str
:param RiskLevel: 威胁等级。严重Serious,高危High,中危Middle,提示Hint
注意:此字段可能返回 null,表示取不到有效值。
:type RiskLevel: str
:param RiskTarget: 检查对象、风险对象.Runc,Kubelet,Containerd,Pods
注意:此字段可能返回 null,表示取不到有效值。
:type RiskTarget: str
:param RiskType: 风险类别,漏洞风险CVERisk,配置风险ConfigRisk
注意:此字段可能返回 null,表示取不到有效值。
:type RiskType: str
:param RiskAttribute: 检测项所属的风险类型,权限提升:PrivilegePromotion,拒绝服务:RefuseService,目录穿越:DirectoryEscape,未授权访问:UnauthorizedAccess,权限许可和访问控制问题:PrivilegeAndAccessControl,敏感信息泄露:SensitiveInfoLeak
注意:此字段可能返回 null,表示取不到有效值。
:type RiskAttribute: str
:param RiskProperty: 风险特征,Tag.存在EXP:ExistEXP,存在POD:ExistPOC,无需重启:NoNeedReboot, 服务重启:ServerRestart,远程信息泄露:RemoteInfoLeak,远程拒绝服务:RemoteRefuseService,远程利用:RemoteExploit,远程执行:RemoteExecute
注意:此字段可能返回 null,表示取不到有效值。
:type RiskProperty: str
:param CVENumber: CVE编号
注意:此字段可能返回 null,表示取不到有效值。
:type CVENumber: str
:param DiscoverTime: 披露时间
注意:此字段可能返回 null,表示取不到有效值。
:type DiscoverTime: str
:param Solution: 解决方案
注意:此字段可能返回 null,表示取不到有效值。
:type Solution: str
:param CVSS: CVSS信息,用于画图
注意:此字段可能返回 null,表示取不到有效值。
:type CVSS: str
:param CVSSScore: CVSS分数
注意:此字段可能返回 null,表示取不到有效值。
:type CVSSScore: str
:param RelateLink: 参考连接
注意:此字段可能返回 null,表示取不到有效值。
:type RelateLink: str
:param AffectedType: 影响类型,为Node或者Workload
注意:此字段可能返回 null,表示取不到有效值。
:type AffectedType: str
:param AffectedVersion: 受影响的版本信息
注意:此字段可能返回 null,表示取不到有效值。
:type AffectedVersion: str
"""
self.CheckItemId = None
self.Name = None
self.ItemDetail = None
self.RiskLevel = None
self.RiskTarget = None
self.RiskType = None
self.RiskAttribute = None
self.RiskProperty = None
self.CVENumber = None
self.DiscoverTime = None
self.Solution = None
self.CVSS = None
self.CVSSScore = None
self.RelateLink = None
self.AffectedType = None
self.AffectedVersion = None
def _deserialize(self, params):
self.CheckItemId = params.get("CheckItemId")
self.Name = params.get("Name")
self.ItemDetail = params.get("ItemDetail")
self.RiskLevel = params.get("RiskLevel")
self.RiskTarget = params.get("RiskTarget")
self.RiskType = params.get("RiskType")
self.RiskAttribute = params.get("RiskAttribute")
self.RiskProperty = params.get("RiskProperty")
self.CVENumber = params.get("CVENumber")
self.DiscoverTime = params.get("DiscoverTime")
self.Solution = params.get("Solution")
self.CVSS = params.get("CVSS")
self.CVSSScore = params.get("CVSSScore")
self.RelateLink = params.get("RelateLink")
self.AffectedType = params.get("AffectedType")
self.AffectedVersion = params.get("AffectedVersion")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ClusterCheckTaskItem(AbstractModel):
"""集群检查任务入参
"""
def __init__(self):
r"""
:param ClusterId: 指定要扫描的集群ID
:type ClusterId: str
:param ClusterRegion: 集群所属地域
:type ClusterRegion: str
:param NodeIp: 指定要扫描的节点IP
:type NodeIp: str
:param WorkloadName: 按照要扫描的workload名字
:type WorkloadName: str
"""
self.ClusterId = None
self.ClusterRegion = None
self.NodeIp = None
self.WorkloadName = None
def _deserialize(self, params):
self.ClusterId = params.get("ClusterId")
self.ClusterRegion = params.get("ClusterRegion")
self.NodeIp = params.get("NodeIp")
self.WorkloadName = params.get("WorkloadName")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ClusterCreateComponentItem(AbstractModel):
"""CreateCheckComponent的入口参数,用于批量安装防御容器
"""
def __init__(self):
r"""
:param ClusterId: 要安装组件的集群ID。
:type ClusterId: str
:param ClusterRegion: 该集群对应的地域
:type ClusterRegion: str
"""
self.ClusterId = None
self.ClusterRegion = None
def _deserialize(self, params):
self.ClusterId = params.get("ClusterId")
self.ClusterRegion = params.get("ClusterRegion")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ClusterInfoItem(AbstractModel):
"""集群资产返回的结构体
"""
def __init__(self):
r"""
:param ClusterId: 集群id
:type ClusterId: str
:param ClusterName: 集群名字
:type ClusterName: str
:param ClusterVersion: 集群版本
:type ClusterVersion: str
:param ClusterOs: 集群操作系统
:type ClusterOs: str
:param ClusterType: 集群类型
:type ClusterType: str
:param ClusterNodeNum: 集群节点数
:type ClusterNodeNum: int
:param Region: 集群区域
:type Region: str
:param DefenderStatus: 监控组件的状态,为Defender_Uninstall、Defender_Normal、Defender_Error、Defender_Installing
:type DefenderStatus: str
:param ClusterStatus: 集群状态
:type ClusterStatus: str
:param ClusterCheckMode: 集群的检测模式,为Cluster_Normal或者Cluster_Actived.
:type ClusterCheckMode: str
:param ClusterAutoCheck: 是否自动定期检测
:type ClusterAutoCheck: bool
:param DefenderErrorReason: 防护容器部署失败原因,为UserDaemonSetNotReady时,和UnreadyNodeNum转成"N个节点防御容器为就绪",其他错误直接展示
:type DefenderErrorReason: str
:param UnreadyNodeNum: 防御容器没有ready状态的节点数量
:type UnreadyNodeNum: int
:param SeriousRiskCount: 严重风险检查项的数量
:type SeriousRiskCount: int
:param HighRiskCount: 高风险检查项的数量
:type HighRiskCount: int
:param MiddleRiskCount: 中风险检查项的数量
:type MiddleRiskCount: int
:param HintRiskCount: 提示风险检查项的数量
:type HintRiskCount: int
:param CheckFailReason: 检查失败原因
:type CheckFailReason: str
:param CheckStatus: 检查状态,为Task_Running, NoRisk, HasRisk, Uncheck, Task_Error
:type CheckStatus: str
:param TaskCreateTime: 任务创建时间,检查时间
:type TaskCreateTime: str
"""
self.ClusterId = None
self.ClusterName = None
self.ClusterVersion = None
self.ClusterOs = None
self.ClusterType = None
self.ClusterNodeNum = None
self.Region = None
self.DefenderStatus = None
self.ClusterStatus = None
self.ClusterCheckMode = None
self.ClusterAutoCheck = None
self.DefenderErrorReason = None
self.UnreadyNodeNum = None
self.SeriousRiskCount = None
self.HighRiskCount = None
self.MiddleRiskCount = None
self.HintRiskCount = None
self.CheckFailReason = None
self.CheckStatus = None
self.TaskCreateTime = None
def _deserialize(self, params):
self.ClusterId = params.get("ClusterId")
self.ClusterName = params.get("ClusterName")
self.ClusterVersion = params.get("ClusterVersion")
self.ClusterOs = params.get("ClusterOs")
self.ClusterType = params.get("ClusterType")
self.ClusterNodeNum = params.get("ClusterNodeNum")
self.Region = params.get("Region")
self.DefenderStatus = params.get("DefenderStatus")
self.ClusterStatus = params.get("ClusterStatus")
self.ClusterCheckMode = params.get("ClusterCheckMode")
self.ClusterAutoCheck = params.get("ClusterAutoCheck")
self.DefenderErrorReason = params.get("DefenderErrorReason")
self.UnreadyNodeNum = params.get("UnreadyNodeNum")
self.SeriousRiskCount = params.get("SeriousRiskCount")
self.HighRiskCount = params.get("HighRiskCount")
self.MiddleRiskCount = params.get("MiddleRiskCount")
self.HintRiskCount = params.get("HintRiskCount")
self.CheckFailReason = params.get("CheckFailReason")
self.CheckStatus = params.get("CheckStatus")
self.TaskCreateTime = params.get("TaskCreateTime")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ClusterRiskItem(AbstractModel):
"""风险项是检查完之后,有问题的检测项,并且加了一些检查结果信息。
"""
def __init__(self):
r"""
:param CheckItem: 检测项相关信息
:type CheckItem: :class:`tencentcloud.tcss.v20201101.models.ClusterCheckItem`
:param VerifyInfo: 验证信息
:type VerifyInfo: str
:param ErrorMessage: 事件描述,检查的错误信息
:type ErrorMessage: str
:param AffectedClusterCount: 受影响的集群数量
:type AffectedClusterCount: int
:param AffectedNodeCount: 受影响的节点数量
:type AffectedNodeCount: int
"""
self.CheckItem = None
self.VerifyInfo = None
self.ErrorMessage = None
self.AffectedClusterCount = None
self.AffectedNodeCount = None
def _deserialize(self, params):
if params.get("CheckItem") is not None:
self.CheckItem = ClusterCheckItem()
self.CheckItem._deserialize(params.get("CheckItem"))
self.VerifyInfo = params.get("VerifyInfo")
self.ErrorMessage = params.get("ErrorMessage")
self.AffectedClusterCount = params.get("AffectedClusterCount")
self.AffectedNodeCount = params.get("AffectedNodeCount")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ComplianceAffectedAsset(AbstractModel):
"""表示检测项所影响的资产的信息。
"""
def __init__(self):
r"""
:param CustomerAssetId: 为客户分配的唯一的资产项的ID。
:type CustomerAssetId: int
:param AssetName: 资产项的名称。
:type AssetName: str
:param AssetType: 资产项的类型
:type AssetType: str
:param CheckStatus: 检测状态
CHECK_INIT, 待检测
CHECK_RUNNING, 检测中
CHECK_FINISHED, 检测完成
CHECK_FAILED, 检测失败
:type CheckStatus: str
:param NodeName: 节点名称。
:type NodeName: str
:param LastCheckTime: 上次检测的时间,格式为”YYYY-MM-DD HH:m::SS“。
如果没有检测过,此处为”0000-00-00 00:00:00“。
:type LastCheckTime: str
:param CheckResult: 检测结果。取值为:
RESULT_FAILED: 未通过
RESULT_PASSED: 通过
:type CheckResult: str
:param HostIP: 主机IP
注意:此字段可能返回 null,表示取不到有效值。
:type HostIP: str
:param ImageTag: 镜像的tag
注意:此字段可能返回 null,表示取不到有效值。
:type ImageTag: str
"""
self.CustomerAssetId = None
self.AssetName = None
self.AssetType = None
self.CheckStatus = None
self.NodeName = None
self.LastCheckTime = None
self.CheckResult = None
self.HostIP = None
self.ImageTag = None
def _deserialize(self, params):
self.CustomerAssetId = params.get("CustomerAssetId")
self.AssetName = params.get("AssetName")
self.AssetType = params.get("AssetType")
self.CheckStatus = params.get("CheckStatus")
self.NodeName = params.get("NodeName")
self.LastCheckTime = params.get("LastCheckTime")
self.CheckResult = params.get("CheckResult")
self.HostIP = params.get("HostIP")
self.ImageTag = params.get("ImageTag")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ComplianceAssetDetailInfo(AbstractModel):
"""表示一项资产的详情。
"""
def __init__(self):
r"""
:param CustomerAssetId: 客户资产的ID。
:type CustomerAssetId: int
:param AssetType: 资产类别。
:type AssetType: str
:param AssetName: 资产的名称。
:type AssetName: str
:param NodeName: 资产所属的节点的名称。
:type NodeName: str
:param HostName: 资产所在的主机的名称。
:type HostName: str
:param HostIP: 资产所在的主机的IP。
:type HostIP: str
:param CheckStatus: 检测状态
CHECK_INIT, 待检测
CHECK_RUNNING, 检测中
CHECK_FINISHED, 检测完成
CHECK_FAILED, 检测失败
:type CheckStatus: str
:param PassedPolicyItemCount: 此类资产通过的检测项的数目。
:type PassedPolicyItemCount: int
:param FailedPolicyItemCount: 此类资产未通过的检测的数目。
:type FailedPolicyItemCount: int
:param LastCheckTime: 上次检测的时间。
注意:此字段可能返回 null,表示取不到有效值。
:type LastCheckTime: str
:param CheckResult: 检测结果:
RESULT_FAILED: 未通过。
RESULT_PASSED: 通过。
注意:此字段可能返回 null,表示取不到有效值。
:type CheckResult: str
:param AssetStatus: 资产的运行状态。
:type AssetStatus: str
:param AssetCreateTime: 创建资产的时间。
ASSET_NORMAL: 正常运行,
ASSET_PAUSED: 暂停运行,
ASSET_STOPPED: 停止运行,
ASSET_ABNORMAL: 异常
:type AssetCreateTime: str
"""
self.CustomerAssetId = None
self.AssetType = None
self.AssetName = None
self.NodeName = None
self.HostName = None
self.HostIP = None
self.CheckStatus = None
self.PassedPolicyItemCount = None
self.FailedPolicyItemCount = None
self.LastCheckTime = None
self.CheckResult = None
self.AssetStatus = None
self.AssetCreateTime = None
def _deserialize(self, params):
self.CustomerAssetId = params.get("CustomerAssetId")
self.AssetType = params.get("AssetType")
self.AssetName = params.get("AssetName")
self.NodeName = params.get("NodeName")
self.HostName = params.get("HostName")
self.HostIP = params.get("HostIP")
self.CheckStatus = params.get("CheckStatus")
self.PassedPolicyItemCount = params.get("PassedPolicyItemCount")
self.FailedPolicyItemCount = params.get("FailedPolicyItemCount")
self.LastCheckTime = params.get("LastCheckTime")
self.CheckResult = params.get("CheckResult")
self.AssetStatus = params.get("AssetStatus")
self.AssetCreateTime = params.get("AssetCreateTime")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ComplianceAssetInfo(AbstractModel):
"""表示一项资产的信息。
"""
def __init__(self):
r"""
:param CustomerAssetId: 客户资产的ID。
:type CustomerAssetId: int
:param AssetType: 资产类别。
:type AssetType: str
:param AssetName: 资产的名称。
:type AssetName: str
:param ImageTag: 当资产为镜像时,这个字段为镜像Tag。
注意:此字段可能返回 null,表示取不到有效值。
:type ImageTag: str
:param HostIP: 资产所在的主机IP。
:type HostIP: str
:param NodeName: 资产所属的节点的名称
:type NodeName: str
:param CheckStatus: 检测状态
CHECK_INIT, 待检测
CHECK_RUNNING, 检测中
CHECK_FINISHED, 检测完成
CHECK_FAILED, 检测失败
:type CheckStatus: str
:param PassedPolicyItemCount: 此类资产通过的检测项的数目。
注意:此字段可能返回 null,表示取不到有效值。
:type PassedPolicyItemCount: int
:param FailedPolicyItemCount: 此类资产未通过的检测的数目。
注意:此字段可能返回 null,表示取不到有效值。
:type FailedPolicyItemCount: int
:param LastCheckTime: 上次检测的时间。
注意:此字段可能返回 null,表示取不到有效值。
:type LastCheckTime: str
:param CheckResult: 检测结果:
RESULT_FAILED: 未通过。
RESULT_PASSED: 通过。
注意:此字段可能返回 null,表示取不到有效值。
:type CheckResult: str
"""
self.CustomerAssetId = None
self.AssetType = None
self.AssetName = None
self.ImageTag = None
self.HostIP = None
self.NodeName = None
self.CheckStatus = None
self.PassedPolicyItemCount = None
self.FailedPolicyItemCount = None
self.LastCheckTime = None
self.CheckResult = None
def _deserialize(self, params):
self.CustomerAssetId = params.get("CustomerAssetId")
self.AssetType = params.get("AssetType")
self.AssetName = params.get("AssetName")
self.ImageTag = params.get("ImageTag")
self.HostIP = params.get("HostIP")
self.NodeName = params.get("NodeName")
self.CheckStatus = params.get("CheckStatus")
self.PassedPolicyItemCount = params.get("PassedPolicyItemCount")
self.FailedPolicyItemCount = params.get("FailedPolicyItemCount")
self.LastCheckTime = params.get("LastCheckTime")
self.CheckResult = params.get("CheckResult")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ComplianceAssetPolicyItem(AbstractModel):
"""表示一条检测项的信息。
"""
def __init__(self):
r"""
:param CustomerPolicyItemId: 为客户分配的唯一的检测项的ID。
:type CustomerPolicyItemId: int
:param BasePolicyItemId: 检测项的原始ID
:type BasePolicyItemId: int
:param Name: 检测项的名称。
:type Name: str
:param Category: 检测项所属的类型的名称
:type Category: str
:param BenchmarkStandardId: 所属的合规标准的ID
:type BenchmarkStandardId: int
:param BenchmarkStandardName: 所属的合规标准的名称
:type BenchmarkStandardName: str
:param RiskLevel: 威胁等级
:type RiskLevel: str
:param CheckStatus: 检测状态
CHECK_INIT, 待检测
CHECK_RUNNING, 检测中
CHECK_FINISHED, 检测完成
CHECK_FAILED, 检测失败
:type CheckStatus: str
:param CheckResult: 检测结果
RESULT_PASSED: 通过
RESULT_FAILED: 未通过
注意:此字段可能返回 null,表示取不到有效值。
:type CheckResult: str
:param WhitelistId: 检测项对应的白名单项的ID。如果存在且非0,表示检测项被用户忽略。
注意:此字段可能返回 null,表示取不到有效值。
:type WhitelistId: int
:param FixSuggestion: 处理建议。
:type FixSuggestion: str
:param LastCheckTime: 最近检测的时间。
注意:此字段可能返回 null,表示取不到有效值。
:type LastCheckTime: str
"""
self.CustomerPolicyItemId = None
self.BasePolicyItemId = None
self.Name = None
self.Category = None
self.BenchmarkStandardId = None
self.BenchmarkStandardName = None
self.RiskLevel = None
self.CheckStatus = None
self.CheckResult = None
self.WhitelistId = None
self.FixSuggestion = None
self.LastCheckTime = None
def _deserialize(self, params):
self.CustomerPolicyItemId = params.get("CustomerPolicyItemId")
self.BasePolicyItemId = params.get("BasePolicyItemId")
self.Name = params.get("Name")
self.Category = params.get("Category")
self.BenchmarkStandardId = params.get("BenchmarkStandardId")
self.BenchmarkStandardName = params.get("BenchmarkStandardName")
self.RiskLevel = params.get("RiskLevel")
self.CheckStatus = params.get("CheckStatus")
self.CheckResult = params.get("CheckResult")
self.WhitelistId = params.get("WhitelistId")
self.FixSuggestion = params.get("FixSuggestion")
self.LastCheckTime = params.get("LastCheckTime")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ComplianceAssetSummary(AbstractModel):
"""表示一类资产的总览信息。
"""
def __init__(self):
r"""
:param AssetType: 资产类别。
:type AssetType: str
:param IsCustomerFirstCheck: 是否为客户的首次检测。与CheckStatus配合使用。
:type IsCustomerFirstCheck: bool
:param CheckStatus: 检测状态
CHECK_UNINIT, 用户未启用此功能
CHECK_INIT, 待检测
CHECK_RUNNING, 检测中
CHECK_FINISHED, 检测完成
CHECK_FAILED, 检测失败
:type CheckStatus: str
:param CheckProgress: 此类别的检测进度,为 0~100 的数。若未在检测中,无此字段。
注意:此字段可能返回 null,表示取不到有效值。
:type CheckProgress: float
:param PassedPolicyItemCount: 此类资产通过的检测项的数目。
:type PassedPolicyItemCount: int
:param FailedPolicyItemCount: 此类资产未通过的检测的数目。
:type FailedPolicyItemCount: int
:param FailedCriticalPolicyItemCount: 此类资产下未通过的严重级别的检测项的数目。
:type FailedCriticalPolicyItemCount: int
:param FailedHighRiskPolicyItemCount: 此类资产下未通过的高危检测项的数目。
:type FailedHighRiskPolicyItemCount: int
:param FailedMediumRiskPolicyItemCount: 此类资产下未通过的中危检测项的数目。
:type FailedMediumRiskPolicyItemCount: int
:param FailedLowRiskPolicyItemCount: 此类资产下未通过的低危检测项的数目。
:type FailedLowRiskPolicyItemCount: int
:param NoticePolicyItemCount: 此类资产下提示级别的检测项的数目。
:type NoticePolicyItemCount: int
:param PassedAssetCount: 通过检测的资产的数目。
:type PassedAssetCount: int
:param FailedAssetCount: 未通过检测的资产的数目。
:type FailedAssetCount: int
:param AssetPassedRate: 此类资产的合规率,0~100的数。
:type AssetPassedRate: float
:param ScanFailedAssetCount: 检测失败的资产的数目。
:type ScanFailedAssetCount: int
:param CheckCostTime: 上次检测的耗时,单位为秒。
注意:此字段可能返回 null,表示取不到有效值。
:type CheckCostTime: float
:param LastCheckTime: 上次检测的时间。
注意:此字段可能返回 null,表示取不到有效值。
:type LastCheckTime: str
:param PeriodRule: 定时检测规则。
:type PeriodRule: :class:`tencentcloud.tcss.v20201101.models.CompliancePeriodTaskRule`
"""
self.AssetType = None
self.IsCustomerFirstCheck = None
self.CheckStatus = None
self.CheckProgress = None
self.PassedPolicyItemCount = None
self.FailedPolicyItemCount = None
self.FailedCriticalPolicyItemCount = None
self.FailedHighRiskPolicyItemCount = None
self.FailedMediumRiskPolicyItemCount = None
self.FailedLowRiskPolicyItemCount = None
self.NoticePolicyItemCount = None
self.PassedAssetCount = None
self.FailedAssetCount = None
self.AssetPassedRate = None
self.ScanFailedAssetCount = None
self.CheckCostTime = None
self.LastCheckTime = None
self.PeriodRule = None
def _deserialize(self, params):
self.AssetType = params.get("AssetType")
self.IsCustomerFirstCheck = params.get("IsCustomerFirstCheck")
self.CheckStatus = params.get("CheckStatus")
self.CheckProgress = params.get("CheckProgress")
self.PassedPolicyItemCount = params.get("PassedPolicyItemCount")
self.FailedPolicyItemCount = params.get("FailedPolicyItemCount")
self.FailedCriticalPolicyItemCount = params.get("FailedCriticalPolicyItemCount")
self.FailedHighRiskPolicyItemCount = params.get("FailedHighRiskPolicyItemCount")
self.FailedMediumRiskPolicyItemCount = params.get("FailedMediumRiskPolicyItemCount")
self.FailedLowRiskPolicyItemCount = params.get("FailedLowRiskPolicyItemCount")
self.NoticePolicyItemCount = params.get("NoticePolicyItemCount")
self.PassedAssetCount = params.get("PassedAssetCount")
self.FailedAssetCount = params.get("FailedAssetCount")
self.AssetPassedRate = params.get("AssetPassedRate")
self.ScanFailedAssetCount = params.get("ScanFailedAssetCount")
self.CheckCostTime = params.get("CheckCostTime")
self.LastCheckTime = params.get("LastCheckTime")
if params.get("PeriodRule") is not None:
self.PeriodRule = CompliancePeriodTaskRule()
self.PeriodRule._deserialize(params.get("PeriodRule"))
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ComplianceBenchmarkStandard(AbstractModel):
"""表示一个合规标准的信息。
"""
def __init__(self):
r"""
:param StandardId: 合规标准的ID
:type StandardId: int
:param Name: 合规标准的名称
:type Name: str
:param PolicyItemCount: 合规标准包含的数目
:type PolicyItemCount: int
:param Enabled: 是否启用此标准
:type Enabled: bool
:param Description: 标准的描述
:type Description: str
"""
self.StandardId = None
self.Name = None
self.PolicyItemCount = None
self.Enabled = None
self.Description = None
def _deserialize(self, params):
self.StandardId = params.get("StandardId")
self.Name = params.get("Name")
self.PolicyItemCount = params.get("PolicyItemCount")
self.Enabled = params.get("Enabled")
self.Description = params.get("Description")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ComplianceBenchmarkStandardEnable(AbstractModel):
"""表示是否启用合规标准。
"""
def __init__(self):
r"""
:param StandardId: 合规标准的ID。
:type StandardId: int
:param Enable: 是否启用合规标准
:type Enable: bool
"""
self.StandardId = None
self.Enable = None
def _deserialize(self, params):
self.StandardId = params.get("StandardId")
self.Enable = params.get("Enable")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ComplianceContainerDetailInfo(AbstractModel):
"""表示容器资产专属的详情。
"""
def __init__(self):
r"""
:param ContainerId: 容器在主机上的ID。
:type ContainerId: str
:param PodName: 容器所属的Pod的名称。
注意:此字段可能返回 null,表示取不到有效值。
:type PodName: str
"""
self.ContainerId = None
self.PodName = None
def _deserialize(self, params):
self.ContainerId = params.get("ContainerId")
self.PodName = params.get("PodName")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ComplianceFilters(AbstractModel):
"""键值对过滤器,用于条件过滤查询。例如过滤ID、名称、状态等 若存在多个Filter时,Filter间的关系为逻辑与(AND)关系。 若同一个Filter存在多个Values,同一Filter下Values间的关系为逻辑或(OR)关系。
"""
def __init__(self):
r"""
:param Name: 过滤键的名称
:type Name: str
:param Values: 一个或者多个过滤值。
:type Values: list of str
:param ExactMatch: 是否模糊查询。默认为是。
:type ExactMatch: bool
"""
self.Name = None
self.Values = None
self.ExactMatch = None
def _deserialize(self, params):
self.Name = params.get("Name")
self.Values = params.get("Values")
self.ExactMatch = params.get("ExactMatch")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ComplianceHostDetailInfo(AbstractModel):
"""表示主机资产专属的详情。
"""
def __init__(self):
r"""
:param DockerVersion: 主机上的Docker版本。
注意:此字段可能返回 null,表示取不到有效值。
:type DockerVersion: str
:param K8SVersion: 主机上的K8S的版本。
注意:此字段可能返回 null,表示取不到有效值。
:type K8SVersion: str
"""
self.DockerVersion = None
self.K8SVersion = None
def _deserialize(self, params):
self.DockerVersion = params.get("DockerVersion")
self.K8SVersion = params.get("K8SVersion")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ComplianceImageDetailInfo(AbstractModel):
"""表示镜像资产专属的详情。
"""
def __init__(self):
r"""
:param ImageId: 镜像在主机上的ID。
:type ImageId: str
:param ImageName: 镜像的名称。
:type ImageName: str
:param ImageTag: 镜像的Tag。
:type ImageTag: str
:param Repository: 镜像所在远程仓库的路径。
注意:此字段可能返回 null,表示取不到有效值。
:type Repository: str
"""
self.ImageId = None
self.ImageName = None
self.ImageTag = None
self.Repository = None
def _deserialize(self, params):
self.ImageId = params.get("ImageId")
self.ImageName = params.get("ImageName")
self.ImageTag = params.get("ImageTag")
self.Repository = params.get("Repository")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ComplianceK8SDetailInfo(AbstractModel):
"""表示K8S资产专属的详情。
"""
def __init__(self):
r"""
:param ClusterName: K8S集群的名称。
注意:此字段可能返回 null,表示取不到有效值。
:type ClusterName: str
:param ClusterVersion: K8S集群的版本。
注意:此字段可能返回 null,表示取不到有效值。
:type ClusterVersion: str
"""
self.ClusterName = None
self.ClusterVersion = None
def _deserialize(self, params):
self.ClusterName = params.get("ClusterName")
self.ClusterVersion = params.get("ClusterVersion")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class CompliancePeriodTask(AbstractModel):
"""表示一个合规基线检测定时任务的信息。
"""
def __init__(self):
r"""
:param PeriodTaskId: 周期任务的ID
:type PeriodTaskId: int
:param AssetType: 资产类型。
ASSET_CONTAINER, 容器
ASSET_IMAGE, 镜像
ASSET_HOST, 主机
ASSET_K8S, K8S资产
:type AssetType: str
:param LastTriggerTime: 最近一次触发的时间
注意:此字段可能返回 null,表示取不到有效值。
:type LastTriggerTime: str
:param TotalPolicyItemCount: 总的检查项数目
:type TotalPolicyItemCount: int
:param PeriodRule: 周期设置
:type PeriodRule: :class:`tencentcloud.tcss.v20201101.models.CompliancePeriodTaskRule`
:param BenchmarkStandardSet: 合规标准列表
:type BenchmarkStandardSet: list of ComplianceBenchmarkStandard
"""
self.PeriodTaskId = None
self.AssetType = None
self.LastTriggerTime = None
self.TotalPolicyItemCount = None
self.PeriodRule = None
self.BenchmarkStandardSet = None
def _deserialize(self, params):
self.PeriodTaskId = params.get("PeriodTaskId")
self.AssetType = params.get("AssetType")
self.LastTriggerTime = params.get("LastTriggerTime")
self.TotalPolicyItemCount = params.get("TotalPolicyItemCount")
if params.get("PeriodRule") is not None:
self.PeriodRule = CompliancePeriodTaskRule()
self.PeriodRule._deserialize(params.get("PeriodRule"))
if params.get("BenchmarkStandardSet") is not None:
self.BenchmarkStandardSet = []
for item in params.get("BenchmarkStandardSet"):
obj = ComplianceBenchmarkStandard()
obj._deserialize(item)
self.BenchmarkStandardSet.append(obj)
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class CompliancePeriodTaskRule(AbstractModel):
"""表示一个定时任务的周期设置
"""
def __init__(self):
r"""
:param Frequency: 执行的频率(几天一次),取值为:1,3,7。
:type Frequency: int
:param ExecutionTime: 在这天的什么时间执行,格式为:HH:mm:SS。
:type ExecutionTime: str
"""
self.Frequency = None
self.ExecutionTime = None
def _deserialize(self, params):
self.Frequency = params.get("Frequency")
self.ExecutionTime = params.get("ExecutionTime")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class CompliancePolicyItemSummary(AbstractModel):
"""表示一条检测项对应的汇总信息。
"""
def __init__(self):
r"""
:param CustomerPolicyItemId: 为客户分配的唯一的检测项的ID。
:type CustomerPolicyItemId: int
:param BasePolicyItemId: 检测项的原始ID。
:type BasePolicyItemId: int
:param Name: 检测项的名称。
:type Name: str
:param Category: 检测项所属的类型,枚举字符串。
:type Category: str
:param BenchmarkStandardName: 所属的合规标准
:type BenchmarkStandardName: str
:param RiskLevel: 威胁等级。RISK_CRITICAL, RISK_HIGH, RISK_MEDIUM, RISK_LOW, RISK_NOTICE。
:type RiskLevel: str
:param AssetType: 检测项所属的资产类型
:type AssetType: str
:param LastCheckTime: 最近检测的时间
注意:此字段可能返回 null,表示取不到有效值。
:type LastCheckTime: str
:param CheckStatus: 检测状态
CHECK_INIT, 待检测
CHECK_RUNNING, 检测中
CHECK_FINISHED, 检测完成
CHECK_FAILED, 检测失败
:type CheckStatus: str
:param CheckResult: 检测结果。RESULT_PASSED: 通过
RESULT_FAILED: 未通过
注意:此字段可能返回 null,表示取不到有效值。
:type CheckResult: str
:param PassedAssetCount: 通过检测的资产的数目
注意:此字段可能返回 null,表示取不到有效值。
:type PassedAssetCount: int
:param FailedAssetCount: 未通过检测的资产的数目
注意:此字段可能返回 null,表示取不到有效值。
:type FailedAssetCount: int
:param WhitelistId: 检测项对应的白名单项的ID。如果存在且非0,表示检测项被用户忽略。
注意:此字段可能返回 null,表示取不到有效值。
:type WhitelistId: int
:param FixSuggestion: 处理建议。
:type FixSuggestion: str
:param BenchmarkStandardId: 所属的合规标准的ID
:type BenchmarkStandardId: int
"""
self.CustomerPolicyItemId = None
self.BasePolicyItemId = None
self.Name = None
self.Category = None
self.BenchmarkStandardName = None
self.RiskLevel = None
self.AssetType = None
self.LastCheckTime = None
self.CheckStatus = None
self.CheckResult = None
self.PassedAssetCount = None
self.FailedAssetCount = None
self.WhitelistId = None
self.FixSuggestion = None
self.BenchmarkStandardId = None
def _deserialize(self, params):
self.CustomerPolicyItemId = params.get("CustomerPolicyItemId")
self.BasePolicyItemId = params.get("BasePolicyItemId")
self.Name = params.get("Name")
self.Category = params.get("Category")
self.BenchmarkStandardName = params.get("BenchmarkStandardName")
self.RiskLevel = params.get("RiskLevel")
self.AssetType = params.get("AssetType")
self.LastCheckTime = params.get("LastCheckTime")
self.CheckStatus = params.get("CheckStatus")
self.CheckResult = params.get("CheckResult")
self.PassedAssetCount = params.get("PassedAssetCount")
self.FailedAssetCount = params.get("FailedAssetCount")
self.WhitelistId = params.get("WhitelistId")
self.FixSuggestion = params.get("FixSuggestion")
self.BenchmarkStandardId = params.get("BenchmarkStandardId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ComplianceScanFailedAsset(AbstractModel):
"""表示检测失败的资产的信息。
"""
def __init__(self):
r"""
:param CustomerAssetId: 客户资产的ID。
:type CustomerAssetId: int
:param AssetType: 资产类别。
:type AssetType: str
:param CheckStatus: 检测状态
CHECK_INIT, 待检测
CHECK_RUNNING, 检测中
CHECK_FINISHED, 检测完成
CHECK_FAILED, 检测失败
:type CheckStatus: str
:param AssetName: 资产的名称。
:type AssetName: str
:param FailureReason: 资产检测失败的原因。
:type FailureReason: str
:param Suggestion: 检测失败的处理建议。
:type Suggestion: str
:param CheckTime: 检测的时间。
:type CheckTime: str
"""
self.CustomerAssetId = None
self.AssetType = None
self.CheckStatus = None
self.AssetName = None
self.FailureReason = None
self.Suggestion = None
self.CheckTime = None
def _deserialize(self, params):
self.CustomerAssetId = params.get("CustomerAssetId")
self.AssetType = params.get("AssetType")
self.CheckStatus = params.get("CheckStatus")
self.AssetName = params.get("AssetName")
self.FailureReason = params.get("FailureReason")
self.Suggestion = params.get("Suggestion")
self.CheckTime = params.get("CheckTime")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ComplianceWhitelistItem(AbstractModel):
"""表示一条白名单记录。
"""
def __init__(self):
r"""
:param WhitelistItemId: 白名单项的ID。
:type WhitelistItemId: int
:param CustomerPolicyItemId: 客户检测项的ID。
:type CustomerPolicyItemId: int
:param Name: 检测项的名称。
:type Name: str
:param StandardName: 合规标准的名称。
:type StandardName: str
:param StandardId: 合规标准的ID。
:type StandardId: int
:param AffectedAssetCount: 检测项影响的资产的数目。
:type AffectedAssetCount: int
:param LastUpdateTime: 最后更新的时间
:type LastUpdateTime: str
:param InsertTime: 加入到白名单的时间
:type InsertTime: str
"""
self.WhitelistItemId = None
self.CustomerPolicyItemId = None
self.Name = None
self.StandardName = None
self.StandardId = None
self.AffectedAssetCount = None
self.LastUpdateTime = None
self.InsertTime = None
def _deserialize(self, params):
self.WhitelistItemId = params.get("WhitelistItemId")
self.CustomerPolicyItemId = params.get("CustomerPolicyItemId")
self.Name = params.get("Name")
self.StandardName = params.get("StandardName")
self.StandardId = params.get("StandardId")
self.AffectedAssetCount = params.get("AffectedAssetCount")
self.LastUpdateTime = params.get("LastUpdateTime")
self.InsertTime = params.get("InsertTime")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ComponentInfo(AbstractModel):
"""容器组件信息
"""
def __init__(self):
r"""
:param Name: 名称
:type Name: str
:param Version: 版本
:type Version: str
"""
self.Name = None
self.Version = None
def _deserialize(self, params):
self.Name = params.get("Name")
self.Version = params.get("Version")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ComponentsInfo(AbstractModel):
"""组件信息
"""
def __init__(self):
r"""
:param Component: 组件名称
注意:此字段可能返回 null,表示取不到有效值。
:type Component: str
:param Version: 组件版本信息
注意:此字段可能返回 null,表示取不到有效值。
:type Version: str
"""
self.Component = None
self.Version = None
def _deserialize(self, params):
self.Component = params.get("Component")
self.Version = params.get("Version")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ContainerInfo(AbstractModel):
"""容器列表集合
"""
def __init__(self):
r"""
:param ContainerID: 容器id
:type ContainerID: str
:param ContainerName: 容器名称
:type ContainerName: str
:param Status: 容器运行状态
:type Status: str
:param CreateTime: 创建时间
:type CreateTime: str
:param RunAs: 运行用户
:type RunAs: str
:param Cmd: 命令行
:type Cmd: str
:param CPUUsage: CPU使用率 *1000
:type CPUUsage: int
:param RamUsage: 内存使用 kb
:type RamUsage: int
:param ImageName: 镜像名称
:type ImageName: str
:param ImageID: 镜像id
:type ImageID: str
:param POD: 镜像id
:type POD: str
:param HostID: 主机id
:type HostID: str
:param HostIP: 主机ip
:type HostIP: str
:param UpdateTime: 更新时间
:type UpdateTime: str
:param HostName: 主机名称
:type HostName: str
:param PublicIp: 外网ip
:type PublicIp: str
"""
self.ContainerID = None
self.ContainerName = None
self.Status = None
self.CreateTime = None
self.RunAs = None
self.Cmd = None
self.CPUUsage = None
self.RamUsage = None
self.ImageName = None
self.ImageID = None
self.POD = None
self.HostID = None
self.HostIP = None
self.UpdateTime = None
self.HostName = None
self.PublicIp = None
def _deserialize(self, params):
self.ContainerID = params.get("ContainerID")
self.ContainerName = params.get("ContainerName")
self.Status = params.get("Status")
self.CreateTime = params.get("CreateTime")
self.RunAs = params.get("RunAs")
self.Cmd = params.get("Cmd")
self.CPUUsage = params.get("CPUUsage")
self.RamUsage = params.get("RamUsage")
self.ImageName = params.get("ImageName")
self.ImageID = params.get("ImageID")
self.POD = params.get("POD")
self.HostID = params.get("HostID")
self.HostIP = params.get("HostIP")
self.UpdateTime = params.get("UpdateTime")
self.HostName = params.get("HostName")
self.PublicIp = params.get("PublicIp")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ContainerMount(AbstractModel):
"""容器挂载信息
"""
def __init__(self):
r"""
:param Type: 挂载类型 bind
:type Type: str
:param Source: 宿主机路径
:type Source: str
:param Destination: 容器内路径
:type Destination: str
:param Mode: 模式
:type Mode: str
:param RW: 读写权限
:type RW: bool
:param Propagation: 传播类型
:type Propagation: str
:param Name: 名称
:type Name: str
:param Driver: 驱动
:type Driver: str
"""
self.Type = None
self.Source = None
self.Destination = None
self.Mode = None
self.RW = None
self.Propagation = None
self.Name = None
self.Driver = None
def _deserialize(self, params):
self.Type = params.get("Type")
self.Source = params.get("Source")
self.Destination = params.get("Destination")
self.Mode = params.get("Mode")
self.RW = params.get("RW")
self.Propagation = params.get("Propagation")
self.Name = params.get("Name")
self.Driver = params.get("Driver")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ContainerNetwork(AbstractModel):
"""容器网络信息
"""
def __init__(self):
r"""
:param EndpointID: endpoint id
:type EndpointID: str
:param Mode: 模式:bridge
:type Mode: str
:param Name: 网络名称
:type Name: str
:param NetworkID: 网络ID
:type NetworkID: str
:param Gateway: 网关
:type Gateway: str
:param Ipv4: IPV4地址
:type Ipv4: str
:param Ipv6: IPV6地址
:type Ipv6: str
:param MAC: MAC 地址
:type MAC: str
"""
self.EndpointID = None
self.Mode = None
self.Name = None
self.NetworkID = None
self.Gateway = None
self.Ipv4 = None
self.Ipv6 = None
self.MAC = None
def _deserialize(self, params):
self.EndpointID = params.get("EndpointID")
self.Mode = params.get("Mode")
self.Name = params.get("Name")
self.NetworkID = params.get("NetworkID")
self.Gateway = params.get("Gateway")
self.Ipv4 = params.get("Ipv4")
self.Ipv6 = params.get("Ipv6")
self.MAC = params.get("MAC")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class CreateAssetImageRegistryScanTaskOneKeyRequest(AbstractModel):
"""CreateAssetImageRegistryScanTaskOneKey请求参数结构体
"""
def __init__(self):
r"""
:param All: 是否扫描全部镜像
:type All: bool
:param Images: 扫描的镜像列表
:type Images: list of ImageInfo
:param ScanType: 扫描类型数组
:type ScanType: list of str
:param Id: 扫描的镜像列表Id
:type Id: list of int non-negative
"""
self.All = None
self.Images = None
self.ScanType = None
self.Id = None
def _deserialize(self, params):
self.All = params.get("All")
if params.get("Images") is not None:
self.Images = []
for item in params.get("Images"):
obj = ImageInfo()
obj._deserialize(item)
self.Images.append(obj)
self.ScanType = params.get("ScanType")
self.Id = params.get("Id")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class CreateAssetImageRegistryScanTaskOneKeyResponse(AbstractModel):
"""CreateAssetImageRegistryScanTaskOneKey返回参数结构体
"""
def __init__(self):
r"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RequestId = None
def _deserialize(self, params):
self.RequestId = params.get("RequestId")
class CreateAssetImageRegistryScanTaskRequest(AbstractModel):
"""CreateAssetImageRegistryScanTask请求参数结构体
"""
def __init__(self):
r"""
:param All: 是否扫描全部镜像
:type All: bool
:param Images: 扫描的镜像列表
:type Images: list of ImageInfo
:param ScanType: 扫描类型数组
:type ScanType: list of str
:param Id: 扫描的镜像列表
:type Id: list of int non-negative
:param Filters: 过滤条件
:type Filters: list of AssetFilters
:param ExcludeImageList: 不需要扫描的镜像列表, 与Filters配合使用
:type ExcludeImageList: list of int non-negative
:param OnlyScanLatest: 是否仅扫描各repository最新版的镜像, 与Filters配合使用
:type OnlyScanLatest: bool
"""
self.All = None
self.Images = None
self.ScanType = None
self.Id = None
self.Filters = None
self.ExcludeImageList = None
self.OnlyScanLatest = None
def _deserialize(self, params):
self.All = params.get("All")
if params.get("Images") is not None:
self.Images = []
for item in params.get("Images"):
obj = ImageInfo()
obj._deserialize(item)
self.Images.append(obj)
self.ScanType = params.get("ScanType")
self.Id = params.get("Id")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = AssetFilters()
obj._deserialize(item)
self.Filters.append(obj)
self.ExcludeImageList = params.get("ExcludeImageList")
self.OnlyScanLatest = params.get("OnlyScanLatest")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class CreateAssetImageRegistryScanTaskResponse(AbstractModel):
"""CreateAssetImageRegistryScanTask返回参数结构体
"""
def __init__(self):
r"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RequestId = None
def _deserialize(self, params):
self.RequestId = params.get("RequestId")
class CreateAssetImageScanSettingRequest(AbstractModel):
"""CreateAssetImageScanSetting请求参数结构体
"""
def __init__(self):
r"""
:param Enable: 开关
:type Enable: bool
:param ScanTime: 扫描时间
:type ScanTime: str
:param ScanPeriod: 扫描周期
:type ScanPeriod: int
:param ScanVirus: 扫描木马
:type ScanVirus: bool
:param ScanRisk: 扫描敏感信息
:type ScanRisk: bool
:param ScanVul: 扫描漏洞
:type ScanVul: bool
:param All: 全部镜像
:type All: bool
:param Images: 自定义镜像
:type Images: list of str
"""
self.Enable = None
self.ScanTime = None
self.ScanPeriod = None
self.ScanVirus = None
self.ScanRisk = None
self.ScanVul = None
self.All = None
self.Images = None
def _deserialize(self, params):
self.Enable = params.get("Enable")
self.ScanTime = params.get("ScanTime")
self.ScanPeriod = params.get("ScanPeriod")
self.ScanVirus = params.get("ScanVirus")
self.ScanRisk = params.get("ScanRisk")
self.ScanVul = params.get("ScanVul")
self.All = params.get("All")
self.Images = params.get("Images")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class CreateAssetImageScanSettingResponse(AbstractModel):
"""CreateAssetImageScanSetting返回参数结构体
"""
def __init__(self):
r"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RequestId = None
def _deserialize(self, params):
self.RequestId = params.get("RequestId")
class CreateAssetImageScanTaskRequest(AbstractModel):
"""CreateAssetImageScanTask请求参数结构体
"""
def __init__(self):
r"""
:param All: 是否扫描全部镜像;全部镜像,镜像列表和根据过滤条件筛选三选一。
:type All: bool
:param Images: 需要扫描的镜像列表;全部镜像,镜像列表和根据过滤条件筛选三选一。
:type Images: list of str
:param ScanVul: 扫描漏洞;漏洞,木马和风险需选其一
:type ScanVul: bool
:param ScanVirus: 扫描木马;漏洞,木马和风险需选其一
:type ScanVirus: bool
:param ScanRisk: 扫描风险;漏洞,木马和风险需选其一
:type ScanRisk: bool
:param Filters: 根据过滤条件筛选出镜像;全部镜像,镜像列表和根据过滤条件筛选三选一。
:type Filters: list of AssetFilters
:param ExcludeImageIds: 根据过滤条件筛选出镜像,再排除个别镜像
:type ExcludeImageIds: list of str
"""
self.All = None
self.Images = None
self.ScanVul = None
self.ScanVirus = None
self.ScanRisk = None
self.Filters = None
self.ExcludeImageIds = None
def _deserialize(self, params):
self.All = params.get("All")
self.Images = params.get("Images")
self.ScanVul = params.get("ScanVul")
self.ScanVirus = params.get("ScanVirus")
self.ScanRisk = params.get("ScanRisk")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = AssetFilters()
obj._deserialize(item)
self.Filters.append(obj)
self.ExcludeImageIds = params.get("ExcludeImageIds")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class CreateAssetImageScanTaskResponse(AbstractModel):
"""CreateAssetImageScanTask返回参数结构体
"""
def __init__(self):
r"""
:param TaskID: 任务id
:type TaskID: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.TaskID = None
self.RequestId = None
def _deserialize(self, params):
self.TaskID = params.get("TaskID")
self.RequestId = params.get("RequestId")
class CreateCheckComponentRequest(AbstractModel):
"""CreateCheckComponent请求参数结构体
"""
def __init__(self):
r"""
:param ClusterInfoList: 要安装的集群列表信息
:type ClusterInfoList: list of ClusterCreateComponentItem
"""
self.ClusterInfoList = None
def _deserialize(self, params):
if params.get("ClusterInfoList") is not None:
self.ClusterInfoList = []
for item in params.get("ClusterInfoList"):
obj = ClusterCreateComponentItem()
obj._deserialize(item)
self.ClusterInfoList.append(obj)
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class CreateCheckComponentResponse(AbstractModel):
"""CreateCheckComponent返回参数结构体
"""
def __init__(self):
r"""
:param InstallResult: "InstallSucc"表示安装成功,"InstallFailed"表示安装失败
:type InstallResult: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.InstallResult = None
self.RequestId = None
def _deserialize(self, params):
self.InstallResult = params.get("InstallResult")
self.RequestId = params.get("RequestId")
class CreateClusterCheckTaskRequest(AbstractModel):
"""CreateClusterCheckTask请求参数结构体
"""
def __init__(self):
r"""
:param ClusterCheckTaskList: 指定要扫描的集群信息
:type ClusterCheckTaskList: list of ClusterCheckTaskItem
"""
self.ClusterCheckTaskList = None
def _deserialize(self, params):
if params.get("ClusterCheckTaskList") is not None:
self.ClusterCheckTaskList = []
for item in params.get("ClusterCheckTaskList"):
obj = ClusterCheckTaskItem()
obj._deserialize(item)
self.ClusterCheckTaskList.append(obj)
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class CreateClusterCheckTaskResponse(AbstractModel):
"""CreateClusterCheckTask返回参数结构体
"""
def __init__(self):
r"""
:param TaskId: 返回创建的集群检查任务的ID,为0表示创建失败。
:type TaskId: int
:param CreateResult: 创建检查任务的结果,"Succ"为成功,其他的为失败原因
:type CreateResult: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.TaskId = None
self.CreateResult = None
self.RequestId = None
def _deserialize(self, params):
self.TaskId = params.get("TaskId")
self.CreateResult = params.get("CreateResult")
self.RequestId = params.get("RequestId")
class CreateComplianceTaskRequest(AbstractModel):
"""CreateComplianceTask请求参数结构体
"""
def __init__(self):
r"""
:param AssetTypeSet: 指定要扫描的资产类型列表。
ASSET_CONTAINER, 容器
ASSET_IMAGE, 镜像
ASSET_HOST, 主机
ASSET_K8S, K8S资产
AssetTypeSet, PolicySetId, PeriodTaskId三个参数,必须要给其中一个参数填写有效的值。
:type AssetTypeSet: list of str
:param PolicySetId: 按照策略集ID指定的策略执行合规检查。
:type PolicySetId: int
:param PeriodTaskId: 按照定时任务ID指定的策略执行合规检查。
:type PeriodTaskId: int
"""
self.AssetTypeSet = None
self.PolicySetId = None
self.PeriodTaskId = None
def _deserialize(self, params):
self.AssetTypeSet = params.get("AssetTypeSet")
self.PolicySetId = params.get("PolicySetId")
self.PeriodTaskId = params.get("PeriodTaskId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class CreateComplianceTaskResponse(AbstractModel):
"""CreateComplianceTask返回参数结构体
"""
def __init__(self):
r"""
:param TaskId: 返回创建的合规检查任务的ID。
:type TaskId: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.TaskId = None
self.RequestId = None
def _deserialize(self, params):
self.TaskId = params.get("TaskId")
self.RequestId = params.get("RequestId")
class CreateExportComplianceStatusListJobRequest(AbstractModel):
"""CreateExportComplianceStatusListJob请求参数结构体
"""
def __init__(self):
r"""
:param AssetType: 要导出信息的资产类型
:type AssetType: str
:param ExportByAsset: 按照检测项导出,还是按照资产导出。true: 按照资产导出;false: 按照检测项导出。
:type ExportByAsset: bool
:param ExportAll: true, 全部导出;false, 根据IdList来导出数据。
:type ExportAll: bool
:param IdList: 要导出的资产ID列表或检测项ID列表,由ExportByAsset的取值决定。
:type IdList: list of int non-negative
"""
self.AssetType = None
self.ExportByAsset = None
self.ExportAll = None
self.IdList = None
def _deserialize(self, params):
self.AssetType = params.get("AssetType")
self.ExportByAsset = params.get("ExportByAsset")
self.ExportAll = params.get("ExportAll")
self.IdList = params.get("IdList")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class CreateExportComplianceStatusListJobResponse(AbstractModel):
"""CreateExportComplianceStatusListJob返回参数结构体
"""
def __init__(self):
r"""
:param JobId: 返回创建的导出任务的ID
注意:此字段可能返回 null,表示取不到有效值。
:type JobId: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.JobId = None
self.RequestId = None
def _deserialize(self, params):
self.JobId = params.get("JobId")
self.RequestId = params.get("RequestId")
class CreateOrModifyPostPayCoresRequest(AbstractModel):
"""CreateOrModifyPostPayCores请求参数结构体
"""
def __init__(self):
r"""
:param CoresCnt: 弹性计费上限,最小值500
:type CoresCnt: int
"""
self.CoresCnt = None
def _deserialize(self, params):
self.CoresCnt = params.get("CoresCnt")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class CreateOrModifyPostPayCoresResponse(AbstractModel):
"""CreateOrModifyPostPayCores返回参数结构体
"""
def __init__(self):
r"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RequestId = None
def _deserialize(self, params):
self.RequestId = params.get("RequestId")
class CreateRefreshTaskRequest(AbstractModel):
"""CreateRefreshTask请求参数结构体
"""
class CreateRefreshTaskResponse(AbstractModel):
"""CreateRefreshTask返回参数结构体
"""
def __init__(self):
r"""
:param TaskId: 返回创建的集群检查任务的ID,为0表示创建失败。
:type TaskId: int
:param CreateResult: 创建检查任务的结果,"Succ"为成功,"Failed"为失败
:type CreateResult: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.TaskId = None
self.CreateResult = None
self.RequestId = None
def _deserialize(self, params):
self.TaskId = params.get("TaskId")
self.CreateResult = params.get("CreateResult")
self.RequestId = params.get("RequestId")
class CreateVirusScanAgainRequest(AbstractModel):
"""CreateVirusScanAgain请求参数结构体
"""
def __init__(self):
r"""
:param TaskId: 任务id
:type TaskId: str
:param ContainerIds: 需要扫描的容器id集合
:type ContainerIds: list of str
:param TimeoutAll: 是否是扫描全部超时的
:type TimeoutAll: bool
:param Timeout: 重新设置的超时时长
:type Timeout: int
"""
self.TaskId = None
self.ContainerIds = None
self.TimeoutAll = None
self.Timeout = None
def _deserialize(self, params):
self.TaskId = params.get("TaskId")
self.ContainerIds = params.get("ContainerIds")
self.TimeoutAll = params.get("TimeoutAll")
self.Timeout = params.get("Timeout")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class CreateVirusScanAgainResponse(AbstractModel):
"""CreateVirusScanAgain返回参数结构体
"""
def __init__(self):
r"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RequestId = None
def _deserialize(self, params):
self.RequestId = params.get("RequestId")
class CreateVirusScanTaskRequest(AbstractModel):
"""CreateVirusScanTask请求参数结构体
"""
def __init__(self):
r"""
:param ScanPathAll: 是否扫描所有路径
:type ScanPathAll: bool
:param ScanRangeType: 扫描范围0容器1主机节点
:type ScanRangeType: int
:param ScanRangeAll: true 全选,false 自选
:type ScanRangeAll: bool
:param Timeout: 超时时长,单位小时
:type Timeout: int
:param ScanPathType: 当ScanPathAll为false生效 0扫描以下路径 1、扫描除以下路径
:type ScanPathType: int
:param ScanIds: 自选扫描范围的容器id或者主机id 根据ScanRangeType决定
:type ScanIds: list of str
:param ScanPath: 自选排除或扫描的地址
:type ScanPath: list of str
"""
self.ScanPathAll = None
self.ScanRangeType = None
self.ScanRangeAll = None
self.Timeout = None
self.ScanPathType = None
self.ScanIds = None
self.ScanPath = None
def _deserialize(self, params):
self.ScanPathAll = params.get("ScanPathAll")
self.ScanRangeType = params.get("ScanRangeType")
self.ScanRangeAll = params.get("ScanRangeAll")
self.Timeout = params.get("Timeout")
self.ScanPathType = params.get("ScanPathType")
self.ScanIds = params.get("ScanIds")
self.ScanPath = params.get("ScanPath")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class CreateVirusScanTaskResponse(AbstractModel):
"""CreateVirusScanTask返回参数结构体
"""
def __init__(self):
r"""
:param TaskID: 任务id
:type TaskID: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.TaskID = None
self.RequestId = None
def _deserialize(self, params):
self.TaskID = params.get("TaskID")
self.RequestId = params.get("RequestId")
class DeleteAbnormalProcessRulesRequest(AbstractModel):
"""DeleteAbnormalProcessRules请求参数结构体
"""
def __init__(self):
r"""
:param RuleIdSet: 策略的ids
:type RuleIdSet: list of str
"""
self.RuleIdSet = None
def _deserialize(self, params):
self.RuleIdSet = params.get("RuleIdSet")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DeleteAbnormalProcessRulesResponse(AbstractModel):
"""DeleteAbnormalProcessRules返回参数结构体
"""
def __init__(self):
r"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RequestId = None
def _deserialize(self, params):
self.RequestId = params.get("RequestId")
class DeleteAccessControlRulesRequest(AbstractModel):
"""DeleteAccessControlRules请求参数结构体
"""
def __init__(self):
r"""
:param RuleIdSet: 策略的ids
:type RuleIdSet: list of str
"""
self.RuleIdSet = None
def _deserialize(self, params):
self.RuleIdSet = params.get("RuleIdSet")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DeleteAccessControlRulesResponse(AbstractModel):
"""DeleteAccessControlRules返回参数结构体
"""
def __init__(self):
r"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RequestId = None
def _deserialize(self, params):
self.RequestId = params.get("RequestId")
class DeleteCompliancePolicyItemFromWhitelistRequest(AbstractModel):
"""DeleteCompliancePolicyItemFromWhitelist请求参数结构体
"""
def __init__(self):
r"""
:param WhitelistIdSet: 指定的白名单项的ID的列表
:type WhitelistIdSet: list of int non-negative
"""
self.WhitelistIdSet = None
def _deserialize(self, params):
self.WhitelistIdSet = params.get("WhitelistIdSet")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DeleteCompliancePolicyItemFromWhitelistResponse(AbstractModel):
"""DeleteCompliancePolicyItemFromWhitelist返回参数结构体
"""
def __init__(self):
r"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RequestId = None
def _deserialize(self, params):
self.RequestId = params.get("RequestId")
class DeleteReverseShellWhiteListsRequest(AbstractModel):
"""DeleteReverseShellWhiteLists请求参数结构体
"""
def __init__(self):
r"""
:param WhiteListIdSet: 白名单ids
:type WhiteListIdSet: list of str
"""
self.WhiteListIdSet = None
def _deserialize(self, params):
self.WhiteListIdSet = params.get("WhiteListIdSet")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DeleteReverseShellWhiteListsResponse(AbstractModel):
"""DeleteReverseShellWhiteLists返回参数结构体
"""
def __init__(self):
r"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RequestId = None
def _deserialize(self, params):
self.RequestId = params.get("RequestId")
class DeleteRiskSyscallWhiteListsRequest(AbstractModel):
"""DeleteRiskSyscallWhiteLists请求参数结构体
"""
def __init__(self):
r"""
:param WhiteListIdSet: 白名单ids
:type WhiteListIdSet: list of str
"""
self.WhiteListIdSet = None
def _deserialize(self, params):
self.WhiteListIdSet = params.get("WhiteListIdSet")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DeleteRiskSyscallWhiteListsResponse(AbstractModel):
"""DeleteRiskSyscallWhiteLists返回参数结构体
"""
def __init__(self):
r"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RequestId = None
def _deserialize(self, params):
self.RequestId = params.get("RequestId")
class DescribeAbnormalProcessDetailRequest(AbstractModel):
"""DescribeAbnormalProcessDetail请求参数结构体
"""
def __init__(self):
r"""
:param EventId: 事件唯一id
:type EventId: str
"""
self.EventId = None
def _deserialize(self, params):
self.EventId = params.get("EventId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeAbnormalProcessDetailResponse(AbstractModel):
"""DescribeAbnormalProcessDetail返回参数结构体
"""
def __init__(self):
r"""
:param EventBaseInfo: 事件基本信息
:type EventBaseInfo: :class:`tencentcloud.tcss.v20201101.models.RunTimeEventBaseInfo`
:param ProcessInfo: 进程信息
:type ProcessInfo: :class:`tencentcloud.tcss.v20201101.models.ProcessDetailInfo`
:param ParentProcessInfo: 父进程信息
:type ParentProcessInfo: :class:`tencentcloud.tcss.v20201101.models.ProcessDetailBaseInfo`
:param EventDetail: 事件描述
:type EventDetail: :class:`tencentcloud.tcss.v20201101.models.AbnormalProcessEventDescription`
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.EventBaseInfo = None
self.ProcessInfo = None
self.ParentProcessInfo = None
self.EventDetail = None
self.RequestId = None
def _deserialize(self, params):
if params.get("EventBaseInfo") is not None:
self.EventBaseInfo = RunTimeEventBaseInfo()
self.EventBaseInfo._deserialize(params.get("EventBaseInfo"))
if params.get("ProcessInfo") is not None:
self.ProcessInfo = ProcessDetailInfo()
self.ProcessInfo._deserialize(params.get("ProcessInfo"))
if params.get("ParentProcessInfo") is not None:
self.ParentProcessInfo = ProcessDetailBaseInfo()
self.ParentProcessInfo._deserialize(params.get("ParentProcessInfo"))
if params.get("EventDetail") is not None:
self.EventDetail = AbnormalProcessEventDescription()
self.EventDetail._deserialize(params.get("EventDetail"))
self.RequestId = params.get("RequestId")
class DescribeAbnormalProcessEventsExportRequest(AbstractModel):
"""DescribeAbnormalProcessEventsExport请求参数结构体
"""
def __init__(self):
r"""
:param ExportField: 导出字段
:type ExportField: list of str
:param Limit: 需要返回的数量,默认为10,最大值为100
:type Limit: int
:param Offset: 偏移量,默认为0。
:type Offset: int
:param Filters: 过滤参数,"Filters":[{"Name":"Status","Values":["2"]}]
:type Filters: list of RunTimeFilters
:param Order: 升序降序,asc desc
:type Order: str
:param By: 排序字段
:type By: str
"""
self.ExportField = None
self.Limit = None
self.Offset = None
self.Filters = None
self.Order = None
self.By = None
def _deserialize(self, params):
self.ExportField = params.get("ExportField")
self.Limit = params.get("Limit")
self.Offset = params.get("Offset")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = RunTimeFilters()
obj._deserialize(item)
self.Filters.append(obj)
self.Order = params.get("Order")
self.By = params.get("By")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeAbnormalProcessEventsExportResponse(AbstractModel):
"""DescribeAbnormalProcessEventsExport返回参数结构体
"""
def __init__(self):
r"""
:param DownloadUrl: execle下载地址
注意:此字段可能返回 null,表示取不到有效值。
:type DownloadUrl: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.DownloadUrl = None
self.RequestId = None
def _deserialize(self, params):
self.DownloadUrl = params.get("DownloadUrl")
self.RequestId = params.get("RequestId")
class DescribeAbnormalProcessEventsRequest(AbstractModel):
"""DescribeAbnormalProcessEvents请求参数结构体
"""
def __init__(self):
r"""
:param Limit: 需要返回的数量,默认为10,最大值为100
:type Limit: int
:param Offset: 偏移量,默认为0。
:type Offset: int
:param Filters: 过滤参数,"Filters":[{"Name":"Status","Values":["2"]}]
:type Filters: list of RunTimeFilters
:param Order: 升序降序,asc desc
:type Order: str
:param By: 排序字段
:type By: str
"""
self.Limit = None
self.Offset = None
self.Filters = None
self.Order = None
self.By = None
def _deserialize(self, params):
self.Limit = params.get("Limit")
self.Offset = params.get("Offset")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = RunTimeFilters()
obj._deserialize(item)
self.Filters.append(obj)
self.Order = params.get("Order")
self.By = params.get("By")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeAbnormalProcessEventsResponse(AbstractModel):
"""DescribeAbnormalProcessEvents返回参数结构体
"""
def __init__(self):
r"""
:param TotalCount: 事件总数量
:type TotalCount: int
:param EventSet: 异常进程数组
:type EventSet: list of AbnormalProcessEventInfo
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.TotalCount = None
self.EventSet = None
self.RequestId = None
def _deserialize(self, params):
self.TotalCount = params.get("TotalCount")
if params.get("EventSet") is not None:
self.EventSet = []
for item in params.get("EventSet"):
obj = AbnormalProcessEventInfo()
obj._deserialize(item)
self.EventSet.append(obj)
self.RequestId = params.get("RequestId")
class DescribeAbnormalProcessRuleDetailRequest(AbstractModel):
"""DescribeAbnormalProcessRuleDetail请求参数结构体
"""
def __init__(self):
r"""
:param RuleId: 策略唯一id
:type RuleId: str
:param ImageId: 镜像id, 在添加白名单的时候使用
:type ImageId: str
"""
self.RuleId = None
self.ImageId = None
def _deserialize(self, params):
self.RuleId = params.get("RuleId")
self.ImageId = params.get("ImageId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeAbnormalProcessRuleDetailResponse(AbstractModel):
"""DescribeAbnormalProcessRuleDetail返回参数结构体
"""
def __init__(self):
r"""
:param RuleDetail: 异常进程策略详细信息
:type RuleDetail: :class:`tencentcloud.tcss.v20201101.models.AbnormalProcessRuleInfo`
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RuleDetail = None
self.RequestId = None
def _deserialize(self, params):
if params.get("RuleDetail") is not None:
self.RuleDetail = AbnormalProcessRuleInfo()
self.RuleDetail._deserialize(params.get("RuleDetail"))
self.RequestId = params.get("RequestId")
class DescribeAbnormalProcessRulesExportRequest(AbstractModel):
"""DescribeAbnormalProcessRulesExport请求参数结构体
"""
def __init__(self):
r"""
:param ExportField: 导出字段
:type ExportField: list of str
:param Limit: 需要返回的数量,默认为10,最大值为100
:type Limit: int
:param Offset: 偏移量,默认为0。
:type Offset: int
:param Filters: 过滤参数,"Filters":[{"Name":"Status","Values":["2"]}]
:type Filters: list of RunTimeFilters
:param Order: 升序降序,asc desc
:type Order: str
:param By: 排序字段
:type By: str
"""
self.ExportField = None
self.Limit = None
self.Offset = None
self.Filters = None
self.Order = None
self.By = None
def _deserialize(self, params):
self.ExportField = params.get("ExportField")
self.Limit = params.get("Limit")
self.Offset = params.get("Offset")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = RunTimeFilters()
obj._deserialize(item)
self.Filters.append(obj)
self.Order = params.get("Order")
self.By = params.get("By")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeAbnormalProcessRulesExportResponse(AbstractModel):
"""DescribeAbnormalProcessRulesExport返回参数结构体
"""
def __init__(self):
r"""
:param DownloadUrl: execle下载地址
注意:此字段可能返回 null,表示取不到有效值。
:type DownloadUrl: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.DownloadUrl = None
self.RequestId = None
def _deserialize(self, params):
self.DownloadUrl = params.get("DownloadUrl")
self.RequestId = params.get("RequestId")
class DescribeAbnormalProcessRulesRequest(AbstractModel):
"""DescribeAbnormalProcessRules请求参数结构体
"""
def __init__(self):
r"""
:param Limit: 需要返回的数量,默认为10,最大值为100
:type Limit: int
:param Offset: 偏移量,默认为0。
:type Offset: int
:param Filters: 过滤参数,"Filters":[{"Name":"Status","Values":["2"]}]
:type Filters: list of RunTimeFilters
:param Order: 升序降序,asc desc
:type Order: str
:param By: 排序字段
:type By: str
"""
self.Limit = None
self.Offset = None
self.Filters = None
self.Order = None
self.By = None
def _deserialize(self, params):
self.Limit = params.get("Limit")
self.Offset = params.get("Offset")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = RunTimeFilters()
obj._deserialize(item)
self.Filters.append(obj)
self.Order = params.get("Order")
self.By = params.get("By")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeAbnormalProcessRulesResponse(AbstractModel):
"""DescribeAbnormalProcessRules返回参数结构体
"""
def __init__(self):
r"""
:param TotalCount: 事件总数量
:type TotalCount: int
:param RuleSet: 异常进程策略信息列表
:type RuleSet: list of RuleBaseInfo
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.TotalCount = None
self.RuleSet = None
self.RequestId = None
def _deserialize(self, params):
self.TotalCount = params.get("TotalCount")
if params.get("RuleSet") is not None:
self.RuleSet = []
for item in params.get("RuleSet"):
obj = RuleBaseInfo()
obj._deserialize(item)
self.RuleSet.append(obj)
self.RequestId = params.get("RequestId")
class DescribeAccessControlDetailRequest(AbstractModel):
"""DescribeAccessControlDetail请求参数结构体
"""
def __init__(self):
r"""
:param EventId: 事件唯一id
:type EventId: str
"""
self.EventId = None
def _deserialize(self, params):
self.EventId = params.get("EventId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeAccessControlDetailResponse(AbstractModel):
"""DescribeAccessControlDetail返回参数结构体
"""
def __init__(self):
r"""
:param EventBaseInfo: 事件基本信息
:type EventBaseInfo: :class:`tencentcloud.tcss.v20201101.models.RunTimeEventBaseInfo`
:param ProcessInfo: 进程信息
:type ProcessInfo: :class:`tencentcloud.tcss.v20201101.models.ProcessDetailInfo`
:param TamperedFileInfo: 被篡改信息
:type TamperedFileInfo: :class:`tencentcloud.tcss.v20201101.models.FileAttributeInfo`
:param EventDetail: 事件描述
:type EventDetail: :class:`tencentcloud.tcss.v20201101.models.AccessControlEventDescription`
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.EventBaseInfo = None
self.ProcessInfo = None
self.TamperedFileInfo = None
self.EventDetail = None
self.RequestId = None
def _deserialize(self, params):
if params.get("EventBaseInfo") is not None:
self.EventBaseInfo = RunTimeEventBaseInfo()
self.EventBaseInfo._deserialize(params.get("EventBaseInfo"))
if params.get("ProcessInfo") is not None:
self.ProcessInfo = ProcessDetailInfo()
self.ProcessInfo._deserialize(params.get("ProcessInfo"))
if params.get("TamperedFileInfo") is not None:
self.TamperedFileInfo = FileAttributeInfo()
self.TamperedFileInfo._deserialize(params.get("TamperedFileInfo"))
if params.get("EventDetail") is not None:
self.EventDetail = AccessControlEventDescription()
self.EventDetail._deserialize(params.get("EventDetail"))
self.RequestId = params.get("RequestId")
class DescribeAccessControlEventsExportRequest(AbstractModel):
"""DescribeAccessControlEventsExport请求参数结构体
"""
def __init__(self):
r"""
:param ExportField: 导出字段
:type ExportField: list of str
:param Limit: 需要返回的数量,默认为10,最大值为100
:type Limit: int
:param Offset: 偏移量,默认为0。
:type Offset: int
:param Filters: 过滤参数,"Filters":[{"Name":"Status","Values":["2"]}]
:type Filters: list of RunTimeFilters
:param Order: 升序降序,asc desc
:type Order: str
:param By: 排序字段
:type By: str
"""
self.ExportField = None
self.Limit = None
self.Offset = None
self.Filters = None
self.Order = None
self.By = None
def _deserialize(self, params):
self.ExportField = params.get("ExportField")
self.Limit = params.get("Limit")
self.Offset = params.get("Offset")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = RunTimeFilters()
obj._deserialize(item)
self.Filters.append(obj)
self.Order = params.get("Order")
self.By = params.get("By")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeAccessControlEventsExportResponse(AbstractModel):
"""DescribeAccessControlEventsExport返回参数结构体
"""
def __init__(self):
r"""
:param DownloadUrl: execle下载地址
注意:此字段可能返回 null,表示取不到有效值。
:type DownloadUrl: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.DownloadUrl = None
self.RequestId = None
def _deserialize(self, params):
self.DownloadUrl = params.get("DownloadUrl")
self.RequestId = params.get("RequestId")
class DescribeAccessControlEventsRequest(AbstractModel):
"""DescribeAccessControlEvents请求参数结构体
"""
def __init__(self):
r"""
:param Limit: 需要返回的数量,默认为10,最大值为100
:type Limit: int
:param Offset: 偏移量,默认为0。
:type Offset: int
:param Filters: 过滤参数,"Filters":[{"Name":"Status","Values":["2"]}]
:type Filters: list of RunTimeFilters
:param Order: 升序降序,asc desc
:type Order: str
:param By: 排序字段
:type By: str
"""
self.Limit = None
self.Offset = None
self.Filters = None
self.Order = None
self.By = None
def _deserialize(self, params):
self.Limit = params.get("Limit")
self.Offset = params.get("Offset")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = RunTimeFilters()
obj._deserialize(item)
self.Filters.append(obj)
self.Order = params.get("Order")
self.By = params.get("By")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeAccessControlEventsResponse(AbstractModel):
"""DescribeAccessControlEvents返回参数结构体
"""
def __init__(self):
r"""
:param TotalCount: 事件总数量
:type TotalCount: int
:param EventSet: 访问控制事件数组
:type EventSet: list of AccessControlEventInfo
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.TotalCount = None
self.EventSet = None
self.RequestId = None
def _deserialize(self, params):
self.TotalCount = params.get("TotalCount")
if params.get("EventSet") is not None:
self.EventSet = []
for item in params.get("EventSet"):
obj = AccessControlEventInfo()
obj._deserialize(item)
self.EventSet.append(obj)
self.RequestId = params.get("RequestId")
class DescribeAccessControlRuleDetailRequest(AbstractModel):
"""DescribeAccessControlRuleDetail请求参数结构体
"""
def __init__(self):
r"""
:param RuleId: 策略唯一id
:type RuleId: str
:param ImageId: 镜像id, 仅仅在事件加白的时候使用
:type ImageId: str
"""
self.RuleId = None
self.ImageId = None
def _deserialize(self, params):
self.RuleId = params.get("RuleId")
self.ImageId = params.get("ImageId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeAccessControlRuleDetailResponse(AbstractModel):
"""DescribeAccessControlRuleDetail返回参数结构体
"""
def __init__(self):
r"""
:param RuleDetail: 运行时策略详细信息
:type RuleDetail: :class:`tencentcloud.tcss.v20201101.models.AccessControlRuleInfo`
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RuleDetail = None
self.RequestId = None
def _deserialize(self, params):
if params.get("RuleDetail") is not None:
self.RuleDetail = AccessControlRuleInfo()
self.RuleDetail._deserialize(params.get("RuleDetail"))
self.RequestId = params.get("RequestId")
class DescribeAccessControlRulesExportRequest(AbstractModel):
"""DescribeAccessControlRulesExport请求参数结构体
"""
def __init__(self):
r"""
:param ExportField: 导出字段
:type ExportField: list of str
:param Limit: 需要返回的数量,默认为10,最大值为100
:type Limit: int
:param Offset: 偏移量,默认为0。
:type Offset: int
:param Filters: 过滤参数,"Filters":[{"Name":"Status","Values":["2"]}]
:type Filters: list of RunTimeFilters
:param Order: 升序降序,asc desc
:type Order: str
:param By: 排序字段
:type By: str
"""
self.ExportField = None
self.Limit = None
self.Offset = None
self.Filters = None
self.Order = None
self.By = None
def _deserialize(self, params):
self.ExportField = params.get("ExportField")
self.Limit = params.get("Limit")
self.Offset = params.get("Offset")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = RunTimeFilters()
obj._deserialize(item)
self.Filters.append(obj)
self.Order = params.get("Order")
self.By = params.get("By")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeAccessControlRulesExportResponse(AbstractModel):
"""DescribeAccessControlRulesExport返回参数结构体
"""
def __init__(self):
r"""
:param DownloadUrl: execle下载地址
注意:此字段可能返回 null,表示取不到有效值。
:type DownloadUrl: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.DownloadUrl = None
self.RequestId = None
def _deserialize(self, params):
self.DownloadUrl = params.get("DownloadUrl")
self.RequestId = params.get("RequestId")
class DescribeAccessControlRulesRequest(AbstractModel):
"""DescribeAccessControlRules请求参数结构体
"""
def __init__(self):
r"""
:param Limit: 需要返回的数量,默认为10,最大值为100
:type Limit: int
:param Offset: 偏移量,默认为0。
:type Offset: int
:param Filters: 过滤参数,"Filters":[{"Name":"Status","Values":["2"]}]
:type Filters: list of RunTimeFilters
:param Order: 升序降序,asc desc
:type Order: str
:param By: 排序字段
:type By: str
"""
self.Limit = None
self.Offset = None
self.Filters = None
self.Order = None
self.By = None
def _deserialize(self, params):
self.Limit = params.get("Limit")
self.Offset = params.get("Offset")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = RunTimeFilters()
obj._deserialize(item)
self.Filters.append(obj)
self.Order = params.get("Order")
self.By = params.get("By")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeAccessControlRulesResponse(AbstractModel):
"""DescribeAccessControlRules返回参数结构体
"""
def __init__(self):
r"""
:param TotalCount: 事件总数量
:type TotalCount: int
:param RuleSet: 访问控制策略信息列表
:type RuleSet: list of RuleBaseInfo
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.TotalCount = None
self.RuleSet = None
self.RequestId = None
def _deserialize(self, params):
self.TotalCount = params.get("TotalCount")
if params.get("RuleSet") is not None:
self.RuleSet = []
for item in params.get("RuleSet"):
obj = RuleBaseInfo()
obj._deserialize(item)
self.RuleSet.append(obj)
self.RequestId = params.get("RequestId")
class DescribeAffectedClusterCountRequest(AbstractModel):
"""DescribeAffectedClusterCount请求参数结构体
"""
class DescribeAffectedClusterCountResponse(AbstractModel):
"""DescribeAffectedClusterCount返回参数结构体
"""
def __init__(self):
r"""
:param SeriousRiskClusterCount: 严重风险的集群数量
:type SeriousRiskClusterCount: int
:param HighRiskClusterCount: 高危风险的集群数量
:type HighRiskClusterCount: int
:param MiddleRiskClusterCount: 中危风险的集群数量
:type MiddleRiskClusterCount: int
:param HintRiskClusterCount: 低危风险的集群数量
:type HintRiskClusterCount: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.SeriousRiskClusterCount = None
self.HighRiskClusterCount = None
self.MiddleRiskClusterCount = None
self.HintRiskClusterCount = None
self.RequestId = None
def _deserialize(self, params):
self.SeriousRiskClusterCount = params.get("SeriousRiskClusterCount")
self.HighRiskClusterCount = params.get("HighRiskClusterCount")
self.MiddleRiskClusterCount = params.get("MiddleRiskClusterCount")
self.HintRiskClusterCount = params.get("HintRiskClusterCount")
self.RequestId = params.get("RequestId")
class DescribeAffectedNodeListRequest(AbstractModel):
"""DescribeAffectedNodeList请求参数结构体
"""
def __init__(self):
r"""
:param CheckItemId: 唯一的检测项的ID
:type CheckItemId: int
:param Offset: 偏移量
:type Offset: int
:param Limit: 每次查询的最大记录数量
:type Limit: int
:param Filters: Name - String
Name 可取值:ClusterName, ClusterId,InstanceId,PrivateIpAddresses
:type Filters: list of ComplianceFilters
:param By: 排序字段
:type By: str
:param Order: 排序方式 asc,desc
:type Order: str
"""
self.CheckItemId = None
self.Offset = None
self.Limit = None
self.Filters = None
self.By = None
self.Order = None
def _deserialize(self, params):
self.CheckItemId = params.get("CheckItemId")
self.Offset = params.get("Offset")
self.Limit = params.get("Limit")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = ComplianceFilters()
obj._deserialize(item)
self.Filters.append(obj)
self.By = params.get("By")
self.Order = params.get("Order")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeAffectedNodeListResponse(AbstractModel):
"""DescribeAffectedNodeList返回参数结构体
"""
def __init__(self):
r"""
:param TotalCount: 受影响的节点总数
:type TotalCount: int
:param AffectedNodeList: 受影响的节点列表
:type AffectedNodeList: list of AffectedNodeItem
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.TotalCount = None
self.AffectedNodeList = None
self.RequestId = None
def _deserialize(self, params):
self.TotalCount = params.get("TotalCount")
if params.get("AffectedNodeList") is not None:
self.AffectedNodeList = []
for item in params.get("AffectedNodeList"):
obj = AffectedNodeItem()
obj._deserialize(item)
self.AffectedNodeList.append(obj)
self.RequestId = params.get("RequestId")
class DescribeAffectedWorkloadListRequest(AbstractModel):
"""DescribeAffectedWorkloadList请求参数结构体
"""
def __init__(self):
r"""
:param CheckItemId: 唯一的检测项的ID
:type CheckItemId: int
:param Offset: 偏移量
:type Offset: int
:param Limit: 每次查询的最大记录数量
:type Limit: int
:param Filters: Name - String
Name 可取值:WorkloadType,ClusterId
:type Filters: list of ComplianceFilters
:param By: 排序字段
:type By: str
:param Order: 排序方式 asc,desc
:type Order: str
"""
self.CheckItemId = None
self.Offset = None
self.Limit = None
self.Filters = None
self.By = None
self.Order = None
def _deserialize(self, params):
self.CheckItemId = params.get("CheckItemId")
self.Offset = params.get("Offset")
self.Limit = params.get("Limit")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = ComplianceFilters()
obj._deserialize(item)
self.Filters.append(obj)
self.By = params.get("By")
self.Order = params.get("Order")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeAffectedWorkloadListResponse(AbstractModel):
"""DescribeAffectedWorkloadList返回参数结构体
"""
def __init__(self):
r"""
:param TotalCount: 受影响的workload列表数量
:type TotalCount: int
:param AffectedWorkloadList: 受影响的workload列表
:type AffectedWorkloadList: list of AffectedWorkloadItem
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.TotalCount = None
self.AffectedWorkloadList = None
self.RequestId = None
def _deserialize(self, params):
self.TotalCount = params.get("TotalCount")
if params.get("AffectedWorkloadList") is not None:
self.AffectedWorkloadList = []
for item in params.get("AffectedWorkloadList"):
obj = AffectedWorkloadItem()
obj._deserialize(item)
self.AffectedWorkloadList.append(obj)
self.RequestId = params.get("RequestId")
class DescribeAssetAppServiceListRequest(AbstractModel):
"""DescribeAssetAppServiceList请求参数结构体
"""
def __init__(self):
r"""
:param Limit: 需要返回的数量,默认为10,最大值为100
:type Limit: int
:param Offset: 偏移量,默认为0。
:type Offset: int
:param Filters: 过滤条件。
<li>Keywords- String - 是否必填:否 - 模糊查询可选字段</li>
:type Filters: list of AssetFilters
"""
self.Limit = None
self.Offset = None
self.Filters = None
def _deserialize(self, params):
self.Limit = params.get("Limit")
self.Offset = params.get("Offset")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = AssetFilters()
obj._deserialize(item)
self.Filters.append(obj)
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeAssetAppServiceListResponse(AbstractModel):
"""DescribeAssetAppServiceList返回参数结构体
"""
def __init__(self):
r"""
:param List: db服务列表
:type List: list of ServiceInfo
:param TotalCount: 总数量
:type TotalCount: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.List = None
self.TotalCount = None
self.RequestId = None
def _deserialize(self, params):
if params.get("List") is not None:
self.List = []
for item in params.get("List"):
obj = ServiceInfo()
obj._deserialize(item)
self.List.append(obj)
self.TotalCount = params.get("TotalCount")
self.RequestId = params.get("RequestId")
class DescribeAssetComponentListRequest(AbstractModel):
"""DescribeAssetComponentList请求参数结构体
"""
def __init__(self):
r"""
:param ContainerID: 容器id
:type ContainerID: str
:param Limit: 需要返回的数量,默认为10,最大值为100
:type Limit: int
:param Offset: 偏移量,默认为0。
:type Offset: int
:param Filters: 过滤条件
:type Filters: list of AssetFilters
"""
self.ContainerID = None
self.Limit = None
self.Offset = None
self.Filters = None
def _deserialize(self, params):
self.ContainerID = params.get("ContainerID")
self.Limit = params.get("Limit")
self.Offset = params.get("Offset")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = AssetFilters()
obj._deserialize(item)
self.Filters.append(obj)
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeAssetComponentListResponse(AbstractModel):
"""DescribeAssetComponentList返回参数结构体
"""
def __init__(self):
r"""
:param List: 组件列表
:type List: list of ComponentInfo
:param TotalCount: 总数量
:type TotalCount: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.List = None
self.TotalCount = None
self.RequestId = None
def _deserialize(self, params):
if params.get("List") is not None:
self.List = []
for item in params.get("List"):
obj = ComponentInfo()
obj._deserialize(item)
self.List.append(obj)
self.TotalCount = params.get("TotalCount")
self.RequestId = params.get("RequestId")
class DescribeAssetContainerDetailRequest(AbstractModel):
"""DescribeAssetContainerDetail请求参数结构体
"""
def __init__(self):
r"""
:param ContainerId: 容器id
:type ContainerId: str
"""
self.ContainerId = None
def _deserialize(self, params):
self.ContainerId = params.get("ContainerId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeAssetContainerDetailResponse(AbstractModel):
"""DescribeAssetContainerDetail返回参数结构体
"""
def __init__(self):
r"""
:param HostID: 主机id
:type HostID: str
:param HostIP: 主机ip
:type HostIP: str
:param ContainerName: 容器名称
:type ContainerName: str
:param Status: 运行状态
:type Status: str
:param RunAs: 运行账户
:type RunAs: str
:param Cmd: 命令行
:type Cmd: str
:param CPUUsage: CPU使用率 * 1000
:type CPUUsage: int
:param RamUsage: 内存使用 KB
:type RamUsage: int
:param ImageName: 镜像名
:type ImageName: str
:param ImageID: 镜像ID
:type ImageID: str
:param POD: 归属POD
:type POD: str
:param K8sMaster: k8s 主节点
:type K8sMaster: str
:param ProcessCnt: 容器内进程数
:type ProcessCnt: int
:param PortCnt: 容器内端口数
:type PortCnt: int
:param ComponentCnt: 组件数
:type ComponentCnt: int
:param AppCnt: app数
:type AppCnt: int
:param WebServiceCnt: websvc数
:type WebServiceCnt: int
:param Mounts: 挂载
:type Mounts: list of ContainerMount
:param Network: 容器网络信息
:type Network: :class:`tencentcloud.tcss.v20201101.models.ContainerNetwork`
:param CreateTime: 创建时间
:type CreateTime: str
:param ImageCreateTime: 镜像创建时间
:type ImageCreateTime: str
:param ImageSize: 镜像大小
:type ImageSize: int
:param HostStatus: 主机状态 offline,online,pause
:type HostStatus: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.HostID = None
self.HostIP = None
self.ContainerName = None
self.Status = None
self.RunAs = None
self.Cmd = None
self.CPUUsage = None
self.RamUsage = None
self.ImageName = None
self.ImageID = None
self.POD = None
self.K8sMaster = None
self.ProcessCnt = None
self.PortCnt = None
self.ComponentCnt = None
self.AppCnt = None
self.WebServiceCnt = None
self.Mounts = None
self.Network = None
self.CreateTime = None
self.ImageCreateTime = None
self.ImageSize = None
self.HostStatus = None
self.RequestId = None
def _deserialize(self, params):
self.HostID = params.get("HostID")
self.HostIP = params.get("HostIP")
self.ContainerName = params.get("ContainerName")
self.Status = params.get("Status")
self.RunAs = params.get("RunAs")
self.Cmd = params.get("Cmd")
self.CPUUsage = params.get("CPUUsage")
self.RamUsage = params.get("RamUsage")
self.ImageName = params.get("ImageName")
self.ImageID = params.get("ImageID")
self.POD = params.get("POD")
self.K8sMaster = params.get("K8sMaster")
self.ProcessCnt = params.get("ProcessCnt")
self.PortCnt = params.get("PortCnt")
self.ComponentCnt = params.get("ComponentCnt")
self.AppCnt = params.get("AppCnt")
self.WebServiceCnt = params.get("WebServiceCnt")
if params.get("Mounts") is not None:
self.Mounts = []
for item in params.get("Mounts"):
obj = ContainerMount()
obj._deserialize(item)
self.Mounts.append(obj)
if params.get("Network") is not None:
self.Network = ContainerNetwork()
self.Network._deserialize(params.get("Network"))
self.CreateTime = params.get("CreateTime")
self.ImageCreateTime = params.get("ImageCreateTime")
self.ImageSize = params.get("ImageSize")
self.HostStatus = params.get("HostStatus")
self.RequestId = params.get("RequestId")
class DescribeAssetContainerListRequest(AbstractModel):
"""DescribeAssetContainerList请求参数结构体
"""
def __init__(self):
r"""
:param Limit: 需要返回的数量,默认为10,最大值为100
:type Limit: int
:param Offset: 偏移量,默认为0。
:type Offset: int
:param Filters: 过滤条件。
<li>ContainerName - String - 是否必填:否 - 容器名称模糊搜索</li>
<li>Status - String - 是否必填:否 - 容器运行状态筛选,0:"created",1:"running", 2:"paused", 3:"restarting", 4:"removing", 5:"exited", 6:"dead" </li>
<li>Runas - String - 是否必填:否 - 运行用户筛选</li>
<li>ImageName- String - 是否必填:否 - 镜像名称搜索</li>
<li>HostIP- string - 是否必填:否 - 主机ip搜索</li>
<li>OrderBy - String 是否必填:否 -排序字段,支持:cpu_usage, mem_usage的动态排序 ["cpu_usage","+"] '+'升序、'-'降序</li>
:type Filters: list of AssetFilters
:param By: 排序字段
:type By: str
:param Order: 排序方式 asc,desc
:type Order: str
"""
self.Limit = None
self.Offset = None
self.Filters = None
self.By = None
self.Order = None
def _deserialize(self, params):
self.Limit = params.get("Limit")
self.Offset = params.get("Offset")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = AssetFilters()
obj._deserialize(item)
self.Filters.append(obj)
self.By = params.get("By")
self.Order = params.get("Order")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeAssetContainerListResponse(AbstractModel):
"""DescribeAssetContainerList返回参数结构体
"""
def __init__(self):
r"""
:param List: 容器列表
:type List: list of ContainerInfo
:param TotalCount: 总数量
:type TotalCount: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.List = None
self.TotalCount = None
self.RequestId = None
def _deserialize(self, params):
if params.get("List") is not None:
self.List = []
for item in params.get("List"):
obj = ContainerInfo()
obj._deserialize(item)
self.List.append(obj)
self.TotalCount = params.get("TotalCount")
self.RequestId = params.get("RequestId")
class DescribeAssetDBServiceListRequest(AbstractModel):
"""DescribeAssetDBServiceList请求参数结构体
"""
def __init__(self):
r"""
:param Limit: 需要返回的数量,默认为10,最大值为100
:type Limit: int
:param Offset: 偏移量,默认为0。
:type Offset: int
:param Filters: 过滤条件。
<li>Keywords- String - 是否必填:否 - 模糊查询可选字段</li>
:type Filters: list of AssetFilters
"""
self.Limit = None
self.Offset = None
self.Filters = None
def _deserialize(self, params):
self.Limit = params.get("Limit")
self.Offset = params.get("Offset")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = AssetFilters()
obj._deserialize(item)
self.Filters.append(obj)
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeAssetDBServiceListResponse(AbstractModel):
"""DescribeAssetDBServiceList返回参数结构体
"""
def __init__(self):
r"""
:param List: db服务列表
:type List: list of ServiceInfo
:param TotalCount: 总数量
:type TotalCount: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.List = None
self.TotalCount = None
self.RequestId = None
def _deserialize(self, params):
if params.get("List") is not None:
self.List = []
for item in params.get("List"):
obj = ServiceInfo()
obj._deserialize(item)
self.List.append(obj)
self.TotalCount = params.get("TotalCount")
self.RequestId = params.get("RequestId")
class DescribeAssetHostDetailRequest(AbstractModel):
"""DescribeAssetHostDetail请求参数结构体
"""
def __init__(self):
r"""
:param HostId: 主机id
:type HostId: str
"""
self.HostId = None
def _deserialize(self, params):
self.HostId = params.get("HostId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeAssetHostDetailResponse(AbstractModel):
"""DescribeAssetHostDetail返回参数结构体
"""
def __init__(self):
r"""
:param UUID: 云镜uuid
:type UUID: str
:param UpdateTime: 更新时间
:type UpdateTime: str
:param HostName: 主机名
:type HostName: str
:param Group: 主机分组
:type Group: str
:param HostIP: 主机IP
:type HostIP: str
:param OsName: 操作系统
:type OsName: str
:param AgentVersion: agent版本
:type AgentVersion: str
:param KernelVersion: 内核版本
:type KernelVersion: str
:param DockerVersion: docker版本
:type DockerVersion: str
:param DockerAPIVersion: docker api版本
:type DockerAPIVersion: str
:param DockerGoVersion: docker go 版本
:type DockerGoVersion: str
:param DockerFileSystemDriver: docker 文件系统类型
:type DockerFileSystemDriver: str
:param DockerRootDir: docker root 目录
:type DockerRootDir: str
:param ImageCnt: 镜像数
:type ImageCnt: int
:param ContainerCnt: 容器数
:type ContainerCnt: int
:param K8sMasterIP: k8s IP
:type K8sMasterIP: str
:param K8sVersion: k8s version
:type K8sVersion: str
:param KubeProxyVersion: kube proxy
:type KubeProxyVersion: str
:param Status: "UNINSTALL":"未安装","OFFLINE":"离线", "ONLINE":"防护中
:type Status: str
:param IsContainerd: 是否Containerd
:type IsContainerd: bool
:param MachineType: 主机来源;"TENCENTCLOUD":"腾讯云服务器","OTHERCLOUD":"非腾讯云服务器"
:type MachineType: str
:param PublicIp: 外网ip
:type PublicIp: str
:param InstanceID: 主机实例ID
:type InstanceID: str
:param RegionID: 地域ID
:type RegionID: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.UUID = None
self.UpdateTime = None
self.HostName = None
self.Group = None
self.HostIP = None
self.OsName = None
self.AgentVersion = None
self.KernelVersion = None
self.DockerVersion = None
self.DockerAPIVersion = None
self.DockerGoVersion = None
self.DockerFileSystemDriver = None
self.DockerRootDir = None
self.ImageCnt = None
self.ContainerCnt = None
self.K8sMasterIP = None
self.K8sVersion = None
self.KubeProxyVersion = None
self.Status = None
self.IsContainerd = None
self.MachineType = None
self.PublicIp = None
self.InstanceID = None
self.RegionID = None
self.RequestId = None
def _deserialize(self, params):
self.UUID = params.get("UUID")
self.UpdateTime = params.get("UpdateTime")
self.HostName = params.get("HostName")
self.Group = params.get("Group")
self.HostIP = params.get("HostIP")
self.OsName = params.get("OsName")
self.AgentVersion = params.get("AgentVersion")
self.KernelVersion = params.get("KernelVersion")
self.DockerVersion = params.get("DockerVersion")
self.DockerAPIVersion = params.get("DockerAPIVersion")
self.DockerGoVersion = params.get("DockerGoVersion")
self.DockerFileSystemDriver = params.get("DockerFileSystemDriver")
self.DockerRootDir = params.get("DockerRootDir")
self.ImageCnt = params.get("ImageCnt")
self.ContainerCnt = params.get("ContainerCnt")
self.K8sMasterIP = params.get("K8sMasterIP")
self.K8sVersion = params.get("K8sVersion")
self.KubeProxyVersion = params.get("KubeProxyVersion")
self.Status = params.get("Status")
self.IsContainerd = params.get("IsContainerd")
self.MachineType = params.get("MachineType")
self.PublicIp = params.get("PublicIp")
self.InstanceID = params.get("InstanceID")
self.RegionID = params.get("RegionID")
self.RequestId = params.get("RequestId")
class DescribeAssetHostListRequest(AbstractModel):
"""DescribeAssetHostList请求参数结构体
"""
def __init__(self):
r"""
:param Limit: 需要返回的数量,默认为10,最大值为100
:type Limit: int
:param Offset: 偏移量,默认为0。
:type Offset: int
:param Filters: 过滤条件。
<li>Status - String - 是否必填:否 - agent状态筛选,"ALL":"全部"(或不传该字段),"UNINSTALL":"未安装","OFFLINE":"离线", "ONLINE":"防护中"</li>
<li>HostName - String - 是否必填:否 - 主机名筛选</li>
<li>Group- String - 是否必填:否 - 主机群组搜索</li>
<li>HostIP- string - 是否必填:否 - 主机ip搜索</li>
<li>HostID- string - 是否必填:否 - 主机id搜索</li>
<li>DockerVersion- string - 是否必填:否 - docker版本搜索</li>
<li>MachineType- string - 是否必填:否 - 主机来源MachineType搜索,"ALL":"全部"(或不传该字段),主机来源:["CVM", "ECM", "LH", "BM"] 中的之一为腾讯云服务器;["Other"]之一非腾讯云服务器;</li>
<li>DockerStatus- string - 是否必填:否 - docker安装状态,"ALL":"全部"(或不传该字段),"INSTALL":"已安装","UNINSTALL":"未安装"</li>
:type Filters: list of AssetFilters
:param By: 排序字段
:type By: str
:param Order: 排序方式 asc,desc
:type Order: str
"""
self.Limit = None
self.Offset = None
self.Filters = None
self.By = None
self.Order = None
def _deserialize(self, params):
self.Limit = params.get("Limit")
self.Offset = params.get("Offset")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = AssetFilters()
obj._deserialize(item)
self.Filters.append(obj)
self.By = params.get("By")
self.Order = params.get("Order")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeAssetHostListResponse(AbstractModel):
"""DescribeAssetHostList返回参数结构体
"""
def __init__(self):
r"""
:param List: 主机列表
:type List: list of HostInfo
:param TotalCount: 总数量
:type TotalCount: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.List = None
self.TotalCount = None
self.RequestId = None
def _deserialize(self, params):
if params.get("List") is not None:
self.List = []
for item in params.get("List"):
obj = HostInfo()
obj._deserialize(item)
self.List.append(obj)
self.TotalCount = params.get("TotalCount")
self.RequestId = params.get("RequestId")
class DescribeAssetImageBindRuleInfoRequest(AbstractModel):
"""DescribeAssetImageBindRuleInfo请求参数结构体
"""
def __init__(self):
r"""
:param Limit: 需要返回的数量,默认为10,最大值为100
:type Limit: int
:param Offset: 偏移量,默认为0。
:type Offset: int
:param Filters: 过滤参数,"Filters":[{"Name":"EventType","Values":[""]}]
EventType取值:
"FILE_ABNORMAL_READ" 访问控制
"MALICE_PROCESS_START" 恶意进程启动
:type Filters: list of RunTimeFilters
:param Order: 升序降序,asc desc
:type Order: str
:param By: 排序字段
:type By: str
"""
self.Limit = None
self.Offset = None
self.Filters = None
self.Order = None
self.By = None
def _deserialize(self, params):
self.Limit = params.get("Limit")
self.Offset = params.get("Offset")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = RunTimeFilters()
obj._deserialize(item)
self.Filters.append(obj)
self.Order = params.get("Order")
self.By = params.get("By")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeAssetImageBindRuleInfoResponse(AbstractModel):
"""DescribeAssetImageBindRuleInfo返回参数结构体
"""
def __init__(self):
r"""
:param TotalCount: 事件总数量
:type TotalCount: int
:param ImageBindRuleSet: 镜像绑定规则列表
:type ImageBindRuleSet: list of ImagesBindRuleInfo
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.TotalCount = None
self.ImageBindRuleSet = None
self.RequestId = None
def _deserialize(self, params):
self.TotalCount = params.get("TotalCount")
if params.get("ImageBindRuleSet") is not None:
self.ImageBindRuleSet = []
for item in params.get("ImageBindRuleSet"):
obj = ImagesBindRuleInfo()
obj._deserialize(item)
self.ImageBindRuleSet.append(obj)
self.RequestId = params.get("RequestId")
class DescribeAssetImageDetailRequest(AbstractModel):
"""DescribeAssetImageDetail请求参数结构体
"""
def __init__(self):
r"""
:param ImageID: 镜像id
:type ImageID: str
"""
self.ImageID = None
def _deserialize(self, params):
self.ImageID = params.get("ImageID")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeAssetImageDetailResponse(AbstractModel):
"""DescribeAssetImageDetail返回参数结构体
"""
def __init__(self):
r"""
:param ImageID: 镜像ID
:type ImageID: str
:param ImageName: 镜像名称
:type ImageName: str
:param CreateTime: 创建时间
:type CreateTime: str
:param Size: 镜像大小
:type Size: int
:param HostCnt: 关联主机个数
注意:此字段可能返回 null,表示取不到有效值。
:type HostCnt: int
:param ContainerCnt: 关联容器个数
注意:此字段可能返回 null,表示取不到有效值。
:type ContainerCnt: int
:param ScanTime: 最近扫描时间
注意:此字段可能返回 null,表示取不到有效值。
:type ScanTime: str
:param VulCnt: 漏洞个数
注意:此字段可能返回 null,表示取不到有效值。
:type VulCnt: int
:param RiskCnt: 风险行为数
注意:此字段可能返回 null,表示取不到有效值。
:type RiskCnt: int
:param SensitiveInfoCnt: 敏感信息数
注意:此字段可能返回 null,表示取不到有效值。
:type SensitiveInfoCnt: int
:param IsTrustImage: 是否信任镜像
:type IsTrustImage: bool
:param OsName: 镜像系统
:type OsName: str
:param AgentError: agent镜像扫描错误
注意:此字段可能返回 null,表示取不到有效值。
:type AgentError: str
:param ScanError: 后端镜像扫描错误
注意:此字段可能返回 null,表示取不到有效值。
:type ScanError: str
:param Architecture: 系统架构
注意:此字段可能返回 null,表示取不到有效值。
:type Architecture: str
:param Author: 作者
注意:此字段可能返回 null,表示取不到有效值。
:type Author: str
:param BuildHistory: 构建历史
注意:此字段可能返回 null,表示取不到有效值。
:type BuildHistory: str
:param ScanVirusProgress: 木马扫描进度
注意:此字段可能返回 null,表示取不到有效值。
:type ScanVirusProgress: int
:param ScanVulProgress: 漏洞扫进度
注意:此字段可能返回 null,表示取不到有效值。
:type ScanVulProgress: int
:param ScanRiskProgress: 敏感信息扫描进度
注意:此字段可能返回 null,表示取不到有效值。
:type ScanRiskProgress: int
:param ScanVirusError: 木马扫描错误
注意:此字段可能返回 null,表示取不到有效值。
:type ScanVirusError: str
:param ScanVulError: 漏洞扫描错误
注意:此字段可能返回 null,表示取不到有效值。
:type ScanVulError: str
:param ScanRiskError: 敏感信息错误
注意:此字段可能返回 null,表示取不到有效值。
:type ScanRiskError: str
:param ScanStatus: 镜像扫描状态
注意:此字段可能返回 null,表示取不到有效值。
:type ScanStatus: str
:param VirusCnt: 木马病毒数
注意:此字段可能返回 null,表示取不到有效值。
:type VirusCnt: int
:param Status: 镜像扫描状态
注意:此字段可能返回 null,表示取不到有效值。
:type Status: int
:param RemainScanTime: 剩余扫描时间
注意:此字段可能返回 null,表示取不到有效值。
:type RemainScanTime: int
:param IsAuthorized: 授权为:1,未授权为:0
:type IsAuthorized: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.ImageID = None
self.ImageName = None
self.CreateTime = None
self.Size = None
self.HostCnt = None
self.ContainerCnt = None
self.ScanTime = None
self.VulCnt = None
self.RiskCnt = None
self.SensitiveInfoCnt = None
self.IsTrustImage = None
self.OsName = None
self.AgentError = None
self.ScanError = None
self.Architecture = None
self.Author = None
self.BuildHistory = None
self.ScanVirusProgress = None
self.ScanVulProgress = None
self.ScanRiskProgress = None
self.ScanVirusError = None
self.ScanVulError = None
self.ScanRiskError = None
self.ScanStatus = None
self.VirusCnt = None
self.Status = None
self.RemainScanTime = None
self.IsAuthorized = None
self.RequestId = None
def _deserialize(self, params):
self.ImageID = params.get("ImageID")
self.ImageName = params.get("ImageName")
self.CreateTime = params.get("CreateTime")
self.Size = params.get("Size")
self.HostCnt = params.get("HostCnt")
self.ContainerCnt = params.get("ContainerCnt")
self.ScanTime = params.get("ScanTime")
self.VulCnt = params.get("VulCnt")
self.RiskCnt = params.get("RiskCnt")
self.SensitiveInfoCnt = params.get("SensitiveInfoCnt")
self.IsTrustImage = params.get("IsTrustImage")
self.OsName = params.get("OsName")
self.AgentError = params.get("AgentError")
self.ScanError = params.get("ScanError")
self.Architecture = params.get("Architecture")
self.Author = params.get("Author")
self.BuildHistory = params.get("BuildHistory")
self.ScanVirusProgress = params.get("ScanVirusProgress")
self.ScanVulProgress = params.get("ScanVulProgress")
self.ScanRiskProgress = params.get("ScanRiskProgress")
self.ScanVirusError = params.get("ScanVirusError")
self.ScanVulError = params.get("ScanVulError")
self.ScanRiskError = params.get("ScanRiskError")
self.ScanStatus = params.get("ScanStatus")
self.VirusCnt = params.get("VirusCnt")
self.Status = params.get("Status")
self.RemainScanTime = params.get("RemainScanTime")
self.IsAuthorized = params.get("IsAuthorized")
self.RequestId = params.get("RequestId")
class DescribeAssetImageHostListRequest(AbstractModel):
"""DescribeAssetImageHostList请求参数结构体
"""
def __init__(self):
r"""
:param Filters: 过滤条件 支持ImageID,HostID
:type Filters: list of AssetFilters
"""
self.Filters = None
def _deserialize(self, params):
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = AssetFilters()
obj._deserialize(item)
self.Filters.append(obj)
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeAssetImageHostListResponse(AbstractModel):
"""DescribeAssetImageHostList返回参数结构体
"""
def __init__(self):
r"""
:param List: 镜像列表
:type List: list of ImageHost
:param TotalCount: 总数量
:type TotalCount: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.List = None
self.TotalCount = None
self.RequestId = None
def _deserialize(self, params):
if params.get("List") is not None:
self.List = []
for item in params.get("List"):
obj = ImageHost()
obj._deserialize(item)
self.List.append(obj)
self.TotalCount = params.get("TotalCount")
self.RequestId = params.get("RequestId")
class DescribeAssetImageListExportRequest(AbstractModel):
"""DescribeAssetImageListExport请求参数结构体
"""
def __init__(self):
r"""
:param ExportField: 导出字段
:type ExportField: list of str
:param Limit: 需要返回的数量,默认为10,最大值为100
:type Limit: int
:param Offset: 偏移量,默认为0。
:type Offset: int
:param Filters: 过滤条件。
<li>ImageName- String - 是否必填:否 - 镜像名称筛选,</li>
<li>ScanStatus - String - 是否必填:否 - 镜像扫描状态notScan,scanning,scanned,scanErr</li>
<li>ImageID- String - 是否必填:否 - 镜像ID筛选,</li>
<li>SecurityRisk- String - 是否必填:否 - 安全风险,VulCnt 、VirusCnt、RiskCnt、IsTrustImage</li>
:type Filters: list of AssetFilters
:param By: 排序字段
:type By: str
:param Order: 排序方式 asc,desc
:type Order: str
"""
self.ExportField = None
self.Limit = None
self.Offset = None
self.Filters = None
self.By = None
self.Order = None
def _deserialize(self, params):
self.ExportField = params.get("ExportField")
self.Limit = params.get("Limit")
self.Offset = params.get("Offset")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = AssetFilters()
obj._deserialize(item)
self.Filters.append(obj)
self.By = params.get("By")
self.Order = params.get("Order")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeAssetImageListExportResponse(AbstractModel):
"""DescribeAssetImageListExport返回参数结构体
"""
def __init__(self):
r"""
:param DownloadUrl: excel文件下载地址
:type DownloadUrl: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.DownloadUrl = None
self.RequestId = None
def _deserialize(self, params):
self.DownloadUrl = params.get("DownloadUrl")
self.RequestId = params.get("RequestId")
class DescribeAssetImageListRequest(AbstractModel):
"""DescribeAssetImageList请求参数结构体
"""
def __init__(self):
r"""
:param Limit: 需要返回的数量,默认为10,最大值为100
:type Limit: int
:param Offset: 偏移量,默认为0。
:type Offset: int
:param Filters: 过滤条件。
<li>ImageName- String - 是否必填:否 - 镜像名称筛选,</li>
<li>ScanStatus - String - 是否必填:否 - 镜像扫描状态notScan,scanning,scanned,scanErr</li>
<li>ImageID- String - 是否必填:否 - 镜像ID筛选,</li>
<li>SecurityRisk- String - 是否必填:否 - 安全风险,VulCnt 、VirusCnt、RiskCnt、IsTrustImage</li>
:type Filters: list of AssetFilters
:param By: 排序字段
:type By: str
:param Order: 排序方式 asc,desc
:type Order: str
"""
self.Limit = None
self.Offset = None
self.Filters = None
self.By = None
self.Order = None
def _deserialize(self, params):
self.Limit = params.get("Limit")
self.Offset = params.get("Offset")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = AssetFilters()
obj._deserialize(item)
self.Filters.append(obj)
self.By = params.get("By")
self.Order = params.get("Order")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeAssetImageListResponse(AbstractModel):
"""DescribeAssetImageList返回参数结构体
"""
def __init__(self):
r"""
:param List: 镜像列表
:type List: list of ImagesInfo
:param TotalCount: 总数量
:type TotalCount: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.List = None
self.TotalCount = None
self.RequestId = None
def _deserialize(self, params):
if params.get("List") is not None:
self.List = []
for item in params.get("List"):
obj = ImagesInfo()
obj._deserialize(item)
self.List.append(obj)
self.TotalCount = params.get("TotalCount")
self.RequestId = params.get("RequestId")
class DescribeAssetImageRegistryAssetStatusRequest(AbstractModel):
"""DescribeAssetImageRegistryAssetStatus请求参数结构体
"""
class DescribeAssetImageRegistryAssetStatusResponse(AbstractModel):
"""DescribeAssetImageRegistryAssetStatus返回参数结构体
"""
def __init__(self):
r"""
:param Status: 更新进度状态,doing更新中,success更新成功,failed失败
:type Status: str
:param Err: 错误信息
注意:此字段可能返回 null,表示取不到有效值。
:type Err: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.Status = None
self.Err = None
self.RequestId = None
def _deserialize(self, params):
self.Status = params.get("Status")
self.Err = params.get("Err")
self.RequestId = params.get("RequestId")
class DescribeAssetImageRegistryDetailRequest(AbstractModel):
"""DescribeAssetImageRegistryDetail请求参数结构体
"""
def __init__(self):
r"""
:param Id: 仓库列表id
:type Id: int
:param ImageId: 镜像ID
:type ImageId: str
"""
self.Id = None
self.ImageId = None
def _deserialize(self, params):
self.Id = params.get("Id")
self.ImageId = params.get("ImageId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeAssetImageRegistryDetailResponse(AbstractModel):
"""DescribeAssetImageRegistryDetail返回参数结构体
"""
def __init__(self):
r"""
:param ImageDigest: 镜像Digest
注意:此字段可能返回 null,表示取不到有效值。
:type ImageDigest: str
:param ImageRepoAddress: 镜像地址
注意:此字段可能返回 null,表示取不到有效值。
:type ImageRepoAddress: str
:param RegistryType: 镜像类型
注意:此字段可能返回 null,表示取不到有效值。
:type RegistryType: str
:param ImageName: 仓库名称
注意:此字段可能返回 null,表示取不到有效值。
:type ImageName: str
:param ImageTag: 镜像版本
注意:此字段可能返回 null,表示取不到有效值。
:type ImageTag: str
:param ScanTime: 扫描时间
注意:此字段可能返回 null,表示取不到有效值。
:type ScanTime: str
:param ScanStatus: 扫描状态
注意:此字段可能返回 null,表示取不到有效值。
:type ScanStatus: str
:param VulCnt: 安全漏洞数
注意:此字段可能返回 null,表示取不到有效值。
:type VulCnt: int
:param VirusCnt: 木马病毒数
注意:此字段可能返回 null,表示取不到有效值。
:type VirusCnt: int
:param RiskCnt: 风险行为数
注意:此字段可能返回 null,表示取不到有效值。
:type RiskCnt: int
:param SentiveInfoCnt: 敏感信息数
注意:此字段可能返回 null,表示取不到有效值。
:type SentiveInfoCnt: int
:param OsName: 镜像系统
注意:此字段可能返回 null,表示取不到有效值。
:type OsName: str
:param ScanVirusError: 木马扫描错误
注意:此字段可能返回 null,表示取不到有效值。
:type ScanVirusError: str
:param ScanVulError: 漏洞扫描错误
注意:此字段可能返回 null,表示取不到有效值。
:type ScanVulError: str
:param LayerInfo: 层文件信息
注意:此字段可能返回 null,表示取不到有效值。
:type LayerInfo: str
:param InstanceId: 实例id
注意:此字段可能返回 null,表示取不到有效值。
:type InstanceId: str
:param InstanceName: 实例名称
注意:此字段可能返回 null,表示取不到有效值。
:type InstanceName: str
:param Namespace: 命名空间
注意:此字段可能返回 null,表示取不到有效值。
:type Namespace: str
:param ScanRiskError: 高危扫描错误
注意:此字段可能返回 null,表示取不到有效值。
:type ScanRiskError: str
:param ScanVirusProgress: 木马信息扫描进度
注意:此字段可能返回 null,表示取不到有效值。
:type ScanVirusProgress: int
:param ScanVulProgress: 漏洞扫描进度
注意:此字段可能返回 null,表示取不到有效值。
:type ScanVulProgress: int
:param ScanRiskProgress: 敏感扫描进度
注意:此字段可能返回 null,表示取不到有效值。
:type ScanRiskProgress: int
:param ScanRemainTime: 剩余扫描时间秒
注意:此字段可能返回 null,表示取不到有效值。
:type ScanRemainTime: int
:param CveStatus: cve扫描状态
注意:此字段可能返回 null,表示取不到有效值。
:type CveStatus: str
:param RiskStatus: 高危扫描状态
注意:此字段可能返回 null,表示取不到有效值。
:type RiskStatus: str
:param VirusStatus: 木马扫描状态
注意:此字段可能返回 null,表示取不到有效值。
:type VirusStatus: str
:param Progress: 总进度
注意:此字段可能返回 null,表示取不到有效值。
:type Progress: int
:param IsAuthorized: 授权状态
注意:此字段可能返回 null,表示取不到有效值。
:type IsAuthorized: int
:param ImageSize: 镜像大小
注意:此字段可能返回 null,表示取不到有效值。
:type ImageSize: int
:param ImageId: 镜像Id
注意:此字段可能返回 null,表示取不到有效值。
:type ImageId: str
:param RegistryRegion: 镜像区域
注意:此字段可能返回 null,表示取不到有效值。
:type RegistryRegion: str
:param ImageCreateTime: 镜像创建的时间
注意:此字段可能返回 null,表示取不到有效值。
:type ImageCreateTime: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.ImageDigest = None
self.ImageRepoAddress = None
self.RegistryType = None
self.ImageName = None
self.ImageTag = None
self.ScanTime = None
self.ScanStatus = None
self.VulCnt = None
self.VirusCnt = None
self.RiskCnt = None
self.SentiveInfoCnt = None
self.OsName = None
self.ScanVirusError = None
self.ScanVulError = None
self.LayerInfo = None
self.InstanceId = None
self.InstanceName = None
self.Namespace = None
self.ScanRiskError = None
self.ScanVirusProgress = None
self.ScanVulProgress = None
self.ScanRiskProgress = None
self.ScanRemainTime = None
self.CveStatus = None
self.RiskStatus = None
self.VirusStatus = None
self.Progress = None
self.IsAuthorized = None
self.ImageSize = None
self.ImageId = None
self.RegistryRegion = None
self.ImageCreateTime = None
self.RequestId = None
def _deserialize(self, params):
self.ImageDigest = params.get("ImageDigest")
self.ImageRepoAddress = params.get("ImageRepoAddress")
self.RegistryType = params.get("RegistryType")
self.ImageName = params.get("ImageName")
self.ImageTag = params.get("ImageTag")
self.ScanTime = params.get("ScanTime")
self.ScanStatus = params.get("ScanStatus")
self.VulCnt = params.get("VulCnt")
self.VirusCnt = params.get("VirusCnt")
self.RiskCnt = params.get("RiskCnt")
self.SentiveInfoCnt = params.get("SentiveInfoCnt")
self.OsName = params.get("OsName")
self.ScanVirusError = params.get("ScanVirusError")
self.ScanVulError = params.get("ScanVulError")
self.LayerInfo = params.get("LayerInfo")
self.InstanceId = params.get("InstanceId")
self.InstanceName = params.get("InstanceName")
self.Namespace = params.get("Namespace")
self.ScanRiskError = params.get("ScanRiskError")
self.ScanVirusProgress = params.get("ScanVirusProgress")
self.ScanVulProgress = params.get("ScanVulProgress")
self.ScanRiskProgress = params.get("ScanRiskProgress")
self.ScanRemainTime = params.get("ScanRemainTime")
self.CveStatus = params.get("CveStatus")
self.RiskStatus = params.get("RiskStatus")
self.VirusStatus = params.get("VirusStatus")
self.Progress = params.get("Progress")
self.IsAuthorized = params.get("IsAuthorized")
self.ImageSize = params.get("ImageSize")
self.ImageId = params.get("ImageId")
self.RegistryRegion = params.get("RegistryRegion")
self.ImageCreateTime = params.get("ImageCreateTime")
self.RequestId = params.get("RequestId")
class DescribeAssetImageRegistryListExportRequest(AbstractModel):
"""DescribeAssetImageRegistryListExport请求参数结构体
"""
def __init__(self):
r"""
:param ExportField: 导出字段
:type ExportField: list of str
:param Limit: 需要返回的数量,默认为10,最大值为100
:type Limit: int
:param Offset: 偏移量,默认为0
:type Offset: int
:param Filters: 排序字段
:type Filters: list of AssetFilters
:param By: 排序字段
:type By: str
:param Order: 排序方式,asc,desc
:type Order: str
:param OnlyShowLatest: 是否仅展示repository版本最新的镜像,默认为false
:type OnlyShowLatest: bool
"""
self.ExportField = None
self.Limit = None
self.Offset = None
self.Filters = None
self.By = None
self.Order = None
self.OnlyShowLatest = None
def _deserialize(self, params):
self.ExportField = params.get("ExportField")
self.Limit = params.get("Limit")
self.Offset = params.get("Offset")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = AssetFilters()
obj._deserialize(item)
self.Filters.append(obj)
self.By = params.get("By")
self.Order = params.get("Order")
self.OnlyShowLatest = params.get("OnlyShowLatest")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeAssetImageRegistryListExportResponse(AbstractModel):
"""DescribeAssetImageRegistryListExport返回参数结构体
"""
def __init__(self):
r"""
:param DownloadUrl: excel文件下载地址
注意:此字段可能返回 null,表示取不到有效值。
:type DownloadUrl: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.DownloadUrl = None
self.RequestId = None
def _deserialize(self, params):
self.DownloadUrl = params.get("DownloadUrl")
self.RequestId = params.get("RequestId")
class DescribeAssetImageRegistryListRequest(AbstractModel):
"""DescribeAssetImageRegistryList请求参数结构体
"""
def __init__(self):
r"""
:param Limit: 需要返回的数量,默认为10,最大值为100
:type Limit: int
:param Offset: 偏移量,默认为0
:type Offset: int
:param Filters: 过滤字段
IsAuthorized是否授权,取值全部all,未授权0,已授权1
:type Filters: list of AssetFilters
:param By: 排序字段
:type By: str
:param Order: 排序方式,asc,desc
:type Order: str
:param OnlyShowLatest: 是否仅展示各repository最新的镜像, 默认为false
:type OnlyShowLatest: bool
"""
self.Limit = None
self.Offset = None
self.Filters = None
self.By = None
self.Order = None
self.OnlyShowLatest = None
def _deserialize(self, params):
self.Limit = params.get("Limit")
self.Offset = params.get("Offset")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = AssetFilters()
obj._deserialize(item)
self.Filters.append(obj)
self.By = params.get("By")
self.Order = params.get("Order")
self.OnlyShowLatest = params.get("OnlyShowLatest")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeAssetImageRegistryListResponse(AbstractModel):
"""DescribeAssetImageRegistryList返回参数结构体
"""
def __init__(self):
r"""
:param List: 镜像仓库列表
注意:此字段可能返回 null,表示取不到有效值。
:type List: list of ImageRepoInfo
:param TotalCount: 总数量
注意:此字段可能返回 null,表示取不到有效值。
:type TotalCount: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.List = None
self.TotalCount = None
self.RequestId = None
def _deserialize(self, params):
if params.get("List") is not None:
self.List = []
for item in params.get("List"):
obj = ImageRepoInfo()
obj._deserialize(item)
self.List.append(obj)
self.TotalCount = params.get("TotalCount")
self.RequestId = params.get("RequestId")
class DescribeAssetImageRegistryRegistryDetailRequest(AbstractModel):
"""DescribeAssetImageRegistryRegistryDetail请求参数结构体
"""
def __init__(self):
r"""
:param RegistryId: 仓库唯一id
:type RegistryId: int
"""
self.RegistryId = None
def _deserialize(self, params):
self.RegistryId = params.get("RegistryId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeAssetImageRegistryRegistryDetailResponse(AbstractModel):
"""DescribeAssetImageRegistryRegistryDetail返回参数结构体
"""
def __init__(self):
r"""
:param Name: 仓库名
:type Name: str
:param Username: 用户名
:type Username: str
:param Password: 密码
:type Password: str
:param Url: 仓库url
:type Url: str
:param RegistryType: 仓库类型,列表:harbor
:type RegistryType: str
:param RegistryVersion: 仓库版本
注意:此字段可能返回 null,表示取不到有效值。
:type RegistryVersion: str
:param NetType: 网络类型,列表:public(公网)
:type NetType: str
:param RegistryRegion: 区域,列表:default(默认)
注意:此字段可能返回 null,表示取不到有效值。
:type RegistryRegion: str
:param SpeedLimit: 限速
注意:此字段可能返回 null,表示取不到有效值。
:type SpeedLimit: int
:param Insecure: 安全模式(证书校验):0(默认) 非安全模式(跳过证书校验):1
注意:此字段可能返回 null,表示取不到有效值。
:type Insecure: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.Name = None
self.Username = None
self.Password = None
self.Url = None
self.RegistryType = None
self.RegistryVersion = None
self.NetType = None
self.RegistryRegion = None
self.SpeedLimit = None
self.Insecure = None
self.RequestId = None
def _deserialize(self, params):
self.Name = params.get("Name")
self.Username = params.get("Username")
self.Password = params.get("Password")
self.Url = params.get("Url")
self.RegistryType = params.get("RegistryType")
self.RegistryVersion = params.get("RegistryVersion")
self.NetType = params.get("NetType")
self.RegistryRegion = params.get("RegistryRegion")
self.SpeedLimit = params.get("SpeedLimit")
self.Insecure = params.get("Insecure")
self.RequestId = params.get("RequestId")
class DescribeAssetImageRegistryRegistryListRequest(AbstractModel):
"""DescribeAssetImageRegistryRegistryList请求参数结构体
"""
class DescribeAssetImageRegistryRegistryListResponse(AbstractModel):
"""DescribeAssetImageRegistryRegistryList返回参数结构体
"""
def __init__(self):
r"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RequestId = None
def _deserialize(self, params):
self.RequestId = params.get("RequestId")
class DescribeAssetImageRegistryRiskInfoListRequest(AbstractModel):
"""DescribeAssetImageRegistryRiskInfoList请求参数结构体
"""
def __init__(self):
r"""
:param Limit: 需要返回的数量,默认为10,最大值为100
:type Limit: int
:param Offset: 偏移量,默认为0。
:type Offset: int
:param Filters: 过滤条件。
<li>Level- String - 是否必填:否 - 漏洞级别筛选,</li>
<li>Name - String - 是否必填:否 - 漏洞名称</li>
:type Filters: list of AssetFilters
:param ImageInfo: 镜像id
:type ImageInfo: :class:`tencentcloud.tcss.v20201101.models.ImageInfo`
:param By: 排序字段(Level)
:type By: str
:param Order: 排序方式 + -
:type Order: str
:param Id: 镜像标识Id
:type Id: int
"""
self.Limit = None
self.Offset = None
self.Filters = None
self.ImageInfo = None
self.By = None
self.Order = None
self.Id = None
def _deserialize(self, params):
self.Limit = params.get("Limit")
self.Offset = params.get("Offset")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = AssetFilters()
obj._deserialize(item)
self.Filters.append(obj)
if params.get("ImageInfo") is not None:
self.ImageInfo = ImageInfo()
self.ImageInfo._deserialize(params.get("ImageInfo"))
self.By = params.get("By")
self.Order = params.get("Order")
self.Id = params.get("Id")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeAssetImageRegistryRiskInfoListResponse(AbstractModel):
"""DescribeAssetImageRegistryRiskInfoList返回参数结构体
"""
def __init__(self):
r"""
:param List: 镜像漏洞列表
注意:此字段可能返回 null,表示取不到有效值。
:type List: list of ImageRisk
:param TotalCount: 总数量
注意:此字段可能返回 null,表示取不到有效值。
:type TotalCount: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.List = None
self.TotalCount = None
self.RequestId = None
def _deserialize(self, params):
if params.get("List") is not None:
self.List = []
for item in params.get("List"):
obj = ImageRisk()
obj._deserialize(item)
self.List.append(obj)
self.TotalCount = params.get("TotalCount")
self.RequestId = params.get("RequestId")
class DescribeAssetImageRegistryRiskListExportRequest(AbstractModel):
"""DescribeAssetImageRegistryRiskListExport请求参数结构体
"""
def __init__(self):
r"""
:param ExportField: 导出字段
:type ExportField: list of str
:param Limit: 需要返回的数量,默认为10,最大值为100
:type Limit: int
:param Offset: 偏移量,默认为0。
:type Offset: int
:param Filters: 过滤条件。
<li>Level- String - 是否必填:否 - 漏洞级别筛选,</li>
<li>Name - String - 是否必填:否 - 漏洞名称</li>
:type Filters: list of AssetFilters
:param ImageInfo: 镜像信息
:type ImageInfo: :class:`tencentcloud.tcss.v20201101.models.ImageInfo`
:param Id: 镜像标识Id
:type Id: int
"""
self.ExportField = None
self.Limit = None
self.Offset = None
self.Filters = None
self.ImageInfo = None
self.Id = None
def _deserialize(self, params):
self.ExportField = params.get("ExportField")
self.Limit = params.get("Limit")
self.Offset = params.get("Offset")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = AssetFilters()
obj._deserialize(item)
self.Filters.append(obj)
if params.get("ImageInfo") is not None:
self.ImageInfo = ImageInfo()
self.ImageInfo._deserialize(params.get("ImageInfo"))
self.Id = params.get("Id")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeAssetImageRegistryRiskListExportResponse(AbstractModel):
"""DescribeAssetImageRegistryRiskListExport返回参数结构体
"""
def __init__(self):
r"""
:param DownloadUrl: excel文件下载地址
注意:此字段可能返回 null,表示取不到有效值。
:type DownloadUrl: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.DownloadUrl = None
self.RequestId = None
def _deserialize(self, params):
self.DownloadUrl = params.get("DownloadUrl")
self.RequestId = params.get("RequestId")
class DescribeAssetImageRegistryScanStatusOneKeyRequest(AbstractModel):
"""DescribeAssetImageRegistryScanStatusOneKey请求参数结构体
"""
def __init__(self):
r"""
:param Images: 需要获取进度的镜像列表
:type Images: list of ImageInfo
:param All: 是否获取全部镜像
:type All: bool
:param Id: 需要获取进度的镜像列表Id
:type Id: list of int non-negative
"""
self.Images = None
self.All = None
self.Id = None
def _deserialize(self, params):
if params.get("Images") is not None:
self.Images = []
for item in params.get("Images"):
obj = ImageInfo()
obj._deserialize(item)
self.Images.append(obj)
self.All = params.get("All")
self.Id = params.get("Id")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeAssetImageRegistryScanStatusOneKeyResponse(AbstractModel):
"""DescribeAssetImageRegistryScanStatusOneKey返回参数结构体
"""
def __init__(self):
r"""
:param ImageTotal: 镜像个数
:type ImageTotal: int
:param ImageScanCnt: 扫描镜像个数
:type ImageScanCnt: int
:param ImageStatus: 扫描进度列表
注意:此字段可能返回 null,表示取不到有效值。
:type ImageStatus: list of ImageProgress
:param SuccessCount: 安全个数
:type SuccessCount: int
:param RiskCount: 风险个数
:type RiskCount: int
:param Schedule: 总的扫描进度
:type Schedule: int
:param Status: 总的扫描状态
:type Status: str
:param ScanRemainTime: 扫描剩余时间
注意:此字段可能返回 null,表示取不到有效值。
:type ScanRemainTime: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.ImageTotal = None
self.ImageScanCnt = None
self.ImageStatus = None
self.SuccessCount = None
self.RiskCount = None
self.Schedule = None
self.Status = None
self.ScanRemainTime = None
self.RequestId = None
def _deserialize(self, params):
self.ImageTotal = params.get("ImageTotal")
self.ImageScanCnt = params.get("ImageScanCnt")
if params.get("ImageStatus") is not None:
self.ImageStatus = []
for item in params.get("ImageStatus"):
obj = ImageProgress()
obj._deserialize(item)
self.ImageStatus.append(obj)
self.SuccessCount = params.get("SuccessCount")
self.RiskCount = params.get("RiskCount")
self.Schedule = params.get("Schedule")
self.Status = params.get("Status")
self.ScanRemainTime = params.get("ScanRemainTime")
self.RequestId = params.get("RequestId")
class DescribeAssetImageRegistrySummaryRequest(AbstractModel):
"""DescribeAssetImageRegistrySummary请求参数结构体
"""
class DescribeAssetImageRegistrySummaryResponse(AbstractModel):
"""DescribeAssetImageRegistrySummary返回参数结构体
"""
def __init__(self):
r"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RequestId = None
def _deserialize(self, params):
self.RequestId = params.get("RequestId")
class DescribeAssetImageRegistryVirusListExportRequest(AbstractModel):
"""DescribeAssetImageRegistryVirusListExport请求参数结构体
"""
def __init__(self):
r"""
:param ExportField: 导出字段
:type ExportField: list of str
:param Limit: 需要返回的数量,默认为10,最大值为100
:type Limit: int
:param Offset: 偏移量,默认为0。
:type Offset: int
:param Filters: 过滤条件。
<li>Level- String - 是否必填:否 - 漏洞级别筛选,</li>
<li>Name - String - 是否必填:否 - 漏洞名称</li>
:type Filters: list of AssetFilters
:param ImageInfo: 镜像信息
:type ImageInfo: :class:`tencentcloud.tcss.v20201101.models.ImageInfo`
:param Id: 镜像标识Id
:type Id: int
"""
self.ExportField = None
self.Limit = None
self.Offset = None
self.Filters = None
self.ImageInfo = None
self.Id = None
def _deserialize(self, params):
self.ExportField = params.get("ExportField")
self.Limit = params.get("Limit")
self.Offset = params.get("Offset")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = AssetFilters()
obj._deserialize(item)
self.Filters.append(obj)
if params.get("ImageInfo") is not None:
self.ImageInfo = ImageInfo()
self.ImageInfo._deserialize(params.get("ImageInfo"))
self.Id = params.get("Id")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeAssetImageRegistryVirusListExportResponse(AbstractModel):
"""DescribeAssetImageRegistryVirusListExport返回参数结构体
"""
def __init__(self):
r"""
:param DownloadUrl: excel文件下载地址
注意:此字段可能返回 null,表示取不到有效值。
:type DownloadUrl: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.DownloadUrl = None
self.RequestId = None
def _deserialize(self, params):
self.DownloadUrl = params.get("DownloadUrl")
self.RequestId = params.get("RequestId")
class DescribeAssetImageRegistryVirusListRequest(AbstractModel):
"""DescribeAssetImageRegistryVirusList请求参数结构体
"""
def __init__(self):
r"""
:param Limit: 需要返回的数量,默认为10,最大值为100
:type Limit: int
:param Offset: 偏移量,默认为0。
:type Offset: int
:param Filters: 过滤条件。
<li>Level- String - 是否必填:否 - 漏洞级别筛选,</li>
<li>Name - String - 是否必填:否 - 漏洞名称</li>
:type Filters: list of AssetFilters
:param ImageInfo: 镜像信息
:type ImageInfo: :class:`tencentcloud.tcss.v20201101.models.ImageInfo`
:param Id: 镜像标识Id
:type Id: int
"""
self.Limit = None
self.Offset = None
self.Filters = None
self.ImageInfo = None
self.Id = None
def _deserialize(self, params):
self.Limit = params.get("Limit")
self.Offset = params.get("Offset")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = AssetFilters()
obj._deserialize(item)
self.Filters.append(obj)
if params.get("ImageInfo") is not None:
self.ImageInfo = ImageInfo()
self.ImageInfo._deserialize(params.get("ImageInfo"))
self.Id = params.get("Id")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeAssetImageRegistryVirusListResponse(AbstractModel):
"""DescribeAssetImageRegistryVirusList返回参数结构体
"""
def __init__(self):
r"""
:param List: 镜像漏洞列表
注意:此字段可能返回 null,表示取不到有效值。
:type List: list of ImageVirus
:param TotalCount: 总数量
注意:此字段可能返回 null,表示取不到有效值。
:type TotalCount: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.List = None
self.TotalCount = None
self.RequestId = None
def _deserialize(self, params):
if params.get("List") is not None:
self.List = []
for item in params.get("List"):
obj = ImageVirus()
obj._deserialize(item)
self.List.append(obj)
self.TotalCount = params.get("TotalCount")
self.RequestId = params.get("RequestId")
class DescribeAssetImageRegistryVulListExportRequest(AbstractModel):
"""DescribeAssetImageRegistryVulListExport请求参数结构体
"""
def __init__(self):
r"""
:param ExportField: 导出字段
:type ExportField: list of str
:param Limit: 需要返回的数量,默认为10,最大值为100
:type Limit: int
:param Offset: 偏移量,默认为0。
:type Offset: int
:param Filters: 过滤条件。
<li>Level- String - 是否必填:否 - 漏洞级别筛选,</li>
<li>Name - String - 是否必填:否 - 漏洞名称</li>
:type Filters: list of AssetFilters
:param ImageInfo: 镜像信息
:type ImageInfo: :class:`tencentcloud.tcss.v20201101.models.ImageInfo`
:param Id: 镜像标识Id
:type Id: int
"""
self.ExportField = None
self.Limit = None
self.Offset = None
self.Filters = None
self.ImageInfo = None
self.Id = None
def _deserialize(self, params):
self.ExportField = params.get("ExportField")
self.Limit = params.get("Limit")
self.Offset = params.get("Offset")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = AssetFilters()
obj._deserialize(item)
self.Filters.append(obj)
if params.get("ImageInfo") is not None:
self.ImageInfo = ImageInfo()
self.ImageInfo._deserialize(params.get("ImageInfo"))
self.Id = params.get("Id")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeAssetImageRegistryVulListExportResponse(AbstractModel):
"""DescribeAssetImageRegistryVulListExport返回参数结构体
"""
def __init__(self):
r"""
:param DownloadUrl: excel文件下载地址
注意:此字段可能返回 null,表示取不到有效值。
:type DownloadUrl: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.DownloadUrl = None
self.RequestId = None
def _deserialize(self, params):
self.DownloadUrl = params.get("DownloadUrl")
self.RequestId = params.get("RequestId")
class DescribeAssetImageRegistryVulListRequest(AbstractModel):
"""DescribeAssetImageRegistryVulList请求参数结构体
"""
def __init__(self):
r"""
:param Limit: 需要返回的数量,默认为10,最大值为100
:type Limit: int
:param Offset: 偏移量,默认为0。
:type Offset: int
:param Filters: 过滤条件。
<li>Level- String - 是否必填:否 - 漏洞级别筛选,</li>
<li>Name - String - 是否必填:否 - 漏洞名称</li>
:type Filters: list of AssetFilters
:param ImageInfo: 镜像信息
:type ImageInfo: :class:`tencentcloud.tcss.v20201101.models.ImageInfo`
:param Id: 镜像标识Id
:type Id: int
"""
self.Limit = None
self.Offset = None
self.Filters = None
self.ImageInfo = None
self.Id = None
def _deserialize(self, params):
self.Limit = params.get("Limit")
self.Offset = params.get("Offset")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = AssetFilters()
obj._deserialize(item)
self.Filters.append(obj)
if params.get("ImageInfo") is not None:
self.ImageInfo = ImageInfo()
self.ImageInfo._deserialize(params.get("ImageInfo"))
self.Id = params.get("Id")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeAssetImageRegistryVulListResponse(AbstractModel):
"""DescribeAssetImageRegistryVulList返回参数结构体
"""
def __init__(self):
r"""
:param List: 镜像漏洞列表
注意:此字段可能返回 null,表示取不到有效值。
:type List: list of ImageVul
:param TotalCount: 总数量
注意:此字段可能返回 null,表示取不到有效值。
:type TotalCount: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.List = None
self.TotalCount = None
self.RequestId = None
def _deserialize(self, params):
if params.get("List") is not None:
self.List = []
for item in params.get("List"):
obj = ImageVul()
obj._deserialize(item)
self.List.append(obj)
self.TotalCount = params.get("TotalCount")
self.RequestId = params.get("RequestId")
class DescribeAssetImageRiskListExportRequest(AbstractModel):
"""DescribeAssetImageRiskListExport请求参数结构体
"""
def __init__(self):
r"""
:param ExportField: 导出字段
:type ExportField: list of str
:param ImageID: 镜像id
:type ImageID: str
:param Filters: 过滤条件。
<li>Level- String - 是否必填:否 - 风险级别 1,2,3,4,</li>
<li>Behavior - String - 是否必填:否 - 风险行为 1,2,3,4</li>
<li>Type - String - 是否必填:否 - 风险类型 1,2,</li>
:type Filters: list of AssetFilters
"""
self.ExportField = None
self.ImageID = None
self.Filters = None
def _deserialize(self, params):
self.ExportField = params.get("ExportField")
self.ImageID = params.get("ImageID")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = AssetFilters()
obj._deserialize(item)
self.Filters.append(obj)
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeAssetImageRiskListExportResponse(AbstractModel):
"""DescribeAssetImageRiskListExport返回参数结构体
"""
def __init__(self):
r"""
:param DownloadUrl: excel文件下载地址
:type DownloadUrl: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.DownloadUrl = None
self.RequestId = None
def _deserialize(self, params):
self.DownloadUrl = params.get("DownloadUrl")
self.RequestId = params.get("RequestId")
class DescribeAssetImageRiskListRequest(AbstractModel):
"""DescribeAssetImageRiskList请求参数结构体
"""
def __init__(self):
r"""
:param ImageID: 镜像id
:type ImageID: str
:param Limit: 需要返回的数量,默认为10,最大值为100
:type Limit: int
:param Offset: 偏移量,默认为0。
:type Offset: int
:param Filters: 过滤条件。
<li>Level- String - 是否必填:否 - 风险级别 1,2,3,4,</li>
<li>Behavior - String - 是否必填:否 - 风险行为 1,2,3,4</li>
<li>Type - String - 是否必填:否 - 风险类型 1,2,</li>
:type Filters: list of AssetFilters
:param By: 排序字段
:type By: str
:param Order: 排序方式
:type Order: str
"""
self.ImageID = None
self.Limit = None
self.Offset = None
self.Filters = None
self.By = None
self.Order = None
def _deserialize(self, params):
self.ImageID = params.get("ImageID")
self.Limit = params.get("Limit")
self.Offset = params.get("Offset")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = AssetFilters()
obj._deserialize(item)
self.Filters.append(obj)
self.By = params.get("By")
self.Order = params.get("Order")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeAssetImageRiskListResponse(AbstractModel):
"""DescribeAssetImageRiskList返回参数结构体
"""
def __init__(self):
r"""
:param List: 镜像病毒列表
:type List: list of ImageRiskInfo
:param TotalCount: 总数量
:type TotalCount: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.List = None
self.TotalCount = None
self.RequestId = None
def _deserialize(self, params):
if params.get("List") is not None:
self.List = []
for item in params.get("List"):
obj = ImageRiskInfo()
obj._deserialize(item)
self.List.append(obj)
self.TotalCount = params.get("TotalCount")
self.RequestId = params.get("RequestId")
class DescribeAssetImageScanSettingRequest(AbstractModel):
"""DescribeAssetImageScanSetting请求参数结构体
"""
class DescribeAssetImageScanSettingResponse(AbstractModel):
"""DescribeAssetImageScanSetting返回参数结构体
"""
def __init__(self):
r"""
:param Enable: 开关
:type Enable: bool
:param ScanTime: 扫描时刻(完整时间;后端按0时区解析时分秒)
:type ScanTime: str
:param ScanPeriod: 扫描间隔
:type ScanPeriod: int
:param ScanVirus: 扫描木马
:type ScanVirus: bool
:param ScanRisk: 扫描敏感信息
:type ScanRisk: bool
:param ScanVul: 扫描漏洞
:type ScanVul: bool
:param All: 扫描全部镜像
:type All: bool
:param Images: 自定义扫描镜像
:type Images: list of str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.Enable = None
self.ScanTime = None
self.ScanPeriod = None
self.ScanVirus = None
self.ScanRisk = None
self.ScanVul = None
self.All = None
self.Images = None
self.RequestId = None
def _deserialize(self, params):
self.Enable = params.get("Enable")
self.ScanTime = params.get("ScanTime")
self.ScanPeriod = params.get("ScanPeriod")
self.ScanVirus = params.get("ScanVirus")
self.ScanRisk = params.get("ScanRisk")
self.ScanVul = params.get("ScanVul")
self.All = params.get("All")
self.Images = params.get("Images")
self.RequestId = params.get("RequestId")
class DescribeAssetImageScanStatusRequest(AbstractModel):
"""DescribeAssetImageScanStatus请求参数结构体
"""
def __init__(self):
r"""
:param TaskID: 任务id
:type TaskID: str
"""
self.TaskID = None
def _deserialize(self, params):
self.TaskID = params.get("TaskID")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeAssetImageScanStatusResponse(AbstractModel):
"""DescribeAssetImageScanStatus返回参数结构体
"""
def __init__(self):
r"""
:param ImageTotal: 镜像个数
:type ImageTotal: int
:param ImageScanCnt: 扫描镜像个数
:type ImageScanCnt: int
:param Status: 扫描状态
:type Status: str
:param Schedule: 扫描进度 ImageScanCnt/ImageTotal *100
:type Schedule: int
:param SuccessCount: 安全个数
:type SuccessCount: int
:param RiskCount: 风险个数
:type RiskCount: int
:param LeftSeconds: 剩余扫描时间
:type LeftSeconds: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.ImageTotal = None
self.ImageScanCnt = None
self.Status = None
self.Schedule = None
self.SuccessCount = None
self.RiskCount = None
self.LeftSeconds = None
self.RequestId = None
def _deserialize(self, params):
self.ImageTotal = params.get("ImageTotal")
self.ImageScanCnt = params.get("ImageScanCnt")
self.Status = params.get("Status")
self.Schedule = params.get("Schedule")
self.SuccessCount = params.get("SuccessCount")
self.RiskCount = params.get("RiskCount")
self.LeftSeconds = params.get("LeftSeconds")
self.RequestId = params.get("RequestId")
class DescribeAssetImageScanTaskRequest(AbstractModel):
"""DescribeAssetImageScanTask请求参数结构体
"""
class DescribeAssetImageScanTaskResponse(AbstractModel):
"""DescribeAssetImageScanTask返回参数结构体
"""
def __init__(self):
r"""
:param TaskID: 任务id
:type TaskID: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.TaskID = None
self.RequestId = None
def _deserialize(self, params):
self.TaskID = params.get("TaskID")
self.RequestId = params.get("RequestId")
class DescribeAssetImageSimpleListRequest(AbstractModel):
"""DescribeAssetImageSimpleList请求参数结构体
"""
def __init__(self):
r"""
:param Limit: 需要返回的数量,默认为10,最大值为100
:type Limit: int
:param Offset: 偏移量,默认为0。
:type Offset: int
:param Filters: 过滤条件。
<li>Keywords- String - 是否必填:否 - 镜像名、镜像id 称筛选,</li>
:type Filters: list of AssetFilters
:param By: 排序字段
:type By: str
:param Order: 排序方式 asc,desc
:type Order: str
"""
self.Limit = None
self.Offset = None
self.Filters = None
self.By = None
self.Order = None
def _deserialize(self, params):
self.Limit = params.get("Limit")
self.Offset = params.get("Offset")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = AssetFilters()
obj._deserialize(item)
self.Filters.append(obj)
self.By = params.get("By")
self.Order = params.get("Order")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeAssetImageSimpleListResponse(AbstractModel):
"""DescribeAssetImageSimpleList返回参数结构体
"""
def __init__(self):
r"""
:param List: 镜像列表
:type List: list of AssetSimpleImageInfo
:param TotalCount: 总数量
:type TotalCount: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.List = None
self.TotalCount = None
self.RequestId = None
def _deserialize(self, params):
if params.get("List") is not None:
self.List = []
for item in params.get("List"):
obj = AssetSimpleImageInfo()
obj._deserialize(item)
self.List.append(obj)
self.TotalCount = params.get("TotalCount")
self.RequestId = params.get("RequestId")
class DescribeAssetImageVirusListExportRequest(AbstractModel):
"""DescribeAssetImageVirusListExport请求参数结构体
"""
def __init__(self):
r"""
:param ExportField: 列表支持字段
:type ExportField: list of str
:param ImageID: 镜像id
:type ImageID: str
:param Filters: 过滤条件。
<li>Name- String - 是否必填:否 - 镜像名称筛选,</li>
<li>RiskLevel - String - 是否必填:否 - 风险等级 1,2,3,4</li>
:type Filters: list of AssetFilters
"""
self.ExportField = None
self.ImageID = None
self.Filters = None
def _deserialize(self, params):
self.ExportField = params.get("ExportField")
self.ImageID = params.get("ImageID")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = AssetFilters()
obj._deserialize(item)
self.Filters.append(obj)
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeAssetImageVirusListExportResponse(AbstractModel):
"""DescribeAssetImageVirusListExport返回参数结构体
"""
def __init__(self):
r"""
:param DownloadUrl: excel文件下载地址
:type DownloadUrl: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.DownloadUrl = None
self.RequestId = None
def _deserialize(self, params):
self.DownloadUrl = params.get("DownloadUrl")
self.RequestId = params.get("RequestId")
class DescribeAssetImageVirusListRequest(AbstractModel):
"""DescribeAssetImageVirusList请求参数结构体
"""
def __init__(self):
r"""
:param ImageID: 镜像id
:type ImageID: str
:param Limit: 需要返回的数量,默认为10,最大值为100
:type Limit: int
:param Offset: 偏移量,默认为0。
:type Offset: int
:param Filters: 过滤条件。
<li>Name- String - 是否必填:否 - 镜像名称筛选,</li>
<li>RiskLevel - String - 是否必填:否 - 风险等级 1,2,3,4</li>
:type Filters: list of AssetFilters
:param Order: 排序 asc desc
:type Order: str
:param By: 排序字段
:type By: str
"""
self.ImageID = None
self.Limit = None
self.Offset = None
self.Filters = None
self.Order = None
self.By = None
def _deserialize(self, params):
self.ImageID = params.get("ImageID")
self.Limit = params.get("Limit")
self.Offset = params.get("Offset")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = AssetFilters()
obj._deserialize(item)
self.Filters.append(obj)
self.Order = params.get("Order")
self.By = params.get("By")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeAssetImageVirusListResponse(AbstractModel):
"""DescribeAssetImageVirusList返回参数结构体
"""
def __init__(self):
r"""
:param List: 镜像病毒列表
:type List: list of ImageVirusInfo
:param TotalCount: 总数量
:type TotalCount: int
:param VirusScanStatus: 病毒扫描状态
0:未扫描
1:扫描中
2:扫描完成
3:扫描出错
4:扫描取消
:type VirusScanStatus: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.List = None
self.TotalCount = None
self.VirusScanStatus = None
self.RequestId = None
def _deserialize(self, params):
if params.get("List") is not None:
self.List = []
for item in params.get("List"):
obj = ImageVirusInfo()
obj._deserialize(item)
self.List.append(obj)
self.TotalCount = params.get("TotalCount")
self.VirusScanStatus = params.get("VirusScanStatus")
self.RequestId = params.get("RequestId")
class DescribeAssetImageVulListExportRequest(AbstractModel):
"""DescribeAssetImageVulListExport请求参数结构体
"""
def __init__(self):
r"""
:param ExportField: 导出字段
:type ExportField: list of str
:param ImageID: 镜像id
:type ImageID: str
:param Limit: 需要返回的数量,默认为10,最大值为100
:type Limit: int
:param Offset: 偏移量,默认为0。
:type Offset: int
:param Filters: 过滤条件。
<li>Name- String - 是否必填:否 - 漏洞名称名称筛选,</li>
<li>Level - String - 是否必填:否 - 风险等级 1,2,3,4</li>
:type Filters: list of AssetFilters
"""
self.ExportField = None
self.ImageID = None
self.Limit = None
self.Offset = None
self.Filters = None
def _deserialize(self, params):
self.ExportField = params.get("ExportField")
self.ImageID = params.get("ImageID")
self.Limit = params.get("Limit")
self.Offset = params.get("Offset")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = AssetFilters()
obj._deserialize(item)
self.Filters.append(obj)
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeAssetImageVulListExportResponse(AbstractModel):
"""DescribeAssetImageVulListExport返回参数结构体
"""
def __init__(self):
r"""
:param DownloadUrl: excel文件下载地址
:type DownloadUrl: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.DownloadUrl = None
self.RequestId = None
def _deserialize(self, params):
self.DownloadUrl = params.get("DownloadUrl")
self.RequestId = params.get("RequestId")
class DescribeAssetImageVulListRequest(AbstractModel):
"""DescribeAssetImageVulList请求参数结构体
"""
def __init__(self):
r"""
:param ImageID: 镜像id
:type ImageID: str
:param Limit: 需要返回的数量,默认为10,最大值为100
:type Limit: int
:param Offset: 偏移量,默认为0。
:type Offset: int
:param Filters: 过滤条件。
<li>Name- String - 是否必填:否 - 漏洞名称名称筛选,</li>
<li>Level - String - 是否必填:否 - 风险等级 1,2,3,4</li>
:type Filters: list of AssetFilters
:param By: 排序字段(Level)
:type By: str
:param Order: 排序方式 + -
:type Order: str
"""
self.ImageID = None
self.Limit = None
self.Offset = None
self.Filters = None
self.By = None
self.Order = None
def _deserialize(self, params):
self.ImageID = params.get("ImageID")
self.Limit = params.get("Limit")
self.Offset = params.get("Offset")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = AssetFilters()
obj._deserialize(item)
self.Filters.append(obj)
self.By = params.get("By")
self.Order = params.get("Order")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeAssetImageVulListResponse(AbstractModel):
"""DescribeAssetImageVulList返回参数结构体
"""
def __init__(self):
r"""
:param List: 镜像漏洞列表
:type List: list of ImagesVul
:param TotalCount: 总数量
:type TotalCount: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.List = None
self.TotalCount = None
self.RequestId = None
def _deserialize(self, params):
if params.get("List") is not None:
self.List = []
for item in params.get("List"):
obj = ImagesVul()
obj._deserialize(item)
self.List.append(obj)
self.TotalCount = params.get("TotalCount")
self.RequestId = params.get("RequestId")
class DescribeAssetPortListRequest(AbstractModel):
"""DescribeAssetPortList请求参数结构体
"""
def __init__(self):
r"""
:param Limit: 需要返回的数量,默认为10,最大值为100
:type Limit: int
:param Offset: 偏移量,默认为0。
:type Offset: int
:param Filters: 过滤条件。
<li>All - String - 是否必填:否 - 模糊查询可选字段</li>
<li>RunAs - String - 是否必填:否 - 运行用户筛选,</li>
<li>ContainerID - String - 是否必填:否 - 容器id</li>
<li>HostID- String - 是否必填:是 - 主机id</li>
<li>HostIP- string - 是否必填:否 - 主机ip搜索</li>
<li>ProcessName- string - 是否必填:否 - 进程名搜索</li>
:type Filters: list of AssetFilters
"""
self.Limit = None
self.Offset = None
self.Filters = None
def _deserialize(self, params):
self.Limit = params.get("Limit")
self.Offset = params.get("Offset")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = AssetFilters()
obj._deserialize(item)
self.Filters.append(obj)
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeAssetPortListResponse(AbstractModel):
"""DescribeAssetPortList返回参数结构体
"""
def __init__(self):
r"""
:param List: 端口列表
:type List: list of PortInfo
:param TotalCount: 总数量
:type TotalCount: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.List = None
self.TotalCount = None
self.RequestId = None
def _deserialize(self, params):
if params.get("List") is not None:
self.List = []
for item in params.get("List"):
obj = PortInfo()
obj._deserialize(item)
self.List.append(obj)
self.TotalCount = params.get("TotalCount")
self.RequestId = params.get("RequestId")
class DescribeAssetProcessListRequest(AbstractModel):
"""DescribeAssetProcessList请求参数结构体
"""
def __init__(self):
r"""
:param Limit: 需要返回的数量,默认为10,最大值为100
:type Limit: int
:param Offset: 偏移量,默认为0。
:type Offset: int
:param Filters: 过滤条件。
<li>RunAs - String - 是否必填:否 - 运行用户筛选,</li>
<li>ContainerID - String - 是否必填:否 - 容器id</li>
<li>HostID- String - 是否必填:是 - 主机id</li>
<li>HostIP- string - 是否必填:否 - 主机ip搜索</li>
<li>ProcessName- string - 是否必填:否 - 进程名搜索</li>
<li>Pid- string - 是否必填:否 - 进程id搜索(关联进程)</li>
:type Filters: list of AssetFilters
"""
self.Limit = None
self.Offset = None
self.Filters = None
def _deserialize(self, params):
self.Limit = params.get("Limit")
self.Offset = params.get("Offset")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = AssetFilters()
obj._deserialize(item)
self.Filters.append(obj)
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeAssetProcessListResponse(AbstractModel):
"""DescribeAssetProcessList返回参数结构体
"""
def __init__(self):
r"""
:param List: 端口列表
:type List: list of ProcessInfo
:param TotalCount: 总数量
:type TotalCount: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.List = None
self.TotalCount = None
self.RequestId = None
def _deserialize(self, params):
if params.get("List") is not None:
self.List = []
for item in params.get("List"):
obj = ProcessInfo()
obj._deserialize(item)
self.List.append(obj)
self.TotalCount = params.get("TotalCount")
self.RequestId = params.get("RequestId")
class DescribeAssetSummaryRequest(AbstractModel):
"""DescribeAssetSummary请求参数结构体
"""
class DescribeAssetSummaryResponse(AbstractModel):
"""DescribeAssetSummary返回参数结构体
"""
def __init__(self):
r"""
:param AppCnt: 应用个数
:type AppCnt: int
:param ContainerCnt: 容器个数
:type ContainerCnt: int
:param ContainerPause: 暂停的容器个数
:type ContainerPause: int
:param ContainerRunning: 运行的容器个数
:type ContainerRunning: int
:param ContainerStop: 停止运行的容器个数
:type ContainerStop: int
:param CreateTime: 创建时间
:type CreateTime: str
:param DbCnt: 数据库个数
:type DbCnt: int
:param ImageCnt: 镜像个数
:type ImageCnt: int
:param HostOnline: 主机在线个数
:type HostOnline: int
:param HostCnt: 主机个数
:type HostCnt: int
:param ImageHasRiskInfoCnt: 有风险的镜像个数
:type ImageHasRiskInfoCnt: int
:param ImageHasVirusCnt: 有病毒的镜像个数
:type ImageHasVirusCnt: int
:param ImageHasVulsCnt: 有漏洞的镜像个数
:type ImageHasVulsCnt: int
:param ImageUntrustCnt: 不受信任的镜像个数
:type ImageUntrustCnt: int
:param ListenPortCnt: 监听的端口个数
:type ListenPortCnt: int
:param ProcessCnt: 进程个数
:type ProcessCnt: int
:param WebServiceCnt: web服务个数
:type WebServiceCnt: int
:param LatestImageScanTime: 最近镜像扫描时间
:type LatestImageScanTime: str
:param ImageUnsafeCnt: 风险镜像个数
:type ImageUnsafeCnt: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.AppCnt = None
self.ContainerCnt = None
self.ContainerPause = None
self.ContainerRunning = None
self.ContainerStop = None
self.CreateTime = None
self.DbCnt = None
self.ImageCnt = None
self.HostOnline = None
self.HostCnt = None
self.ImageHasRiskInfoCnt = None
self.ImageHasVirusCnt = None
self.ImageHasVulsCnt = None
self.ImageUntrustCnt = None
self.ListenPortCnt = None
self.ProcessCnt = None
self.WebServiceCnt = None
self.LatestImageScanTime = None
self.ImageUnsafeCnt = None
self.RequestId = None
def _deserialize(self, params):
self.AppCnt = params.get("AppCnt")
self.ContainerCnt = params.get("ContainerCnt")
self.ContainerPause = params.get("ContainerPause")
self.ContainerRunning = params.get("ContainerRunning")
self.ContainerStop = params.get("ContainerStop")
self.CreateTime = params.get("CreateTime")
self.DbCnt = params.get("DbCnt")
self.ImageCnt = params.get("ImageCnt")
self.HostOnline = params.get("HostOnline")
self.HostCnt = params.get("HostCnt")
self.ImageHasRiskInfoCnt = params.get("ImageHasRiskInfoCnt")
self.ImageHasVirusCnt = params.get("ImageHasVirusCnt")
self.ImageHasVulsCnt = params.get("ImageHasVulsCnt")
self.ImageUntrustCnt = params.get("ImageUntrustCnt")
self.ListenPortCnt = params.get("ListenPortCnt")
self.ProcessCnt = params.get("ProcessCnt")
self.WebServiceCnt = params.get("WebServiceCnt")
self.LatestImageScanTime = params.get("LatestImageScanTime")
self.ImageUnsafeCnt = params.get("ImageUnsafeCnt")
self.RequestId = params.get("RequestId")
class DescribeAssetWebServiceListRequest(AbstractModel):
"""DescribeAssetWebServiceList请求参数结构体
"""
def __init__(self):
r"""
:param Limit: 需要返回的数量,默认为10,最大值为100
:type Limit: int
:param Offset: 偏移量,默认为0。
:type Offset: int
:param Filters: 过滤条件。
<li>Keywords- String - 是否必填:否 - 模糊查询可选字段</li>
<li>Type- String - 是否必填:否 - 主机运行状态筛选,"Apache"
"Jboss"
"lighttpd"
"Nginx"
"Tomcat"</li>
:type Filters: list of AssetFilters
"""
self.Limit = None
self.Offset = None
self.Filters = None
def _deserialize(self, params):
self.Limit = params.get("Limit")
self.Offset = params.get("Offset")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = AssetFilters()
obj._deserialize(item)
self.Filters.append(obj)
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeAssetWebServiceListResponse(AbstractModel):
"""DescribeAssetWebServiceList返回参数结构体
"""
def __init__(self):
r"""
:param List: 主机列表
:type List: list of ServiceInfo
:param TotalCount: 总数量
:type TotalCount: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.List = None
self.TotalCount = None
self.RequestId = None
def _deserialize(self, params):
if params.get("List") is not None:
self.List = []
for item in params.get("List"):
obj = ServiceInfo()
obj._deserialize(item)
self.List.append(obj)
self.TotalCount = params.get("TotalCount")
self.RequestId = params.get("RequestId")
class DescribeCheckItemListRequest(AbstractModel):
"""DescribeCheckItemList请求参数结构体
"""
def __init__(self):
r"""
:param Offset: 偏移量
:type Offset: int
:param Limit: 每次查询的最大记录数量
:type Limit: int
:param Filters: Name 可取值:risk_level风险等级, risk_target检查对象,风险对象,risk_type风险类别,risk_attri检测项所属的风险类型
:type Filters: list of ComplianceFilters
"""
self.Offset = None
self.Limit = None
self.Filters = None
def _deserialize(self, params):
self.Offset = params.get("Offset")
self.Limit = params.get("Limit")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = ComplianceFilters()
obj._deserialize(item)
self.Filters.append(obj)
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeCheckItemListResponse(AbstractModel):
"""DescribeCheckItemList返回参数结构体
"""
def __init__(self):
r"""
:param ClusterCheckItems: 检查项详情数组
:type ClusterCheckItems: list of ClusterCheckItem
:param TotalCount: 检查项总数
:type TotalCount: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.ClusterCheckItems = None
self.TotalCount = None
self.RequestId = None
def _deserialize(self, params):
if params.get("ClusterCheckItems") is not None:
self.ClusterCheckItems = []
for item in params.get("ClusterCheckItems"):
obj = ClusterCheckItem()
obj._deserialize(item)
self.ClusterCheckItems.append(obj)
self.TotalCount = params.get("TotalCount")
self.RequestId = params.get("RequestId")
class DescribeClusterDetailRequest(AbstractModel):
"""DescribeClusterDetail请求参数结构体
"""
def __init__(self):
r"""
:param ClusterId: 集群id
:type ClusterId: str
"""
self.ClusterId = None
def _deserialize(self, params):
self.ClusterId = params.get("ClusterId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeClusterDetailResponse(AbstractModel):
"""DescribeClusterDetail返回参数结构体
"""
def __init__(self):
r"""
:param ClusterId: 集群id
:type ClusterId: str
:param ClusterName: 集群名字
:type ClusterName: str
:param ScanTaskProgress: 当前集群扫描任务的进度,100表示扫描完成.
:type ScanTaskProgress: int
:param ClusterVersion: 集群版本
:type ClusterVersion: str
:param ContainerRuntime: 运行时组件
:type ContainerRuntime: str
:param ClusterNodeNum: 集群节点数
:type ClusterNodeNum: int
:param ClusterStatus: 集群状态 (Running 运行中 Creating 创建中 Abnormal 异常 )
:type ClusterStatus: str
:param ClusterType: 集群类型:为托管集群MANAGED_CLUSTER、独立集群INDEPENDENT_CLUSTER
:type ClusterType: str
:param Region: 集群区域
:type Region: str
:param SeriousRiskCount: 严重风险检查项的数量
:type SeriousRiskCount: int
:param HighRiskCount: 高风险检查项的数量
:type HighRiskCount: int
:param MiddleRiskCount: 中风险检查项的数量
:type MiddleRiskCount: int
:param HintRiskCount: 提示风险检查项的数量
:type HintRiskCount: int
:param CheckStatus: 检查任务的状态
:type CheckStatus: str
:param DefenderStatus: 防御容器状态
:type DefenderStatus: str
:param TaskCreateTime: 扫描任务创建时间
:type TaskCreateTime: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.ClusterId = None
self.ClusterName = None
self.ScanTaskProgress = None
self.ClusterVersion = None
self.ContainerRuntime = None
self.ClusterNodeNum = None
self.ClusterStatus = None
self.ClusterType = None
self.Region = None
self.SeriousRiskCount = None
self.HighRiskCount = None
self.MiddleRiskCount = None
self.HintRiskCount = None
self.CheckStatus = None
self.DefenderStatus = None
self.TaskCreateTime = None
self.RequestId = None
def _deserialize(self, params):
self.ClusterId = params.get("ClusterId")
self.ClusterName = params.get("ClusterName")
self.ScanTaskProgress = params.get("ScanTaskProgress")
self.ClusterVersion = params.get("ClusterVersion")
self.ContainerRuntime = params.get("ContainerRuntime")
self.ClusterNodeNum = params.get("ClusterNodeNum")
self.ClusterStatus = params.get("ClusterStatus")
self.ClusterType = params.get("ClusterType")
self.Region = params.get("Region")
self.SeriousRiskCount = params.get("SeriousRiskCount")
self.HighRiskCount = params.get("HighRiskCount")
self.MiddleRiskCount = params.get("MiddleRiskCount")
self.HintRiskCount = params.get("HintRiskCount")
self.CheckStatus = params.get("CheckStatus")
self.DefenderStatus = params.get("DefenderStatus")
self.TaskCreateTime = params.get("TaskCreateTime")
self.RequestId = params.get("RequestId")
class DescribeClusterSummaryRequest(AbstractModel):
"""DescribeClusterSummary请求参数结构体
"""
class DescribeClusterSummaryResponse(AbstractModel):
"""DescribeClusterSummary返回参数结构体
"""
def __init__(self):
r"""
:param TotalCount: 集群总数
:type TotalCount: int
:param RiskClusterCount: 有风险的集群数量
:type RiskClusterCount: int
:param UncheckClusterCount: 未检查的集群数量
:type UncheckClusterCount: int
:param ManagedClusterCount: 托管集群数量
:type ManagedClusterCount: int
:param IndependentClusterCount: 独立集群数量
:type IndependentClusterCount: int
:param NoRiskClusterCount: 无风险的集群数量
:type NoRiskClusterCount: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.TotalCount = None
self.RiskClusterCount = None
self.UncheckClusterCount = None
self.ManagedClusterCount = None
self.IndependentClusterCount = None
self.NoRiskClusterCount = None
self.RequestId = None
def _deserialize(self, params):
self.TotalCount = params.get("TotalCount")
self.RiskClusterCount = params.get("RiskClusterCount")
self.UncheckClusterCount = params.get("UncheckClusterCount")
self.ManagedClusterCount = params.get("ManagedClusterCount")
self.IndependentClusterCount = params.get("IndependentClusterCount")
self.NoRiskClusterCount = params.get("NoRiskClusterCount")
self.RequestId = params.get("RequestId")
class DescribeComplianceAssetDetailInfoRequest(AbstractModel):
"""DescribeComplianceAssetDetailInfo请求参数结构体
"""
def __init__(self):
r"""
:param CustomerAssetId: 客户资产ID。
:type CustomerAssetId: int
"""
self.CustomerAssetId = None
def _deserialize(self, params):
self.CustomerAssetId = params.get("CustomerAssetId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeComplianceAssetDetailInfoResponse(AbstractModel):
"""DescribeComplianceAssetDetailInfo返回参数结构体
"""
def __init__(self):
r"""
:param AssetDetailInfo: 某资产的详情。
:type AssetDetailInfo: :class:`tencentcloud.tcss.v20201101.models.ComplianceAssetDetailInfo`
:param ContainerDetailInfo: 当资产为容器时,返回此字段。
注意:此字段可能返回 null,表示取不到有效值。
:type ContainerDetailInfo: :class:`tencentcloud.tcss.v20201101.models.ComplianceContainerDetailInfo`
:param ImageDetailInfo: 当资产为镜像时,返回此字段。
注意:此字段可能返回 null,表示取不到有效值。
:type ImageDetailInfo: :class:`tencentcloud.tcss.v20201101.models.ComplianceImageDetailInfo`
:param HostDetailInfo: 当资产为主机时,返回此字段。
注意:此字段可能返回 null,表示取不到有效值。
:type HostDetailInfo: :class:`tencentcloud.tcss.v20201101.models.ComplianceHostDetailInfo`
:param K8SDetailInfo: 当资产为K8S时,返回此字段。
注意:此字段可能返回 null,表示取不到有效值。
:type K8SDetailInfo: :class:`tencentcloud.tcss.v20201101.models.ComplianceK8SDetailInfo`
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.AssetDetailInfo = None
self.ContainerDetailInfo = None
self.ImageDetailInfo = None
self.HostDetailInfo = None
self.K8SDetailInfo = None
self.RequestId = None
def _deserialize(self, params):
if params.get("AssetDetailInfo") is not None:
self.AssetDetailInfo = ComplianceAssetDetailInfo()
self.AssetDetailInfo._deserialize(params.get("AssetDetailInfo"))
if params.get("ContainerDetailInfo") is not None:
self.ContainerDetailInfo = ComplianceContainerDetailInfo()
self.ContainerDetailInfo._deserialize(params.get("ContainerDetailInfo"))
if params.get("ImageDetailInfo") is not None:
self.ImageDetailInfo = ComplianceImageDetailInfo()
self.ImageDetailInfo._deserialize(params.get("ImageDetailInfo"))
if params.get("HostDetailInfo") is not None:
self.HostDetailInfo = ComplianceHostDetailInfo()
self.HostDetailInfo._deserialize(params.get("HostDetailInfo"))
if params.get("K8SDetailInfo") is not None:
self.K8SDetailInfo = ComplianceK8SDetailInfo()
self.K8SDetailInfo._deserialize(params.get("K8SDetailInfo"))
self.RequestId = params.get("RequestId")
class DescribeComplianceAssetListRequest(AbstractModel):
"""DescribeComplianceAssetList请求参数结构体
"""
def __init__(self):
r"""
:param AssetTypeSet: 资产类型列表。
:type AssetTypeSet: list of str
:param Offset: 起始偏移量,默认为0。
:type Offset: int
:param Limit: 返回的数据量,默认为10,最大为100。
:type Limit: int
:param Filters: 查询过滤器
:type Filters: list of ComplianceFilters
"""
self.AssetTypeSet = None
self.Offset = None
self.Limit = None
self.Filters = None
def _deserialize(self, params):
self.AssetTypeSet = params.get("AssetTypeSet")
self.Offset = params.get("Offset")
self.Limit = params.get("Limit")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = ComplianceFilters()
obj._deserialize(item)
self.Filters.append(obj)
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeComplianceAssetListResponse(AbstractModel):
"""DescribeComplianceAssetList返回参数结构体
"""
def __init__(self):
r"""
:param TotalCount: 返回资产的总数。
:type TotalCount: int
:param AssetInfoList: 返回各类资产的列表。
注意:此字段可能返回 null,表示取不到有效值。
:type AssetInfoList: list of ComplianceAssetInfo
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.TotalCount = None
self.AssetInfoList = None
self.RequestId = None
def _deserialize(self, params):
self.TotalCount = params.get("TotalCount")
if params.get("AssetInfoList") is not None:
self.AssetInfoList = []
for item in params.get("AssetInfoList"):
obj = ComplianceAssetInfo()
obj._deserialize(item)
self.AssetInfoList.append(obj)
self.RequestId = params.get("RequestId")
class DescribeComplianceAssetPolicyItemListRequest(AbstractModel):
"""DescribeComplianceAssetPolicyItemList请求参数结构体
"""
def __init__(self):
r"""
:param CustomerAssetId: 客户资产的ID。
:type CustomerAssetId: int
:param Offset: 起始偏移量,默认为0。
:type Offset: int
:param Limit: 要获取的数据量,默认为10,最大为100。
:type Limit: int
:param Filters: 过滤器列表。Name字段支持
RiskLevel
:type Filters: list of ComplianceFilters
"""
self.CustomerAssetId = None
self.Offset = None
self.Limit = None
self.Filters = None
def _deserialize(self, params):
self.CustomerAssetId = params.get("CustomerAssetId")
self.Offset = params.get("Offset")
self.Limit = params.get("Limit")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = ComplianceFilters()
obj._deserialize(item)
self.Filters.append(obj)
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeComplianceAssetPolicyItemListResponse(AbstractModel):
"""DescribeComplianceAssetPolicyItemList返回参数结构体
"""
def __init__(self):
r"""
:param TotalCount: 返回检测项的总数。如果用户未启用基线检查,此处返回0。
:type TotalCount: int
:param AssetPolicyItemList: 返回某个资产下的检测项的列表。
:type AssetPolicyItemList: list of ComplianceAssetPolicyItem
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.TotalCount = None
self.AssetPolicyItemList = None
self.RequestId = None
def _deserialize(self, params):
self.TotalCount = params.get("TotalCount")
if params.get("AssetPolicyItemList") is not None:
self.AssetPolicyItemList = []
for item in params.get("AssetPolicyItemList"):
obj = ComplianceAssetPolicyItem()
obj._deserialize(item)
self.AssetPolicyItemList.append(obj)
self.RequestId = params.get("RequestId")
class DescribeCompliancePeriodTaskListRequest(AbstractModel):
"""DescribeCompliancePeriodTaskList请求参数结构体
"""
def __init__(self):
r"""
:param AssetType: 资产的类型,取值为:
ASSET_CONTAINER, 容器
ASSET_IMAGE, 镜像
ASSET_HOST, 主机
ASSET_K8S, K8S资产
:type AssetType: str
:param Offset: 偏移量,默认为0。
:type Offset: int
:param Limit: 需要返回的数量,默认为10,最大值为100。
:type Limit: int
"""
self.AssetType = None
self.Offset = None
self.Limit = None
def _deserialize(self, params):
self.AssetType = params.get("AssetType")
self.Offset = params.get("Offset")
self.Limit = params.get("Limit")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeCompliancePeriodTaskListResponse(AbstractModel):
"""DescribeCompliancePeriodTaskList返回参数结构体
"""
def __init__(self):
r"""
:param TotalCount: 定时任务的总量。
:type TotalCount: int
:param PeriodTaskSet: 定时任务信息的列表
:type PeriodTaskSet: list of CompliancePeriodTask
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.TotalCount = None
self.PeriodTaskSet = None
self.RequestId = None
def _deserialize(self, params):
self.TotalCount = params.get("TotalCount")
if params.get("PeriodTaskSet") is not None:
self.PeriodTaskSet = []
for item in params.get("PeriodTaskSet"):
obj = CompliancePeriodTask()
obj._deserialize(item)
self.PeriodTaskSet.append(obj)
self.RequestId = params.get("RequestId")
class DescribeCompliancePolicyItemAffectedAssetListRequest(AbstractModel):
"""DescribeCompliancePolicyItemAffectedAssetList请求参数结构体
"""
def __init__(self):
r"""
:param CustomerPolicyItemId: DescribeComplianceTaskPolicyItemSummaryList返回的CustomerPolicyItemId,表示检测项的ID。
:type CustomerPolicyItemId: int
:param Offset: 起始偏移量,默认为0。
:type Offset: int
:param Limit: 需要返回的数量,默认为10,最大值为100。
:type Limit: int
:param Filters: 过滤条件。
Name - String
Name 可取值:NodeName, CheckResult
:type Filters: list of ComplianceFilters
"""
self.CustomerPolicyItemId = None
self.Offset = None
self.Limit = None
self.Filters = None
def _deserialize(self, params):
self.CustomerPolicyItemId = params.get("CustomerPolicyItemId")
self.Offset = params.get("Offset")
self.Limit = params.get("Limit")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = ComplianceFilters()
obj._deserialize(item)
self.Filters.append(obj)
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeCompliancePolicyItemAffectedAssetListResponse(AbstractModel):
"""DescribeCompliancePolicyItemAffectedAssetList返回参数结构体
"""
def __init__(self):
r"""
:param AffectedAssetList: 返回各检测项所影响的资产的列表。
:type AffectedAssetList: list of ComplianceAffectedAsset
:param TotalCount: 检测项影响的资产的总数。
:type TotalCount: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.AffectedAssetList = None
self.TotalCount = None
self.RequestId = None
def _deserialize(self, params):
if params.get("AffectedAssetList") is not None:
self.AffectedAssetList = []
for item in params.get("AffectedAssetList"):
obj = ComplianceAffectedAsset()
obj._deserialize(item)
self.AffectedAssetList.append(obj)
self.TotalCount = params.get("TotalCount")
self.RequestId = params.get("RequestId")
class DescribeCompliancePolicyItemAffectedSummaryRequest(AbstractModel):
"""DescribeCompliancePolicyItemAffectedSummary请求参数结构体
"""
def __init__(self):
r"""
:param CustomerPolicyItemId: DescribeComplianceTaskPolicyItemSummaryList返回的CustomerPolicyItemId,表示检测项的ID。
:type CustomerPolicyItemId: int
"""
self.CustomerPolicyItemId = None
def _deserialize(self, params):
self.CustomerPolicyItemId = params.get("CustomerPolicyItemId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeCompliancePolicyItemAffectedSummaryResponse(AbstractModel):
"""DescribeCompliancePolicyItemAffectedSummary返回参数结构体
"""
def __init__(self):
r"""
:param PolicyItemSummary: 返回各检测项影响的资产的汇总信息。
:type PolicyItemSummary: :class:`tencentcloud.tcss.v20201101.models.CompliancePolicyItemSummary`
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.PolicyItemSummary = None
self.RequestId = None
def _deserialize(self, params):
if params.get("PolicyItemSummary") is not None:
self.PolicyItemSummary = CompliancePolicyItemSummary()
self.PolicyItemSummary._deserialize(params.get("PolicyItemSummary"))
self.RequestId = params.get("RequestId")
class DescribeComplianceScanFailedAssetListRequest(AbstractModel):
"""DescribeComplianceScanFailedAssetList请求参数结构体
"""
def __init__(self):
r"""
:param AssetTypeSet: 资产类型列表。
ASSET_CONTAINER, 容器
ASSET_IMAGE, 镜像
ASSET_HOST, 主机
ASSET_K8S, K8S资产
:type AssetTypeSet: list of str
:param Offset: 起始偏移量,默认为0。
:type Offset: int
:param Limit: 返回的数据量,默认为10,最大为100。
:type Limit: int
:param Filters: 查询过滤器
:type Filters: list of ComplianceFilters
"""
self.AssetTypeSet = None
self.Offset = None
self.Limit = None
self.Filters = None
def _deserialize(self, params):
self.AssetTypeSet = params.get("AssetTypeSet")
self.Offset = params.get("Offset")
self.Limit = params.get("Limit")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = ComplianceFilters()
obj._deserialize(item)
self.Filters.append(obj)
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeComplianceScanFailedAssetListResponse(AbstractModel):
"""DescribeComplianceScanFailedAssetList返回参数结构体
"""
def __init__(self):
r"""
:param TotalCount: 返回检测失败的资产的总数。
:type TotalCount: int
:param ScanFailedAssetList: 返回各类检测失败的资产的汇总信息的列表。
注意:此字段可能返回 null,表示取不到有效值。
:type ScanFailedAssetList: list of ComplianceScanFailedAsset
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.TotalCount = None
self.ScanFailedAssetList = None
self.RequestId = None
def _deserialize(self, params):
self.TotalCount = params.get("TotalCount")
if params.get("ScanFailedAssetList") is not None:
self.ScanFailedAssetList = []
for item in params.get("ScanFailedAssetList"):
obj = ComplianceScanFailedAsset()
obj._deserialize(item)
self.ScanFailedAssetList.append(obj)
self.RequestId = params.get("RequestId")
class DescribeComplianceTaskAssetSummaryRequest(AbstractModel):
"""DescribeComplianceTaskAssetSummary请求参数结构体
"""
def __init__(self):
r"""
:param AssetTypeSet: 资产类型列表。
ASSET_CONTAINER, 容器
ASSET_IMAGE, 镜像
ASSET_HOST, 主机
ASSET_K8S, K8S资产
:type AssetTypeSet: list of str
"""
self.AssetTypeSet = None
def _deserialize(self, params):
self.AssetTypeSet = params.get("AssetTypeSet")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeComplianceTaskAssetSummaryResponse(AbstractModel):
"""DescribeComplianceTaskAssetSummary返回参数结构体
"""
def __init__(self):
r"""
:param Status: 返回用户的状态,
USER_UNINIT: 用户未初始化。
USER_INITIALIZING,表示用户正在初始化环境。
USER_NORMAL: 正常状态。
:type Status: str
:param AssetSummaryList: 返回各类资产的汇总信息的列表。
:type AssetSummaryList: list of ComplianceAssetSummary
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.Status = None
self.AssetSummaryList = None
self.RequestId = None
def _deserialize(self, params):
self.Status = params.get("Status")
if params.get("AssetSummaryList") is not None:
self.AssetSummaryList = []
for item in params.get("AssetSummaryList"):
obj = ComplianceAssetSummary()
obj._deserialize(item)
self.AssetSummaryList.append(obj)
self.RequestId = params.get("RequestId")
class DescribeComplianceTaskPolicyItemSummaryListRequest(AbstractModel):
"""DescribeComplianceTaskPolicyItemSummaryList请求参数结构体
"""
def __init__(self):
r"""
:param AssetType: 资产类型。仅查询与指定资产类型相关的检测项。
ASSET_CONTAINER, 容器
ASSET_IMAGE, 镜像
ASSET_HOST, 主机
ASSET_K8S, K8S资产
:type AssetType: str
:param Offset: 起始偏移量,默认为0。
:type Offset: int
:param Limit: 需要返回的数量,默认为10,最大值为100。
:type Limit: int
:param Filters: 过滤条件。
Name - String
Name 可取值:ItemType, StandardId, RiskLevel。
当为K8S资产时,还可取ClusterName。
:type Filters: list of ComplianceFilters
"""
self.AssetType = None
self.Offset = None
self.Limit = None
self.Filters = None
def _deserialize(self, params):
self.AssetType = params.get("AssetType")
self.Offset = params.get("Offset")
self.Limit = params.get("Limit")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = ComplianceFilters()
obj._deserialize(item)
self.Filters.append(obj)
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeComplianceTaskPolicyItemSummaryListResponse(AbstractModel):
"""DescribeComplianceTaskPolicyItemSummaryList返回参数结构体
"""
def __init__(self):
r"""
:param TaskId: 返回最近一次合规检查任务的ID。这个任务为本次所展示数据的来源。
注意:此字段可能返回 null,表示取不到有效值。
:type TaskId: int
:param TotalCount: 返回检测项的总数。
:type TotalCount: int
:param PolicyItemSummaryList: 返回各检测项对应的汇总信息的列表。
:type PolicyItemSummaryList: list of CompliancePolicyItemSummary
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.TaskId = None
self.TotalCount = None
self.PolicyItemSummaryList = None
self.RequestId = None
def _deserialize(self, params):
self.TaskId = params.get("TaskId")
self.TotalCount = params.get("TotalCount")
if params.get("PolicyItemSummaryList") is not None:
self.PolicyItemSummaryList = []
for item in params.get("PolicyItemSummaryList"):
obj = CompliancePolicyItemSummary()
obj._deserialize(item)
self.PolicyItemSummaryList.append(obj)
self.RequestId = params.get("RequestId")
class DescribeComplianceWhitelistItemListRequest(AbstractModel):
"""DescribeComplianceWhitelistItemList请求参数结构体
"""
def __init__(self):
r"""
:param Offset: 起始偏移量,默认为0。
:type Offset: int
:param Limit: 要获取的数量,默认为10,最大为100。
:type Limit: int
:param AssetTypeSet: 资产类型列表。
:type AssetTypeSet: list of str
:param Filters: 查询过滤器
:type Filters: list of ComplianceFilters
:param By: 排序字段
:type By: str
:param Order: 排序方式 desc asc
:type Order: str
"""
self.Offset = None
self.Limit = None
self.AssetTypeSet = None
self.Filters = None
self.By = None
self.Order = None
def _deserialize(self, params):
self.Offset = params.get("Offset")
self.Limit = params.get("Limit")
self.AssetTypeSet = params.get("AssetTypeSet")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = ComplianceFilters()
obj._deserialize(item)
self.Filters.append(obj)
self.By = params.get("By")
self.Order = params.get("Order")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeComplianceWhitelistItemListResponse(AbstractModel):
"""DescribeComplianceWhitelistItemList返回参数结构体
"""
def __init__(self):
r"""
:param WhitelistItemSet: 白名单项的列表。
:type WhitelistItemSet: list of ComplianceWhitelistItem
:param TotalCount: 白名单项的总数。
:type TotalCount: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.WhitelistItemSet = None
self.TotalCount = None
self.RequestId = None
def _deserialize(self, params):
if params.get("WhitelistItemSet") is not None:
self.WhitelistItemSet = []
for item in params.get("WhitelistItemSet"):
obj = ComplianceWhitelistItem()
obj._deserialize(item)
self.WhitelistItemSet.append(obj)
self.TotalCount = params.get("TotalCount")
self.RequestId = params.get("RequestId")
class DescribeContainerAssetSummaryRequest(AbstractModel):
"""DescribeContainerAssetSummary请求参数结构体
"""
class DescribeContainerAssetSummaryResponse(AbstractModel):
"""DescribeContainerAssetSummary返回参数结构体
"""
def __init__(self):
r"""
:param ContainerTotalCnt: 容器总数
:type ContainerTotalCnt: int
:param ContainerRunningCnt: 正在运行容器数量
:type ContainerRunningCnt: int
:param ContainerPauseCnt: 暂停运行容器数量
:type ContainerPauseCnt: int
:param ContainerStopped: 停止运行容器数量
:type ContainerStopped: int
:param ImageCnt: 本地镜像数量
:type ImageCnt: int
:param HostCnt: 主机节点数量
:type HostCnt: int
:param HostRunningCnt: 主机正在运行节点数量
:type HostRunningCnt: int
:param HostOfflineCnt: 主机离线节点数量
:type HostOfflineCnt: int
:param ImageRegistryCnt: 镜像仓库数量
:type ImageRegistryCnt: int
:param ImageTotalCnt: 镜像总数
:type ImageTotalCnt: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.ContainerTotalCnt = None
self.ContainerRunningCnt = None
self.ContainerPauseCnt = None
self.ContainerStopped = None
self.ImageCnt = None
self.HostCnt = None
self.HostRunningCnt = None
self.HostOfflineCnt = None
self.ImageRegistryCnt = None
self.ImageTotalCnt = None
self.RequestId = None
def _deserialize(self, params):
self.ContainerTotalCnt = params.get("ContainerTotalCnt")
self.ContainerRunningCnt = params.get("ContainerRunningCnt")
self.ContainerPauseCnt = params.get("ContainerPauseCnt")
self.ContainerStopped = params.get("ContainerStopped")
self.ImageCnt = params.get("ImageCnt")
self.HostCnt = params.get("HostCnt")
self.HostRunningCnt = params.get("HostRunningCnt")
self.HostOfflineCnt = params.get("HostOfflineCnt")
self.ImageRegistryCnt = params.get("ImageRegistryCnt")
self.ImageTotalCnt = params.get("ImageTotalCnt")
self.RequestId = params.get("RequestId")
class DescribeContainerSecEventSummaryRequest(AbstractModel):
"""DescribeContainerSecEventSummary请求参数结构体
"""
class DescribeContainerSecEventSummaryResponse(AbstractModel):
"""DescribeContainerSecEventSummary返回参数结构体
"""
def __init__(self):
r"""
:param UnhandledEscapeCnt: 未处理逃逸事件
:type UnhandledEscapeCnt: int
:param UnhandledReverseShellCnt: 未处理反弹shell事件
:type UnhandledReverseShellCnt: int
:param UnhandledRiskSyscallCnt: 未处理高危系统调用
:type UnhandledRiskSyscallCnt: int
:param UnhandledAbnormalProcessCnt: 未处理异常进程
:type UnhandledAbnormalProcessCnt: int
:param UnhandledFileCnt: 未处理文件篡改
:type UnhandledFileCnt: int
:param UnhandledVirusEventCnt: 未处理木马事件
:type UnhandledVirusEventCnt: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.UnhandledEscapeCnt = None
self.UnhandledReverseShellCnt = None
self.UnhandledRiskSyscallCnt = None
self.UnhandledAbnormalProcessCnt = None
self.UnhandledFileCnt = None
self.UnhandledVirusEventCnt = None
self.RequestId = None
def _deserialize(self, params):
self.UnhandledEscapeCnt = params.get("UnhandledEscapeCnt")
self.UnhandledReverseShellCnt = params.get("UnhandledReverseShellCnt")
self.UnhandledRiskSyscallCnt = params.get("UnhandledRiskSyscallCnt")
self.UnhandledAbnormalProcessCnt = params.get("UnhandledAbnormalProcessCnt")
self.UnhandledFileCnt = params.get("UnhandledFileCnt")
self.UnhandledVirusEventCnt = params.get("UnhandledVirusEventCnt")
self.RequestId = params.get("RequestId")
class DescribeEscapeEventDetailRequest(AbstractModel):
"""DescribeEscapeEventDetail请求参数结构体
"""
def __init__(self):
r"""
:param EventId: 事件唯一id
:type EventId: str
"""
self.EventId = None
def _deserialize(self, params):
self.EventId = params.get("EventId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeEscapeEventDetailResponse(AbstractModel):
"""DescribeEscapeEventDetail返回参数结构体
"""
def __init__(self):
r"""
:param EventBaseInfo: 事件基本信息
:type EventBaseInfo: :class:`tencentcloud.tcss.v20201101.models.RunTimeEventBaseInfo`
:param ProcessInfo: 进程信息
:type ProcessInfo: :class:`tencentcloud.tcss.v20201101.models.ProcessDetailInfo`
:param EventDetail: 事件描述
:type EventDetail: :class:`tencentcloud.tcss.v20201101.models.EscapeEventDescription`
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.EventBaseInfo = None
self.ProcessInfo = None
self.EventDetail = None
self.RequestId = None
def _deserialize(self, params):
if params.get("EventBaseInfo") is not None:
self.EventBaseInfo = RunTimeEventBaseInfo()
self.EventBaseInfo._deserialize(params.get("EventBaseInfo"))
if params.get("ProcessInfo") is not None:
self.ProcessInfo = ProcessDetailInfo()
self.ProcessInfo._deserialize(params.get("ProcessInfo"))
if params.get("EventDetail") is not None:
self.EventDetail = EscapeEventDescription()
self.EventDetail._deserialize(params.get("EventDetail"))
self.RequestId = params.get("RequestId")
class DescribeEscapeEventInfoRequest(AbstractModel):
"""DescribeEscapeEventInfo请求参数结构体
"""
def __init__(self):
r"""
:param Limit: 需要返回的数量,默认为10,最大值为100
:type Limit: int
:param Offset: 偏移量,默认为0。
:type Offset: int
:param Filters: 过滤参数,"Filters":[{"Name":"Status","Values":["2"]}]
:type Filters: list of RunTimeFilters
:param Order: 升序降序,asc desc
:type Order: str
:param By: 排序字段
:type By: str
"""
self.Limit = None
self.Offset = None
self.Filters = None
self.Order = None
self.By = None
def _deserialize(self, params):
self.Limit = params.get("Limit")
self.Offset = params.get("Offset")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = RunTimeFilters()
obj._deserialize(item)
self.Filters.append(obj)
self.Order = params.get("Order")
self.By = params.get("By")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeEscapeEventInfoResponse(AbstractModel):
"""DescribeEscapeEventInfo返回参数结构体
"""
def __init__(self):
r"""
:param EventSet: 逃逸事件数组
:type EventSet: list of EscapeEventInfo
:param TotalCount: 事件总数量
:type TotalCount: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.EventSet = None
self.TotalCount = None
self.RequestId = None
def _deserialize(self, params):
if params.get("EventSet") is not None:
self.EventSet = []
for item in params.get("EventSet"):
obj = EscapeEventInfo()
obj._deserialize(item)
self.EventSet.append(obj)
self.TotalCount = params.get("TotalCount")
self.RequestId = params.get("RequestId")
class DescribeEscapeEventsExportRequest(AbstractModel):
"""DescribeEscapeEventsExport请求参数结构体
"""
def __init__(self):
r"""
:param ExportField: 导出字段
:type ExportField: list of str
:param Limit: 需要返回的数量,默认为10,最大值为100
:type Limit: int
:param Offset: 偏移量,默认为0。
:type Offset: int
:param Filters: 过滤参数,"Filters":[{"Name":"Status","Values":["2"]}]
:type Filters: list of RunTimeFilters
:param Order: 升序降序,asc desc
:type Order: str
:param By: 排序字段
:type By: str
"""
self.ExportField = None
self.Limit = None
self.Offset = None
self.Filters = None
self.Order = None
self.By = None
def _deserialize(self, params):
self.ExportField = params.get("ExportField")
self.Limit = params.get("Limit")
self.Offset = params.get("Offset")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = RunTimeFilters()
obj._deserialize(item)
self.Filters.append(obj)
self.Order = params.get("Order")
self.By = params.get("By")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeEscapeEventsExportResponse(AbstractModel):
"""DescribeEscapeEventsExport返回参数结构体
"""
def __init__(self):
r"""
:param DownloadUrl: execle下载地址
注意:此字段可能返回 null,表示取不到有效值。
:type DownloadUrl: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.DownloadUrl = None
self.RequestId = None
def _deserialize(self, params):
self.DownloadUrl = params.get("DownloadUrl")
self.RequestId = params.get("RequestId")
class DescribeEscapeRuleInfoRequest(AbstractModel):
"""DescribeEscapeRuleInfo请求参数结构体
"""
class DescribeEscapeRuleInfoResponse(AbstractModel):
"""DescribeEscapeRuleInfo返回参数结构体
"""
def __init__(self):
r"""
:param RuleSet: 规则信息
:type RuleSet: list of EscapeRule
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RuleSet = None
self.RequestId = None
def _deserialize(self, params):
if params.get("RuleSet") is not None:
self.RuleSet = []
for item in params.get("RuleSet"):
obj = EscapeRule()
obj._deserialize(item)
self.RuleSet.append(obj)
self.RequestId = params.get("RequestId")
class DescribeEscapeSafeStateRequest(AbstractModel):
"""DescribeEscapeSafeState请求参数结构体
"""
class DescribeEscapeSafeStateResponse(AbstractModel):
"""DescribeEscapeSafeState返回参数结构体
"""
def __init__(self):
r"""
:param IsSafe: Unsafe:存在风险,Safe:暂无风险,UnKnown:未知风险
:type IsSafe: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.IsSafe = None
self.RequestId = None
def _deserialize(self, params):
self.IsSafe = params.get("IsSafe")
self.RequestId = params.get("RequestId")
class DescribeExportJobResultRequest(AbstractModel):
"""DescribeExportJobResult请求参数结构体
"""
def __init__(self):
r"""
:param JobId: CreateExportComplianceStatusListJob返回的JobId字段的值
:type JobId: str
"""
self.JobId = None
def _deserialize(self, params):
self.JobId = params.get("JobId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeExportJobResultResponse(AbstractModel):
"""DescribeExportJobResult返回参数结构体
"""
def __init__(self):
r"""
:param ExportStatus: 导出的状态。取值为, SUCCESS:成功、FAILURE:失败,RUNNING: 进行中。
:type ExportStatus: str
:param DownloadURL: 返回下载URL
注意:此字段可能返回 null,表示取不到有效值。
:type DownloadURL: str
:param ExportProgress: 当ExportStatus为RUNNING时,返回导出进度。0~100范围的浮点数。
注意:此字段可能返回 null,表示取不到有效值。
:type ExportProgress: float
:param FailureMsg: 失败原因
注意:此字段可能返回 null,表示取不到有效值。
:type FailureMsg: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.ExportStatus = None
self.DownloadURL = None
self.ExportProgress = None
self.FailureMsg = None
self.RequestId = None
def _deserialize(self, params):
self.ExportStatus = params.get("ExportStatus")
self.DownloadURL = params.get("DownloadURL")
self.ExportProgress = params.get("ExportProgress")
self.FailureMsg = params.get("FailureMsg")
self.RequestId = params.get("RequestId")
class DescribeImageAuthorizedInfoRequest(AbstractModel):
"""DescribeImageAuthorizedInfo请求参数结构体
"""
class DescribeImageAuthorizedInfoResponse(AbstractModel):
"""DescribeImageAuthorizedInfo返回参数结构体
"""
def __init__(self):
r"""
:param TotalAuthorizedCnt: 总共有效的镜像授权数
:type TotalAuthorizedCnt: int
:param UsedAuthorizedCnt: 已使用镜像授权数
:type UsedAuthorizedCnt: int
:param ScannedImageCnt: 已开启扫描镜像数
:type ScannedImageCnt: int
:param NotScannedImageCnt: 未开启扫描镜像数
:type NotScannedImageCnt: int
:param NotScannedLocalImageCnt: 本地未开启扫描镜像数
:type NotScannedLocalImageCnt: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.TotalAuthorizedCnt = None
self.UsedAuthorizedCnt = None
self.ScannedImageCnt = None
self.NotScannedImageCnt = None
self.NotScannedLocalImageCnt = None
self.RequestId = None
def _deserialize(self, params):
self.TotalAuthorizedCnt = params.get("TotalAuthorizedCnt")
self.UsedAuthorizedCnt = params.get("UsedAuthorizedCnt")
self.ScannedImageCnt = params.get("ScannedImageCnt")
self.NotScannedImageCnt = params.get("NotScannedImageCnt")
self.NotScannedLocalImageCnt = params.get("NotScannedLocalImageCnt")
self.RequestId = params.get("RequestId")
class DescribeImageRegistryTimingScanTaskRequest(AbstractModel):
"""DescribeImageRegistryTimingScanTask请求参数结构体
"""
class DescribeImageRegistryTimingScanTaskResponse(AbstractModel):
"""DescribeImageRegistryTimingScanTask返回参数结构体
"""
def __init__(self):
r"""
:param Enable: 定时扫描开关
注意:此字段可能返回 null,表示取不到有效值。
:type Enable: bool
:param ScanTime: 定时任务扫描时间
:type ScanTime: str
:param ScanPeriod: 定时扫描间隔
:type ScanPeriod: int
:param ScanType: 扫描类型数组
注意:此字段可能返回 null,表示取不到有效值。
:type ScanType: list of str
:param All: 扫描全部镜像
:type All: bool
:param Images: 自定义扫描镜像
注意:此字段可能返回 null,表示取不到有效值。
:type Images: list of ImageInfo
:param Id: 自动以扫描镜像Id
注意:此字段可能返回 null,表示取不到有效值。
:type Id: list of int non-negative
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.Enable = None
self.ScanTime = None
self.ScanPeriod = None
self.ScanType = None
self.All = None
self.Images = None
self.Id = None
self.RequestId = None
def _deserialize(self, params):
self.Enable = params.get("Enable")
self.ScanTime = params.get("ScanTime")
self.ScanPeriod = params.get("ScanPeriod")
self.ScanType = params.get("ScanType")
self.All = params.get("All")
if params.get("Images") is not None:
self.Images = []
for item in params.get("Images"):
obj = ImageInfo()
obj._deserialize(item)
self.Images.append(obj)
self.Id = params.get("Id")
self.RequestId = params.get("RequestId")
class DescribeImageRiskSummaryRequest(AbstractModel):
"""DescribeImageRiskSummary请求参数结构体
"""
class DescribeImageRiskSummaryResponse(AbstractModel):
"""DescribeImageRiskSummary返回参数结构体
"""
def __init__(self):
r"""
:param VulnerabilityCnt: 安全漏洞
:type VulnerabilityCnt: list of RunTimeRiskInfo
:param MalwareVirusCnt: 木马病毒
:type MalwareVirusCnt: list of RunTimeRiskInfo
:param RiskCnt: 敏感信息
:type RiskCnt: list of RunTimeRiskInfo
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.VulnerabilityCnt = None
self.MalwareVirusCnt = None
self.RiskCnt = None
self.RequestId = None
def _deserialize(self, params):
if params.get("VulnerabilityCnt") is not None:
self.VulnerabilityCnt = []
for item in params.get("VulnerabilityCnt"):
obj = RunTimeRiskInfo()
obj._deserialize(item)
self.VulnerabilityCnt.append(obj)
if params.get("MalwareVirusCnt") is not None:
self.MalwareVirusCnt = []
for item in params.get("MalwareVirusCnt"):
obj = RunTimeRiskInfo()
obj._deserialize(item)
self.MalwareVirusCnt.append(obj)
if params.get("RiskCnt") is not None:
self.RiskCnt = []
for item in params.get("RiskCnt"):
obj = RunTimeRiskInfo()
obj._deserialize(item)
self.RiskCnt.append(obj)
self.RequestId = params.get("RequestId")
class DescribeImageRiskTendencyRequest(AbstractModel):
"""DescribeImageRiskTendency请求参数结构体
"""
def __init__(self):
r"""
:param StartTime: 开始时间
:type StartTime: str
:param EndTime: 结束时间
:type EndTime: str
"""
self.StartTime = None
self.EndTime = None
def _deserialize(self, params):
self.StartTime = params.get("StartTime")
self.EndTime = params.get("EndTime")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeImageRiskTendencyResponse(AbstractModel):
"""DescribeImageRiskTendency返回参数结构体
"""
def __init__(self):
r"""
:param ImageRiskTendencySet: 本地镜像新增风险趋势信息列表
:type ImageRiskTendencySet: list of ImageRiskTendencyInfo
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.ImageRiskTendencySet = None
self.RequestId = None
def _deserialize(self, params):
if params.get("ImageRiskTendencySet") is not None:
self.ImageRiskTendencySet = []
for item in params.get("ImageRiskTendencySet"):
obj = ImageRiskTendencyInfo()
obj._deserialize(item)
self.ImageRiskTendencySet.append(obj)
self.RequestId = params.get("RequestId")
class DescribeImageSimpleListRequest(AbstractModel):
"""DescribeImageSimpleList请求参数结构体
"""
def __init__(self):
r"""
:param Filters: IsAuthorized 是否已经授权, 0:否 1:是 无:全部
:type Filters: list of RunTimeFilters
:param Limit: 需要返回的数量,默认为10,最大值为100
:type Limit: int
:param Offset: 偏移量,默认为0。
:type Offset: int
:param Order: 排序方式
:type Order: str
:param By: 排序字段
:type By: str
"""
self.Filters = None
self.Limit = None
self.Offset = None
self.Order = None
self.By = None
def _deserialize(self, params):
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = RunTimeFilters()
obj._deserialize(item)
self.Filters.append(obj)
self.Limit = params.get("Limit")
self.Offset = params.get("Offset")
self.Order = params.get("Order")
self.By = params.get("By")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeImageSimpleListResponse(AbstractModel):
"""DescribeImageSimpleList返回参数结构体
"""
def __init__(self):
r"""
:param ImageList: 镜像列表
:type ImageList: list of ImageSimpleInfo
:param ImageCnt: 镜像数
:type ImageCnt: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.ImageList = None
self.ImageCnt = None
self.RequestId = None
def _deserialize(self, params):
if params.get("ImageList") is not None:
self.ImageList = []
for item in params.get("ImageList"):
obj = ImageSimpleInfo()
obj._deserialize(item)
self.ImageList.append(obj)
self.ImageCnt = params.get("ImageCnt")
self.RequestId = params.get("RequestId")
class DescribePostPayDetailRequest(AbstractModel):
"""DescribePostPayDetail请求参数结构体
"""
def __init__(self):
r"""
:param Limit: 需要返回的数量,默认为10,最大值为100
:type Limit: int
:param Offset: 偏移量,默认为0。
:type Offset: int
"""
self.Limit = None
self.Offset = None
def _deserialize(self, params):
self.Limit = params.get("Limit")
self.Offset = params.get("Offset")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribePostPayDetailResponse(AbstractModel):
"""DescribePostPayDetail返回参数结构体
"""
def __init__(self):
r"""
:param SoftQuotaDayDetail: 弹性计费扣费详情
注意:此字段可能返回 null,表示取不到有效值。
:type SoftQuotaDayDetail: list of SoftQuotaDayInfo
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.SoftQuotaDayDetail = None
self.RequestId = None
def _deserialize(self, params):
if params.get("SoftQuotaDayDetail") is not None:
self.SoftQuotaDayDetail = []
for item in params.get("SoftQuotaDayDetail"):
obj = SoftQuotaDayInfo()
obj._deserialize(item)
self.SoftQuotaDayDetail.append(obj)
self.RequestId = params.get("RequestId")
class DescribeProVersionInfoRequest(AbstractModel):
"""DescribeProVersionInfo请求参数结构体
"""
class DescribeProVersionInfoResponse(AbstractModel):
"""DescribeProVersionInfo返回参数结构体
"""
def __init__(self):
r"""
:param StartTime: 专业版开始时间,补充购买时才不为空
注意:此字段可能返回 null,表示取不到有效值。
:type StartTime: str
:param EndTime: 专业版结束时间,补充购买时才不为空
注意:此字段可能返回 null,表示取不到有效值。
:type EndTime: str
:param CoresCnt: 需购买的机器核数
:type CoresCnt: int
:param MaxPostPayCoresCnt: 弹性计费上限
:type MaxPostPayCoresCnt: int
:param ResourceId: 资源ID
注意:此字段可能返回 null,表示取不到有效值。
:type ResourceId: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.StartTime = None
self.EndTime = None
self.CoresCnt = None
self.MaxPostPayCoresCnt = None
self.ResourceId = None
self.RequestId = None
def _deserialize(self, params):
self.StartTime = params.get("StartTime")
self.EndTime = params.get("EndTime")
self.CoresCnt = params.get("CoresCnt")
self.MaxPostPayCoresCnt = params.get("MaxPostPayCoresCnt")
self.ResourceId = params.get("ResourceId")
self.RequestId = params.get("RequestId")
class DescribePurchaseStateInfoRequest(AbstractModel):
"""DescribePurchaseStateInfo请求参数结构体
"""
class DescribePurchaseStateInfoResponse(AbstractModel):
"""DescribePurchaseStateInfo返回参数结构体
"""
def __init__(self):
r"""
:param State: 0:可申请试用可购买;1:只可购买(含试用审核不通过和试用过期);2:试用生效中;3:专业版生效中;4:专业版过期
:type State: int
:param CoresCnt: 总核数
注意:此字段可能返回 null,表示取不到有效值。
:type CoresCnt: int
:param AuthorizedCoresCnt: 已购买核数
注意:此字段可能返回 null,表示取不到有效值。
:type AuthorizedCoresCnt: int
:param ImageCnt: 镜像数
注意:此字段可能返回 null,表示取不到有效值。
:type ImageCnt: int
:param AuthorizedImageCnt: 已授权镜像数
注意:此字段可能返回 null,表示取不到有效值。
:type AuthorizedImageCnt: int
:param PurchasedAuthorizedCnt: 已购买镜像授权数
注意:此字段可能返回 null,表示取不到有效值。
:type PurchasedAuthorizedCnt: int
:param ExpirationTime: 过期时间
注意:此字段可能返回 null,表示取不到有效值。
:type ExpirationTime: str
:param AutomaticRenewal: 0表示默认状态(用户未设置,即初始状态), 1表示自动续费,2表示明确不自动续费(用户设置)
注意:此字段可能返回 null,表示取不到有效值。
:type AutomaticRenewal: int
:param GivenAuthorizedCnt: 试用期间赠送镜像授权数,可能会过期
注意:此字段可能返回 null,表示取不到有效值。
:type GivenAuthorizedCnt: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.State = None
self.CoresCnt = None
self.AuthorizedCoresCnt = None
self.ImageCnt = None
self.AuthorizedImageCnt = None
self.PurchasedAuthorizedCnt = None
self.ExpirationTime = None
self.AutomaticRenewal = None
self.GivenAuthorizedCnt = None
self.RequestId = None
def _deserialize(self, params):
self.State = params.get("State")
self.CoresCnt = params.get("CoresCnt")
self.AuthorizedCoresCnt = params.get("AuthorizedCoresCnt")
self.ImageCnt = params.get("ImageCnt")
self.AuthorizedImageCnt = params.get("AuthorizedImageCnt")
self.PurchasedAuthorizedCnt = params.get("PurchasedAuthorizedCnt")
self.ExpirationTime = params.get("ExpirationTime")
self.AutomaticRenewal = params.get("AutomaticRenewal")
self.GivenAuthorizedCnt = params.get("GivenAuthorizedCnt")
self.RequestId = params.get("RequestId")
class DescribeRefreshTaskRequest(AbstractModel):
"""DescribeRefreshTask请求参数结构体
"""
def __init__(self):
r"""
:param TaskId: 任务ID
:type TaskId: int
"""
self.TaskId = None
def _deserialize(self, params):
self.TaskId = params.get("TaskId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeRefreshTaskResponse(AbstractModel):
"""DescribeRefreshTask返回参数结构体
"""
def __init__(self):
r"""
:param TaskStatus: 刷新任务状态,可能为:Task_New,Task_Running,Task_Finish,Task_Error,Task_NoExist
:type TaskStatus: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.TaskStatus = None
self.RequestId = None
def _deserialize(self, params):
self.TaskStatus = params.get("TaskStatus")
self.RequestId = params.get("RequestId")
class DescribeReverseShellDetailRequest(AbstractModel):
"""DescribeReverseShellDetail请求参数结构体
"""
def __init__(self):
r"""
:param EventId: 事件唯一id
:type EventId: str
"""
self.EventId = None
def _deserialize(self, params):
self.EventId = params.get("EventId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeReverseShellDetailResponse(AbstractModel):
"""DescribeReverseShellDetail返回参数结构体
"""
def __init__(self):
r"""
:param EventBaseInfo: 事件基本信息
:type EventBaseInfo: :class:`tencentcloud.tcss.v20201101.models.RunTimeEventBaseInfo`
:param ProcessInfo: 进程信息
:type ProcessInfo: :class:`tencentcloud.tcss.v20201101.models.ProcessDetailInfo`
:param ParentProcessInfo: 父进程信息
:type ParentProcessInfo: :class:`tencentcloud.tcss.v20201101.models.ProcessDetailBaseInfo`
:param EventDetail: 事件描述
:type EventDetail: :class:`tencentcloud.tcss.v20201101.models.ReverseShellEventDescription`
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.EventBaseInfo = None
self.ProcessInfo = None
self.ParentProcessInfo = None
self.EventDetail = None
self.RequestId = None
def _deserialize(self, params):
if params.get("EventBaseInfo") is not None:
self.EventBaseInfo = RunTimeEventBaseInfo()
self.EventBaseInfo._deserialize(params.get("EventBaseInfo"))
if params.get("ProcessInfo") is not None:
self.ProcessInfo = ProcessDetailInfo()
self.ProcessInfo._deserialize(params.get("ProcessInfo"))
if params.get("ParentProcessInfo") is not None:
self.ParentProcessInfo = ProcessDetailBaseInfo()
self.ParentProcessInfo._deserialize(params.get("ParentProcessInfo"))
if params.get("EventDetail") is not None:
self.EventDetail = ReverseShellEventDescription()
self.EventDetail._deserialize(params.get("EventDetail"))
self.RequestId = params.get("RequestId")
class DescribeReverseShellEventsExportRequest(AbstractModel):
"""DescribeReverseShellEventsExport请求参数结构体
"""
def __init__(self):
r"""
:param ExportField: 导出字段
:type ExportField: list of str
:param Limit: 需要返回的数量,默认为10,最大值为100
:type Limit: int
:param Offset: 偏移量,默认为0。
:type Offset: int
:param Filters: 过滤参数,"Filters":[{"Name":"Status","Values":["2"]}]
:type Filters: list of RunTimeFilters
:param Order: 升序降序,asc desc
:type Order: str
:param By: 排序字段
:type By: str
"""
self.ExportField = None
self.Limit = None
self.Offset = None
self.Filters = None
self.Order = None
self.By = None
def _deserialize(self, params):
self.ExportField = params.get("ExportField")
self.Limit = params.get("Limit")
self.Offset = params.get("Offset")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = RunTimeFilters()
obj._deserialize(item)
self.Filters.append(obj)
self.Order = params.get("Order")
self.By = params.get("By")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeReverseShellEventsExportResponse(AbstractModel):
"""DescribeReverseShellEventsExport返回参数结构体
"""
def __init__(self):
r"""
:param DownloadUrl: execle下载地址
注意:此字段可能返回 null,表示取不到有效值。
:type DownloadUrl: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.DownloadUrl = None
self.RequestId = None
def _deserialize(self, params):
self.DownloadUrl = params.get("DownloadUrl")
self.RequestId = params.get("RequestId")
class DescribeReverseShellEventsRequest(AbstractModel):
"""DescribeReverseShellEvents请求参数结构体
"""
def __init__(self):
r"""
:param Limit: 需要返回的数量,默认为10,最大值为100
:type Limit: int
:param Offset: 偏移量,默认为0。
:type Offset: int
:param Filters: 过滤参数,"Filters":[{"Name":"Status","Values":["2"]}]
:type Filters: list of RunTimeFilters
:param Order: 升序降序,asc desc
:type Order: str
:param By: 排序字段
:type By: str
"""
self.Limit = None
self.Offset = None
self.Filters = None
self.Order = None
self.By = None
def _deserialize(self, params):
self.Limit = params.get("Limit")
self.Offset = params.get("Offset")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = RunTimeFilters()
obj._deserialize(item)
self.Filters.append(obj)
self.Order = params.get("Order")
self.By = params.get("By")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeReverseShellEventsResponse(AbstractModel):
"""DescribeReverseShellEvents返回参数结构体
"""
def __init__(self):
r"""
:param TotalCount: 事件总数量
:type TotalCount: int
:param EventSet: 反弹shell数组
:type EventSet: list of ReverseShellEventInfo
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.TotalCount = None
self.EventSet = None
self.RequestId = None
def _deserialize(self, params):
self.TotalCount = params.get("TotalCount")
if params.get("EventSet") is not None:
self.EventSet = []
for item in params.get("EventSet"):
obj = ReverseShellEventInfo()
obj._deserialize(item)
self.EventSet.append(obj)
self.RequestId = params.get("RequestId")
class DescribeReverseShellWhiteListDetailRequest(AbstractModel):
"""DescribeReverseShellWhiteListDetail请求参数结构体
"""
def __init__(self):
r"""
:param WhiteListId: 白名单id
:type WhiteListId: str
"""
self.WhiteListId = None
def _deserialize(self, params):
self.WhiteListId = params.get("WhiteListId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeReverseShellWhiteListDetailResponse(AbstractModel):
"""DescribeReverseShellWhiteListDetail返回参数结构体
"""
def __init__(self):
r"""
:param WhiteListDetailInfo: 事件基本信息
:type WhiteListDetailInfo: :class:`tencentcloud.tcss.v20201101.models.ReverseShellWhiteListInfo`
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.WhiteListDetailInfo = None
self.RequestId = None
def _deserialize(self, params):
if params.get("WhiteListDetailInfo") is not None:
self.WhiteListDetailInfo = ReverseShellWhiteListInfo()
self.WhiteListDetailInfo._deserialize(params.get("WhiteListDetailInfo"))
self.RequestId = params.get("RequestId")
class DescribeReverseShellWhiteListsRequest(AbstractModel):
"""DescribeReverseShellWhiteLists请求参数结构体
"""
def __init__(self):
r"""
:param Limit: 需要返回的数量,默认为10,最大值为100
:type Limit: int
:param Offset: 偏移量,默认为0。
:type Offset: int
:param Filters: 过滤参数,"Filters":[{"Name":"Status","Values":["2"]}]
:type Filters: list of RunTimeFilters
:param Order: 升序降序,asc desc
:type Order: str
:param By: 排序字段
:type By: str
"""
self.Limit = None
self.Offset = None
self.Filters = None
self.Order = None
self.By = None
def _deserialize(self, params):
self.Limit = params.get("Limit")
self.Offset = params.get("Offset")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = RunTimeFilters()
obj._deserialize(item)
self.Filters.append(obj)
self.Order = params.get("Order")
self.By = params.get("By")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeReverseShellWhiteListsResponse(AbstractModel):
"""DescribeReverseShellWhiteLists返回参数结构体
"""
def __init__(self):
r"""
:param TotalCount: 事件总数量
:type TotalCount: int
:param WhiteListSet: 白名单信息列表
:type WhiteListSet: list of ReverseShellWhiteListBaseInfo
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.TotalCount = None
self.WhiteListSet = None
self.RequestId = None
def _deserialize(self, params):
self.TotalCount = params.get("TotalCount")
if params.get("WhiteListSet") is not None:
self.WhiteListSet = []
for item in params.get("WhiteListSet"):
obj = ReverseShellWhiteListBaseInfo()
obj._deserialize(item)
self.WhiteListSet.append(obj)
self.RequestId = params.get("RequestId")
class DescribeRiskListRequest(AbstractModel):
"""DescribeRiskList请求参数结构体
"""
def __init__(self):
r"""
:param ClusterId: 要查询的集群ID,如果不指定,则查询用户所有的风险项
:type ClusterId: str
:param Offset: 偏移量
:type Offset: int
:param Limit: 每次查询的最大记录数量
:type Limit: int
:param Filters: Name - String
Name 可取值:RiskLevel风险等级, RiskTarget检查对象,风险对象,RiskType风险类别,RiskAttribute检测项所属的风险类型,Name
:type Filters: list of ComplianceFilters
:param By: 排序字段
:type By: str
:param Order: 排序方式 asc,desc
:type Order: str
"""
self.ClusterId = None
self.Offset = None
self.Limit = None
self.Filters = None
self.By = None
self.Order = None
def _deserialize(self, params):
self.ClusterId = params.get("ClusterId")
self.Offset = params.get("Offset")
self.Limit = params.get("Limit")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = ComplianceFilters()
obj._deserialize(item)
self.Filters.append(obj)
self.By = params.get("By")
self.Order = params.get("Order")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeRiskListResponse(AbstractModel):
"""DescribeRiskList返回参数结构体
"""
def __init__(self):
r"""
:param ClusterRiskItems: 风险详情数组
:type ClusterRiskItems: list of ClusterRiskItem
:param TotalCount: 风险项的总数
:type TotalCount: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.ClusterRiskItems = None
self.TotalCount = None
self.RequestId = None
def _deserialize(self, params):
if params.get("ClusterRiskItems") is not None:
self.ClusterRiskItems = []
for item in params.get("ClusterRiskItems"):
obj = ClusterRiskItem()
obj._deserialize(item)
self.ClusterRiskItems.append(obj)
self.TotalCount = params.get("TotalCount")
self.RequestId = params.get("RequestId")
class DescribeRiskSyscallDetailRequest(AbstractModel):
"""DescribeRiskSyscallDetail请求参数结构体
"""
def __init__(self):
r"""
:param EventId: 事件唯一id
:type EventId: str
"""
self.EventId = None
def _deserialize(self, params):
self.EventId = params.get("EventId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeRiskSyscallDetailResponse(AbstractModel):
"""DescribeRiskSyscallDetail返回参数结构体
"""
def __init__(self):
r"""
:param EventBaseInfo: 事件基本信息
:type EventBaseInfo: :class:`tencentcloud.tcss.v20201101.models.RunTimeEventBaseInfo`
:param ProcessInfo: 进程信息
:type ProcessInfo: :class:`tencentcloud.tcss.v20201101.models.ProcessDetailInfo`
:param ParentProcessInfo: 父进程信息
:type ParentProcessInfo: :class:`tencentcloud.tcss.v20201101.models.ProcessDetailBaseInfo`
:param EventDetail: 事件描述
:type EventDetail: :class:`tencentcloud.tcss.v20201101.models.RiskSyscallEventDescription`
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.EventBaseInfo = None
self.ProcessInfo = None
self.ParentProcessInfo = None
self.EventDetail = None
self.RequestId = None
def _deserialize(self, params):
if params.get("EventBaseInfo") is not None:
self.EventBaseInfo = RunTimeEventBaseInfo()
self.EventBaseInfo._deserialize(params.get("EventBaseInfo"))
if params.get("ProcessInfo") is not None:
self.ProcessInfo = ProcessDetailInfo()
self.ProcessInfo._deserialize(params.get("ProcessInfo"))
if params.get("ParentProcessInfo") is not None:
self.ParentProcessInfo = ProcessDetailBaseInfo()
self.ParentProcessInfo._deserialize(params.get("ParentProcessInfo"))
if params.get("EventDetail") is not None:
self.EventDetail = RiskSyscallEventDescription()
self.EventDetail._deserialize(params.get("EventDetail"))
self.RequestId = params.get("RequestId")
class DescribeRiskSyscallEventsExportRequest(AbstractModel):
"""DescribeRiskSyscallEventsExport请求参数结构体
"""
def __init__(self):
r"""
:param ExportField: 导出字段
:type ExportField: list of str
:param Limit: 需要返回的数量,默认为10,最大值为100
:type Limit: int
:param Offset: 偏移量,默认为0。
:type Offset: int
:param Filters: 过滤参数,"Filters":[{"Name":"Status","Values":["2"]}]
:type Filters: list of RunTimeFilters
:param Order: 升序降序,asc desc
:type Order: str
:param By: 排序字段
:type By: str
"""
self.ExportField = None
self.Limit = None
self.Offset = None
self.Filters = None
self.Order = None
self.By = None
def _deserialize(self, params):
self.ExportField = params.get("ExportField")
self.Limit = params.get("Limit")
self.Offset = params.get("Offset")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = RunTimeFilters()
obj._deserialize(item)
self.Filters.append(obj)
self.Order = params.get("Order")
self.By = params.get("By")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeRiskSyscallEventsExportResponse(AbstractModel):
"""DescribeRiskSyscallEventsExport返回参数结构体
"""
def __init__(self):
r"""
:param DownloadUrl: Excel下载地址
注意:此字段可能返回 null,表示取不到有效值。
:type DownloadUrl: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.DownloadUrl = None
self.RequestId = None
def _deserialize(self, params):
self.DownloadUrl = params.get("DownloadUrl")
self.RequestId = params.get("RequestId")
class DescribeRiskSyscallEventsRequest(AbstractModel):
"""DescribeRiskSyscallEvents请求参数结构体
"""
def __init__(self):
r"""
:param Limit: 需要返回的数量,默认为10,最大值为100
:type Limit: int
:param Offset: 偏移量,默认为0。
:type Offset: int
:param Filters: 过滤参数,"Filters":[{"Name":"Status","Values":["2"]}]
:type Filters: list of RunTimeFilters
:param Order: 升序降序,asc desc
:type Order: str
:param By: 排序字段
:type By: str
"""
self.Limit = None
self.Offset = None
self.Filters = None
self.Order = None
self.By = None
def _deserialize(self, params):
self.Limit = params.get("Limit")
self.Offset = params.get("Offset")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = RunTimeFilters()
obj._deserialize(item)
self.Filters.append(obj)
self.Order = params.get("Order")
self.By = params.get("By")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeRiskSyscallEventsResponse(AbstractModel):
"""DescribeRiskSyscallEvents返回参数结构体
"""
def __init__(self):
r"""
:param TotalCount: 事件总数量
:type TotalCount: int
:param EventSet: 高危系统调用数组
:type EventSet: list of RiskSyscallEventInfo
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.TotalCount = None
self.EventSet = None
self.RequestId = None
def _deserialize(self, params):
self.TotalCount = params.get("TotalCount")
if params.get("EventSet") is not None:
self.EventSet = []
for item in params.get("EventSet"):
obj = RiskSyscallEventInfo()
obj._deserialize(item)
self.EventSet.append(obj)
self.RequestId = params.get("RequestId")
class DescribeRiskSyscallNamesRequest(AbstractModel):
"""DescribeRiskSyscallNames请求参数结构体
"""
class DescribeRiskSyscallNamesResponse(AbstractModel):
"""DescribeRiskSyscallNames返回参数结构体
"""
def __init__(self):
r"""
:param TotalCount: 事件总数量
:type TotalCount: int
:param SyscallNames: 系统调用名称列表
:type SyscallNames: list of str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.TotalCount = None
self.SyscallNames = None
self.RequestId = None
def _deserialize(self, params):
self.TotalCount = params.get("TotalCount")
self.SyscallNames = params.get("SyscallNames")
self.RequestId = params.get("RequestId")
class DescribeRiskSyscallWhiteListDetailRequest(AbstractModel):
"""DescribeRiskSyscallWhiteListDetail请求参数结构体
"""
def __init__(self):
r"""
:param WhiteListId: 白名单id
:type WhiteListId: str
"""
self.WhiteListId = None
def _deserialize(self, params):
self.WhiteListId = params.get("WhiteListId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeRiskSyscallWhiteListDetailResponse(AbstractModel):
"""DescribeRiskSyscallWhiteListDetail返回参数结构体
"""
def __init__(self):
r"""
:param WhiteListDetailInfo: 白名单基本信息
:type WhiteListDetailInfo: :class:`tencentcloud.tcss.v20201101.models.RiskSyscallWhiteListInfo`
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.WhiteListDetailInfo = None
self.RequestId = None
def _deserialize(self, params):
if params.get("WhiteListDetailInfo") is not None:
self.WhiteListDetailInfo = RiskSyscallWhiteListInfo()
self.WhiteListDetailInfo._deserialize(params.get("WhiteListDetailInfo"))
self.RequestId = params.get("RequestId")
class DescribeRiskSyscallWhiteListsRequest(AbstractModel):
"""DescribeRiskSyscallWhiteLists请求参数结构体
"""
def __init__(self):
r"""
:param Limit: 需要返回的数量,默认为10,最大值为100
:type Limit: int
:param Offset: 偏移量,默认为0。
:type Offset: int
:param Filters: 过滤参数,"Filters":[{"Name":"Status","Values":["2"]}]
:type Filters: list of RunTimeFilters
:param Order: 升序降序,asc desc
:type Order: str
:param By: 排序字段
:type By: str
"""
self.Limit = None
self.Offset = None
self.Filters = None
self.Order = None
self.By = None
def _deserialize(self, params):
self.Limit = params.get("Limit")
self.Offset = params.get("Offset")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = RunTimeFilters()
obj._deserialize(item)
self.Filters.append(obj)
self.Order = params.get("Order")
self.By = params.get("By")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeRiskSyscallWhiteListsResponse(AbstractModel):
"""DescribeRiskSyscallWhiteLists返回参数结构体
"""
def __init__(self):
r"""
:param TotalCount: 事件总数量
:type TotalCount: int
:param WhiteListSet: 白名单信息列表
:type WhiteListSet: list of RiskSyscallWhiteListBaseInfo
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.TotalCount = None
self.WhiteListSet = None
self.RequestId = None
def _deserialize(self, params):
self.TotalCount = params.get("TotalCount")
if params.get("WhiteListSet") is not None:
self.WhiteListSet = []
for item in params.get("WhiteListSet"):
obj = RiskSyscallWhiteListBaseInfo()
obj._deserialize(item)
self.WhiteListSet.append(obj)
self.RequestId = params.get("RequestId")
class DescribeSecEventsTendencyRequest(AbstractModel):
"""DescribeSecEventsTendency请求参数结构体
"""
def __init__(self):
r"""
:param StartTime: 开始时间
:type StartTime: str
:param EndTime: 结束时间
:type EndTime: str
"""
self.StartTime = None
self.EndTime = None
def _deserialize(self, params):
self.StartTime = params.get("StartTime")
self.EndTime = params.get("EndTime")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeSecEventsTendencyResponse(AbstractModel):
"""DescribeSecEventsTendency返回参数结构体
"""
def __init__(self):
r"""
:param EventTendencySet: 运行时安全事件趋势信息列表
:type EventTendencySet: list of SecTendencyEventInfo
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.EventTendencySet = None
self.RequestId = None
def _deserialize(self, params):
if params.get("EventTendencySet") is not None:
self.EventTendencySet = []
for item in params.get("EventTendencySet"):
obj = SecTendencyEventInfo()
obj._deserialize(item)
self.EventTendencySet.append(obj)
self.RequestId = params.get("RequestId")
class DescribeTaskResultSummaryRequest(AbstractModel):
"""DescribeTaskResultSummary请求参数结构体
"""
class DescribeTaskResultSummaryResponse(AbstractModel):
"""DescribeTaskResultSummary返回参数结构体
"""
def __init__(self):
r"""
:param SeriousRiskNodeCount: 严重风险影响的节点数量,返回7天数据
:type SeriousRiskNodeCount: list of int non-negative
:param HighRiskNodeCount: 高风险影响的节点的数量,返回7天数据
:type HighRiskNodeCount: list of int non-negative
:param MiddleRiskNodeCount: 中风险检查项的节点数量,返回7天数据
:type MiddleRiskNodeCount: list of int non-negative
:param HintRiskNodeCount: 提示风险检查项的节点数量,返回7天数据
:type HintRiskNodeCount: list of int non-negative
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.SeriousRiskNodeCount = None
self.HighRiskNodeCount = None
self.MiddleRiskNodeCount = None
self.HintRiskNodeCount = None
self.RequestId = None
def _deserialize(self, params):
self.SeriousRiskNodeCount = params.get("SeriousRiskNodeCount")
self.HighRiskNodeCount = params.get("HighRiskNodeCount")
self.MiddleRiskNodeCount = params.get("MiddleRiskNodeCount")
self.HintRiskNodeCount = params.get("HintRiskNodeCount")
self.RequestId = params.get("RequestId")
class DescribeUnfinishRefreshTaskRequest(AbstractModel):
"""DescribeUnfinishRefreshTask请求参数结构体
"""
class DescribeUnfinishRefreshTaskResponse(AbstractModel):
"""DescribeUnfinishRefreshTask返回参数结构体
"""
def __init__(self):
r"""
:param TaskId: 返回最近的一次任务ID
:type TaskId: int
:param TaskStatus: 任务状态,为Task_New,Task_Running,Task_Finish,Task_Error,Task_NoExist.Task_New,Task_Running表示有任务存在,不允许新下发
:type TaskStatus: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.TaskId = None
self.TaskStatus = None
self.RequestId = None
def _deserialize(self, params):
self.TaskId = params.get("TaskId")
self.TaskStatus = params.get("TaskStatus")
self.RequestId = params.get("RequestId")
class DescribeUserClusterRequest(AbstractModel):
"""DescribeUserCluster请求参数结构体
"""
def __init__(self):
r"""
:param Offset: 偏移量
:type Offset: int
:param Limit: 每次查询的最大记录数量
:type Limit: int
:param Filters: Name - String
Name 可取值:ClusterName,ClusterId,ClusterType,Region,ClusterCheckMode,ClusterAutoCheck
:type Filters: list of ComplianceFilters
:param By: 排序字段
:type By: str
:param Order: 排序方式 asc,desc
:type Order: str
"""
self.Offset = None
self.Limit = None
self.Filters = None
self.By = None
self.Order = None
def _deserialize(self, params):
self.Offset = params.get("Offset")
self.Limit = params.get("Limit")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = ComplianceFilters()
obj._deserialize(item)
self.Filters.append(obj)
self.By = params.get("By")
self.Order = params.get("Order")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeUserClusterResponse(AbstractModel):
"""DescribeUserCluster返回参数结构体
"""
def __init__(self):
r"""
:param TotalCount: 集群总数
:type TotalCount: int
:param ClusterInfoList: 集群的详细信息
:type ClusterInfoList: list of ClusterInfoItem
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.TotalCount = None
self.ClusterInfoList = None
self.RequestId = None
def _deserialize(self, params):
self.TotalCount = params.get("TotalCount")
if params.get("ClusterInfoList") is not None:
self.ClusterInfoList = []
for item in params.get("ClusterInfoList"):
obj = ClusterInfoItem()
obj._deserialize(item)
self.ClusterInfoList.append(obj)
self.RequestId = params.get("RequestId")
class DescribeValueAddedSrvInfoRequest(AbstractModel):
"""DescribeValueAddedSrvInfo请求参数结构体
"""
class DescribeValueAddedSrvInfoResponse(AbstractModel):
"""DescribeValueAddedSrvInfo返回参数结构体
"""
def __init__(self):
r"""
:param RegistryImageCnt: 仓库镜像未授权数量
:type RegistryImageCnt: int
:param LocalImageCnt: 本地镜像未授权数量
:type LocalImageCnt: int
:param UnusedAuthorizedCnt: 未使用的镜像安全扫描授权数
:type UnusedAuthorizedCnt: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RegistryImageCnt = None
self.LocalImageCnt = None
self.UnusedAuthorizedCnt = None
self.RequestId = None
def _deserialize(self, params):
self.RegistryImageCnt = params.get("RegistryImageCnt")
self.LocalImageCnt = params.get("LocalImageCnt")
self.UnusedAuthorizedCnt = params.get("UnusedAuthorizedCnt")
self.RequestId = params.get("RequestId")
class DescribeVirusDetailRequest(AbstractModel):
"""DescribeVirusDetail请求参数结构体
"""
def __init__(self):
r"""
:param Id: 木马文件id
:type Id: str
"""
self.Id = None
def _deserialize(self, params):
self.Id = params.get("Id")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeVirusDetailResponse(AbstractModel):
"""DescribeVirusDetail返回参数结构体
"""
def __init__(self):
r"""
:param ImageId: 镜像ID
注意:此字段可能返回 null,表示取不到有效值。
:type ImageId: str
:param ImageName: 镜像名称
注意:此字段可能返回 null,表示取不到有效值。
:type ImageName: str
:param CreateTime: 创建时间
注意:此字段可能返回 null,表示取不到有效值。
:type CreateTime: str
:param Size: 木马文件大小
注意:此字段可能返回 null,表示取不到有效值。
:type Size: int
:param FilePath: 木马文件路径
注意:此字段可能返回 null,表示取不到有效值。
:type FilePath: str
:param ModifyTime: 最近生成时间
注意:此字段可能返回 null,表示取不到有效值。
:type ModifyTime: str
:param VirusName: 病毒名称
注意:此字段可能返回 null,表示取不到有效值。
:type VirusName: str
:param RiskLevel: 风险等级 RISK_CRITICAL, RISK_HIGH, RISK_MEDIUM, RISK_LOW, RISK_NOTICE。
注意:此字段可能返回 null,表示取不到有效值。
:type RiskLevel: str
:param ContainerName: 容器名称
注意:此字段可能返回 null,表示取不到有效值。
:type ContainerName: str
:param ContainerId: 容器id
注意:此字段可能返回 null,表示取不到有效值。
:type ContainerId: str
:param HostName: 主机名称
注意:此字段可能返回 null,表示取不到有效值。
:type HostName: str
:param HostId: 主机id
注意:此字段可能返回 null,表示取不到有效值。
:type HostId: str
:param ProcessName: 进程名称
注意:此字段可能返回 null,表示取不到有效值。
:type ProcessName: str
:param ProcessPath: 进程路径
注意:此字段可能返回 null,表示取不到有效值。
:type ProcessPath: str
:param ProcessMd5: 进程md5
注意:此字段可能返回 null,表示取不到有效值。
:type ProcessMd5: str
:param ProcessId: 进程id
注意:此字段可能返回 null,表示取不到有效值。
:type ProcessId: int
:param ProcessArgv: 进程参数
注意:此字段可能返回 null,表示取不到有效值。
:type ProcessArgv: str
:param ProcessChan: 进程链
注意:此字段可能返回 null,表示取不到有效值。
:type ProcessChan: str
:param ProcessAccountGroup: 进程组
注意:此字段可能返回 null,表示取不到有效值。
:type ProcessAccountGroup: str
:param ProcessStartAccount: 进程启动用户
注意:此字段可能返回 null,表示取不到有效值。
:type ProcessStartAccount: str
:param ProcessFileAuthority: 进程文件权限
注意:此字段可能返回 null,表示取不到有效值。
:type ProcessFileAuthority: str
:param SourceType: 来源:0:一键扫描, 1:定时扫描 2:实时监控
注意:此字段可能返回 null,表示取不到有效值。
:type SourceType: int
:param PodName: 集群名称
注意:此字段可能返回 null,表示取不到有效值。
:type PodName: str
:param Tags: 标签
注意:此字段可能返回 null,表示取不到有效值。
:type Tags: list of str
:param HarmDescribe: 事件描述
注意:此字段可能返回 null,表示取不到有效值。
:type HarmDescribe: str
:param SuggestScheme: 建议方案
注意:此字段可能返回 null,表示取不到有效值。
:type SuggestScheme: str
:param Mark: 备注
注意:此字段可能返回 null,表示取不到有效值。
:type Mark: str
:param FileName: 风险文件名称
注意:此字段可能返回 null,表示取不到有效值。
:type FileName: str
:param FileMd5: 文件MD5
注意:此字段可能返回 null,表示取不到有效值。
:type FileMd5: str
:param EventType: 事件类型
注意:此字段可能返回 null,表示取不到有效值。
:type EventType: str
:param Status: DEAL_NONE:文件待处理
DEAL_IGNORE:已经忽略
DEAL_ADD_WHITELIST:加白
DEAL_DEL:文件已经删除
DEAL_ISOLATE:已经隔离
DEAL_ISOLATING:隔离中
DEAL_ISOLATE_FAILED:隔离失败
DEAL_RECOVERING:恢复中
DEAL_RECOVER_FAILED: 恢复失败
注意:此字段可能返回 null,表示取不到有效值。
:type Status: str
:param SubStatus: 失败子状态:
FILE_NOT_FOUND:文件不存在
FILE_ABNORMAL:文件异常
FILE_ABNORMAL_DEAL_RECOVER:恢复文件时,文件异常
BACKUP_FILE_NOT_FOUND:备份文件不存在
CONTAINER_NOT_FOUND_DEAL_ISOLATE:隔离时,容器不存在
CONTAINER_NOT_FOUND_DEAL_RECOVER:恢复时,容器不存在
注意:此字段可能返回 null,表示取不到有效值。
:type SubStatus: str
:param HostIP: 内网ip
注意:此字段可能返回 null,表示取不到有效值。
:type HostIP: str
:param ClientIP: 外网ip
注意:此字段可能返回 null,表示取不到有效值。
:type ClientIP: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.ImageId = None
self.ImageName = None
self.CreateTime = None
self.Size = None
self.FilePath = None
self.ModifyTime = None
self.VirusName = None
self.RiskLevel = None
self.ContainerName = None
self.ContainerId = None
self.HostName = None
self.HostId = None
self.ProcessName = None
self.ProcessPath = None
self.ProcessMd5 = None
self.ProcessId = None
self.ProcessArgv = None
self.ProcessChan = None
self.ProcessAccountGroup = None
self.ProcessStartAccount = None
self.ProcessFileAuthority = None
self.SourceType = None
self.PodName = None
self.Tags = None
self.HarmDescribe = None
self.SuggestScheme = None
self.Mark = None
self.FileName = None
self.FileMd5 = None
self.EventType = None
self.Status = None
self.SubStatus = None
self.HostIP = None
self.ClientIP = None
self.RequestId = None
def _deserialize(self, params):
self.ImageId = params.get("ImageId")
self.ImageName = params.get("ImageName")
self.CreateTime = params.get("CreateTime")
self.Size = params.get("Size")
self.FilePath = params.get("FilePath")
self.ModifyTime = params.get("ModifyTime")
self.VirusName = params.get("VirusName")
self.RiskLevel = params.get("RiskLevel")
self.ContainerName = params.get("ContainerName")
self.ContainerId = params.get("ContainerId")
self.HostName = params.get("HostName")
self.HostId = params.get("HostId")
self.ProcessName = params.get("ProcessName")
self.ProcessPath = params.get("ProcessPath")
self.ProcessMd5 = params.get("ProcessMd5")
self.ProcessId = params.get("ProcessId")
self.ProcessArgv = params.get("ProcessArgv")
self.ProcessChan = params.get("ProcessChan")
self.ProcessAccountGroup = params.get("ProcessAccountGroup")
self.ProcessStartAccount = params.get("ProcessStartAccount")
self.ProcessFileAuthority = params.get("ProcessFileAuthority")
self.SourceType = params.get("SourceType")
self.PodName = params.get("PodName")
self.Tags = params.get("Tags")
self.HarmDescribe = params.get("HarmDescribe")
self.SuggestScheme = params.get("SuggestScheme")
self.Mark = params.get("Mark")
self.FileName = params.get("FileName")
self.FileMd5 = params.get("FileMd5")
self.EventType = params.get("EventType")
self.Status = params.get("Status")
self.SubStatus = params.get("SubStatus")
self.HostIP = params.get("HostIP")
self.ClientIP = params.get("ClientIP")
self.RequestId = params.get("RequestId")
class DescribeVirusListRequest(AbstractModel):
"""DescribeVirusList请求参数结构体
"""
def __init__(self):
r"""
:param Limit: 需要返回的数量,默认为10,最大值为100
:type Limit: int
:param Offset: 偏移量,默认为0。
:type Offset: int
:param Filters: 过滤条件。
<li>FileName - String - 是否必填:否 - 文件名称</li>
<li>FilePath - String - 是否必填:否 - 文件路径</li>
<li>VirusName - String - 是否必填:否 - 病毒名称</li>
<li>ContainerName- String - 是否必填:是 - 容器名称</li>
<li>ContainerId- string - 是否必填:否 - 容器id</li>
<li>ImageName- string - 是否必填:否 - 镜像名称</li>
<li>ImageId- string - 是否必填:否 - 镜像id</li>
<li>IsRealTime- int - 是否必填:否 - 过滤是否实时监控数据</li>
<li>TaskId- string - 是否必填:否 - 任务ID</li>
:type Filters: list of RunTimeFilters
:param Order: 排序方式
:type Order: str
:param By: 排序字段
:type By: str
"""
self.Limit = None
self.Offset = None
self.Filters = None
self.Order = None
self.By = None
def _deserialize(self, params):
self.Limit = params.get("Limit")
self.Offset = params.get("Offset")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = RunTimeFilters()
obj._deserialize(item)
self.Filters.append(obj)
self.Order = params.get("Order")
self.By = params.get("By")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeVirusListResponse(AbstractModel):
"""DescribeVirusList返回参数结构体
"""
def __init__(self):
r"""
:param List: 木马列表
:type List: list of VirusInfo
:param TotalCount: 总数量
:type TotalCount: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.List = None
self.TotalCount = None
self.RequestId = None
def _deserialize(self, params):
if params.get("List") is not None:
self.List = []
for item in params.get("List"):
obj = VirusInfo()
obj._deserialize(item)
self.List.append(obj)
self.TotalCount = params.get("TotalCount")
self.RequestId = params.get("RequestId")
class DescribeVirusMonitorSettingRequest(AbstractModel):
"""DescribeVirusMonitorSetting请求参数结构体
"""
class DescribeVirusMonitorSettingResponse(AbstractModel):
"""DescribeVirusMonitorSetting返回参数结构体
"""
def __init__(self):
r"""
:param EnableScan: 是否开启实时监控
:type EnableScan: bool
:param ScanPathAll: 扫描全部路径
注意:此字段可能返回 null,表示取不到有效值。
:type ScanPathAll: bool
:param ScanPathType: 当ScanPathAll为true 生效 0扫描以下路径 1、扫描除以下路径
注意:此字段可能返回 null,表示取不到有效值。
:type ScanPathType: int
:param ScanPath: 自选排除或扫描的地址
注意:此字段可能返回 null,表示取不到有效值。
:type ScanPath: list of str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.EnableScan = None
self.ScanPathAll = None
self.ScanPathType = None
self.ScanPath = None
self.RequestId = None
def _deserialize(self, params):
self.EnableScan = params.get("EnableScan")
self.ScanPathAll = params.get("ScanPathAll")
self.ScanPathType = params.get("ScanPathType")
self.ScanPath = params.get("ScanPath")
self.RequestId = params.get("RequestId")
class DescribeVirusScanSettingRequest(AbstractModel):
"""DescribeVirusScanSetting请求参数结构体
"""
class DescribeVirusScanSettingResponse(AbstractModel):
"""DescribeVirusScanSetting返回参数结构体
"""
def __init__(self):
r"""
:param EnableScan: 是否开启定期扫描
:type EnableScan: bool
:param Cycle: 检测周期每隔多少天
:type Cycle: int
:param BeginScanAt: 扫描开始时间
:type BeginScanAt: str
:param ScanPathAll: 扫描全部路径
:type ScanPathAll: bool
:param ScanPathType: 当ScanPathAll为true 生效 0扫描以下路径 1、扫描除以下路径
:type ScanPathType: int
:param Timeout: 超时时长,单位小时
:type Timeout: int
:param ScanRangeType: 扫描范围0容器1主机节点
:type ScanRangeType: int
:param ScanRangeAll: true 全选,false 自选
:type ScanRangeAll: bool
:param ScanIds: 自选扫描范围的容器id或者主机id 根据ScanRangeType决定
:type ScanIds: list of str
:param ScanPath: 自选排除或扫描的地址
:type ScanPath: list of str
:param ClickTimeout: 一键检测的超时设置
注意:此字段可能返回 null,表示取不到有效值。
:type ClickTimeout: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.EnableScan = None
self.Cycle = None
self.BeginScanAt = None
self.ScanPathAll = None
self.ScanPathType = None
self.Timeout = None
self.ScanRangeType = None
self.ScanRangeAll = None
self.ScanIds = None
self.ScanPath = None
self.ClickTimeout = None
self.RequestId = None
def _deserialize(self, params):
self.EnableScan = params.get("EnableScan")
self.Cycle = params.get("Cycle")
self.BeginScanAt = params.get("BeginScanAt")
self.ScanPathAll = params.get("ScanPathAll")
self.ScanPathType = params.get("ScanPathType")
self.Timeout = params.get("Timeout")
self.ScanRangeType = params.get("ScanRangeType")
self.ScanRangeAll = params.get("ScanRangeAll")
self.ScanIds = params.get("ScanIds")
self.ScanPath = params.get("ScanPath")
self.ClickTimeout = params.get("ClickTimeout")
self.RequestId = params.get("RequestId")
class DescribeVirusScanTaskStatusRequest(AbstractModel):
"""DescribeVirusScanTaskStatus请求参数结构体
"""
def __init__(self):
r"""
:param TaskID: 任务id
:type TaskID: str
"""
self.TaskID = None
def _deserialize(self, params):
self.TaskID = params.get("TaskID")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeVirusScanTaskStatusResponse(AbstractModel):
"""DescribeVirusScanTaskStatus返回参数结构体
"""
def __init__(self):
r"""
:param ContainerTotal: 查杀容器个数
:type ContainerTotal: int
:param RiskContainerCnt: 风险容器个数
:type RiskContainerCnt: int
:param Status: 扫描状态 任务状态:
SCAN_NONE:无,
SCAN_SCANNING:正在扫描中,
SCAN_FINISH:扫描完成,
SCAN_TIMEOUT:扫描超时
SCAN_CANCELING: 取消中
SCAN_CANCELED:已取消
:type Status: str
:param Schedule: 扫描进度 I
:type Schedule: int
:param ContainerScanCnt: 已经扫描了的容器个数
:type ContainerScanCnt: int
:param RiskCnt: 风险个数
:type RiskCnt: int
:param LeftSeconds: 剩余扫描时间
:type LeftSeconds: int
:param StartTime: 扫描开始时间
:type StartTime: str
:param EndTime: 扫描结束时间
:type EndTime: str
:param ScanType: 扫描类型,"CYCLE":周期扫描, "MANUAL":手动扫描
:type ScanType: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.ContainerTotal = None
self.RiskContainerCnt = None
self.Status = None
self.Schedule = None
self.ContainerScanCnt = None
self.RiskCnt = None
self.LeftSeconds = None
self.StartTime = None
self.EndTime = None
self.ScanType = None
self.RequestId = None
def _deserialize(self, params):
self.ContainerTotal = params.get("ContainerTotal")
self.RiskContainerCnt = params.get("RiskContainerCnt")
self.Status = params.get("Status")
self.Schedule = params.get("Schedule")
self.ContainerScanCnt = params.get("ContainerScanCnt")
self.RiskCnt = params.get("RiskCnt")
self.LeftSeconds = params.get("LeftSeconds")
self.StartTime = params.get("StartTime")
self.EndTime = params.get("EndTime")
self.ScanType = params.get("ScanType")
self.RequestId = params.get("RequestId")
class DescribeVirusScanTimeoutSettingRequest(AbstractModel):
"""DescribeVirusScanTimeoutSetting请求参数结构体
"""
def __init__(self):
r"""
:param ScanType: 设置类型0一键检测,1定时检测
:type ScanType: int
"""
self.ScanType = None
def _deserialize(self, params):
self.ScanType = params.get("ScanType")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeVirusScanTimeoutSettingResponse(AbstractModel):
"""DescribeVirusScanTimeoutSetting返回参数结构体
"""
def __init__(self):
r"""
:param Timeout: 超时时长单位小时
注意:此字段可能返回 null,表示取不到有效值。
:type Timeout: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.Timeout = None
self.RequestId = None
def _deserialize(self, params):
self.Timeout = params.get("Timeout")
self.RequestId = params.get("RequestId")
class DescribeVirusSummaryRequest(AbstractModel):
"""DescribeVirusSummary请求参数结构体
"""
class DescribeVirusSummaryResponse(AbstractModel):
"""DescribeVirusSummary返回参数结构体
"""
def __init__(self):
r"""
:param TaskId: 最近的一次扫描任务id
:type TaskId: str
:param RiskContainerCnt: 木马影响容器个数
注意:此字段可能返回 null,表示取不到有效值。
:type RiskContainerCnt: int
:param RiskCnt: 待处理风险个数
注意:此字段可能返回 null,表示取不到有效值。
:type RiskCnt: int
:param VirusDataBaseModifyTime: 病毒库更新时间
注意:此字段可能返回 null,表示取不到有效值。
:type VirusDataBaseModifyTime: str
:param RiskContainerIncrease: 木马影响容器个数较昨日增长
注意:此字段可能返回 null,表示取不到有效值。
:type RiskContainerIncrease: int
:param RiskIncrease: 待处理风险个数较昨日增长
注意:此字段可能返回 null,表示取不到有效值。
:type RiskIncrease: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.TaskId = None
self.RiskContainerCnt = None
self.RiskCnt = None
self.VirusDataBaseModifyTime = None
self.RiskContainerIncrease = None
self.RiskIncrease = None
self.RequestId = None
def _deserialize(self, params):
self.TaskId = params.get("TaskId")
self.RiskContainerCnt = params.get("RiskContainerCnt")
self.RiskCnt = params.get("RiskCnt")
self.VirusDataBaseModifyTime = params.get("VirusDataBaseModifyTime")
self.RiskContainerIncrease = params.get("RiskContainerIncrease")
self.RiskIncrease = params.get("RiskIncrease")
self.RequestId = params.get("RequestId")
class DescribeVirusTaskListRequest(AbstractModel):
"""DescribeVirusTaskList请求参数结构体
"""
def __init__(self):
r"""
:param TaskId: 任务id
:type TaskId: str
:param Limit: 需要返回的数量,默认为10,最大值为100
:type Limit: int
:param Offset: 偏移量,默认为0。
:type Offset: int
:param Filters: 过滤条件。
<li>ContainerName - String - 是否必填:否 - 容器名称</li>
<li>ContainerId - String - 是否必填:否 - 容器id</li>
<li>Hostname - String - 是否必填:否 - 主机名称</li>
<li>HostIp- String - 是否必填:是 - 容器名称</li>
:type Filters: list of RunTimeFilters
:param By: 排序字段
:type By: str
:param Order: 排序方式
:type Order: str
"""
self.TaskId = None
self.Limit = None
self.Offset = None
self.Filters = None
self.By = None
self.Order = None
def _deserialize(self, params):
self.TaskId = params.get("TaskId")
self.Limit = params.get("Limit")
self.Offset = params.get("Offset")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = RunTimeFilters()
obj._deserialize(item)
self.Filters.append(obj)
self.By = params.get("By")
self.Order = params.get("Order")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DescribeVirusTaskListResponse(AbstractModel):
"""DescribeVirusTaskList返回参数结构体
"""
def __init__(self):
r"""
:param List: 文件查杀列表
:type List: list of VirusTaskInfo
:param TotalCount: 总数量(容器任务数量)
:type TotalCount: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.List = None
self.TotalCount = None
self.RequestId = None
def _deserialize(self, params):
if params.get("List") is not None:
self.List = []
for item in params.get("List"):
obj = VirusTaskInfo()
obj._deserialize(item)
self.List.append(obj)
self.TotalCount = params.get("TotalCount")
self.RequestId = params.get("RequestId")
class DescribeWarningRulesRequest(AbstractModel):
"""DescribeWarningRules请求参数结构体
"""
class DescribeWarningRulesResponse(AbstractModel):
"""DescribeWarningRules返回参数结构体
"""
def __init__(self):
r"""
:param WarningRules: 告警策略列表
:type WarningRules: list of WarningRule
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.WarningRules = None
self.RequestId = None
def _deserialize(self, params):
if params.get("WarningRules") is not None:
self.WarningRules = []
for item in params.get("WarningRules"):
obj = WarningRule()
obj._deserialize(item)
self.WarningRules.append(obj)
self.RequestId = params.get("RequestId")
class EscapeEventDescription(AbstractModel):
"""运行时容器逃逸事件描述信息
"""
def __init__(self):
r"""
:param Description: 事件规则
:type Description: str
:param Solution: 解决方案
:type Solution: str
:param Remark: 事件备注信息
注意:此字段可能返回 null,表示取不到有效值。
:type Remark: str
"""
self.Description = None
self.Solution = None
self.Remark = None
def _deserialize(self, params):
self.Description = params.get("Description")
self.Solution = params.get("Solution")
self.Remark = params.get("Remark")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class EscapeEventInfo(AbstractModel):
"""容器逃逸事件列表
"""
def __init__(self):
r"""
:param EventType: 事件类型
ESCAPE_HOST_ACESS_FILE:宿主机文件访问逃逸
ESCAPE_MOUNT_NAMESPACE:MountNamespace逃逸
ESCAPE_PRIVILEDGE:程序提权逃逸
ESCAPE_PRIVILEDGE_CONTAINER_START:特权容器启动逃逸
ESCAPE_MOUNT_SENSITIVE_PTAH:敏感路径挂载
ESCAPE_SYSCALL:Syscall逃逸
:type EventType: str
:param ContainerName: 容器名
:type ContainerName: str
:param ImageName: 镜像名
:type ImageName: str
:param Status: 状态
EVENT_UNDEAL:事件未处理
EVENT_DEALED:事件已经处理
EVENT_INGNORE:事件忽略
:type Status: str
:param EventId: 事件记录的唯一id
:type EventId: str
:param NodeName: 节点名称
:type NodeName: str
:param PodName: pod(实例)的名字
:type PodName: str
:param FoundTime: 生成时间
:type FoundTime: str
:param EventName: 事件名字,
宿主机文件访问逃逸、
Syscall逃逸、
MountNamespace逃逸、
程序提权逃逸、
特权容器启动逃逸、
敏感路径挂载
:type EventName: str
:param ImageId: 镜像id,用于跳转
:type ImageId: str
:param ContainerId: 容器id,用于跳转
:type ContainerId: str
:param Solution: 事件解决方案
:type Solution: str
:param Description: 事件描述
:type Description: str
:param EventCount: 事件数量
:type EventCount: int
:param LatestFoundTime: 最近生成时间
:type LatestFoundTime: str
"""
self.EventType = None
self.ContainerName = None
self.ImageName = None
self.Status = None
self.EventId = None
self.NodeName = None
self.PodName = None
self.FoundTime = None
self.EventName = None
self.ImageId = None
self.ContainerId = None
self.Solution = None
self.Description = None
self.EventCount = None
self.LatestFoundTime = None
def _deserialize(self, params):
self.EventType = params.get("EventType")
self.ContainerName = params.get("ContainerName")
self.ImageName = params.get("ImageName")
self.Status = params.get("Status")
self.EventId = params.get("EventId")
self.NodeName = params.get("NodeName")
self.PodName = params.get("PodName")
self.FoundTime = params.get("FoundTime")
self.EventName = params.get("EventName")
self.ImageId = params.get("ImageId")
self.ContainerId = params.get("ContainerId")
self.Solution = params.get("Solution")
self.Description = params.get("Description")
self.EventCount = params.get("EventCount")
self.LatestFoundTime = params.get("LatestFoundTime")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class EscapeRule(AbstractModel):
"""容器逃逸扫描策略开关信息
"""
def __init__(self):
r"""
:param Type: 规则类型
ESCAPE_HOST_ACESS_FILE:宿主机文件访问逃逸
ESCAPE_MOUNT_NAMESPACE:MountNamespace逃逸
ESCAPE_PRIVILEDGE:程序提权逃逸
ESCAPE_PRIVILEDGE_CONTAINER_START:特权容器启动逃逸
ESCAPE_MOUNT_SENSITIVE_PTAH:敏感路径挂载
ESCAPE_SYSCALL:Syscall逃逸
:type Type: str
:param Name: 规则名称
宿主机文件访问逃逸、
Syscall逃逸、
MountNamespace逃逸、
程序提权逃逸、
特权容器启动逃逸、
敏感路径挂载
:type Name: str
:param IsEnable: 是否打开:false否 ,true是
:type IsEnable: bool
"""
self.Type = None
self.Name = None
self.IsEnable = None
def _deserialize(self, params):
self.Type = params.get("Type")
self.Name = params.get("Name")
self.IsEnable = params.get("IsEnable")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class EscapeRuleEnabled(AbstractModel):
"""修改容器逃逸扫描策略开关信息
"""
def __init__(self):
r"""
:param Type: 规则类型
ESCAPE_HOST_ACESS_FILE:宿主机文件访问逃逸
ESCAPE_MOUNT_NAMESPACE:MountNamespace逃逸
ESCAPE_PRIVILEDGE:程序提权逃逸
ESCAPE_PRIVILEDGE_CONTAINER_START:特权容器启动逃逸
ESCAPE_MOUNT_SENSITIVE_PTAH:敏感路径挂载
ESCAPE_SYSCALL:Syscall逃逸
:type Type: str
:param IsEnable: 是否打开:false否 ,true是
:type IsEnable: bool
"""
self.Type = None
self.IsEnable = None
def _deserialize(self, params):
self.Type = params.get("Type")
self.IsEnable = params.get("IsEnable")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ExportVirusListRequest(AbstractModel):
"""ExportVirusList请求参数结构体
"""
def __init__(self):
r"""
:param Filters: 过滤条件。
<li>FileName - String - 是否必填:否 - 文件名称</li>
<li>FilePath - String - 是否必填:否 - 文件路径</li>
<li>VirusName - String - 是否必填:否 - 病毒名称</li>
<li>ContainerName- String - 是否必填:是 - 容器名称</li>
<li>ContainerId- string - 是否必填:否 - 容器id</li>
<li>ImageName- string - 是否必填:否 - 镜像名称</li>
<li>ImageId- string - 是否必填:否 - 镜像id</li>
:type Filters: list of RunTimeFilters
:param Order: 排序方式
:type Order: str
:param By: 排序字段
:type By: str
:param ExportField: 导出字段
:type ExportField: list of str
"""
self.Filters = None
self.Order = None
self.By = None
self.ExportField = None
def _deserialize(self, params):
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = RunTimeFilters()
obj._deserialize(item)
self.Filters.append(obj)
self.Order = params.get("Order")
self.By = params.get("By")
self.ExportField = params.get("ExportField")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ExportVirusListResponse(AbstractModel):
"""ExportVirusList返回参数结构体
"""
def __init__(self):
r"""
:param JobId: 导出任务ID,前端拿着任务ID查询任务进度
:type JobId: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.JobId = None
self.RequestId = None
def _deserialize(self, params):
self.JobId = params.get("JobId")
self.RequestId = params.get("RequestId")
class FileAttributeInfo(AbstractModel):
"""容器安全运行时,文件属性信息
"""
def __init__(self):
r"""
:param FileName: 文件名
:type FileName: str
:param FileType: 文件类型
:type FileType: str
:param FileSize: 文件大小(字节)
:type FileSize: int
:param FilePath: 文件路径
:type FilePath: str
:param FileCreateTime: 文件创建时间
:type FileCreateTime: str
:param LatestTamperedFileMTime: 最近被篡改文件创建时间
:type LatestTamperedFileMTime: str
"""
self.FileName = None
self.FileType = None
self.FileSize = None
self.FilePath = None
self.FileCreateTime = None
self.LatestTamperedFileMTime = None
def _deserialize(self, params):
self.FileName = params.get("FileName")
self.FileType = params.get("FileType")
self.FileSize = params.get("FileSize")
self.FilePath = params.get("FilePath")
self.FileCreateTime = params.get("FileCreateTime")
self.LatestTamperedFileMTime = params.get("LatestTamperedFileMTime")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class HostInfo(AbstractModel):
"""容器安全主机列表
"""
def __init__(self):
r"""
:param HostID: 主机id
:type HostID: str
:param HostIP: 主机ip即内网ip
:type HostIP: str
:param HostName: 主机名称
:type HostName: str
:param Group: 业务组
:type Group: str
:param DockerVersion: docker 版本
:type DockerVersion: str
:param DockerFileSystemDriver: docker 文件系统类型
:type DockerFileSystemDriver: str
:param ImageCnt: 镜像个数
:type ImageCnt: int
:param ContainerCnt: 容器个数
:type ContainerCnt: int
:param Status: agent运行状态
:type Status: str
:param IsContainerd: 是否是Containerd
:type IsContainerd: bool
:param MachineType: 主机来源:["CVM", "ECM", "LH", "BM"] 中的之一为腾讯云服务器;["Other"]之一非腾讯云服务器;
:type MachineType: str
:param PublicIp: 外网ip
:type PublicIp: str
:param Uuid: 主机uuid
:type Uuid: str
:param InstanceID: 主机实例ID
:type InstanceID: str
:param RegionID: 地域ID
:type RegionID: int
"""
self.HostID = None
self.HostIP = None
self.HostName = None
self.Group = None
self.DockerVersion = None
self.DockerFileSystemDriver = None
self.ImageCnt = None
self.ContainerCnt = None
self.Status = None
self.IsContainerd = None
self.MachineType = None
self.PublicIp = None
self.Uuid = None
self.InstanceID = None
self.RegionID = None
def _deserialize(self, params):
self.HostID = params.get("HostID")
self.HostIP = params.get("HostIP")
self.HostName = params.get("HostName")
self.Group = params.get("Group")
self.DockerVersion = params.get("DockerVersion")
self.DockerFileSystemDriver = params.get("DockerFileSystemDriver")
self.ImageCnt = params.get("ImageCnt")
self.ContainerCnt = params.get("ContainerCnt")
self.Status = params.get("Status")
self.IsContainerd = params.get("IsContainerd")
self.MachineType = params.get("MachineType")
self.PublicIp = params.get("PublicIp")
self.Uuid = params.get("Uuid")
self.InstanceID = params.get("InstanceID")
self.RegionID = params.get("RegionID")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ImageHost(AbstractModel):
"""容器安全 主机镜像关联列表
"""
def __init__(self):
r"""
:param ImageID: 镜像id
:type ImageID: str
:param HostID: 主机id
:type HostID: str
"""
self.ImageID = None
self.HostID = None
def _deserialize(self, params):
self.ImageID = params.get("ImageID")
self.HostID = params.get("HostID")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ImageInfo(AbstractModel):
"""基本镜像信息
"""
def __init__(self):
r"""
:param InstanceName: 实例名称
:type InstanceName: str
:param Namespace: 命名空间
:type Namespace: str
:param ImageName: 镜像名称
:type ImageName: str
:param ImageTag: 镜像tag
:type ImageTag: str
:param Force: 强制扫描
:type Force: str
:param ImageDigest: 镜像id
:type ImageDigest: str
:param RegistryType: 仓库类型
:type RegistryType: str
:param ImageRepoAddress: 镜像仓库地址
:type ImageRepoAddress: str
:param InstanceId: 实例id
:type InstanceId: str
"""
self.InstanceName = None
self.Namespace = None
self.ImageName = None
self.ImageTag = None
self.Force = None
self.ImageDigest = None
self.RegistryType = None
self.ImageRepoAddress = None
self.InstanceId = None
def _deserialize(self, params):
self.InstanceName = params.get("InstanceName")
self.Namespace = params.get("Namespace")
self.ImageName = params.get("ImageName")
self.ImageTag = params.get("ImageTag")
self.Force = params.get("Force")
self.ImageDigest = params.get("ImageDigest")
self.RegistryType = params.get("RegistryType")
self.ImageRepoAddress = params.get("ImageRepoAddress")
self.InstanceId = params.get("InstanceId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ImageProgress(AbstractModel):
"""基本镜像信息
"""
def __init__(self):
r"""
:param ImageId: 镜像id
注意:此字段可能返回 null,表示取不到有效值。
:type ImageId: str
:param RegistryType: 仓库类型
注意:此字段可能返回 null,表示取不到有效值。
:type RegistryType: str
:param ImageRepoAddress: 镜像仓库地址
注意:此字段可能返回 null,表示取不到有效值。
:type ImageRepoAddress: str
:param InstanceId: 实例id
注意:此字段可能返回 null,表示取不到有效值。
:type InstanceId: str
:param InstanceName: 实例名称
注意:此字段可能返回 null,表示取不到有效值。
:type InstanceName: str
:param Namespace: 命名空间
注意:此字段可能返回 null,表示取不到有效值。
:type Namespace: str
:param ImageName: 仓库名称
注意:此字段可能返回 null,表示取不到有效值。
:type ImageName: str
:param ImageTag: 镜像tag
注意:此字段可能返回 null,表示取不到有效值。
:type ImageTag: str
:param ScanStatus: 镜像扫描状态
注意:此字段可能返回 null,表示取不到有效值。
:type ScanStatus: str
:param CveProgress: 镜像cve扫描进度
注意:此字段可能返回 null,表示取不到有效值。
:type CveProgress: int
:param RiskProgress: 镜像敏感扫描进度
注意:此字段可能返回 null,表示取不到有效值。
:type RiskProgress: int
:param VirusProgress: 镜像木马扫描进度
注意:此字段可能返回 null,表示取不到有效值。
:type VirusProgress: int
"""
self.ImageId = None
self.RegistryType = None
self.ImageRepoAddress = None
self.InstanceId = None
self.InstanceName = None
self.Namespace = None
self.ImageName = None
self.ImageTag = None
self.ScanStatus = None
self.CveProgress = None
self.RiskProgress = None
self.VirusProgress = None
def _deserialize(self, params):
self.ImageId = params.get("ImageId")
self.RegistryType = params.get("RegistryType")
self.ImageRepoAddress = params.get("ImageRepoAddress")
self.InstanceId = params.get("InstanceId")
self.InstanceName = params.get("InstanceName")
self.Namespace = params.get("Namespace")
self.ImageName = params.get("ImageName")
self.ImageTag = params.get("ImageTag")
self.ScanStatus = params.get("ScanStatus")
self.CveProgress = params.get("CveProgress")
self.RiskProgress = params.get("RiskProgress")
self.VirusProgress = params.get("VirusProgress")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ImageRepoInfo(AbstractModel):
"""容器安全镜像仓库列表
"""
def __init__(self):
r"""
:param ImageDigest: 镜像Digest
:type ImageDigest: str
:param ImageRepoAddress: 镜像仓库地址
:type ImageRepoAddress: str
:param RegistryType: 仓库类型
:type RegistryType: str
:param ImageName: 镜像名称
:type ImageName: str
:param ImageTag: 镜像版本
:type ImageTag: str
:param ImageSize: 镜像大小
:type ImageSize: int
:param ScanTime: 最近扫描时间
:type ScanTime: str
:param ScanStatus: 扫描状态
:type ScanStatus: str
:param VulCnt: 安全漏洞数
:type VulCnt: int
:param VirusCnt: 木马病毒数
:type VirusCnt: int
:param RiskCnt: 风险行为数
:type RiskCnt: int
:param SentiveInfoCnt: 敏感信息数
:type SentiveInfoCnt: int
:param IsTrustImage: 是否可信镜像
:type IsTrustImage: bool
:param OsName: 镜像系统
:type OsName: str
:param ScanVirusError: 木马扫描错误
注意:此字段可能返回 null,表示取不到有效值。
:type ScanVirusError: str
:param ScanVulError: 漏洞扫描错误
注意:此字段可能返回 null,表示取不到有效值。
:type ScanVulError: str
:param InstanceId: 实例id
:type InstanceId: str
:param InstanceName: 实例名称
:type InstanceName: str
:param Namespace: 命名空间
:type Namespace: str
:param ScanRiskError: 高危扫描错误
注意:此字段可能返回 null,表示取不到有效值。
:type ScanRiskError: str
:param ScanVirusProgress: 敏感信息扫描进度
注意:此字段可能返回 null,表示取不到有效值。
:type ScanVirusProgress: int
:param ScanVulProgress: 木马扫描进度
注意:此字段可能返回 null,表示取不到有效值。
:type ScanVulProgress: int
:param ScanRiskProgress: 漏洞扫描进度
注意:此字段可能返回 null,表示取不到有效值。
:type ScanRiskProgress: int
:param ScanRemainTime: 剩余扫描时间秒
注意:此字段可能返回 null,表示取不到有效值。
:type ScanRemainTime: int
:param CveStatus: cve扫描状态
注意:此字段可能返回 null,表示取不到有效值。
:type CveStatus: str
:param RiskStatus: 高危扫描状态
注意:此字段可能返回 null,表示取不到有效值。
:type RiskStatus: str
:param VirusStatus: 木马扫描状态
注意:此字段可能返回 null,表示取不到有效值。
:type VirusStatus: str
:param Progress: 总进度
注意:此字段可能返回 null,表示取不到有效值。
:type Progress: int
:param IsAuthorized: 授权状态
:type IsAuthorized: int
:param RegistryRegion: 仓库区域
:type RegistryRegion: str
:param Id: 列表id
:type Id: int
:param ImageId: 镜像Id
注意:此字段可能返回 null,表示取不到有效值。
:type ImageId: str
:param ImageCreateTime: 镜像创建的时间
注意:此字段可能返回 null,表示取不到有效值。
:type ImageCreateTime: str
:param IsLatestImage: 是否为镜像的最新版本
注意:此字段可能返回 null,表示取不到有效值。
:type IsLatestImage: bool
"""
self.ImageDigest = None
self.ImageRepoAddress = None
self.RegistryType = None
self.ImageName = None
self.ImageTag = None
self.ImageSize = None
self.ScanTime = None
self.ScanStatus = None
self.VulCnt = None
self.VirusCnt = None
self.RiskCnt = None
self.SentiveInfoCnt = None
self.IsTrustImage = None
self.OsName = None
self.ScanVirusError = None
self.ScanVulError = None
self.InstanceId = None
self.InstanceName = None
self.Namespace = None
self.ScanRiskError = None
self.ScanVirusProgress = None
self.ScanVulProgress = None
self.ScanRiskProgress = None
self.ScanRemainTime = None
self.CveStatus = None
self.RiskStatus = None
self.VirusStatus = None
self.Progress = None
self.IsAuthorized = None
self.RegistryRegion = None
self.Id = None
self.ImageId = None
self.ImageCreateTime = None
self.IsLatestImage = None
def _deserialize(self, params):
self.ImageDigest = params.get("ImageDigest")
self.ImageRepoAddress = params.get("ImageRepoAddress")
self.RegistryType = params.get("RegistryType")
self.ImageName = params.get("ImageName")
self.ImageTag = params.get("ImageTag")
self.ImageSize = params.get("ImageSize")
self.ScanTime = params.get("ScanTime")
self.ScanStatus = params.get("ScanStatus")
self.VulCnt = params.get("VulCnt")
self.VirusCnt = params.get("VirusCnt")
self.RiskCnt = params.get("RiskCnt")
self.SentiveInfoCnt = params.get("SentiveInfoCnt")
self.IsTrustImage = params.get("IsTrustImage")
self.OsName = params.get("OsName")
self.ScanVirusError = params.get("ScanVirusError")
self.ScanVulError = params.get("ScanVulError")
self.InstanceId = params.get("InstanceId")
self.InstanceName = params.get("InstanceName")
self.Namespace = params.get("Namespace")
self.ScanRiskError = params.get("ScanRiskError")
self.ScanVirusProgress = params.get("ScanVirusProgress")
self.ScanVulProgress = params.get("ScanVulProgress")
self.ScanRiskProgress = params.get("ScanRiskProgress")
self.ScanRemainTime = params.get("ScanRemainTime")
self.CveStatus = params.get("CveStatus")
self.RiskStatus = params.get("RiskStatus")
self.VirusStatus = params.get("VirusStatus")
self.Progress = params.get("Progress")
self.IsAuthorized = params.get("IsAuthorized")
self.RegistryRegion = params.get("RegistryRegion")
self.Id = params.get("Id")
self.ImageId = params.get("ImageId")
self.ImageCreateTime = params.get("ImageCreateTime")
self.IsLatestImage = params.get("IsLatestImage")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ImageRisk(AbstractModel):
"""容器安全镜像高危行为信息
"""
def __init__(self):
r"""
:param Behavior: 高危行为
注意:此字段可能返回 null,表示取不到有效值。
:type Behavior: int
:param Type: 种类
注意:此字段可能返回 null,表示取不到有效值。
:type Type: int
:param Level: 风险等级
注意:此字段可能返回 null,表示取不到有效值。
:type Level: str
:param Desc: 描述
注意:此字段可能返回 null,表示取不到有效值。
:type Desc: str
:param InstructionContent: 解决方案
注意:此字段可能返回 null,表示取不到有效值。
:type InstructionContent: str
"""
self.Behavior = None
self.Type = None
self.Level = None
self.Desc = None
self.InstructionContent = None
def _deserialize(self, params):
self.Behavior = params.get("Behavior")
self.Type = params.get("Type")
self.Level = params.get("Level")
self.Desc = params.get("Desc")
self.InstructionContent = params.get("InstructionContent")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ImageRiskInfo(AbstractModel):
"""镜像风险详情
"""
def __init__(self):
r"""
:param Behavior: 行为
:type Behavior: int
:param Type: 类型
:type Type: int
:param Level: 级别
:type Level: int
:param Desc: 详情
:type Desc: str
:param InstructionContent: 解决方案
:type InstructionContent: str
"""
self.Behavior = None
self.Type = None
self.Level = None
self.Desc = None
self.InstructionContent = None
def _deserialize(self, params):
self.Behavior = params.get("Behavior")
self.Type = params.get("Type")
self.Level = params.get("Level")
self.Desc = params.get("Desc")
self.InstructionContent = params.get("InstructionContent")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ImageRiskTendencyInfo(AbstractModel):
"""运行时安全事件趋势信息
"""
def __init__(self):
r"""
:param ImageRiskSet: 趋势列表
:type ImageRiskSet: list of RunTimeTendencyInfo
:param ImageRiskType: 风险类型:
IRT_VULNERABILITY : 安全漏洞
IRT_MALWARE_VIRUS: 木马病毒
IRT_RISK:敏感信息
:type ImageRiskType: str
"""
self.ImageRiskSet = None
self.ImageRiskType = None
def _deserialize(self, params):
if params.get("ImageRiskSet") is not None:
self.ImageRiskSet = []
for item in params.get("ImageRiskSet"):
obj = RunTimeTendencyInfo()
obj._deserialize(item)
self.ImageRiskSet.append(obj)
self.ImageRiskType = params.get("ImageRiskType")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ImageSimpleInfo(AbstractModel):
"""镜像列表
"""
def __init__(self):
r"""
:param ImageID: 镜像id
:type ImageID: str
:param ImageName: 镜像名称
:type ImageName: str
:param Size: 镜像大小
:type Size: int
:param ImageType: 类型
:type ImageType: str
:param ContainerCnt: 关联容器数
:type ContainerCnt: int
"""
self.ImageID = None
self.ImageName = None
self.Size = None
self.ImageType = None
self.ContainerCnt = None
def _deserialize(self, params):
self.ImageID = params.get("ImageID")
self.ImageName = params.get("ImageName")
self.Size = params.get("Size")
self.ImageType = params.get("ImageType")
self.ContainerCnt = params.get("ContainerCnt")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ImageVirus(AbstractModel):
"""容器安全镜像病毒信息
"""
def __init__(self):
r"""
:param Path: 路径
注意:此字段可能返回 null,表示取不到有效值。
:type Path: str
:param RiskLevel: 风险等级
注意:此字段可能返回 null,表示取不到有效值。
:type RiskLevel: str
:param Category: 分类
注意:此字段可能返回 null,表示取不到有效值。
:type Category: str
:param VirusName: 病毒名称
注意:此字段可能返回 null,表示取不到有效值。
:type VirusName: str
:param Tags: 标签
注意:此字段可能返回 null,表示取不到有效值。
:type Tags: list of str
:param Desc: 描述
注意:此字段可能返回 null,表示取不到有效值。
:type Desc: str
:param Solution: 解决方案
注意:此字段可能返回 null,表示取不到有效值。
:type Solution: str
:param FileType: 文件类型
注意:此字段可能返回 null,表示取不到有效值。
:type FileType: str
:param FileName: 文件路径
注意:此字段可能返回 null,表示取不到有效值。
:type FileName: str
:param FileMd5: 文件md5
注意:此字段可能返回 null,表示取不到有效值。
:type FileMd5: str
:param FileSize: 大小
注意:此字段可能返回 null,表示取不到有效值。
:type FileSize: int
:param FirstScanTime: 首次发现时间
注意:此字段可能返回 null,表示取不到有效值。
:type FirstScanTime: str
:param LatestScanTime: 最近扫描时间
注意:此字段可能返回 null,表示取不到有效值。
:type LatestScanTime: str
"""
self.Path = None
self.RiskLevel = None
self.Category = None
self.VirusName = None
self.Tags = None
self.Desc = None
self.Solution = None
self.FileType = None
self.FileName = None
self.FileMd5 = None
self.FileSize = None
self.FirstScanTime = None
self.LatestScanTime = None
def _deserialize(self, params):
self.Path = params.get("Path")
self.RiskLevel = params.get("RiskLevel")
self.Category = params.get("Category")
self.VirusName = params.get("VirusName")
self.Tags = params.get("Tags")
self.Desc = params.get("Desc")
self.Solution = params.get("Solution")
self.FileType = params.get("FileType")
self.FileName = params.get("FileName")
self.FileMd5 = params.get("FileMd5")
self.FileSize = params.get("FileSize")
self.FirstScanTime = params.get("FirstScanTime")
self.LatestScanTime = params.get("LatestScanTime")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ImageVirusInfo(AbstractModel):
"""容器安全镜像病毒信息
"""
def __init__(self):
r"""
:param Path: 路径
注意:此字段可能返回 null,表示取不到有效值。
:type Path: str
:param RiskLevel: 风险等级
注意:此字段可能返回 null,表示取不到有效值。
:type RiskLevel: int
:param VirusName: 病毒名称
注意:此字段可能返回 null,表示取不到有效值。
:type VirusName: str
:param Tags: 标签
注意:此字段可能返回 null,表示取不到有效值。
:type Tags: list of str
:param Desc: 描述
注意:此字段可能返回 null,表示取不到有效值。
:type Desc: str
:param Solution: 修护建议
注意:此字段可能返回 null,表示取不到有效值。
:type Solution: str
:param Size: 大小
注意:此字段可能返回 null,表示取不到有效值。
:type Size: int
:param FirstScanTime: 首次发现时间
注意:此字段可能返回 null,表示取不到有效值。
:type FirstScanTime: str
:param LatestScanTime: 最近扫描时间
注意:此字段可能返回 null,表示取不到有效值。
:type LatestScanTime: str
:param Md5: 文件md5
注意:此字段可能返回 null,表示取不到有效值。
:type Md5: str
:param FileName: 文件名称
注意:此字段可能返回 null,表示取不到有效值。
:type FileName: str
"""
self.Path = None
self.RiskLevel = None
self.VirusName = None
self.Tags = None
self.Desc = None
self.Solution = None
self.Size = None
self.FirstScanTime = None
self.LatestScanTime = None
self.Md5 = None
self.FileName = None
def _deserialize(self, params):
self.Path = params.get("Path")
self.RiskLevel = params.get("RiskLevel")
self.VirusName = params.get("VirusName")
self.Tags = params.get("Tags")
self.Desc = params.get("Desc")
self.Solution = params.get("Solution")
self.Size = params.get("Size")
self.FirstScanTime = params.get("FirstScanTime")
self.LatestScanTime = params.get("LatestScanTime")
self.Md5 = params.get("Md5")
self.FileName = params.get("FileName")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ImageVul(AbstractModel):
"""容器安全镜像漏洞信息
"""
def __init__(self):
r"""
:param CVEID: 漏洞id
注意:此字段可能返回 null,表示取不到有效值。
:type CVEID: str
:param POCID: 观点验证程序id
注意:此字段可能返回 null,表示取不到有效值。
:type POCID: str
:param Name: 漏洞名称
注意:此字段可能返回 null,表示取不到有效值。
:type Name: str
:param Components: 涉及组件信息
注意:此字段可能返回 null,表示取不到有效值。
:type Components: list of ComponentsInfo
:param Category: 分类
注意:此字段可能返回 null,表示取不到有效值。
:type Category: str
:param CategoryType: 分类2
注意:此字段可能返回 null,表示取不到有效值。
:type CategoryType: str
:param Level: 风险等级
注意:此字段可能返回 null,表示取不到有效值。
:type Level: str
:param Des: 描述
注意:此字段可能返回 null,表示取不到有效值。
:type Des: str
:param OfficialSolution: 解决方案
注意:此字段可能返回 null,表示取不到有效值。
:type OfficialSolution: str
:param Reference: 引用
注意:此字段可能返回 null,表示取不到有效值。
:type Reference: str
:param DefenseSolution: 防御方案
注意:此字段可能返回 null,表示取不到有效值。
:type DefenseSolution: str
:param SubmitTime: 提交时间
注意:此字段可能返回 null,表示取不到有效值。
:type SubmitTime: str
:param CvssScore: Cvss分数
注意:此字段可能返回 null,表示取不到有效值。
:type CvssScore: str
:param CvssVector: Cvss信息
注意:此字段可能返回 null,表示取不到有效值。
:type CvssVector: str
:param IsSuggest: 是否建议修复
注意:此字段可能返回 null,表示取不到有效值。
:type IsSuggest: str
:param FixedVersions: 修复版本号
注意:此字段可能返回 null,表示取不到有效值。
:type FixedVersions: str
:param Tag: 漏洞标签:"CanBeFixed","DynamicLevelPoc","DynamicLevelExp"
注意:此字段可能返回 null,表示取不到有效值。
:type Tag: list of str
:param Component: 组件名
注意:此字段可能返回 null,表示取不到有效值。
:type Component: str
:param Version: 组件版本
注意:此字段可能返回 null,表示取不到有效值。
:type Version: str
"""
self.CVEID = None
self.POCID = None
self.Name = None
self.Components = None
self.Category = None
self.CategoryType = None
self.Level = None
self.Des = None
self.OfficialSolution = None
self.Reference = None
self.DefenseSolution = None
self.SubmitTime = None
self.CvssScore = None
self.CvssVector = None
self.IsSuggest = None
self.FixedVersions = None
self.Tag = None
self.Component = None
self.Version = None
def _deserialize(self, params):
self.CVEID = params.get("CVEID")
self.POCID = params.get("POCID")
self.Name = params.get("Name")
if params.get("Components") is not None:
self.Components = []
for item in params.get("Components"):
obj = ComponentsInfo()
obj._deserialize(item)
self.Components.append(obj)
self.Category = params.get("Category")
self.CategoryType = params.get("CategoryType")
self.Level = params.get("Level")
self.Des = params.get("Des")
self.OfficialSolution = params.get("OfficialSolution")
self.Reference = params.get("Reference")
self.DefenseSolution = params.get("DefenseSolution")
self.SubmitTime = params.get("SubmitTime")
self.CvssScore = params.get("CvssScore")
self.CvssVector = params.get("CvssVector")
self.IsSuggest = params.get("IsSuggest")
self.FixedVersions = params.get("FixedVersions")
self.Tag = params.get("Tag")
self.Component = params.get("Component")
self.Version = params.get("Version")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ImagesBindRuleInfo(AbstractModel):
"""查询镜像绑定的运行时规则信息
"""
def __init__(self):
r"""
:param ImageId: 镜像id
:type ImageId: str
:param ImageName: 镜像名称
:type ImageName: str
:param ContainerCnt: 关联容器数量
:type ContainerCnt: int
:param RuleId: 绑定规则id
注意:此字段可能返回 null,表示取不到有效值。
:type RuleId: str
:param RuleName: 规则名字
注意:此字段可能返回 null,表示取不到有效值。
:type RuleName: str
:param ImageSize: 镜像大小
注意:此字段可能返回 null,表示取不到有效值。
:type ImageSize: int
:param ScanTime: 最近扫描时间
注意:此字段可能返回 null,表示取不到有效值。
:type ScanTime: str
"""
self.ImageId = None
self.ImageName = None
self.ContainerCnt = None
self.RuleId = None
self.RuleName = None
self.ImageSize = None
self.ScanTime = None
def _deserialize(self, params):
self.ImageId = params.get("ImageId")
self.ImageName = params.get("ImageName")
self.ContainerCnt = params.get("ContainerCnt")
self.RuleId = params.get("RuleId")
self.RuleName = params.get("RuleName")
self.ImageSize = params.get("ImageSize")
self.ScanTime = params.get("ScanTime")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ImagesInfo(AbstractModel):
"""容器安全镜像列表
"""
def __init__(self):
r"""
:param ImageID: 镜像id
:type ImageID: str
:param ImageName: 镜像名称
:type ImageName: str
:param CreateTime: 创建时间
:type CreateTime: str
:param Size: 镜像大小
:type Size: int
:param HostCnt: 主机个数
:type HostCnt: int
:param ContainerCnt: 容器个数
:type ContainerCnt: int
:param ScanTime: 扫描时间
:type ScanTime: str
:param VulCnt: 漏洞个数
:type VulCnt: int
:param VirusCnt: 病毒个数
:type VirusCnt: int
:param RiskCnt: 敏感信息个数
:type RiskCnt: int
:param IsTrustImage: 是否信任镜像
:type IsTrustImage: bool
:param OsName: 镜像系统
:type OsName: str
:param AgentError: agent镜像扫描错误
:type AgentError: str
:param ScanError: 后端镜像扫描错误
:type ScanError: str
:param ScanStatus: 扫描状态
:type ScanStatus: str
:param ScanVirusError: 木马扫描错误信息
:type ScanVirusError: str
:param ScanVulError: 漏洞扫描错误信息
:type ScanVulError: str
:param ScanRiskError: 风险扫描错误信息
:type ScanRiskError: str
:param IsSuggest: 是否是重点关注镜像,为0不是,非0是
:type IsSuggest: int
:param IsAuthorized: 是否授权,1是0否
:type IsAuthorized: int
:param ComponentCnt: 组件个数
:type ComponentCnt: int
"""
self.ImageID = None
self.ImageName = None
self.CreateTime = None
self.Size = None
self.HostCnt = None
self.ContainerCnt = None
self.ScanTime = None
self.VulCnt = None
self.VirusCnt = None
self.RiskCnt = None
self.IsTrustImage = None
self.OsName = None
self.AgentError = None
self.ScanError = None
self.ScanStatus = None
self.ScanVirusError = None
self.ScanVulError = None
self.ScanRiskError = None
self.IsSuggest = None
self.IsAuthorized = None
self.ComponentCnt = None
def _deserialize(self, params):
self.ImageID = params.get("ImageID")
self.ImageName = params.get("ImageName")
self.CreateTime = params.get("CreateTime")
self.Size = params.get("Size")
self.HostCnt = params.get("HostCnt")
self.ContainerCnt = params.get("ContainerCnt")
self.ScanTime = params.get("ScanTime")
self.VulCnt = params.get("VulCnt")
self.VirusCnt = params.get("VirusCnt")
self.RiskCnt = params.get("RiskCnt")
self.IsTrustImage = params.get("IsTrustImage")
self.OsName = params.get("OsName")
self.AgentError = params.get("AgentError")
self.ScanError = params.get("ScanError")
self.ScanStatus = params.get("ScanStatus")
self.ScanVirusError = params.get("ScanVirusError")
self.ScanVulError = params.get("ScanVulError")
self.ScanRiskError = params.get("ScanRiskError")
self.IsSuggest = params.get("IsSuggest")
self.IsAuthorized = params.get("IsAuthorized")
self.ComponentCnt = params.get("ComponentCnt")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ImagesVul(AbstractModel):
"""容器安全镜像漏洞
"""
def __init__(self):
r"""
:param CVEID: 漏洞id
:type CVEID: str
:param Name: 漏洞名称
:type Name: str
:param Component: 组件
:type Component: str
:param Version: 版本
:type Version: str
:param Category: 分类
:type Category: str
:param CategoryType: 分类2
:type CategoryType: str
:param Level: 风险等级
:type Level: int
:param Des: 描述
:type Des: str
:param OfficialSolution: 解决方案
:type OfficialSolution: str
:param Reference: 引用
:type Reference: str
:param DefenseSolution: 防御方案
:type DefenseSolution: str
:param SubmitTime: 提交时间
:type SubmitTime: str
:param CVSSV3Score: CVSS V3分数
:type CVSSV3Score: float
:param CVSSV3Desc: CVSS V3描述
:type CVSSV3Desc: str
:param IsSuggest: 是否是重点关注:true:是,false:不是
:type IsSuggest: bool
:param FixedVersions: 修复版本号
注意:此字段可能返回 null,表示取不到有效值。
:type FixedVersions: str
:param Tag: 漏洞标签:"CanBeFixed","DynamicLevelPoc","DynamicLevelExp"
注意:此字段可能返回 null,表示取不到有效值。
:type Tag: list of str
"""
self.CVEID = None
self.Name = None
self.Component = None
self.Version = None
self.Category = None
self.CategoryType = None
self.Level = None
self.Des = None
self.OfficialSolution = None
self.Reference = None
self.DefenseSolution = None
self.SubmitTime = None
self.CVSSV3Score = None
self.CVSSV3Desc = None
self.IsSuggest = None
self.FixedVersions = None
self.Tag = None
def _deserialize(self, params):
self.CVEID = params.get("CVEID")
self.Name = params.get("Name")
self.Component = params.get("Component")
self.Version = params.get("Version")
self.Category = params.get("Category")
self.CategoryType = params.get("CategoryType")
self.Level = params.get("Level")
self.Des = params.get("Des")
self.OfficialSolution = params.get("OfficialSolution")
self.Reference = params.get("Reference")
self.DefenseSolution = params.get("DefenseSolution")
self.SubmitTime = params.get("SubmitTime")
self.CVSSV3Score = params.get("CVSSV3Score")
self.CVSSV3Desc = params.get("CVSSV3Desc")
self.IsSuggest = params.get("IsSuggest")
self.FixedVersions = params.get("FixedVersions")
self.Tag = params.get("Tag")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class InitializeUserComplianceEnvironmentRequest(AbstractModel):
"""InitializeUserComplianceEnvironment请求参数结构体
"""
class InitializeUserComplianceEnvironmentResponse(AbstractModel):
"""InitializeUserComplianceEnvironment返回参数结构体
"""
def __init__(self):
r"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RequestId = None
def _deserialize(self, params):
self.RequestId = params.get("RequestId")
class ModifyAbnormalProcessRuleStatusRequest(AbstractModel):
"""ModifyAbnormalProcessRuleStatus请求参数结构体
"""
def __init__(self):
r"""
:param RuleIdSet: 策略的ids
:type RuleIdSet: list of str
:param IsEnable: 策略开关,true开启,false关闭
:type IsEnable: bool
"""
self.RuleIdSet = None
self.IsEnable = None
def _deserialize(self, params):
self.RuleIdSet = params.get("RuleIdSet")
self.IsEnable = params.get("IsEnable")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ModifyAbnormalProcessRuleStatusResponse(AbstractModel):
"""ModifyAbnormalProcessRuleStatus返回参数结构体
"""
def __init__(self):
r"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RequestId = None
def _deserialize(self, params):
self.RequestId = params.get("RequestId")
class ModifyAbnormalProcessStatusRequest(AbstractModel):
"""ModifyAbnormalProcessStatus请求参数结构体
"""
def __init__(self):
r"""
:param EventIdSet: 处理事件ids
:type EventIdSet: list of str
:param Status: 标记事件的状态,
EVENT_DEALED:事件处理
EVENT_INGNORE":事件忽略
EVENT_DEL:事件删除
EVENT_ADD_WHITE:事件加白
:type Status: str
:param Remark: 事件备注
:type Remark: str
"""
self.EventIdSet = None
self.Status = None
self.Remark = None
def _deserialize(self, params):
self.EventIdSet = params.get("EventIdSet")
self.Status = params.get("Status")
self.Remark = params.get("Remark")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ModifyAbnormalProcessStatusResponse(AbstractModel):
"""ModifyAbnormalProcessStatus返回参数结构体
"""
def __init__(self):
r"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RequestId = None
def _deserialize(self, params):
self.RequestId = params.get("RequestId")
class ModifyAccessControlRuleStatusRequest(AbstractModel):
"""ModifyAccessControlRuleStatus请求参数结构体
"""
def __init__(self):
r"""
:param RuleIdSet: 策略的ids
:type RuleIdSet: list of str
:param IsEnable: 策略开关,true:代表开启, false代表关闭
:type IsEnable: bool
"""
self.RuleIdSet = None
self.IsEnable = None
def _deserialize(self, params):
self.RuleIdSet = params.get("RuleIdSet")
self.IsEnable = params.get("IsEnable")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ModifyAccessControlRuleStatusResponse(AbstractModel):
"""ModifyAccessControlRuleStatus返回参数结构体
"""
def __init__(self):
r"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RequestId = None
def _deserialize(self, params):
self.RequestId = params.get("RequestId")
class ModifyAccessControlStatusRequest(AbstractModel):
"""ModifyAccessControlStatus请求参数结构体
"""
def __init__(self):
r"""
:param EventIdSet: 处理事件ids
:type EventIdSet: list of str
:param Status: 标记事件的状态,
EVENT_DEALED:事件已经处理
EVENT_INGNORE:事件忽略
EVENT_DEL:事件删除
EVENT_ADD_WHITE:事件加白
:type Status: str
:param Remark: 备注事件信息
:type Remark: str
"""
self.EventIdSet = None
self.Status = None
self.Remark = None
def _deserialize(self, params):
self.EventIdSet = params.get("EventIdSet")
self.Status = params.get("Status")
self.Remark = params.get("Remark")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ModifyAccessControlStatusResponse(AbstractModel):
"""ModifyAccessControlStatus返回参数结构体
"""
def __init__(self):
r"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RequestId = None
def _deserialize(self, params):
self.RequestId = params.get("RequestId")
class ModifyAssetImageRegistryScanStopOneKeyRequest(AbstractModel):
"""ModifyAssetImageRegistryScanStopOneKey请求参数结构体
"""
def __init__(self):
r"""
:param All: 是否扫描全部镜像
:type All: bool
:param Images: 扫描的镜像列表
:type Images: list of ImageInfo
:param Id: 扫描的镜像列表Id
:type Id: list of int non-negative
"""
self.All = None
self.Images = None
self.Id = None
def _deserialize(self, params):
self.All = params.get("All")
if params.get("Images") is not None:
self.Images = []
for item in params.get("Images"):
obj = ImageInfo()
obj._deserialize(item)
self.Images.append(obj)
self.Id = params.get("Id")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ModifyAssetImageRegistryScanStopOneKeyResponse(AbstractModel):
"""ModifyAssetImageRegistryScanStopOneKey返回参数结构体
"""
def __init__(self):
r"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RequestId = None
def _deserialize(self, params):
self.RequestId = params.get("RequestId")
class ModifyAssetImageRegistryScanStopRequest(AbstractModel):
"""ModifyAssetImageRegistryScanStop请求参数结构体
"""
def __init__(self):
r"""
:param All: 是否扫描全部镜像
:type All: bool
:param Images: 扫描的镜像列表
:type Images: list of ImageInfo
:param Id: 扫描的镜像列表
:type Id: list of int non-negative
:param Filters: 过滤条件
:type Filters: list of AssetFilters
:param ExcludeImageList: 不要扫描的镜像列表,与Filters配合使用
:type ExcludeImageList: list of int non-negative
:param OnlyScanLatest: 是否仅扫描各repository最新版本的镜像
:type OnlyScanLatest: bool
"""
self.All = None
self.Images = None
self.Id = None
self.Filters = None
self.ExcludeImageList = None
self.OnlyScanLatest = None
def _deserialize(self, params):
self.All = params.get("All")
if params.get("Images") is not None:
self.Images = []
for item in params.get("Images"):
obj = ImageInfo()
obj._deserialize(item)
self.Images.append(obj)
self.Id = params.get("Id")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = AssetFilters()
obj._deserialize(item)
self.Filters.append(obj)
self.ExcludeImageList = params.get("ExcludeImageList")
self.OnlyScanLatest = params.get("OnlyScanLatest")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ModifyAssetImageRegistryScanStopResponse(AbstractModel):
"""ModifyAssetImageRegistryScanStop返回参数结构体
"""
def __init__(self):
r"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RequestId = None
def _deserialize(self, params):
self.RequestId = params.get("RequestId")
class ModifyAssetImageScanStopRequest(AbstractModel):
"""ModifyAssetImageScanStop请求参数结构体
"""
def __init__(self):
r"""
:param TaskID: 任务id;任务id,镜像id和根据过滤条件筛选三选一。
:type TaskID: str
:param Images: 镜像id;任务id,镜像id和根据过滤条件筛选三选一。
:type Images: list of str
:param Filters: 根据过滤条件筛选出镜像;任务id,镜像id和根据过滤条件筛选三选一。
:type Filters: list of AssetFilters
:param ExcludeImageIds: 根据过滤条件筛选出镜像,再排除个别镜像
:type ExcludeImageIds: str
"""
self.TaskID = None
self.Images = None
self.Filters = None
self.ExcludeImageIds = None
def _deserialize(self, params):
self.TaskID = params.get("TaskID")
self.Images = params.get("Images")
if params.get("Filters") is not None:
self.Filters = []
for item in params.get("Filters"):
obj = AssetFilters()
obj._deserialize(item)
self.Filters.append(obj)
self.ExcludeImageIds = params.get("ExcludeImageIds")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ModifyAssetImageScanStopResponse(AbstractModel):
"""ModifyAssetImageScanStop返回参数结构体
"""
def __init__(self):
r"""
:param Status: 停止状态
:type Status: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.Status = None
self.RequestId = None
def _deserialize(self, params):
self.Status = params.get("Status")
self.RequestId = params.get("RequestId")
class ModifyAssetRequest(AbstractModel):
"""ModifyAsset请求参数结构体
"""
def __init__(self):
r"""
:param All: 全部同步
:type All: bool
:param Hosts: 要同步的主机列表 两个参数必选一个 All优先
:type Hosts: list of str
"""
self.All = None
self.Hosts = None
def _deserialize(self, params):
self.All = params.get("All")
self.Hosts = params.get("Hosts")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ModifyAssetResponse(AbstractModel):
"""ModifyAsset返回参数结构体
"""
def __init__(self):
r"""
:param Status: 同步任务发送结果
:type Status: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.Status = None
self.RequestId = None
def _deserialize(self, params):
self.Status = params.get("Status")
self.RequestId = params.get("RequestId")
class ModifyCompliancePeriodTaskRequest(AbstractModel):
"""ModifyCompliancePeriodTask请求参数结构体
"""
def __init__(self):
r"""
:param PeriodTaskId: 要修改的定时任务的ID,由DescribeCompliancePeriodTaskList接口返回。
:type PeriodTaskId: int
:param PeriodRule: 定时任务的周期规则。不填时,不修改。
:type PeriodRule: :class:`tencentcloud.tcss.v20201101.models.CompliancePeriodTaskRule`
:param StandardSettings: 设置合规标准。不填时,不修改。
:type StandardSettings: list of ComplianceBenchmarkStandardEnable
"""
self.PeriodTaskId = None
self.PeriodRule = None
self.StandardSettings = None
def _deserialize(self, params):
self.PeriodTaskId = params.get("PeriodTaskId")
if params.get("PeriodRule") is not None:
self.PeriodRule = CompliancePeriodTaskRule()
self.PeriodRule._deserialize(params.get("PeriodRule"))
if params.get("StandardSettings") is not None:
self.StandardSettings = []
for item in params.get("StandardSettings"):
obj = ComplianceBenchmarkStandardEnable()
obj._deserialize(item)
self.StandardSettings.append(obj)
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ModifyCompliancePeriodTaskResponse(AbstractModel):
"""ModifyCompliancePeriodTask返回参数结构体
"""
def __init__(self):
r"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RequestId = None
def _deserialize(self, params):
self.RequestId = params.get("RequestId")
class ModifyEscapeEventStatusRequest(AbstractModel):
"""ModifyEscapeEventStatus请求参数结构体
"""
def __init__(self):
r"""
:param EventIdSet: 处理事件ids
:type EventIdSet: list of str
:param Status: 标记事件的状态
EVENT_DEALED:事件已经处理
EVENT_INGNORE:事件忽略
EVENT_DEL:事件删除
:type Status: str
:param Remark: 备注
:type Remark: str
"""
self.EventIdSet = None
self.Status = None
self.Remark = None
def _deserialize(self, params):
self.EventIdSet = params.get("EventIdSet")
self.Status = params.get("Status")
self.Remark = params.get("Remark")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ModifyEscapeEventStatusResponse(AbstractModel):
"""ModifyEscapeEventStatus返回参数结构体
"""
def __init__(self):
r"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RequestId = None
def _deserialize(self, params):
self.RequestId = params.get("RequestId")
class ModifyEscapeRuleRequest(AbstractModel):
"""ModifyEscapeRule请求参数结构体
"""
def __init__(self):
r"""
:param RuleSet: 需要修改的数组
:type RuleSet: list of EscapeRuleEnabled
"""
self.RuleSet = None
def _deserialize(self, params):
if params.get("RuleSet") is not None:
self.RuleSet = []
for item in params.get("RuleSet"):
obj = EscapeRuleEnabled()
obj._deserialize(item)
self.RuleSet.append(obj)
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ModifyEscapeRuleResponse(AbstractModel):
"""ModifyEscapeRule返回参数结构体
"""
def __init__(self):
r"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RequestId = None
def _deserialize(self, params):
self.RequestId = params.get("RequestId")
class ModifyReverseShellStatusRequest(AbstractModel):
"""ModifyReverseShellStatus请求参数结构体
"""
def __init__(self):
r"""
:param EventIdSet: 处理事件ids
:type EventIdSet: list of str
:param Status: 标记事件的状态,
EVENT_DEALED:事件处理
EVENT_INGNORE":事件忽略
EVENT_DEL:事件删除
EVENT_ADD_WHITE:事件加白
:type Status: str
:param Remark: 事件备注
:type Remark: str
"""
self.EventIdSet = None
self.Status = None
self.Remark = None
def _deserialize(self, params):
self.EventIdSet = params.get("EventIdSet")
self.Status = params.get("Status")
self.Remark = params.get("Remark")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ModifyReverseShellStatusResponse(AbstractModel):
"""ModifyReverseShellStatus返回参数结构体
"""
def __init__(self):
r"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RequestId = None
def _deserialize(self, params):
self.RequestId = params.get("RequestId")
class ModifyRiskSyscallStatusRequest(AbstractModel):
"""ModifyRiskSyscallStatus请求参数结构体
"""
def __init__(self):
r"""
:param EventIdSet: 处理事件ids
:type EventIdSet: list of str
:param Status: 标记事件的状态,
EVENT_DEALED:事件处理
EVENT_INGNORE":事件忽略
EVENT_DEL:事件删除
EVENT_ADD_WHITE:事件加白
:type Status: str
:param Remark: 事件备注
:type Remark: str
"""
self.EventIdSet = None
self.Status = None
self.Remark = None
def _deserialize(self, params):
self.EventIdSet = params.get("EventIdSet")
self.Status = params.get("Status")
self.Remark = params.get("Remark")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ModifyRiskSyscallStatusResponse(AbstractModel):
"""ModifyRiskSyscallStatus返回参数结构体
"""
def __init__(self):
r"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RequestId = None
def _deserialize(self, params):
self.RequestId = params.get("RequestId")
class ModifyVirusFileStatusRequest(AbstractModel):
"""ModifyVirusFileStatus请求参数结构体
"""
def __init__(self):
r"""
:param EventIdSet: 处理事件id
:type EventIdSet: list of str
:param Status: 标记事件的状态,
EVENT_DEALED:事件处理
EVENT_INGNORE":事件忽略
EVENT_DEL:事件删除
EVENT_ADD_WHITE:事件加白
EVENT_PENDING: 事件待处理
:type Status: str
:param Remark: 事件备注
:type Remark: str
"""
self.EventIdSet = None
self.Status = None
self.Remark = None
def _deserialize(self, params):
self.EventIdSet = params.get("EventIdSet")
self.Status = params.get("Status")
self.Remark = params.get("Remark")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ModifyVirusFileStatusResponse(AbstractModel):
"""ModifyVirusFileStatus返回参数结构体
"""
def __init__(self):
r"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RequestId = None
def _deserialize(self, params):
self.RequestId = params.get("RequestId")
class ModifyVirusMonitorSettingRequest(AbstractModel):
"""ModifyVirusMonitorSetting请求参数结构体
"""
def __init__(self):
r"""
:param EnableScan: 是否开启定期扫描
:type EnableScan: bool
:param ScanPathAll: 扫描全部路径
:type ScanPathAll: bool
:param ScanPathType: 当ScanPathAll为true 生效 0扫描以下路径 1、扫描除以下路径(扫描范围只能小于等于1)
:type ScanPathType: int
:param ScanPath: 自选排除或扫描的地址
:type ScanPath: list of str
"""
self.EnableScan = None
self.ScanPathAll = None
self.ScanPathType = None
self.ScanPath = None
def _deserialize(self, params):
self.EnableScan = params.get("EnableScan")
self.ScanPathAll = params.get("ScanPathAll")
self.ScanPathType = params.get("ScanPathType")
self.ScanPath = params.get("ScanPath")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ModifyVirusMonitorSettingResponse(AbstractModel):
"""ModifyVirusMonitorSetting返回参数结构体
"""
def __init__(self):
r"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RequestId = None
def _deserialize(self, params):
self.RequestId = params.get("RequestId")
class ModifyVirusScanSettingRequest(AbstractModel):
"""ModifyVirusScanSetting请求参数结构体
"""
def __init__(self):
r"""
:param EnableScan: 是否开启定期扫描
:type EnableScan: bool
:param Cycle: 检测周期每隔多少天(1|3|7)
:type Cycle: int
:param BeginScanAt: 扫描开始时间
:type BeginScanAt: str
:param ScanPathAll: 扫描全部路径(true:全选,false:自选)
:type ScanPathAll: bool
:param ScanPathType: 当ScanPathAll为true 生效 0扫描以下路径 1、扫描除以下路径
:type ScanPathType: int
:param Timeout: 超时时长(5~24h)
:type Timeout: int
:param ScanRangeType: 扫描范围0容器1主机节点
:type ScanRangeType: int
:param ScanRangeAll: true 全选,false 自选
:type ScanRangeAll: bool
:param ScanIds: 自选扫描范围的容器id或者主机id 根据ScanRangeType决定
:type ScanIds: list of str
:param ScanPath: 扫描路径
:type ScanPath: list of str
"""
self.EnableScan = None
self.Cycle = None
self.BeginScanAt = None
self.ScanPathAll = None
self.ScanPathType = None
self.Timeout = None
self.ScanRangeType = None
self.ScanRangeAll = None
self.ScanIds = None
self.ScanPath = None
def _deserialize(self, params):
self.EnableScan = params.get("EnableScan")
self.Cycle = params.get("Cycle")
self.BeginScanAt = params.get("BeginScanAt")
self.ScanPathAll = params.get("ScanPathAll")
self.ScanPathType = params.get("ScanPathType")
self.Timeout = params.get("Timeout")
self.ScanRangeType = params.get("ScanRangeType")
self.ScanRangeAll = params.get("ScanRangeAll")
self.ScanIds = params.get("ScanIds")
self.ScanPath = params.get("ScanPath")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ModifyVirusScanSettingResponse(AbstractModel):
"""ModifyVirusScanSetting返回参数结构体
"""
def __init__(self):
r"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RequestId = None
def _deserialize(self, params):
self.RequestId = params.get("RequestId")
class ModifyVirusScanTimeoutSettingRequest(AbstractModel):
"""ModifyVirusScanTimeoutSetting请求参数结构体
"""
def __init__(self):
r"""
:param Timeout: 超时时长单位小时(5~24h)
:type Timeout: int
:param ScanType: 设置类型0一键检测,1定时检测
:type ScanType: int
"""
self.Timeout = None
self.ScanType = None
def _deserialize(self, params):
self.Timeout = params.get("Timeout")
self.ScanType = params.get("ScanType")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ModifyVirusScanTimeoutSettingResponse(AbstractModel):
"""ModifyVirusScanTimeoutSetting返回参数结构体
"""
def __init__(self):
r"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RequestId = None
def _deserialize(self, params):
self.RequestId = params.get("RequestId")
class PortInfo(AbstractModel):
"""容器安全端口信息列表
"""
def __init__(self):
r"""
:param Type: 类型
:type Type: str
:param PublicIP: 对外ip
:type PublicIP: str
:param PublicPort: 主机端口
:type PublicPort: int
:param ContainerPort: 容器端口
:type ContainerPort: int
:param ContainerPID: 容器Pid
:type ContainerPID: int
:param ContainerName: 容器名
:type ContainerName: str
:param HostID: 主机id
:type HostID: str
:param HostIP: 主机ip
:type HostIP: str
:param ProcessName: 进程名称
:type ProcessName: str
:param ListenContainer: 容器内监听地址
:type ListenContainer: str
:param ListenHost: 容器外监听地址
:type ListenHost: str
:param RunAs: 运行账号
:type RunAs: str
:param HostName: 主机名称
:type HostName: str
:param PublicIp: 外网ip
:type PublicIp: str
"""
self.Type = None
self.PublicIP = None
self.PublicPort = None
self.ContainerPort = None
self.ContainerPID = None
self.ContainerName = None
self.HostID = None
self.HostIP = None
self.ProcessName = None
self.ListenContainer = None
self.ListenHost = None
self.RunAs = None
self.HostName = None
self.PublicIp = None
def _deserialize(self, params):
self.Type = params.get("Type")
self.PublicIP = params.get("PublicIP")
self.PublicPort = params.get("PublicPort")
self.ContainerPort = params.get("ContainerPort")
self.ContainerPID = params.get("ContainerPID")
self.ContainerName = params.get("ContainerName")
self.HostID = params.get("HostID")
self.HostIP = params.get("HostIP")
self.ProcessName = params.get("ProcessName")
self.ListenContainer = params.get("ListenContainer")
self.ListenHost = params.get("ListenHost")
self.RunAs = params.get("RunAs")
self.HostName = params.get("HostName")
self.PublicIp = params.get("PublicIp")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ProcessDetailBaseInfo(AbstractModel):
"""运行是安全详情,进程基础信息
"""
def __init__(self):
r"""
:param ProcessName: 进程名称
:type ProcessName: str
:param ProcessId: 进程pid
:type ProcessId: int
:param ProcessStartUser: 进程启动用户
:type ProcessStartUser: str
:param ProcessUserGroup: 进程用户组
:type ProcessUserGroup: str
:param ProcessPath: 进程路径
:type ProcessPath: str
:param ProcessParam: 进程命令行参数
:type ProcessParam: str
"""
self.ProcessName = None
self.ProcessId = None
self.ProcessStartUser = None
self.ProcessUserGroup = None
self.ProcessPath = None
self.ProcessParam = None
def _deserialize(self, params):
self.ProcessName = params.get("ProcessName")
self.ProcessId = params.get("ProcessId")
self.ProcessStartUser = params.get("ProcessStartUser")
self.ProcessUserGroup = params.get("ProcessUserGroup")
self.ProcessPath = params.get("ProcessPath")
self.ProcessParam = params.get("ProcessParam")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ProcessDetailInfo(AbstractModel):
"""运行是安全详情,进程信息
"""
def __init__(self):
r"""
:param ProcessName: 进程名称
:type ProcessName: str
:param ProcessAuthority: 进程权限
:type ProcessAuthority: str
:param ProcessId: 进程pid
:type ProcessId: int
:param ProcessStartUser: 进程启动用户
:type ProcessStartUser: str
:param ProcessUserGroup: 进程用户组
:type ProcessUserGroup: str
:param ProcessPath: 进程路径
:type ProcessPath: str
:param ProcessTree: 进程树
:type ProcessTree: str
:param ProcessMd5: 进程md5
:type ProcessMd5: str
:param ProcessParam: 进程命令行参数
:type ProcessParam: str
"""
self.ProcessName = None
self.ProcessAuthority = None
self.ProcessId = None
self.ProcessStartUser = None
self.ProcessUserGroup = None
self.ProcessPath = None
self.ProcessTree = None
self.ProcessMd5 = None
self.ProcessParam = None
def _deserialize(self, params):
self.ProcessName = params.get("ProcessName")
self.ProcessAuthority = params.get("ProcessAuthority")
self.ProcessId = params.get("ProcessId")
self.ProcessStartUser = params.get("ProcessStartUser")
self.ProcessUserGroup = params.get("ProcessUserGroup")
self.ProcessPath = params.get("ProcessPath")
self.ProcessTree = params.get("ProcessTree")
self.ProcessMd5 = params.get("ProcessMd5")
self.ProcessParam = params.get("ProcessParam")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ProcessInfo(AbstractModel):
"""容器安全进程列表
"""
def __init__(self):
r"""
:param StartTime: 进程启动时间
:type StartTime: str
:param RunAs: 运行用户
:type RunAs: str
:param CmdLine: 命令行参数
:type CmdLine: str
:param Exe: Exe路径
:type Exe: str
:param PID: 主机PID
:type PID: int
:param ContainerPID: 容器内pid
:type ContainerPID: int
:param ContainerName: 容器名称
:type ContainerName: str
:param HostID: 主机id
:type HostID: str
:param HostIP: 主机ip
:type HostIP: str
:param ProcessName: 进程名称
:type ProcessName: str
:param HostName: 主机名称
:type HostName: str
:param PublicIp: 外网ip
:type PublicIp: str
"""
self.StartTime = None
self.RunAs = None
self.CmdLine = None
self.Exe = None
self.PID = None
self.ContainerPID = None
self.ContainerName = None
self.HostID = None
self.HostIP = None
self.ProcessName = None
self.HostName = None
self.PublicIp = None
def _deserialize(self, params):
self.StartTime = params.get("StartTime")
self.RunAs = params.get("RunAs")
self.CmdLine = params.get("CmdLine")
self.Exe = params.get("Exe")
self.PID = params.get("PID")
self.ContainerPID = params.get("ContainerPID")
self.ContainerName = params.get("ContainerName")
self.HostID = params.get("HostID")
self.HostIP = params.get("HostIP")
self.ProcessName = params.get("ProcessName")
self.HostName = params.get("HostName")
self.PublicIp = params.get("PublicIp")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class RemoveAssetImageRegistryRegistryDetailRequest(AbstractModel):
"""RemoveAssetImageRegistryRegistryDetail请求参数结构体
"""
def __init__(self):
r"""
:param RegistryId: 仓库唯一id
:type RegistryId: int
"""
self.RegistryId = None
def _deserialize(self, params):
self.RegistryId = params.get("RegistryId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class RemoveAssetImageRegistryRegistryDetailResponse(AbstractModel):
"""RemoveAssetImageRegistryRegistryDetail返回参数结构体
"""
def __init__(self):
r"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RequestId = None
def _deserialize(self, params):
self.RequestId = params.get("RequestId")
class RenewImageAuthorizeStateRequest(AbstractModel):
"""RenewImageAuthorizeState请求参数结构体
"""
def __init__(self):
r"""
:param AllImages: 是否全部未授权镜像
:type AllImages: bool
:param ImageIds: 镜像ids
:type ImageIds: list of str
"""
self.AllImages = None
self.ImageIds = None
def _deserialize(self, params):
self.AllImages = params.get("AllImages")
self.ImageIds = params.get("ImageIds")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class RenewImageAuthorizeStateResponse(AbstractModel):
"""RenewImageAuthorizeState返回参数结构体
"""
def __init__(self):
r"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RequestId = None
def _deserialize(self, params):
self.RequestId = params.get("RequestId")
class ReverseShellEventDescription(AbstractModel):
"""运行时容器反弹shell事件描述信息
"""
def __init__(self):
r"""
:param Description: 描述信息
:type Description: str
:param Solution: 解决方案
:type Solution: str
:param Remark: 事件备注信息
注意:此字段可能返回 null,表示取不到有效值。
:type Remark: str
:param DstAddress: 目标地址
:type DstAddress: str
"""
self.Description = None
self.Solution = None
self.Remark = None
self.DstAddress = None
def _deserialize(self, params):
self.Description = params.get("Description")
self.Solution = params.get("Solution")
self.Remark = params.get("Remark")
self.DstAddress = params.get("DstAddress")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ReverseShellEventInfo(AbstractModel):
"""容器安全运行时高危系统调用信息
"""
def __init__(self):
r"""
:param ProcessName: 进程名称
:type ProcessName: str
:param ProcessPath: 进程路径
:type ProcessPath: str
:param ImageId: 镜像id
:type ImageId: str
:param ContainerId: 容器id
:type ContainerId: str
:param ImageName: 镜像名
:type ImageName: str
:param ContainerName: 容器名
:type ContainerName: str
:param FoundTime: 生成时间
:type FoundTime: str
:param Solution: 事件解决方案
:type Solution: str
:param Description: 事件详细描述
:type Description: str
:param Status: 状态,EVENT_UNDEAL:事件未处理
EVENT_DEALED:事件已经处理
EVENT_INGNORE:事件已经忽略
EVENT_ADD_WHITE:时间已经加白
:type Status: str
:param EventId: 事件id
:type EventId: str
:param Remark: 备注
:type Remark: str
:param PProcessName: 父进程名
:type PProcessName: str
:param EventCount: 事件数量
:type EventCount: int
:param LatestFoundTime: 最近生成时间
:type LatestFoundTime: str
:param DstAddress: 目标地址
:type DstAddress: str
"""
self.ProcessName = None
self.ProcessPath = None
self.ImageId = None
self.ContainerId = None
self.ImageName = None
self.ContainerName = None
self.FoundTime = None
self.Solution = None
self.Description = None
self.Status = None
self.EventId = None
self.Remark = None
self.PProcessName = None
self.EventCount = None
self.LatestFoundTime = None
self.DstAddress = None
def _deserialize(self, params):
self.ProcessName = params.get("ProcessName")
self.ProcessPath = params.get("ProcessPath")
self.ImageId = params.get("ImageId")
self.ContainerId = params.get("ContainerId")
self.ImageName = params.get("ImageName")
self.ContainerName = params.get("ContainerName")
self.FoundTime = params.get("FoundTime")
self.Solution = params.get("Solution")
self.Description = params.get("Description")
self.Status = params.get("Status")
self.EventId = params.get("EventId")
self.Remark = params.get("Remark")
self.PProcessName = params.get("PProcessName")
self.EventCount = params.get("EventCount")
self.LatestFoundTime = params.get("LatestFoundTime")
self.DstAddress = params.get("DstAddress")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ReverseShellWhiteListBaseInfo(AbstractModel):
"""反弹shell白名单信息
"""
def __init__(self):
r"""
:param Id: 白名单id
:type Id: str
:param ImageCount: 镜像数量
:type ImageCount: int
:param ProcessName: 连接进程名字
:type ProcessName: str
:param DstIp: 目标地址ip
:type DstIp: str
:param CreateTime: 创建时间
:type CreateTime: str
:param UpdateTime: 更新时间
:type UpdateTime: str
:param DstPort: 目标端口
:type DstPort: str
:param IsGlobal: 是否是全局白名单,true全局
:type IsGlobal: bool
:param ImageIds: 镜像id数组,为空代表全部
:type ImageIds: list of str
"""
self.Id = None
self.ImageCount = None
self.ProcessName = None
self.DstIp = None
self.CreateTime = None
self.UpdateTime = None
self.DstPort = None
self.IsGlobal = None
self.ImageIds = None
def _deserialize(self, params):
self.Id = params.get("Id")
self.ImageCount = params.get("ImageCount")
self.ProcessName = params.get("ProcessName")
self.DstIp = params.get("DstIp")
self.CreateTime = params.get("CreateTime")
self.UpdateTime = params.get("UpdateTime")
self.DstPort = params.get("DstPort")
self.IsGlobal = params.get("IsGlobal")
self.ImageIds = params.get("ImageIds")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ReverseShellWhiteListInfo(AbstractModel):
"""反弹shell白名单信息
"""
def __init__(self):
r"""
:param DstIp: 目标IP
:type DstIp: str
:param DstPort: 目标端口
:type DstPort: str
:param ProcessName: 目标进程
:type ProcessName: str
:param ImageIds: 镜像id数组,为空代表全部
:type ImageIds: list of str
:param Id: 白名单id,如果新建则id为空
:type Id: str
"""
self.DstIp = None
self.DstPort = None
self.ProcessName = None
self.ImageIds = None
self.Id = None
def _deserialize(self, params):
self.DstIp = params.get("DstIp")
self.DstPort = params.get("DstPort")
self.ProcessName = params.get("ProcessName")
self.ImageIds = params.get("ImageIds")
self.Id = params.get("Id")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class RiskSyscallEventDescription(AbstractModel):
"""运行时容器高危系统调用事件描述信息
"""
def __init__(self):
r"""
:param Description: 描述信息
:type Description: str
:param Solution: 解决方案
:type Solution: str
:param Remark: 事件备注信息
注意:此字段可能返回 null,表示取不到有效值。
:type Remark: str
:param SyscallName: 系统调用名称
:type SyscallName: str
"""
self.Description = None
self.Solution = None
self.Remark = None
self.SyscallName = None
def _deserialize(self, params):
self.Description = params.get("Description")
self.Solution = params.get("Solution")
self.Remark = params.get("Remark")
self.SyscallName = params.get("SyscallName")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class RiskSyscallEventInfo(AbstractModel):
"""容器安全运行时高危系统调用信息
"""
def __init__(self):
r"""
:param ProcessName: 进程名称
:type ProcessName: str
:param ProcessPath: 进程路径
:type ProcessPath: str
:param ImageId: 镜像id
:type ImageId: str
:param ContainerId: 容器id
:type ContainerId: str
:param ImageName: 镜像名
:type ImageName: str
:param ContainerName: 容器名
:type ContainerName: str
:param FoundTime: 生成时间
:type FoundTime: str
:param Solution: 事件解决方案
:type Solution: str
:param Description: 事件详细描述
:type Description: str
:param SyscallName: 系统调用名称
:type SyscallName: str
:param Status: 状态,EVENT_UNDEAL:事件未处理
EVENT_DEALED:事件已经处理
EVENT_INGNORE:事件已经忽略
EVENT_ADD_WHITE:时间已经加白
:type Status: str
:param EventId: 事件id
:type EventId: str
:param NodeName: 节点名称
:type NodeName: str
:param PodName: pod(实例)的名字
:type PodName: str
:param Remark: 备注
:type Remark: str
:param RuleExist: 系统监控名称是否存在
:type RuleExist: bool
:param EventCount: 事件数量
:type EventCount: int
:param LatestFoundTime: 最近生成时间
:type LatestFoundTime: str
"""
self.ProcessName = None
self.ProcessPath = None
self.ImageId = None
self.ContainerId = None
self.ImageName = None
self.ContainerName = None
self.FoundTime = None
self.Solution = None
self.Description = None
self.SyscallName = None
self.Status = None
self.EventId = None
self.NodeName = None
self.PodName = None
self.Remark = None
self.RuleExist = None
self.EventCount = None
self.LatestFoundTime = None
def _deserialize(self, params):
self.ProcessName = params.get("ProcessName")
self.ProcessPath = params.get("ProcessPath")
self.ImageId = params.get("ImageId")
self.ContainerId = params.get("ContainerId")
self.ImageName = params.get("ImageName")
self.ContainerName = params.get("ContainerName")
self.FoundTime = params.get("FoundTime")
self.Solution = params.get("Solution")
self.Description = params.get("Description")
self.SyscallName = params.get("SyscallName")
self.Status = params.get("Status")
self.EventId = params.get("EventId")
self.NodeName = params.get("NodeName")
self.PodName = params.get("PodName")
self.Remark = params.get("Remark")
self.RuleExist = params.get("RuleExist")
self.EventCount = params.get("EventCount")
self.LatestFoundTime = params.get("LatestFoundTime")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class RiskSyscallWhiteListBaseInfo(AbstractModel):
"""高危系统调用白名单信息
"""
def __init__(self):
r"""
:param Id: 白名单id
:type Id: str
:param ImageCount: 镜像数量
:type ImageCount: int
:param ProcessPath: 连接进程路径
:type ProcessPath: str
:param SyscallNames: 系统调用名称列表
:type SyscallNames: list of str
:param CreateTime: 创建时间
:type CreateTime: str
:param UpdateTime: 更新时间
:type UpdateTime: str
:param IsGlobal: 是否是全局白名单,true全局
:type IsGlobal: bool
:param ImageIds: 镜像id数组
:type ImageIds: list of str
"""
self.Id = None
self.ImageCount = None
self.ProcessPath = None
self.SyscallNames = None
self.CreateTime = None
self.UpdateTime = None
self.IsGlobal = None
self.ImageIds = None
def _deserialize(self, params):
self.Id = params.get("Id")
self.ImageCount = params.get("ImageCount")
self.ProcessPath = params.get("ProcessPath")
self.SyscallNames = params.get("SyscallNames")
self.CreateTime = params.get("CreateTime")
self.UpdateTime = params.get("UpdateTime")
self.IsGlobal = params.get("IsGlobal")
self.ImageIds = params.get("ImageIds")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class RiskSyscallWhiteListInfo(AbstractModel):
"""高危系统调用白名单信息
"""
def __init__(self):
r"""
:param ImageIds: 镜像id数组,为空代表全部
:type ImageIds: list of str
:param SyscallNames: 系统调用名称,通过DescribeRiskSyscallNames接口获取枚举列表
:type SyscallNames: list of str
:param ProcessPath: 目标进程
:type ProcessPath: str
:param Id: 白名单id,如果新建则id为空
:type Id: str
"""
self.ImageIds = None
self.SyscallNames = None
self.ProcessPath = None
self.Id = None
def _deserialize(self, params):
self.ImageIds = params.get("ImageIds")
self.SyscallNames = params.get("SyscallNames")
self.ProcessPath = params.get("ProcessPath")
self.Id = params.get("Id")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class RuleBaseInfo(AbstractModel):
"""运行时安全,策略基本信息
"""
def __init__(self):
r"""
:param IsDefault: true: 默认策略,false:自定义策略
:type IsDefault: bool
:param EffectImageCount: 策略生效镜像数量
:type EffectImageCount: int
:param RuleId: 策略Id
:type RuleId: str
:param UpdateTime: 策略更新时间, 存在为空的情况
注意:此字段可能返回 null,表示取不到有效值。
:type UpdateTime: str
:param RuleName: 策略名字
:type RuleName: str
:param EditUserName: 编辑用户名称
:type EditUserName: str
:param IsEnable: true: 策略启用,false:策略禁用
:type IsEnable: bool
"""
self.IsDefault = None
self.EffectImageCount = None
self.RuleId = None
self.UpdateTime = None
self.RuleName = None
self.EditUserName = None
self.IsEnable = None
def _deserialize(self, params):
self.IsDefault = params.get("IsDefault")
self.EffectImageCount = params.get("EffectImageCount")
self.RuleId = params.get("RuleId")
self.UpdateTime = params.get("UpdateTime")
self.RuleName = params.get("RuleName")
self.EditUserName = params.get("EditUserName")
self.IsEnable = params.get("IsEnable")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class RunTimeEventBaseInfo(AbstractModel):
"""运行时安全事件基本信息
"""
def __init__(self):
r"""
:param EventId: 事件唯一ID
:type EventId: str
:param FoundTime: 事件发现时间
:type FoundTime: str
:param ContainerId: 容器id
:type ContainerId: str
:param ContainerName: 容器名称
:type ContainerName: str
:param ImageId: 镜像id
:type ImageId: str
:param ImageName: 镜像名称
:type ImageName: str
:param NodeName: 节点名称
:type NodeName: str
:param PodName: Pod名称
:type PodName: str
:param Status: 状态, “EVENT_UNDEAL”:事件未处理
"EVENT_DEALED":事件已经处理
"EVENT_INGNORE":事件已经忽略
:type Status: str
:param EventName: 事件名称:
宿主机文件访问逃逸、
Syscall逃逸、
MountNamespace逃逸、
程序提权逃逸、
特权容器启动逃逸、
敏感路径挂载
恶意进程启动
文件篡改
:type EventName: str
:param EventType: 事件类型
ESCAPE_HOST_ACESS_FILE:宿主机文件访问逃逸
ESCAPE_MOUNT_NAMESPACE:MountNamespace逃逸
ESCAPE_PRIVILEDGE:程序提权逃逸
ESCAPE_PRIVILEDGE_CONTAINER_START:特权容器启动逃逸
ESCAPE_MOUNT_SENSITIVE_PTAH:敏感路径挂载
ESCAPE_SYSCALL:Syscall逃逸
:type EventType: str
:param EventCount: 事件数量
:type EventCount: int
:param LatestFoundTime: 最近生成时间
:type LatestFoundTime: str
:param HostIP: 内网ip
注意:此字段可能返回 null,表示取不到有效值。
:type HostIP: str
:param ClientIP: 外网ip
注意:此字段可能返回 null,表示取不到有效值。
:type ClientIP: str
"""
self.EventId = None
self.FoundTime = None
self.ContainerId = None
self.ContainerName = None
self.ImageId = None
self.ImageName = None
self.NodeName = None
self.PodName = None
self.Status = None
self.EventName = None
self.EventType = None
self.EventCount = None
self.LatestFoundTime = None
self.HostIP = None
self.ClientIP = None
def _deserialize(self, params):
self.EventId = params.get("EventId")
self.FoundTime = params.get("FoundTime")
self.ContainerId = params.get("ContainerId")
self.ContainerName = params.get("ContainerName")
self.ImageId = params.get("ImageId")
self.ImageName = params.get("ImageName")
self.NodeName = params.get("NodeName")
self.PodName = params.get("PodName")
self.Status = params.get("Status")
self.EventName = params.get("EventName")
self.EventType = params.get("EventType")
self.EventCount = params.get("EventCount")
self.LatestFoundTime = params.get("LatestFoundTime")
self.HostIP = params.get("HostIP")
self.ClientIP = params.get("ClientIP")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class RunTimeFilters(AbstractModel):
"""容器安全
描述键值对过滤器,用于条件过滤查询。例如过滤ID、名称、状态等
若存在多个Filter时,Filter间的关系为逻辑与(AND)关系。
若同一个Filter存在多个Values,同一Filter下Values间的关系为逻辑或(OR)关系。
"""
def __init__(self):
r"""
:param Name: 过滤键的名称
:type Name: str
:param Values: 一个或者多个过滤值。
:type Values: list of str
:param ExactMatch: 是否模糊查询
:type ExactMatch: bool
"""
self.Name = None
self.Values = None
self.ExactMatch = None
def _deserialize(self, params):
self.Name = params.get("Name")
self.Values = params.get("Values")
self.ExactMatch = params.get("ExactMatch")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class RunTimeRiskInfo(AbstractModel):
"""运行时风险信息
"""
def __init__(self):
r"""
:param Cnt: 数量
:type Cnt: int
:param Level: 风险等级:
CRITICAL: 严重
HIGH: 高
MEDIUM:中
LOW: 低
:type Level: str
"""
self.Cnt = None
self.Level = None
def _deserialize(self, params):
self.Cnt = params.get("Cnt")
self.Level = params.get("Level")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class RunTimeTendencyInfo(AbstractModel):
"""运行时趋势信息
"""
def __init__(self):
r"""
:param CurTime: 当天时间
:type CurTime: str
:param Cnt: 当前数量
:type Cnt: int
"""
self.CurTime = None
self.Cnt = None
def _deserialize(self, params):
self.CurTime = params.get("CurTime")
self.Cnt = params.get("Cnt")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ScanComplianceAssetsByPolicyItemRequest(AbstractModel):
"""ScanComplianceAssetsByPolicyItem请求参数结构体
"""
def __init__(self):
r"""
:param CustomerPolicyItemId: 指定的检测项的ID
:type CustomerPolicyItemId: int
:param CustomerAssetIdSet: 要重新扫描的客户资产项ID的列表。
:type CustomerAssetIdSet: list of int non-negative
"""
self.CustomerPolicyItemId = None
self.CustomerAssetIdSet = None
def _deserialize(self, params):
self.CustomerPolicyItemId = params.get("CustomerPolicyItemId")
self.CustomerAssetIdSet = params.get("CustomerAssetIdSet")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ScanComplianceAssetsByPolicyItemResponse(AbstractModel):
"""ScanComplianceAssetsByPolicyItem返回参数结构体
"""
def __init__(self):
r"""
:param TaskId: 返回重新检测任务的ID。
:type TaskId: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.TaskId = None
self.RequestId = None
def _deserialize(self, params):
self.TaskId = params.get("TaskId")
self.RequestId = params.get("RequestId")
class ScanComplianceAssetsRequest(AbstractModel):
"""ScanComplianceAssets请求参数结构体
"""
def __init__(self):
r"""
:param CustomerAssetIdSet: 要重新扫描的客户资产项ID的列表。
:type CustomerAssetIdSet: list of int non-negative
"""
self.CustomerAssetIdSet = None
def _deserialize(self, params):
self.CustomerAssetIdSet = params.get("CustomerAssetIdSet")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ScanComplianceAssetsResponse(AbstractModel):
"""ScanComplianceAssets返回参数结构体
"""
def __init__(self):
r"""
:param TaskId: 返回重新检测任务的ID。
:type TaskId: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.TaskId = None
self.RequestId = None
def _deserialize(self, params):
self.TaskId = params.get("TaskId")
self.RequestId = params.get("RequestId")
class ScanCompliancePolicyItemsRequest(AbstractModel):
"""ScanCompliancePolicyItems请求参数结构体
"""
def __init__(self):
r"""
:param CustomerPolicyItemIdSet: 要重新扫描的客户检测项的列表。
:type CustomerPolicyItemIdSet: list of int non-negative
"""
self.CustomerPolicyItemIdSet = None
def _deserialize(self, params):
self.CustomerPolicyItemIdSet = params.get("CustomerPolicyItemIdSet")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ScanCompliancePolicyItemsResponse(AbstractModel):
"""ScanCompliancePolicyItems返回参数结构体
"""
def __init__(self):
r"""
:param TaskId: 返回重新检测任务的ID。
:type TaskId: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.TaskId = None
self.RequestId = None
def _deserialize(self, params):
self.TaskId = params.get("TaskId")
self.RequestId = params.get("RequestId")
class ScanComplianceScanFailedAssetsRequest(AbstractModel):
"""ScanComplianceScanFailedAssets请求参数结构体
"""
def __init__(self):
r"""
:param CustomerAssetIdSet: 要重新扫描的客户资产项ID的列表。
:type CustomerAssetIdSet: list of int non-negative
"""
self.CustomerAssetIdSet = None
def _deserialize(self, params):
self.CustomerAssetIdSet = params.get("CustomerAssetIdSet")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ScanComplianceScanFailedAssetsResponse(AbstractModel):
"""ScanComplianceScanFailedAssets返回参数结构体
"""
def __init__(self):
r"""
:param TaskId: 返回重新检测任务的ID。
:type TaskId: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.TaskId = None
self.RequestId = None
def _deserialize(self, params):
self.TaskId = params.get("TaskId")
self.RequestId = params.get("RequestId")
class SecTendencyEventInfo(AbstractModel):
"""运行时安全事件趋势信息
"""
def __init__(self):
r"""
:param EventSet: 趋势列表
:type EventSet: list of RunTimeTendencyInfo
:param EventType: 事件类型:
ET_ESCAPE : 容器逃逸
ET_REVERSE_SHELL: 反弹shell
ET_RISK_SYSCALL:高危系统调用
ET_ABNORMAL_PROCESS: 异常进程
ET_ACCESS_CONTROL 文件篡改
:type EventType: str
"""
self.EventSet = None
self.EventType = None
def _deserialize(self, params):
if params.get("EventSet") is not None:
self.EventSet = []
for item in params.get("EventSet"):
obj = RunTimeTendencyInfo()
obj._deserialize(item)
self.EventSet.append(obj)
self.EventType = params.get("EventType")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class ServiceInfo(AbstractModel):
"""容器安全服务信息列表
"""
def __init__(self):
r"""
:param ServiceID: 服务id
:type ServiceID: str
:param HostID: 主机id
:type HostID: str
:param HostIP: 主机ip
:type HostIP: str
:param ContainerName: 容器名
:type ContainerName: str
:param Type: 服务名 例如nginx/redis
:type Type: str
:param Version: 版本
:type Version: str
:param RunAs: 账号
:type RunAs: str
:param Listen: 监听端口
:type Listen: list of str
:param Config: 配置
:type Config: str
:param ProcessCnt: 关联进程数
:type ProcessCnt: int
:param AccessLog: 访问日志
:type AccessLog: str
:param ErrorLog: 错误日志
:type ErrorLog: str
:param DataPath: 数据目录
:type DataPath: str
:param WebRoot: web目录
:type WebRoot: str
:param Pids: 关联的进程id
:type Pids: list of int non-negative
:param MainType: 服务类型 app,web,db
:type MainType: str
:param Exe: 执行文件
:type Exe: str
:param Parameter: 服务命令行参数
:type Parameter: str
:param ContainerId: 容器id
:type ContainerId: str
:param HostName: 主机名称
:type HostName: str
:param PublicIp: 外网ip
:type PublicIp: str
"""
self.ServiceID = None
self.HostID = None
self.HostIP = None
self.ContainerName = None
self.Type = None
self.Version = None
self.RunAs = None
self.Listen = None
self.Config = None
self.ProcessCnt = None
self.AccessLog = None
self.ErrorLog = None
self.DataPath = None
self.WebRoot = None
self.Pids = None
self.MainType = None
self.Exe = None
self.Parameter = None
self.ContainerId = None
self.HostName = None
self.PublicIp = None
def _deserialize(self, params):
self.ServiceID = params.get("ServiceID")
self.HostID = params.get("HostID")
self.HostIP = params.get("HostIP")
self.ContainerName = params.get("ContainerName")
self.Type = params.get("Type")
self.Version = params.get("Version")
self.RunAs = params.get("RunAs")
self.Listen = params.get("Listen")
self.Config = params.get("Config")
self.ProcessCnt = params.get("ProcessCnt")
self.AccessLog = params.get("AccessLog")
self.ErrorLog = params.get("ErrorLog")
self.DataPath = params.get("DataPath")
self.WebRoot = params.get("WebRoot")
self.Pids = params.get("Pids")
self.MainType = params.get("MainType")
self.Exe = params.get("Exe")
self.Parameter = params.get("Parameter")
self.ContainerId = params.get("ContainerId")
self.HostName = params.get("HostName")
self.PublicIp = params.get("PublicIp")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class SetCheckModeRequest(AbstractModel):
"""SetCheckMode请求参数结构体
"""
def __init__(self):
r"""
:param ClusterIds: 要设置的集群ID列表
:type ClusterIds: list of str
:param ClusterCheckMode: 集群检查模式(正常模式"Cluster_Normal"、主动模式"Cluster_Actived"、不设置"Cluster_Unset")
:type ClusterCheckMode: str
:param ClusterAutoCheck: 0不设置 1打开 2关闭
:type ClusterAutoCheck: int
"""
self.ClusterIds = None
self.ClusterCheckMode = None
self.ClusterAutoCheck = None
def _deserialize(self, params):
self.ClusterIds = params.get("ClusterIds")
self.ClusterCheckMode = params.get("ClusterCheckMode")
self.ClusterAutoCheck = params.get("ClusterAutoCheck")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class SetCheckModeResponse(AbstractModel):
"""SetCheckMode返回参数结构体
"""
def __init__(self):
r"""
:param SetCheckResult: "Succ"表示设置成功,"Failed"表示设置失败
:type SetCheckResult: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.SetCheckResult = None
self.RequestId = None
def _deserialize(self, params):
self.SetCheckResult = params.get("SetCheckResult")
self.RequestId = params.get("RequestId")
class SoftQuotaDayInfo(AbstractModel):
"""后付费详情
"""
def __init__(self):
r"""
:param PayTime: 扣费时间
:type PayTime: str
:param CoresCnt: 计费核数
:type CoresCnt: int
"""
self.PayTime = None
self.CoresCnt = None
def _deserialize(self, params):
self.PayTime = params.get("PayTime")
self.CoresCnt = params.get("CoresCnt")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class StopVirusScanTaskRequest(AbstractModel):
"""StopVirusScanTask请求参数结构体
"""
def __init__(self):
r"""
:param TaskId: 任务ID
:type TaskId: str
:param ContainerIds: 需要停止的容器id 为空默认停止整个任务
:type ContainerIds: list of str
"""
self.TaskId = None
self.ContainerIds = None
def _deserialize(self, params):
self.TaskId = params.get("TaskId")
self.ContainerIds = params.get("ContainerIds")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class StopVirusScanTaskResponse(AbstractModel):
"""StopVirusScanTask返回参数结构体
"""
def __init__(self):
r"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RequestId = None
def _deserialize(self, params):
self.RequestId = params.get("RequestId")
class SyncAssetImageRegistryAssetRequest(AbstractModel):
"""SyncAssetImageRegistryAsset请求参数结构体
"""
class SyncAssetImageRegistryAssetResponse(AbstractModel):
"""SyncAssetImageRegistryAsset返回参数结构体
"""
def __init__(self):
r"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RequestId = None
def _deserialize(self, params):
self.RequestId = params.get("RequestId")
class UpdateAssetImageRegistryRegistryDetailRequest(AbstractModel):
"""UpdateAssetImageRegistryRegistryDetail请求参数结构体
"""
def __init__(self):
r"""
:param Name: 仓库名
:type Name: str
:param Username: 用户名
:type Username: str
:param Password: 密码
:type Password: str
:param Url: 仓库url
:type Url: str
:param RegistryType: 仓库类型,列表:harbor
:type RegistryType: str
:param NetType: 网络类型,列表:public(公网)
:type NetType: str
:param RegistryVersion: 仓库版本
:type RegistryVersion: str
:param RegistryRegion: 区域,列表:default(默认)
:type RegistryRegion: str
:param SpeedLimit: 限速
:type SpeedLimit: int
:param Insecure: 安全模式(证书校验):0(默认) 非安全模式(跳过证书校验):1
:type Insecure: int
"""
self.Name = None
self.Username = None
self.Password = None
self.Url = None
self.RegistryType = None
self.NetType = None
self.RegistryVersion = None
self.RegistryRegion = None
self.SpeedLimit = None
self.Insecure = None
def _deserialize(self, params):
self.Name = params.get("Name")
self.Username = params.get("Username")
self.Password = params.get("Password")
self.Url = params.get("Url")
self.RegistryType = params.get("RegistryType")
self.NetType = params.get("NetType")
self.RegistryVersion = params.get("RegistryVersion")
self.RegistryRegion = params.get("RegistryRegion")
self.SpeedLimit = params.get("SpeedLimit")
self.Insecure = params.get("Insecure")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class UpdateAssetImageRegistryRegistryDetailResponse(AbstractModel):
"""UpdateAssetImageRegistryRegistryDetail返回参数结构体
"""
def __init__(self):
r"""
:param HealthCheckErr: 连接错误信息
注意:此字段可能返回 null,表示取不到有效值。
:type HealthCheckErr: str
:param NameRepeatErr: 名称错误信息
注意:此字段可能返回 null,表示取不到有效值。
:type NameRepeatErr: str
:param RegistryId: 仓库唯一id
注意:此字段可能返回 null,表示取不到有效值。
:type RegistryId: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.HealthCheckErr = None
self.NameRepeatErr = None
self.RegistryId = None
self.RequestId = None
def _deserialize(self, params):
self.HealthCheckErr = params.get("HealthCheckErr")
self.NameRepeatErr = params.get("NameRepeatErr")
self.RegistryId = params.get("RegistryId")
self.RequestId = params.get("RequestId")
class UpdateImageRegistryTimingScanTaskRequest(AbstractModel):
"""UpdateImageRegistryTimingScanTask请求参数结构体
"""
def __init__(self):
r"""
:param ScanPeriod: 定时扫描周期
:type ScanPeriod: int
:param Enable: 定时扫描开关
:type Enable: bool
:param ScanTime: 定时扫描的时间
:type ScanTime: str
:param ScanType: 扫描木马类型数组
:type ScanType: list of str
:param Images: 扫描镜像
:type Images: list of ImageInfo
:param All: 是否扫描所有
:type All: bool
:param Id: 扫描镜像Id
:type Id: list of int non-negative
"""
self.ScanPeriod = None
self.Enable = None
self.ScanTime = None
self.ScanType = None
self.Images = None
self.All = None
self.Id = None
def _deserialize(self, params):
self.ScanPeriod = params.get("ScanPeriod")
self.Enable = params.get("Enable")
self.ScanTime = params.get("ScanTime")
self.ScanType = params.get("ScanType")
if params.get("Images") is not None:
self.Images = []
for item in params.get("Images"):
obj = ImageInfo()
obj._deserialize(item)
self.Images.append(obj)
self.All = params.get("All")
self.Id = params.get("Id")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class UpdateImageRegistryTimingScanTaskResponse(AbstractModel):
"""UpdateImageRegistryTimingScanTask返回参数结构体
"""
def __init__(self):
r"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RequestId = None
def _deserialize(self, params):
self.RequestId = params.get("RequestId")
class VirusInfo(AbstractModel):
"""运行时木马列表信息
"""
def __init__(self):
r"""
:param FileName: 文件名称
:type FileName: str
:param FilePath: 文件路径
:type FilePath: str
:param VirusName: 病毒名称
:type VirusName: str
:param CreateTime: 创建时间
:type CreateTime: str
:param ModifyTime: 更新时间
:type ModifyTime: str
:param ContainerName: 容器名称
:type ContainerName: str
:param ContainerId: 容器id
:type ContainerId: str
:param ContainerStatus: 容器状态,CS_RUNING:运行, CS_PAUSE:暂停,CS_STOP:停止,
CS_CREATE:已经创建, CS_DESTORY:销毁
:type ContainerStatus: str
:param ImageName: 镜像名称
:type ImageName: str
:param ImageId: 镜像id
:type ImageId: str
:param Status: DEAL_NONE:文件待处理
DEAL_IGNORE:已经忽略
DEAL_ADD_WHITELIST:加白
DEAL_DEL:文件已经删除
DEAL_ISOLATE:已经隔离
DEAL_ISOLATING:隔离中
DEAL_ISOLATE_FAILED:隔离失败
DEAL_RECOVERING:恢复中
DEAL_RECOVER_FAILED: 恢复失败
:type Status: str
:param Id: 事件id
:type Id: str
:param HarmDescribe: 事件描述
:type HarmDescribe: str
:param SuggestScheme: 建议方案
:type SuggestScheme: str
:param SubStatus: 失败子状态:
FILE_NOT_FOUND:文件不存在
FILE_ABNORMAL:文件异常
FILE_ABNORMAL_DEAL_RECOVER:恢复文件时,文件异常
BACKUP_FILE_NOT_FOUND:备份文件不存在
CONTAINER_NOT_FOUND_DEAL_ISOLATE:隔离时,容器不存在
CONTAINER_NOT_FOUND_DEAL_RECOVER:恢复时,容器不存在
TIMEOUT: 超时
TOO_MANY: 任务过多
OFFLINE: 离线
INTERNAL: 服务内部错误
VALIDATION: 参数非法
:type SubStatus: str
"""
self.FileName = None
self.FilePath = None
self.VirusName = None
self.CreateTime = None
self.ModifyTime = None
self.ContainerName = None
self.ContainerId = None
self.ContainerStatus = None
self.ImageName = None
self.ImageId = None
self.Status = None
self.Id = None
self.HarmDescribe = None
self.SuggestScheme = None
self.SubStatus = None
def _deserialize(self, params):
self.FileName = params.get("FileName")
self.FilePath = params.get("FilePath")
self.VirusName = params.get("VirusName")
self.CreateTime = params.get("CreateTime")
self.ModifyTime = params.get("ModifyTime")
self.ContainerName = params.get("ContainerName")
self.ContainerId = params.get("ContainerId")
self.ContainerStatus = params.get("ContainerStatus")
self.ImageName = params.get("ImageName")
self.ImageId = params.get("ImageId")
self.Status = params.get("Status")
self.Id = params.get("Id")
self.HarmDescribe = params.get("HarmDescribe")
self.SuggestScheme = params.get("SuggestScheme")
self.SubStatus = params.get("SubStatus")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class VirusTaskInfo(AbstractModel):
"""运行时文件查杀任务容器列表信息
"""
def __init__(self):
r"""
:param ContainerName: 容器名称
:type ContainerName: str
:param ContainerId: 容器id
:type ContainerId: str
:param ImageName: 镜像名称
:type ImageName: str
:param ImageId: 镜像Id
:type ImageId: str
:param HostName: 主机名称
:type HostName: str
:param HostIp: 主机ip
:type HostIp: str
:param Status: 扫描状态:
WAIT: 等待扫描
FAILED: 失败
SCANNING: 扫描中
FINISHED: 结束
CANCELING: 取消中
CANCELED: 已取消
CANCEL_FAILED: 取消失败
:type Status: str
:param StartTime: 检测开始时间
:type StartTime: str
:param EndTime: 检测结束时间
:type EndTime: str
:param RiskCnt: 风险个数
:type RiskCnt: int
:param Id: 事件id
:type Id: str
:param ErrorMsg: 错误原因:
SEND_SUCCESSED: 下发成功
SCAN_WAIT: agent排队扫描等待中
OFFLINE: 离线
SEND_FAILED:下发失败
TIMEOUT: 超时
LOW_AGENT_VERSION: 客户端版本过低
AGENT_NOT_FOUND: 镜像所属客户端版不存在
TOO_MANY: 任务过多
VALIDATION: 参数非法
INTERNAL: 服务内部错误
MISC: 其他错误
UNAUTH: 所在镜像未授权
SEND_CANCEL_SUCCESSED:下发成功
:type ErrorMsg: str
"""
self.ContainerName = None
self.ContainerId = None
self.ImageName = None
self.ImageId = None
self.HostName = None
self.HostIp = None
self.Status = None
self.StartTime = None
self.EndTime = None
self.RiskCnt = None
self.Id = None
self.ErrorMsg = None
def _deserialize(self, params):
self.ContainerName = params.get("ContainerName")
self.ContainerId = params.get("ContainerId")
self.ImageName = params.get("ImageName")
self.ImageId = params.get("ImageId")
self.HostName = params.get("HostName")
self.HostIp = params.get("HostIp")
self.Status = params.get("Status")
self.StartTime = params.get("StartTime")
self.EndTime = params.get("EndTime")
self.RiskCnt = params.get("RiskCnt")
self.Id = params.get("Id")
self.ErrorMsg = params.get("ErrorMsg")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class WarningRule(AbstractModel):
"""告警配置策略
"""
def __init__(self):
r"""
:param Type: 告警事件类型:
镜像仓库安全-木马:IMG_REG_VIRUS
镜像仓库安全-漏洞:IMG_REG_VUL
镜像仓库安全-敏感信息:IMG_REG_RISK
镜像安全-木马:IMG_VIRUS
镜像安全-漏洞:IMG_VUL
镜像安全-敏感信息:IMG_RISK
镜像安全-镜像拦截:IMG_INTERCEPT
运行时安全-容器逃逸:RUNTIME_ESCAPE
运行时安全-异常进程:RUNTIME_FILE
运行时安全-异常文件访问:RUNTIME_PROCESS
运行时安全-高危系统调用:RUNTIME_SYSCALL
运行时安全-反弹Shell:RUNTIME_REVERSE_SHELL
运行时安全-木马:RUNTIME_VIRUS
:type Type: str
:param Switch: 开关状态:
打开:ON
关闭:OFF
:type Switch: str
:param BeginTime: 告警开始时间,格式: HH:mm
:type BeginTime: str
:param EndTime: 告警结束时间,格式: HH:mm
:type EndTime: str
:param ControlBits: 告警等级策略控制,二进制位每位代表一个含义,值以字符串类型传递
控制开关分为高、中、低,则二进制位分别为:第1位:低,第2位:中,第3位:高,0表示关闭、1表示打开。
如:高危和中危打开告警,低危关闭告警,则二进制值为:110
告警类型不区分等级控制,则传1。
:type ControlBits: str
"""
self.Type = None
self.Switch = None
self.BeginTime = None
self.EndTime = None
self.ControlBits = None
def _deserialize(self, params):
self.Type = params.get("Type")
self.Switch = params.get("Switch")
self.BeginTime = params.get("BeginTime")
self.EndTime = params.get("EndTime")
self.ControlBits = params.get("ControlBits")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
| tzpBingo/github-trending | codespace/python/tencentcloud/tcss/v20201101/models.py | Python | mit | 529,829 |
from pathlib import Path
import cv2
import dlib
import numpy as np
import argparse
from contextlib import contextmanager
from omegaconf import OmegaConf
from tensorflow.keras.utils import get_file
from src.factory import get_model
pretrained_model = "https://github.com/yu4u/age-gender-estimation/releases/download/v0.6/EfficientNetB3_224_weights.11-3.44.hdf5"
modhash = '6d7f7b7ced093a8b3ef6399163da6ece'
def get_args():
parser = argparse.ArgumentParser(description="This script detects faces from web cam input, "
"and estimates age and gender for the detected faces.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--weight_file", type=str, default=None,
help="path to weight file (e.g. weights.28-3.73.hdf5)")
parser.add_argument("--margin", type=float, default=0.4,
help="margin around detected face for age-gender estimation")
parser.add_argument("--image_dir", type=str, default=None,
help="target image directory; if set, images in image_dir are used instead of webcam")
args = parser.parse_args()
return args
def draw_label(image, point, label, font=cv2.FONT_HERSHEY_SIMPLEX,
font_scale=0.8, thickness=1):
size = cv2.getTextSize(label, font, font_scale, thickness)[0]
x, y = point
cv2.rectangle(image, (x, y - size[1]), (x + size[0], y), (255, 0, 0), cv2.FILLED)
cv2.putText(image, label, point, font, font_scale, (255, 255, 255), thickness, lineType=cv2.LINE_AA)
@contextmanager
def video_capture(*args, **kwargs):
cap = cv2.VideoCapture(*args, **kwargs)
try:
yield cap
finally:
cap.release()
def yield_images():
# capture video
with video_capture(0) as cap:
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
while True:
# get video frame
ret, img = cap.read()
if not ret:
raise RuntimeError("Failed to capture image")
yield img
def yield_images_from_dir(image_dir):
image_dir = Path(image_dir)
for image_path in image_dir.glob("*.*"):
img = cv2.imread(str(image_path), 1)
if img is not None:
h, w, _ = img.shape
r = 640 / max(w, h)
yield cv2.resize(img, (int(w * r), int(h * r)))
def main():
args = get_args()
weight_file = args.weight_file
margin = args.margin
image_dir = args.image_dir
if not weight_file:
weight_file = get_file("weights.28-3.73.hdf5", pretrained_model, cache_subdir="pretrained_models",
file_hash=modhash, cache_dir=str(Path(__file__).resolve().parent))
# for face detection
detector = dlib.get_frontal_face_detector()
# load model and weights
model_name, img_size = Path(weight_file).stem.split("_")[:2]
img_size = int(img_size)
cfg = OmegaConf.from_dotlist([f"model.model_name={model_name}", f"model.img_size={img_size}"])
model = get_model(cfg)
model.load_weights(weight_file)
image_generator = yield_images_from_dir(image_dir) if image_dir else yield_images()
for img in image_generator:
input_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img_h, img_w, _ = np.shape(input_img)
# detect faces using dlib detector
detected = detector(input_img, 1)
faces = np.empty((len(detected), img_size, img_size, 3))
if len(detected) > 0:
for i, d in enumerate(detected):
x1, y1, x2, y2, w, h = d.left(), d.top(), d.right() + 1, d.bottom() + 1, d.width(), d.height()
xw1 = max(int(x1 - margin * w), 0)
yw1 = max(int(y1 - margin * h), 0)
xw2 = min(int(x2 + margin * w), img_w - 1)
yw2 = min(int(y2 + margin * h), img_h - 1)
cv2.rectangle(img, (x1, y1), (x2, y2), (255, 0, 0), 2)
# cv2.rectangle(img, (xw1, yw1), (xw2, yw2), (255, 0, 0), 2)
faces[i] = cv2.resize(img[yw1:yw2 + 1, xw1:xw2 + 1], (img_size, img_size))
# predict ages and genders of the detected faces
results = model.predict(faces)
predicted_genders = results[0]
ages = np.arange(0, 101).reshape(101, 1)
predicted_ages = results[1].dot(ages).flatten()
# draw results
for i, d in enumerate(detected):
label = "{}, {}".format(int(predicted_ages[i]),
"M" if predicted_genders[i][0] < 0.5 else "F")
draw_label(img, (d.left(), d.top()), label)
cv2.imshow("result", img)
key = cv2.waitKey(-1) if image_dir else cv2.waitKey(30)
if key == 27: # ESC
break
if __name__ == '__main__':
main()
| yu4u/age-gender-estimation | demo.py | Python | mit | 4,936 |
#!/usr/local/bin/python
a=['red','orange','yellow','green','blue','purple']
odds=a[::2]
evens=a[1::2]
print odds
print evens
x=b'abcdefg'
y=x[::-1]
print y
c=['a','b','c','d','e','f']
d=c[::2]
e=d[1:-1]
print e
| Vayne-Lover/Effective | Python/Effective Python/item6.py | Python | mit | 211 |
# -*- coding: utf-8 -*-
# This file is part of pygal
#
# A python svg graph plotting library
# Copyright © 2012 Kozea
#
# This library is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# This library 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 Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with pygal. If not, see <http://www.gnu.org/licenses/>.
"""
Config module with all options
"""
from copy import deepcopy
from pygal.style import Style, DefaultStyle
class FontSizes(object):
"""Container for font sizes"""
CONFIG_ITEMS = []
class Key(object):
_categories = []
def __init__(
self, default_value, type_, category, doc,
subdoc="", subtype=None):
self.value = default_value
self.type = type_
self.doc = doc
self.category = category
self.subdoc = subdoc
self.subtype = subtype
self.name = "Unbound"
if not category in self._categories:
self._categories.append(category)
CONFIG_ITEMS.append(self)
@property
def is_boolean(self):
return self.type == bool
@property
def is_numeric(self):
return self.type == int
@property
def is_string(self):
return self.type == str
@property
def is_list(self):
return self.type == list
def coerce(self, value):
if self.type == Style:
return value
elif self.type == list:
return self.type(
map(
self.subtype, map(
lambda x: x.strip(), value.split(','))))
return self.type(value)
class MetaConfig(type):
def __new__(mcs, classname, bases, classdict):
for k, v in classdict.items():
if isinstance(v, Key):
v.name = k
return type.__new__(mcs, classname, bases, classdict)
class Config(object):
"""Class holding config values"""
__metaclass__ = MetaConfig
style = Key(
DefaultStyle, Style, "Style", "Style holding values injected in css")
css = Key(
('style.css', 'graph.css'), list, "Style",
"List of css file",
"It can be an absolute file path or an external link",
str)
############ Look ############
title = Key(
None, str, "Look",
"Graph title.", "Leave it to None to disable title.")
width = Key(
800, int, "Look", "Graph width")
height = Key(
600, int, "Look", "Graph height")
show_dots = Key(True, bool, "Look", "Set to false to remove dots")
stroke = Key(
True, bool, "Look",
"Line dots (set it to false to get a scatter plot)")
fill = Key(
False, bool, "Look", "Fill areas under lines")
show_legend = Key(
True, bool, "Look", "Set to false to remove legend")
legend_at_bottom = Key(
False, bool, "Look", "Set to true to position legend at bottom")
legend_box_size = Key(
12, int, "Look", "Size of legend boxes")
rounded_bars = Key(
None, int, "Look", "Set this to the desired radius in px")
############ Label ############
x_labels = Key(
None, list, "Label",
"X labels, must have same len than data.",
"Leave it to None to disable x labels display.",
str)
y_labels = Key(
None, list, "Label",
"You can specify explicit y labels",
"Must be a list of numbers", float)
x_label_rotation = Key(
0, int, "Label", "Specify x labels rotation angles", "in degrees")
y_label_rotation = Key(
0, int, "Label", "Specify y labels rotation angles", "in degrees")
############ Value ############
human_readable = Key(
False, bool, "Value", "Display values in human readable format",
"(ie: 12.4M)")
logarithmic = Key(
False, bool, "Value", "Display values in logarithmic scale")
interpolate = Key(
None, str, "Value", "Interpolation, this requires scipy module",
"May be any of 'linear', 'nearest', 'zero', 'slinear', 'quadratic,"
"'cubic', 'krogh', 'barycentric', 'univariate',"
"or an integer specifying the order"
"of the spline interpolator")
interpolation_precision = Key(
250, int, "Value", "Number of interpolated points between two values")
order_min = Key(
None, int, "Value", "Minimum order of scale, defaults to None")
range = Key(
None, list, "Value", "Explicitly specify min and max of values",
"(ie: (0, 100))", int)
include_x_axis = Key(
False, bool, "Value", "Always include x axis")
zero = Key(
0, int, "Value",
"Set the ordinate zero value",
"Useful for filling to another base than abscissa")
############ Text ############
no_data_text = Key(
"No data", str, "Text", "Text to display when no data is given")
label_font_size = Key(10, int, "Text", "Label font size")
value_font_size = Key(8, int, "Text", "Value font size")
tooltip_font_size = Key(20, int, "Text", "Tooltip font size")
title_font_size = Key(16, int, "Text", "Title font size")
legend_font_size = Key(14, int, "Text", "Legend font size")
no_data_font_size = Key(64, int, "Text", "No data text font size")
print_values = Key(
True, bool,
"Text", "Print values when graph is in non interactive mode")
print_zeroes = Key(
False, bool,
"Text", "Print zeroes when graph is in non interactive mode")
truncate_legend = Key(
None, int, "Text",
"Legend string length truncation threshold", "None = auto")
truncate_label = Key(
None, int, "Text",
"Label string length truncation threshold", "None = auto")
############ Misc ############
js = Key(
('https://raw.github.com/Kozea/pygal.js/master/svg.jquery.js',
'https://raw.github.com/Kozea/pygal.js/master/pygal-tooltips.js'),
list, "Misc", "List of js file",
"It can be a filepath or an external link",
str)
disable_xml_declaration = Key(
False, bool, "Misc",
"Don't write xml declaration and return str instead of string",
"usefull for writing output directly in html")
explicit_size = Key(
False, bool, "Misc", "Write width and height attributes")
pretty_print = Key(
False, bool, "Misc", "Pretty print the svg")
strict = Key(
False, bool, "Misc",
"If True don't try to adapt / filter wrong values")
def __init__(self, **kwargs):
"""Can be instanciated with config kwargs"""
for k in dir(self):
v = getattr(self, k)
if (k not in self.__dict__ and not
k.startswith('_') and not
hasattr(v, '__call__')):
if isinstance(v, Key):
v = v.value
setattr(self, k, v)
self.css = list(self.css)
self.js = list(self.js)
self._update(kwargs)
def __call__(self, **kwargs):
"""Can be updated with kwargs"""
self._update(kwargs)
def _update(self, kwargs):
self.__dict__.update(
dict([(k, v) for (k, v) in kwargs.items()
if not k.startswith('_') and k in dir(self)]))
def font_sizes(self, with_unit=True):
"""Getter for all font size configs"""
fs = FontSizes()
for name in dir(self):
if name.endswith('_font_size'):
setattr(
fs,
name.replace('_font_size', ''),
('%dpx' % getattr(self, name))
if with_unit else getattr(self, name))
return fs
def to_dict(self):
config = {}
for attr in dir(self):
if not attr.startswith('__'):
value = getattr(self, attr)
if hasattr(value, 'to_dict'):
config[attr] = value.to_dict()
elif not hasattr(value, '__call__'):
config[attr] = value
return config
def copy(self):
return deepcopy(self)
| vineethguna/heroku-buildpack-libsandbox | vendor/pygal-0.13.0/pygal/config.py | Python | mit | 8,580 |
# __version__ = "1.0"
from . import data_processing
from . import plotly_usmap
from . import UI_setup
# from .data_processing import *
# from .plotly_usmap import *
# from .UI_setup import *
| UWSEDS-aut17/uwseds-group-city-fynders | cityfynders/__init__.py | Python | mit | 193 |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2016 Pi-Yueh Chuang <pychuang@gwu.edu>
#
# Distributed under terms of the MIT license.
"""__init__.py"""
from utils.errors.Error import Error
from utils.errors.InfLoopError import InfLoopError
__author__ = "Pi-Yueh Chuang"
__version__ = "alpha"
| piyueh/SEM-Toolbox | utils/errors/__init__.py | Python | mit | 330 |
#!/usr/bin/env python3
#
# Copyright (c) 2016-2018 Weitian LI <weitian@aaronly.me>
# MIT License
#
# TODO:
# * allow to query by coordinates & radius range
# * filter queried results according to the type/other...
# * if not queried by name, then try query by coordinates
#
"""
Query NED with the provided name or coordinate.
NASA/IPAC Extragalactic Database: http://ned.ipac.caltech.edu/
References
----------
* astroquery: NedClass
https://astroquery.readthedocs.org/en/latest/api/astroquery.ned.NedClass.html
"""
import sys
import argparse
import csv
from collections import OrderedDict
from astroquery.ned import Ned
from astroquery.exceptions import RemoteServiceError
# Ned configurations
Ned.TIMEOUT = 20
def query_name(name, verbose=False, print_header=False):
"""
Query NED by source name.
"""
try:
q = Ned.query_object(name)
objname = q["Object Name"][0]
objtype = q["Type"][0].decode("utf-8")
ra = q["RA(deg)"][0]
dec = q["DEC(deg)"][0]
velocity = q["Velocity"][0]
z = q["Redshift"][0]
z_flag = q["Redshift Flag"][0].decode("utf-8")
refs = q["References"][0]
notes = q["Notes"][0]
except RemoteServiceError:
objname = None
objtype = None
ra = None
dec = None
velocity = None
z = None
z_flag = None
refs = None
notes = None
if verbose:
print("*** %s: not found ***" % name, file=sys.stderr)
#
results = OrderedDict([
("Name", name),
("NED_Name", objname),
("Type", objtype),
("RA", ra),
("DEC", dec),
("Velocity", velocity),
("z", z),
("z_Flag", z_flag),
("References", refs),
("Notes", notes),
])
if verbose:
if print_header:
print(",".join(results.keys()))
print(",".join([str(v) for v in results.values()]))
return results
def main():
parser = argparse.ArgumentParser(
description="Query NED database by source name")
parser.add_argument("-v", "--verbose", dest="verbose",
action="store_true",
help="show verbose information")
parser.add_argument("-b", "--brief", dest="brief",
action="store_true",
help="be brief and do not print header")
parser.add_argument("-i", "--input", dest="input", required=True,
help="source names to be queried (sep by comma); " +
"or a file contains the names (one per line)")
parser.add_argument("-o", "--output", dest="output",
default=sys.stdout,
help="output CSV file with queried data")
args = parser.parse_args()
try:
names = list(map(str.strip, open(args.input).readlines()))
except FileNotFoundError:
names = list(map(str.strip, args.input.split(",")))
results_list = []
print_header = True
for name in names:
qr = query_name(name, verbose=args.verbose,
print_header=print_header)
print_header = False
results_list.append(qr)
try:
of = open(args.output, "w")
except TypeError:
of = args.output
writer = csv.writer(of)
if not args.brief:
writer.writerow(results_list[0].keys())
for res in results_list:
writer.writerow(res.values())
if of is not sys.stdout:
of.close()
if __name__ == "__main__":
main()
| liweitianux/atoolbox | astro/query_ned.py | Python | mit | 3,683 |
from setuptools import setup, find_packages
import gravatar
setup(
name='dj-gravatar',
version=gravatar.__version__,
packages=find_packages(),
long_description=open('README.md').read(),
install_requires=[
'Django',
]
)
| Sheeprider/dj-gravatar | setup.py | Python | mit | 252 |
#!/usr/bin/python
from commands.utilities import register
import asyncio
import re
class Voting():
def __init__(self, config=None):
# regex to match a number at the start of the message.
# Being a float is optional.
self.length_re = r'--((\d*)?(\.\d*)?)'
# regex to atch and capture vote options in square bracket.
self.options_re = r'\[(.+)\]'
self.vote_length = 0.5
self.default_options = ['yes', 'no']
self.active_votes = {}
def apply_regex(self, msg, regex):
'''
Applies the regex and removes the matched
elements from the message.
Returns the matched group.
'''
result = re.search(regex, msg)
if result:
msg = re.sub(regex, '', msg).strip()
return msg, result.group(0)
else:
return False
def handle_input(self, msg):
'''
Parses the supplied message to determine the vote
length and supplied parameteres(if any).
Expected vote format:
!vote[--time] String of the vote [[parameter1, parm2]]
'''
# Check if the user supplied a length
regex_result = self.apply_regex(msg, self.length_re)
if regex_result:
msg, matched_length = regex_result
# start at the second index to avoid the -- at the start
# of the time parameter.
vote_length = float(matched_length[2:])
else:
vote_length = self.vote_length
# Check if the user supplied extra parameters
regex_result = self.apply_regex(msg, self.options_re)
if regex_result:
msg, extra_options = regex_result
# remove square brackets, split on comma and strip whitespace
extra_options = extra_options.replace('[', '').replace(']', '')
options = extra_options.lower().split(',')
options = [word.strip() for word in options]
# Storing length in a variable here to later compare
# after forming a dictionary to ensure there were no
# duplicates.
option_len = len(options)
if len(options) < 2:
return False
# Create a dictionary with the voter counts set to 0
values = [0 for option in options]
vote_options = dict(zip(options, values))
# Make sure the options aren't repeated by comparing length
# before the dictionary was created.
if option_len != len(vote_options):
return False
else:
values = [0 for index in self.default_options]
vote_options = dict(zip(self.default_options, values))
# What remains of the msg should be the vote question.
if len(msg.strip()) < 1:
return False
return msg, vote_length, vote_options
async def send_start_message(self, client, channel, vote_length, msg):
'''
Simple function that sends a message that a
vote has started asyncronously.
'''
vote_parms = self.active_votes[channel][1]
start_string = 'Starting vote ```%s``` with options ' % msg
param_string = ' '.join(['%s' for index in range(len(vote_parms))])
start_string += '[ ' + param_string % tuple(vote_parms.keys()) + ' ]'
start_string += ' For %s minutes.' % vote_length
await channel.send(start_string)
async def end_vote(self, client, channel, msg):
'''
Counts the votes to determine the winner and sends
the finish message. Cant simply check the max value
because there might be a draw. Should probably break
it up.
'''
vote_parms = self.active_votes[channel][1]
end_string = 'Voting for ```%s``` completed.' % msg
max_value = max(vote_parms.values())
winners = [key for key, value in vote_parms.items()
if value == max_value]
if len(winners) == 1:
end_string += ' The winner is **%s**' % tuple(winners)
else:
winner_string = ' '.join(['%s' for index in range(len(winners))])
end_string += ' The winners are [ **' + winner_string % tuple(winners) + '** ]'
await channel.send(end_string)
async def run_vote(self, client, channel, vote_length, msg):
'''
Simple async function that sleeps for the vote length
and calls the start and end voting functions.
'''
await self.send_start_message(client, channel, vote_length, msg)
# sleep for the vote length.
await asyncio.sleep(vote_length * 60)
# Count the votes and send the ending message
await self.end_vote(client, channel, msg)
# Delete the dictionary entry now that the vote is finished.
del self.active_votes[channel]
@register('!vote')
async def start_vote(self, msg, user, channel, client, *args, **kwargs):
'''
Main function that handles the vote function. Makes sure
that only vote is going at a time in a channel.
Calls from a channel that has a vote going on are
considered to be a vote for the ongoing vote.
dict entry: active_votes(client, {option: count}, [voters])
'''
if channel not in self.active_votes:
processed_input = self.handle_input(msg)
if processed_input:
msg, vote_len, params = processed_input
# Save a reference to the sleep function, the valid params
# for the specific vote and an empty list which will contain
# the name of users who have already voted.
self.active_votes[channel] = (self.run_vote, params, [])
# print('starting vote with ', params)
# Start the actual vote.
await self.active_votes[channel][0](client, channel, vote_len, msg)
else:
return ('Invalid format for starting a vote. The correct format is '
'```!vote[--time] Vote question [vote options]``` '
'**eg:** !vote start a vote on some topic? [yes, no, maybe]')
else:
# An active vote already exists for this channel.
# First check if the user has already voted in it.
if user in self.active_votes[channel][2]:
return ("Stop attempting electoral fraud %s, "
"you've already voted") % user
else:
# Check if the supplied argument is a valid vote option.
vote_option = msg.lower().strip()
valid_options = self.active_votes[channel][1]
if vote_option in valid_options:
self.active_votes[channel][1][vote_option] += 1
# Add the user to the list of users.
self.active_votes[channel][2].append(user)
# return 'Increasing %s vote :)' % vote_option
else:
error_str = 'Invalid vote option %s. ' % user
error_str += 'The options are ' + str(tuple(valid_options.keys()))
return error_str
| ellipses/Yaksha | src/commands/voting.py | Python | mit | 7,274 |
import time
import requests
from .exceptions import HttpError
from .json import json_loads
def check_rep(rep):
if (rep.status_code // 100) != 2:
raise HttpError(rep.text, rep.status_code)
def rep_to_json(rep):
check_rep(rep)
# we use our json loads for date parsing
return json_loads(rep.text)
class RestClient:
MAX_ITERATIONS = 100
def __init__(
self,
url,
login,
password,
verify_ssl=True
):
self.base_url = url.strip("/")
self.session = requests.Session()
self.session.auth = (login, password)
self.verify_ssl = verify_ssl
def list(self, path, params=None):
rep = self.session.get(
f"{self.base_url}/{path}/",
params=params,
verify=self.verify_ssl)
return rep_to_json(rep)
def retrieve(self, path, resource_id):
rep = self.session.get(
f"{self.base_url}/{path}/{resource_id}/",
verify=self.verify_ssl)
return rep_to_json(rep)
def create(self, path, data):
rep = self.session.post(
f"{self.base_url}/{path}/",
json=data,
verify=self.verify_ssl)
return rep_to_json(rep)
def partial_update(self, path, resource_id, data):
rep = self.session.patch(
f"{self.base_url}/{path}/{resource_id}/",
json=data,
verify=self.verify_ssl)
return rep_to_json(rep)
def update(self, path, resource_id, data):
rep = self.session.put(
f"{self.base_url}/{path}/{resource_id}/",
json=data,
verify=self.verify_ssl)
return rep_to_json(rep)
def detail_action(
self,
path,
resource_id,
http_method,
action_name,
params=None,
data=None,
return_json=True,
send_json=True):
rep = getattr(self.session, http_method.lower())(
f"{self.base_url}/{path}/{resource_id}/{action_name}/",
params=params,
json=data if send_json else None,
data=None if send_json else data,
verify=self.verify_ssl
)
if rep.status_code == 204:
return
if return_json:
return rep_to_json(rep)
check_rep(rep)
return rep.content
def list_action(
self,
path,
http_method,
action_name,
params=None,
data=None,
return_json=True,
send_json=True):
rep = getattr(self.session, http_method.lower())(
f"{self.base_url}/{path}/{action_name}/",
params=params,
json=data if send_json else None,
data=None if send_json else data,
verify=self.verify_ssl
)
if rep.status_code == 204:
return
if return_json:
return rep_to_json(rep)
check_rep(rep)
return rep.content
def destroy(self, path, resource_id, params=None):
rep = self.session.delete(
f"{self.base_url}/{path}/{resource_id}/",
params=params,
verify=self.verify_ssl)
if rep.status_code == 204:
return
return rep_to_json(rep)
def wait_for_on(self, timeout=10, freq=1):
start = time.time()
if timeout <= 0:
raise ValueError
while True:
if (time.time() - start) > timeout:
raise TimeoutError
try:
rep = self.session.get(
f"{self.base_url}/oteams/projects/",
params=dict(empty=True),
verify=self.verify_ssl)
if rep.status_code == 503:
raise TimeoutError
break
except (requests.exceptions.ConnectionError, TimeoutError):
pass
time.sleep(freq)
| openergy/openergy | ovbpclient/rest_client.py | Python | mit | 4,045 |
"""Queue implementation using Linked list."""
from __future__ import print_function
from linked_list import Linked_List, Node
class Queue(Linked_List):
def __init__(self):
Linked_List.__init__(self)
def enqueue(self, item):
node = Node(item)
self.insert_front(node)
def dequeue(self):
return self.remove_end()
def is_empty(self):
return self.count == 0
def size(self):
return self.count
def test_queue():
print("\n\n QUEUE TESTING")
queue = Queue()
print("Queue Empty?", queue.is_empty())
queue.enqueue("A")
queue.enqueue("B")
queue.enqueue("C")
print("Queue Size:", queue.size())
print(queue)
print("DEQUEUEING 1")
print(queue.dequeue())
print(queue)
print("Queue Size:", queue.size())
print("DEQUEUEING 2")
print(queue.dequeue())
print(queue)
print("Queue Size:", queue.size())
print("Queue Empty?", queue.is_empty())
print("DEQUEUEING 3")
print(queue.dequeue())
print(queue)
print("Queue Size:", queue.size())
print("Queue Empty?", queue.is_empty())
print(queue)
print("DEQUEUEING 4")
print(queue.dequeue())
if __name__ == '__main__':
test_queue()
| dineshrajpurohit/ds_al | queue.py | Python | mit | 1,234 |
from key import Key
def _object_getattr(obj, field):
"""Attribute getter for the objects to operate on.
This function can be overridden in classes or instances of Query, Filter, and
Order. Thus, a custom function to extract values to attributes can be
specified, and the system can remain agnostic to the client's data model,
without loosing query power.
For example, the default implementation works with attributes and items::
def _object_getattr(obj, field):
# check whether this key is an attribute
if hasattr(obj, field):
value = getattr(obj, field)
# if not, perhaps it is an item (raw dicts, etc)
elif field in obj:
value = obj[field]
# return whatever we've got.
return value
Or consider a more complex, application-specific structure::
def _object_getattr(version, field):
if field in ['key', 'committed', 'created', 'hash']:
return getattr(version, field)
else:
return version.attributes[field]['value']
"""
# TODO: consider changing this to raise an exception if no value is found.
value = None
# check whether this key is an attribute
if hasattr(obj, field):
value = getattr(obj, field)
# if not, perhaps it is an item (raw dicts, etc)
elif field in obj:
value = obj[field]
# return whatever we've got.
return value
def limit_gen(limit, iterable):
"""A generator that applies a count `limit`."""
limit = int(limit)
assert limit >= 0, 'negative limit'
for item in iterable:
if limit <= 0:
break
yield item
limit -= 1
def offset_gen(offset, iterable, skip_signal=None):
"""A generator that applies an `offset`, skipping `offset` elements from
`iterable`. If skip_signal is a callable, it will be called with every
skipped element.
"""
offset = int(offset)
assert offset >= 0, 'negative offset'
for item in iterable:
if offset > 0:
offset -= 1
if callable(skip_signal):
skip_signal(item)
else:
yield item
def chain_gen(iterables):
"""A generator that chains `iterables`."""
for iterable in iterables:
for item in iterable:
yield item
class Filter(object):
"""Represents a Filter for a specific field and its value.
Filters are used on queries to narrow down the set of matching objects.
Args:
field: the attribute name (string) on which to apply the filter.
op: the conditional operator to apply (one of
['<', '<=', '=', '!=', '>=', '>']).
value: the attribute value to compare against.
Examples::
Filter('name', '=', 'John Cleese')
Filter('age', '>=', 18)
"""
conditional_operators = ['<', '<=', '=', '!=', '>=', '>']
"""Conditional operators that Filters support."""
_conditional_cmp = {
"<": lambda a, b: a < b,
"<=": lambda a, b: a <= b,
"=": lambda a, b: a == b,
"!=": lambda a, b: a != b,
">=": lambda a, b: a >= b,
">": lambda a, b: a > b
}
object_getattr = staticmethod(_object_getattr)
"""Object attribute getter. Can be overridden to match client data model.
See :py:meth:`datastore.query._object_getattr`.
"""
def __init__(self, field, op, value):
if op not in self.conditional_operators:
raise ValueError(
'"%s" is not a valid filter Conditional Operator' % op)
self.field = field
self.op = op
self.value = value
def __call__(self, obj):
"""Returns whether this object passes this filter.
This method aggressively tries to find the appropriate value.
"""
value = self.object_getattr(obj, self.field)
# TODO: which way should the direction go here? it may make more sense to
# convert the passed-in value instead. Or try both? Or not at all?
if not isinstance(value, self.value.__class__) and not self.value is None and not value is None:
value = self.value.__class__(value)
return self.valuePasses(value)
def valuePasses(self, value):
"""Returns whether this value passes this filter"""
return self._conditional_cmp[self.op](value, self.value)
def __str__(self):
return '%s %s %s' % (self.field, self.op, self.value)
def __repr__(self):
return "Filter('%s', '%s', %s)" % (self.field, self.op, repr(self.value))
def __eq__(self, o):
return self.field == o.field and self.op == o.op and self.value == o.value
def __ne__(self, other):
return not self.__eq__(other)
def __hash__(self):
return hash(repr(self))
def generator(self, iterable):
"""Generator function that iteratively filters given `items`."""
for item in iterable:
if self(item):
yield item
@classmethod
def filter(cls, filters, iterable):
"""Returns the elements in `iterable` that pass given `filters`"""
if isinstance(filters, Filter):
filters = [filters]
for filter in filters:
iterable = filter.generator(iterable)
return iterable
class Order(object):
"""Represents an Order upon a specific field, and a direction.
Orders are used on queries to define how they operate on objects
Args:
order: an order in string form. This follows the format: [+-]name
where + is ascending, - is descending, and name is the name
of the field to order by.
Note: if no ordering operator is specified, + is default.
Examples::
Order('+name') # ascending order by name
Order('-age') # descending order by age
Order('score') # ascending order by score
"""
order_operators = ['-', '+']
"""Ordering operators: + is ascending, - is descending."""
object_getattr = staticmethod(_object_getattr)
"""Object attribute getter. Can be overridden to match client data model.
See :py:meth:`datastore.query._object_getattr`.
"""
def __init__(self, order):
self.op = '+'
try:
if order[0] in self.order_operators:
self.op = order[0]
order = order[1:]
except IndexError:
raise ValueError('Order input be at least two characters long.')
self.field = order
if self.op not in self.order_operators:
raise ValueError('"%s" is not a valid Order Operator.' % op)
def __str__(self):
return '%s%s' % (self.op, self.field)
def __repr__(self):
return "Order('%s%s')" % (self.op, self.field)
def __eq__(self, other):
return self.field == other.field and self.op == other.op
def __ne__(self, other):
return not self.__eq__(other)
def __hash__(self):
return hash(repr(self))
def isAscending(self):
return self.op == '+'
def isDescending(self):
return not self.isAscending()
def keyfn(self, obj):
"""A key function to be used in pythonic sort operations."""
return self.object_getattr(obj, self.field)
@classmethod
def multipleOrderComparison(cls, orders):
"""Returns a function that will compare two items according to `orders`"""
comparers = [(o.keyfn, 1 if o.isAscending() else -1) for o in orders]
def cmpfn(a, b):
for keyfn, ascOrDesc in comparers:
comparison = cmp(keyfn(a), keyfn(b)) * ascOrDesc
if comparison is not 0:
return comparison
return 0
return cmpfn
@classmethod
def sorted(cls, items, orders):
"""Returns the elements in `items` sorted according to `orders`"""
return sorted(items, cmp=cls.multipleOrderComparison(orders))
class Query(object):
"""A Query describes a set of objects.
Queries are used to retrieve objects and instances matching a set of criteria
from Datastores. Query objects themselves are simply descriptions,
the actual Query implementations are left up to the Datastores.
"""
"""Object attribute getter. Can be overridden to match client data model."""
object_getattr = staticmethod(_object_getattr)
def __init__(self, key=Key('/'), limit=None, offset=0, offset_key=None, object_getattr=None):
""" Initialize a query.
Parameters
key: a key representing the level of this query. For example, a Query with
Key('/MontyPython/Actor:') would query objects in that key path, eg:
Key('/MontyPython/Actor:JohnCleese')
Key('/MontyPython/Actor:EricIdle')
Key('/MontyPython/Actor:GrahamChapman')
It is up to datastores how to implement this namespacing. E.g.,
some datastores may store values in different tables or collections.
limit: an integer representing the maximum number of results to return.
offset: an integer representing a number of results to skip.
object_getattr: a function to extract attribute values from an object. It
is used to satisfy query filters and orders. Defining this function
allows the client to control the data model of the stored values.
The default function attempts to access values as attributes
(__getattr__) or items (__getitem__).
"""
if not isinstance(key, Key):
raise TypeError('key must be of type %s' % Key)
self.key = key
self.limit = int(limit) if limit is not None else None
self.offset = int(offset)
self.offset_key = offset_key
self.filters = []
self.orders = []
if object_getattr:
self.object_getattr = object_getattr
def __str__(self):
"""Returns a string describing this query."""
return repr(self)
def __repr__(self):
"""Returns the representation of this query. Enables eval(repr(.))."""
return 'Query.from_dict(%s)' % self.dict()
def __call__(self, iterable):
"""Naively apply this query on an iterable of objects.
Applying a query applies filters, sorts by appropriate orders, and returns
a limited set.
WARNING: When orders are applied, this function operates on the entire set
of entities directly, not just iterators/generators. That means
the entire result set will be in memory. Datastores with large
objects and large query results should translate the Query and
perform their own optimizations.
"""
cursor = Cursor(self, iterable)
cursor.apply_filter()
cursor.apply_order()
cursor.apply_offset()
cursor.apply_limit()
return cursor
def order(self, order):
"""Adds an Order to this query.
Args:
see :py:class:`Order <datastore.query.Order>` constructor
Returns self for JS-like method chaining::
query.order('+age').order('-home')
"""
order = order if isinstance(order, Order) else Order(order)
# ensure order gets attr values the same way the rest of the query
# does.
order.object_getattr = self.object_getattr
self.orders.append(order)
return self # for chaining
def filter(self, *args):
"""Adds a Filter to this query.
Args:
see :py:class:`Filter <datastore.query.Filter>` constructor
Returns self for JS-like method chaining::
query.filter('age', '>', 18).filter('sex', '=', 'Female')
"""
if len(args) == 1 and isinstance(args[0], Filter):
filter = args[0]
else:
filter = Filter(*args)
# ensure filter gets attr values the same way the rest of the query
# does.
filter.object_getattr = self.object_getattr
self.filters.append(filter)
return self # for chaining
def __cmp__(self, other):
return cmp(self.dict(), other.dict())
def __hash__(self):
return hash(repr(self))
def copy(self):
"""Returns a copy of this query."""
if self.object_getattr is Query.object_getattr:
other = Query(self.key)
else:
other = Query(self.key, object_getattr=self.object_getattr)
other.limit = self.limit
other.offset = self.offset
other.offset_key = self.offset_key
other.filters = self.filters
other.orders = self.orders
return other
def dict(self):
"""Returns a dictionary representing this query."""
d = dict()
d['key'] = str(self.key)
if self.limit is not None:
d['limit'] = self.limit
if self.offset > 0:
d['offset'] = self.offset
if self.offset_key:
d['offset_key'] = str(self.offset_key)
if len(self.filters) > 0:
d['filter'] = [[f.field, f.op, f.value] for f in self.filters]
if len(self.orders) > 0:
d['order'] = [str(o) for o in self.orders]
return d
@classmethod
def from_dict(cls, dictionary):
"""Constructs a query from a dictionary."""
query = cls(Key(dictionary['key']))
for key, value in dictionary.items():
if key == 'order':
for order in value:
query.order(order)
elif key == 'filter':
for filter in value:
if not isinstance(filter, Filter):
filter = Filter(*filter)
query.filter(filter)
elif key in ['limit', 'offset', 'offset_key']:
setattr(query, key, value)
return query
def is_iterable(obj):
return hasattr(obj, '__iter__') or hasattr(obj, '__getitem__')
class Cursor(object):
"""Represents a query result generator."""
__slots__ = ('query', '_iterable', '_iterator', 'skipped', 'returned', )
def __init__(self, query, iterable):
if not isinstance(query, Query):
raise ValueError('Cursor received invalid query: %s' % query)
if not is_iterable(iterable):
raise ValueError('Cursor received invalid iterable: %s' % iterable)
self.query = query
self._iterable = iterable
self._iterator = None
self.returned = 0
self.skipped = 0
def __iter__(self):
"""The cursor itself is the iterator. Note that it cannot be used twice,
and once iteration starts, the cursor cannot be modified.
"""
if self._iterator:
raise RuntimeError('Attempt to iterate over Cursor twice.')
self._iterator = iter(self._iterable)
return self
def next(self):
"""Iterator next. Build up count of returned elements during iteration."""
# if iteration has not begun, begin it.
if not self._iterator:
self.__iter__()
next = self._iterator.next()
if next is not StopIteration:
self._returned_inc(next)
return next
def _skipped_inc(self, item):
"""A function to increment the skipped count."""
self.skipped += 1
def _returned_inc(self, item):
"""A function to increment the returned count."""
self.returned += 1
def _ensure_modification_is_safe(self):
"""Assertions to ensure modification of this Cursor is safe."""
assert self.query, 'Cursor must have a Query.'
assert is_iterable(
self._iterable), 'Cursor must have a resultset iterable.'
assert not self._iterator, 'Cursor must not be modified after iteration.'
def apply_filter(self):
"""Naively apply query filters."""
self._ensure_modification_is_safe()
if len(self.query.filters) > 0:
self._iterable = Filter.filter(self.query.filters, self._iterable)
def apply_order(self):
"""Naively apply query orders."""
self._ensure_modification_is_safe()
if len(self.query.orders) > 0:
self._iterable = Order.sorted(self._iterable, self.query.orders)
# not a generator :(
def apply_offset(self):
"""Naively apply query offset."""
self._ensure_modification_is_safe()
if self.query.offset != 0:
self._iterable = \
offset_gen(self.query.offset,
self._iterable, self._skipped_inc)
# _skipped_inc helps keep count of skipped elements
def apply_limit(self):
"""Naively apply query limit."""
self._ensure_modification_is_safe()
if self.query.limit is not None:
self._iterable = limit_gen(self.query.limit, self._iterable)
| alexandonian/ptutils | ptutils/datastore/query.py | Python | mit | 17,240 |
#!/usr/bin/env python
"""Query and aggregate data from log files using SQL-like syntax"""
import sys
import argparse
import os
import re
import ast
import readline
import atexit
import time
import inspect
from multiprocessing import cpu_count
try:
from collections import OrderedDict
except ImportError:
# python < 2.7 compatability
from compat.OrderedDict import OrderedDict
from ply import yacc
import parser
import parallel
import screen
import sqlfuncs
import logformat
from util import NoTokenError, parse_format_string, Complete, Table, pretty_print
DEBUG = False
log_regex = None
class LogQuery(object):
def __init__(self, data, query):
self.data = data
self.query = query
try:
self.ast = parser.parse(query)
except NoTokenError, e:
print "ERROR: %s" % e.message
print query
return
except SyntaxError:
return
if DEBUG:
# pretty-printer
sq = str(self.ast)
pretty_print(sq)
print sq
print '-'*screen.width
pass
def run(self):
start_time = time.time()
op_data = sqlfuncs.do(self.ast, self.data[:]) # COPY!!!
response = OrderedDict()
for row in op_data:
for key in row.keys():
if not response.has_key(key):
response[key] = []
response[key].append(row[key])
Table(response, start_time).prnt()
class LoGrok(object):
def __init__(self, args, interactive=False, curses=False, chunksize=10000):
if curses:
screen.init_curses()
elif interactive:
screen.init_linebased()
self.interactive = interactive
self.args = args
self.processed_rows = 0
self.oldpct = 0
self.data = []
self.chunksize = chunksize
self.complete = Complete()
self.crunchlogs()
self.interact()
def crunchlogs(self):
global log_regex
if self.args.format is not None:
logformat = self.args.format
else:
logformat = logformat.TYPES[self.args.type]
print
lines = []
for logfile in self.args.logfile:
screen.print_mutable("Reading lines from %s:" % logfile.name)
lines += logfile.readlines()
screen.print_mutable("Reading lines from %s: %d" % (logfile.name, len(lines)))
logfile.close()
screen.print_mutable("", True)
log_regex = re.compile(parse_format_string(logformat))
if self.args.lines:
lines = lines[:self.args.lines]
st = time.time()
self.data = parallel.run(log_match, lines, _print=True)
et = time.time()
print "%d lines crunched in %0.3f seconds" % (len(lines), (et-st))
def interact(self):
if screen.is_curses():
screen.draw_curses_screen(self.data)
self.main_loop()
elif self.interactive:
self.shell()
else:
self.query(self.args.query)
def shell(self):
try:
history = os.path.expanduser('~/.logrok_history')
readline.read_history_file(history)
except IOError:
pass
atexit.register(readline.write_history_file, history)
readline.set_history_length(1000)
readline.parse_and_bind('tab: complete')
readline.set_completer(self.complete.complete)
# XXX This is ugly and needs to be more intelligent. Ideally, the
# completer would use readline.readline() to contextually switch out
# the returned matches
self.complete.addopts(['select', 'from log', 'where', 'between',
'order by', 'group by', 'limit', ] + get_sqlfuncs() + self.data[0].keys())
while True:
q = raw_input("logrok> ").strip()
while not q.endswith(";"):
q += raw_input("> ").strip()
self.query(q)
def query(self, query):
semicolon = query.find(';')
if semicolon != -1:
query = query[:semicolon]
if query in ('quit', 'bye', 'exit'):
sys.exit(0)
if query.startswith('help') or query.startswith('?'):
answer = "Use sql syntax against your log, `from` clauses are ignored.\n"\
"Queries can span multiple lines and _must_ end in a semicolon `;`.\n"\
" Try: `show fields;` to see available field names. Press TAB at the\n"\
" beginning of a new line to see all available completions."
print answer
return
if query in ('show fields', 'show headers'):
print ', '.join(self.data[0].keys())
return
else:
try:
q = LogQuery(self.data, query)
return q.run()
except SyntaxError, e:
return e.message
def main_loop(self):
while 1:
c = screen.getch()
if c == ord('x'): break
if c == ord('q'): screen.prompt("QUERY:", self.query)
def get_sqlfuncs():
return map(
lambda x: x[0],
filter(
lambda x: not x[0].startswith('_') and not x[0] == 'do',
inspect.getmembers(sqlfuncs, inspect.isfunction)
)
)
@parallel.map
def log_match(chunk):
response = []
for line in chunk:
out = {}
m = log_regex.match(line)
for key in log_regex.groupindex:
if logformat.types.has_key(key):
f = logformat.types[key]
else:
f = str
"""
# XXX
# This is a hack a big big hack
# It's here because I discovered that converting the date
# strings into date objects using strptime is a HUGE performance hit!
# -- don't know what to do about that
if f not in (int, str):
f = str
"""
d = m.group(key)
out[key] = f(d)
response.append(out)
return response
def main():
cmd = argparse.ArgumentParser(description="Grok/Query/Aggregate log files. Requires python2 >= 2.7")
typ = cmd.add_mutually_exclusive_group(required=True)
typ.add_argument('-t', '--type', metavar='TYPE', choices=logformat.TYPES, help='{%s} Use built-in log type (default: apache-common)'%', '.join(logformat.TYPES), default='apache-common')
typ.add_argument('-f', '--format', action='store', help='Log format (use apache LogFormat string)')
typ.add_argument('-C', '--config', type=argparse.FileType('r'), help='httpd.conf file in which to find LogFormat string (requires -T)')
cmd.add_argument('-T', '--ctype', help='type-name for LogFormat from specified httpd.conf file (only works with -c)')
cmd.add_argument('-j', '--processes', action='store', type=int, help='Number of processes to fork for log crunching (default: smart)', default=parallel.SMART)
cmd.add_argument('-l', '--lines', action='store', type=int, help='Only process LINES lines of input')
interactive = cmd.add_mutually_exclusive_group(required=False)
interactive.add_argument('-i', '--interactive', action='store_true', help="Use line-based interactive interface")
interactive.add_argument('-c', '--curses', action='store_true', help=argparse.SUPPRESS)
interactive.add_argument('-q', '--query', help="The query to run")
cmd.add_argument('-d', '--debug', action='store_true', help="Turn debugging on (you don't want this)")
cmd.add_argument('logfile', nargs='+', type=argparse.FileType('r'), help="log(s) to parse/query")
args = cmd.parse_args(sys.argv[1:])
if args.config and not args.ctype:
cmd.error("-C/--config option requires -T/--ctype option")
if args.ctype and not args.config:
cmd.error("-T/--ctype only works with -C/--config option")
if args.config and args.ctype:
config = args.config.read()
args.config.close()
m = re.search(r'^logformat[\s]+(.*)[\s]+%s' % args.ctype, config, re.I|re.M)
if m is None:
cmd.error("LogFormat %s not found in %s" % (args.ctype, args.config.name))
format = m.group(1)
if (format.startswith("'") or format.startswith('"')) and (format.endswith("'") or format.endswith('"')):
format = format[1:-1]
args.format = format.replace(r"\'", "'").replace(r'\"', '"')
global DEBUG
DEBUG = args.debug
parser.DEBUG = DEBUG
parallel.DEBUG = DEBUG
sqlfuncs.DEBUG = DEBUG
parser.init()
parallel.numprocs = args.processes
LoGrok(args, interactive=args.interactive, curses=args.curses)
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
parallel.killall()
# TODO -- reset terminal if curses
print
sys.exit(1)
| spuriousdata/logrok | logrok/logrok.py | Python | mit | 8,948 |
from sqlalchemy import Column, String
from FooBaseH import FooBaseH
class FooBaseH2(FooBaseH):
name2 = Column(String)
__mapper_args__ = {
'polymorphic_identity': "2"
}
| aitgon/wopmars | wopmars/tests/resource/model/FooBaseH2.py | Python | mit | 192 |
class Card:
"""
Static class that handles cards. We represent cards as 32-bit integers, so
there is no object instantiation - they are just ints. Most of the bits are
used, and have a specific meaning. See below:
Card:
bitrank suit rank prime
+--------+--------+--------+--------+
|xxxbbbbb|bbbbbbbb|cdhsrrrr|xxpppppp|
+--------+--------+--------+--------+
1) p = prime number of rank (deuce=2,trey=3,four=5,...,ace=41)
2) r = rank of card (deuce=0,trey=1,four=2,five=3,...,ace=12)
3) cdhs = suit of card (bit turned on based on suit of card)
4) b = bit turned on depending on rank of card
5) x = unused
This representation will allow us to do very important things like:
- Make a unique prime prodcut for each hand
- Detect flushes
- Detect straights
and is also quite performant.
"""
# the basics
STR_RANKS = '23456789TJQKA'
INT_RANKS = list(range(13))
PRIMES = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41]
# converstion from string => int
CHAR_RANK_TO_INT_RANK = dict(zip(list(STR_RANKS), INT_RANKS))
CHAR_SUIT_TO_INT_SUIT = {
's': 1, # spades
'h': 2, # hearts
'd': 4, # diamonds
'c': 8, # clubs
}
INT_SUIT_TO_CHAR_SUIT = 'xshxdxxxc'
# for pretty printing
PRETTY_SUITS = {
1: u"\u2660", # spades
2: u"\u2764", # hearts
4: u"\u2666", # diamonds
8: u"\u2663" # clubs
}
@staticmethod
def new(string):
"""
Converts Card string to binary integer representation of card, inspired by:
http://www.suffecool.net/poker/evaluator.html
"""
rank_char = string[0]
suit_char = string[1]
rank_int = Card.CHAR_RANK_TO_INT_RANK[rank_char]
suit_int = Card.CHAR_SUIT_TO_INT_SUIT[suit_char]
rank_prime = Card.PRIMES[rank_int]
bitrank = 1 << rank_int << 16
suit = suit_int << 12
rank = rank_int << 8
return bitrank | suit | rank | rank_prime
@staticmethod
def int_to_str(card_int):
rank_int = Card.get_rank_int(card_int)
suit_int = Card.get_suit_int(card_int)
return Card.STR_RANKS[rank_int] + Card.INT_SUIT_TO_CHAR_SUIT[suit_int]
@staticmethod
def get_rank_int(card_int):
return (card_int >> 8) & 0xF
@staticmethod
def get_suit_int(card_int):
return (card_int >> 12) & 0xF
@staticmethod
def get_bitrank_int(card_int):
return (card_int >> 16) & 0x1FFF
@staticmethod
def get_prime(card_int):
return card_int & 0x3F
@staticmethod
def hand_to_binary(card_strs):
"""
Expects a list of cards as strings and returns a list
of integers of same length corresponding to those strings.
"""
bhand = []
for c in card_strs:
bhand.append(Card.new(c))
return bhand
@staticmethod
def prime_product_from_hand(card_ints):
"""
Expects a list of cards in integer form.
"""
product = 1
for c in card_ints:
product *= (c & 0xFF)
return product
@staticmethod
def prime_product_from_rankbits(rankbits):
"""
Returns the prime product using the bitrank (b)
bits of the hand. Each 1 in the sequence is converted
to the correct prime and multiplied in.
Params:
rankbits = a single 32-bit (only 13-bits set) integer representing
the ranks of 5 _different_ ranked cards
(5 of 13 bits are set)
Primarily used for evaulating flushes and straights,
two occasions where we know the ranks are *ALL* different.
Assumes that the input is in form (set bits):
rankbits
+--------+--------+
|xxxbbbbb|bbbbbbbb|
+--------+--------+
"""
product = 1
for i in Card.INT_RANKS:
# if the ith bit is set
if rankbits & (1 << i):
product *= Card.PRIMES[i]
return product
@staticmethod
def int_to_binary(card_int):
"""
For debugging purposes. Displays the binary number as a
human readable string in groups of four digits.
"""
bstr = bin(card_int)[2:][::-1] # chop off the 0b and THEN reverse string
output = list("".join(["0000" + "\t"] * 7) + "0000")
for i in range(len(bstr)):
output[i + int(i//4)] = bstr[i]
# output the string to console
output.reverse()
return "".join(output)
@staticmethod
def int_to_pretty_str(card_int):
"""
Returns a single card string
"""
# suit and rank
suit_int = Card.get_suit_int(card_int)
rank_int = Card.get_rank_int(card_int)
suit = Card.PRETTY_SUITS[suit_int]
rank = Card.STR_RANKS[rank_int]
return str(rank) + " of " + str(suit)
| RIP95/kurisu-bot | addons/deuces/card.py | Python | mit | 5,195 |
import json
import os
from commonfunctions import commonfunctions as cf
dir = cf.working_directory
transcripts = []
for x in os.listdir(dir):
with open(os.path.join(dir, x)) as f:
transcripts.append(json.load(f))
with open('worldcitiesout.json', 'r') as f:
city_dicts = json.load(f)
city_dicts = [x for x in city_dicts if x['Country'] == 'us']
results = []
for transcript in transcripts:
description = transcript['description']
date = transcript['date']
for text in transcript['text_by_speakers']:
for city_dict in city_dicts:
index = text['text'].lower().find(" " + city_dict['City'] + " ")
if index > 0:
if index < 90:
from_index = 0
else:
from_index = index - 100
if len(text['text']) < index + 90:
to_index = len(text['text'])
else:
to_index = index + 100
result = ({'speaker': text['speaker'],
'city': city_dict,
'debate': {'description': description, 'date': date,
'context': text['text'][from_index:to_index]}})
print result
results.append(result)
with open('city-mentions.json', 'w') as f:
json.dump(results, f) | keelanfh/electionary | analysis/city-mentions.py | Python | mit | 1,375 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
import functools
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union
import warnings
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.mgmt.core.exceptions import ARMErrorFormat
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._api_tag_description_operations import build_create_or_update_request, build_delete_request, build_get_entity_tag_request, build_get_request, build_list_by_service_request
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class ApiTagDescriptionOperations:
"""ApiTagDescriptionOperations async operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~api_management_client.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer) -> None:
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
@distributed_trace
def list_by_service(
self,
resource_group_name: str,
service_name: str,
api_id: str,
filter: Optional[str] = None,
top: Optional[int] = None,
skip: Optional[int] = None,
**kwargs: Any
) -> AsyncIterable["_models.TagDescriptionCollection"]:
"""Lists all Tags descriptions in scope of API. Model similar to swagger - tagDescription is
defined on API level but tag may be assigned to the Operations.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param service_name: The name of the API Management service.
:type service_name: str
:param api_id: API revision identifier. Must be unique in the current API Management service
instance. Non-current revision has ;rev=n as a suffix where n is the revision number.
:type api_id: str
:param filter: | Field | Usage | Supported operators | Supported
functions |</br>|-------------|-------------|-------------|-------------|</br>| displayName
| filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>| name |
filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |</br>.
:type filter: str
:param top: Number of records to return.
:type top: int
:param skip: Number of records to skip.
:type skip: int
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either TagDescriptionCollection or the result of
cls(response)
:rtype:
~azure.core.async_paging.AsyncItemPaged[~api_management_client.models.TagDescriptionCollection]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.TagDescriptionCollection"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_service_request(
resource_group_name=resource_group_name,
service_name=service_name,
api_id=api_id,
subscription_id=self._config.subscription_id,
filter=filter,
top=top,
skip=skip,
template_url=self.list_by_service.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
request = build_list_by_service_request(
resource_group_name=resource_group_name,
service_name=service_name,
api_id=api_id,
subscription_id=self._config.subscription_id,
filter=filter,
top=top,
skip=skip,
template_url=next_link,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("TagDescriptionCollection", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(
get_next, extract_data
)
list_by_service.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/apis/{apiId}/tagDescriptions'} # type: ignore
@distributed_trace_async
async def get_entity_tag(
self,
resource_group_name: str,
service_name: str,
api_id: str,
tag_description_id: str,
**kwargs: Any
) -> bool:
"""Gets the entity state version of the tag specified by its identifier.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param service_name: The name of the API Management service.
:type service_name: str
:param api_id: API revision identifier. Must be unique in the current API Management service
instance. Non-current revision has ;rev=n as a suffix where n is the revision number.
:type api_id: str
:param tag_description_id: Tag description identifier. Used when creating tagDescription for
API/Tag association. Based on API and Tag names.
:type tag_description_id: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: bool, or the result of cls(response)
:rtype: bool
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType[None]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_get_entity_tag_request(
resource_group_name=resource_group_name,
service_name=service_name,
api_id=api_id,
tag_description_id=tag_description_id,
subscription_id=self._config.subscription_id,
template_url=self.get_entity_tag.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
response_headers = {}
response_headers['ETag']=self._deserialize('str', response.headers.get('ETag'))
if cls:
return cls(pipeline_response, None, response_headers)
return 200 <= response.status_code <= 299
get_entity_tag.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/apis/{apiId}/tagDescriptions/{tagDescriptionId}'} # type: ignore
@distributed_trace_async
async def get(
self,
resource_group_name: str,
service_name: str,
api_id: str,
tag_description_id: str,
**kwargs: Any
) -> "_models.TagDescriptionContract":
"""Get Tag description in scope of API.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param service_name: The name of the API Management service.
:type service_name: str
:param api_id: API revision identifier. Must be unique in the current API Management service
instance. Non-current revision has ;rev=n as a suffix where n is the revision number.
:type api_id: str
:param tag_description_id: Tag description identifier. Used when creating tagDescription for
API/Tag association. Based on API and Tag names.
:type tag_description_id: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: TagDescriptionContract, or the result of cls(response)
:rtype: ~api_management_client.models.TagDescriptionContract
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.TagDescriptionContract"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_get_request(
resource_group_name=resource_group_name,
service_name=service_name,
api_id=api_id,
tag_description_id=tag_description_id,
subscription_id=self._config.subscription_id,
template_url=self.get.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
response_headers = {}
response_headers['ETag']=self._deserialize('str', response.headers.get('ETag'))
deserialized = self._deserialize('TagDescriptionContract', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, response_headers)
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/apis/{apiId}/tagDescriptions/{tagDescriptionId}'} # type: ignore
@distributed_trace_async
async def create_or_update(
self,
resource_group_name: str,
service_name: str,
api_id: str,
tag_description_id: str,
parameters: "_models.TagDescriptionCreateParameters",
if_match: Optional[str] = None,
**kwargs: Any
) -> "_models.TagDescriptionContract":
"""Create/Update tag description in scope of the Api.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param service_name: The name of the API Management service.
:type service_name: str
:param api_id: API revision identifier. Must be unique in the current API Management service
instance. Non-current revision has ;rev=n as a suffix where n is the revision number.
:type api_id: str
:param tag_description_id: Tag description identifier. Used when creating tagDescription for
API/Tag association. Based on API and Tag names.
:type tag_description_id: str
:param parameters: Create parameters.
:type parameters: ~api_management_client.models.TagDescriptionCreateParameters
:param if_match: ETag of the Entity. Not required when creating an entity, but required when
updating an entity.
:type if_match: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: TagDescriptionContract, or the result of cls(response)
:rtype: ~api_management_client.models.TagDescriptionContract
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.TagDescriptionContract"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
content_type = kwargs.pop('content_type', "application/json") # type: Optional[str]
_json = self._serialize.body(parameters, 'TagDescriptionCreateParameters')
request = build_create_or_update_request(
resource_group_name=resource_group_name,
service_name=service_name,
api_id=api_id,
tag_description_id=tag_description_id,
subscription_id=self._config.subscription_id,
content_type=content_type,
json=_json,
if_match=if_match,
template_url=self.create_or_update.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
response_headers = {}
if response.status_code == 200:
response_headers['ETag']=self._deserialize('str', response.headers.get('ETag'))
deserialized = self._deserialize('TagDescriptionContract', pipeline_response)
if response.status_code == 201:
response_headers['ETag']=self._deserialize('str', response.headers.get('ETag'))
deserialized = self._deserialize('TagDescriptionContract', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, response_headers)
return deserialized
create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/apis/{apiId}/tagDescriptions/{tagDescriptionId}'} # type: ignore
@distributed_trace_async
async def delete(
self,
resource_group_name: str,
service_name: str,
api_id: str,
tag_description_id: str,
if_match: str,
**kwargs: Any
) -> None:
"""Delete tag description for the Api.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param service_name: The name of the API Management service.
:type service_name: str
:param api_id: API revision identifier. Must be unique in the current API Management service
instance. Non-current revision has ;rev=n as a suffix where n is the revision number.
:type api_id: str
:param tag_description_id: Tag description identifier. Used when creating tagDescription for
API/Tag association. Based on API and Tag names.
:type tag_description_id: str
:param if_match: ETag of the Entity. ETag should match the current entity state from the header
response of the GET request or it should be * for unconditional update.
:type if_match: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: None, or the result of cls(response)
:rtype: None
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType[None]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_delete_request(
resource_group_name=resource_group_name,
service_name=service_name,
api_id=api_id,
tag_description_id=tag_description_id,
subscription_id=self._config.subscription_id,
if_match=if_match,
template_url=self.delete.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/apis/{apiId}/tagDescriptions/{tagDescriptionId}'} # type: ignore
| Azure/azure-sdk-for-python | sdk/apimanagement/azure-mgmt-apimanagement/azure/mgmt/apimanagement/aio/operations/_api_tag_description_operations.py | Python | mit | 19,783 |
# Copyright 2015 Google Inc. 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.
# ==============================================================================
"""Tests for tensorflow.ops.math_ops.matrix_solve."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
def BatchMatMul(a, b):
# A numpy implementation of tf.batch_matmul().
if a.ndim < 3:
return np.dot(a, b)
# Get the number of matrices.
n = np.prod(a.shape[:-2])
assert n == np.prod(b.shape[:-2])
a_flat = np.reshape(a, tuple([n]) + a.shape[-2:])
b_flat = np.reshape(b, tuple([n]) + b.shape[-2:])
c_flat_shape = [n, a.shape[-2], b.shape[-1]]
c_flat = np.empty(c_flat_shape)
for i in range(n):
c_flat[i, :, :] = np.dot(a_flat[i, :, :], b_flat[i, :, :])
return np.reshape(c_flat, a.shape[:-1] + b_flat.shape[-1:])
def BatchRegularizedLeastSquares(matrices, rhss, l2_regularization=0.0):
# A numpy implementation of regularized least squares solver using
# the normal equations.
matrix_dims = matrices.shape
matrices_transposed = np.swapaxes(matrices, -2, -1)
rows = matrix_dims[-2]
cols = matrix_dims[-1]
if rows >= cols:
preconditioner = l2_regularization * np.identity(cols)
gramian = BatchMatMul(matrices_transposed, matrices) + preconditioner
inverse = np.linalg.inv(gramian)
left_pseudo_inverse = BatchMatMul(inverse, matrices_transposed)
return BatchMatMul(left_pseudo_inverse, rhss)
else:
preconditioner = l2_regularization * np.identity(rows)
gramian = BatchMatMul(matrices, matrices_transposed) + preconditioner
inverse = np.linalg.inv(gramian)
right_pseudo_inverse = BatchMatMul(matrices_transposed, inverse)
return BatchMatMul(right_pseudo_inverse, rhss)
class MatrixSolveLsOpTest(tf.test.TestCase):
def _verifySolve(self, x, y):
for np_type in [np.float32, np.float64]:
a = x.astype(np_type)
b = y.astype(np_type)
np_ans, _, _, _ = np.linalg.lstsq(a, b)
for fast in [True, False]:
with self.test_session():
tf_ans = tf.matrix_solve_ls(a, b, fast=fast).eval()
self.assertEqual(np_ans.shape, tf_ans.shape)
# Check residual norm.
tf_r = b - BatchMatMul(a, tf_ans)
tf_r_norm = np.sum(tf_r * tf_r)
np_r = b - BatchMatMul(a, np_ans)
np_r_norm = np.sum(np_r * np_r)
self.assertAllClose(np_r_norm, tf_r_norm)
# Check solution.
if fast or a.shape[0] >= a.shape[1]:
# We skip this test for the underdetermined case when using the
# slow path, because Eigen does not return a minimum norm solution.
# TODO(rmlarsen): Enable this check for all paths if/when we fix
# Eigen's solver.
self.assertAllClose(np_ans, tf_ans, atol=1e-5, rtol=1e-5)
def _verifySolveBatch(self, x, y):
# Since numpy.linalg.lsqr does not support batch solves, as opposed
# to numpy.linalg.solve, we just perform this test for a fixed batch size
# of 2x3.
for np_type in [np.float32, np.float64]:
a = np.tile(x.astype(np_type), [2, 3, 1, 1])
b = np.tile(y.astype(np_type), [2, 3, 1, 1])
np_ans = np.empty([2, 3, a.shape[-1], b.shape[-1]])
for dim1 in range(2):
for dim2 in range(3):
np_ans[dim1, dim2, :, :], _, _, _ = np.linalg.lstsq(
a[dim1, dim2, :, :], b[dim1, dim2, :, :])
for fast in [True, False]:
with self.test_session():
tf_ans = tf.batch_matrix_solve_ls(a, b, fast=fast).eval()
self.assertEqual(np_ans.shape, tf_ans.shape)
# Check residual norm.
tf_r = b - BatchMatMul(a, tf_ans)
tf_r_norm = np.sum(tf_r * tf_r)
np_r = b - BatchMatMul(a, np_ans)
np_r_norm = np.sum(np_r * np_r)
self.assertAllClose(np_r_norm, tf_r_norm)
# Check solution.
if fast or a.shape[-2] >= a.shape[-1]:
# We skip this test for the underdetermined case when using the
# slow path, because Eigen does not return a minimum norm solution.
# TODO(rmlarsen): Enable this check for all paths if/when we fix
# Eigen's solver.
self.assertAllClose(np_ans, tf_ans, atol=1e-5, rtol=1e-5)
def _verifyRegularized(self, x, y, l2_regularizer):
for np_type in [np.float32, np.float64]:
# Test with a single matrix.
a = x.astype(np_type)
b = y.astype(np_type)
np_ans = BatchRegularizedLeastSquares(a, b, l2_regularizer)
with self.test_session():
tf_ans = tf.matrix_solve_ls(a,
b,
l2_regularizer=l2_regularizer,
fast=True).eval()
self.assertAllClose(np_ans, tf_ans, atol=1e-5, rtol=1e-5)
# Test with a 2x3 batch of matrices.
a = np.tile(x.astype(np_type), [2, 3, 1, 1])
b = np.tile(y.astype(np_type), [2, 3, 1, 1])
np_ans = BatchRegularizedLeastSquares(a, b, l2_regularizer)
with self.test_session():
tf_ans = tf.batch_matrix_solve_ls(a,
b,
l2_regularizer=l2_regularizer,
fast=True).eval()
self.assertAllClose(np_ans, tf_ans, atol=1e-5, rtol=1e-5)
def testSquare(self):
# 2x2 matrices, 2x3 right-hand sides.
matrix = np.array([[1., 2.], [3., 4.]])
rhs = np.array([[1., 0., 1.], [0., 1., 1.]])
self._verifySolve(matrix, rhs)
self._verifySolveBatch(matrix, rhs)
self._verifyRegularized(matrix, rhs, l2_regularizer=0.1)
def testOverdetermined(self):
# 2x2 matrices, 2x3 right-hand sides.
matrix = np.array([[1., 2.], [3., 4.], [5., 6.]])
rhs = np.array([[1., 0., 1.], [0., 1., 1.], [1., 1., 0.]])
self._verifySolve(matrix, rhs)
self._verifySolveBatch(matrix, rhs)
self._verifyRegularized(matrix, rhs, l2_regularizer=0.1)
def testUnderdetermined(self):
# 2x2 matrices, 2x3 right-hand sides.
matrix = np.array([[1., 2., 3], [4., 5., 6.]])
rhs = np.array([[1., 0., 1.], [0., 1., 1.]])
self._verifySolve(matrix, rhs)
self._verifySolveBatch(matrix, rhs)
self._verifyRegularized(matrix, rhs, l2_regularizer=0.1)
def testWrongDimensions(self):
# The matrix and right-hand sides should have the same number of rows.
with self.test_session():
matrix = tf.constant([[1., 0.], [0., 1.]])
rhs = tf.constant([[1., 0.]])
with self.assertRaises(ValueError):
tf.matrix_solve_ls(matrix, rhs)
with self.assertRaises(ValueError):
tf.batch_matrix_solve_ls(matrix, rhs)
def testEmpty(self):
full = np.array([[1., 2.], [3., 4.], [5., 6.]])
empty0 = np.empty([3, 0])
empty1 = np.empty([0, 2])
for fast in [True, False]:
with self.test_session():
tf_ans = tf.matrix_solve_ls(empty0, empty0, fast=fast).eval()
self.assertEqual(tf_ans.shape, (0, 0))
tf_ans = tf.matrix_solve_ls(empty0, full, fast=fast).eval()
self.assertEqual(tf_ans.shape, (0, 2))
tf_ans = tf.matrix_solve_ls(full, empty0, fast=fast).eval()
self.assertEqual(tf_ans.shape, (2, 0))
tf_ans = tf.matrix_solve_ls(empty1, empty1, fast=fast).eval()
self.assertEqual(tf_ans.shape, (2, 2))
def testBatchResultSize(self):
# 3x3x3 matrices, 3x3x1 right-hand sides.
matrix = np.array([1., 2., 3., 4., 5., 6., 7., 8., 9.] * 3).reshape(3, 3, 3)
rhs = np.array([1., 2., 3.] * 3).reshape(3, 3, 1)
answer = tf.batch_matrix_solve(matrix, rhs)
ls_answer = tf.batch_matrix_solve_ls(matrix, rhs)
self.assertEqual(ls_answer.get_shape(), [3, 3, 1])
self.assertEqual(answer.get_shape(), [3, 3, 1])
if __name__ == "__main__":
tf.test.main()
| DailyActie/Surrogate-Model | 01-codes/tensorflow-master/tensorflow/python/kernel_tests/matrix_solve_ls_op_test.py | Python | mit | 9,206 |
__all__ = [
'RedisError',
'ProtocolError',
'ReplyError',
'MaxClientsError',
'AuthError',
'PipelineError',
'MultiExecError',
'WatchVariableError',
'ChannelClosedError',
'ConnectionClosedError',
'ConnectionForcedCloseError',
'PoolClosedError',
'MasterNotFoundError',
'SlaveNotFoundError',
'ReadOnlyError',
]
class RedisError(Exception):
"""Base exception class for aioredis exceptions."""
class ProtocolError(RedisError):
"""Raised when protocol error occurs."""
class ReplyError(RedisError):
"""Raised for redis error replies (-ERR)."""
MATCH_REPLY = None
def __new__(cls, msg, *args):
for klass in cls.__subclasses__():
if msg and klass.MATCH_REPLY and msg.startswith(klass.MATCH_REPLY):
return klass(msg, *args)
return super().__new__(cls, msg, *args)
class MaxClientsError(ReplyError):
"""Raised for redis server when the maximum number of client has been
reached."""
MATCH_REPLY = "ERR max number of clients reached"
class AuthError(ReplyError):
"""Raised when authentication errors occurs."""
MATCH_REPLY = ("NOAUTH ", "ERR invalid password")
class PipelineError(RedisError):
"""Raised if command within pipeline raised error."""
def __init__(self, errors):
super().__init__('{} errors:'.format(self.__class__.__name__), errors)
class MultiExecError(PipelineError):
"""Raised if command within MULTI/EXEC block caused error."""
class WatchVariableError(MultiExecError):
"""Raised if watched variable changed (EXEC returns None)."""
class ChannelClosedError(RedisError):
"""Raised when Pub/Sub channel is unsubscribed and messages queue is empty.
"""
class ReadOnlyError(RedisError):
"""Raised from slave when read-only mode is enabled"""
class MasterNotFoundError(RedisError):
"""Raised for sentinel master not found error."""
class SlaveNotFoundError(RedisError):
"""Raised for sentinel slave not found error."""
class MasterReplyError(RedisError):
"""Raised by sentinel client for master error replies."""
class SlaveReplyError(RedisError):
"""Raised by sentinel client for slave error replies."""
class ConnectionClosedError(RedisError):
"""Raised if connection to server was closed."""
class ConnectionForcedCloseError(ConnectionClosedError):
"""Raised if connection was closed with .close() method."""
class PoolClosedError(RedisError):
"""Raised if pool is closed."""
class RedisClusterError(RedisError):
"""Cluster exception class for aioredis exceptions."""
| ymap/aioredis | aioredis/errors.py | Python | mit | 2,627 |
"""Read in lightcurve files."""
import logging
import numpy as np
import astropy.io.ascii as at
def read_single_aperture(filename):
"""Read in one of AMC's K2 light curves,
inputs
------
filename: string
should look like EPIC_205030103_xy_ap1.5_fixbox_cleaned.dat
outputs
-------
time, flux, unc_flux, x_pos, y_pos, qual_flux: arrays
aperture: float
"""
# Read in the file
lc = at.read(filename, delimiter=' ',data_start=1)
split_filename = filename.split("/")[-1].split('_')
logging.debug(split_filename)
if split_filename[0]=="EPIC":
epicID = split_filename[1]
else:
epicID = split_filename[0]
aperture = split_filename[3]
if aperture.startswith("ap"):
aperture = aperture[2:]
if aperture.endswith(".dat"):
aperture = aperture[:-4]
# Extract the useful columns
time = lc["Dates"]
flux = lc["Flux"]
try:
unc_flux = lc["Uncert{}".format(aperture)]
except:
unc_flux = np.ones_like(flux)
x_pos = lc["Xpos"]
y_pos = lc["Ypos"]
try:
qual_flux = lc["Quality"]
except:
qual_flux = np.ones_like(flux)
aperture = float(aperture)
# Return the columns
return time, flux, unc_flux, x_pos, y_pos, qual_flux, aperture
def read_double_aperture(filename):
"""Read in one of AMC's K2 lc files with 2 aperture extractions.
inputs
------
filename: string
should look like EPIC_205030103_xy_ap#.#_#.#_fixbox.dat
outputs
-------
time: array
flux, unc_flux: arrays, shape=(2, n_datapoints)
A flux and uncertainty array for each aperture in the file
x_pos, y_pos, qual_flux: arrays
apertures: array, length=2
The apertures contained in the file
"""
# Read in the file
lc = at.read(filename, delimiter=' ',data_start=1)
split_filename = filename.split("/")[-1].split('_')
logging.debug(split_filename)
epicID = split_filename[1]
# Extract the useful columns
time = lc["Dates"]
fluxes = np.array([lc["Flux5"], lc["Flux3"]])
unc_fluxes = np.array([lc["Uncert5"], lc["Uncert3"]])
apertures = np.array([5.,3.])
x_pos = lc["Xpos"]
y_pos = lc["Ypos"]
qual_flux = lc["Quality"]
# Return the columns
return time, fluxes, unc_fluxes, x_pos, y_pos, qual_flux, apertures
def read_list(file_list):
"""Read in a list of lightcurve filenames."""
pass
| stephtdouglas/k2spin | k2io.py | Python | mit | 2,475 |
from __future__ import print_function
import numpy
import time
import traceback
import colorsys
import random
class EffectLayer(object):
"""Abstract base class for one layer of an LED light effect. Layers operate on a shared framebuffer,
adding their own contribution to the buffer and possibly blending or overlaying with data from
prior layers.
The 'frame' passed to each render() function is an array of LEDs. Each LED is a 3-element list
with the red, green, and blue components each as floating point values with a normalized
brightness range of [0, 1]. If a component is beyond this range, it will be clamped during
conversion to the hardware color format.
"""
transitionFadeTime = 1.0
maximum_errors = 5
def render(self, params, frame):
raise NotImplementedError("Implement render() in your EffectLayer subclass")
def safely_render(self, params, frame):
if not hasattr(self, 'error_count'):
self.error_count = 0
try:
if self.error_count < EffectLayer.maximum_errors:
self.render(params, frame)
except Exception as err:
error_log = open('error.log','a')
error_log.write(time.asctime(time.gmtime()) + " UTC" + " : ")
traceback.print_exc(file=error_log)
print("ERROR:", err, "in", self)
self.error_count += 1
if self.error_count >= EffectLayer.maximum_errors:
print("Disabling", self, "for throwing too many errors")
class HeadsetResponsiveEffectLayer(EffectLayer):
"""A layer effect that responds to the MindWave headset in some way.
Two major differences from EffectLayer:
1) Constructor expects four paramters:
-- respond_to: the name of a field in EEGInfo (threads.HeadsetThread.EEGInfo).
Currently this means either 'attention' or 'meditation'
-- smooth_response_over_n_secs: to avoid rapid fluctuations from headset
noise, averages the response metric over this many seconds
-- minimum_response_level: if the response level is below this, the layer isn't rendered
-- inverse: If this is true, the layer will respond to (1-response_level)
instead of response_level
2) Subclasses now only implement the render_responsive() function, which
is the same as EffectLayer's render() function but has one extra
parameter, response_level, which is the current EEG value of the indicated
field (assumed to be on a 0-1 scale, or None if no value has been read yet).
"""
def __init__(self, respond_to, smooth_response_over_n_secs=0, minimum_response_level=None, inverse=False):
# Name of the eeg field to influence this effect
if respond_to not in ('attention', 'meditation'):
raise Exception('respond_to was "%s" -- should be "attention" or "meditation"'
% respond_to)
self.respond_to = respond_to
self.smooth_response_over_n_secs = smooth_response_over_n_secs
self.measurements = []
self.timestamps = []
self.last_eeg = None
self.last_response_level = None
self.minimum_response_level = minimum_response_level
# We want to smoothly transition between values instead of jumping
# (as the headset typically gives one reading per second)
self.fading_to = None
self.inverse = inverse
def start_fade(self, new_level):
if not self.last_response_level:
self.last_response_level = new_level
else:
self.fading_to = new_level
def end_fade(self):
self.last_response_level = self.fading_to
self.fading_to = None
def calculate_response_level(self, params, use_eeg2=False):
now = time.time()
response_level = None
# Update our measurements, if we have a new one
eeg = params.eeg2 if use_eeg2 else params.eeg1
if eeg and eeg != self.last_eeg and eeg.on:
if self.fading_to:
self.end_fade()
# Prepend newest measurement and timestamp
self.measurements[:0] = [getattr(eeg, self.respond_to)]
self.timestamps[:0] = [now]
self.last_eeg = eeg
# Compute the parameter to send to our rendering function
N = len(self.measurements)
idx = 0
while idx < N:
dt = self.timestamps[0] - self.timestamps[idx]
if dt >= self.smooth_response_over_n_secs:
self.measurements = self.measurements[:(idx + 1)]
self.timestamps = self.timestamps[:(idx + 1)]
break
idx += 1
self.start_fade(sum(self.measurements) * 1.0 / len(self.measurements))
response_level = self.last_response_level
elif self.fading_to:
# We assume one reading per second, so a one-second fade
fade_progress = now - self.timestamps[0]
if fade_progress >= 1:
self.end_fade()
response_level = self.last_response_level
else:
response_level = (
fade_progress * self.fading_to +
(1 - fade_progress) * self.last_response_level)
if response_level and self.inverse:
response_level = 1 - response_level
return response_level
def render(self, params, frame):
response_level = self.calculate_response_level(params)
if self.minimum_response_level == None or response_level >= self.minimum_response_level:
self.render_responsive(params, frame, response_level)
def render_responsive(self, params, frame, response_level):
raise NotImplementedError(
"Implement render_responsive() in your HeadsetResponsiveEffectLayer subclass")
########################################################
# Simple EffectLayer implementations and examples
########################################################
class ColorLayer(EffectLayer):
"""Simplest layer, draws a static RGB color"""
def __init__(self, color):
self.color = color
def render(self, params, frame):
frame[:] += self.color
class RGBLayer(EffectLayer):
"""Simplest layer, draws a static RGB color cube."""
def render(self, params, frame):
length = len(frame)
step_size = 1.0 / length
hue = 0.0
for pixel in xrange(0, length):
frame[pixel] = colorsys.hsv_to_rgb(hue, 1, 1)
hue += step_size
class MultiplierLayer(EffectLayer):
""" Renders two layers in temporary frames, then adds the product of those frames
to the frame passed into its render method
"""
def __init__(self, layer1, layer2):
self.layer1 = layer1
self.layer2 = layer2
def render(self, params, frame):
temp1 = numpy.zeros(frame.shape)
temp2 = numpy.zeros(frame.shape)
self.layer1.render(params, temp1)
self.layer2.render(params, temp2)
numpy.multiply(temp1, temp2, temp1)
numpy.add(frame, temp1, frame)
class BlinkyLayer(EffectLayer):
"""Test our timing accuracy: Just blink everything on and off every other frame."""
on = False
def render(self, params, frame):
self.on = not self.on
frame[:] += self.on
class ColorBlinkyLayer(EffectLayer):
on = False
def render(self, params, frame):
self.on = not self.on
color = numpy.array(colorsys.hsv_to_rgb(random.random(),1,1))
if self.on:
frame[:] += color
class SnowstormLayer(EffectLayer):
transitionFadeTime = 1.0
def render(self, params, frame):
numpy.add(frame, numpy.random.rand(params.num_pixels, 1), frame)
class TechnicolorSnowstormLayer(EffectLayer):
transitionFadeTime = 1.5
def render(self, params, frame):
numpy.add(frame, numpy.random.rand(params.num_pixels, 3), frame)
class WhiteOutLayer(EffectLayer):
""" Sets everything to white """
transitionFadeTime = 0.5
def render(self, params, frame):
frame += numpy.ones(frame.shape)
class GammaLayer(EffectLayer):
"""Apply a gamma correction to the brightness, to adjust for the eye's nonlinear sensitivity."""
def __init__(self, gamma):
# Build a lookup table
self.lutX = numpy.arange(0, 1, 0.01)
self.lutY = numpy.power(self.lutX, gamma)
def render(self, params, frame):
frame[:] = numpy.interp(frame.reshape(-1), self.lutX, self.lutY).reshape(frame.shape)
######################################################################
# Simple HeadsetResponsiveEffectLayer implementations and examples
######################################################################
class ResponsiveGreenHighRedLow(HeadsetResponsiveEffectLayer):
"""Colors everything green if the response metric is high, red if low.
Interpolates in between.
"""
def __init__(self, respond_to='attention', smooth_response_over_n_secs=3):
super(ResponsiveGreenHighRedLow,self).__init__(
respond_to, smooth_response_over_n_secs=smooth_response_over_n_secs)
def render_responsive(self, params, frame, response_level):
if response_level is None:
# No signal (blue)
frame[:,2] += 1
else:
frame[:,0] += 1 - response_level
frame[:,1] += response_level
class BrainStaticLayer(HeadsetResponsiveEffectLayer):
def __init__(self, minFactor = 0.3, respond_to='meditation', smooth_response_over_n_secs=0):
super(BrainStaticLayer,self).__init__(respond_to, smooth_response_over_n_secs)
self.minFactor = minFactor
def render_responsive(self, params, frame, response_level):
r = 1-response_level if response_level else 1
numpy.multiply(frame, 1-numpy.random.rand(params.num_pixels, 1)*r*self.minFactor, frame)
| chillpop/RELAX-HARDER | effects/base.py | Python | mit | 10,042 |
import detectlanguage
def detect(data):
result = detectlanguage.client.post('detect', { 'q': data })
return result['data']['detections']
def simple_detect(data):
result = detect(data)
return result[0]['language']
def user_status():
return detectlanguage.client.get('user/status')
def languages():
return detectlanguage.client.get('languages')
| detectlanguage/detectlanguage-python | detectlanguage/api.py | Python | mit | 353 |
def solution(s):
i = 0
j = len(s) - 1
while i < j:
if s[i] == s[j]:
i += 1
j -= 1
else:
t = s[i + 1:j + 1]
if t == t[::-1]:
return i
else:
return j
return -1
testCount = int(input())
for testId in range(testCount):
s = input().strip()
i = solution(s)
print(i)
| lilsweetcaligula/Online-Judges | hackerrank/algorithms/strings/easy/palindrome_index/py/solution.py | Python | mit | 414 |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "PhotoLoader.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| SerSamgy/PhotoLoader | manage.py | Python | mit | 254 |
""" Converter using Pygments.
Registers Pygments for all lexer file types. Should
be registered first to allow overriding other converters
for specific extensions (markdown, etc). """
import codecs
from pygments import highlight
from pygments.formatters import HtmlFormatter
from pygments.lexers import get_lexer_for_filename
class PygmentsConverter:
def __init__(self, config):
self.config = config
config.converter(self.handles, self.convert)
def convert(self, source, **context):
""" Converts the source file and saves to the destination """
with codecs.open(source, encoding='utf-8') as src:
code = src.read()
theme = 'default'
lexer = get_lexer_for_filename(source)
formatter = HtmlFormatter(linenos=False, cssclass='syntax')
content = highlight(code, lexer, formatter)
return self.config.render_template(theme, content, **context)
def handles(self, source):
try:
return get_lexer_for_filename(source) is not None
except:
return False
| kevinbeaty/mvw | mvw/converters/pygmentsconvert.py | Python | mit | 1,084 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('postcode_api', '0010_auto_20150601_1513'),
]
operations = [
migrations.AlterIndexTogether(
name='address',
index_together=set([('postcode_index', 'uprn')]),
),
]
| ministryofjustice/postcodeinfo | postcodeinfo/apps/postcode_api/migrations/0011_auto_20150702_1812.py | Python | mit | 394 |
import os
import os.path
import binascii
import tempfile
import shutil
import getpass
import time
from twisted.trial import unittest
from twisted.internet.protocol import Factory
from twisted.internet import reactor, defer, protocol, error
from txdbus import bus, endpoints, authentication
from txdbus.authentication import DBusAuthenticationFailed
class GetPass(object):
def getuser(self):
return 'testuser'
tohex = binascii.hexlify
unhex = binascii.unhexlify
class ClientAuthenticatorTester(unittest.TestCase):
def setUp(self):
authentication.getpass = GetPass() # override 'getpass' module
self.ca = authentication.ClientAuthenticator()
self.reply = None
self.ca.beginAuthentication(self)
def tearDown(self):
authentication.getpass = getpass
def sendAuthMessage(self, m):
self.reply = m
def send(self, msg):
self.ca.handleAuthMessage(msg)
def ae(self, x,y):
self.assertEquals(x,y)
def are(self, x):
self.assertEquals(self.reply, x)
def test_bad_auth_message(self):
self.assertRaises(DBusAuthenticationFailed, self.send, 'BAD_LINE')
def test_rejection(self):
self.ae(self.ca.authMech, 'EXTERNAL')
self.are( 'AUTH EXTERNAL')
self.send('REJECTED')
self.ae(self.ca.authMech, 'DBUS_COOKIE_SHA1')
self.are( 'AUTH DBUS_COOKIE_SHA1 ' + tohex('testuser'))
self.send('REJECTED')
self.ae(self.ca.authMech, 'ANONYMOUS')
self.are( 'AUTH ANONYMOUS 747864627573')
self.assertRaises(DBusAuthenticationFailed, self.send, 'REJECTED')
def test_error(self):
self.ae(self.ca.authMech, 'EXTERNAL')
self.are( 'AUTH EXTERNAL')
self.send('ERROR')
self.ae(self.ca.authMech, 'DBUS_COOKIE_SHA1')
self.are( 'AUTH DBUS_COOKIE_SHA1 ' + tohex('testuser'))
self.send('ERROR')
self.ae(self.ca.authMech, 'ANONYMOUS')
self.are( 'AUTH ANONYMOUS 747864627573')
def test_ok(self):
self.assertRaises(DBusAuthenticationFailed, self.send, 'OK')
self.assertRaises(DBusAuthenticationFailed, self.send, 'OK foo')
self.send('OK ' + tohex('foo'))
self.ae(self.ca.getGUID(), 'foo')
self.are( 'BEGIN')
self.assertTrue(self.ca.authenticationSucceeded())
def test_agree_unix_fd(self):
self.are('AUTH EXTERNAL')
self.send('AGREE_UNIX_FD')
self.are('AUTH EXTERNAL')
def test_data_external(self):
self.ca.authMech = 'EXTERNAL'
self.send('DATA')
self.are('DATA')
def test_get_cookie(self):
t = tempfile.mkdtemp()
k = os.path.join(t,'keyring')
ctx = 'foo'
cid = 'bar'
fn = os.path.join(k, ctx)
try:
os.mkdir(k, 0o0777)
self.ca.cookie_dir = k
self.assertRaises(Exception, self.ca._authGetDBusCookie, None, None)
os.chmod(k, 0o0700)
self.ca.cookie_dir = '/etc'
self.assertRaises(Exception, self.ca._authGetDBusCookie, None, None)
with open(fn, 'w') as f:
f.write('abcd 12345 234234234\n')
f.write('bar 12345 123456\n')
self.ca.cookie_dir = k
self.ae(self.ca._authGetDBusCookie(ctx,cid), '123456')
finally:
shutil.rmtree(t)
def test_data_dbus_cookie_sha1_err(self):
self.ca.authMech = 'DBUS_COOKIE_SHA1'
self.send('DATA ACK!')
self.are('ERROR Non-hexadecimal digit found')
class BusCookieAuthenticatorTester(unittest.TestCase):
def setUp(self):
self.ba = authentication.BusCookieAuthenticator()
def ae(self, x,y):
self.assertEquals(x,y)
def ar(self, x):
self.assertEquals(x, ('REJECTED', None))
def s(self, x):
return self.ba.step(x)
def s1(self, x, y=None):
return self.ba._step_one(x, y)
def s2(self, x):
return self.ba._step_two(x)
def test_mech_name(self):
self.ae(self.ba.getMechanismName(), 'DBUS_COOKIE_SHA1')
def test_step(self):
self.ar( self.s(None) )
self.ba.step_num = 2
self.ar( self.s('foo') )
def test_step1_invalid_username(self):
self.ar( self.s1('foobarbazwannabewilliamwallace') )
def test_step1_invalid_uid(self):
self.ar( self.s1(99999999999) )
def test_step1_bad_user_keyring_permissions(self):
t = tempfile.mkdtemp()
k = os.path.join(t,'keyring')
try:
os.mkdir(k, 0o0777)
self.ar(self.s1(0,k))
finally:
shutil.rmtree(t)
def test_step1_create_user_keyring_dir(self):
t = tempfile.mkdtemp()
k = os.path.join(t,'keyring')
try:
self.assertTrue( not os.path.exists(k) )
self.ae(self.s1(0,k)[0], 'CONTINUE')
self.assertTrue( os.path.exists(k) )
finally:
shutil.rmtree(t)
def test_step2_fail(self):
t = tempfile.mkdtemp()
k = os.path.join(t,'keyring')
try:
self.assertTrue( not os.path.exists(k) )
self.ae(self.s1(0,k)[0], 'CONTINUE')
self.assertTrue( os.path.exists(k) )
self.ar(self.s2('INVALID RESPONSE'))
finally:
shutil.rmtree(t)
def test_lock(self):
t = tempfile.mkdtemp()
k = os.path.join(t,'keyring')
try:
self.assertTrue( not os.path.exists(k) )
self.ae(self.s1(0,k)[0], 'CONTINUE')
self.assertTrue( os.path.exists(k) )
lf = self.ba.cookie_file + '.lock'
with open(lf, 'w') as f:
f.write('\0')
self.ba._get_lock()
self.assertTrue(True)
finally:
shutil.rmtree(t)
class DBusCookieAuthenticationTester(unittest.TestCase):
def setUp(self):
authentication.getpass = GetPass() # override 'getpass' module
self.ca = authentication.ClientAuthenticator()
self.ba = authentication.BusCookieAuthenticator()
self.reply = None
self.ca.beginAuthentication(self)
def tearDown(self):
authentication.getpass = getpass
def sendAuthMessage(self, m):
self.reply = m
def send(self, msg):
self.ca.handleAuthMessage(msg)
def test_dbus_cookie_authentication(self):
self.assertEquals(self.ba.getMechanismName(), 'DBUS_COOKIE_SHA1')
while not self.ca.authMech == 'DBUS_COOKIE_SHA1':
self.ca.authTryNextMethod()
self.assertEquals(self.reply, 'AUTH DBUS_COOKIE_SHA1 ' + tohex('testuser'))
t = tempfile.mkdtemp()
k = os.path.join(t,'keyring')
try:
self.ca.cookie_dir = k
s1 = self.ba._step_one('0',k)
self.assertEquals(s1[0], 'CONTINUE')
self.send( 'DATA ' + tohex(s1[1]) )
self.assertTrue( self.reply.startswith('DATA') )
self.assertEquals(self.ba._step_two(unhex(self.reply.split()[1])), ('OK',None))
finally:
shutil.rmtree(t)
class DBusCookieCookieHandlingTester(unittest.TestCase):
def setUp(self):
self.ba = authentication.BusCookieAuthenticator()
self.t = tempfile.mkdtemp()
self.ba.cookie_file = os.path.join(self.t,'nomnomnom')
def tearDown(self):
shutil.rmtree(self.t)
def test_make_cookies(self):
def g(t):
def tf():
return time.time()-t
return tf
self.ba._create_cookie(g(31.0))
self.ba._create_cookie(g(31.0))
self.ba._create_cookie(g(20.0))
self.ba._create_cookie(g(21.2))
c = self.ba._get_cookies()
self.assertEquals(set(['3','4']), set( x[0] for x in c ))
def test_del_cookie_with_remaining(self):
self.ba._create_cookie()
self.ba._create_cookie()
self.ba._create_cookie()
self.ba.cookieId = 2
self.ba._delete_cookie()
c = self.ba._get_cookies()
self.assertEquals(set(['1','3']), set( x[0] for x in c ))
def test_del_cookie_last(self):
self.ba._create_cookie()
self.ba.cookieId = 1
self.assertTrue(os.path.exists(self.ba.cookie_file))
self.ba._delete_cookie()
self.assertTrue(not os.path.exists(self.ba.cookie_file))
class ExternalAuthMechanismTester(unittest.TestCase):
def test_external_auth_logic(self):
bea = authentication.BusExternalAuthenticator()
self.assertEquals(bea.getMechanismName(), 'EXTERNAL')
class T(object):
_unix_creds = None
bea.init(T())
self.assertEquals(bea.step(''), ('REJECT', 'Unix credentials not available'))
bea.creds = ('foo', 0)
self.assertEquals(bea.step(''), ('CONTINUE', ''))
self.assertEquals(bea.step(''), ('OK',None))
self.assertEquals(bea.getUserName(), 'root')
bea.cancel()
class AnonymousAuthMechanismTester(unittest.TestCase):
def test_anonymous_auth_logic(self):
baa = authentication.BusAnonymousAuthenticator()
self.assertEquals(baa.getMechanismName(), 'ANONYMOUS')
baa.init(None)
self.assertEquals(baa.step(''), ('OK',None))
self.assertEquals(baa.getUserName(), 'anonymous')
baa.cancel()
#----------------------------------------------------------------------
# Protocol Level Tests
#----------------------------------------------------------------------
# Always use the internal bus for tests if a system bus isn't available
# typically the session bus won't exist on Windows
#
INTERNAL_BUS = not 'DBUS_SESSION_BUS_ADDRESS' in os.environ
INTERNAL_BUS = True
def delay(arg):
d = defer.Deferred()
reactor.callLater(0.05, lambda : d.callback(arg) )
return d
def get_username():
uname = os.environ.get('USERNAME', None)
if uname is None:
uname = os.environ.get('LOGNAME', None)
return uname
class AuthTestProtocol(protocol.Protocol):
_buffer = ''
_sent_null = False
def connectionMade(self):
self.disconnect_d = None
self.disconnect_timeout = None
self.fail_exit_d = None
self.factory._ok(self)
def dataReceived(self, data):
lines = (self._buffer+data).split('\r\n')
self._buffer = lines.pop(-1)
for line in lines:
self.gotMessage(line)
def disconnect(self):
self.transport.loseConnection()
def setTest(self, test):
self.test = test
self.assertTrue = self.test.assertTrue
self.assertEquals = self.test.assertEquals
self.fail = self.test.fail
def succeed(self):
self.assertTrue(True)
def connectionLost(self, reason):
if self.disconnect_d:
if self.disconnect_timeout:
self.disconnect_timeout.cancel()
self.disconnect_timeout = None
d = self.disconnect_d
self.disconnect_d = None
d.callback(None)
elif self.fail_exit_d:
d = self.fail_exit_d
self.fail_exit_d = None
d.errback(unittest.FailTest('Connection unexpectedly dropped'))
def failOnExit(self):
self.fail_exit_d = defer.Deferred()
def cleanup(_):
self.fail_exit_d = None
return _
self.fail_exit_d.addCallback(cleanup)
return self.fail_exit_d
def expectDisconnect(self):
self.disconnect_d = defer.Deferred()
def timeout():
self.fail()
d = self.disconnect_d
self.disconnect_d = None
d.errback(Exception('Disconnect timed out'))
self.disconnect_timeout = reactor.callLater(2, timeout)
self.disconnect_d.addCallback( lambda _: self.succeed() )
return self.disconnect_d
def send(self, msg):
if not self._sent_null:
self.transport.write('\0')
self._sent_null = True
self.transport.write(msg + '\r\n')
def test_no_null_byte_at_start(self):
d = self.expectDisconnect()
self.transport.write('blah')
return d
def test_bad_command(self):
d = self.failOnExit()
self.send('FISHY')
def recv( msg ):
self.assertEquals(msg, 'ERROR "Unknown command"')
d.callback(None)
self.gotMessage = recv
return d
def test_bad_mech(self):
d = self.failOnExit()
self.send('AUTH FOOBAR')
def recv( msg ):
self.assertTrue(msg.startswith('REJECTED'))
d.callback(None)
self.gotMessage = recv
return d
def test_bad_mech2(self):
d = self.failOnExit()
self.send('AUTH FOO BAR')
def recv( msg ):
self.assertTrue(msg.startswith('REJECTED'))
d.callback(None)
self.gotMessage = recv
return d
def test_too_long(self):
d = self.expectDisconnect()
self.send('AUTH ' + 'A'* 17000)
return d
def test_max_rejects(self):
d = self.expectDisconnect()
def retry(_=None):
dr = defer.Deferred()
self.send('AUTH FOOBAR')
def recv( msg ):
self.assertTrue(msg.startswith('REJECTED'))
dr.callback(None)
self.gotMessage = recv
return dr
x = retry()
x.addCallback( retry )
x.addCallback( retry )
x.addCallback( retry )
x.addCallback( retry )
x.addCallback( retry )
return d
def test_reject(self):
d = self.failOnExit()
self.send('AUTH DBUS_COOKIE_SHA1')
def recv(msg):
self.assertTrue(msg.startswith('REJECTED'))
d.callback(None)
self.gotMessage = recv
return d
def test_retry(self):
d = self.failOnExit()
self.send('AUTH DBUS_COOKIE_SHA1')
def recv2(msg):
self.assertTrue(msg.startswith('DATA'))
d.callback(None)
def recv1(msg):
self.send('AUTH DBUS_COOKIE_SHA1 ' + binascii.hexlify(get_username()))
self.assertTrue(msg.startswith('REJECTED'))
self.gotMessage = recv2
self.gotMessage = recv1
return d
def test_cancel(self):
d = self.failOnExit()
self.send('AUTH DBUS_COOKIE_SHA1 '+ binascii.hexlify(get_username()))
def recv2(msg):
self.assertTrue(msg.startswith('REJECTED'))
d.callback(None)
def recv1(msg):
self.send('CANCEL' )
self.assertTrue(msg.startswith('DATA'))
self.gotMessage = recv2
self.gotMessage = recv1
return d
class AuthFactory (Factory):
"""
Factory for DBusClientConnection instances
"""
protocol = AuthTestProtocol
def __init__(self):
self.d = defer.Deferred()
def _ok(self, proto):
self.d.callback( proto )
def _failed(self, err):
self.d.errback(err)
def getConnection(self):
"""
Returns the fully-connected DBusClientConnection instance. This method
should be used to obtain a reference to the DBusClientConnection as it
will be called back/error backed after authentication and DBus session
registration are complete.
"""
return self.d
class ServerObjectTester(unittest.TestCase):
def setUp(self):
if INTERNAL_BUS:
os.environ['DBUS_SESSION_BUS_ADDRESS']='unix:abstract=/tmp/txdbus-test,guid=5'
bus_obj = bus.Bus()
f = Factory()
f.protocol = bus.BusProtocol
f.bus = bus_obj
point = endpoints.getDBusEnvEndpoints(reactor, False)[0]
d = point.listen(f)
def got_port(port):
self.port = port
return self._client_connect()
d.addCallback( got_port )
return d
else:
return self._client_connect()
def _client_connect(self):
self.conn = None
f = AuthFactory()
point = endpoints.getDBusEnvEndpoints(reactor)[0]
point.connect(f)
d = f.getConnection()
d.addCallback(self._connected)
return d
def _connected(self, conn):
self.conn = conn
self.conn.setTest(self)
def tearDown(self):
if self.conn:
self.conn.disconnect()
if INTERNAL_BUS:
return self.port.stopListening()
def test_no_null_byte_at_start(self):
return self.conn.test_no_null_byte_at_start()
def test_bad_command(self):
return self.conn.test_bad_command()
def test_bad_mech(self):
return self.conn.test_bad_mech()
def test_bad_mech2(self):
return self.conn.test_bad_mech2()
def test_too_long(self):
return self.conn.test_too_long()
def test_reject(self):
return self.conn.test_reject()
def test_retry(self):
return self.conn.test_retry()
def test_cancel(self):
return self.conn.test_cancel()
def test_max_rejects(self):
return self.conn.test_max_rejects()
| Pyrrvs/txdbus | txdbus/test/test_authentication.py | Python | mit | 17,765 |
from asyncio import AbstractEventLoop
import aiomysql.sa
import asyncpg
from asyncio_extras import async_contextmanager
from cetus.types import (ConnectionType,
MySQLConnectionType,
PostgresConnectionType)
from sqlalchemy.engine.url import URL
DEFAULT_MYSQL_PORT = 3306
DEFAULT_POSTGRES_PORT = 5432
DEFAULT_MIN_CONNECTIONS_LIMIT = 10
DEFAULT_CONNECTION_TIMEOUT = 60
@async_contextmanager
async def get_connection_pool(
*, db_uri: URL,
is_mysql: bool,
timeout: float = DEFAULT_CONNECTION_TIMEOUT,
min_size: int = DEFAULT_MIN_CONNECTIONS_LIMIT,
max_size: int,
loop: AbstractEventLoop):
if is_mysql:
async with get_mysql_connection_pool(
db_uri,
timeout=timeout,
min_size=min_size,
max_size=max_size,
loop=loop) as connection_pool:
yield connection_pool
else:
async with get_postgres_connection_pool(
db_uri,
timeout=timeout,
min_size=min_size,
max_size=max_size,
loop=loop) as connection_pool:
yield connection_pool
@async_contextmanager
async def get_mysql_connection_pool(
db_uri: URL, *,
timeout: float = DEFAULT_CONNECTION_TIMEOUT,
min_size: int = DEFAULT_MIN_CONNECTIONS_LIMIT,
max_size: int,
loop: AbstractEventLoop):
# `None` port causes exceptions
port = db_uri.port or DEFAULT_MYSQL_PORT
# we use engine instead of plain connection pool
# because `aiomysql` has transactions API
# only for engine-based connections
async with aiomysql.sa.create_engine(
host=db_uri.host,
port=port,
user=db_uri.username,
password=db_uri.password,
db=db_uri.database,
charset='utf8',
connect_timeout=timeout,
# TODO: check if `asyncpg` connections
# are autocommit by default
autocommit=True,
minsize=min_size,
maxsize=max_size,
loop=loop) as engine:
yield engine
@async_contextmanager
async def get_postgres_connection_pool(
db_uri: URL, *,
timeout: float = DEFAULT_CONNECTION_TIMEOUT,
min_size: int = DEFAULT_MIN_CONNECTIONS_LIMIT,
max_size: int,
loop: AbstractEventLoop):
# for symmetry with MySQL case
port = db_uri.port or DEFAULT_POSTGRES_PORT
async with asyncpg.create_pool(
host=db_uri.host,
port=port,
user=db_uri.username,
password=db_uri.password,
database=db_uri.database,
timeout=timeout,
min_size=min_size,
max_size=max_size,
loop=loop) as pool:
yield pool
@async_contextmanager
async def begin_transaction(
*, connection: ConnectionType,
is_mysql: bool):
if is_mysql:
async with begin_mysql_transaction(connection):
yield
else:
async with begin_postgres_transaction(connection):
yield
@async_contextmanager
async def begin_mysql_transaction(
connection: MySQLConnectionType):
transaction = connection.begin()
async with transaction:
yield
@async_contextmanager
async def begin_postgres_transaction(
connection: PostgresConnectionType,
*, isolation: str = 'read_committed',
read_only: bool = False,
deferrable: bool = False):
transaction = connection.transaction(
isolation=isolation,
readonly=read_only,
deferrable=deferrable)
async with transaction:
yield
@async_contextmanager
async def get_connection(
*, db_uri: URL,
is_mysql: bool,
timeout: float = DEFAULT_CONNECTION_TIMEOUT,
loop: AbstractEventLoop):
if is_mysql:
async with get_mysql_connection(
db_uri,
timeout=timeout,
loop=loop) as connection:
yield connection
else:
async with get_postgres_connection(
db_uri,
timeout=timeout,
loop=loop) as connection:
yield connection
@async_contextmanager
async def get_mysql_connection(
db_uri: URL, *,
timeout: float = DEFAULT_CONNECTION_TIMEOUT,
loop: AbstractEventLoop):
# `None` port causes exceptions
port = db_uri.port or DEFAULT_MYSQL_PORT
# we use engine-based connection
# instead of plain connection
# because `aiomysql` has transactions API
# only for engine-based connections
async with aiomysql.sa.create_engine(
host=db_uri.host,
port=port,
user=db_uri.username,
password=db_uri.password,
db=db_uri.database,
charset='utf8',
connect_timeout=timeout,
# TODO: check if `asyncpg` connections
# are autocommit by default
autocommit=True,
minsize=1,
maxsize=1,
loop=loop) as engine:
async with engine.acquire() as connection:
yield connection
@async_contextmanager
async def get_postgres_connection(
db_uri: URL, *,
timeout: float = DEFAULT_CONNECTION_TIMEOUT,
loop: AbstractEventLoop):
# for symmetry with MySQL case
port = db_uri.port or DEFAULT_POSTGRES_PORT
connection = await asyncpg.connect(
host=db_uri.host,
port=port,
user=db_uri.username,
password=db_uri.password,
database=db_uri.database,
timeout=timeout,
loop=loop)
try:
yield connection
finally:
await connection.close()
| lycantropos/cetus | cetus/data_access/connectors.py | Python | mit | 5,800 |
#!/usr/bin/env python3
"""
Created on 18 Sep 2016
@author: Bruno Beloff (bruno.beloff@southcoastscience.com)
"""
from scs_core.data.datetime import LocalizedDatetime
from scs_core.data.json import JSONify
from scs_core.particulate.pmx_datum import PMxDatum
# --------------------------------------------------------------------------------------------------------------------
now = LocalizedDatetime.now().utc()
pmx = PMxDatum(now, 11, 22, None, 33)
print(pmx)
print("-")
jstr = JSONify.dumps(pmx)
print(jstr)
print("-")
| south-coast-science/scs_dfe_eng | tests/particulate/pmx_datum_test.py | Python | mit | 530 |
import hexchat
#Based on Weechat's Weestats: https://weechat.org/scripts/source/weestats.py.html/
#By Filip H.F. 'FiXato' Slagter <fixato [at] gmail [dot] com>
__module_name__ = 'HexStats'
__module_version__ = '0.0.1'
__module_description__ = 'Displays HexChat-wide User Statistics'
__module_author__ = 'Vlek'
def stats(word, word_to_eol, userdata):
print( getstats() )
return hexchat.EAT_ALL
def printstats(word, word_to_eol, userdata):
hexchat.command('say {}'.format( getstats() ))
return hexchat.EAT_ALL
def check_opped(ctx, nickprefixes):
op_idx = nickprefixes.index('@')
nick = ctx.get_info('nick')
me = [user for user in ctx.get_list('users') if hexchat.nickcmp(user.nick, nick) == 0][0]
if me.prefix and nickprefixes.index(me.prefix[0]) <= op_idx:
return True
return False
def getstats():
contexts = hexchat.get_list('channels')
channels = 0
servers = 0
queries = 0
ops = 0
for ctx in contexts:
if ctx.type == 1:
servers += 1
elif ctx.type == 2:
channels += 1
if check_opped(ctx.context, ctx.nickprefixes):
ops += 1
elif ctx.type == 3:
queries += 1
return 'Stats: {} channels ({} OPs), {} servers, {} queries'.format( channels, ops,
servers, queries )
hexchat.hook_command("stats", stats, help="/stats displays HexChat user statistics")
hexchat.hook_command("printstats", printstats, help="/printstats Says HexChat user statistics in current context")
| Vlek/plugins | HexChat/HexStats.py | Python | mit | 1,614 |
from django.contrib import admin
from .models import Post, Publisher
class PostInline(admin.StackedInline):
model = Post
class PublisherAdmin(admin.ModelAdmin):
inlines = [PostInline,]
admin.site.register(Publisher, PublisherAdmin)
admin.site.register(Post) | omerturner/manakinproducts | blog/admin.py | Python | mit | 286 |
import dijon
def test_compare_sequence_no_difference():
source_data = ['a', 'b', 'c']
target_data = ['a', 'b', 'c']
diff_graph = dijon.compare(source_data, target_data)
diff_nodes = [n for n in diff_graph.iter_nodes(differences=True)]
assert len(diff_nodes) == 0
def test_compare_sequence_append():
source_data = ['a', 'b', 'c']
target_data = ['a', 'b', 'c', 'd']
diff_graph = dijon.compare(source_data, target_data)
diff_nodes = [n for n in diff_graph.iter_nodes(differences=True)]
assert len(diff_nodes) == 1
difference = diff_nodes[0]
assert isinstance(difference, dijon.SequenceItemAddition)
assert difference.full_path == ('root', (None, 3))
assert difference.source is None
assert difference.target.full_path == ('root', (None, 3), 3)
assert difference.target.value == 'd'
def test_compare_sequence_insert():
source_data = ['a', 'b', 'c']
target_data = ['z', 'a', 'b', 'c']
diff_graph = dijon.compare(source_data, target_data)
diff_nodes = [n for n in diff_graph.iter_nodes(differences=True)]
assert len(diff_nodes) == 4
difference = diff_nodes[0]
assert isinstance(difference, dijon.SequenceItemModification)
assert difference.full_path == ('root', (0, 1))
assert difference.source.full_path == ('root', (0, 1), 0)
assert difference.source.data == 'a'
assert difference.target.full_path == ('root', (0, 1), 1)
assert difference.target.data == 'a'
difference = diff_nodes[1]
assert isinstance(difference, dijon.SequenceItemModification)
assert difference.full_path == ('root', (1, 2))
assert difference.source.full_path == ('root', (1, 2), 1)
assert difference.source.data == 'b'
assert difference.target.full_path == ('root', (1, 2), 2)
assert difference.target.data == 'b'
difference = diff_nodes[2]
assert isinstance(difference, dijon.SequenceItemModification)
assert difference.full_path == ('root', (2, 3))
assert difference.source.full_path == ('root', (2, 3), 2)
assert difference.source.data == 'c'
assert difference.target.full_path == ('root', (2, 3), 3)
assert difference.target.data == 'c'
difference = diff_nodes[3]
assert isinstance(difference, dijon.SequenceItemAddition)
assert difference.full_path == ('root', (None, 0))
assert difference.source is None
assert difference.target.full_path == ('root', (None, 0), 0)
assert difference.target.data == 'z'
target_data = ['a', 'b', 'z', 'c']
diff_graph = dijon.compare(source_data, target_data)
diff_nodes = [n for n in diff_graph.iter_nodes(differences=True)]
assert len(diff_nodes) == 2
difference = diff_nodes[0]
assert isinstance(difference, dijon.SequenceItemModification)
assert difference.full_path == ('root', (2, 3))
assert difference.source.full_path == ('root', (2, 3), 2)
assert difference.source.data == 'c'
assert difference.target.full_path == ('root', (2, 3), 3)
assert difference.target.data == 'c'
difference = diff_nodes[1]
assert isinstance(difference, dijon.SequenceItemAddition)
assert difference.full_path == ('root', (None, 2))
assert difference.source is None
assert difference.target.full_path == ('root', (None, 2), 2)
assert difference.target.data == 'z'
def test_compare_sequence_deletion():
source_data = ['a', 'b', 'c']
target_data = ['a', 'b']
diff_graph = dijon.compare(source_data, target_data)
diff_nodes = [n for n in diff_graph.iter_nodes(differences=True)]
assert len(diff_nodes) == 1
difference = diff_nodes[0]
assert isinstance(difference, dijon.SequenceItemDeletion)
assert difference.full_path == ('root', (2, None))
assert difference.source.full_path == ('root', (2, None), 2)
assert difference.source.data == 'c'
assert difference.target is None
target_data = ['b', 'c']
diff_graph = dijon.compare(source_data, target_data)
diff_nodes = [n for n in diff_graph.iter_nodes(differences=True)]
assert len(diff_nodes) == 3
difference = diff_nodes[0]
assert isinstance(difference, dijon.SequenceItemModification)
assert difference.full_path == ('root', (1, 0))
assert difference.source.full_path == ('root', (1, 0), 1)
assert difference.source.data == 'b'
assert difference.target.full_path == ('root', (1, 0), 0)
assert difference.target.data == 'b'
difference = diff_nodes[1]
assert isinstance(difference, dijon.SequenceItemModification)
assert difference.full_path == ('root', (2, 1))
assert difference.source.full_path == ('root', (2, 1), 2)
assert difference.source.data == 'c'
assert difference.target.full_path == ('root', (2, 1), 1)
assert difference.target.data == 'c'
difference = diff_nodes[2]
assert isinstance(difference, dijon.SequenceItemDeletion)
assert difference.full_path == ('root', (0, None))
assert difference.source.full_path == ('root', (0, None), 0)
assert difference.source.data == 'a'
assert difference.target is None
target_data = ['a', 'c']
diff_graph = dijon.compare(source_data, target_data)
diff_nodes = [n for n in diff_graph.iter_nodes(differences=True)]
assert len(diff_nodes) == 2
difference = diff_nodes[0]
assert isinstance(difference, dijon.SequenceItemModification)
assert difference.full_path == ('root', (2, 1))
assert difference.source.full_path == ('root', (2, 1), 2)
assert difference.source.data == 'c'
assert difference.target.full_path == ('root', (2, 1), 1)
assert difference.target.data == 'c'
difference = diff_nodes[1]
assert isinstance(difference, dijon.SequenceItemDeletion)
assert difference.full_path == ('root', (1, None))
assert difference.source.full_path == ('root', (1, None), 1)
assert difference.source.data == 'b'
assert difference.target is None
| artPlusPlus/dijon | tests/test_sequence_compare.py | Python | mit | 5,916 |
{
"name": "website_sale_birthdate",
"author": "IT-Projects LLC, Ivan Yelizariev",
"license": "Other OSI approved licence", # MIT
"support": "apps@itpp.dev",
"website": "https://yelizariev.github.io",
"category": "eCommerce",
"vesion": "13.0.1.0",
"depends": ["website_sale", "partner_person"],
"data": ["views.xml"],
"installable": False,
}
| it-projects-llc/website-addons | website_sale_birthdate/__manifest__.py | Python | mit | 382 |
import json
from math import ceil
from asyncpg import Connection
from qllr.common import MATCH_LIST_ITEM_COUNT
from qllr.db import cache
from qllr.settings import PLAYER_COUNT_PER_PAGE
KEEPING_TIME = 60 * 60 * 24 * 30
SQL_TOP_PLAYERS_BY_GAMETYPE = """
SELECT
p.steam_id,
p.name,
p.model,
gr.rating,
gr.deviation,
gr.n,
count(*) OVER () AS count,
ROW_NUMBER() OVER (ORDER BY gr.rating DESC) AS rank
FROM
players p
LEFT JOIN (SUBQUERY) gr ON
gr.steam_id = p.steam_id
WHERE
gr.n >= 10 AND
gr.last_played_timestamp > LEAST( $1, (
SELECT timestamp
FROM matches
WHERE gametype_id = $2
ORDER BY timestamp DESC
LIMIT 1 OFFSET {OFFSET}
)) AND
gr.gametype_id = $2
ORDER BY gr.rating DESC
""".format(
OFFSET=int(MATCH_LIST_ITEM_COUNT)
).replace(
"(SUBQUERY)", "({SUBQUERY})"
)
SQL_TOP_PLAYERS_BY_GAMETYPE_R1 = SQL_TOP_PLAYERS_BY_GAMETYPE.format(
SUBQUERY="""
SELECT
steam_id,
r1_mean AS rating,
r1_deviation AS deviation,
last_played_timestamp,
gametype_id,
n
FROM
gametype_ratings
"""
)
SQL_TOP_PLAYERS_BY_GAMETYPE_R2 = SQL_TOP_PLAYERS_BY_GAMETYPE.format(
SUBQUERY="""
SELECT
steam_id,
r2_value AS rating,
0 AS deviation,
last_played_timestamp,
gametype_id,
n
FROM
gametype_ratings
"""
)
def get_sql_top_players_query_by_gametype_id(gametype_id: int):
if cache.USE_AVG_PERF[gametype_id]:
return SQL_TOP_PLAYERS_BY_GAMETYPE_R2
else:
return SQL_TOP_PLAYERS_BY_GAMETYPE_R1
async def get_list(con: Connection, gametype_id: int, page: int, show_inactive=False):
await con.set_type_codec(
"json", encoder=json.dumps, decoder=json.loads, schema="pg_catalog"
)
query = get_sql_top_players_query_by_gametype_id(
gametype_id
) + "LIMIT {LIMIT} OFFSET {OFFSET}".format(
LIMIT=int(PLAYER_COUNT_PER_PAGE), OFFSET=int(PLAYER_COUNT_PER_PAGE * page)
)
start_timestamp = 0
if show_inactive is False:
start_timestamp = cache.LAST_GAME_TIMESTAMPS[gametype_id] - KEEPING_TIME
result = []
player_count = 0
async for row in con.cursor(query, start_timestamp, gametype_id):
if row[0] != None:
result.append(
{
"_id": str(row[0]),
"name": row[1],
"model": (
row[2] + ("/default" if row[2].find("/") == -1 else "")
).lower(),
"rating": round(row[3], 2),
"rd": round(row[4], 2),
"n": row[5],
"rank": row[7],
}
)
player_count = row[6]
steam_ids = list(map(lambda player: int(player["_id"]), result))
query = """
SELECT
s.steam_id,
CEIL(AVG(CASE
WHEN m.team1_score > m.team2_score AND s.team = 1 THEN 1
WHEN m.team2_score > m.team1_score AND s.team = 2 THEN 1
ELSE 0
END)*100)
FROM
matches m
LEFT JOIN scoreboards s ON s.match_id = m.match_id
WHERE
m.gametype_id = $1 AND s.steam_id = ANY($2)
GROUP BY s.steam_id;
"""
for row in await con.fetch(query, gametype_id, steam_ids):
try:
result_index = steam_ids.index(row[0])
result[result_index]["win_ratio"] = int(row[1])
except ValueError:
pass # must not happen
return {
"ok": True,
"response": result,
"page_count": ceil(player_count / PLAYER_COUNT_PER_PAGE),
}
| em92/pickup-rating | qllr/blueprints/ratings/methods.py | Python | mit | 3,787 |
# Now make a simple example using the custom projection.
import pdb
import sys
import os
import pkg_resources
pkg_resources.require('matplotlib==1.4.0')
import datetime
from dateutil.relativedelta import relativedelta
import re
import math
from matplotlib.ticker import ScalarFormatter, MultipleLocator
from matplotlib.collections import LineCollection
import matplotlib.pyplot as plt
from StringIO import StringIO
import numpy as np
from numpy import load
# Exception handling, with line number and stuff
import linecache
import sys
def PrintException():
exc_type, exc_obj, tb = sys.exc_info()
f = tb.tb_frame
lineno = tb.tb_lineno
filename = f.f_code.co_filename
linecache.checkcache(filename)
line = linecache.getline(filename, lineno, f.f_globals)
print 'EXCEPTION IN ({}, LINE {} "{}"): {}'.format(filename, lineno, line.strip(), exc_obj)
import imp
imp.load_source('SoundingRoutines', '/nfs/see-fs-01_users/eepdw/python_scripts/Tephigram/Sounding_Routines.py')
imp.load_source('TephigramPlot', '/nfs/see-fs-01_users/eepdw/python_scripts/Tephigram/Tephigram_Functions.py')
from TephigramPlot import *
from SoundingRoutines import *
imp.load_source('GeogFuncs', '/nfs/see-fs-01_users/eepdw/python_scripts/modules/GeogFunctions.py')
from GeogFuncs import *
pmin=200.
station_list_cs=[42182, 43003, 43014, 42867, 43371, 43353, 43285, 43192, 43150, 42339, 40990, 40948]
#station_list_cs=[43003]
date_min=datetime.datetime(1960,5,1,0,0,0)
date_max=datetime.datetime(2014,10,1,0,0,0)
delta = relativedelta(weeks=+1)
variable_list={'pressures': 0, 'temps':1, 'dewpoints':2, 'winddirs':3, 'windspeeds':4, 'pot_temp':5,
'sat_vap_pres':6, 'vap_press':7, 'rel_hum':8, 'wvmr':9, 'sp_hum':10, 'sat_temp':11,
'theta_e':12, 'theta_e_sat':13, 'theta_e_minus_theta_e_sat':14}
variable_list_line={'lcl_temp': 0, 'lcl_vpt':1, 'pbl_pressure':2, 'surface_pressure':3, 'T_eq_0':4}
def variable_name_index_match(variable, variable_list):
for key, value in variable_list.iteritems(): # iter on both keys and values
if key.startswith('%s' % variable) and key.endswith('%s' % variable):
arr_index_var=value
return arr_index_var
# Parse the data
for stat in station_list_cs:
station_name,la,lo, st_height=StationInfoSearch(stat)
load_file = load('/nfs/a90/eepdw/Data/Observations/Radiosonde_Numpy/Radiosonde_Cross_Section_'
'IND_SOUNDING_INTERP_MEAN_Climat_%s_%s_%s_%s.npz'
% (date_min.strftime('%Y%m%d'), date_max.strftime('%Y%m%d'), delta, stat))
data=load_file['date_bin_mean_all_dates_one_station']
dates=load_file['dates_for_plotting']
for bin in range(data.shape[0]):
try:
p=data[bin,0,:]/100
T=data[bin,1,:]-273.15
Td=T-data[bin,2,:]
h=data[bin,15,:]
da=dates[bin]
#print T
#print p
#print Td
#pdb.set_trace()
#u_wind,v_wind = u_v_winds(data[bin,3,:], data[bin,4,:])
u_wind,v_wind = data[bin,-2,:], data[bin,-1,:]
# Create a new figure. The dimensions here give a good aspect ratio
fig = plt.figure(figsize=(10, 8), frameon=False)
#fig.patch.set_visible(False)
tephigram_plot_height=0.85
tephigram_plot_bottom=.085
ax = fig.add_axes([.085,tephigram_plot_bottom,.65,tephigram_plot_height], projection='skewx', frameon=False, axisbg='w')
ax.set_yscale('log')
plt.grid(True)
#pdb.set_trace()
tmax=math.ceil(nanmax(T)/10)*10
tmin=math.floor(nanmin(Td[p>400])/10)*10
pmax=math.ceil(nanmax(p)/50)*50
P=linspace(pmax,pmin,37)
w = array([0.0001,0.0004,0.001, 0.002, 0.004, 0.007, 0.01, 0.016, 0.024, 0.032, 0.064, 0.128])
ax.add_mixratio_isopleths(w,linspace(pmax, 700., 37),color='m',ls='-',alpha=.5,lw=0.5)
ax.add_dry_adiabats(linspace(-40,40,9),P,color='k',ls='-',alpha=.5,lw=0.8)
ax.add_moist_adiabats(linspace(-40,40,18),P,color='k',ls='--',alpha=.5,lw=0.8, do_labels=False)
ax.other_housekeeping(pmax, pmin, 40,-40)
wbax = fig.add_axes([0.75,tephigram_plot_bottom,0.12,tephigram_plot_height],frameon=False, sharey=ax, label='barbs')
ax_text_box = fig.add_axes([0.85,0.085,.12,tephigram_plot_height], frameon=False, axisbg='w')
# Plot the data using normal plotting functions, in this case using semilogy
ax.semilogy(T, p, 'r', linewidth=2)
ax.semilogy(Td, p, 'r',linewidth=2)
# row_labels=(
# 'SLAT',
# 'SLON',
# 'SELV',
# 'SHOW',
# 'LIFT',
# 'LFTV',
# 'SWET',
# 'KINX',
# 'CTOT',
# 'VTOT',
# 'TOTL',
# 'CAPE',
# 'CINS',
# 'CAPV',
# 'CINV',
# 'LFCT',
# 'LFCV',
# 'BRCH',
# 'BRCV',
# 'LCLT',
# 'LCLP',
# 'MLTH',
# 'MLMR',
# 'THCK',
# 'PWAT')
# variable='pbl_pressure'
# var_index = variable_name_index_match(variable, variable_list_line)
# print load_file['date_bin_mean_all_dates_one_station_single'].shape
# pbl_pressure = load_file['date_bin_mean_all_dates_one_station_single'][bin,0,var_index]
# print pbl_pressure
# EQLV, pp, lclp,lfcp, lclt, delta_z, CAPE, CIN=CapeCinPBLInput(p, T, Td, h, st_height, pbl_pressure/100)
# print lclp
# table_vals=(
# #'%s' % station_name,
# #'Climatology - Week beg. %s' % da,
# '%s' % la,
# '%s' % lo,
# '%s' % st_height,
# '%.1f' % ShowalterIndex(T, Td, p), # ['Showalter index',
# '%.1f' % LiftedIndex(T, Td, p, h, st_height), # 'Lifted index',
# '--', # 'LIFT computed using virtual temperature',
# '--', # 'SWEAT index',
# '%.1f' % KIndex(T, Td, p), # 'K index',
# '%.1f' % CrossTotalsIndex(T, Td, p), # 'Cross totals index',
# '%.1f' % VerticalTotalsIndex(T, p), # 'Vertical totals index',
# '%.1f' % TotalTotalsIndex(T, Td, p), # 'Total totals index',
# '%.1f' % CAPE, # 'CAPE',
# '%.1f' % CIN, # 'CIN',
# '--', # 'CAPE using virtual temperature',
# '--', # 'CINS using virtual temperature',
# '%.1f' % lfcp, # 'Level of free convection',
# '--', # 'LFCT using virtual temperature',
# '--' , # 'Bulk Richardson number',
# '--', # 'Bulk richardson using CAPV',
# '%.1f' % lclt, # 'Temp [K] of the Lifted Condensation Level',
# '%.1f' % lclp , # 'Pres [hPa] of the Lifted Condensation Level',
# '--', # 'Mean mixed layer potential temperature',
# '--', # 'Mean mixed layer mixing ratio',
# '--', # '1000 hPa to 500 hPa thickness',
# '--') # 'Precipitable water [mm] for entire sounding']
# Wind barbs
barbs_idx=np.logspace(np.log10(10),np.log10(max(len(u_wind))),num=32).astype(int)
wbax.set_yscale('log')
wbax.xaxis.set_ticks([],[])
wbax.yaxis.grid(True,ls='-',color='y',lw=0.5)
wbax.set_xlim(-1.5,1.5)
wbax.get_yaxis().set_visible(False)
wbax.set_ylim(pmax+100,pmin)
wbax.barbs((zeros(p.shape))[barbs_idx-1],p[barbs_idx-1], u_wind[barbs_idx-1], v_wind[barbs_idx-1])
# Disables the log-formatting that comes with semilogy
ax.yaxis.set_major_formatter(ScalarFormatter())
ax.set_yticks(linspace(100,1000,10))
ax.set_ylim(pmax,pmin)
ax.set_xlim(-40.,40.)
ax.xaxis.set_ticks([],[])
ax_text_box.xaxis.set_visible(False)
ax_text_box.yaxis.set_visible(False)
for tick in wbax.yaxis.get_major_ticks():
# tick.label1On = False
pass
#wbax.get_yaxis().set_tick_params(size=0,color='y')
# y_loc=1.
# max_string_length = max([len(line) for line in row_labels])
# for t,r in zip(row_labels,table_vals):
# label_rightjust=('{:>%i}' % max_string_length).format(t)
# ax_text_box.text(0.5, y_loc, ' %s:' % (label_rightjust), size=8, horizontalalignment='right')
# ax_text_box.text(0.5, y_loc, ' %s' % (r), size=8, horizontalalignment='left')
# y_loc-=0.04
fig.text(.02,0.965, '%s %s' %(stat, station_name), size=12, horizontalalignment='left')
fig.text(.02,0.035, 'Climatology - Week beg. %s ' %(da.strftime('%m-%d')), size=12, horizontalalignment='left')
#plt.show()
plt.savefig('/nfs/a90/eepdw/Figures/Radiosonde/Tephigrams/Weekly_Climatology/Weekly_Climatology_%s_%s_%s_Skew_T.png' % (station_name.replace('/','_').replace(' ', '_'), stat, da.strftime('%Y%m%d')))
plt.close()
except Exception:
print PrintException()
| peterwilletts24/Python-Scripts | Tephigram/Tephigrams_From_Radiosonde_Climatology_Onset.py | Python | mit | 11,003 |
# tree_generator was written with Python 2.7.4.
# The pickle files it produces should not be read with a version of
# Python less than 2.7.4, as they are not forwards compatible.
from piece_definitions import PIECES
import numpy as np
import sys
import collections
import itertools
import argparse
import multiprocessing
import time
import hashlib
from math import factorial
from rect import Rect
from tree import *
from helper import *
import pickle
WIDTH = 4 # Default width
HEIGHT = 4 # Default height
BOARD = Board(HEIGHT, WIDTH)
PIECES_FIT = (WIDTH * HEIGHT) / 4 # Number of pieces that can fit in board
NUM_PIECES = len(PIECES)
NOTIFY_INTERVAL = 10 # Number of seconds between progress notification
args = None
# The adjacent function returns a 2D-array of all blocks that are vertically adjacent
# to the given 2D-array "a".
# A piece is not hovering in midair if part of it collides with the adjacent matrix.
def adjacent(a):
HEIGHT = a.shape[0]
WIDTH = a.shape[1]
m = np.zeros((HEIGHT, WIDTH), np.bool)
m[-1] = True # Set bottom row
# Set edge values
for x in range(HEIGHT):
for y in range(WIDTH):
if np.all(a[:, y]): # Special case for blocks that take up a whole column
m[:, y] = False
elif a[x, y] and x > 0:
m[x-1, y] = True
# Remove all but heighest values
for x in range(HEIGHT):
for y in range(WIDTH):
if m[x, y]:
m[x+1:, y] = False
return m
# The overhang function returns a 2D-array of all blocks that are empty space, but
# have a piece above them.
# A piece can be successfully dropped from above into its current position if it does
# not collide with the overhang matrix.
def overhang(a):
HEIGHT = a.shape[0]
WIDTH = a.shape[1]
m = np.zeros((HEIGHT, WIDTH), np.bool)
for y in range(WIDTH):
for x in range(1, HEIGHT):
if a[x-1, y] and not a[x, y]:
m[x, y] = True
return m
# The possible function returns a value indicating if a piece placement "p" on a given
# Tetris grid "a" would be possible (p does not occupy the same space as a).
def possible(p, a):
# See if the pieces clash
land = np.logical_and(p, a)
if np.any(land):
return False
return True
# The possible function returns a value indicating if a piece placement "p" on a given
# Tetris grid "a" would be valid (p is not in mid-air, and can be dropped vertically
# into destination position).
def valid(p, a):
# See if the piece is being placed in mid-air
hover = np.logical_and( p, adjacent(a) )
if not np.any(hover):
return False
# See if the piece can be placed when dropped vertically
drop = np.logical_and( p, overhang(a) )
if np.any(drop):
return False
return True
# Calculate every possible position a piece can have on a WIDTH*HEIGHT grid
def calculate_positions():
print 'Computing all possible orientations and positions of given tetrominoes on %dx%d grid.' % (WIDTH, HEIGHT)
possibilities = []
i = 0
for n, p in enumerate(PIECES):
options = []
p_width = len(p[0])
p_height = len(p)
# Calculate the number of rotations a piece requires, default 3 (all)
nrot = 4
if rall(p):
if p_width == p_height: # Piece is square, no rotation needed
nrot = 1
else: # Piece is rectangular, one rotation needed
nrot = 2
# Add all rotations to an options list
for r in range(nrot):
p = np.rot90(p, r)
# Remove duplicate rotations
already = False
for p2, r2 in options:
if np.array_equal(p, p2):
already = True
if not already:
options.append((p, r))
# Create all combinations
for _, r in options:
for h in range(HEIGHT):
for w in range(WIDTH):
try:
i += 1
op = DAction(BOARD, n, r, h, w)
possibilities.append(op)
except PieceNotFitError:
pass
print i
lp = len(possibilities)
print "There are %d possible orientations and positions for the given tetrominoes." % lp
calculate_possible(possibilities)
# Simple iterator that outputs the HEIGHT and WIDTH for our multiprocessing functions
def hw_iterator():
while True:
yield (HEIGHT, WIDTH)
# Check possibility
def check_possibility(data):
global PIECES, HEIGHT, WIDTH
hw, cur_pieces = data
height, width = hw
HEIGHT = height
WIDTH = width
board = np.zeros((HEIGHT, WIDTH), np.bool)
indr = [] # List of coordinate pairs of all pieces
lowestc = [HEIGHT, WIDTH] # Lowest coordinate of all pieces: (bottom, left)
highestc = [0, 0] # Highest coordinate of all pieces: (top, right)
boxcalc = False
prev_p = None
prev_bounding = None
for p in cur_pieces:
pheight = len(PIECES[p.piece])
pwidth = len(PIECES[p.piece][0])
coords = [[p.h, p.w], [pheight + p.h, pwidth + p.w]]
max_bounding = Rect(lowestc, highestc)
cur_bounding = Rect(*coords) # (bottom, left), (top, right)
if prev_p is not None and prev_bounding is not None:
board = np.logical_or(prev_p.data, board)
indr.append(prev_bounding)
prev_p = p
prev_bounding = cur_bounding
# We couldn't work out if it collides or not cheaply, so now onto the hard stuff
if not possible(p.data, board):
return None # This seems to have improved performance by like 10000%, very suspicious, keep an eye on it
return cur_pieces
# Input seconds, output H:MM:SS
def time_output(s):
hours, remainder = divmod(s, 3600)
minutes, seconds = divmod(remainder, 60)
return '%.f:%02.f:%02.f' % (hours, minutes, seconds)
# We combine all existing combinations and rotations of pieces to see which
# successfully fit together.
def calculate_possible(positions):
lp = len(positions)
search_space = 0
iterables = []
for i in range(PIECES_FIT):
search_space = search_space + ( factorial(lp) / ( factorial(lp-(PIECES_FIT-i)) * factorial(PIECES_FIT-i) ) )
iterables.append(itertools.combinations(positions, PIECES_FIT-i))
print "Calculating possible combinations of tetrominoes from all placements (%d combinations)." % search_space
start_time = time.time()
combinations = []
timer = time.time()
prev_i = 0
pool = multiprocessing.Pool() # Use multiple processes to leaverage maximum processing power
#for i, res in enumerate( itertools.imap(check_possibility, itertools.combinations(positions, PIECES_FIT)) ):
for i, res in enumerate( pool.imap_unordered(check_possibility, itertools.izip(hw_iterator(), itertools.chain(*iterables)), max(5, search_space/500)) ):
if res:
combinations.append(res)
elapsed = time.time() - timer
if elapsed > NOTIFY_INTERVAL and i != 0: # If x seconds have elapsed
pps = (i-prev_i)/elapsed
print "Searched %d/%d placements (%.1f%% complete, %.0f pieces/sec, ~%s remaining)" % (i, search_space, (i/float(search_space))*100, pps, time_output((search_space-i)/pps))
prev_i = i
timer = time.time()
pool.terminate()
lc = len(combinations)
print "There are %d possible combinations of a maximum of %d tetrominoes within the %d positions." % (lc, PIECES_FIT, search_space)
print "The calculation took %s." % time_output(time.time() - start_time)
if args.out_p:
pickle.dump(combinations, open(args.out_p,'wb'))
print "Output saved to '%s'." % args.out_p
calculate_valid(combinations)
# Check validity
def check_validity(data):
global HEIGHT, WIDTH
hw, pieces = data
height, width = hw
HEIGHT = height
WIDTH = width
board = np.zeros((HEIGHT, WIDTH), np.bool)
pos = True
for p in pieces:
if valid(p.data, board):
board = np.logical_or(p.data, board)
else:
return None
if pos:
return pieces
# We permute over all possible combinations and rotations of pieces to see which
# are valid tetris plays.
def calculate_valid(possibilities):
lp = len(possibilities)
search_space = lp * factorial(PIECES_FIT)
start_time = time.time()
print "Calculating valid permutations of tetrominoes from all possible (%d permutations)." % search_space
combinations = []
timer = time.time()
prev_i = 0
counter = 0
pool = multiprocessing.Pool() # Use multiple processes to leaverage maximum processing power
for possibility in possibilities:
# We permute every combination to work out the orders in which it would be valid
#for i, res in enumerate( itertools.imap(check_validity, itertools.permutations(possibility, len(possibility))) ):
for i, res in enumerate( pool.imap_unordered(check_validity, itertools.izip(hw_iterator(), itertools.permutations(possibility, len(possibility))), max(5,search_space/20)) ):
if res:
combinations.append(res)
counter += 1
elapsed = time.time() - timer
if elapsed > NOTIFY_INTERVAL and i != 0: # If x seconds have elapsed
pps = (i-prev_i)/elapsed
print "Searched %d/%d placements (%.1f%% complete, %.0f pieces/sec, ~%s remaining)" % (i, search_space, (i/float(search_space))*100, pps, time_output((search_space-i)/pps))
prev_i = i
timer = time.time()
pool.terminate()
print counter
lc = len(combinations)
print "There are %d valid permutations of a maximum of %d tetrominoes within the %d possibilities." % (lc, PIECES_FIT, search_space)
print "The calculation took %s." % time_output(time.time() - start_time)
if args.out_v:
pickle.dump(combinations, open(args.out_v,'wb'))
print "Output saved to '%s'." % args.out_v
# for c in combinations:
# found = False
# for e in c:
# if e.piece in [5, 6] or found:
# found = True
# break
# if found:
# print_multi_board(to_byte_matrix(c))
# print
combinations.sort()
create_tree(combinations)
# Creates tree from sorted list of tuples of actions
# "permutations" assumes a sorted list of permutations
def create_tree(permutations):
print "Converting %d permutations into decision tree." % len(permutations)
# Create root tree node. It has no parent and maximal utility.
root = State(BOARD, None, np.zeros((HEIGHT,WIDTH), np.bool))
root.utility = float('inf') # Utility of this action
# Terminal nodes are used to reverse traverse the tree to calculate the max_utility
term_nodes = []
print "Calculating utilities."
for nodes in permutations:
actions = []
parents = []
children = []
cur_parent = root
board_state = np.zeros((HEIGHT,WIDTH), np.bool)
for i, p in enumerate(nodes):
board_state = np.logical_or(board_state, p.data)
a = p.get_action()
actions.append(a)
if a not in cur_parent.actions[a.piece].keys(): # Make sure we don't override the state node
s = State(BOARD, cur_parent, board_state)
# print "%s{%s}.actions[%d][%s] = %s{%s}" % (cur_parent, hex(id(cur_parent)), a.piece, a, s, hex(id(s)))
cur_parent.actions[a.piece][a] = s
cur_parent = s
else:
cur_parent = cur_parent.actions[a.piece][a]
# Get list of memory references when traversing downwards
cur_state = root
drilldown = []
for a in actions:
drilldown.append(id(cur_state))
cur_state = cur_state.actions[a.piece][a]
drilldown.append(id(cur_state))
drilldown.reverse()
# Get list of memory references when traversing upwards
cur_state = cur_parent
i = 0
drillup = []
while cur_state.parent is not None and i <= PIECES_FIT:
drillup.append(id(cur_state))
cur_state = cur_state.parent
i += 1
drillup.append(id(cur_state))
# Sanity check to ensure that parent->children == children->parent
if not (drillup == drilldown):
print "Uh oh, something is wrong!"
print drilldown
print drillup
print
# cur_parent is the terminal node (at least currently)
cur_parent.max_utility = cur_parent.utility # The maximum utility of a terminal node is itself
term_nodes.append(cur_parent)
# Reverse traverse the tree to calculate the max_utility
print "Calculating max utilities."
for n in term_nodes:
i = 0
while n.parent is not None:
c = n
n = n.parent
if c.max_utility > n.max_utility:
n.max_utility = c.max_utility
i += 1
if i > PIECES_FIT:
break
print "We seem to be stuck in a loop, exiting"
if n != root:
print "Something is very wrong. The final node isn't the parent."
print "Tree created."
if args.out_t:
pickle.dump(root, open(args.out_t,'wb'))
print "Output saved to '%s'." % args.out_t
# Enter an interactive shell
# import code
# vars = globals().copy()
# vars.update(locals())
# shell = code.InteractiveConsole(vars)
# shell.interact()
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description='Computes a Tetris decision tree for a NxM sized grid'
)
parser.add_argument('--width', metavar='WIDTH', type=int,
default=WIDTH, help='width of Tetris grid')
parser.add_argument('--height', metavar='HEIGHT', type=int,
default=HEIGHT, help='height of Tetris grid')
pin = parser.add_mutually_exclusive_group()
pin.add_argument('--in-p', metavar='IN_P', type=str,
help='import possibilities and resume program')
pin.add_argument('--in-v', metavar='IN_V', type=str,
help='import valid permutations and resume program')
pout = parser.add_argument_group('output')
pout.add_argument('--out-p', metavar='OUT_P', type=str,
default='possible.p', help='save possible combinations [default: possible.p]')
pout.add_argument('--out-v', metavar='OUT_V', type=str,
default='valid.p', help='save valid permutations [default: valid.p]')
pout.add_argument('--out-t', metavar='OUT_T', type=str,
default='tree.p', help='save generated tree [default: tree.p]')
args = parser.parse_args()
WIDTH = args.width # Width of board
HEIGHT = args.height # Height of board
BOARD = Board(HEIGHT, WIDTH)
PIECES_FIT = (WIDTH * HEIGHT) / 4
if sys.version_info[:3] != (2, 7, 4):
print "WARNING: This program was designed to work on Python 2.7.4."
print " Not using that version could cause pickle compatibility issues."
if args.in_p:
p = pickle.load( open(args.in_p,'rb') )
calculate_valid(p)
elif args.in_v:
p = pickle.load( open(args.in_v,'rb') )
create_tree(p)
else:
calculate_positions()
print "Program complete."
| atyndall/cits4211 | tools/tree_generator.py | Python | mit | 14,570 |
import urllib2,json
def almanac(zip):
url = "http://api.wunderground.com/api/4997e70515d4cbbd/almanac/q/%d.json"%(zip)
r = urllib2.urlopen(url)
data = json.loads(r.read())
almanac = {"record low":data['almanac']['temp_low']['record']['F'].encode("ascii"),
"record high":data['almanac']['temp_high']['record']['F'].encode("ascii"),
"normal low":data['almanac']['temp_low']['normal']['F'].encode("ascii"),
"normal high":data['almanac']['temp_high']['normal']['F'].encode("ascii")
}
return almanac
print(almanac(11214))
| aacoppa/inglorious-gangsters | weather.py | Python | mit | 601 |
from flask import Blueprint, render_template, abort
from jinja2 import TemplateNotFound
form_page = Blueprint('form_page', __name__,
template_folder='templates')
@form_page.route('/<page>')
def show(page):
try:
form = AppForms.query.filter_by(name=page).first()
return render_template('form.html', form=form)
except TemplateNotFound:
abort(404) | elbow-jason/flask-meta | flask_meta/appmeta/controllers/form_page.py | Python | mit | 402 |
from behave import then, when
from bs4 import BeautifulSoup
from bs4.element import Tag
from pageobjects.pages import About, Welcome
@when(u'I instantiate the Welcome page object')
def new_pageobject(context):
context.page = Welcome(context)
@then(u'it provides a valid Beautiful Soup document')
def pageobject_works(context):
assert context.page.response.status_code == 200
assert context.page.request == context.page.response.request
assert isinstance(context.page.document, BeautifulSoup)
assert 'Test App: behave-django' == context.page.document.title.string, \
"unexpected title: %s" % context.page.document.title.string
@then(u'get_link() returns the link subdocument')
def getlink_subdocument(context):
context.about_link = context.page.get_link('about')
assert isinstance(context.about_link, Tag), \
"should be instance of %s (not %s)" % (
Tag.__name__, context.about_link.__class__.__name__)
@when('I call click() on the link')
def linkelement_click(context):
context.next_page = context.about_link.click()
@then('it loads a new PageObject')
def click_returns_pageobject(context):
assert About(context) == context.next_page
| behave/behave-django | tests/acceptance/steps/using_pageobjects.py | Python | mit | 1,207 |
# Test quiver-time
import keras as ks
from quiver_engine import server
import sys
# Load model
if sys.version_info.major == 2:
model = ks.models.load_model('models/my_bestmodel.h5')
elif sys.version_info.major == 3:
model = ks.models.load_model('models/my_bestmodel_py3.h5')
# Names of classes of PAMAP2
classes = ['lying',
'sitting',
'standing',
'walking',
'cycling',
'vacccuum',
'ironing']
# Launch server
server.launch(model, classes=classes, top=7, input_folder='input/')
| wmkouw/quiver-time | test_signal.py | Python | mit | 511 |
# The MIT License (MIT)
# Copyright (c) 2016, 2017 by the ESA CCI Toolbox development team and contributors
#
# 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.
"""
Description
===========
This module provides Cate's data access API.
Technical Requirements
======================
**Query data store**
:Description: Allow querying registered ECV data stores using a simple function that takes a
set of query parameters and returns data source identifiers that can be used to open
datasets in Cate.
:URD-Source:
* CCIT-UR-DM0006: Data access to ESA CCI
* CCIT-UR-DM0010: The data module shall have the means to attain meta-level status information
per ECV type
* CCIT-UR-DM0013: The CCI Toolbox shall allow filtering
----
**Add data store**
:Description: Allow adding of user defined data stores specifying the access protocol and the
layout of the data.
These data stores can be used to access datasets.
:URD-Source:
* CCIT-UR-DM0011: Data access to non-CCI data
----
**Open dataset**
:Description: Allow opening an ECV dataset given an identifier returned by the *data store query*.
The dataset returned complies to the Cate common data model.
The dataset to be returned can optionally be constrained in time and space.
:URD-Source:
* CCIT-UR-DM0001: Data access and input
* CCIT-UR-DM0004: Open multiple inputs
* CCIT-UR-DM0005: Data access using different protocols>
* CCIT-UR-DM0007: Open single ECV
* CCIT-UR-DM0008: Open multiple ECV
* CCIT-UR-DM0009: Open any ECV
* CCIT-UR-DM0012: Open different formats
Verification
============
The module's unit-tests are located in
`test/test_ds.py <https://github.com/CCI-Tools/cate/blob/master/test/test_ds.py>`_
and may be executed using ``$ py.test test/test_ds.py --cov=cate/core/ds.py`` for extra code
coverage information.
Components
==========
"""
import datetime
import glob
import logging
import re
from typing import Sequence, Optional, Union, Any, Dict, Set, Tuple
import geopandas as gpd
import xarray as xr
import xcube.core.store as xcube_store
from xcube.core.select import select_subset
from xcube.core.store import DATASET_TYPE
from xcube.core.store import MutableDataStore
from xcube.util.progress import ProgressObserver
from xcube.util.progress import ProgressState
from xcube.util.progress import add_progress_observers
from .cdm import get_lon_dim_name, get_lat_dim_name
from .types import PolygonLike, TimeRangeLike, VarNamesLike, ValidationError
from ..util.monitor import ChildMonitor
from ..util.monitor import Monitor
_TIMESTAMP_FORMAT = "%Y-%m-%dT%H:%M:%S"
__author__ = "Chris Bernat (Telespazio VEGA UK Ltd), ", \
"Tonio Fincke (Brockmann Consult GmbH), " \
"Norman Fomferra (Brockmann Consult GmbH), " \
"Marco Zühlke (Brockmann Consult GmbH)"
URL_REGEX = re.compile(
r'^(?:http|ftp)s?://' # http:// or https://
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)$', re.IGNORECASE)
_LOG = logging.getLogger('cate')
DATA_STORE_POOL = xcube_store.DataStorePool()
class DataAccessWarning(UserWarning):
"""
Warnings produced by Cate's data stores and data sources instances,
used to report any problems handling data.
"""
pass
class DataAccessError(Exception):
"""
Exceptions produced by Cate's data stores and data sources instances,
used to report any problems handling data.
"""
class NetworkError(ConnectionError):
"""
Exceptions produced by Cate's data stores and data sources instances,
used to report any problems with the network or in case an endpoint
couldn't be found nor reached.
"""
pass
class DataStoreNotice:
"""
A short notice that can be exposed to users by data stores.
"""
def __init__(self, id: str, title: str, content: str, intent: str = None, icon: str = None):
"""
A short notice that can be exposed to users by data stores.
:param id: Notice ID.
:param title: A human-readable, plain text title.
:param content: A human-readable, plain text title that may be formatted using Markdown.
:param intent: Notice intent,
may be one of "default", "primary", "success", "warning", "danger"
:param icon: An option icon name. See https://blueprintjs.com/docs/versions/1/#core/icons
"""
if id is None or id == "":
raise ValueError("invalid id")
if title is None or title == "":
raise ValueError("invalid title")
if content is None or content == "":
raise ValueError("invalid content")
if intent not in {None, "default", "primary", "success", "warning", "danger"}:
raise ValueError("invalid intent")
self._dict = dict(id=id, title=title, content=content, icon=icon, intent=intent)
@property
def id(self):
return self._dict["id"]
@property
def title(self):
return self._dict["title"]
@property
def content(self):
return self._dict["content"]
@property
def intent(self):
return self._dict["intent"]
@property
def icon(self):
return self._dict["icon"]
def to_dict(self):
return dict(self._dict)
class XcubeProgressObserver(ProgressObserver):
def __init__(self, monitor: Monitor):
self._monitor = monitor
self._latest_completed_work = 0.0
def on_begin(self, state_stack: Sequence[ProgressState]):
if len(state_stack) == 1:
self._monitor.start(state_stack[0].label, state_stack[0].total_work)
def on_update(self, state_stack: Sequence[ProgressState]):
if state_stack[0].completed_work > self._latest_completed_work:
self._monitor.progress(state_stack[0].completed_work
- self._latest_completed_work,
state_stack[-1].label)
self._latest_completed_work = state_stack[0].completed_work
def on_end(self, state_stack: Sequence[ProgressState]):
if len(state_stack) == 1:
self._monitor.done()
INFO_FIELD_NAMES = sorted(["abstract",
"bbox_minx",
"bbox_miny",
"bbox_maxx",
"bbox_maxy",
"catalog_url",
"catalogue_url",
"cci_project",
"creation_date",
"data_type",
"data_types",
"ecv",
"file_format",
"file_formats",
"info_url",
"institute",
"institutes",
"licences",
"platform_id",
"platform_ids",
"processing_level",
"processing_levels",
"product_string",
"product_strings",
"product_version",
"product_versions",
"publication_date",
"sensor_id",
"sensor_ids",
"temporal_coverage_end",
"temporal_coverage_start",
"time_frequencies",
"time_frequency",
"title",
"uuid"])
def get_metadata_from_descriptor(descriptor: xcube_store.DataDescriptor) -> Dict:
metadata = dict(data_id=descriptor.data_id,
type_specifier=str(descriptor.data_type))
if descriptor.crs:
metadata['crs'] = descriptor.crs
if descriptor.bbox:
metadata['bbox'] = descriptor.bbox
if hasattr(descriptor, 'spatial_res'):
metadata['spatial_res'] = descriptor.spatial_res
if descriptor.time_range:
metadata['time_range'] = descriptor.time_range
if descriptor.time_period:
metadata['time_period'] = descriptor.time_period
if hasattr(descriptor, 'attrs') \
and isinstance(getattr(descriptor, 'attrs'), dict):
for name in INFO_FIELD_NAMES:
value = descriptor.attrs.get(name, None)
# Many values are one-element lists: turn them into scalars
if isinstance(value, list) and len(value) == 1:
value = value[0]
if value is not None:
metadata[name] = value
for vars_key in ('data_vars', 'coords'):
if hasattr(descriptor, vars_key) \
and isinstance(getattr(descriptor, vars_key), dict):
metadata[vars_key] = []
var_attrs = ['units', 'long_name', 'standard_name']
for var_name, var_descriptor in getattr(descriptor, vars_key).items():
var_dict = dict(name=var_name,
dtype=var_descriptor.dtype,
dims=var_descriptor.dims)
if var_descriptor.chunks is not None:
var_dict['chunks'] = var_descriptor.chunks
if var_descriptor.attrs:
for var_attr in var_attrs:
if var_attr in var_descriptor.attrs:
var_dict[var_attr] = var_descriptor.attrs.get(var_attr)
metadata[vars_key].append(var_dict)
return metadata
def get_info_string_from_data_descriptor(descriptor: xcube_store.DataDescriptor) -> str:
meta_info = get_metadata_from_descriptor(descriptor)
max_len = 0
for name in meta_info.keys():
max_len = max(max_len, len(name))
info_lines = []
for name, value in meta_info.items():
if name not in ('data_vars', 'coords'):
info_lines.append('%s:%s %s' % (name,
(1 + max_len - len(name)) * ' ',
value))
return '\n'.join(info_lines)
def find_data_store(ds_id: str) -> Tuple[Optional[str], Optional[xcube_store.DataStore]]:
"""
Find the data store that includes the given *ds_id*.
This will raise an exception if the *ds_id* is given in more than one data store.
:param ds_id: A data source identifier.
:return: All data sources matching the given constrains.
"""
results = []
for store_instance_id in DATA_STORE_POOL.store_instance_ids:
data_store = DATA_STORE_POOL.get_store(store_instance_id)
if data_store.has_data(ds_id):
results.append((store_instance_id, data_store))
if len(results) > 1:
raise ValidationError(f'{len(results)} data sources found for the given ID {ds_id!r}')
if len(results) == 1:
return results[0]
return None, None
def get_data_store_notices(datastore_id: str) -> Sequence[dict]:
store_id = DATA_STORE_POOL.get_store_config(datastore_id).store_id
def name_is(extension):
return store_id == extension.name
extensions = xcube_store.find_data_store_extensions(predicate=name_is)
if len(extensions) == 0:
_LOG.warning(f'Found no extension for data store {datastore_id}')
return []
return extensions[0].metadata.get('data_store_notices', [])
def get_data_descriptor(ds_id: str) -> Optional[xcube_store.DataDescriptor]:
data_store_id, data_store = find_data_store(ds_id)
if data_store:
return data_store.describe_data(ds_id)
def open_dataset(dataset_id: str,
time_range: TimeRangeLike.TYPE = None,
region: PolygonLike.TYPE = None,
var_names: VarNamesLike.TYPE = None,
data_store_id: str = None,
force_local: bool = False,
local_ds_id: str = None,
monitor: Monitor = Monitor.NONE) -> Tuple[Any, str]:
"""
Open a dataset from a data source.
:param dataset_id: The identifier of an ECV dataset. Must not be empty.
:param time_range: An optional time constraint comprising start and end date.
If given, it must be a :py:class:`TimeRangeLike`.
:param region: An optional region constraint.
If given, it must be a :py:class:`PolygonLike`.
:param var_names: Optional names of variables to be included.
If given, it must be a :py:class:`VarNamesLike`.
:param data_store_id: Optional data store identifier. If given, *ds_id* will only be
looked up from the specified data store.
:param force_local: Optional flag for remote data sources only
Whether to make a local copy of data source if it's not present
:param local_ds_id: Optional ID for newly created copy of remote data
:param monitor: A progress monitor
:return: A tuple consisting of a new dataset instance and its id
"""
if not dataset_id:
raise ValidationError('No data source given')
if data_store_id:
data_store = DATA_STORE_POOL.get_store(data_store_id)
else:
data_store_id, data_store = find_data_store(ds_id=dataset_id)
if not data_store:
raise ValidationError(f"No data store found that contains the ID '{dataset_id}'")
data_type = None
potential_data_types = data_store.get_data_types_for_data(dataset_id)
for potential_data_type in potential_data_types:
if DATASET_TYPE.is_super_type_of(potential_data_type):
data_type = potential_data_type
break
if data_type is None:
raise ValidationError(f"Could not open '{dataset_id}' as dataset.")
openers = data_store.get_data_opener_ids(dataset_id, data_type)
if len(openers) == 0:
raise DataAccessError(f'Could not find an opener for "{dataset_id}".')
opener_id = openers[0]
open_work = 10
cache_work = 10 if force_local else 0
subset_work = 0
open_schema = data_store.get_open_data_params_schema(dataset_id, opener_id)
open_args = {}
subset_args = {}
if var_names:
var_names_list = VarNamesLike.convert(var_names)
if 'variable_names' in open_schema.properties:
open_args['variable_names'] = var_names_list
elif 'drop_variables' in open_schema.properties:
data_desc = data_store.describe_data(dataset_id, data_type)
if hasattr(data_desc, 'data_vars') \
and isinstance(getattr(data_desc, 'data_vars'), dict):
open_args['drop_variables'] = [var_name
for var_name in data_desc.data_vars.keys()
if var_name not in var_names_list]
else:
subset_args['var_names'] = var_names_list
subset_work += 1
if time_range:
time_range = TimeRangeLike.convert(time_range)
time_range = [datetime.datetime.strftime(time_range[0], '%Y-%m-%d'),
datetime.datetime.strftime(time_range[1], '%Y-%m-%d')]
if 'time_range' in open_schema.properties:
open_args['time_range'] = time_range
else:
subset_args['time_range'] = time_range
subset_work += 1
if region:
bbox = list(PolygonLike.convert(region).bounds)
if 'bbox' in open_schema.properties:
open_args['bbox'] = bbox
else:
subset_args['bbox'] = bbox
subset_work += 1
with monitor.starting('Open dataset', open_work + subset_work + cache_work):
with add_progress_observers(XcubeProgressObserver(ChildMonitor(monitor, open_work))):
dataset = data_store.open_data(data_id=dataset_id, opener_id=opener_id, **open_args)
dataset = select_subset(dataset, **subset_args)
monitor.progress(subset_work)
if force_local:
with add_progress_observers(XcubeProgressObserver(ChildMonitor(monitor, cache_work))):
dataset, dataset_id = make_local(data=dataset,
local_name=local_ds_id,
orig_dataset_name=dataset_id)
return dataset, dataset_id
def make_local(data: Any,
*,
local_name: Optional[str] = None,
orig_dataset_name: Optional[str] = None) -> Tuple[Any, str]:
local_data_store_id = 'local'
local_store = DATA_STORE_POOL.get_store(local_data_store_id)
if local_store is None:
raise ValueError(f'Cannot find data store {local_data_store_id!r}')
if not isinstance(local_store, MutableDataStore):
raise ValueError(f'Data store {local_data_store_id!r} is not writable')
if isinstance(data, xr.Dataset):
extension = '.zarr'
elif isinstance(data, gpd.GeoDataFrame):
extension = '.geojson'
else:
raise DataAccessError(f'Unsupported data type {type(data)}')
if local_name is not None and not local_name.endswith(extension):
local_name = local_name + extension
if not local_name and orig_dataset_name is not None:
i = 1
local_name = f'local.{orig_dataset_name}.{i}{extension}'
while local_store.has_data(local_name):
i += 1
local_name = f'local.{orig_dataset_name}.{i}{extension}'
local_data_id = local_store.write_data(data=data, data_id=local_name)
return local_store.open_data(data_id=local_data_id), local_data_id
def add_as_local(data_source_id: str, paths: Union[str, Sequence[str]] = None) -> Tuple[Any, str]:
paths = _resolve_input_paths(paths)
if not paths:
raise ValueError("No paths found")
# todo also support geodataframes
if len(paths) == 1:
ds = xr.open_dataset(paths[0])
else:
ds = xr.open_mfdataset(paths=paths)
return make_local(ds, local_name=data_source_id)
def _resolve_input_paths(paths: Union[str, Sequence[str]]) -> Sequence[str]:
# very similar code is used in nc2zarr
resolved_input_files = []
if isinstance(paths, str):
resolved_input_files.extend(glob.glob(paths, recursive=True))
elif paths is not None and len(paths):
for file in paths:
resolved_input_files.extend(glob.glob(file, recursive=True))
# Get rid of doubles, but preserve order
seen_input_files = set()
unique_input_files = []
for input_file in resolved_input_files:
if input_file not in seen_input_files:
unique_input_files.append(input_file)
seen_input_files.add(input_file)
return unique_input_files
def get_spatial_ext_chunk_sizes(ds_or_path: Union[xr.Dataset, str]) -> Dict[str, int]:
"""
Get the spatial, external chunk sizes for the latitude and longitude dimensions
of a dataset as provided in a variable's encoding object.
:param ds_or_path: An xarray dataset or a path to file that can be opened by xarray.
:return: A mapping from dimension name to external chunk sizes.
"""
if isinstance(ds_or_path, str):
ds = xr.open_dataset(ds_or_path, decode_times=False)
else:
ds = ds_or_path
lon_name = get_lon_dim_name(ds)
lat_name = get_lat_dim_name(ds)
if lon_name and lat_name:
chunk_sizes = get_ext_chunk_sizes(ds, {lat_name, lon_name})
else:
chunk_sizes = None
if isinstance(ds_or_path, str):
ds.close()
return chunk_sizes
def get_ext_chunk_sizes(ds: xr.Dataset, dim_names: Set[str] = None,
init_value=0, map_fn=max, reduce_fn=None) -> Dict[str, int]:
"""
Get the external chunk sizes for each dimension of a dataset as provided in a variable's encoding object.
:param ds: The dataset.
:param dim_names: The names of dimensions of data variables whose external chunking should be collected.
:param init_value: The initial value (not necessarily a chunk size) for mapping multiple different chunk sizes.
:param map_fn: The mapper function that maps a chunk size from a previous (initial) value.
:param reduce_fn: The reducer function the reduces multiple mapped chunk sizes to a single one.
:return: A mapping from dimension name to external chunk sizes.
"""
agg_chunk_sizes = None
for var_name in ds.variables:
var = ds[var_name]
if var.encoding:
chunk_sizes = var.encoding.get('chunksizes')
if chunk_sizes \
and len(chunk_sizes) == len(var.dims) \
and (not dim_names or dim_names.issubset(set(var.dims))):
for dim_name, size in zip(var.dims, chunk_sizes):
if not dim_names or dim_name in dim_names:
if agg_chunk_sizes is None:
agg_chunk_sizes = dict()
old_value = agg_chunk_sizes.get(dim_name)
agg_chunk_sizes[dim_name] = map_fn(size, init_value if old_value is None else old_value)
if agg_chunk_sizes and reduce_fn:
agg_chunk_sizes = {k: reduce_fn(v) for k, v in agg_chunk_sizes.items()}
return agg_chunk_sizes
def format_variables_info_string(descriptor: xcube_store.DataDescriptor):
"""
Return some textual information about the variables described by this DataDescriptor.
Useful for CLI / REPL applications.
:param descriptor: data descriptor
:return: a string describing the variables in the dataset
"""
meta_info = get_metadata_from_descriptor(descriptor)
variables = meta_info.get('data_vars', [])
if len(variables) == 0:
return 'No variables information available.'
info_lines = []
for variable in variables:
info_lines.append('%s (%s):' % (variable.get('name', '?'), variable.get('units', '-')))
info_lines.append(' Long name: %s' % variable.get('long_name', '?'))
info_lines.append(' CF standard name: %s' % variable.get('standard_name', '?'))
info_lines.append('')
return '\n'.join(info_lines)
def format_cached_datasets_coverage_string(cache_coverage: dict) -> str:
"""
Return a textual representation of information about cached, locally available data sets.
Useful for CLI / REPL applications.
:param cache_coverage:
:return:
"""
if not cache_coverage:
return 'No information about cached datasets available.'
info_lines = []
for date_from, date_to in sorted(cache_coverage.items()):
info_lines.append('{date_from} to {date_to}'
.format(date_from=date_from.strftime('%Y-%m-%d'),
date_to=date_to.strftime('%Y-%m-%d')))
return '\n'.join(info_lines)
| CCI-Tools/cate-core | cate/core/ds.py | Python | mit | 23,947 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-04-11 11:22
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('events', '0009_event_title'),
]
operations = [
migrations.CreateModel(
name='IgnoredEvent',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('ignored', models.BooleanField(default=True)),
('since', models.DateTimeField(auto_now=True)),
('event', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='events.Event')),
('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
| EricZaporzan/evention | evention/events/migrations/0010_ignoredevent.py | Python | mit | 1,007 |
import unittest
from openmdao.main.api import VariableTree, Component, Assembly
from openmdao.main.datatypes.api import Float, VarTree
class VT(VariableTree):
x = Float()
class C(Component):
x = Float(iotype='in')
out = Float(iotype='out')
def execute(self):
self.out = 2 * self.x
class A(Assembly):
vt = VarTree(VT(), iotype='in')
def configure(self):
self.add('c', C())
self.driver.workflow.add(['c'])
self.connect('vt.x', 'c.x')
self.create_passthrough('c.out')
class TestCase(unittest.TestCase):
def test_vtree(self):
a = A()
a.vt.x = 1.0
a.run()
self.assertEqual(a.out, 2.0)
if __name__ == '__main__':
unittest.main()
| DailyActie/Surrogate-Model | 01-codes/OpenMDAO-Framework-dev/openmdao.main/src/openmdao/main/test/test_aningvtree.py | Python | mit | 742 |
"""
Settings and configuration for Django.
Values will be read from the module specified by the DJANGO_SETTINGS_MODULE environment
variable, and then from django.conf.global_settings; see the global settings file for
a list of all possible variables.
"""
import importlib
import os
import time
from aiohttp.log import web_logger
from . import global_settings
ENVIRONMENT_VARIABLE = "AIOWEB_SETTINGS_MODULE"
class ImproperlyConfigured(BaseException):
def __init__(self, reason):
self.reason = reason
def __str__(self):
return self.reason
class BaseSettings(object):
"""
Common logic for settings whether set by a module or by the user.
"""
def __setattr__(self, name, value):
if name in ("MEDIA_URL", "STATIC_URL") and value and not value.endswith('/'):
raise ImproperlyConfigured("If set, %s must end with a slash" % name)
object.__setattr__(self, name, value)
class Settings(BaseSettings):
def __init__(self, settings_module):
# update this dict from global settings (but only for ALL_CAPS settings)
for setting in dir(global_settings):
if setting.isupper():
setattr(self, setting, getattr(global_settings, setting))
# store the settings module in case someone later cares
self.SETTINGS_MODULE = settings_module
if self.SETTINGS_MODULE:
try:
mod = importlib.import_module(self.SETTINGS_MODULE)
tuple_settings = (
"APPS",
)
self._explicit_settings = set()
for setting in dir(mod):
if setting.isupper():
setting_value = getattr(mod, setting)
if (setting in tuple_settings and
not isinstance(setting_value, (list, tuple))):
raise ImproperlyConfigured("The %s setting must be a list or a tuple. " % setting)
setattr(self, setting, setting_value)
self._explicit_settings.add(setting)
except ImportError:
web_logger.warn("Failed to import settings module")
else:
web_logger.warn("No settings module specified")
def is_overridden(self, setting):
return setting in self._explicit_settings
def __repr__(self):
return '<%(cls)s "%(settings_module)s">' % {
'cls': self.__class__.__name__,
'settings_module': self.SETTINGS_MODULE,
}
class UserSettingsHolder(BaseSettings):
"""
Holder for user configured settings.
"""
# SETTINGS_MODULE doesn't make much sense in the manually configured
# (standalone) case.
SETTINGS_MODULE = None
def __init__(self, default_settings):
"""
Requests for configuration variables not in this class are satisfied
from the module specified in default_settings (if possible).
"""
self.__dict__['_deleted'] = set()
self.default_settings = default_settings
def __getattr__(self, name):
if name in self._deleted:
raise AttributeError
return getattr(self.default_settings, name)
def __setattr__(self, name, value):
self._deleted.discard(name)
super(UserSettingsHolder, self).__setattr__(name, value)
def __delattr__(self, name):
self._deleted.add(name)
if hasattr(self, name):
super(UserSettingsHolder, self).__delattr__(name)
def __dir__(self):
return sorted(
s for s in list(self.__dict__) + dir(self.default_settings)
if s not in self._deleted
)
def is_overridden(self, setting):
deleted = (setting in self._deleted)
set_locally = (setting in self.__dict__)
set_on_default = getattr(self.default_settings, 'is_overridden', lambda s: False)(setting)
return (deleted or set_locally or set_on_default)
def __repr__(self):
return '<%(cls)s>' % {
'cls': self.__class__.__name__,
}
settings = Settings(os.environ.get(ENVIRONMENT_VARIABLE))
| kreopt/aioweb | aioweb/conf/__init__.py | Python | mit | 4,182 |
# My files
from handlers import MainPage
from handlers import WelcomePage
from handlers import SignUpPage
from handlers import SignIn
from handlers import SignOut
from handlers import NewPost
from handlers import EditPost
from handlers import DeletePost
from handlers import SinglePost
from handlers import LikePost
from handlers import DislikePost
from handlers import EditComment
from handlers import DeleteComment
import webapp2
app = webapp2.WSGIApplication([
('/', MainPage),
('/signup', SignUpPage),
('/welcome', WelcomePage),
('/post/([0-9]+)', SinglePost),
('/new-post', NewPost),
('/edit-post/([0-9]+)', EditPost),
('/delete-post', DeletePost),
('/like-post', LikePost),
('/dislike-post', DislikePost),
('/edit-comment', EditComment),
('/delete-comment', DeleteComment),
('/login', SignIn),
('/logout', SignOut)
], debug=True)
| joepettigrew/multi-blog | main.py | Python | mit | 890 |
# -*- coding: utf-8 -*-
'''
Created on 2013-3-8
@author: m00147039
'''
import sqlite3
#===============================================================================
# DB Data struct
#===============================================================================
ID = 0
PROCDUCTTYPE = 1
VERSION = 2
MODULENAME = 3
table_struct ={
0: "id",
1:'producttype',
2:'version',
3:'modulename'
}
#===============================================================================
# �豸������
#===============================================================================
class driver_mgmt():
_conn = None
_useselfdb = True
def __init__(self,db=None,DBName=None):
try:
if db != None:
self._conn=db
self._useselfdb = False
else:
self._conn = sqlite3.connect(DBName)
self._useselfdb = True
self._conn.execute("create table if not exists drivers_table( id integer primary key autoincrement, \
productType varchar(128), \
version varchar(128), \
modulename varchar(128));")
self._cur = self._conn.cursor()
except:
pass
def __exit__(self):
try:
if (self._useselfdb == True and self._conn != None):
self._conn.close()
else:
self._conn = None
except:
pass
def find_driver(self,productType,version):
try:
tcontent =(productType,version)
self._cur.execute("select * from drivers_table where productType=? and version=?;", tcontent)
return self._cur.fetchone()
except:
return None
def find_driverbyid(self,id):
try:
tcontent =(id,)
self._cur.execute("select * from drivers_table where id = ?;", tcontent)
line = self._cur.fetchone()
if (line is not None):
return line[PROCDUCTTYPE],line[VERSION],line[MODULENAME]
return None,None,None
except:
return None,None,None
def add_driver(self,productType,version,modulename):
try:
tcontent =(productType,version,modulename)
sql_state="insert into drivers_table(productType,version,modulename) values (?,?,?);"
if self.find_driver(productType,version)!=None:
tcontent =(productType,version,modulename,productType,version)
sql_state='update drivers_table set productType=?,version=?,modulename=? where productType=? and version=? ;'
self._conn.execute(sql_state, tcontent)
self._conn.commit()
return True
except:
return False
def show_drivers(self):
try:
res=self._cur.execute("select * from drivers_table;")
for line in res:
print line
return None
except:
return None
def getAllDriverInfo(self):
try:
c=self._cur.execute("select distinct * from drivers_table;")
res=c.fetchall()
namelist=[]
count=0
for line in res:
count=count+1
namelist.append({'id': line[0], 'productType':line[1],'version':line[2],'driverFile':line[3]})
return namelist
except:
return namelist
def delete_driver_id(self, sid):
try:
tcontent =(sid,)
sql_state='delete from drivers_table where id=?;'
self._conn.execute(sql_state, tcontent)
self._conn.commit()
return True
except:
return False
def delete_driver(self, productType,version):
try:
line=self.find_driver(productType,version)
if line== None:
return False
tcontent =(line[0],)
sql_state='delete from drivers_table where id=?;'
self._conn.execute(sql_state, tcontent)
self._conn.commit()
return True
except:
return False
def getdriverinfo(db,productType,version):
try:
dm=driver_mgmt(db)
line=dm.find_driver(productType, version)
if line == None:
return None
else:
return line[MODULENAME]
except:
return None
if __name__ == '__main__':
#===========================================================================
# Unit test samples
#===========================================================================
dm = driver_mgmt(None,'D:/OPS2.db')
dm.add_driver('NE5000E', '1.0', 'xxx_Driver.py')
dm.delete_driver('NE5000E', '1.0')
dm.show_drivers()
print dm.find_driver('NE5000E', '1.0')
| HuaweiSNC/OPS2 | src/python/dao/driver_mgmt.py | Python | mit | 5,150 |
import sys
from Crypto.Cipher import AES, PKCS1_OAEP
from Crypto.PublicKey import RSA
from Crypto import Random
#AES key size
AES_KEY_SIZE = 32
# Uses null character as the padding character
PADDING_VALUE = '/0'
def padAES(message):
lacking_char_num = (AES.block_size - (len(message) % AES.block_size)) % AES.block_size
padded_message = message + lacking_char_num * PADDING_VALUE
return padded_message
def encryptAES(message):
# Get a random AES_BLOCK_SIZE byte key for AES
aes_key = Random.new().read(AES_KEY_SIZE)
# Initialization Vector
iv = Random.new().read(AES.block_size)
# Create a cipher using CFB mode
cipher = AES.new(aes_key, AES.MODE_CFB, iv)
# Encrypt the padded message
encrypted_msg = cipher.encrypt(padAES(message))
return [iv, aes_key, encrypted_msg]
def decryptAES(iv, aesKey, message):
#Create cipher
cipher = AES.new(aesKey, AES.MODE_CFB, iv)
#Decipher the message
decrypted_msg = cipher.decrypt(message)
# Strip padding chars
decrypted_msg = decrypted_msg.rstrip(PADDING_VALUE)
return decrypted_msg
def getRSAKey():
random_generator = Random.new().read
rsa_key = RSA.generate(1024, random_generator)
return rsa_key
def encryptRSA(message, rsaPU): #
encrypted_msg = rsaPU.encrypt(message, 32)[0]
return encrypted_msg
def decryptRSA(ciphertext, rsa_key):
msg = rsa_key.decrypt(ciphertext)
return msg
| 74105/aspp | crypto.py | Python | mit | 1,451 |
import pandas as pd
df = pd.read_csv('data/src/titanic_train.csv', index_col=0).drop(['Name', 'Ticket', 'SibSp', 'Parch'], axis=1)
print(df.head())
# Survived Pclass Sex Age Fare Cabin Embarked
# PassengerId
# 1 0 3 male 22.0 7.2500 NaN S
# 2 1 1 female 38.0 71.2833 C85 C
# 3 1 3 female 26.0 7.9250 NaN S
# 4 1 1 female 35.0 53.1000 C123 S
# 5 0 3 male 35.0 8.0500 NaN S
print(pd.crosstab(df['Sex'], df['Pclass']))
# Pclass 1 2 3
# Sex
# female 94 76 144
# male 122 108 347
print(type(pd.crosstab(df['Sex'], df['Pclass'])))
# <class 'pandas.core.frame.DataFrame'>
print(pd.crosstab([df['Sex'], df['Survived']], [df['Pclass'], df['Embarked']]))
# Pclass 1 2 3
# Embarked C Q S C Q S C Q S
# Sex Survived
# female 0 1 0 2 0 0 6 8 9 55
# 1 42 1 46 7 2 61 15 24 33
# male 0 25 1 51 8 1 82 33 36 231
# 1 17 0 28 2 0 15 10 3 34
print(pd.crosstab([df['Sex'], df['Survived']], [df['Pclass'], df['Embarked']],
margins=True))
# Pclass 1 2 3 All
# Embarked C Q S C Q S C Q S
# Sex Survived
# female 0 1 0 2 0 0 6 8 9 55 81
# 1 42 1 46 7 2 61 15 24 33 231
# male 0 25 1 51 8 1 82 33 36 231 468
# 1 17 0 28 2 0 15 10 3 34 109
# All 85 2 127 17 3 164 66 72 353 889
print(pd.crosstab([df['Sex'], df['Survived']], [df['Pclass'], df['Embarked']],
margins=True, margins_name='Total'))
# Pclass 1 2 3 Total
# Embarked C Q S C Q S C Q S
# Sex Survived
# female 0 1 0 2 0 0 6 8 9 55 81
# 1 42 1 46 7 2 61 15 24 33 231
# male 0 25 1 51 8 1 82 33 36 231 468
# 1 17 0 28 2 0 15 10 3 34 109
# Total 85 2 127 17 3 164 66 72 353 889
print(pd.crosstab(df['Sex'], df['Pclass'], margins=True, normalize=True))
# Pclass 1 2 3 All
# Sex
# female 0.105499 0.085297 0.161616 0.352413
# male 0.136925 0.121212 0.389450 0.647587
# All 0.242424 0.206510 0.551066 1.000000
print(pd.crosstab(df['Sex'], df['Pclass'], margins=True, normalize='index'))
# Pclass 1 2 3
# Sex
# female 0.299363 0.242038 0.458599
# male 0.211438 0.187175 0.601386
# All 0.242424 0.206510 0.551066
print(pd.crosstab(df['Sex'], df['Pclass'], margins=True, normalize='columns'))
# Pclass 1 2 3 All
# Sex
# female 0.435185 0.413043 0.293279 0.352413
# male 0.564815 0.586957 0.706721 0.647587
# print(pd.crosstab(df['Sex'], [df['Pclass'], df['Embarked']],
# margins=True, normalize=True))
# TypeError: Expected tuple, got str
print(pd.crosstab(df['Sex'], [df['Pclass'], df['Embarked']],
margins=True, normalize='index'))
# Pclass 1 2 \
# Embarked C Q S C Q S
# Sex
# female 0.137821 0.003205 0.153846 0.022436 0.006410 0.214744
# male 0.072790 0.001733 0.136915 0.017331 0.001733 0.168111
# All 0.095613 0.002250 0.142857 0.019123 0.003375 0.184477
# Pclass 3
# Embarked C Q S
# Sex
# female 0.073718 0.105769 0.282051
# male 0.074523 0.067591 0.459272
# All 0.074241 0.080990 0.397075
# print(pd.crosstab(df['Sex'], [df['Pclass'], df['Embarked']],
# margins=True, normalize='columns'))
# ValueError: Length of new names must be 1, got 2
print(pd.crosstab(df['Sex'], [df['Pclass'], df['Embarked']], normalize=True))
# Pclass 1 2 \
# Embarked C Q S C Q S
# Sex
# female 0.048369 0.001125 0.053993 0.007874 0.002250 0.075366
# male 0.047244 0.001125 0.088864 0.011249 0.001125 0.109111
# Pclass 3
# Embarked C Q S
# Sex
# female 0.025872 0.03712 0.098988
# male 0.048369 0.04387 0.298088
print(pd.crosstab(df['Sex'], [df['Pclass'], df['Embarked']], normalize='index'))
# Pclass 1 2 \
# Embarked C Q S C Q S
# Sex
# female 0.137821 0.003205 0.153846 0.022436 0.006410 0.214744
# male 0.072790 0.001733 0.136915 0.017331 0.001733 0.168111
# Pclass 3
# Embarked C Q S
# Sex
# female 0.073718 0.105769 0.282051
# male 0.074523 0.067591 0.459272
print(pd.crosstab(df['Sex'], [df['Pclass'], df['Embarked']], normalize='columns'))
# Pclass 1 2 3 \
# Embarked C Q S C Q S C
# Sex
# female 0.505882 0.5 0.377953 0.411765 0.666667 0.408537 0.348485
# male 0.494118 0.5 0.622047 0.588235 0.333333 0.591463 0.651515
# Pclass
# Embarked Q S
# Sex
# female 0.458333 0.249292
# male 0.541667 0.750708
| nkmk/python-snippets | notebook/pandas_crosstab.py | Python | mit | 6,511 |
phone = "315-555-2955"
print "Area Code: {0}".format(phone[0:3])
print "Local: {0}".format(phone[4:])
print "Different format: ({0}) {1}".format(phone[0:3], phone[4:])
| codelikeagirlcny/python-lessons-cny | code-exercises-etc/section_02_(strings)/z.ajm.str-format-phone-ex.20151024.py | Python | mit | 169 |
"""
Definition of the plugin.
"""
from django.utils.translation import ugettext_lazy as _
from fluent_contents.extensions import ContentPlugin, plugin_pool
from . import models
@plugin_pool.register
class LocationPlugin(ContentPlugin):
model = models.LocationItem
category = _('Assets')
render_template = 'icekit/plugins/location/item.html'
raw_id_fields = ['location', ]
| ic-labs/django-icekit | icekit/plugins/location/content_plugins.py | Python | mit | 391 |
#!/usr/bin/env python3
# Copyright (c) 2015-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the ZMQ API."""
import configparser
import os
import struct
from test_framework.test_framework import StatusquoTestFramework, SkipTest
from test_framework.util import (assert_equal,
bytes_to_hex_str,
)
class ZMQTest (StatusquoTestFramework):
def __init__(self):
super().__init__()
self.num_nodes = 2
def setup_nodes(self):
# Try to import python3-zmq. Skip this test if the import fails.
try:
import zmq
except ImportError:
raise SkipTest("python3-zmq module not available.")
# Check that statusquo has been built with ZMQ enabled
config = configparser.ConfigParser()
if not self.options.configfile:
self.options.configfile = os.path.dirname(__file__) + "/../config.ini"
config.read_file(open(self.options.configfile))
if not config["components"].getboolean("ENABLE_ZMQ"):
raise SkipTest("statusquod has not been built with zmq enabled.")
self.zmqContext = zmq.Context()
self.zmqSubSocket = self.zmqContext.socket(zmq.SUB)
self.zmqSubSocket.set(zmq.RCVTIMEO, 60000)
self.zmqSubSocket.setsockopt(zmq.SUBSCRIBE, b"hashblock")
self.zmqSubSocket.setsockopt(zmq.SUBSCRIBE, b"hashtx")
ip_address = "tcp://127.0.0.1:26121"
self.zmqSubSocket.connect(ip_address)
extra_args = [['-zmqpubhashtx=%s' % ip_address, '-zmqpubhashblock=%s' % ip_address], []]
self.nodes = self.start_nodes(self.num_nodes, self.options.tmpdir, extra_args)
def run_test(self):
try:
self._zmq_test()
finally:
# Destroy the zmq context
self.log.debug("Destroying zmq context")
self.zmqContext.destroy(linger=None)
def _zmq_test(self):
genhashes = self.nodes[0].generate(1)
self.sync_all()
self.log.info("Wait for tx")
msg = self.zmqSubSocket.recv_multipart()
topic = msg[0]
assert_equal(topic, b"hashtx")
body = msg[1]
msgSequence = struct.unpack('<I', msg[-1])[-1]
assert_equal(msgSequence, 0) # must be sequence 0 on hashtx
self.log.info("Wait for block")
msg = self.zmqSubSocket.recv_multipart()
topic = msg[0]
body = msg[1]
msgSequence = struct.unpack('<I', msg[-1])[-1]
assert_equal(msgSequence, 0) # must be sequence 0 on hashblock
blkhash = bytes_to_hex_str(body)
assert_equal(genhashes[0], blkhash) # blockhash from generate must be equal to the hash received over zmq
self.log.info("Generate 10 blocks (and 10 coinbase txes)")
n = 10
genhashes = self.nodes[1].generate(n)
self.sync_all()
zmqHashes = []
blockcount = 0
for x in range(n * 2):
msg = self.zmqSubSocket.recv_multipart()
topic = msg[0]
body = msg[1]
if topic == b"hashblock":
zmqHashes.append(bytes_to_hex_str(body))
msgSequence = struct.unpack('<I', msg[-1])[-1]
assert_equal(msgSequence, blockcount + 1)
blockcount += 1
for x in range(n):
assert_equal(genhashes[x], zmqHashes[x]) # blockhash from generate must be equal to the hash received over zmq
self.log.info("Wait for tx from second node")
# test tx from a second node
hashRPC = self.nodes[1].sendtoaddress(self.nodes[0].getnewaddress(), 1.0)
self.sync_all()
# now we should receive a zmq msg because the tx was broadcast
msg = self.zmqSubSocket.recv_multipart()
topic = msg[0]
body = msg[1]
assert_equal(topic, b"hashtx")
hashZMQ = bytes_to_hex_str(body)
msgSequence = struct.unpack('<I', msg[-1])[-1]
assert_equal(msgSequence, blockcount + 1)
assert_equal(hashRPC, hashZMQ) # txid from sendtoaddress must be equal to the hash received over zmq
if __name__ == '__main__':
ZMQTest().main()
| Exgibichi/statusquo | test/functional/zmq_test.py | Python | mit | 4,305 |
# Derived from keras-rl
import opensim as osim
import numpy as np
import sys
from keras.models import Sequential, Model
from keras.layers import Dense, Activation, Flatten, Input, concatenate
from keras.optimizers import Adam
import numpy as np
from rl.agents import DDPGAgent
from rl.memory import SequentialMemory
from rl.random import OrnsteinUhlenbeckProcess
from osim.env import *
from osim.http.client import Client
from keras.optimizers import RMSprop
import argparse
import math
# Command line parameters
parser = argparse.ArgumentParser(description='Train or test neural net motor controller')
parser.add_argument('--train', dest='train', action='store_true', default=True)
parser.add_argument('--test', dest='train', action='store_false', default=True)
parser.add_argument('--steps', dest='steps', action='store', default=10000, type=int)
parser.add_argument('--visualize', dest='visualize', action='store_true', default=False)
parser.add_argument('--model', dest='model', action='store', default="example.h5f")
parser.add_argument('--token', dest='token', action='store', required=False)
args = parser.parse_args()
# Load walking environment
env = RunEnv(args.visualize)
env.reset()
nb_actions = env.action_space.shape[0]
# Total number of steps in training
nallsteps = args.steps
# Create networks for DDPG
# Next, we build a very simple model.
actor = Sequential()
actor.add(Flatten(input_shape=(1,) + env.observation_space.shape))
actor.add(Dense(32))
actor.add(Activation('relu'))
actor.add(Dense(32))
actor.add(Activation('relu'))
actor.add(Dense(32))
actor.add(Activation('relu'))
actor.add(Dense(nb_actions))
actor.add(Activation('sigmoid'))
print(actor.summary())
action_input = Input(shape=(nb_actions,), name='action_input')
observation_input = Input(shape=(1,) + env.observation_space.shape, name='observation_input')
flattened_observation = Flatten()(observation_input)
x = concatenate([action_input, flattened_observation])
x = Dense(64)(x)
x = Activation('relu')(x)
x = Dense(64)(x)
x = Activation('relu')(x)
x = Dense(64)(x)
x = Activation('relu')(x)
x = Dense(1)(x)
x = Activation('linear')(x)
critic = Model(inputs=[action_input, observation_input], outputs=x)
print(critic.summary())
# Set up the agent for training
memory = SequentialMemory(limit=100000, window_length=1)
random_process = OrnsteinUhlenbeckProcess(theta=.15, mu=0., sigma=.2, size=env.noutput)
agent = DDPGAgent(nb_actions=nb_actions, actor=actor, critic=critic, critic_action_input=action_input,
memory=memory, nb_steps_warmup_critic=100, nb_steps_warmup_actor=100,
random_process=random_process, gamma=.99, target_model_update=1e-3,
delta_clip=1.)
# agent = ContinuousDQNAgent(nb_actions=env.noutput, V_model=V_model, L_model=L_model, mu_model=mu_model,
# memory=memory, nb_steps_warmup=1000, random_process=random_process,
# gamma=.99, target_model_update=0.1)
agent.compile(Adam(lr=.001, clipnorm=1.), metrics=['mae'])
# Okay, now it's time to learn something! We visualize the training here for show, but this
# slows down training quite a lot. You can always safely abort the training prematurely using
# Ctrl + C.
if args.train:
agent.fit(env, nb_steps=nallsteps, visualize=False, verbose=1, nb_max_episode_steps=env.timestep_limit, log_interval=10000)
# After training is done, we save the final weights.
agent.save_weights(args.model, overwrite=True)
# If TEST and TOKEN, submit to crowdAI
if not args.train and args.token:
agent.load_weights(args.model)
# Settings
remote_base = 'http://grader.crowdai.org:1729'
client = Client(remote_base)
# Create environment
observation = client.env_create(args.token)
# Run a single step
# The grader runs 3 simulations of at most 1000 steps each. We stop after the last one
while True:
v = np.array(observation).reshape((env.observation_space.shape[0]))
action = agent.forward(v)
[observation, reward, done, info] = client.env_step(action.tolist())
if done:
observation = client.env_reset()
if not observation:
break
client.submit()
# If TEST and no TOKEN, run some test experiments
if not args.train and not args.token:
agent.load_weights(args.model)
# Finally, evaluate our algorithm for 1 episode.
agent.test(env, nb_episodes=1, visualize=False, nb_max_episode_steps=500)
| stanfordnmbl/osim-rl | examples/legacy/example.py | Python | mit | 4,483 |
from abstract_importer import AbstractImporter
from slugify import slugify
class KosovoImporter(AbstractImporter):
def __init__(self):
pass
def get_csv_filename(self):
return "importer/data/kosovo/kosovo-budget-expenditures-2014.csv"
def get_region(self):
return 'Kosovo'
def get_dataset(self):
return 'Budget Expenditure (2014)'
def build_docs(self, row):
# In this case, it's because in the CSV doc there is a column for each year...
year = row[3]
# Clean expense string so that is is numerical (e.g. turn blank string to 0).
cost = row[2].replace(',', '')
if not cost.strip():
cost = 0
# Create doc.
doc = {
'region': {
'name': self.get_region(),
'slug': slugify(self.get_region(), to_lower=True)
},
'dataset': {
'name': self.get_dataset(),
'slug': slugify(self.get_dataset(), to_lower=True)
},
'activity': {
'type': row[0],
'description': row[1]
},
'cost': float(cost),
'year': int(year)
}
# Console output to provide user with feedback on status of importing process.
print '%s - %s: %s (%s %i)' % (doc['activity']['type'], doc['activity']['description'], doc['cost'], doc['region']['name'], doc['year'])
return [doc] | opendatakosovo/relate-with-it | importer/kosovo_importer.py | Python | mit | 1,479 |
"""
SoftLayer.tests.managers.ordering_tests
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:license: MIT, see LICENSE for more details.
"""
import SoftLayer
from SoftLayer import testing
from SoftLayer.testing import fixtures
class OrderingTests(testing.TestCase):
def set_up(self):
self.ordering = SoftLayer.OrderingManager(self.client)
def test_get_package_by_type_returns_no_outlet_packages(self):
packages = self._get_server_packages()
filtered_packages = self.ordering.filter_outlet_packages(packages)
for package_id in [27, 28]:
self._assert_package_id_not_present(package_id, filtered_packages)
def _get_server_packages(self):
return self.ordering.get_packages_of_type(['BARE_METAL_CPU'])
def _assert_package_id_not_present(self, package_id, packages):
package_ids = []
for package in packages:
package_ids.append(package['id'])
self.assertNotIn(package_id, package_ids)
def test_get_active_packages(self):
packages = self._get_server_packages()
filtered_packages = self.ordering.get_only_active_packages(packages)
for package_id in [15]:
self._assert_package_id_not_present(package_id, filtered_packages)
def test_get_package_by_type_returns_if_found(self):
package_type = "BARE_METAL_CORE"
mask = "mask[id, name]"
package = self.ordering.get_package_by_type(package_type, mask)
self.assertIsNotNone(package)
def test_get_package_by_type_returns_none_if_not_found(self):
mock = self.set_mock('SoftLayer_Product_Package', 'getAllObjects')
mock.return_value = []
package = self.ordering.get_package_by_type("PIZZA_FLAVORED_SERVERS")
self.assertIsNone(package)
def test_get_package_id_by_type_returns_valid_id(self):
mock = self.set_mock('SoftLayer_Product_Package', 'getAllObjects')
mock.return_value = [
{'id': 46, 'name': 'Virtual Servers',
'description': 'Virtual Server Instances',
'type': {'keyName': 'VIRTUAL_SERVER_INSTANCE'}, 'isActive': 1},
]
package_type = "VIRTUAL_SERVER_INSTANCE"
package_id = self.ordering.get_package_id_by_type(package_type)
self.assertEqual(46, package_id)
def test_get_package_id_by_type_fails_for_nonexistent_package_type(self):
mock = self.set_mock('SoftLayer_Product_Package', 'getAllObjects')
mock.return_value = []
with self.assertRaises(ValueError):
self.ordering.get_package_id_by_type("STRAWBERRY_FLAVORED_SERVERS")
def test_get_order_container(self):
container = self.ordering.get_order_container(1234)
quote = self.ordering.client['Billing_Order_Quote']
container_fixture = quote.getRecalculatedOrderContainer(id=1234)
self.assertEqual(container, container_fixture['orderContainers'][0])
def test_get_quotes(self):
quotes = self.ordering.get_quotes()
quotes_fixture = self.ordering.client['Account'].getActiveQuotes()
self.assertEqual(quotes, quotes_fixture)
def test_get_quote_details(self):
quote = self.ordering.get_quote_details(1234)
quote_service = self.ordering.client['Billing_Order_Quote']
quote_fixture = quote_service.getObject(id=1234)
self.assertEqual(quote, quote_fixture)
def test_verify_quote(self):
result = self.ordering.verify_quote(1234,
[{'hostname': 'test1',
'domain': 'example.com'}],
quantity=1)
self.assertEqual(result, fixtures.SoftLayer_Product_Order.verifyOrder)
self.assert_called_with('SoftLayer_Product_Order', 'verifyOrder')
def test_order_quote(self):
result = self.ordering.order_quote(1234,
[{'hostname': 'test1',
'domain': 'example.com'}],
quantity=1)
self.assertEqual(result, fixtures.SoftLayer_Product_Order.placeOrder)
self.assert_called_with('SoftLayer_Product_Order', 'placeOrder')
def test_generate_order_template(self):
result = self.ordering.generate_order_template(
1234, [{'hostname': 'test1', 'domain': 'example.com'}], quantity=1)
self.assertEqual(result, {'presetId': None,
'hardware': [{'domain': 'example.com',
'hostname': 'test1'}],
'useHourlyPricing': '',
'packageId': 50,
'prices': [{'id': 1921}],
'quantity': 1})
def test_generate_order_template_extra_quantity(self):
with self.assertRaises(ValueError):
self.ordering.generate_order_template(1234, [], quantity=1)
| cloudify-cosmo/softlayer-python | SoftLayer/tests/managers/ordering_tests.py | Python | mit | 5,044 |
"""
POZ Development Application.
"""
import numpy as np
# import cv2
import pozutil as pu
import test_util as tpu
def perspective_test(_y, _z, _ele, _azi):
print "--------------------------------------"
print "Perspective Transform tests"
print
cam = pu.CameraHelper()
# some landmarks in a 3x3 grid pattern
p0 = np.float32([-1., _y - 1.0, _z])
p1 = np.float32([0., _y - 1.0, _z])
p2 = np.float32([1., _y - 1.0, _z])
p3 = np.float32([-1., _y + 1.0, _z])
p4 = np.float32([0., _y + 1.0, _z])
p5 = np.float32([1., _y + 1.0, _z])
p6 = np.float32([-1., _y, _z])
p7 = np.float32([0, _y, _z])
p8 = np.float32([1., _y, _z])
# 3x3 grid array
ppp = np.array([p0, p1, p2, p3, p4, p5, p6, p7, p8])
print "Here are some landmarks in world"
print ppp
puv_acc = []
quv_acc = []
for vp in ppp:
# original view of landmarks
u, v = cam.project_xyz_to_uv(vp)
puv_acc.append(np.float32([u, v]))
# rotated view of landmarks
xyz_r = pu.calc_xyz_after_rotation_deg(vp, _ele, _azi, 0)
u, v = cam.project_xyz_to_uv(xyz_r)
quv_acc.append(np.float32([u, v]))
puv = np.array(puv_acc)
quv = np.array(quv_acc)
# 4-pt "diamond" array
quv4 = np.array([quv[1], quv[4], quv[6], quv[8]])
puv4 = np.array([puv[1], puv[4], puv[6], puv[8]])
print
print "Landmark img coords before rotate:"
print puv
print "Landmark img coords after rotate:"
print quv
print quv4
print
# h, _ = cv2.findHomography(puv, quv)
# hh = cv2.getPerspectiveTransform(puv4, quv4)
# print h
# print hh
# perspectiveTransform needs an extra dimension
puv1 = np.expand_dims(puv, axis=0)
# print "Test perspectiveTransform with findHomography matrix:"
# xpersp = cv2.perspectiveTransform(puv1, h)
# print xpersp
# print "Test perspectiveTransform with getPerspectiveTransform matrix:"
# xpersp = cv2.perspectiveTransform(puv1, hh)
# print xpersp
# print
if __name__ == "__main__":
# robot always knows the Y and Elevation of its camera
# (arbitrary assignments for testing)
known_cam_y = -3.
known_cam_el = 0.0
tests = [(1., 1., tpu.lm_vis_1_1),
(7., 6., tpu.lm_vis_7_6)]
print "--------------------------------------"
print "Landmark Test"
print
test_index = 0
vis_map = tests[test_index][2]
# robot does not know its (X, Z) position
# it will have to solve for it
cam_x = tests[test_index][0]
cam_z = tests[test_index][1]
print "Known (X,Z): ", (cam_x, cam_z)
for key in sorted(vis_map.keys()):
cam_azim = vis_map[key].az + 0. # change offset for testing
cam_elev = vis_map[key].el + known_cam_el
print "-----------"
# print "Known Camera Elev =", cam_elev
xyz = [cam_x, known_cam_y, cam_z]
angs = [cam_azim, cam_elev]
print "Landmark {:s}. Camera Azim = {:8.2f}".format(key, cam_azim)
lm1 = tpu.mark1[key]
f, x, z, a = tpu.landmark_test(lm1, tpu.mark2[key], xyz, angs)
print "Robot is at: {:6.3f},{:6.3f},{:20.14f}".format(x, z, a)
f, x, z, a = tpu.landmark_test(lm1, tpu.mark3[key], xyz, angs)
print "Robot is at: {:6.3f},{:6.3f},{:20.14f}".format(x, z, a)
tpu.pnp_test(key, xyz, angs)
| mwgit00/poz | poz.py | Python | mit | 3,487 |
"""
This file is part of pyCMBS.
(c) 2012- Alexander Loew
For COPYING and LICENSE details, please refer to the LICENSE file
"""
"""
development script for pattern correlation analysis
"""
from pycmbs.diagnostic import PatternCorrelation
from pycmbs.data import Data
import numpy as np
import matplotlib.pyplot as plt
plt.close('all')
fname = '../pycmbs/examples/example_data/air.mon.mean.nc'
# generate two datasets
x = Data(fname, 'air', read=True)
xc = x.get_climatology(return_object=True)
yc = xc.copy()
yc.data = yc.data * np.random.random(yc.shape)*10.
PC = PatternCorrelation(xc, yc)
PC.plot()
plt.show()
| pygeo/pycmbs | scripts/pattern_correlation.py | Python | mit | 619 |
from frontend import app
from flask import render_template
from flask import send_from_directory
from flask import request
from flask import redirect
from flask import url_for
from flask import flash
from flask import abort
import os
import models
import forms
from wtfpeewee.orm import model_form
@app.route('/register/', methods=['GET', 'POST'])
def register():
Form = forms.ManualRegisterForm(request.values)
if request.method == 'POST':
if Form.submit.data:
saveFormsToModels(Form)
return redirect(url_for('register'))
return render_template('frontpage.html',
form = Form,
)
@app.route('/add/<modelname>/', methods=['GET', 'POST'])
def add(modelname):
kwargs = listAndEdit(modelname)
return render_template('editpage.html', **kwargs)
@app.route('/add/<modelname>/to/<foreign_table>/<foreign_key>', methods=['GET', 'POST'])
def addto(modelname, foreign_table, foreign_key):
kwargs = listAndEdit(modelname,
action = 'AddTo',
foreign_table = foreign_table,
foreign_key = foreign_key)
return render_template('editpage.html', **kwargs)
@app.route('/edit/<modelname>/<entryid>', methods=['GET', 'POST'])
def edit(modelname, entryid):
kwargs = listAndEdit(modelname, entryid)
#print kwargs
return render_template('editpage.html', **kwargs)
def saveFormsToModels(form):
# needs the form fields to be named modelname_fieldname
editedModels = {}
foreignKeys = []
for formfield in form.data:
if formfield in ['csrf_token']:
continue
try:
modelname, field = formfield.split('_')
except:
continue
value = form[formfield].data
try:
functionName, foreignKeyName = value.split('_')
if functionName == 'ForeignKey':
foreignKeys.append(
dict(
modelname = modelname,
field = field,
foreignKeyName = foreignKeyName,
)
)
continue
except:
pass
try:
setattr(editedModels[modelname], field, value)
except:
editedModels[modelname] = models.ALL_MODELS_DICT[modelname]()
setattr(editedModels[modelname], field, value)
for model in editedModels:
editedModels[model].save()
for key in foreignKeys:
setattr(
editedModels[key['modelname']],
key['field'],
editedModels[key['foreignKeyName']])
print 'start'
print 'Set attr: {}, {}, {}'.format(
editedModels[key['modelname']],
key['field'],
editedModels[key['foreignKeyName']])
for model in editedModels:
editedModels[model].save()
def getFields(model, exclude=['id']):
foreignKeys = {x.column : x.dest_table for x in models.db.get_foreign_keys(model.__name__)}
#fields = [(x, type(model._meta.fields[x]).__name__, foreignKeys) for x in model._meta.sorted_field_names if not x in exclude]
#print foreignKeys
fields = []
for field in model._meta.sorted_field_names:
if not field in exclude:
fieldtype = type(model._meta.fields[field]).__name__
foreignFieldName = '{}_id'.format(field)
if foreignFieldName in foreignKeys:
foreignKeyModelName = foreignKeys[foreignFieldName].title()
else:
foreignKeyModelName = False
fields.append(
(field, fieldtype, foreignKeyModelName))
#print "Field: {}\nType: {}\nModelname: {}\n".format(field, fieldtype, foreignKeyModelName)
return fields
def getRelatedModels(entry):
entries = {}
models = []
try:
for query, fk in reversed(list(entry.dependencies())):
#for x in dir(fk):
#print x
for x in fk.model_class.select().where(query):
#print 'here:'
#print x
modelname = fk.model_class.__name__
try:
entries[modelname].append(x)
except:
models.append(modelname)
entries[modelname] = []
entries[modelname].append(x)
#entries.append((fk.model_class.__name__, x))
except:
pass
return (models, entries)
def listAndEdit(modelname, entryid = 0, entries = False, action = False, **kwargs):
try:
model = models.ALL_MODELS_DICT[modelname]
except KeyError:
abort(404)
if not entries:
entries = model.select()
modelForm = model_form(model)
fields = getFields(model)
try:
entry = model.get(id=int(entryid))
dependencies = getRelatedModels(entry)
except:
entry = model()
dependencies = False
form = modelForm(obj = entry)
if request.method == 'POST':
if request.form['submit'] == 'Save':
form = modelForm(request.values, obj = entry)
if form.validate():
form.populate_obj(entry)
entry.save()
if action == 'AddTo':
addForeignKey(model, entry, kwargs['foreign_table'], kwargs['foreign_key'])
redirect(url_for('edit', modelname = model, entryid = kwargs['foreign_key']))
flash('Your entry has been saved')
print 'saved'
elif request.form['submit'] == 'Delete':
try:
model.get(model.id == int(entryid)).delete_instance(recursive = True)
#redirect(url_for('add', modelname = modelname))
except:
pass
finally:
entry = model()
form = modelForm(obj = entry)
kwargs = dict(
links = [x.__name__ for x in models.ALL_MODELS],
header = model.__name__,
form=form,
entry=entry,
entries=entries,
fields = fields,
dependencies = dependencies,
)
return kwargs
def addForeignKey(model, entry, foreign_table, foreign_key):
foreignModel = models.ALL_MODELS_DICT[foreign_table]
foreignItem = foreignModel.get(foreignModel.id == int(foreign_key))
foreignFieldName = model.__name__.lower()
print "entry = {}".format(foreignModel)
print "item = {}".format(foreignItem)
print "fieldName = {}".format(foreignFieldName)
print "id = {}".format(entry.id)
setattr(foreignItem, foreignFieldName, entry.id)
foreignItem.save()
@app.route('/favicon.ico')
def favicon():
return send_from_directory(
os.path.join(app.root_path, 'static'), 'favicon.png', mimetype='image/vnd.microsoft.icon')
| maltonx/workforce | views.py | Python | mit | 7,037 |
import sys
import re
def import_file(lines):
tags_label = "TAGS: "
separator = 60*"-"
idx = 0
while idx < len(lines):
assert lines[idx].startswith(tags_label)
tags = lines[idx][len(tags_label):].split(",")
tags = [t.strip() for t in tags if t.strip()]
idx += 1
body = []
while idx < len(lines) and not lines[idx].startswith(separator):
body.append(lines[idx])
idx += 1
idx += 1 # skip separator
import pypandoc
body = "\n".join(body)
body = pypandoc.convert(body, "org", format="markdown_phpextra")
if tags:
lineend = body.find("\n")
if lineend == -1:
lineend = len(body)
tags_str = " " + ":%s:" % (":".join(tags))
body = body[:lineend] + tags_str + body[lineend:]
body = "** " + re.sub(r"^\*+ ", "", body)
print(body)
def main():
with open(sys.argv[1], "r") as inf:
lines = list(inf)
import_file(lines)
if __name__ == "__main__":
main()
| inducer/synoptic | synoptic-to-org.py | Python | mit | 1,087 |
# http://www.pythonchallenge.com/pc/def/equality.html
import re
file_ob = open("3.dat", 'r')
ob_read = file_ob.read()
read_arr = list(ob_read)
word = []
def for_loop(): # Loops through array to find solution
for i in range(len(read_arr)):
if (i + 8) > len(read_arr): # To keep index in bounds
break
if not(read_arr[i]).isupper() and (read_arr[i + 1]).isupper() and (read_arr[i + 2]).isupper() and (read_arr[i + 3]).isupper() and(read_arr[i + 4]).islower() and (read_arr[i + 5]).isupper() and (read_arr[i + 6]).isupper() and (read_arr[i + 7]).isupper() and not(read_arr[i + 8]).isupper():
word.append(read_arr[i + 4])
print "".join(word)
def reg_ex(): # Uses regex to find the pattern
print "".join( re.findall("[^A-Z][A-Z]{3}([a-z])[A-Z]{3}[^A-Z]", ob_read))
# for_loop()
# reg_ex()
| yarabarla/python-challenge | 3.py | Python | mit | 812 |
"""
WSGI config for berth project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "berth.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
| joealcorn/berth.cc | berth/wsgi.py | Python | mit | 385 |
from gitmostwanted.app import celery, db
from gitmostwanted.lib.github.api import user_starred, user_starred_star
from gitmostwanted.models.repo import Repo
from gitmostwanted.models.user import UserAttitude
@celery.task()
def repo_starred_star(user_id: int, access_token: str):
starred, code = user_starred(access_token)
if not starred:
return False
attitudes = UserAttitude.list_liked_by_user(user_id)
lst_in = [repo_like(s['full_name'], user_id) for s in starred
if not [a for a in attitudes if s['full_name'] == a.repo.full_name]]
lst_out = [user_starred_star(r.repo.full_name, access_token) for r in attitudes
if not [x for x in starred if x['full_name'] == r.repo.full_name]]
return len(lst_out), len(list(filter(None, lst_in)))
def repo_like(repo_name: str, uid: int):
repo = Repo.get_one_by_full_name(repo_name)
if not repo:
return None
db.session.merge(UserAttitude.like(uid, repo.id))
db.session.commit()
return repo.id
| kkamkou/gitmostwanted.com | gitmostwanted/tasks/github.py | Python | mit | 1,028 |
import demo
demo.main()
| jasset75/finengine | app.py | Python | mit | 25 |
from flask import render_template, redirect, request, url_for, flash
from flask.ext.login import login_user, current_user, logout_user, login_required
from . import auth
from ..models import User, AnonymousUser
from .forms import LoginForm, RegistrationForm, ChangePasswordForm, \
PasswordResetRequestForm, PasswordResetForm, ChangeEmailForm
from .. import db
from ..email import send_email
@auth.before_app_request
def before_request():
if current_user.is_authenticated(): current_user.ping()
if not current_user.confirmed and request.endpoint[:5] != 'auth.':
return redirect(url_for('auth.unconfirmed'))
@auth.route('/unconfirmed')
def unconfirmed():
if current_user.is_anonymous() or current_user.confirmed:
return redirect(url_for('main.index'))
return render_template('auth/unconfirmed.html')
@auth.route('/login', methods=['GET', 'POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
if user is not None and user.verify_password(form.password.data):
login_user(user, form.remember_me.data)
return redirect(request.args.get('next') or url_for('main.index'))
flash('Invalid username or password.')
return render_template('auth/login.html', form=form)
@auth.route('/logout')
@login_required
def logout():
logout_user()
flash('You have been logged out.')
return redirect(url_for('main.index'))
@auth.route('/register', methods=['GET', 'POST'])
def register():
form = RegistrationForm()
if form.validate_on_submit():
user = User(email=form.email.data,
username=form.username.data,
password=form.password.data)
db.session.add(user)
db.session.commit()
token = user.generate_confirmation_token()
send_email(user.email, 'Confirm Your Account',
'auth/email/confirm', user=user, token=token)
flash('A confirmation email has been sent to you by email.')
return redirect(url_for('auth.login'))
return render_template('auth/register.html', form=form)
@auth.route('/confirm/<token>')
@login_required
def confirm(token):
if current_user.confirmed:
return redirect(url_for('main.index'))
if current_user.confirm(token):
flash('You have confirmed your account. Thanks!')
else:
flash('The confirmation link is invalid or has expired.')
return redirect(url_for('main.index'))
@auth.route('/confirm')
@login_required
def resend_confirmation():
token = current_user.generate_confirmation_token()
send_email(current_user.email, 'Confirm Your Account',
'auth/email/confirm', user=current_user, token=token)
flash('A new confirmation email has been sent to you by email.')
return redirect(url_for('main.index'))
@auth.route('/change_password', methods=['GET', 'POST'])
@login_required
def change_password():
form = ChangePasswordForm()
if form.validate_on_submit():
if current_user.verify_password(form.old_password.data):
current_user.password = form.password.data
db.session.add(current_user)
flash('Your password has been updated.')
return redirect(url_for('main.index'))
else:
flash('Invalid password.')
return render_template("auth/change_password.html", form=form)
@auth.route('/reset', methods=['GET', 'POST'])
def password_reset_request():
if not current_user.is_anonymous():
return redirect(url_for('main.index'))
form = PasswordResetRequestForm()
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
if user:
token = user.generate_reset_token()
send_email(user.email, 'Reset Your Password',
'auth/email/reset_password',
user=user, token=token,
next=request.args.get('next'))
flash('An email with instructions to reset your password has been '
'sent to you.')
return redirect(url_for('auth.login'))
return render_template('auth/reset_password.html', form=form)
@auth.route('/reset/<token>', methods=['GET', 'POST'])
def password_reset(token):
if not current_user.is_anonymous():
return redirect(url_for('main.index'))
form = PasswordResetForm()
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
if user is None:
return redirect(url_for('main.index'))
if user.reset_password(token, form.password.data):
flash('Your password has been updated.')
return redirect(url_for('auth.login'))
else:
return redirect(url_for('main.index'))
return render_template('auth/reset_password.html', form=form)
@auth.route('/change_email', methods=['GET', 'POST'])
@login_required
def change_email_request():
form = ChangeEmailForm()
if form.validate_on_submit():
if current_user.verify_password(form.password.data):
new_email = form.email.data
token = current_user.generate_email_change_token(new_email)
send_email(new_email, 'Confirm your email address',
'auth/email/change_email',
user=current_user, token=token)
flash('An email with instructions to confirm your new email '
'address has been sent to you.')
return redirect(url_for('main.index'))
else:
flash('Invalid email or password.')
return render_template("auth/change_email.html", form=form)
@auth.route('/change_email/<token>')
@login_required
def change_email(token):
if current_user.change_email(token):
flash('Your email address has been updated.')
else:
flash('Invalid request.')
return redirect(url_for('main.index'))
| AguNnamdi/flask_microblog | app/auth/views.py | Python | mit | 5,982 |
from rhino.test import TestClient
from examples.build_url import app
client = TestClient(app.wsgi)
def test_index():
res = client.get('/')
assert res.code == 302
assert res.headers['Location'] == 'http://localhost/u:1/p:1'
def test_url():
res = client.get('/u:1/p:1')
assert 'http://localhost/u:1/p:1' in res.body
| trendels/rhino | test/examples/test_build_url.py | Python | mit | 339 |
"""
Allow to trace called methods and package
"""
import frida
import re
syms = []
def on_message(message, data):
global syms
global index, filename
if message['type'] == 'send':
if "SYM" in message["payload"]:
c = message["payload"].split(":")[1]
print c
syms.append(c)
else:
print("[*] {0}".format(message["payload"]))
else:
print(message)
def overload2params(x):
start = 97
params = []
count_re = re.compile('\((.*)\)')
arguments = count_re.findall(x)
if arguments[0]:
arguments = arguments[0]
arguments = arguments.replace(" ", "")
arguments = arguments.split(",")
for _ in arguments:
params.append(chr(start))
start += 1
return ",".join(params)
else:
return ""
def get_script():
jscode = """
Java.perform(function() {
var flagArray = [];
var randomfile = Java.use('java.io.RandomAccessFile');
var skip = true;
randomfile.seek.implementation = function(pos)
{
if (pos == 0){
skip = false;
}
return randomfile.seek.call(this, pos);
}
randomfile.writeChar.implementation = function(c)
{
if(skip || c == 10)
{
send("PARTIAL:"+flagArray.join(""));
}else{
send("index: "+c);
flagArray.push(String.fromCharCode(c))
send("SYM:"+String.fromCharCode(c));
}
return randomfile.writeChar.call(this, c);
}
});
"""
return jscode
def attach_to_process(proc_name):
done = False
process = None
while not done:
try:
process = frida.get_usb_device().attach(proc_name)
done = True
except Exception:
pass
return process
if __name__ == "__main__":
print "[+] Waiting for app called {0}".format("hackchallenge.ahe17.teamsik.org.romanempire")
process = attach_to_process("hackchallenge.ahe17.teamsik.org.romanempire")
script = get_script()
try:
script = process.create_script(script)
except frida.InvalidArgumentError as e:
message = e.args[0]
line = re.compile('Script\(line (\d+)\)')
line = int(line.findall(message)[0])
script = script.split("\n")
print "[-] Error on line {0}:\n{1}: {2}".format(line, line, script[line])
exit(0)
script.on('message', on_message)
print('[*] Attached on process')
print('[*] Press enter to exit...')
script.load()
try:
raw_input()
except KeyboardInterrupt:
pass
print "FLAG: " + "".join(syms) | mseclab/AHE17 | YouCanHideButYouCannotRun/multithreads.py | Python | mit | 2,670 |
#!/usr/bin/env python3
"""Simple log converter for SOTA
It inputs a simplified text log and converts it to SOTA CSV format.
The input is a simplified version which allows most of the data field
to be guessed by previous input.
Example of input file:
# lines starting with # are comments
# first line contains information about the activation
# multiple activations can be separated by a blank line
# blank lines right after the first line and between comments are not considered
[callsign] [date] SOTA-ref [YOFF-ref] [locator] [other notes] [...]
# fields are optional, they must be specified for the first time in a file
# after that thay will persist across activations
# if chases are also included the SOTA-ref must be set to *
# everything after the SOTA-ref is considered additional note
# and will not persist to next section (not even YOFF ref)
# one optional note is a type of contest if the SOTA operation was carried
# out within the rules of contest (for example Field-day), the type of contest
# should be specified in the format contes:_contest_type_ where _contest_type_
# will specify a rule file which determines the exchanges format and the
# scoring method (this is still need to be expanded)
# next lines hold qso data
[time] [callsign] [freq] [mode] [RST-sent] [RST-rcvd] [SOTA-ref] [notes]
# everything is optional, if not present the previous value will be reused
# however if some fields cannot be differentiated uniquely than it needs to be
# all present
# field rules:
# time will be in the format hhmm or hh:mm (numbers and optional colon)
# hour part is optional and first 0 is also optional
# examples
# 0810 or 08:10 complete time {08:10}
# 811 missing 0 {08:11}
# 9:2 missing 0s {09:02}
# 3 missing hour part {09:03}
# 05 missing hour part {09:05}
# 13 missing hour part {09:13}
# 4 missing hour part, minute less than previous, hour is incremented {10:04}
# callsign any combination of letters and numbers
# at least 1 number in the middle
# frequency decimal number in MHz n[.nnn][MHz]
# must be in a radio amateur band range
# mode a valid amateur radio mode
# RST's either RST or RS format based on mode
# if not present it is considered to be 59 or 599
# SOTA-ref is in format assoc/region-nnn
# anything else not fitting is considered notes
# a line is not allowed to consist only of notes
# further notes not meant for SOTA database can be commented out
"""
import sys
import re
from datetime import date
import os.path
import argparse
import json
from contest import Contest
import country
import qslinfo
class LogException(Exception):
def __init__(self, message, pos):
self.message = message
self.pos = pos
# string matching functions
call_prefix = r"(?:(?=.?[a-z])[0-9a-z]{1,2}(?:(?<=3d)a)?)"
call = re.compile(r"(?:"+call_prefix+r"[0-9]?/)?("+call_prefix+r"[0-9][a-z0-9]*)(?:/[0-9a-z]+){0,2}", re.I)
sota_ref = re.compile(r"[a-z0-9]{1,3}/[a-z]{2}-[0-9]{3}", re.I)
wwff_ref = re.compile(r"[a-z0-9]{1,2}f{2}-[0-9]{3,4}", re.I)
locator = re.compile(r"[a-x]{2}[0-9]{2}[a-x]{2}", re.I)
date_reg = re.compile(r"([0-9]{4})(?P<sep>[.-])([0-9]{2})(?P=sep)([0-9]{2})")
time_reg = re.compile(r"(?P<hour>0?[0-9]|1[0-9]|2[0-3])?((?(hour)[0-5]|[0-5]?)[0-9])")
freq = re.compile(r"((?:[0-9]+\.)?[0-9]+)([kMG]?Hz|[mc]?m)?")
rst = re.compile(r"[1-5][1-9][1-9]?")
word = re.compile(r"\S+")
contest = re.compile(r"contest:(\w+)\s*")
annotation = re.compile(r"[@%$]{1,2}")
def find_word(string, start=0):
"""Find the first word starting from `start` position
Return the word and the position before and after the word
"""
while start < len(string) and string[start].isspace():
start += 1
end = start
while end < len(string) and not string[end].isspace():
end += 1
return string[start:end], start, end
bands = {
'160m' : ( 1.8, 2.0 ),
'80m' : ( 3.5, 4.0 ),
'40m' : ( 7.0, 7.3 ),
'30m' : ( 10.1, 10.15 ),
'20m' : ( 14.0, 14.35 ),
'17m' : ( 18.068, 18.168 ),
'15m' : ( 21.0, 21.45 ),
'12m' : ( 24.89, 24.99 ),
'10m' : ( 28.0, 29.7 ),
'6m' : ( 50.0, 54.0 ),
'2m' : ( 144.0, 148.0 ),
'1.25m' : ( 219.0, 225.0 ),
'70cm' : ( 420.0, 450.0 ),
'35cm' : ( 902.0, 928.0 ),
'23cm' : ( 1240.0, 1300.0 ),
'13cm' : ( 2300.0, 2450.0 ),
'9cm' : ( 3400.0, 3475.0 ),
'6cm' : ( 5650.0, 5850.0 ),
'3cm' : ( 10000.0, 10500.0 ),
'1.25cm' : ( 24000.0, 24250.0 ),
'6mm' : ( 47000.0, 47200.0 ),
'4mm' : ( 75500.0, 81500.0 ),
'2.5mm' : ( 122250.0, 123000.0 ),
'2mm' : ( 134000.0, 141000.0 ),
'1mm' : ( 241000.0, 250000.0 ),
}
def match_freq(s):
# check if the string s is a correct amateur band frequency
# return the string if it is or False otherwise
# the string can either specify the frequency or the band
# specifying the band must contain the m unit as consacrated bands
# frequency can either specify the unit, or be a single number
# which is considered to be in MHz, if unit is not MHz if will
# be converted, or if missing will be added to output string
m = freq.fullmatch(s)
if not m:
return False
mul = 1.0
if m.group(2):
if s.endswith('m'):
if s in bands:
return s
else:
return False
if m.group(2) == kHz:
mul = 0.001
elif m.group(2) == GHz:
mul = 1000.0
n = float(m.group(1)) * mul
for f in bands.values():
if n >= f[0] and n <= f[1]:
if mul == 1.0:
return m.group(1) + 'MHz'
else:
return "{:.3f}MHz".format(n)
return False
def quote_text(string):
"""Quote a string by the CSV rules:
if the text contains commas, newlines or quotes it will be quoted
quotes inside the text will be doubled
"""
if not string:
return string
if ',' in string or '\n' in string or '"' in string:
# check if already quoted
if string[0] == '"' and string[-1] == '"':
# check if every inner quote is doubled
if '"' not in string[1:-1].replace('""', ''):
return string
# if not then inner part must be doubled
string = string[1:-1]
# double the inner quotes and quote string
string = '"{}"'.format(string.replace('"','""'))
return string
class Activation:
"""Class holding information about an activation or a chase
Activations contain information about the date and place of activation,
callsign used and all qsos.
Also a link to the previous activation is stored
In a chase multiple qsos can be merged from a single day.
"""
def __init__(self, string, prev=None):
"""Initialize the activation from the string
At least callsign, date, and sota reference are needed, other
information is optional.
If a previous activation is given then the callsign and date
can be preserved from it, but new sota reference is mandatory.
An asterisk instead of sota reference means a chase
"""
self.previous = prev
# start splitting the string into words
w, pos, end = find_word(string)
# callsign
m = call.fullmatch(w)
if m:
self.callsign = w.upper()
w, pos, end = find_word(string, end)
elif prev:
self.callsign = prev.callsign
else:
raise LogException("Error in activation definition, missing callsign", pos)
# date
m = date_reg.fullmatch(w)
if m:
try:
self.date = date(int(m.group(1)), int(m.group(3)), int(m.group(4)))
except ValueError:
raise LogException("Error in activation definition, invalid date format", pos)
w, pos, end = find_word(string, end)
elif prev:
self.date = prev.date
else:
raise LogException("Error in activation definition, missing date", pos)
# sota reference is mandatory
m = sota_ref.fullmatch(w)
if m:
self.ref = w.upper()
elif w == '*':
self.ref = ''
else:
raise LogException("Error in activation definition, invalid SOTA reference detected", pos)
notes = string[end:].strip()
m = contest.search(notes)
if m:
self.contest = Contest(m.group(1))
notes = notes[:m.start()] + notes[m.end():]
else:
self.contest = None
self.notes = notes
self.qsos = []
# TODO: other information
self.wwff = None
self.locator = None
def add_qso(self, string):
"""Add a QSO to list of qsos
Consider the last qso as the previous one for the new qso
"""
prev_qso = self.qsos[-1] if self.qsos else None
if self.contest:
self.qsos.append(QSO(string, prev_qso, self.contest.exchange))
else:
self.qsos.append(QSO(string, prev_qso))
def print_qsos(self, format='SOTA_v2', config=None, handle=None, qsl_info=None):
if self.previous:
self.previous.print_qsos(format, config, handle, qsl_info)
# TODO: trace, remove it from final code
#print("Processing {} from {} with callsign {}".format(
# "chase" if not self.ref else "activation of {}".format(self.ref),
# self.date.strftime("%Y-%m-%d"), self.callsign))
# TODO: only SOTA_v2 is understood as of now
if format == 'SOTA_v2':
sota_line = ['v2', self.callsign, self.ref, self.date.strftime("%d/%m/%Y")] + [''] * 6
for qso in self.qsos:
sota_line[4] = '{:02}{:02}'.format(qso.time[0], qso.time[1])
sota_line[5] = qso.freq
sota_line[6] = qso.mode
sota_line[7] = qso.callsign
sota_line[8] = getattr(qso, 'ref', '')
sota_line[9] = quote_text(qso.notes)
#sota_line[9] = quote_text(' '.join((qso.sent, qso.rcvd, qso.notes)))
print(','.join(sota_line), file=handle)
# contest format: if a contest was specified for an activation
# use the contest rules to determine the output format
elif format == 'contest' and self.contest:
self.contest.configure(self, config)
for qso in self.qsos:
self.contest.add_qso(self.callsign, self.date, qso)
print(self.contest, file=handle)
# qsl status format:
# group callsigns by country and add qsl marker:
# * - sent, but not confirmed yet
# ** - confirmed
# an additional config parameter is a dictionary with previous qsl
# information
elif format == 'qsl':
if not qsl_info:
qsl_info = qslinfo.QSL()
print_stat = True
else:
print_stat = False
qsl_info.add_qsos(self.qsos, self.date)
if print_stat:
qsl_info.print_stat(handle)
else:
raise ValueError("Unrecognized output format")
class QSO:
"""Class containing information about a qso
It is initialized from a string and a previous qso object.
Missing fields from the string are filled with data from previous qso
"""
def __init__(self, string, prev=None, exchange=None):
"""Initialize qso data with the following information:
time callsign freq mode rst_sent rest_rcvd SOTA_ref notes
"""
words = [(m.group(), m.start(), {}) for m in word.finditer(string)]
if not words:
raise LogException("Empty QSO", 0)
# try to match words into categories
for i,w in enumerate(words):
t = w[2]
# time
if i < 1:
m = time_reg.fullmatch(w[0])
if m:
t['time'] = (int(m.group(1)) if m.group(1) else None, int(m.group(2)))
# callsign
if i < 2:
m = call.fullmatch(w[0])
if m:
t['call'] = w[0].upper()
# freq
if i < 3:
m = match_freq(w[0])
if m:
t['freq'] = m
# mode
# TODO: add all possible modes and translations
if i < 4:
if w[0].lower() in ['cw', 'ssb', 'fm', 'am']:
t['mode'] = w[0].upper()
elif w[0].lower() in ['data', 'psk', 'psk31', 'psk63', 'rtty', 'fsk441', 'jt65', 'ft8']:
t['mode'] = 'Data'
elif w[0].lower() in ['other']:
t['mode'] = 'Other'
# rst
if i < 6:
m = rst.fullmatch(w[0])
if m:
t['rst'] = w[0]
# sota ref
m = sota_ref.fullmatch(w[0])
if m:
t['sota'] = w[0].upper()
# optional contest exchange
if exchange and i < 7:
m = exchange.fullmatch(w[0])
if m:
t['exch'] = w[0]
# annotation about QSLing
m = annotation.fullmatch(w[0])
if m:
t['qsl'] = (w[0][0], w[0][1:])
# now filter the type list
# print(words)
typeorder = ['time', 'call', 'freq', 'mode', 'rst', 'rst', 'exch', 'sota']
wlist = [None, None, None, None, None, None, None, None]
lastelem = -1
noteselem = 7
for i,w in enumerate(words):
for e in range(lastelem + 1, len(typeorder)):
if typeorder[e] in w[2]:
lastelem = e
wlist[e] = w
break
else:
noteselem = i
break
# try to move back multiple mapped words
felist = [(i+2,w) for i,w in enumerate(wlist[2:6]) if w]
for i in range(6,3,-1):
if wlist[i] is None and felist and typeorder[i] in felist[-1][1][2]:
wlist[i] = felist[-1][1]
wlist[felist[-1][0]] = None
felist.pop()
if felist and felist[-1][0] == i:
felist.pop()
# check for minimum change
if wlist[1] is None and wlist[2] is None and wlist[3] is None:
raise LogException("Invalid change from previous QSO", words[i][1])
# now recreate all elements
# time
if wlist[0] is None or wlist[0][2]['time'][0] is None:
if prev is None:
raise LogException("Missing time value", 0)
if wlist[0] is not None:
self.time = (prev.time[0], wlist[0][2]['time'][1])
if self.time[1] < prev.time[1]:
hour = self.time[0] + 1
if hour == 24:
hour = 0
self.time = (hour, self.time[1])
else:
self.time = prev.time
else:
self.time = wlist[0][2]['time']
# call
if wlist[1] is None:
if prev is None:
raise LogException("Missing callsign", 0)
self.callsign = prev.callsign
else:
self.callsign = wlist[1][2]['call']
# freq
if wlist[2] is None:
if prev is None:
raise LogException("Missing frequency", 0)
self.freq = prev.freq
else:
self.freq = wlist[2][2]['freq']
# mode
if wlist[3] is None:
if prev is None:
raise LogException("Missing mode", 0)
self.mode = prev.mode
else:
self.mode = wlist[3][2]['mode']
# rst
if self.mode == 'CW' or self.mode == 'Data':
def_rst = '599'
else:
def_rst = '59'
if wlist[4] is None:
self.sent = def_rst
else:
if len(wlist[4][2]['rst']) != len(def_rst):
raise LogException("Invalid RST for this mode", 0)
self.sent = wlist[4][2]['rst']
if wlist[5] is None:
self.rcvd = def_rst
else:
if len(wlist[5][2]['rst']) != len(def_rst):
raise LogException("Invalid RST for this mode", 0)
self.rcvd = wlist[5][2]['rst']
# optional exchange
if wlist[6] is not None:
self.exch = wlist[6][2]['exch']
# SOTA ref
if wlist[7] is not None:
self.ref = wlist[7][2]['sota']
# notes
if noteselem < len(words):
self.notes = ' '.join(x[0] for x in words[noteselem:] if 'qsl' not in x[2])
else:
self.notes = ''
# qsl info
q = [x[2]['qsl'] for x in words[noteselem:] if 'qsl' in x[2]]
if q:
self.qsl_sent = q[0][0]
self.qsl_rcvd = q[0][1]
# day adjustment for multiple day activation
if prev:
if prev.time[0] * 60 + prev.time[1] > self.time[0] * self.time[1]:
self.day = prev.day + 1
else:
self.day = prev.day
else:
self.day = 0
def parse_input(input_handle, output_handle=None, output_name='', **params):
comment_line = False
blank_line = False
possible_blank_line = False
activation = None
qso = None
errors = []
cnt = 0
# go though the lines
for line in input_handle:
cnt += 1
s,d,c = line.partition('#')
s = s.strip()
if not s:
if d:
possible_blank_line = False
comment_line = True
elif activation and activation.qsos:
if comment_line:
possible_blank_line = True
comment_line = False
else:
blank_line = True
continue
comment_line = False
if possible_blank_line:
blank_line = True
possible_blank_line = False
# normal line found
# if previous line was a blank line
try:
if blank_line or not activation:
activation = Activation(s, activation)
blank_line = False
else:
activation.add_qso(s)
except LogException as e:
errors.append((cnt, str(e), s, e.pos))
# if any error found, print it on stderr
if errors:
for e in errors:
print("{}:{}: {}\n {}\n {:>{}}".format(
input_handle.name, e[0], e[1], e[2], '^', e[3] + 1),
file=sys.stderr)
else:
if output_handle:
activation.print_qsos(handle=output_handle, **params)
elif output_name:
filename = output_name.format(
callsign = call.fullmatch(activation.callsign).group(1),
file = os.path.splitext(os.path.basename(input_handle.name))[0],
ext = activation.contest.output.ext if params.get('format') == 'contest' else 'csv'
)
with open(filename, 'w', encoding='utf-8') as f:
activation.print_qsos(handle=f, **params)
else:
activation.print_qsos(**params)
if __name__ == '__main__':
# parse arguments
parser = argparse.ArgumentParser(description='Simple log converter for creating SOTA csv, Cabrillo, etc. from a simplified log file.')
parser.add_argument('files', metavar='FILE', nargs='*',
help='Log file to be processed. If no file is present the standard input is used. If both some files and the standard input is needed use `-` to add standard input to the list of files')
format_group = parser.add_mutually_exclusive_group()
format_group.add_argument('-c', '--contest', action='store_true',
help='Create output for the contest specified in the processed file')
format_group.add_argument('-q', '--qsl', action='store_true',
help='Display QSL status of contacted OM')
parser.add_argument('-o', '--output',
help='Output file or directory. If not present, the generated output is printed to standard output. If the argument is a directory, then a file with the same name as the input file and a proper extension will be used.')
args = parser.parse_args()
params = {}
if args.contest:
params['format'] = 'contest'
if args.qsl:
params['format'] = 'qsl'
params['qsl_info'] = qslinfo.QSL()
if os.path.isfile('qsl.lst'):
params['qsl_info'].load('qsl.lst')
if not args.files:
args.files.append('-')
if args.output:
if os.path.isdir(args.output):
params['output_name'] = os.path.join(args.output, '{callsign} {file}.{ext}')
elif len(args.files) != 1 or args.files[0] != '-':
params['output_handle'] = open(args.output, 'w', encoding='utf-8')
for file in args.files:
if file == '-':
parse_input(sys.stdin)
else:
if args.contest:
config = os.path.splitext(handle.name)[0] + '.cts'
if os.path.isfile(config):
params['config'] = config
elif 'config' in params:
del params['config']
with open(file, 'r', encoding='utf-8') as f:
parse_input(f, **params)
if 'output_handle' in params:
close(params['output_handle'])
if 'qsl_info' in params:
params['qsl_info'].save('qsl.lst')
params['qsl_info'].print_stat()
| kcs/SOTAnaplo | log2csv.py | Python | mit | 21,801 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpRequest, HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.arm_polling import ARMPolling
from .. import models as _models
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
class VirtualHubRouteTableV2SOperations(object):
"""VirtualHubRouteTableV2SOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.network.v2020_11_01.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
def get(
self,
resource_group_name, # type: str
virtual_hub_name, # type: str
route_table_name, # type: str
**kwargs # type: Any
):
# type: (...) -> "_models.VirtualHubRouteTableV2"
"""Retrieves the details of a VirtualHubRouteTableV2.
:param resource_group_name: The resource group name of the VirtualHubRouteTableV2.
:type resource_group_name: str
:param virtual_hub_name: The name of the VirtualHub.
:type virtual_hub_name: str
:param route_table_name: The name of the VirtualHubRouteTableV2.
:type route_table_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: VirtualHubRouteTableV2, or the result of cls(response)
:rtype: ~azure.mgmt.network.v2020_11_01.models.VirtualHubRouteTableV2
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualHubRouteTableV2"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-11-01"
accept = "application/json"
# Construct URL
url = self.get.metadata['url'] # type: ignore
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'virtualHubName': self._serialize.url("virtual_hub_name", virtual_hub_name, 'str'),
'routeTableName': self._serialize.url("route_table_name", route_table_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.get(url, query_parameters, header_parameters)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('VirtualHubRouteTableV2', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/routeTables/{routeTableName}'} # type: ignore
def _create_or_update_initial(
self,
resource_group_name, # type: str
virtual_hub_name, # type: str
route_table_name, # type: str
virtual_hub_route_table_v2_parameters, # type: "_models.VirtualHubRouteTableV2"
**kwargs # type: Any
):
# type: (...) -> "_models.VirtualHubRouteTableV2"
cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualHubRouteTableV2"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-11-01"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Construct URL
url = self._create_or_update_initial.metadata['url'] # type: ignore
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'virtualHubName': self._serialize.url("virtual_hub_name", virtual_hub_name, 'str'),
'routeTableName': self._serialize.url("route_table_name", route_table_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
body_content = self._serialize.body(virtual_hub_route_table_v2_parameters, 'VirtualHubRouteTableV2')
body_content_kwargs['content'] = body_content
request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize('VirtualHubRouteTableV2', pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize('VirtualHubRouteTableV2', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/routeTables/{routeTableName}'} # type: ignore
def begin_create_or_update(
self,
resource_group_name, # type: str
virtual_hub_name, # type: str
route_table_name, # type: str
virtual_hub_route_table_v2_parameters, # type: "_models.VirtualHubRouteTableV2"
**kwargs # type: Any
):
# type: (...) -> LROPoller["_models.VirtualHubRouteTableV2"]
"""Creates a VirtualHubRouteTableV2 resource if it doesn't exist else updates the existing
VirtualHubRouteTableV2.
:param resource_group_name: The resource group name of the VirtualHub.
:type resource_group_name: str
:param virtual_hub_name: The name of the VirtualHub.
:type virtual_hub_name: str
:param route_table_name: The name of the VirtualHubRouteTableV2.
:type route_table_name: str
:param virtual_hub_route_table_v2_parameters: Parameters supplied to create or update
VirtualHubRouteTableV2.
:type virtual_hub_route_table_v2_parameters: ~azure.mgmt.network.v2020_11_01.models.VirtualHubRouteTableV2
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling.
Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of LROPoller that returns either VirtualHubRouteTableV2 or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.network.v2020_11_01.models.VirtualHubRouteTableV2]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualHubRouteTableV2"]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = self._create_or_update_initial(
resource_group_name=resource_group_name,
virtual_hub_name=virtual_hub_name,
route_table_name=route_table_name,
virtual_hub_route_table_v2_parameters=virtual_hub_route_table_v2_parameters,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize('VirtualHubRouteTableV2', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'virtualHubName': self._serialize.url("virtual_hub_name", virtual_hub_name, 'str'),
'routeTableName': self._serialize.url("route_table_name", route_table_name, 'str'),
}
if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = NoPolling()
else: polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/routeTables/{routeTableName}'} # type: ignore
def _delete_initial(
self,
resource_group_name, # type: str
virtual_hub_name, # type: str
route_table_name, # type: str
**kwargs # type: Any
):
# type: (...) -> None
cls = kwargs.pop('cls', None) # type: ClsType[None]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-11-01"
accept = "application/json"
# Construct URL
url = self._delete_initial.metadata['url'] # type: ignore
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'virtualHubName': self._serialize.url("virtual_hub_name", virtual_hub_name, 'str'),
'routeTableName': self._serialize.url("route_table_name", route_table_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.delete(url, query_parameters, header_parameters)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/routeTables/{routeTableName}'} # type: ignore
def begin_delete(
self,
resource_group_name, # type: str
virtual_hub_name, # type: str
route_table_name, # type: str
**kwargs # type: Any
):
# type: (...) -> LROPoller[None]
"""Deletes a VirtualHubRouteTableV2.
:param resource_group_name: The resource group name of the VirtualHubRouteTableV2.
:type resource_group_name: str
:param virtual_hub_name: The name of the VirtualHub.
:type virtual_hub_name: str
:param route_table_name: The name of the VirtualHubRouteTableV2.
:type route_table_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling.
Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType[None]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = self._delete_initial(
resource_group_name=resource_group_name,
virtual_hub_name=virtual_hub_name,
route_table_name=route_table_name,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
if cls:
return cls(pipeline_response, None, {})
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'virtualHubName': self._serialize.url("virtual_hub_name", virtual_hub_name, 'str'),
'routeTableName': self._serialize.url("route_table_name", route_table_name, 'str'),
}
if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = NoPolling()
else: polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/routeTables/{routeTableName}'} # type: ignore
def list(
self,
resource_group_name, # type: str
virtual_hub_name, # type: str
**kwargs # type: Any
):
# type: (...) -> Iterable["_models.ListVirtualHubRouteTableV2SResult"]
"""Retrieves the details of all VirtualHubRouteTableV2s.
:param resource_group_name: The resource group name of the VirtualHub.
:type resource_group_name: str
:param virtual_hub_name: The name of the VirtualHub.
:type virtual_hub_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either ListVirtualHubRouteTableV2SResult or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.network.v2020_11_01.models.ListVirtualHubRouteTableV2SResult]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.ListVirtualHubRouteTableV2SResult"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-11-01"
accept = "application/json"
def prepare_request(next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.list.metadata['url'] # type: ignore
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'virtualHubName': self._serialize.url("virtual_hub_name", virtual_hub_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {} # type: Dict[str, Any]
request = self._client.get(url, query_parameters, header_parameters)
return request
def extract_data(pipeline_response):
deserialized = self._deserialize('ListVirtualHubRouteTableV2SResult', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(
get_next, extract_data
)
list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/routeTables'} # type: ignore
| Azure/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2020_11_01/operations/_virtual_hub_route_table_v2_s_operations.py | Python | mit | 22,766 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(name='megacl',
version='0.4.6',
description='mega.co.nz command line client.',
author='Arthibus Gisséhel',
author_email='public-dev-megacl@gissehel.org',
url='https://github.com/gissehel/megacl.git',
packages=['megacllib'],
scripts=['mcl','megacl'],
license='MIT',
keywords='commandline mega.co.nz mega',
long_description=open('README.rst').read(),
install_requires=['supertools','cltools>=0.4.0','mega.py>=0.9.13',
'requests', # non declared yet mega.py dependency
'pycrypto', # non declared yet mega.py dependency
],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Information Technology',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Topic :: Communications',
'Topic :: Internet',
'Topic :: System :: Filesystems',
'Topic :: Utilities',
],
)
| gissehel/megacl | setup.py | Python | mit | 1,210 |
"""
The set [1,2,3,...,n] contains a total of n! unique permutations.
By listing and labeling all of the permutations in order, we get the following sequence for n = 3:
"123"
"132"
"213"
"231"
"312"
"321"
Given n and k, return the kth permutation sequence.
Note:
Given n will be between 1 and 9 inclusive.
Given k will be between 1 and n! inclusive.
Example 1:
Input: n = 3, k = 3
Output: "213"
Example 2:
Input: n = 4, k = 9
Output: "2314"
"""
class Solution:
def getPermutation(self, n: int, k: int) -> str:
facts = [0]
fact = 1
for i in range(1, n):
fact *= i
facts.append(fact)
facts = facts[::-1]
candidates = list(range(1, n + 1))
ret = []
k -= 1
for i in range(n):
if facts[i] != 0:
index, k = divmod(k, facts[i])
else:
index, k = 0, 0
ret.append(candidates[index])
del candidates[index]
return ''.join((str(e) for e in ret))
| franklingu/leetcode-solutions | questions/permutation-sequence/Solution.py | Python | mit | 1,021 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# rtstock documentation build configuration file, created by
# sphinx-quickstart on Tue Jul 9 22:26:36 2013.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
# If extensions (or modules to document with autodoc) are in another
# directory, add these directories to sys.path here. If the directory is
# relative to the documentation root, use os.path.abspath to make it
# absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# Get the project root dir, which is the parent dir of this
cwd = os.getcwd()
project_root = os.path.dirname(cwd)
# Insert the project root dir as the first element in the PYTHONPATH.
# This lets us ensure that the source package is imported, and that its
# version is used.
sys.path.insert(0, project_root)
import rtstock
# -- General configuration ---------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Realtime Stock'
copyright = u"2016, Rafael Lopes Conde dos Reis"
# The version info for the project you're documenting, acts as replacement
# for |version| and |release|, also used in various other places throughout
# the built documents.
#
# The short X.Y version.
version = rtstock.__version__
# The full version, including alpha/beta/rc tags.
release = rtstock.__version__
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to
# some non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built
# documents.
#keep_warnings = False
# -- Options for HTML output -------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a
# theme further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as
# html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the
# top of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon
# of the docs. This file should be a Windows icon file (.ico) being
# 16x16 or 32x32 pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets)
# here, relative to this directory. They are copied after the builtin
# static files, so a file named "default.css" will overwrite the builtin
# "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page
# bottom, using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names
# to template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer.
# Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer.
# Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages
# will contain a <link> tag referring to it. The value of this option
# must be the base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'rtstockdoc'
# -- Options for LaTeX output ------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass
# [howto/manual]).
latex_documents = [
('index', 'rtstock.tex',
u'Realtime Stock Documentation',
u'Rafael Lopes Conde dos Reis', 'manual'),
]
# The name of an image file (relative to this directory) to place at
# the top of the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings
# are parts, not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'rtstock',
u'Realtime Stock Documentation',
[u'Rafael Lopes Conde dos Reis'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ----------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'rtstock',
u'Realtime Stock Documentation',
u'Rafael Lopes Conde dos Reis',
'rtstock',
'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
| condereis/realtime-stock | docs/conf.py | Python | mit | 8,475 |
class Solution(object):
def solveNQueens(self, n):
"""
:type n: int
:rtype: List[List[str]]
"""
def search(cur):
if cur == n:
add_answer()
else:
for i in range(n):
ok = True
rows[cur] = i
for j in range(cur):
if not is_valied(cur, j):
ok = False
break
if ok:
search(cur + 1)
def is_valied(pre_row, cur_row):
if rows[pre_row] == rows[cur_row] or \
pre_row - rows[pre_row] == cur_row - rows[cur_row] or \
pre_row + rows[pre_row] == cur_row + rows[cur_row]:
return False
else:
return True
def add_answer():
ans = []
for num in rows:
res_str = ""
for i in range(n):
if i == num:
res_str += "Q"
else:
res_str += "."
ans.append(res_str)
result.append(ans)
result = []
rows = [0] * n
search(0)
return result
print Solution().solveNQueens(4)
| ChuanleiGuo/AlgorithmsPlayground | LeetCodeSolutions/python/51_N-Queens.py | Python | mit | 1,340 |
__all__ = ['Constraint', 'ConstraintGroup', 'TotalSumValueConstraint', 'UniqueValueConstraint']
from .constraint import Constraint
from .constraintgroup import ConstraintGroup
from .totalsumvalueconstraint import TotalSumValueConstraint
from .uniquevalueconstraint import UniqueValueConstraint
| JoostvanPinxten/ConstraintPuzzler | constraints/__init__.py | Python | mit | 296 |
def on_square():
pass
def total_after():
pass
| rootulp/xpython | exercises/grains/grains.py | Python | mit | 56 |
"""
<Program Name>
ed25519_keys.py
<Author>
Vladimir Diaz <vladimir.v.diaz@gmail.com>
<Started>
September 24, 2013.
<Copyright>
See LICENSE for licensing information.
<Purpose>
The goal of this module is to support ed25519 signatures. ed25519 is an
elliptic-curve public key signature scheme, its main strength being small
signatures (64 bytes) and small public keys (32 bytes).
http://ed25519.cr.yp.to/
'ssl_crypto/ed25519_keys.py' calls 'ed25519.py', which is the pure Python
implementation of ed25519 optimized for a faster runtime. The Python
reference implementation is concise, but very slow (verifying signatures
takes ~9 seconds on an Intel core 2 duo @ 2.2 ghz x 2). The optimized
version can verify signatures in ~2 seconds.
http://ed25519.cr.yp.to/software.html
https://github.com/pyca/ed25519
Optionally, ed25519 cryptographic operations may be executed by PyNaCl, which
is a Python binding to the NaCl library and is faster than the pure python
implementation. Verifying signatures can take approximately 0.0009 seconds.
PyNaCl relies on the libsodium C library. PyNaCl is required for key and
signature generation. Verifying signatures may be done in pure Python.
https://github.com/pyca/pynacl
https://github.com/jedisct1/libsodium
http://nacl.cr.yp.to/
https://github.com/pyca/ed25519
The ed25519-related functions included here are generate(), create_signature()
and verify_signature(). The 'ed25519' and PyNaCl (i.e., 'nacl') modules used
by ed25519_keys.py perform the actual ed25519 computations and the functions
listed above can be viewed as an easy-to-use public interface.
"""
# Help with Python 3 compatibility, where the print statement is a function, an
# implicit relative import is invalid, and the '/' operator performs true
# division. Example: print 'hello world' raises a 'SyntaxError' exception.
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
# 'binascii' required for hexadecimal conversions. Signatures and
# public/private keys are hexlified.
import binascii
# TODO: The 'warnings' module needed to temporarily suppress user warnings
# raised by 'pynacl' (as of version 0.2.3). Warnings temporarily suppressed
# here to avoid confusing users with an unexpected error message that gives
# no indication of its source. These warnings are printed when using
# the repository tools, including for clients that request an update.
# http://docs.python.org/2/library/warnings.html#temporarily-suppressing-warnings
import warnings
# 'os' required to generate OS-specific randomness (os.urandom) suitable for
# cryptographic use.
# http://docs.python.org/2/library/os.html#miscellaneous-functions
import os
# Import the python implementation of the ed25519 algorithm provided by pyca,
# which is an optimized version of the one provided by ed25519's authors.
# Note: The pure Python version does not include protection against side-channel
# attacks. Verifying signatures can take approximately 2 seconds on an intel
# core 2 duo @ 2.2 ghz x 2). Optionally, the PyNaCl module may be used to
# speed up ed25519 cryptographic operations.
# http://ed25519.cr.yp.to/software.html
# https://github.com/pyca/ed25519
# https://github.com/pyca/pynacl
#
# Import the PyNaCl library, if available. It is recommended this library be
# used over the pure python implementation of ed25519, due to its speedier
# routines and side-channel protections available in the libsodium library.
#
# TODO: Version 0.2.3 of 'pynacl' prints: "UserWarning: reimporting '...' might
# overwrite older definitions." when importing 'nacl.signing'. Suppress user
# warnings temporarily (at least until this issue is fixed by PyNaCl).
#
# Note: A 'pragma: no cover' comment is intended for test 'coverage'. Lines
# or code blocks with this comment should not be flagged as uncovered.
# pynacl will always be install prior to running the unit tests.
with warnings.catch_warnings():
warnings.simplefilter('ignore')
try:
import nacl.signing
import nacl.encoding
# PyNaCl's 'cffi' dependency may raise an 'IOError' exception when importing
# 'nacl.signing'.
except (ImportError, IOError): # pragma: no cover
pass
# The optimized pure Python implementation of ed25519 provided by TUF. If
# PyNaCl cannot be imported and an attempt to use is made in this module, a
# 'ssl_commons__exceptions.UnsupportedLibraryError' exception is raised.
from ._vendor.ed25519 import ed25519 as _vendor__ed25519__ed25519
# Digest objects needed to generate hashes.
from . import hash as ssl_crypto__hash
# Perform object format-checking.
from . import formats as ssl_crypto__formats
from ..ssl_commons import exceptions as ssl_commons__exceptions
# Supported ed25519 signing method: 'ed25519'. The pure Python implementation
# (i.e., ed25519') and PyNaCl (i.e., 'nacl', libsodium+Python bindings) modules
# are currently supported in the creationg of 'ed25519' signatures.
# Previously, a distinction was made between signatures made by the pure Python
# implementation and PyNaCl.
_SUPPORTED_ED25519_SIGNING_METHODS = ['ed25519']
def generate_public_and_private():
"""
<Purpose>
Generate a pair of ed25519 public and private keys with PyNaCl. The public
and private keys returned conform to 'ssl_crypto__formats.ED25519PULIC_SCHEMA' and
'ssl_crypto__formats.ED25519SEED_SCHEMA', respectively, and have the form:
'\xa2F\x99\xe0\x86\x80%\xc8\xee\x11\xb95T\xd9\...'
An ed25519 seed key is a random 32-byte string. Public keys are also 32
bytes.
>>> public, private = generate_public_and_private()
>>> ssl_crypto__formats.ED25519PUBLIC_SCHEMA.matches(public)
True
>>> ssl_crypto__formats.ED25519SEED_SCHEMA.matches(private)
True
<Arguments>
None.
<Exceptions>
ssl_commons__exceptions.UnsupportedLibraryError, if the PyNaCl ('nacl') module is unavailable.
NotImplementedError, if a randomness source is not found by 'os.urandom'.
<Side Effects>
The ed25519 keys are generated by first creating a random 32-byte seed
with os.urandom() and then calling PyNaCl's nacl.signing.SigningKey().
<Returns>
A (public, private) tuple that conform to 'ssl_crypto__formats.ED25519PUBLIC_SCHEMA'
and 'ssl_crypto__formats.ED25519SEED_SCHEMA', respectively.
"""
# Generate ed25519's seed key by calling os.urandom(). The random bytes
# returned should be suitable for cryptographic use and is OS-specific.
# Raise 'NotImplementedError' if a randomness source is not found.
# ed25519 seed keys are fixed at 32 bytes (256-bit keys).
# http://blog.mozilla.org/warner/2011/11/29/ed25519-keys/
seed = os.urandom(32)
public = None
# Generate the public key. PyNaCl (i.e., 'nacl' module) performs the actual
# key generation.
try:
nacl_key = nacl.signing.SigningKey(seed)
public = nacl_key.verify_key.encode(encoder=nacl.encoding.RawEncoder())
except NameError: # pragma: no cover
message = 'The PyNaCl library and/or its dependencies unavailable.'
raise ssl_commons__exceptions.UnsupportedLibraryError(message)
return public, seed
def create_signature(public_key, private_key, data):
"""
<Purpose>
Return a (signature, method) tuple, where the method is 'ed25519' and is
always generated by PyNaCl (i.e., 'nacl'). The signature returned conforms
to 'ssl_crypto__formats.ED25519SIGNATURE_SCHEMA', and has the form:
'\xae\xd7\x9f\xaf\x95{bP\x9e\xa8YO Z\x86\x9d...'
A signature is a 64-byte string.
>>> public, private = generate_public_and_private()
>>> data = b'The quick brown fox jumps over the lazy dog'
>>> signature, method = \
create_signature(public, private, data)
>>> ssl_crypto__formats.ED25519SIGNATURE_SCHEMA.matches(signature)
True
>>> method == 'ed25519'
True
>>> signature, method = \
create_signature(public, private, data)
>>> ssl_crypto__formats.ED25519SIGNATURE_SCHEMA.matches(signature)
True
>>> method == 'ed25519'
True
<Arguments>
public:
The ed25519 public key, which is a 32-byte string.
private:
The ed25519 private key, which is a 32-byte string.
data:
Data object used by create_signature() to generate the signature.
<Exceptions>
ssl_commons__exceptions.FormatError, if the arguments are improperly formatted.
ssl_commons__exceptions.CryptoError, if a signature cannot be created.
<Side Effects>
nacl.signing.SigningKey.sign() called to generate the actual signature.
<Returns>
A signature dictionary conformat to 'ssl_crypto.format.SIGNATURE_SCHEMA'.
ed25519 signatures are 64 bytes, however, the hexlified signature is
stored in the dictionary returned.
"""
# Does 'public_key' have the correct format?
# This check will ensure 'public_key' conforms to
# 'ssl_crypto__formats.ED25519PUBLIC_SCHEMA', which must have length 32 bytes.
# Raise 'ssl_commons__exceptions.FormatError' if the check fails.
ssl_crypto__formats.ED25519PUBLIC_SCHEMA.check_match(public_key)
# Is 'private_key' properly formatted?
ssl_crypto__formats.ED25519SEED_SCHEMA.check_match(private_key)
# Signing the 'data' object requires a seed and public key.
# nacl.signing.SigningKey.sign() generates the signature.
public = public_key
private = private_key
method = None
signature = None
# The private and public keys have been validated above by 'ssl_crypto__formats' and
# should be 32-byte strings.
method = 'ed25519'
try:
nacl_key = nacl.signing.SigningKey(private)
nacl_sig = nacl_key.sign(data)
signature = nacl_sig.signature
except NameError: # pragma: no cover
message = 'The PyNaCl library and/or its dependencies unavailable.'
raise ssl_commons__exceptions.UnsupportedLibraryError(message)
except (ValueError, TypeError, nacl.exceptions.CryptoError) as e:
message = 'An "ed25519" signature could not be created with PyNaCl.'
raise ssl_commons__exceptions.CryptoError(message + str(e))
return signature, method
def verify_signature(public_key, method, signature, data, use_pynacl=False):
"""
<Purpose>
Determine whether the private key corresponding to 'public_key' produced
'signature'. verify_signature() will use the public key, the 'method' and
'sig', and 'data' arguments to complete the verification.
>>> public, private = generate_public_and_private()
>>> data = b'The quick brown fox jumps over the lazy dog'
>>> signature, method = \
create_signature(public, private, data)
>>> verify_signature(public, method, signature, data, use_pynacl=False)
True
>>> verify_signature(public, method, signature, data, use_pynacl=True)
True
>>> bad_data = b'The sly brown fox jumps over the lazy dog'
>>> bad_signature, method = \
create_signature(public, private, bad_data)
>>> verify_signature(public, method, bad_signature, data, use_pynacl=False)
False
<Arguments>
public_key:
The public key is a 32-byte string.
method:
'ed25519' signature method generated by either the pure python
implementation (i.e., ed25519.py) or PyNacl (i.e., 'nacl').
signature:
The signature is a 64-byte string.
data:
Data object used by ssl_crypto.ed25519_keys.create_signature() to generate
'signature'. 'data' is needed here to verify the signature.
use_pynacl:
True, if the ed25519 signature should be verified by PyNaCl. False,
if the signature should be verified with the pure Python implementation
of ed25519 (slower).
<Exceptions>
ssl_commons__exceptions.UnknownMethodError. Raised if the signing method used by
'signature' is not one supported by ssl_crypto.ed25519_keys.create_signature().
ssl_commons__exceptions.FormatError. Raised if the arguments are improperly formatted.
<Side Effects>
ssl_crypto._vendor.ed25519.ed25519.checkvalid() called to do the actual
verification. nacl.signing.VerifyKey.verify() called if 'use_pynacl' is
True.
<Returns>
Boolean. True if the signature is valid, False otherwise.
"""
# Does 'public_key' have the correct format?
# This check will ensure 'public_key' conforms to
# 'ssl_crypto__formats.ED25519PUBLIC_SCHEMA', which must have length 32 bytes.
# Raise 'ssl_commons__exceptions.FormatError' if the check fails.
ssl_crypto__formats.ED25519PUBLIC_SCHEMA.check_match(public_key)
# Is 'method' properly formatted?
ssl_crypto__formats.NAME_SCHEMA.check_match(method)
# Is 'signature' properly formatted?
ssl_crypto__formats.ED25519SIGNATURE_SCHEMA.check_match(signature)
# Is 'use_pynacl' properly formatted?
ssl_crypto__formats.BOOLEAN_SCHEMA.check_match(use_pynacl)
# Verify 'signature'. Before returning the Boolean result,
# ensure 'ed25519' was used as the signing method.
# Raise 'ssl_commons__exceptions.UnsupportedLibraryError' if 'use_pynacl' is True but 'nacl' is
# unavailable.
public = public_key
valid_signature = False
if method in _SUPPORTED_ED25519_SIGNING_METHODS:
if use_pynacl:
try:
nacl_verify_key = nacl.signing.VerifyKey(public)
nacl_message = nacl_verify_key.verify(data, signature)
valid_signature = True
except NameError: # pragma: no cover
message = 'The PyNaCl library and/or its dependencies unavailable.'
raise ssl_commons__exceptions.UnsupportedLibraryError(message)
except nacl.exceptions.BadSignatureError:
pass
# Verify 'ed25519' signature with the pure Python implementation.
else:
try:
_vendor__ed25519__ed25519.checkvalid(signature, data, public)
valid_signature = True
# The pure Python implementation raises 'Exception' if 'signature' is
# invalid.
except Exception as e:
pass
else:
message = 'Unsupported ed25519 signing method: '+repr(method)+'.\n'+ \
'Supported methods: '+repr(_SUPPORTED_ED25519_SIGNING_METHODS)+'.'
raise ssl_commons__exceptions.UnknownMethodError(message)
return valid_signature
if __name__ == '__main__':
# The interactive sessions of the documentation strings can
# be tested by running 'ed25519_keys.py' as a standalone module.
# python -B ed25519_keys.py
import doctest
doctest.testmod()
| team-ferret/pip-in-toto | pip/toto/ssl_crypto/ed25519_keys.py | Python | mit | 14,560 |
# Generated by Django 3.1 on 2020-08-13 19:23
from django.db import migrations, models
import django.db.models.deletion
import django_countries.fields
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='LunchType',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=64)),
('sort_order', models.PositiveIntegerField()),
('unit_price', models.DecimalField(decimal_places=2, default=0, max_digits=12)),
],
options={
'ordering': ['sort_order'],
},
),
migrations.CreateModel(
name='PassType',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('type', models.CharField(choices=[('party', 'Party Pass'), ('full', 'Full Pass')], max_length=32)),
('name', models.CharField(max_length=64)),
('active', models.BooleanField(default=False)),
('sort_order', models.PositiveIntegerField()),
('quantity_in_stock', models.PositiveIntegerField(default=0)),
('unit_price', models.DecimalField(decimal_places=2, default=0, max_digits=12)),
('data', models.JSONField(blank=True)),
],
options={
'ordering': ['sort_order'],
},
),
migrations.CreateModel(
name='Registration',
fields=[
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('first_name', models.CharField(max_length=64)),
('last_name', models.CharField(max_length=64)),
('email', models.EmailField(max_length=254, unique=True)),
('dance_role', models.CharField(choices=[('leader', 'Leader'), ('follower', 'Follower')], default='leader', max_length=32)),
('residing_country', django_countries.fields.CountryField(max_length=2)),
('workshop_partner_name', models.CharField(blank=True, max_length=128)),
('workshop_partner_email', models.EmailField(blank=True, max_length=254)),
('crew_remarks', models.TextField(blank=True, max_length=4096)),
('total_price', models.DecimalField(decimal_places=2, default=0, max_digits=12)),
('audition_url', models.URLField(blank=True)),
('accepted_at', models.DateTimeField(blank=True, null=True)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('lunch', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='registration.lunchtype')),
('pass_type', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='registration.passtype')),
],
),
migrations.CreateModel(
name='Payment',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('mollie_payment_id', models.CharField(blank=True, max_length=64, null=True, unique=True)),
('amount', models.DecimalField(decimal_places=2, default=0, max_digits=12)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('registration', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='registration.registration')),
],
),
migrations.CreateModel(
name='Interaction',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('description', models.TextField(blank=True, max_length=4096)),
('created_at', models.DateTimeField(auto_now_add=True)),
('registration', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='registration.registration')),
],
),
]
| smokeyfeet/smokeyfeet-registration | src/smokeyfeet/registration/migrations/0001_initial.py | Python | mit | 4,391 |
import numpy as np
import matplotlib.pyplot as plt
import sys
fname = sys.argv[1]
exes = [0] * 101
wise = [0] * 101
f = open(fname, 'r')
for i in range(101):
split = f.readline().split(" ")
exes[i] = split[0]
wise[i] = split[1]
x = np.asarray(exes)
y = np.asarray(wise)
fig, ax = plt.subplots()
ax.set_xlabel("Fraction through data")
ax.set_ylabel("Probability of correctness")
tit = fname[:-4].split(" ") # remove .txt
inte = "S_{err}= |, \sigma_{err}= |, S_{read}= |, \sigma_{err}= |, S_{curve}= ".split("|")
title = "$" + inte[0] + tit[0] + inte[1] + tit[1] + inte[2] + tit[2] + inte[3] + tit[3] + inte[4] + tit[4] + "$"
ax.set_title(title)
line, = ax.plot(x, y)
plt.show() | mtkwock/Genome-Matching | code/plot_chances.py | Python | mit | 690 |
#!/usr/bin/env python
# -*-coding:utf-8-*-
import time
from time import sleep
import random
depo, sus, tab, user_puntos, pc_puntos = ["piedra", "papel", "tijera", "lagarto", "spock"], "-" * 35, " " * 4, 0, 0
print """Hola! Bienvenido al juego Piedra Papel Tijera Lagarto Spock!\nEstas son las reglas:\n Las tijeras cortan el papel\n El papel cubre a la piedra\n La piedra aplasta al lagarto\n El lagarto envenena a Spock\n Spock destroza las tijeras\n Las tijeras decapitan al lagarto\n El lagarto se come el papel\n El papel refuta a Spock\n Spock vaporiza la piedra\n Y como es habitual... la piedra aplasta las tijeras.\nRecuerda que si escribes algun valor incorrecto pierdes un punto!\nEl primero en llegar a 10 puntos gana!
"""
sleep(2)
print "\nTus puntos son:{}\nY los puntos de la pc son:{}\n".format(user_puntos, pc_puntos)
sleep(1)
while (pc_puntos < 10 and user_puntos < 10):
tu = raw_input("Que eliges? Piedra, papel, tijera, lagarto o Spock:\n('marcador' para ver los puntos)(Control + C para salir)\n\n(Escribe en minusculas)" + tab)
pc = random.choice(depo)
sleep(0.5)
if tu in depo:
print (("\nElegiste {}\nComputadora eligio {}\nAsi que:").format(tu, pc))
elif tu not in depo and tu != "marcador":
print "\nEscribe un valor correcto!\nPierdes un punto"
if tu == pc:
print '\n Es un Empate...\n'
elif tu == 'piedra' and pc == 'tijera':
user_puntos = user_puntos + 1
print "\n Ganaste! Como es habitual... la piedra aplasta las tijeras.\nGanas un punto!!!\nTus puntos son:{}\nY los puntos de la pc son:{}\n".format(user_puntos, pc_puntos)
elif tu == 'papel' and pc == 'piedra':
user_puntos = user_puntos + 1
print "\n Ganaste! Papel cubre a la piedra\nGanas un punto!!!\nTus puntos son:{}\nY los puntos de la pc son:{}\n".format(user_puntos, pc_puntos)
elif tu == 'tijera' and pc == 'papel':
user_puntos = user_puntos + 1
print "\n Ganaste! Tijeras cortan el papel\nGanas un punto!!!\nTus puntos son:{}\nY los puntos de la pc son:{}\n".format(user_puntos, pc_puntos)
elif tu == 'piedra' and pc == 'lagarto':
user_puntos = user_puntos + 1
print "\n Ganaste! La piedra aplasta al lagarto\nGanas un punto!!!\nTus puntos son:{}\nY los puntos de la pc son:{}\n".format(user_puntos, pc_puntos)
elif tu == 'lagarto' and pc == 'spock':
user_puntos = user_puntos + 1
print "\n Ganaste! Lagarto envenena Spock\nGanas un punto!!!\nTus puntos son:{}\nY los puntos de la pc son:{}\n".format(user_puntos, pc_puntos)
elif tu == 'spock' and pc == 'tijera':
user_puntos = user_puntos + 1
print "\n Ganaste! Spock destroza las tijeras\nGanas un punto!!!\nTus puntos son:{}\nY los puntos de la pc son:{}\n".format(user_puntos, pc_puntos)
elif tu == 'tijera' and pc == 'lagarto':
user_puntos = user_puntos + 1
print "\n Ganaste! Las tijeras decapitan al lagarto\nGanas un punto!!!\nTus puntos son:{}\nY los puntos de la pc son:{}\n".format(user_puntos, pc_puntos)
elif tu == 'lagarto' and pc == 'papel':
user_puntos = user_puntos + 1
print "\n Ganaste! El lagarto se come el papel\nGanas un punto!!!\nTus puntos son:{}\nY los puntos de la pc son:{}\n".format(user_puntos, pc_puntos)
elif tu == 'papel' and pc == 'spock':
user_puntos = user_puntos + 1
print "\n Ganaste! El papel refuta a Spock\nGanas un punto!!!\nTus puntos son:{}\nY los puntos de la pc son:{}\n".format(user_puntos, pc_puntos)
elif tu == 'spock' and pc == 'piedra':
user_puntos = user_puntos + 1
print "\n Ganaste! Spock vaporiza la piedra\nGanas un punto!!!\nTus puntos son:{}\nY los puntos de la pc son:{}\n".format(user_puntos, pc_puntos)
elif tu == "marcador" and pc == pc:
print "\nTus puntos son:{}\nY los puntos de la pc son:{}\n".format(user_puntos, pc_puntos)
sleep(0.5)
else:
pc_puntos = pc_puntos + 1
print "\n Lo siento, perdiste: {} le gana a {} \n{}\nPierdes un punto...\nTus puntos son:{}\nY los puntos de la pc son:{}\n".format(pc, tu, sus, user_puntos, pc_puntos)
print "Acabo el juego...\nEl ganador es...\n "
sleep(2)
if pc_puntos == 10:
print "La computadora!\nGracias por jugar!"
else:
print "Tu!\nGracias por jugar!\nVuelve Pronto!"
| juandc/platzi-courses | Python-Django-2016/Python/Reto/Otros-Competidores/Juan-David-Castro/pptls.py | Python | mit | 4,317 |
import logging
import hashlib
from pylons import request, response, session, tmpl_context as c
from pylons.controllers.util import abort, redirect_to, etag_cache
from pylons.decorators import jsonify
from pylons.i18n.translation import _
from wurdig.lib.base import BaseController, render
log = logging.getLogger(__name__)
class JsController(BaseController):
@jsonify
def _json(self):
translations = {
'Are you positive you want to do that?': _('Are you positive '
'you want to do that?'),
'The item has successfully been deleted.': _('The item has '
'successfully been deleted.'),
'Disapprove': _('Disapprove'),
'The item has successfully been approved.': _('The item has '
'successfully been approved.'),
'Approve': _('Approve'),
'The item has successfully been disapproved.': _('The item has successfully '
'been disapproved.'),
'Your+request+has+been+completed+successfully': _('Your+request+has+been+'
'completed+successfully'),
'An unexpected error has occurred.': _('An unexpected error has occurred.'),
'Enter key word(s)': _('Enter key word(s)')
}
return translations
def translations(self):
json_string = "if(!this.WURDIG) {var WURDIG = {};}WURDIG.translate = %s" % self._json()
etag_cache(key=hashlib.md5(json_string).hexdigest())
response.content_type = 'application/x-javascript; charset=utf-8'
response.cache_control = 'max-age=2592000'
response.pragma = ''
return json_string | leveille/blog.v1 | wurdig/controllers/js.py | Python | mit | 1,892 |
import re
import os
import sys
import time
import datetime
import traceback
from decimal import Decimal
import threading
import asyncio
from electrum.bitcoin import TYPE_ADDRESS
from electrum.storage import WalletStorage
from electrum.wallet import Wallet, InternalAddressCorruption
from electrum.paymentrequest import InvoiceStore
from electrum.util import profiler, InvalidPassword, send_exception_to_crash_reporter
from electrum.plugin import run_hook
from electrum.util import format_satoshis, format_satoshis_plain, format_fee_satoshis
from electrum.paymentrequest import PR_UNPAID, PR_PAID, PR_UNKNOWN, PR_EXPIRED
from electrum import blockchain
from electrum.network import Network, TxBroadcastError, BestEffortRequestFailed
from .i18n import _
from kivy.app import App
from kivy.core.window import Window
from kivy.logger import Logger
from kivy.utils import platform
from kivy.properties import (OptionProperty, AliasProperty, ObjectProperty,
StringProperty, ListProperty, BooleanProperty, NumericProperty)
from kivy.cache import Cache
from kivy.clock import Clock
from kivy.factory import Factory
from kivy.metrics import inch
from kivy.lang import Builder
## lazy imports for factory so that widgets can be used in kv
#Factory.register('InstallWizard', module='electrum.gui.kivy.uix.dialogs.installwizard')
#Factory.register('InfoBubble', module='electrum.gui.kivy.uix.dialogs')
#Factory.register('OutputList', module='electrum.gui.kivy.uix.dialogs')
#Factory.register('OutputItem', module='electrum.gui.kivy.uix.dialogs')
from .uix.dialogs.installwizard import InstallWizard
from .uix.dialogs import InfoBubble, crash_reporter
from .uix.dialogs import OutputList, OutputItem
from .uix.dialogs import TopLabel, RefLabel
#from kivy.core.window import Window
#Window.softinput_mode = 'below_target'
# delayed imports: for startup speed on android
notification = app = ref = None
util = False
# register widget cache for keeping memory down timeout to forever to cache
# the data
Cache.register('electrum_widgets', timeout=0)
from kivy.uix.screenmanager import Screen
from kivy.uix.tabbedpanel import TabbedPanel
from kivy.uix.label import Label
from kivy.core.clipboard import Clipboard
Factory.register('TabbedCarousel', module='electrum.gui.kivy.uix.screens')
# Register fonts without this you won't be able to use bold/italic...
# inside markup.
from kivy.core.text import Label
Label.register('Roboto',
'electrum/gui/kivy/data/fonts/Roboto.ttf',
'electrum/gui/kivy/data/fonts/Roboto.ttf',
'electrum/gui/kivy/data/fonts/Roboto-Bold.ttf',
'electrum/gui/kivy/data/fonts/Roboto-Bold.ttf')
from electrum.util import (base_units, NoDynamicFeeEstimates, decimal_point_to_base_unit_name,
base_unit_name_to_decimal_point, NotEnoughFunds, UnknownBaseUnit,
DECIMAL_POINT_DEFAULT)
class ElectrumWindow(App):
electrum_config = ObjectProperty(None)
language = StringProperty('en')
# properties might be updated by the network
num_blocks = NumericProperty(0)
num_nodes = NumericProperty(0)
server_host = StringProperty('')
server_port = StringProperty('')
num_chains = NumericProperty(0)
blockchain_name = StringProperty('')
fee_status = StringProperty('Fee')
balance = StringProperty('')
fiat_balance = StringProperty('')
is_fiat = BooleanProperty(False)
blockchain_forkpoint = NumericProperty(0)
auto_connect = BooleanProperty(False)
def on_auto_connect(self, instance, x):
net_params = self.network.get_parameters()
net_params = net_params._replace(auto_connect=self.auto_connect)
self.network.run_from_another_thread(self.network.set_parameters(net_params))
def toggle_auto_connect(self, x):
self.auto_connect = not self.auto_connect
oneserver = BooleanProperty(False)
def on_oneserver(self, instance, x):
net_params = self.network.get_parameters()
net_params = net_params._replace(oneserver=self.oneserver)
self.network.run_from_another_thread(self.network.set_parameters(net_params))
def toggle_oneserver(self, x):
self.oneserver = not self.oneserver
proxy_str = StringProperty('')
def update_proxy_str(self, proxy: dict):
mode = proxy.get('mode')
host = proxy.get('host')
port = proxy.get('port')
self.proxy_str = (host + ':' + port) if mode else _('None')
def choose_server_dialog(self, popup):
from .uix.dialogs.choice_dialog import ChoiceDialog
protocol = 's'
def cb2(host):
from electrum import constants
pp = servers.get(host, constants.net.DEFAULT_PORTS)
port = pp.get(protocol, '')
popup.ids.host.text = host
popup.ids.port.text = port
servers = self.network.get_servers()
ChoiceDialog(_('Choose a server'), sorted(servers), popup.ids.host.text, cb2).open()
def choose_blockchain_dialog(self, dt):
from .uix.dialogs.choice_dialog import ChoiceDialog
chains = self.network.get_blockchains()
def cb(name):
with blockchain.blockchains_lock: blockchain_items = list(blockchain.blockchains.items())
for chain_id, b in blockchain_items:
if name == b.get_name():
self.network.run_from_another_thread(self.network.follow_chain_given_id(chain_id))
chain_objects = [blockchain.blockchains.get(chain_id) for chain_id in chains]
chain_objects = filter(lambda b: b is not None, chain_objects)
names = [b.get_name() for b in chain_objects]
if len(names) > 1:
cur_chain = self.network.blockchain().get_name()
ChoiceDialog(_('Choose your chain'), names, cur_chain, cb).open()
use_rbf = BooleanProperty(False)
def on_use_rbf(self, instance, x):
self.electrum_config.set_key('use_rbf', self.use_rbf, True)
use_change = BooleanProperty(False)
def on_use_change(self, instance, x):
self.electrum_config.set_key('use_change', self.use_change, True)
use_unconfirmed = BooleanProperty(False)
def on_use_unconfirmed(self, instance, x):
self.electrum_config.set_key('confirmed_only', not self.use_unconfirmed, True)
def set_URI(self, uri):
self.switch_to('send')
self.send_screen.set_URI(uri)
def on_new_intent(self, intent):
if intent.getScheme() != 'fujicoin':
return
uri = intent.getDataString()
self.set_URI(uri)
def on_language(self, instance, language):
Logger.info('language: {}'.format(language))
_.switch_lang(language)
def update_history(self, *dt):
if self.history_screen:
self.history_screen.update()
def on_quotes(self, d):
Logger.info("on_quotes")
self._trigger_update_status()
self._trigger_update_history()
def on_history(self, d):
Logger.info("on_history")
if self.wallet:
self.wallet.clear_coin_price_cache()
self._trigger_update_history()
def on_fee_histogram(self, *args):
self._trigger_update_history()
def _get_bu(self):
decimal_point = self.electrum_config.get('decimal_point', DECIMAL_POINT_DEFAULT)
try:
return decimal_point_to_base_unit_name(decimal_point)
except UnknownBaseUnit:
return decimal_point_to_base_unit_name(DECIMAL_POINT_DEFAULT)
def _set_bu(self, value):
assert value in base_units.keys()
decimal_point = base_unit_name_to_decimal_point(value)
self.electrum_config.set_key('decimal_point', decimal_point, True)
self._trigger_update_status()
self._trigger_update_history()
wallet_name = StringProperty(_('No Wallet'))
base_unit = AliasProperty(_get_bu, _set_bu)
fiat_unit = StringProperty('')
def on_fiat_unit(self, a, b):
self._trigger_update_history()
def decimal_point(self):
return base_units[self.base_unit]
def btc_to_fiat(self, amount_str):
if not amount_str:
return ''
if not self.fx.is_enabled():
return ''
rate = self.fx.exchange_rate()
if rate.is_nan():
return ''
fiat_amount = self.get_amount(amount_str + ' ' + self.base_unit) * rate / pow(10, 8)
return "{:.2f}".format(fiat_amount).rstrip('0').rstrip('.')
def fiat_to_btc(self, fiat_amount):
if not fiat_amount:
return ''
rate = self.fx.exchange_rate()
if rate.is_nan():
return ''
satoshis = int(pow(10,8) * Decimal(fiat_amount) / Decimal(rate))
return format_satoshis_plain(satoshis, self.decimal_point())
def get_amount(self, amount_str):
a, u = amount_str.split()
assert u == self.base_unit
try:
x = Decimal(a)
except:
return None
p = pow(10, self.decimal_point())
return int(p * x)
_orientation = OptionProperty('landscape',
options=('landscape', 'portrait'))
def _get_orientation(self):
return self._orientation
orientation = AliasProperty(_get_orientation,
None,
bind=('_orientation',))
'''Tries to ascertain the kind of device the app is running on.
Cane be one of `tablet` or `phone`.
:data:`orientation` is a read only `AliasProperty` Defaults to 'landscape'
'''
_ui_mode = OptionProperty('phone', options=('tablet', 'phone'))
def _get_ui_mode(self):
return self._ui_mode
ui_mode = AliasProperty(_get_ui_mode,
None,
bind=('_ui_mode',))
'''Defines tries to ascertain the kind of device the app is running on.
Cane be one of `tablet` or `phone`.
:data:`ui_mode` is a read only `AliasProperty` Defaults to 'phone'
'''
def __init__(self, **kwargs):
# initialize variables
self._clipboard = Clipboard
self.info_bubble = None
self.nfcscanner = None
self.tabs = None
self.is_exit = False
self.wallet = None
self.pause_time = 0
self.asyncio_loop = asyncio.get_event_loop()
App.__init__(self)#, **kwargs)
title = _('Electrum App')
self.electrum_config = config = kwargs.get('config', None)
self.language = config.get('language', 'en')
self.network = network = kwargs.get('network', None) # type: Network
if self.network:
self.num_blocks = self.network.get_local_height()
self.num_nodes = len(self.network.get_interfaces())
net_params = self.network.get_parameters()
self.server_host = net_params.host
self.server_port = net_params.port
self.auto_connect = net_params.auto_connect
self.oneserver = net_params.oneserver
self.proxy_config = net_params.proxy if net_params.proxy else {}
self.update_proxy_str(self.proxy_config)
self.plugins = kwargs.get('plugins', [])
self.gui_object = kwargs.get('gui_object', None)
self.daemon = self.gui_object.daemon
self.fx = self.daemon.fx
self.use_rbf = config.get('use_rbf', True)
self.use_change = config.get('use_change', True)
self.use_unconfirmed = not config.get('confirmed_only', False)
# create triggers so as to minimize updating a max of 2 times a sec
self._trigger_update_wallet = Clock.create_trigger(self.update_wallet, .5)
self._trigger_update_status = Clock.create_trigger(self.update_status, .5)
self._trigger_update_history = Clock.create_trigger(self.update_history, .5)
self._trigger_update_interfaces = Clock.create_trigger(self.update_interfaces, .5)
self._periodic_update_status_during_sync = Clock.schedule_interval(self.update_wallet_synchronizing_progress, .5)
# cached dialogs
self._settings_dialog = None
self._password_dialog = None
self.fee_status = self.electrum_config.get_fee_status()
def on_pr(self, pr):
if not self.wallet:
self.show_error(_('No wallet loaded.'))
return
if pr.verify(self.wallet.contacts):
key = self.wallet.invoices.add(pr)
if self.invoices_screen:
self.invoices_screen.update()
status = self.wallet.invoices.get_status(key)
if status == PR_PAID:
self.show_error("invoice already paid")
self.send_screen.do_clear()
else:
if pr.has_expired():
self.show_error(_('Payment request has expired'))
else:
self.switch_to('send')
self.send_screen.set_request(pr)
else:
self.show_error("invoice error:" + pr.error)
self.send_screen.do_clear()
def on_qr(self, data):
from electrum.bitcoin import base_decode, is_address
data = data.strip()
if is_address(data):
self.set_URI(data)
return
if data.startswith('fujicoin:'):
self.set_URI(data)
return
# try to decode transaction
from electrum.transaction import Transaction
from electrum.util import bh2u
try:
text = bh2u(base_decode(data, None, base=43))
tx = Transaction(text)
tx.deserialize()
except:
tx = None
if tx:
self.tx_dialog(tx)
return
# show error
self.show_error("Unable to decode QR data")
def update_tab(self, name):
s = getattr(self, name + '_screen', None)
if s:
s.update()
@profiler
def update_tabs(self):
for tab in ['invoices', 'send', 'history', 'receive', 'address']:
self.update_tab(tab)
def switch_to(self, name):
s = getattr(self, name + '_screen', None)
if s is None:
s = self.tabs.ids[name + '_screen']
s.load_screen()
panel = self.tabs.ids.panel
tab = self.tabs.ids[name + '_tab']
panel.switch_to(tab)
def show_request(self, addr):
self.switch_to('receive')
self.receive_screen.screen.address = addr
def show_pr_details(self, req, status, is_invoice):
from electrum.util import format_time
requestor = req.get('requestor')
exp = req.get('exp')
memo = req.get('memo')
amount = req.get('amount')
fund = req.get('fund')
popup = Builder.load_file('electrum/gui/kivy/uix/ui_screens/invoice.kv')
popup.is_invoice = is_invoice
popup.amount = amount
popup.requestor = requestor if is_invoice else req.get('address')
popup.exp = format_time(exp) if exp else ''
popup.description = memo if memo else ''
popup.signature = req.get('signature', '')
popup.status = status
popup.fund = fund if fund else 0
txid = req.get('txid')
popup.tx_hash = txid or ''
popup.on_open = lambda: popup.ids.output_list.update(req.get('outputs', []))
popup.export = self.export_private_keys
popup.open()
def show_addr_details(self, req, status):
from electrum.util import format_time
fund = req.get('fund')
isaddr = 'y'
popup = Builder.load_file('electrum/gui/kivy/uix/ui_screens/invoice.kv')
popup.isaddr = isaddr
popup.is_invoice = False
popup.status = status
popup.requestor = req.get('address')
popup.fund = fund if fund else 0
popup.export = self.export_private_keys
popup.open()
def qr_dialog(self, title, data, show_text=False, text_for_clipboard=None):
from .uix.dialogs.qr_dialog import QRDialog
def on_qr_failure():
popup.dismiss()
msg = _('Failed to display QR code.')
if text_for_clipboard:
msg += '\n' + _('Text copied to clipboard.')
self._clipboard.copy(text_for_clipboard)
Clock.schedule_once(lambda dt: self.show_info(msg))
popup = QRDialog(title, data, show_text, failure_cb=on_qr_failure,
text_for_clipboard=text_for_clipboard)
popup.open()
def scan_qr(self, on_complete):
if platform != 'android':
return
from jnius import autoclass, cast
from android import activity
PythonActivity = autoclass('org.kivy.android.PythonActivity')
SimpleScannerActivity = autoclass("org.electrum.qr.SimpleScannerActivity")
Intent = autoclass('android.content.Intent')
intent = Intent(PythonActivity.mActivity, SimpleScannerActivity)
def on_qr_result(requestCode, resultCode, intent):
try:
if resultCode == -1: # RESULT_OK:
# this doesn't work due to some bug in jnius:
# contents = intent.getStringExtra("text")
String = autoclass("java.lang.String")
contents = intent.getStringExtra(String("text"))
on_complete(contents)
except Exception as e: # exc would otherwise get lost
send_exception_to_crash_reporter(e)
finally:
activity.unbind(on_activity_result=on_qr_result)
activity.bind(on_activity_result=on_qr_result)
PythonActivity.mActivity.startActivityForResult(intent, 0)
def do_share(self, data, title):
if platform != 'android':
return
from jnius import autoclass, cast
JS = autoclass('java.lang.String')
Intent = autoclass('android.content.Intent')
sendIntent = Intent()
sendIntent.setAction(Intent.ACTION_SEND)
sendIntent.setType("text/plain")
sendIntent.putExtra(Intent.EXTRA_TEXT, JS(data))
PythonActivity = autoclass('org.kivy.android.PythonActivity')
currentActivity = cast('android.app.Activity', PythonActivity.mActivity)
it = Intent.createChooser(sendIntent, cast('java.lang.CharSequence', JS(title)))
currentActivity.startActivity(it)
def build(self):
return Builder.load_file('electrum/gui/kivy/main.kv')
def _pause(self):
if platform == 'android':
# move activity to back
from jnius import autoclass
python_act = autoclass('org.kivy.android.PythonActivity')
mActivity = python_act.mActivity
mActivity.moveTaskToBack(True)
def on_start(self):
''' This is the start point of the kivy ui
'''
import time
Logger.info('Time to on_start: {} <<<<<<<<'.format(time.clock()))
win = Window
win.bind(size=self.on_size, on_keyboard=self.on_keyboard)
win.bind(on_key_down=self.on_key_down)
#win.softinput_mode = 'below_target'
self.on_size(win, win.size)
self.init_ui()
crash_reporter.ExceptionHook(self)
# init plugins
run_hook('init_kivy', self)
# fiat currency
self.fiat_unit = self.fx.ccy if self.fx.is_enabled() else ''
# default tab
self.switch_to('history')
# bind intent for fujicoin: URI scheme
if platform == 'android':
from android import activity
from jnius import autoclass
PythonActivity = autoclass('org.kivy.android.PythonActivity')
mactivity = PythonActivity.mActivity
self.on_new_intent(mactivity.getIntent())
activity.bind(on_new_intent=self.on_new_intent)
# connect callbacks
if self.network:
interests = ['wallet_updated', 'network_updated', 'blockchain_updated',
'status', 'new_transaction', 'verified']
self.network.register_callback(self.on_network_event, interests)
self.network.register_callback(self.on_fee, ['fee'])
self.network.register_callback(self.on_fee_histogram, ['fee_histogram'])
self.network.register_callback(self.on_quotes, ['on_quotes'])
self.network.register_callback(self.on_history, ['on_history'])
# load wallet
self.load_wallet_by_name(self.electrum_config.get_wallet_path())
# URI passed in config
uri = self.electrum_config.get('url')
if uri:
self.set_URI(uri)
def get_wallet_path(self):
if self.wallet:
return self.wallet.storage.path
else:
return ''
def on_wizard_complete(self, wizard, storage):
if storage:
wallet = Wallet(storage)
wallet.start_network(self.daemon.network)
self.daemon.add_wallet(wallet)
self.load_wallet(wallet)
elif not self.wallet:
# wizard did not return a wallet; and there is no wallet open atm
# try to open last saved wallet (potentially start wizard again)
self.load_wallet_by_name(self.electrum_config.get_wallet_path(), ask_if_wizard=True)
def load_wallet_by_name(self, path, ask_if_wizard=False):
if not path:
return
if self.wallet and self.wallet.storage.path == path:
return
wallet = self.daemon.load_wallet(path, None)
if wallet:
if wallet.has_password():
self.password_dialog(wallet, _('Enter PIN code'), lambda x: self.load_wallet(wallet), self.stop)
else:
self.load_wallet(wallet)
else:
def launch_wizard():
wizard = Factory.InstallWizard(self.electrum_config, self.plugins)
wizard.path = path
wizard.bind(on_wizard_complete=self.on_wizard_complete)
storage = WalletStorage(path, manual_upgrades=True)
if not storage.file_exists():
wizard.run('new')
elif storage.is_encrypted():
raise Exception("Kivy GUI does not support encrypted wallet files.")
elif storage.requires_upgrade():
wizard.upgrade_storage(storage)
else:
raise Exception("unexpected storage file situation")
if not ask_if_wizard:
launch_wizard()
else:
from .uix.dialogs.question import Question
def handle_answer(b: bool):
if b:
launch_wizard()
else:
try: os.unlink(path)
except FileNotFoundError: pass
self.stop()
d = Question(_('Do you want to launch the wizard again?'), handle_answer)
d.open()
def on_stop(self):
Logger.info('on_stop')
if self.wallet:
self.electrum_config.save_last_wallet(self.wallet)
self.stop_wallet()
def stop_wallet(self):
if self.wallet:
self.daemon.stop_wallet(self.wallet.storage.path)
self.wallet = None
def on_key_down(self, instance, key, keycode, codepoint, modifiers):
if 'ctrl' in modifiers:
# q=24 w=25
if keycode in (24, 25):
self.stop()
elif keycode == 27:
# r=27
# force update wallet
self.update_wallet()
elif keycode == 112:
# pageup
#TODO move to next tab
pass
elif keycode == 117:
# pagedown
#TODO move to prev tab
pass
#TODO: alt+tab_number to activate the particular tab
def on_keyboard(self, instance, key, keycode, codepoint, modifiers):
if key == 27 and self.is_exit is False:
self.is_exit = True
self.show_info(_('Press again to exit'))
return True
# override settings button
if key in (319, 282): #f1/settings button on android
#self.gui.main_gui.toggle_settings(self)
return True
def settings_dialog(self):
from .uix.dialogs.settings import SettingsDialog
if self._settings_dialog is None:
self._settings_dialog = SettingsDialog(self)
self._settings_dialog.update()
self._settings_dialog.open()
def popup_dialog(self, name):
if name == 'settings':
self.settings_dialog()
elif name == 'wallets':
from .uix.dialogs.wallets import WalletDialog
d = WalletDialog()
d.open()
elif name == 'status':
popup = Builder.load_file('electrum/gui/kivy/uix/ui_screens/'+name+'.kv')
master_public_keys_layout = popup.ids.master_public_keys
for xpub in self.wallet.get_master_public_keys()[1:]:
master_public_keys_layout.add_widget(TopLabel(text=_('Master Public Key')))
ref = RefLabel()
ref.name = _('Master Public Key')
ref.data = xpub
master_public_keys_layout.add_widget(ref)
popup.open()
else:
popup = Builder.load_file('electrum/gui/kivy/uix/ui_screens/'+name+'.kv')
popup.open()
@profiler
def init_ui(self):
''' Initialize The Ux part of electrum. This function performs the basic
tasks of setting up the ui.
'''
#from weakref import ref
self.funds_error = False
# setup UX
self.screens = {}
#setup lazy imports for mainscreen
Factory.register('AnimatedPopup',
module='electrum.gui.kivy.uix.dialogs')
Factory.register('QRCodeWidget',
module='electrum.gui.kivy.uix.qrcodewidget')
# preload widgets. Remove this if you want to load the widgets on demand
#Cache.append('electrum_widgets', 'AnimatedPopup', Factory.AnimatedPopup())
#Cache.append('electrum_widgets', 'QRCodeWidget', Factory.QRCodeWidget())
# load and focus the ui
self.root.manager = self.root.ids['manager']
self.history_screen = None
self.contacts_screen = None
self.send_screen = None
self.invoices_screen = None
self.receive_screen = None
self.requests_screen = None
self.address_screen = None
self.icon = "electrum/gui/icons/electrum.png"
self.tabs = self.root.ids['tabs']
def update_interfaces(self, dt):
net_params = self.network.get_parameters()
self.num_nodes = len(self.network.get_interfaces())
self.num_chains = len(self.network.get_blockchains())
chain = self.network.blockchain()
self.blockchain_forkpoint = chain.get_max_forkpoint()
self.blockchain_name = chain.get_name()
interface = self.network.interface
if interface:
self.server_host = interface.host
else:
self.server_host = str(net_params.host) + ' (connecting...)'
self.proxy_config = net_params.proxy or {}
self.update_proxy_str(self.proxy_config)
def on_network_event(self, event, *args):
Logger.info('network event: '+ event)
if event == 'network_updated':
self._trigger_update_interfaces()
self._trigger_update_status()
elif event == 'wallet_updated':
self._trigger_update_wallet()
self._trigger_update_status()
elif event == 'blockchain_updated':
# to update number of confirmations in history
self._trigger_update_wallet()
elif event == 'status':
self._trigger_update_status()
elif event == 'new_transaction':
self._trigger_update_wallet()
elif event == 'verified':
self._trigger_update_wallet()
@profiler
def load_wallet(self, wallet):
if self.wallet:
self.stop_wallet()
self.wallet = wallet
self.wallet_name = wallet.basename()
self.update_wallet()
# Once GUI has been initialized check if we want to announce something
# since the callback has been called before the GUI was initialized
if self.receive_screen:
self.receive_screen.clear()
self.update_tabs()
run_hook('load_wallet', wallet, self)
try:
wallet.try_detecting_internal_addresses_corruption()
except InternalAddressCorruption as e:
self.show_error(str(e))
send_exception_to_crash_reporter(e)
def update_status(self, *dt):
if not self.wallet:
return
if self.network is None or not self.network.is_connected():
status = _("Offline")
elif self.network.is_connected():
self.num_blocks = self.network.get_local_height()
server_height = self.network.get_server_height()
server_lag = self.num_blocks - server_height
if not self.wallet.up_to_date or server_height == 0:
num_sent, num_answered = self.wallet.get_history_sync_state_details()
status = ("{} [size=18dp]({}/{})[/size]"
.format(_("Synchronizing..."), num_answered, num_sent))
elif server_lag > 1:
status = _("Server is lagging ({} blocks)").format(server_lag)
else:
status = ''
else:
status = _("Disconnected")
if status:
self.balance = status
self.fiat_balance = status
else:
c, u, x = self.wallet.get_balance()
text = self.format_amount(c+x+u)
self.balance = str(text.strip()) + ' [size=22dp]%s[/size]'% self.base_unit
self.fiat_balance = self.fx.format_amount(c+u+x) + ' [size=22dp]%s[/size]'% self.fx.ccy
def update_wallet_synchronizing_progress(self, *dt):
if not self.wallet:
return
if not self.wallet.up_to_date:
self._trigger_update_status()
def get_max_amount(self):
from electrum.transaction import TxOutput
if run_hook('abort_send', self):
return ''
inputs = self.wallet.get_spendable_coins(None, self.electrum_config)
if not inputs:
return ''
addr = str(self.send_screen.screen.address) or self.wallet.dummy_address()
outputs = [TxOutput(TYPE_ADDRESS, addr, '!')]
try:
tx = self.wallet.make_unsigned_transaction(inputs, outputs, self.electrum_config)
except NoDynamicFeeEstimates as e:
Clock.schedule_once(lambda dt, bound_e=e: self.show_error(str(bound_e)))
return ''
except NotEnoughFunds:
return ''
except InternalAddressCorruption as e:
self.show_error(str(e))
send_exception_to_crash_reporter(e)
return ''
amount = tx.output_value()
__, x_fee_amount = run_hook('get_tx_extra_fee', self.wallet, tx) or (None, 0)
amount_after_all_fees = amount - x_fee_amount
return format_satoshis_plain(amount_after_all_fees, self.decimal_point())
def format_amount(self, x, is_diff=False, whitespaces=False):
return format_satoshis(x, 0, self.decimal_point(), is_diff=is_diff, whitespaces=whitespaces)
def format_amount_and_units(self, x):
return format_satoshis_plain(x, self.decimal_point()) + ' ' + self.base_unit
def format_fee_rate(self, fee_rate):
# fee_rate is in sat/kB
return format_fee_satoshis(fee_rate/1000) + ' sat/byte'
#@profiler
def update_wallet(self, *dt):
self._trigger_update_status()
if self.wallet and (self.wallet.up_to_date or not self.network or not self.network.is_connected()):
self.update_tabs()
def notify(self, message):
try:
global notification, os
if not notification:
from plyer import notification
icon = (os.path.dirname(os.path.realpath(__file__))
+ '/../../' + self.icon)
notification.notify('Electrum', message,
app_icon=icon, app_name='Electrum')
except ImportError:
Logger.Error('Notification: needs plyer; `sudo python3 -m pip install plyer`')
def on_pause(self):
self.pause_time = time.time()
# pause nfc
if self.nfcscanner:
self.nfcscanner.nfc_disable()
return True
def on_resume(self):
now = time.time()
if self.wallet and self.wallet.has_password() and now - self.pause_time > 60:
self.password_dialog(self.wallet, _('Enter PIN'), None, self.stop)
if self.nfcscanner:
self.nfcscanner.nfc_enable()
def on_size(self, instance, value):
width, height = value
self._orientation = 'landscape' if width > height else 'portrait'
self._ui_mode = 'tablet' if min(width, height) > inch(3.51) else 'phone'
def on_ref_label(self, label, touch):
if label.touched:
label.touched = False
self.qr_dialog(label.name, label.data, True)
else:
label.touched = True
self._clipboard.copy(label.data)
Clock.schedule_once(lambda dt: self.show_info(_('Text copied to clipboard.\nTap again to display it as QR code.')))
def show_error(self, error, width='200dp', pos=None, arrow_pos=None,
exit=False, icon='atlas://electrum/gui/kivy/theming/light/error', duration=0,
modal=False):
''' Show an error Message Bubble.
'''
self.show_info_bubble( text=error, icon=icon, width=width,
pos=pos or Window.center, arrow_pos=arrow_pos, exit=exit,
duration=duration, modal=modal)
def show_info(self, error, width='200dp', pos=None, arrow_pos=None,
exit=False, duration=0, modal=False):
''' Show an Info Message Bubble.
'''
self.show_error(error, icon='atlas://electrum/gui/kivy/theming/light/important',
duration=duration, modal=modal, exit=exit, pos=pos,
arrow_pos=arrow_pos)
def show_info_bubble(self, text=_('Hello World'), pos=None, duration=0,
arrow_pos='bottom_mid', width=None, icon='', modal=False, exit=False):
'''Method to show an Information Bubble
.. parameters::
text: Message to be displayed
pos: position for the bubble
duration: duration the bubble remains on screen. 0 = click to hide
width: width of the Bubble
arrow_pos: arrow position for the bubble
'''
info_bubble = self.info_bubble
if not info_bubble:
info_bubble = self.info_bubble = Factory.InfoBubble()
win = Window
if info_bubble.parent:
win.remove_widget(info_bubble
if not info_bubble.modal else
info_bubble._modal_view)
if not arrow_pos:
info_bubble.show_arrow = False
else:
info_bubble.show_arrow = True
info_bubble.arrow_pos = arrow_pos
img = info_bubble.ids.img
if text == 'texture':
# icon holds a texture not a source image
# display the texture in full screen
text = ''
img.texture = icon
info_bubble.fs = True
info_bubble.show_arrow = False
img.allow_stretch = True
info_bubble.dim_background = True
info_bubble.background_image = 'atlas://electrum/gui/kivy/theming/light/card'
else:
info_bubble.fs = False
info_bubble.icon = icon
#if img.texture and img._coreimage:
# img.reload()
img.allow_stretch = False
info_bubble.dim_background = False
info_bubble.background_image = 'atlas://data/images/defaulttheme/bubble'
info_bubble.message = text
if not pos:
pos = (win.center[0], win.center[1] - (info_bubble.height/2))
info_bubble.show(pos, duration, width, modal=modal, exit=exit)
def tx_dialog(self, tx):
from .uix.dialogs.tx_dialog import TxDialog
d = TxDialog(self, tx)
d.open()
def sign_tx(self, *args):
threading.Thread(target=self._sign_tx, args=args).start()
def _sign_tx(self, tx, password, on_success, on_failure):
try:
self.wallet.sign_transaction(tx, password)
except InvalidPassword:
Clock.schedule_once(lambda dt: on_failure(_("Invalid PIN")))
return
on_success = run_hook('tc_sign_wrapper', self.wallet, tx, on_success, on_failure) or on_success
Clock.schedule_once(lambda dt: on_success(tx))
def _broadcast_thread(self, tx, on_complete):
status = False
try:
self.network.run_from_another_thread(self.network.broadcast_transaction(tx))
except TxBroadcastError as e:
msg = e.get_message_for_gui()
except BestEffortRequestFailed as e:
msg = repr(e)
else:
status, msg = True, tx.txid()
Clock.schedule_once(lambda dt: on_complete(status, msg))
def broadcast(self, tx, pr=None):
def on_complete(ok, msg):
if ok:
self.show_info(_('Payment sent.'))
if self.send_screen:
self.send_screen.do_clear()
if pr:
self.wallet.invoices.set_paid(pr, tx.txid())
self.wallet.invoices.save()
self.update_tab('invoices')
else:
msg = msg or ''
self.show_error(msg)
if self.network and self.network.is_connected():
self.show_info(_('Sending'))
threading.Thread(target=self._broadcast_thread, args=(tx, on_complete)).start()
else:
self.show_info(_('Cannot broadcast transaction') + ':\n' + _('Not connected'))
def description_dialog(self, screen):
from .uix.dialogs.label_dialog import LabelDialog
text = screen.message
def callback(text):
screen.message = text
d = LabelDialog(_('Enter description'), text, callback)
d.open()
def amount_dialog(self, screen, show_max):
from .uix.dialogs.amount_dialog import AmountDialog
amount = screen.amount
if amount:
amount, u = str(amount).split()
assert u == self.base_unit
def cb(amount):
screen.amount = amount
popup = AmountDialog(show_max, amount, cb)
popup.open()
def invoices_dialog(self, screen):
from .uix.dialogs.invoices import InvoicesDialog
if len(self.wallet.invoices.sorted_list()) == 0:
self.show_info(' '.join([
_('No saved invoices.'),
_('Signed invoices are saved automatically when you scan them.'),
_('You may also save unsigned requests or contact addresses using the save button.')
]))
return
popup = InvoicesDialog(self, screen, None)
popup.update()
popup.open()
def requests_dialog(self, screen):
from .uix.dialogs.requests import RequestsDialog
if len(self.wallet.get_sorted_requests(self.electrum_config)) == 0:
self.show_info(_('No saved requests.'))
return
popup = RequestsDialog(self, screen, None)
popup.update()
popup.open()
def addresses_dialog(self, screen):
from .uix.dialogs.addresses import AddressesDialog
popup = AddressesDialog(self, screen, None)
popup.update()
popup.open()
def fee_dialog(self, label, dt):
from .uix.dialogs.fee_dialog import FeeDialog
def cb():
self.fee_status = self.electrum_config.get_fee_status()
fee_dialog = FeeDialog(self, self.electrum_config, cb)
fee_dialog.open()
def on_fee(self, event, *arg):
self.fee_status = self.electrum_config.get_fee_status()
def protected(self, msg, f, args):
if self.wallet.has_password():
on_success = lambda pw: f(*(args + (pw,)))
self.password_dialog(self.wallet, msg, on_success, lambda: None)
else:
f(*(args + (None,)))
def delete_wallet(self):
from .uix.dialogs.question import Question
basename = os.path.basename(self.wallet.storage.path)
d = Question(_('Delete wallet?') + '\n' + basename, self._delete_wallet)
d.open()
def _delete_wallet(self, b):
if b:
basename = self.wallet.basename()
self.protected(_("Enter your PIN code to confirm deletion of {}").format(basename), self.__delete_wallet, ())
def __delete_wallet(self, pw):
wallet_path = self.get_wallet_path()
dirname = os.path.dirname(wallet_path)
basename = os.path.basename(wallet_path)
if self.wallet.has_password():
try:
self.wallet.check_password(pw)
except:
self.show_error("Invalid PIN")
return
self.stop_wallet()
os.unlink(wallet_path)
self.show_error(_("Wallet removed: {}").format(basename))
new_path = self.electrum_config.get_wallet_path()
self.load_wallet_by_name(new_path)
def show_seed(self, label):
self.protected(_("Enter your PIN code in order to decrypt your seed"), self._show_seed, (label,))
def _show_seed(self, label, password):
if self.wallet.has_password() and password is None:
return
keystore = self.wallet.keystore
try:
seed = keystore.get_seed(password)
passphrase = keystore.get_passphrase(password)
except:
self.show_error("Invalid PIN")
return
label.text = _('Seed') + ':\n' + seed
if passphrase:
label.text += '\n\n' + _('Passphrase') + ': ' + passphrase
def password_dialog(self, wallet, msg, on_success, on_failure):
from .uix.dialogs.password_dialog import PasswordDialog
if self._password_dialog is None:
self._password_dialog = PasswordDialog()
self._password_dialog.init(self, wallet, msg, on_success, on_failure)
self._password_dialog.open()
def change_password(self, cb):
from .uix.dialogs.password_dialog import PasswordDialog
if self._password_dialog is None:
self._password_dialog = PasswordDialog()
message = _("Changing PIN code.") + '\n' + _("Enter your current PIN:")
def on_success(old_password, new_password):
self.wallet.update_password(old_password, new_password)
self.show_info(_("Your PIN code was updated"))
on_failure = lambda: self.show_error(_("PIN codes do not match"))
self._password_dialog.init(self, self.wallet, message, on_success, on_failure, is_change=1)
self._password_dialog.open()
def export_private_keys(self, pk_label, addr):
if self.wallet.is_watching_only():
self.show_info(_('This is a watching-only wallet. It does not contain private keys.'))
return
def show_private_key(addr, pk_label, password):
if self.wallet.has_password() and password is None:
return
if not self.wallet.can_export():
return
try:
key = str(self.wallet.export_private_key(addr, password)[0])
pk_label.data = key
except InvalidPassword:
self.show_error("Invalid PIN")
return
self.protected(_("Enter your PIN code in order to decrypt your private key"), show_private_key, (addr, pk_label))
| fujicoin/electrum-fjc | electrum/gui/kivy/main_window.py | Python | mit | 44,226 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('customers', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='address',
name='recipient',
),
migrations.DeleteModel(
name='Address',
),
migrations.AddField(
model_name='recipient',
name='address_line1',
field=models.CharField(max_length=45, verbose_name=b'Address line 1', blank=True),
preserve_default=True,
),
migrations.AddField(
model_name='recipient',
name='address_line2',
field=models.CharField(max_length=45, verbose_name=b'Address line 2', blank=True),
preserve_default=True,
),
migrations.AddField(
model_name='recipient',
name='city',
field=models.CharField(max_length=50, blank=True),
preserve_default=True,
),
migrations.AddField(
model_name='recipient',
name='country',
field=models.CharField(max_length=40, verbose_name=b'Country', blank=True),
preserve_default=True,
),
migrations.AddField(
model_name='recipient',
name='postal_code',
field=models.CharField(max_length=10, verbose_name=b'Postal Code', blank=True),
preserve_default=True,
),
migrations.AddField(
model_name='recipient',
name='state_province',
field=models.CharField(max_length=40, verbose_name=b'State/Province', blank=True),
preserve_default=True,
),
]
| davogler/POSTv3 | customers/migrations/0002_auto_20150405_1041.py | Python | mit | 1,800 |
class StretchException(Exception):
"""Common base class for all exceptions raised explicitly by stretch.
Exceptions which are subclasses of this type will be handled nicely by
stretch and will not cause the program to exit. Any exceptions raised
which are not a subclass of this type will exit(1) and print a traceback
to stdout.
"""
level = "error"
def __init__(self, message, **kwargs):
Exception.__init__(self, message)
self.message = message
self.kwargs = kwargs
def format_message(self):
return self.message
def __unicode__(self):
return self.message
def __str__(self):
return self.message.encode('utf-8')
| paddycarey/stretch | stretch/exceptions.py | Python | mit | 710 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.12 on 2016-12-06 09:04
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('cms', '0016_auto_20160608_1535'),
('maps', '0002_auto_20160926_1157'),
]
operations = [
migrations.AddField(
model_name='googlemap',
name='cms_page',
field=models.ForeignKey(editable=False, null=True, on_delete=django.db.models.deletion.CASCADE, to='cms.Page'),
),
]
| rouxcode/django-cms-plugins | cmsplugins/maps/migrations/0003_googlemap_cms_page.py | Python | mit | 601 |
import random
import time
import datetime
from consts import *
__all__ = ['gen_valid_id', 'gen_list_page', 'log']
def gen_valid_id(collection):
def gen_id():
_id = ''
for i in range(4):
_id += random.choice('0123456789')
return _id
id = gen_id()
while collection.find_one({'id': id}):
id = gen_id()
return id
def gen_list_page(collection, status, page=1):
page = int(page)
left = (page - 1) * 15
right = left + 15
all = collection.find({'status': status}).sort([('id', 1)])
max_page = int((all.count()-1) / 15) + 1 if all.count() else 0
if page > max_page:
return PAGE_NOT_EXIST
elif page < 1:
return ARGS_INCORRECT
header = '===== {0}/{1} =====\n'.format(page, max_page)
selected = all[left:right]
return header + '\n'.join([
'{id} {title} ({comment})'.format(**i) for i in selected])
def log(m):
with open('log', 'a') as f:
if m.type == 'text': exp=m.content
elif m.type == 'image': exp=m.img
elif m.type == 'link': exp=';'.join([m.title, m.description, m.url])
else: exp=str(dict(m))
f.write(LOG.format(datetime.datetime.fromtimestamp(
time.time()).strftime('%Y-%m-%d %H:%M:%S'), m.source, m.type, exp))
def add_key(key, value):
from pymongo import MongoClient
collection = MongoClient()['SongsDistributor']['collection']
for i in ('checked', 'pending'):
collection.update_many({'status': i}, {'$set': {key: value}})
print('ok')
| oyiadin/Songs-Distributor | utils.py | Python | mit | 1,548 |
import os
path = os.path.dirname(os.path.realpath(__file__))
sbmlFilePath = os.path.join(path, 'BIOMD0000000489.xml')
with open(sbmlFilePath,'r') as f:
sbmlString = f.read()
def module_exists(module_name):
try:
__import__(module_name)
except ImportError:
return False
else:
return True
if module_exists('libsbml'):
import libsbml
sbml = libsbml.readSBMLFromString(sbmlString) | biomodels/BIOMD0000000489 | BIOMD0000000489/model.py | Python | cc0-1.0 | 427 |
print """
Version Info
============
To obtain version info::
from scan.version import __version__, version_history
print __version__
print version_history
"""
import sys
sys.path.append("..")
from scan.version import __version__, version_history
print "Version history::"
for line in version_history.splitlines():
print (" " + line)
| PythonScanClient/PyScanClient | doc/make_version.py | Python | epl-1.0 | 355 |
import linecache
import os.path
import re
import sys
import traceback # @Reimport
from _pydev_bundle import pydev_log
from _pydevd_bundle import pydevd_dont_trace
from _pydevd_bundle import pydevd_vars
from _pydevd_bundle.pydevd_breakpoints import get_exception_breakpoint
from _pydevd_bundle.pydevd_comm import CMD_STEP_CAUGHT_EXCEPTION, CMD_STEP_RETURN, CMD_STEP_OVER, CMD_SET_BREAK, \
CMD_STEP_INTO, CMD_SMART_STEP_INTO, CMD_RUN_TO_LINE, CMD_SET_NEXT_STATEMENT, CMD_STEP_INTO_MY_CODE
from _pydevd_bundle.pydevd_constants import STATE_SUSPEND, dict_contains, get_thread_id, STATE_RUN, dict_iter_values, IS_PY3K, \
dict_keys, dict_pop, RETURN_VALUES_DICT
from _pydevd_bundle.pydevd_dont_trace_files import DONT_TRACE, PYDEV_FILE
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, just_raised
from _pydevd_bundle.pydevd_utils import get_clsname_for_code
from pydevd_file_utils import get_abs_path_real_path_and_base_from_frame
try:
from inspect import CO_GENERATOR
except:
CO_GENERATOR = 0
try:
from _pydevd_bundle.pydevd_signature import send_signature_call_trace
except ImportError:
def send_signature_call_trace(*args, **kwargs):
pass
basename = os.path.basename
IGNORE_EXCEPTION_TAG = re.compile('[^#]*#.*@IgnoreException')
DEBUG_START = ('pydevd.py', 'run')
DEBUG_START_PY3K = ('_pydev_execfile.py', 'execfile')
TRACE_PROPERTY = 'pydevd_traceproperty.py'
get_file_type = DONT_TRACE.get
#=======================================================================================================================
# PyDBFrame
#=======================================================================================================================
class PyDBFrame: # No longer cdef because object was dying when only a reference to trace_dispatch was kept (need to check alternatives).
'''This makes the tracing for a given frame, so, the trace_dispatch
is used initially when we enter into a new context ('call') and then
is reused for the entire context.
'''
#Note: class (and not instance) attributes.
#Same thing in the main debugger but only considering the file contents, while the one in the main debugger
#considers the user input (so, the actual result must be a join of both).
filename_to_lines_where_exceptions_are_ignored = {}
filename_to_stat_info = {}
should_skip = -1
# IFDEF CYTHON
# def __init__(self, args):
# self._args = args # In the cython version we don't need to pass the frame
# ELSE
def __init__(self, args):
#args = main_debugger, filename, base, info, t, frame
#yeap, much faster than putting in self and then getting it from self later on
self._args = args[:-1] # Remove the frame (we don't want to have a reference to it).
# ENDIF
def set_suspend(self, *args, **kwargs):
self._args[0].set_suspend(*args, **kwargs)
def do_wait_suspend(self, *args, **kwargs):
self._args[0].do_wait_suspend(*args, **kwargs)
# IFDEF CYTHON
# def trace_exception(self, frame, str event, arg):
# cdef bint flag;
# ELSE
def trace_exception(self, frame, event, arg):
# ENDIF
if event == 'exception':
flag, frame = self.should_stop_on_exception(frame, event, arg)
if flag:
self.handle_exception(frame, event, arg)
return self.trace_dispatch
return self.trace_exception
# IFDEF CYTHON
# def should_stop_on_exception(self, frame, str event, arg):
# cdef PyDBAdditionalThreadInfo info;
# cdef bint flag;
# ELSE
def should_stop_on_exception(self, frame, event, arg):
# ENDIF
# main_debugger, _filename, info, _thread = self._args
main_debugger = self._args[0]
info = self._args[2]
flag = False
if info.pydev_state != STATE_SUSPEND: #and breakpoint is not None:
exception, value, trace = arg
if trace is not None: #on jython trace is None on the first event
exception_breakpoint = get_exception_breakpoint(
exception, main_debugger.break_on_caught_exceptions)
if exception_breakpoint is not None:
if exception_breakpoint.ignore_libraries:
if exception_breakpoint.notify_on_first_raise_only:
if main_debugger.first_appearance_in_scope(trace):
add_exception_to_frame(frame, (exception, value, trace))
try:
info.pydev_message = exception_breakpoint.qname
except:
info.pydev_message = exception_breakpoint.qname.encode('utf-8')
flag = True
else:
pydev_log.debug("Ignore exception %s in library %s" % (exception, frame.f_code.co_filename))
flag = False
else:
if not exception_breakpoint.notify_on_first_raise_only or just_raised(trace):
add_exception_to_frame(frame, (exception, value, trace))
try:
info.pydev_message = exception_breakpoint.qname
except:
info.pydev_message = exception_breakpoint.qname.encode('utf-8')
flag = True
else:
flag = False
else:
try:
if main_debugger.plugin is not None:
result = main_debugger.plugin.exception_break(main_debugger, self, frame, self._args, arg)
if result:
(flag, frame) = result
except:
flag = False
return flag, frame
def handle_exception(self, frame, event, arg):
try:
# print 'handle_exception', frame.f_lineno, frame.f_code.co_name
# We have 3 things in arg: exception type, description, traceback object
trace_obj = arg[2]
main_debugger = self._args[0]
if not hasattr(trace_obj, 'tb_next'):
return #Not always there on Jython...
initial_trace_obj = trace_obj
if trace_obj.tb_next is None and trace_obj.tb_frame is frame:
#I.e.: tb_next should be only None in the context it was thrown (trace_obj.tb_frame is frame is just a double check).
if main_debugger.break_on_exceptions_thrown_in_same_context:
#Option: Don't break if an exception is caught in the same function from which it is thrown
return
else:
#Get the trace_obj from where the exception was raised...
while trace_obj.tb_next is not None:
trace_obj = trace_obj.tb_next
if main_debugger.ignore_exceptions_thrown_in_lines_with_ignore_exception:
for check_trace_obj in (initial_trace_obj, trace_obj):
filename = get_abs_path_real_path_and_base_from_frame(check_trace_obj.tb_frame)[1]
filename_to_lines_where_exceptions_are_ignored = self.filename_to_lines_where_exceptions_are_ignored
lines_ignored = filename_to_lines_where_exceptions_are_ignored.get(filename)
if lines_ignored is None:
lines_ignored = filename_to_lines_where_exceptions_are_ignored[filename] = {}
try:
curr_stat = os.stat(filename)
curr_stat = (curr_stat.st_size, curr_stat.st_mtime)
except:
curr_stat = None
last_stat = self.filename_to_stat_info.get(filename)
if last_stat != curr_stat:
self.filename_to_stat_info[filename] = curr_stat
lines_ignored.clear()
try:
linecache.checkcache(filename)
except:
#Jython 2.1
linecache.checkcache()
from_user_input = main_debugger.filename_to_lines_where_exceptions_are_ignored.get(filename)
if from_user_input:
merged = {}
merged.update(lines_ignored)
#Override what we have with the related entries that the user entered
merged.update(from_user_input)
else:
merged = lines_ignored
exc_lineno = check_trace_obj.tb_lineno
# print ('lines ignored', lines_ignored)
# print ('user input', from_user_input)
# print ('merged', merged, 'curr', exc_lineno)
if not dict_contains(merged, exc_lineno): #Note: check on merged but update lines_ignored.
try:
line = linecache.getline(filename, exc_lineno, check_trace_obj.tb_frame.f_globals)
except:
#Jython 2.1
line = linecache.getline(filename, exc_lineno)
if IGNORE_EXCEPTION_TAG.match(line) is not None:
lines_ignored[exc_lineno] = 1
return
else:
#Put in the cache saying not to ignore
lines_ignored[exc_lineno] = 0
else:
#Ok, dict has it already cached, so, let's check it...
if merged.get(exc_lineno, 0):
return
thread = self._args[3]
try:
frame_id_to_frame = {}
frame_id_to_frame[id(frame)] = frame
f = trace_obj.tb_frame
while f is not None:
frame_id_to_frame[id(f)] = f
f = f.f_back
f = None
thread_id = get_thread_id(thread)
pydevd_vars.add_additional_frame_by_id(thread_id, frame_id_to_frame)
try:
main_debugger.send_caught_exception_stack(thread, arg, id(frame))
self.set_suspend(thread, CMD_STEP_CAUGHT_EXCEPTION)
self.do_wait_suspend(thread, frame, event, arg)
main_debugger.send_caught_exception_stack_proceeded(thread)
finally:
pydevd_vars.remove_additional_frame_by_id(thread_id)
except:
traceback.print_exc()
main_debugger.set_trace_for_frame_and_parents(frame)
finally:
#Clear some local variables...
trace_obj = None
initial_trace_obj = None
check_trace_obj = None
f = None
frame_id_to_frame = None
main_debugger = None
thread = None
def get_func_name(self, frame):
code_obj = frame.f_code
func_name = code_obj.co_name
try:
cls_name = get_clsname_for_code(code_obj, frame)
if cls_name is not None:
return "%s.%s" % (cls_name, func_name)
else:
return func_name
except:
traceback.print_exc()
return func_name
def manage_return_values(self, main_debugger, frame, event, arg):
try:
if main_debugger.show_return_values:
if event == "return" and hasattr(frame, "f_code") and hasattr(frame.f_code, "co_name"):
if hasattr(frame, "f_back") and hasattr(frame.f_back, "f_locals"):
return_values_dict = frame.f_back.f_locals.get(RETURN_VALUES_DICT, None)
if return_values_dict is None:
return_values_dict = {}
frame.f_back.f_locals[RETURN_VALUES_DICT] = return_values_dict
name = self.get_func_name(frame)
return_values_dict[name] = arg
if main_debugger.remove_return_values_flag:
# Showing return values was turned off, we should remove them from locals dict.
# The values can be in the current frame or in the back one
dict_pop(frame.f_locals, RETURN_VALUES_DICT, None)
if hasattr(frame, "f_back") and hasattr(frame.f_back, "f_locals"):
dict_pop(frame.f_back.f_locals, RETURN_VALUES_DICT, None)
main_debugger.remove_return_values_flag = False
except:
main_debugger.remove_return_values_flag = False
traceback.print_exc()
# IFDEF CYTHON
# def trace_dispatch(self, frame, str event, arg):
# cdef str filename;
# cdef bint is_exception_event;
# cdef bint has_exception_breakpoints;
# cdef bint can_skip;
# cdef PyDBAdditionalThreadInfo info;
# cdef int step_cmd;
# cdef int line;
# cdef str curr_func_name;
# cdef bint exist_result;
# ELSE
def trace_dispatch(self, frame, event, arg):
# ENDIF
main_debugger, filename, info, thread = self._args
try:
# print 'frame trace_dispatch', frame.f_lineno, frame.f_code.co_name, event
info.is_tracing = True
if main_debugger._finish_debugging_session:
return None
if event == 'call' and main_debugger.signature_factory:
send_signature_call_trace(main_debugger, frame, filename)
plugin_manager = main_debugger.plugin
is_exception_event = event == 'exception'
has_exception_breakpoints = main_debugger.break_on_caught_exceptions or main_debugger.has_plugin_exception_breaks
if is_exception_event:
if has_exception_breakpoints:
flag, frame = self.should_stop_on_exception(frame, event, arg)
if flag:
self.handle_exception(frame, event, arg)
return self.trace_dispatch
elif event not in ('line', 'call', 'return'):
#I believe this can only happen in jython on some frontiers on jython and java code, which we don't want to trace.
return None
stop_frame = info.pydev_step_stop
step_cmd = info.pydev_step_cmd
if is_exception_event:
breakpoints_for_file = None
if stop_frame and stop_frame is not frame and step_cmd == CMD_STEP_OVER and \
arg[0] in (StopIteration, GeneratorExit) and arg[2] is None:
info.pydev_step_cmd = CMD_STEP_INTO
info.pydev_step_stop = None
else:
# If we are in single step mode and something causes us to exit the current frame, we need to make sure we break
# eventually. Force the step mode to step into and the step stop frame to None.
# I.e.: F6 in the end of a function should stop in the next possible position (instead of forcing the user
# to make a step in or step over at that location).
# Note: this is especially troublesome when we're skipping code with the
# @DontTrace comment.
if stop_frame is frame and event == 'return' and step_cmd in (CMD_STEP_RETURN, CMD_STEP_OVER):
if not frame.f_code.co_flags & CO_GENERATOR:
info.pydev_step_cmd = CMD_STEP_INTO
info.pydev_step_stop = None
breakpoints_for_file = main_debugger.breakpoints.get(filename)
can_skip = False
if info.pydev_state == STATE_RUN:
#we can skip if:
#- we have no stop marked
#- we should make a step return/step over and we're not in the current frame
can_skip = (step_cmd == -1 and stop_frame is None)\
or (step_cmd in (CMD_STEP_RETURN, CMD_STEP_OVER) and stop_frame is not frame)
if can_skip and plugin_manager is not None and main_debugger.has_plugin_line_breaks:
can_skip = not plugin_manager.can_not_skip(main_debugger, self, frame)
if can_skip and main_debugger.show_return_values:
# trace function for showing return values after step over
if info.pydev_step_cmd == CMD_STEP_OVER and hasattr(frame, "f_back") and frame.f_back == info.pydev_step_stop:
can_skip = False
# Let's check to see if we are in a function that has a breakpoint. If we don't have a breakpoint,
# we will return nothing for the next trace
#also, after we hit a breakpoint and go to some other debugging state, we have to force the set trace anyway,
#so, that's why the additional checks are there.
if not breakpoints_for_file:
if can_skip:
if has_exception_breakpoints:
return self.trace_exception
else:
return None
else:
#checks the breakpoint to see if there is a context match in some function
curr_func_name = frame.f_code.co_name
#global context is set with an empty name
if curr_func_name in ('?', '<module>'):
curr_func_name = ''
for breakpoint in dict_iter_values(breakpoints_for_file): #jython does not support itervalues()
#will match either global or some function
if breakpoint.func_name in ('None', curr_func_name):
break
else: # if we had some break, it won't get here (so, that's a context that we want to skip)
if can_skip:
if has_exception_breakpoints:
return self.trace_exception
else:
return None
#We may have hit a breakpoint or we are already in step mode. Either way, let's check what we should do in this frame
#print 'NOT skipped', frame.f_lineno, frame.f_code.co_name, event
try:
line = frame.f_lineno
flag = False
#return is not taken into account for breakpoint hit because we'd have a double-hit in this case
#(one for the line and the other for the return).
stop_info = {}
breakpoint = None
exist_result = False
stop = False
bp_type = None
if not flag and event != 'return' and info.pydev_state != STATE_SUSPEND and breakpoints_for_file is not None \
and dict_contains(breakpoints_for_file, line):
breakpoint = breakpoints_for_file[line]
new_frame = frame
stop = True
if step_cmd == CMD_STEP_OVER and stop_frame is frame and event in ('line', 'return'):
stop = False #we don't stop on breakpoint if we have to stop by step-over (it will be processed later)
elif plugin_manager is not None and main_debugger.has_plugin_line_breaks:
result = plugin_manager.get_breakpoint(main_debugger, self, frame, event, self._args)
if result:
exist_result = True
(flag, breakpoint, new_frame, bp_type) = result
if breakpoint:
#ok, hit breakpoint, now, we have to discover if it is a conditional breakpoint
# lets do the conditional stuff here
if stop or exist_result:
condition = breakpoint.condition
if condition is not None:
try:
val = eval(condition, new_frame.f_globals, new_frame.f_locals)
if not val:
return self.trace_dispatch
except:
if type(condition) != type(''):
if hasattr(condition, 'encode'):
condition = condition.encode('utf-8')
msg = 'Error while evaluating expression: %s\n' % (condition,)
sys.stderr.write(msg)
traceback.print_exc()
if not main_debugger.suspend_on_breakpoint_exception:
return self.trace_dispatch
else:
stop = True
try:
# add exception_type and stacktrace into thread additional info
etype, value, tb = sys.exc_info()
try:
error = ''.join(traceback.format_exception_only(etype, value))
stack = traceback.extract_stack(f=tb.tb_frame.f_back)
# On self.set_suspend(thread, CMD_SET_BREAK) this info will be
# sent to the client.
info.conditional_breakpoint_exception = \
('Condition:\n' + condition + '\n\nError:\n' + error, stack)
finally:
etype, value, tb = None, None, None
except:
traceback.print_exc()
if breakpoint.expression is not None:
try:
try:
val = eval(breakpoint.expression, new_frame.f_globals, new_frame.f_locals)
except:
val = sys.exc_info()[1]
finally:
if val is not None:
info.pydev_message = str(val)
if not main_debugger.first_breakpoint_reached:
if event == 'call':
if hasattr(frame, 'f_back'):
back = frame.f_back
if back is not None:
# When we start debug session, we call execfile in pydevd run function. It produces an additional
# 'call' event for tracing and we stop on the first line of code twice.
_, back_filename, base = get_abs_path_real_path_and_base_from_frame(back)
if (base == DEBUG_START[0] and back.f_code.co_name == DEBUG_START[1]) or \
(base == DEBUG_START_PY3K[0] and back.f_code.co_name == DEBUG_START_PY3K[1]):
stop = False
main_debugger.first_breakpoint_reached = True
else:
# if the frame is traced after breakpoint stop,
# but the file should be ignored while stepping because of filters
if step_cmd != -1:
if main_debugger.is_filter_enabled and main_debugger.is_ignored_by_filters(filename):
# ignore files matching stepping filters
return self.trace_dispatch
if main_debugger.is_filter_libraries and main_debugger.not_in_scope(filename):
# ignore library files while stepping
return self.trace_dispatch
if main_debugger.show_return_values or main_debugger.remove_return_values_flag:
self.manage_return_values(main_debugger, frame, event, arg)
if stop:
self.set_suspend(thread, CMD_SET_BREAK)
if breakpoint and breakpoint.suspend_policy == "ALL":
main_debugger.suspend_all_other_threads(thread)
elif flag and plugin_manager is not None:
result = plugin_manager.suspend(main_debugger, thread, frame, bp_type)
if result:
frame = result
# if thread has a suspend flag, we suspend with a busy wait
if info.pydev_state == STATE_SUSPEND:
self.do_wait_suspend(thread, frame, event, arg)
return self.trace_dispatch
except:
traceback.print_exc()
raise
#step handling. We stop when we hit the right frame
try:
should_skip = 0
if pydevd_dont_trace.should_trace_hook is not None:
if self.should_skip == -1:
# I.e.: cache the result on self.should_skip (no need to evaluate the same frame multiple times).
# Note that on a code reload, we won't re-evaluate this because in practice, the frame.f_code
# Which will be handled by this frame is read-only, so, we can cache it safely.
if not pydevd_dont_trace.should_trace_hook(frame, filename):
# -1, 0, 1 to be Cython-friendly
should_skip = self.should_skip = 1
else:
should_skip = self.should_skip = 0
else:
should_skip = self.should_skip
plugin_stop = False
if should_skip:
stop = False
elif step_cmd == CMD_STEP_INTO:
stop = event in ('line', 'return')
if plugin_manager is not None:
result = plugin_manager.cmd_step_into(main_debugger, frame, event, self._args, stop_info, stop)
if result:
stop, plugin_stop = result
elif step_cmd == CMD_STEP_INTO_MY_CODE:
if not main_debugger.not_in_scope(frame.f_code.co_filename):
stop = event == 'line'
elif step_cmd == CMD_STEP_OVER:
stop = stop_frame is frame and event in ('line', 'return')
if frame.f_code.co_flags & CO_GENERATOR:
if event == 'return':
stop = False
if plugin_manager is not None:
result = plugin_manager.cmd_step_over(main_debugger, frame, event, self._args, stop_info, stop)
if result:
stop, plugin_stop = result
elif step_cmd == CMD_SMART_STEP_INTO:
stop = False
if info.pydev_smart_step_stop is frame:
info.pydev_func_name = '.invalid.' # Must match the type in cython
info.pydev_smart_step_stop = None
if event == 'line' or event == 'exception':
curr_func_name = frame.f_code.co_name
#global context is set with an empty name
if curr_func_name in ('?', '<module>') or curr_func_name is None:
curr_func_name = ''
if curr_func_name == info.pydev_func_name:
stop = True
elif step_cmd == CMD_STEP_RETURN:
stop = event == 'return' and stop_frame is frame
elif step_cmd == CMD_RUN_TO_LINE or step_cmd == CMD_SET_NEXT_STATEMENT:
stop = False
if event == 'line' or event == 'exception':
#Yes, we can only act on line events (weird hum?)
#Note: This code is duplicated at pydevd.py
#Acting on exception events after debugger breaks with exception
curr_func_name = frame.f_code.co_name
#global context is set with an empty name
if curr_func_name in ('?', '<module>'):
curr_func_name = ''
if curr_func_name == info.pydev_func_name:
line = info.pydev_next_line
if frame.f_lineno == line:
stop = True
else:
if frame.f_trace is None:
frame.f_trace = self.trace_dispatch
frame.f_lineno = line
frame.f_trace = None
stop = True
else:
stop = False
if stop and step_cmd != -1 and IS_PY3K:
# in Py3k we start script via our custom `execfile` function, and we shouldn't stop there
# while stepping when execution is finished
if event == 'return' and hasattr(frame, "f_back") and hasattr(frame.f_back, "f_code"):
back_filename = os.path.basename(frame.f_back.f_code.co_filename)
file_type = get_file_type(back_filename)
if file_type == PYDEV_FILE:
stop = False
if plugin_stop:
stopped_on_plugin = plugin_manager.stop(main_debugger, frame, event, self._args, stop_info, arg, step_cmd)
elif stop:
if event == 'line':
self.set_suspend(thread, step_cmd)
self.do_wait_suspend(thread, frame, event, arg)
else: #return event
back = frame.f_back
if back is not None:
#When we get to the pydevd run function, the debugging has actually finished for the main thread
#(note that it can still go on for other threads, but for this one, we just make it finish)
#So, just setting it to None should be OK
_, back_filename, base = get_abs_path_real_path_and_base_from_frame(back)
if base == DEBUG_START[0] and back.f_code.co_name == DEBUG_START[1]:
back = None
elif base == TRACE_PROPERTY:
# We dont want to trace the return event of pydevd_traceproperty (custom property for debugging)
#if we're in a return, we want it to appear to the user in the previous frame!
return None
elif pydevd_dont_trace.should_trace_hook is not None:
if not pydevd_dont_trace.should_trace_hook(back, back_filename):
# In this case, we'll have to skip the previous one because it shouldn't be traced.
# Also, we have to reset the tracing, because if the parent's parent (or some
# other parent) has to be traced and it's not currently, we wouldn't stop where
# we should anymore (so, a step in/over/return may not stop anywhere if no parent is traced).
# Related test: _debugger_case17a.py
main_debugger.set_trace_for_frame_and_parents(back, overwrite_prev_trace=True)
return None
if back is not None:
#if we're in a return, we want it to appear to the user in the previous frame!
self.set_suspend(thread, step_cmd)
self.do_wait_suspend(thread, back, event, arg)
else:
#in jython we may not have a back frame
info.pydev_step_stop = None
info.pydev_step_cmd = -1
info.pydev_state = STATE_RUN
except KeyboardInterrupt:
raise
except:
try:
traceback.print_exc()
info.pydev_step_cmd = -1
except:
return None
#if we are quitting, let's stop the tracing
retVal = None
if not main_debugger.quitting:
retVal = self.trace_dispatch
return retVal
finally:
info.is_tracing = False
#end trace_dispatch
| RandallDW/Aruba_plugin | plugins/org.python.pydev/pysrc/_pydevd_bundle/pydevd_frame.py | Python | epl-1.0 | 33,951 |
# module General Ui
# file ui_maya_dock.py
# Main Dock Window interface
from thlib.side.Qt import QtWidgets as QtGui
#from thlib.side.Qt import QtCore
from thlib.environment import env_inst, env_mode, env_read_config, env_write_config
import thlib.maya_functions as mf
import thlib.tactic_classes as tc
import thlib.global_functions as gf
from maya.app.general.mayaMixin import MayaQWidgetDockableMixin
import maya.cmds as cmds
import ui_main_classes
# reload(ui_main_classes)
class Ui_DockMain(MayaQWidgetDockableMixin, QtGui.QMainWindow):
def __init__(self, parent=None):
super(self.__class__, self).__init__(parent=parent)
env_inst.ui_maya_dock = self
self.setObjectName('TacticHandlerDock')
self.docked = None
self.dock_pos = None
self.dock_area = None
self.dock_size = None
self.dock_is_floating = None
self.readSettings()
self.toggle_dock = None
self.maya_dock = None
self.status_bar = None
self.create_ui_main()
self.create_ui()
self.catch_maya_closing()
def create_ui(self):
if self.docked:
self.set_docked()
else:
self.set_undocked()
def toggle_docking(self):
if self.toggle_dock:
self.set_undocked()
else:
self.set_docked()
def create_ui_main(self):
env_inst.ui_main = ui_main_classes.Ui_Main()
self.setCentralWidget(env_inst.ui_main)
self.setWindowTitle(env_inst.ui_main.windowTitle())
self.move(self.dock_pos)
def set_docked(self):
# status_bar = env_inst.ui_main.statusBar()
# if status_bar:
# status_bar.show()
self.toggle_dock = True
self.setDockableParameters(
dockable=True,
floating=self.dock_is_floating,
area=self.dock_area,
width=self.dock_size.width(),
height=self.dock_size.height()
)
self.show()
self.raise_()
self.docked = True
def set_undocked(self):
self.toggle_dock = False
self.setDockableParameters(
dockable=False,
floating=self.dock_is_floating,
area=self.dock_area,
width=self.dock_size.width(),
height=self.dock_size.height()
)
if self.maya_dock:
print self.maya_dock
self.removeDockWidget(self.maya_dock)
self.maya_dock.close()
self.maya_dock.deleteLater()
self.docked = False
# status_bar = env_inst.ui_main.statusBar()
# status_bar.show()
def set_settings_from_dict(self, settings_dict=None):
ref_settings_dict = {
'docked': 0,
'dock_pos': (200, 200),
'dock_size': (427, 690),
'dock_isFloating': 0,
'dock_tabArea': 1,
}
settings = gf.check_config(ref_settings_dict, settings_dict)
self.docked = bool(int(settings['docked']))
self.dock_pos = gf.tuple_to_qsize(settings['dock_pos'], 'pos')
self.dock_size = gf.tuple_to_qsize(settings['dock_size'], 'size')
self.dock_is_floating = bool(int(settings['dock_isFloating']))
if int(settings['dock_tabArea']) == 2:
self.dock_area = 'right'
else:
self.dock_area = 'left'
def get_settings_dict(self):
settings_dict = {
'docked': int(self.docked),
}
if self.docked:
maya_dock = self.parent()
settings_dict['dock_pos'] = gf.qsize_to_tuple(maya_dock.pos())
settings_dict['dock_size'] = gf.qsize_to_tuple(maya_dock.size())
settings_dict['dock_isFloating'] = int(bool(self.isFloating()))
settings_dict['dock_tabArea'] = int(env_inst.ui_super.dockWidgetArea(self.maya_dock))
else:
settings_dict['dock_pos'] = gf.qsize_to_tuple(self.pos())
settings_dict['dock_size'] = gf.qsize_to_tuple(self.size())
settings_dict['dock_isFloating'] = 0
settings_dict['dock_tabArea'] = 1
return settings_dict
def readSettings(self):
self.set_settings_from_dict(
env_read_config(filename='ui_maya_settings', unique_id='ui_main', long_abs_path=True)
)
def writeSettings(self):
env_write_config(self.get_settings_dict(), filename='ui_maya_settings', unique_id='ui_main', long_abs_path=True)
def raise_window(self):
if self.isMaximized():
self.showMaximized()
else:
self.showNormal()
QtGui.QDialog.activateWindow(self)
def catch_maya_closing(self):
QtGui.QApplication.instance().aboutToQuit.connect(env_inst.ui_main.close)
QtGui.QApplication.instance().aboutToQuit.connect(self.close)
def closeEvent(self, event):
if self.docked:
self.removeDockWidget(self.maya_dock)
self.maya_dock.close()
self.maya_dock.deleteLater()
self.writeSettings()
event.accept()
def init_env(current_path):
env_mode.set_current_path(current_path)
env_mode.set_mode('maya')
def close_all_instances():
try:
main_docks = mf.get_maya_dock_window()
for dock in main_docks:
dock.writeSettings()
dock.close()
dock.deleteLater()
if env_inst.ui_main:
env_inst.ui_main.close()
if cmds.workspaceControl('TacticHandlerDockWorkspaceControl', e=True, exists=True):
cmds.deleteUI('TacticHandlerDockWorkspaceControl', control=True)
except:
raise
@gf.catch_error
def create_ui(error_tuple=None):
if error_tuple:
env_mode.set_offline()
main_tab = Ui_DockMain()
gf.error_handle(error_tuple)
else:
env_mode.set_online()
main_tab = Ui_DockMain()
main_tab.show()
main_tab.raise_()
@gf.catch_error
def startup(restart=False, *args, **kwargs):
if restart:
close_all_instances()
env_inst.ui_super = mf.get_maya_window()
try:
main_tab = mf.get_maya_dock_window()[0]
main_tab.show()
main_tab.raise_()
main_tab.raise_window()
except:
# def server_ping_agent():
# return tc.server_ping()
#
# ping_worker, thread_pool = gf.get_thread_worker(
# server_ping_agent,
# finished_func=lambda: create_ui(None),
# error_func=create_ui
# )
#
# thread_pool.start(ping_worker)
env_inst.start_pools()
worker = env_inst.server_pool.add_task(tc.server_ping)
worker.finished.connect(create_ui)
worker.error.connect(create_ui)
worker.start()
| listyque/TACTIC-Handler | thlib/ui_classes/ui_maya_dock.py | Python | epl-1.0 | 6,812 |
#!/usr/bin/env python
import os,sys,time
import numpy as np
import bitarray
import tables as tb
import logging
import yaml
import matplotlib.pyplot as plt
import monopix_daq.scan_base as scan_base
import monopix_daq.analysis.interpreter as interpreter
local_configuration={"exp_time": 1.0,
"cnt_th": 1,
"n_pix": 512,
"th_start": 0.85,
"th_stop": 0.5,
"th_step":[-0.01,-0.002,-0.0005]
}
class EnTune(scan_base.ScanBase):
scan_id = "en_tune"
def scan(self,**kwargs):
th=kwargs.pop("th_start",0.85)
th_stop=kwargs.pop("th_stop",0.5)
th_step=kwargs.pop("th_step",[-0.01,-0.002,-0.0005])
cnt_th=kwargs.pop("cnt_th",1)
exp_time=kwargs.pop("exp_time",1.0)
n_pix=kwargs.pop("n_pix",512)
####################
## create a table for scan_params
param_dtype=[("scan_param_id","<i4"),("th","<f2")]
description=np.zeros((1,),dtype=param_dtype).dtype
self.scan_param_table = self.h5_file.create_table(self.h5_file.root,
name='scan_parameters', title='scan_parameters',
description=description, filters=self.filter_tables)
scan_param_id=0
en_org=np.copy(self.dut.PIXEL_CONF["PREAMP_EN"][:,:])
th_step_i=0
fig,ax=plt.subplots(2,2)
plt.ion()
while th > th_stop or th_step_i==len(th_step):
self.monopix.set_th(th)
en=np.copy(self.dut.PIXEL_CONF["PREAMP_EN"][:,:])
self.monopix.set_monoread()
with self.readout(scan_param_id=scan_param_id,fill_buffer=True,clear_buffer=True,
readout_interval=0.005):
time.sleep(exp_time)
self.monopix.stop_monoread()
scan_param_id=scan_param_id+1
##########################
### get data from buffer
buf = self.fifo_readout.data
if len(buf)==0:
self.logger.info("en_tune:th=%.4f pix=%d, no data"%(th,len(np.argwhere(en))))
th=th+th_step[th_step_i]
continue
elif th_step_i!=(len(th_step)-1):
self.logger.info("en_tune:th=%.4f step=%.4f "%(th,th_step[th_step_i]))
th=th-th_step[th_step_i]
th_step_i=th_step_i+1
continue
data = np.concatenate([buf.popleft()[0] for i in range(len(buf))])
img=interpreter.raw2img(data,delete_noise=False)
##########################
## showing status
self.logger.info("en_tune:==== %.4f===data %d=====cnt %d======en %d====="%(
th,len(data),np.sum(img), len(en[en])))
ax[0,0].cla()
ax[0,0].imshow(np.transpose(img),vmax=min(np.max(img),100),origin="low",aspect="auto")
ax[0,0].set_title("th=%.4f"%th)
ax[1,0].cla()
ax[1,0].imshow(np.transpose(self.monopix.get_tdac_memory()),vmax=16,vmin=0,origin="low",aspect="auto")
ax[0,1].cla()
ax[0,1].imshow(np.transpose(en),vmax=1,vmin=0,origin="low",aspect="auto")
ax[0,1].set_title("en=%d"%len(np.where(en)))
fig.tight_layout()
fig.savefig(os.path.join(self.working_dir,"last_scan.png"),format="png")
plt.pause(0.003)
##########################
### find noisy
arg=np.argwhere(img>cnt_th)
s="en_tune:noisy pixel %d"%len(arg)
for a in arg:
s="[%d,%d]=%d"%(a[0],a[1],img[a[0],a[1]]),
self.logger.info(s)
self.logger.info("en_tune:th=%.4f en=%d"%(th,len(np.argwhere(en))))
en=np.bitwise_and(en,img<=cnt_th)
if n_pix >= len(np.argwhere(en)):
self.monopix.set_th(th-th_step[th_step_i])
break
else:
th=th+th_step[th_step_i]
self.monopix.set_preamp_en(en)
self.logger.info("en_tune:th=%.4f en=%d"%(
self.dut.SET_VALUE["TH"],
len(np.argwhere(self.dut.PIXEL_CONF["PREAMP_EN"][:,:]))
))
def analyze(self):
pass
def plot(self):
fraw = self.output_filename +'.h5'
fpdf = self.output_filename +'.pdf'
import monopix_daq.analysis.plotting_base as plotting_base
with plotting_base.PlottingBase(fpdf,save_png=True) as plotting:
with tb.open_file(fraw) as f:
firmware=yaml.load(f.root.meta_data.attrs.firmware)
## DAC Configuration page
dat=yaml.load(f.root.meta_data.attrs.dac_status)
dat.update(yaml.load(f.root.meta_data.attrs.power_status))
plotting.table_1value(dat,page_title="Chip configuration")
## Pixel Configuration page (before tuning)
dat=yaml.load(f.root.meta_data.attrs.pixel_conf_before)
plotting.plot_2d_pixel_4(
[dat["PREAMP_EN"],dat["INJECT_EN"],dat["MONITOR_EN"],dat["TRIM_EN"]],
page_title="Pixel configuration before tuninig",
title=["Preamp","Inj","Mon","TDAC"],
z_min=[0,0,0,0], z_max=[1,1,1,15])
## Preamp Configuration
dat=yaml.load(f.root.meta_data.attrs.pixel_conf)
plotting.plot_2d_pixel_hist(np.array(dat["PREAMP_EN"]),
title="Enabled preamp",
z_max=1)
if __name__ == "__main__":
from monopix_daq import monopix
import argparse
parser = argparse.ArgumentParser(usage="python en_tune.py",
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument("--config_file", type=str, default=None)
parser.add_argument('-e',"--exp_time", type=float, default=local_configuration["exp_time"])
parser.add_argument('-npix',"--n_pix", type=float, default=local_configuration["n_pix"])
parser.add_argument('-t',"--th_start", type=float, default=local_configuration["th_start"])
parser.add_argument("-f","--flavor", type=str, default="28:32")
parser.add_argument("--tdac", type=int, default=None)
parser.add_argument("--LSBdacL", type=int, default=None)
parser.add_argument("-p","--power_reset", action='store_const', const=1, default=0) ## defualt=True: skip power reset
parser.add_argument("-fout","--output_file", type=str, default=None)
args=parser.parse_args()
local_configuration["exp_time"]=args.exp_time
local_configuration["n_pix"]=args.n_pix
local_configuration["th_start"]=args.th_start
m=monopix.Monopix(no_power_reset=not bool(args.power_reset))
scan = EnTune(m, fout=args.output_file, online_monitor_addr="tcp://127.0.0.1:6500")
if args.config_file is not None:
m.load_config(args.config_file)
if args.flavor is not None:
m.set_preamp_en("none")
if args.flavor=="all":
collist=np.arange(0,36,1)
else:
tmp=args.flavor.split(":")
collist=np.arange(int(tmp[0]),int(tmp[1]),1)
en=np.copy(m.dut.PIXEL_CONF["PREAMP_EN"][:,:])
for c in collist:
en[c,:]=True
m.set_preamp_en(en)
if args.tdac is not None:
m.set_tdac(args.tdac)
if args.LSBdacL is not None:
m.set_global(LSBdacL=args.LSBdacL)
scan.start(**local_configuration)
#scan.analyze()
scan.plot()
| SiLab-Bonn/monopix_daq | monopix_daq/scans/en_tune.py | Python | gpl-2.0 | 7,608 |
#!/usr/bin/env python
#
# MountDirectories.py: this file is part of the GRS suite
# Copyright (C) 2015 Anthony G. Basile
#
# This program 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.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
from copy import deepcopy
from grs.Constants import CONST
from grs.Execute import Execute
class MountDirectories():
""" This controls the mounting/unmounting of directories under the system's
portage configroot.
"""
def __init__(self, portage_configroot=CONST.PORTAGE_CONFIGROOT, \
package=CONST.PACKAGE, portage=CONST.PORTAGE, logfile=CONST.LOGFILE):
# The order is respected. Note that 'dev' needs to be mounted beore 'dev/pts'.
self.directories = [
'dev',
'dev/pts',
{'dev/shm' : ('tmpfs', 'shm')},
'proc',
'sys',
[portage, 'usr/portage'],
[package, 'usr/portage/packages']
]
# Once initiated, we only work with one portage_configroot
self.portage_configroot = portage_configroot
self.package = package
self.portage = portage
self.logfile = logfile
# We need to umount in the reverse order
self.rev_directories = deepcopy(self.directories)
self.rev_directories.reverse()
def ismounted(self, mountpoint):
""" Obtain all the current mountpoints. Since python's os.path.ismount()
fails for for bind mounts, we obtain these ourselves from /proc/mounts.
"""
mountpoints = []
for line in open('/proc/mounts', 'r').readlines():
mountpoints.append(line.split()[1])
# Let's make sure mountoint is canonical real path, no sym links, since that's
# what /proc/mounts reports. Otherwise we can get a false negative on matching.
mountpoint = os.path.realpath(mountpoint)
return mountpoint in mountpoints
def are_mounted(self):
""" Return whether some or all of the self.directories[] are mounted. """
some_mounted = False
all_mounted = True
for mount in self.directories:
if isinstance(mount, str):
target_directory = mount
elif isinstance(mount, list):
target_directory = mount[1]
elif isinstance(mount, dict):
tmp = list(mount.keys())
target_directory = tmp[0]
target_directory = os.path.join(self.portage_configroot, target_directory)
if self.ismounted(target_directory):
some_mounted = True
else:
all_mounted = False
return some_mounted, all_mounted
def mount_all(self):
""" Mount all the self.directories[] under the system's portage configroot. """
# If any are mounted, let's first unmount all, then mount all
some_mounted, all_mounted = self.are_mounted()
if some_mounted:
self.umount_all()
# Now go through each of the self.directories[] to be mounted in order.
for mount in self.directories:
if isinstance(mount, str):
# In this case, the source_directory is assumed to exist relative to /
# and we will just bind mount it in the system's portage configroot.
source_directory = mount
target_directory = mount
elif isinstance(mount, list):
# In this case, the source_directory is assumed to be an abspath, and
# we create it if it doesn't already exist.
source_directory = mount[0]
os.makedirs(source_directory, mode=0o755, exist_ok=True)
target_directory = mount[1]
elif isinstance(mount, dict):
# In this case, we are given the mountpoint, type and name,
# so we just go right ahead and mount -t type name mountpoint.
# This is useful for tmpfs filesystems.
tmp = list(mount.values())
tmp = tmp[0]
vfstype = tmp[0]
vfsname = tmp[1]
tmp = list(mount.keys())
target_directory = tmp[0]
# Let's make sure the target_directory exists.
target_directory = os.path.join(self.portage_configroot, target_directory)
os.makedirs(target_directory, mode=0o755, exist_ok=True)
# Okay now we're ready to do the actual mounting.
if isinstance(mount, str):
cmd = 'mount --bind /%s %s' % (source_directory, target_directory)
elif isinstance(mount, list):
cmd = 'mount --bind %s %s' % (source_directory, target_directory)
elif isinstance(mount, dict):
cmd = 'mount -t %s %s %s' % (vfstype, vfsname, target_directory)
Execute(cmd, timeout=60, logfile=self.logfile)
def umount_all(self):
""" Unmount all the self.directories[]. """
# We must unmount in the opposite order that we mounted.
for mount in self.rev_directories:
if isinstance(mount, str):
target_directory = mount
elif isinstance(mount, list):
target_directory = mount[1]
elif isinstance(mount, dict):
tmp = list(mount.keys())
target_directory = tmp[0]
target_directory = os.path.join(self.portage_configroot, target_directory)
if self.ismounted(target_directory):
cmd = 'umount --force %s' % target_directory
Execute(cmd, timeout=60, logfile=self.logfile)
| gentoo/grss | grs/MountDirectories.py | Python | gpl-2.0 | 6,242 |
import pytest
import subprocess
import tempfile
import shutil
import os
import config
import time
import pymongo
@pytest.fixture(scope='session')
def mongod(request):
subprocess.call(['pkill', '-f', 'mongod*tmp'])
server = MongoServer()
server.start()
def stop():
server.stop()
server.clean()
request.addfinalizer(stop)
from tests.base_test_case import BaseTestCase
BaseTestCase.mongod = server
return server
@pytest.fixture(scope='session')
def exclusive_tests(request):
subprocess.call(['pkill', '-f', 'code/server/app.py'])
class MongoServer(object):
def __init__(self):
self.tmp_path = tempfile.mkdtemp()
self.db_path = os.path.join(self.tmp_path, 'db')
os.mkdir(self.db_path)
def start(self):
self.server = subprocess.Popen(
['mongod', '--dbpath', self.db_path, '--port',
str(config.MONGO_PORT), '--smallfiles']
)
self.wait_alive()
def stop(self):
self.server.terminate()
self.server.wait()
def clean(self):
shutil.rmtree(self.tmp_path)
def drop_db(self):
client = pymongo.MongoClient(config.MONGO_URL())
client.drop_database(config.MONGO_DB_NAME)
def wait_alive(self):
while True:
try:
client = pymongo.MongoClient(config.MONGO_URL())
result = client.admin.command('ping')
if result['ok']:
break
except:
pass
time.sleep(0.1)
| alexander-gridnev/mongstore | code/server/tests/conftest.py | Python | gpl-2.0 | 1,564 |
import Levenshtein
import re
from prisoners import db
from prisoners.models.original import Gedetineerde
#prisonersmatch = db.Table('PrisonersMatch',
# db.Column('master_id_ged', db.Integer, db.ForeignKey('PrisonersCompare.id_gedetineerde')),
# db.Column('slave_id_ged', db.Integer, db.ForeignKey('PrisonersCompare.c_id_gedetineerde'))
# )
class PrisonersMatch(db.Model):
__tablename__ = 'PrisonersMatch'
id = db.Column(db.Integer, primary_key=True)
master_id_ged = db.Column(db.Integer, db.ForeignKey('PrisonersCompare.id_gedetineerde'))
slave_id_ged = db.Column(db.Integer, db.ForeignKey('PrisonersCompare.c_id_gedetineerde'))
class PrisonersCompare(db.Model):
__tablename__ = 'PrisonersCompare'
id = db.Column(db.Integer, primary_key=True)
id_gedetineerde = db.Column(db.Integer, db.ForeignKey(Gedetineerde.Id_gedetineerde))
Voornaam = db.Column(db.String(255), nullable=False, index=True)
Naam = db.Column(db.String(255), nullable=False, index=True)
Geboortejaar = db.Column(db.Integer, index=True)
Geboortemaand = db.Column(db.Integer, index=True)
Geboortedag = db.Column(db.Integer, index=True)
Geboorteplaats = db.Column(db.String(255), index=True, nullable=False)
c_id_gedetineerde = db.Column(db.Integer, index=True)
c_voornaam = db.Column(db.String(255), nullable=False, index=True)
c_naam = db.Column(db.String(255), nullable=False, index=True)
c_geboortejaar = db.Column(db.Integer, index=True)
c_geboortemaand = db.Column(db.Integer, index=True)
c_geboortedag = db.Column(db.Integer, index=True)
c_geboorteplaats = db.Column(db.String(255), index=True, nullable=False)
has_been_checked = db.Column(db.Boolean, nullable=False, default=False)
l_score = db.Column(db.Numeric(10,9), index=True)
matches = db.relationship('PrisonersCompare',
secondary=PrisonersMatch.__table__,
primaryjoin=(PrisonersMatch.master_id_ged == id_gedetineerde),
secondaryjoin=(PrisonersMatch.slave_id_ged == c_id_gedetineerde),
backref=db.backref('match_master', lazy='dynamic'),
lazy='dynamic'
)
def __init__(self, id_gedetineerde, voornaam, naam, geboorteplaats, c_id_gedetineerde, c_voornaam, c_naam,
c_geboorteplaats, geboortejaar=None, geboortemaand=None, geboortedag=None, c_geboortejaar=None,
c_geboortemaand=None, c_geboortedag=None):
self.id_gedetineerde = id_gedetineerde
self.Voornaam = voornaam
self.Naam = naam
self.Geboortejaar = geboortejaar
self.Geboortemaand = geboortemaand
self.Geboortedag = geboortedag
self.Geboorteplaats = geboorteplaats
self.c_id_gedetineerde = c_id_gedetineerde
self.c_voornaam = c_voornaam
self.c_naam = c_naam
self.c_geboortejaar = c_geboortejaar
self.c_geboortemaand = c_geboortemaand
self.c_geboortedag = c_geboortedag
self.c_geboorteplaats = c_geboorteplaats
def c_l_score(self):
"""
Compute the levenshtein distance between naamvoornaam and c_naamc_voornaam
:return:
"""
master_naam = '{0}{1}'.format(self.Naam, self.Voornaam)
master_c_naam = '{0}{1}'.format(self.c_naam, self.c_voornaam)
non_alpha = re.compile('[^a-z]')
# To lowercase
master_naam.lower()
master_c_naam.lower()
# Remove all non alphabetical characters
master_naam = non_alpha.sub('', master_naam)
master_c_naam = non_alpha.sub('', master_c_naam)
# Compute ratio
self.l_score = Levenshtein.ratio(master_naam, master_c_naam)
class UnmatchedBrugge(db.Model):
__tablename__ = 'UnmatchedBrugge'
id = db.Column(db.Integer, primary_key=True)
id_gedetineerde = db.Column(db.Integer, index=True)
class UnmatchedGent(db.Model):
__tablename__ = 'UnmatchedGent'
id = db.Column(db.Integer, primary_key=True)
id_gedetineerde = db.Column(db.Integer, index=True)
| pieterdp/doctoraat-ewout | prisoners/models/compare.py | Python | gpl-2.0 | 4,206 |
# This file is part of pybliographer
#
# Copyright (C) 1998-2004 Frederic GOBRY
# Email : gobry@pybliographer.org
#
# This program 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 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
#
# TODO: get rid of all of this, and use standard iterators / generators
class Iterator:
base = None
title = "Some Selection"
def iterator (self):
''' loop method, so that we can for example call a method by
passing indifferently a database or a database iterator...
'''
return self
def __iter__ (self):
retval = self.first ()
while retval != None:
yield retval
retval = self.next()
raise StopIteration
def set_position (self, pos=0):
self._position = 0
def get_position (self):
return self._position
def first (self):
self.set_position (0)
return self.next ()
class DBIterator (Iterator):
''' This class defines a database iterator '''
def __init__ (self, database):
self.keys = database.keys ()
self.base = database
self.database = database
self.count = 0
return
def __iter__ (self):
self._position = 0
for k in self.keys:
yield self.database [k]
self._position += 1
def first (self):
self.count = 0
return self.next ()
def next (self):
try:
entry = self.database [self.keys [self.count]]
except IndexError:
entry = None
self.count = self.count + 1
return entry
| zkota/pyblio-1.3 | Legacy/Iterator.py | Python | gpl-2.0 | 2,270 |
# -*- coding: utf-8 -*-
from sqlalchemy import select, desc
import const
from ..sqlalchemy_table import SqlTable
class TmpAnimts(SqlTable):
def __init__(self, engine, table):
self.engine = engine
self.table = table
SqlTable.__init__(self, self.engine, self.table, (const.NAME_TAN,))
def add(self, name, start_date, over_date, state, provider_id):
values = {
const.NAME_TAN: name,
const.ST_DATE_TAN: start_date,
const.OV_DATE_TAN: over_date,
const.STATE_TAN: state,
const.PROVIDER_ID_TAN: provider_id
}
return self.insert(values)[0]
# vim: set ts=4 sw=4 sts=4 et:
| authurlan/amdfin | server/database/amdfin/tmp_animts.py | Python | gpl-2.0 | 686 |