hexsha stringlengths 40 40 | size int64 4 996k | ext stringclasses 8
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 245 | max_stars_repo_name stringlengths 6 130 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 245 | max_issues_repo_name stringlengths 6 130 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 245 | max_forks_repo_name stringlengths 6 130 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 4 996k | avg_line_length float64 1.33 58.2k | max_line_length int64 2 323k | alphanum_fraction float64 0 0.97 | content_no_comment stringlengths 0 946k | is_comment_constant_removed bool 2
classes | is_sharp_comment_removed bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
790bc46c1ca684242c3375cd3c7dd7464b95ae8e | 1,901 | py | Python | tiktok_bot/models/comment.py | reliefs/tiktok_bot | 30404c0cd9ae1d52eb5b8818fbf282af1f68ee7a | [
"MIT"
] | 118 | 2019-10-22T07:56:34.000Z | 2022-03-30T11:33:25.000Z | tiktok_bot/models/comment.py | reliefs/tiktok_bot | 30404c0cd9ae1d52eb5b8818fbf282af1f68ee7a | [
"MIT"
] | 14 | 2019-10-27T00:06:29.000Z | 2020-12-30T09:10:43.000Z | tiktok_bot/models/comment.py | reliefs/tiktok_bot | 30404c0cd9ae1d52eb5b8818fbf282af1f68ee7a | [
"MIT"
] | 40 | 2019-10-27T15:46:58.000Z | 2022-03-15T00:21:47.000Z | from typing import List, Optional
from pydantic import BaseModel
from typing_extensions import Literal
from .request import BaseResponseData, CountOffsetParams, ListRequestParams, ListResponseData
from .tag import Tag
from .user import CommonUserDetails
class Comment(BaseModel):
# The ID of the post
aweme_id: str
# The ID of the comment
cid: str
# The timestamp in seconds when the comment was posted
create_time: int
# The number of times the comment has been liked
digg_count: int
# If this comment is replying to a comment, this array contains the original comment
reply_comment: Optional[List["Comment"]] = None
# If this comment is replying to a comment, the ID of that comment - "0" if not a reply
reply_id: str
# The status of the comment - 1 = published, 4 = published by you?
status: int
# The comment text
text: str
# Details about any tags in the comment
text_extra: List[Tag]
# Details about the author
user: CommonUserDetails
# 1 if the user likes the comment
user_digged: Literal[0, 1]
class ListCommentsRequest(ListRequestParams, CountOffsetParams):
# The ID of the post to list comments for
aweme_id: str
# ??? - default is 2
comment_style: Optional[int] = None
# ???
digged_cid = None
# ???
insert_cids = None
class ListCommentsResponse(ListResponseData, CountOffsetParams):
comments: List[Comment]
class PostCommentRequest(BaseModel):
# The ID of the post to comment on
aweme_id: str
# The comment text
text: str
# The ID of the comment that is being replied to
reply_id: Optional[str] = None
# Details about any tags in the comment
text_extra: List[Tag]
# ???
is_self_see: Literal[0, 1]
class PostCommentResponse(BaseResponseData):
# The comment that was posted
comment: Comment
| 22.630952 | 93 | 0.696476 | from typing import List, Optional
from pydantic import BaseModel
from typing_extensions import Literal
from .request import BaseResponseData, CountOffsetParams, ListRequestParams, ListResponseData
from .tag import Tag
from .user import CommonUserDetails
class Comment(BaseModel):
aweme_id: str
cid: str
create_time: int
digg_count: int
reply_comment: Optional[List["Comment"]] = None
reply_id: str
status: int
text: str
text_extra: List[Tag]
user: CommonUserDetails
user_digged: Literal[0, 1]
class ListCommentsRequest(ListRequestParams, CountOffsetParams):
aweme_id: str
comment_style: Optional[int] = None
digged_cid = None
insert_cids = None
class ListCommentsResponse(ListResponseData, CountOffsetParams):
comments: List[Comment]
class PostCommentRequest(BaseModel):
aweme_id: str
text: str
reply_id: Optional[str] = None
text_extra: List[Tag]
is_self_see: Literal[0, 1]
class PostCommentResponse(BaseResponseData):
comment: Comment
| true | true |
790bc527f550caf6d6c3c54aa154d04198b28640 | 2,339 | py | Python | src/playthrough-bot/models/alembic/env.py | Rain288/playthrough-bot | 9ddefa336bf59cf8ab4a1de83ff4c4777195619b | [
"MIT"
] | 1 | 2019-02-02T03:58:05.000Z | 2019-02-02T03:58:05.000Z | src/playthrough-bot/models/alembic/env.py | Rain288/playthrough-bot | 9ddefa336bf59cf8ab4a1de83ff4c4777195619b | [
"MIT"
] | 1 | 2019-02-02T03:58:05.000Z | 2019-02-10T14:51:05.000Z | src/playthrough-bot/models/alembic/env.py | evangelos-ch/playthrough-bot | 9ddefa336bf59cf8ab4a1de83ff4c4777195619b | [
"MIT"
] | null | null | null | # pylint: disable=no-member
from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
from playthrough-bot.models import ModelBase, get_engine
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
config.set_main_option("sqlalchemy.url", str(get_engine().url))
# Interpret the config file for Python logging.
# This line sets up loggers basically.
fileConfig(config.config_file_name)
# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
target_metadata = ModelBase.metadata
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
connectable = engine_from_config(
config.get_section(config.config_ini_section),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
with connectable.connect() as connection:
context.configure(
connection=connection,
target_metadata=target_metadata,
render_as_batch=config.get_main_option("sqlalchemy.url").startswith(
"sqlite:"
),
)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
| 26.885057 | 80 | 0.70714 |
from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
from playthrough-bot.models import ModelBase, get_engine
config = context.config
config.set_main_option("sqlalchemy.url", str(get_engine().url))
fileConfig(config.config_file_name)
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
target_metadata = ModelBase.metadata
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
connectable = engine_from_config(
config.get_section(config.config_ini_section),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
with connectable.connect() as connection:
context.configure(
connection=connection,
target_metadata=target_metadata,
render_as_batch=config.get_main_option("sqlalchemy.url").startswith(
"sqlite:"
),
)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
| false | true |
790bc552861a63a0b44e136084ced7fa30eddacf | 120 | py | Python | Regex/Capturing & Non-Capturing Groups.py | rafaelgreca/hackerrank-solutions | 2be6c8fdd9b7f2ab3a678e7dcdc27e730edfaef3 | [
"MIT"
] | 2 | 2020-05-28T07:15:00.000Z | 2020-07-21T08:34:06.000Z | Regex/Capturing & Non-Capturing Groups.py | rafaelgreca/hackerrank-solutions | 2be6c8fdd9b7f2ab3a678e7dcdc27e730edfaef3 | [
"MIT"
] | null | null | null | Regex/Capturing & Non-Capturing Groups.py | rafaelgreca/hackerrank-solutions | 2be6c8fdd9b7f2ab3a678e7dcdc27e730edfaef3 | [
"MIT"
] | null | null | null | Regex_Pattern = r'(ok){3,}' # Do not delete 'r'.
import re
print(str(bool(re.search(Regex_Pattern, input()))).lower()) | 24 | 59 | 0.666667 | Regex_Pattern = r'(ok){3,}'
import re
print(str(bool(re.search(Regex_Pattern, input()))).lower()) | true | true |
790bc55d23e266c9aec44d33c5233dd226e9045f | 746 | py | Python | botblox_config/data_manager/erase.py | ararobotique/botblox-manager-software | 64c5c893601ea62a7ac414023455e8c2da04816d | [
"MIT"
] | 6 | 2021-04-18T21:30:17.000Z | 2022-01-13T06:37:43.000Z | botblox_config/data_manager/erase.py | ararobotique/botblox-manager-software | 64c5c893601ea62a7ac414023455e8c2da04816d | [
"MIT"
] | 36 | 2020-12-16T12:29:24.000Z | 2021-09-18T14:52:25.000Z | botblox_config/data_manager/erase.py | ararobotique/botblox-manager-software | 64c5c893601ea62a7ac414023455e8c2da04816d | [
"MIT"
] | 2 | 2021-04-08T20:27:48.000Z | 2021-08-30T17:32:28.000Z | from argparse import Action, Namespace
from typing import (List)
from .switch_config import SwitchConfigCLI
from ..switch import SwitchChip
class EraseConfigCLI(SwitchConfigCLI):
"""
The "erase" action that removes all stored items from the EEPROM memory.
"""
def __init__(self, subparsers: Action, switch: SwitchChip) -> None:
super().__init__(subparsers, switch)
self._subparser = self._subparsers.add_parser(
"erase",
help="Erase all configuration",
)
self._subparser.set_defaults(execute=self.apply)
def apply(self, args: Namespace) -> SwitchConfigCLI:
return self
def create_configuration(self) -> List[List[int]]:
return [[101, 0, 0, 0]]
| 28.692308 | 76 | 0.670241 | from argparse import Action, Namespace
from typing import (List)
from .switch_config import SwitchConfigCLI
from ..switch import SwitchChip
class EraseConfigCLI(SwitchConfigCLI):
def __init__(self, subparsers: Action, switch: SwitchChip) -> None:
super().__init__(subparsers, switch)
self._subparser = self._subparsers.add_parser(
"erase",
help="Erase all configuration",
)
self._subparser.set_defaults(execute=self.apply)
def apply(self, args: Namespace) -> SwitchConfigCLI:
return self
def create_configuration(self) -> List[List[int]]:
return [[101, 0, 0, 0]]
| true | true |
790bc6fa7673a8d96d10c13fc38f867949e749dc | 2,324 | py | Python | ucscsdk/mometa/adaptor/AdaptorEthCompQueueProfile.py | parag-may4/ucscsdk | 2ea762fa070330e3a4e2c21b46b157469555405b | [
"Apache-2.0"
] | null | null | null | ucscsdk/mometa/adaptor/AdaptorEthCompQueueProfile.py | parag-may4/ucscsdk | 2ea762fa070330e3a4e2c21b46b157469555405b | [
"Apache-2.0"
] | null | null | null | ucscsdk/mometa/adaptor/AdaptorEthCompQueueProfile.py | parag-may4/ucscsdk | 2ea762fa070330e3a4e2c21b46b157469555405b | [
"Apache-2.0"
] | null | null | null | """This module contains the general information for AdaptorEthCompQueueProfile ManagedObject."""
from ...ucscmo import ManagedObject
from ...ucsccoremeta import UcscVersion, MoPropertyMeta, MoMeta
from ...ucscmeta import VersionMeta
class AdaptorEthCompQueueProfileConsts():
pass
class AdaptorEthCompQueueProfile(ManagedObject):
"""This is AdaptorEthCompQueueProfile class."""
consts = AdaptorEthCompQueueProfileConsts()
naming_props = set([])
mo_meta = MoMeta("AdaptorEthCompQueueProfile", "adaptorEthCompQueueProfile", "eth-comp-q", VersionMeta.Version111a, "InputOutput", 0x1f, [], ["admin", "ls-config-policy", "ls-network", "ls-server-policy"], [u'adaptorHostEthIfProfile', u'adaptorUsnicConnDef'], [], ["Get", "Set"])
prop_meta = {
"child_action": MoPropertyMeta("child_action", "childAction", "string", VersionMeta.Version111a, MoPropertyMeta.INTERNAL, None, None, None, r"""((deleteAll|ignore|deleteNonPresent),){0,2}(deleteAll|ignore|deleteNonPresent){0,1}""", [], []),
"count": MoPropertyMeta("count", "count", "ushort", VersionMeta.Version111a, MoPropertyMeta.READ_WRITE, 0x2, None, None, None, [], ["1-2000"]),
"dn": MoPropertyMeta("dn", "dn", "string", VersionMeta.Version111a, MoPropertyMeta.READ_ONLY, 0x4, 0, 256, None, [], []),
"ring_size": MoPropertyMeta("ring_size", "ringSize", "ushort", VersionMeta.Version111a, MoPropertyMeta.READ_ONLY, None, None, None, None, [], ["1-1"]),
"rn": MoPropertyMeta("rn", "rn", "string", VersionMeta.Version111a, MoPropertyMeta.READ_ONLY, 0x8, 0, 256, None, [], []),
"status": MoPropertyMeta("status", "status", "string", VersionMeta.Version111a, MoPropertyMeta.READ_WRITE, 0x10, None, None, r"""((removed|created|modified|deleted),){0,3}(removed|created|modified|deleted){0,1}""", [], []),
}
prop_map = {
"childAction": "child_action",
"count": "count",
"dn": "dn",
"ringSize": "ring_size",
"rn": "rn",
"status": "status",
}
def __init__(self, parent_mo_or_dn, **kwargs):
self._dirty_mask = 0
self.child_action = None
self.count = None
self.ring_size = None
self.status = None
ManagedObject.__init__(self, "AdaptorEthCompQueueProfile", parent_mo_or_dn, **kwargs)
| 49.446809 | 283 | 0.669105 |
from ...ucscmo import ManagedObject
from ...ucsccoremeta import UcscVersion, MoPropertyMeta, MoMeta
from ...ucscmeta import VersionMeta
class AdaptorEthCompQueueProfileConsts():
pass
class AdaptorEthCompQueueProfile(ManagedObject):
consts = AdaptorEthCompQueueProfileConsts()
naming_props = set([])
mo_meta = MoMeta("AdaptorEthCompQueueProfile", "adaptorEthCompQueueProfile", "eth-comp-q", VersionMeta.Version111a, "InputOutput", 0x1f, [], ["admin", "ls-config-policy", "ls-network", "ls-server-policy"], [u'adaptorHostEthIfProfile', u'adaptorUsnicConnDef'], [], ["Get", "Set"])
prop_meta = {
"child_action": MoPropertyMeta("child_action", "childAction", "string", VersionMeta.Version111a, MoPropertyMeta.INTERNAL, None, None, None, r"""((deleteAll|ignore|deleteNonPresent),){0,2}(deleteAll|ignore|deleteNonPresent){0,1}""", [], []),
"count": MoPropertyMeta("count", "count", "ushort", VersionMeta.Version111a, MoPropertyMeta.READ_WRITE, 0x2, None, None, None, [], ["1-2000"]),
"dn": MoPropertyMeta("dn", "dn", "string", VersionMeta.Version111a, MoPropertyMeta.READ_ONLY, 0x4, 0, 256, None, [], []),
"ring_size": MoPropertyMeta("ring_size", "ringSize", "ushort", VersionMeta.Version111a, MoPropertyMeta.READ_ONLY, None, None, None, None, [], ["1-1"]),
"rn": MoPropertyMeta("rn", "rn", "string", VersionMeta.Version111a, MoPropertyMeta.READ_ONLY, 0x8, 0, 256, None, [], []),
"status": MoPropertyMeta("status", "status", "string", VersionMeta.Version111a, MoPropertyMeta.READ_WRITE, 0x10, None, None, r"""((removed|created|modified|deleted),){0,3}(removed|created|modified|deleted){0,1}""", [], []),
}
prop_map = {
"childAction": "child_action",
"count": "count",
"dn": "dn",
"ringSize": "ring_size",
"rn": "rn",
"status": "status",
}
def __init__(self, parent_mo_or_dn, **kwargs):
self._dirty_mask = 0
self.child_action = None
self.count = None
self.ring_size = None
self.status = None
ManagedObject.__init__(self, "AdaptorEthCompQueueProfile", parent_mo_or_dn, **kwargs)
| true | true |
790bc74afceb54e8f3e9d007005e22897ef55221 | 6,404 | py | Python | mycroft/skills/common_query_skill.py | assistent-cat/mycroft-core | 6f8bae6ba136c9dd66ca47aaadd75e214d006190 | [
"Apache-2.0"
] | 2 | 2021-04-05T22:28:37.000Z | 2021-06-16T00:24:41.000Z | mycroft/skills/common_query_skill.py | assistent-cat/mycroft-core | 6f8bae6ba136c9dd66ca47aaadd75e214d006190 | [
"Apache-2.0"
] | 4 | 2021-06-08T20:55:12.000Z | 2022-03-12T00:15:06.000Z | mycroft/skills/common_query_skill.py | assistent-cat/mycroft-core | 6f8bae6ba136c9dd66ca47aaadd75e214d006190 | [
"Apache-2.0"
] | 2 | 2020-09-28T01:38:34.000Z | 2020-12-03T03:14:32.000Z | # Copyright 2018 Mycroft AI Inc.
#
# 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.
from enum import IntEnum
from abc import ABC, abstractmethod
from .mycroft_skill import MycroftSkill
class CQSMatchLevel(IntEnum):
EXACT = 1 # Skill could find a specific answer for the question
CATEGORY = 2 # Skill could find an answer from a category in the query
GENERAL = 3 # The query could be processed as a general quer
# Copy of CQSMatchLevel to use if the skill returns visual media
CQSVisualMatchLevel = IntEnum('CQSVisualMatchLevel',
[e.name for e in CQSMatchLevel])
def is_CQSVisualMatchLevel(match_level):
return isinstance(match_level, type(CQSVisualMatchLevel.EXACT))
VISUAL_DEVICES = ['mycroft_mark_2']
def handles_visuals(platform):
return platform in VISUAL_DEVICES
class CommonQuerySkill(MycroftSkill, ABC):
"""Question answering skills should be based on this class.
The skill author needs to implement `CQS_match_query_phrase` returning an
answer and can optionally implement `CQS_action` to perform additional
actions if the skill's answer is selected.
This class works in conjunction with skill-query which collects
answers from several skills presenting the best one available.
"""
def __init__(self, name=None, bus=None):
super().__init__(name, bus)
def bind(self, bus):
"""Overrides the default bind method of MycroftSkill.
This registers messagebus handlers for the skill during startup
but is nothing the skill author needs to consider.
"""
if bus:
super().bind(bus)
self.add_event('question:query', self.__handle_question_query)
self.add_event('question:action', self.__handle_query_action)
def __handle_question_query(self, message):
search_phrase = message.data["phrase"]
# First, notify the requestor that we are attempting to handle
# (this extends a timeout while this skill looks for a match)
self.bus.emit(message.response({"phrase": search_phrase,
"skill_id": self.skill_id,
"searching": True}))
# Now invoke the CQS handler to let the skill perform its search
result = self.CQS_match_query_phrase(search_phrase)
if result:
match = result[0]
level = result[1]
answer = result[2]
callback = result[3] if len(result) > 3 else None
confidence = self.__calc_confidence(match, search_phrase, level)
self.bus.emit(message.response({"phrase": search_phrase,
"skill_id": self.skill_id,
"answer": answer,
"callback_data": callback,
"conf": confidence}))
else:
# Signal we are done (can't handle it)
self.bus.emit(message.response({"phrase": search_phrase,
"skill_id": self.skill_id,
"searching": False}))
def __calc_confidence(self, match, phrase, level):
# Assume the more of the words that get consumed, the better the match
consumed_pct = len(match.split()) / len(phrase.split())
if consumed_pct > 1.0:
consumed_pct = 1.0
# Add bonus if match has visuals and the device supports them.
platform = self.config_core.get('enclosure', {}).get('platform')
if is_CQSVisualMatchLevel(level) and handles_visuals(platform):
bonus = 0.1
else:
bonus = 0
if int(level) == int(CQSMatchLevel.EXACT):
return 0.9 + (consumed_pct / 10) + bonus
elif int(level) == int(CQSMatchLevel.CATEGORY):
return 0.6 + (consumed_pct / 10) + bonus
elif int(level) == int(CQSMatchLevel.GENERAL):
return 0.5 + (consumed_pct / 10) + bonus
else:
return 0.0 # should never happen
def __handle_query_action(self, message):
"""Message handler for question:action.
Extracts phrase and data from message forward this to the skills
CQS_action method.
"""
if message.data["skill_id"] != self.skill_id:
# Not for this skill!
return
phrase = message.data["phrase"]
data = message.data.get("callback_data")
# Invoke derived class to provide playback data
self.CQS_action(phrase, data)
@abstractmethod
def CQS_match_query_phrase(self, phrase):
"""Analyze phrase to see if it is a play-able phrase with this skill.
Needs to be implemented by the skill.
Arguments:
phrase (str): User phrase, "What is an aardwark"
Returns:
(match, CQSMatchLevel[, callback_data]) or None: Tuple containing
a string with the appropriate matching phrase, the PlayMatch
type, and optionally data to return in the callback if the
match is selected.
"""
# Derived classes must implement this, e.g.
return None
def CQS_action(self, phrase, data):
"""Take additional action IF the skill is selected.
The speech is handled by the common query but if the chosen skill
wants to display media, set a context or prepare for sending
information info over e-mail this can be implemented here.
Args:
phrase (str): User phrase uttered after "Play", e.g. "some music"
data (dict): Callback data specified in match_query_phrase()
"""
# Derived classes may implement this if they use additional media
# or wish to set context after being called.
pass
| 39.288344 | 78 | 0.626327 |
from enum import IntEnum
from abc import ABC, abstractmethod
from .mycroft_skill import MycroftSkill
class CQSMatchLevel(IntEnum):
EXACT = 1
CATEGORY = 2
GENERAL = 3
CQSVisualMatchLevel = IntEnum('CQSVisualMatchLevel',
[e.name for e in CQSMatchLevel])
def is_CQSVisualMatchLevel(match_level):
return isinstance(match_level, type(CQSVisualMatchLevel.EXACT))
VISUAL_DEVICES = ['mycroft_mark_2']
def handles_visuals(platform):
return platform in VISUAL_DEVICES
class CommonQuerySkill(MycroftSkill, ABC):
def __init__(self, name=None, bus=None):
super().__init__(name, bus)
def bind(self, bus):
if bus:
super().bind(bus)
self.add_event('question:query', self.__handle_question_query)
self.add_event('question:action', self.__handle_query_action)
def __handle_question_query(self, message):
search_phrase = message.data["phrase"]
self.bus.emit(message.response({"phrase": search_phrase,
"skill_id": self.skill_id,
"searching": True}))
result = self.CQS_match_query_phrase(search_phrase)
if result:
match = result[0]
level = result[1]
answer = result[2]
callback = result[3] if len(result) > 3 else None
confidence = self.__calc_confidence(match, search_phrase, level)
self.bus.emit(message.response({"phrase": search_phrase,
"skill_id": self.skill_id,
"answer": answer,
"callback_data": callback,
"conf": confidence}))
else:
self.bus.emit(message.response({"phrase": search_phrase,
"skill_id": self.skill_id,
"searching": False}))
def __calc_confidence(self, match, phrase, level):
# Assume the more of the words that get consumed, the better the match
consumed_pct = len(match.split()) / len(phrase.split())
if consumed_pct > 1.0:
consumed_pct = 1.0
# Add bonus if match has visuals and the device supports them.
platform = self.config_core.get('enclosure', {}).get('platform')
if is_CQSVisualMatchLevel(level) and handles_visuals(platform):
bonus = 0.1
else:
bonus = 0
if int(level) == int(CQSMatchLevel.EXACT):
return 0.9 + (consumed_pct / 10) + bonus
elif int(level) == int(CQSMatchLevel.CATEGORY):
return 0.6 + (consumed_pct / 10) + bonus
elif int(level) == int(CQSMatchLevel.GENERAL):
return 0.5 + (consumed_pct / 10) + bonus
else:
return 0.0 # should never happen
def __handle_query_action(self, message):
if message.data["skill_id"] != self.skill_id:
# Not for this skill!
return
phrase = message.data["phrase"]
data = message.data.get("callback_data")
# Invoke derived class to provide playback data
self.CQS_action(phrase, data)
@abstractmethod
def CQS_match_query_phrase(self, phrase):
# Derived classes must implement this, e.g.
return None
def CQS_action(self, phrase, data):
# Derived classes may implement this if they use additional media
# or wish to set context after being called.
pass
| true | true |
790bc912b9632f19ea762af1efef5229f787d170 | 27,416 | py | Python | evaluate_3dpw_mine.py | akashsengupta1997/GraphCMR | 0b8b05be4f711995ba50e414effbde98b6b11c5b | [
"BSD-3-Clause"
] | null | null | null | evaluate_3dpw_mine.py | akashsengupta1997/GraphCMR | 0b8b05be4f711995ba50e414effbde98b6b11c5b | [
"BSD-3-Clause"
] | null | null | null | evaluate_3dpw_mine.py | akashsengupta1997/GraphCMR | 0b8b05be4f711995ba50e414effbde98b6b11c5b | [
"BSD-3-Clause"
] | null | null | null | import os
import numpy as np
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
import torch
from torch.utils.data import DataLoader
from tqdm import tqdm
import argparse
import cv2
import config
from utils import Mesh
from models import CMR
from models.smpl_from_lib import SMPL
from utils.pose_utils import compute_similarity_transform_batch, \
scale_and_translation_transform_batch
from utils.cam_utils import orthographic_project_torch, undo_keypoint_normalisation
from datasets.my_3dpw_eval_dataset import PW3DEvalDataset
def evaluate_3dpw(model,
eval_dataset,
metrics,
device,
vis_save_path,
num_workers=4,
pin_memory=True,
vis_every_n_batches=1000):
eval_dataloader = DataLoader(eval_dataset,
batch_size=1,
shuffle=False,
drop_last=True,
num_workers=num_workers,
pin_memory=pin_memory)
smpl = SMPL(config.SMPL_MODEL_DIR, batch_size=1)
smpl_male = SMPL(config.SMPL_MODEL_DIR, batch_size=1, gender='male')
smpl_female = SMPL(config.SMPL_MODEL_DIR, batch_size=1, gender='female')
smpl.to(device)
smpl_male.to(device)
smpl_female.to(device)
J_regressor = torch.from_numpy(np.load(config.JOINT_REGRESSOR_H36M)).float()
J_regressor_batch = J_regressor[None, :].to(device)
if 'pve' in metrics:
pve_smpl_sum = 0.0
pve_graph_sum = 0.0
pve_smpl_per_frame = []
pve_graph_per_frame = []
if 'pve_scale_corrected' in metrics:
pve_scale_corrected_smpl_sum = 0.0
pve_scale_corrected_graph_sum = 0.0
pve_scale_corrected_smpl_per_frame = []
pve_scale_corrected_graph_per_frame = []
if 'pve_pa' in metrics:
pve_pa_smpl_sum = 0.0
pve_pa_graph_sum = 0.0
pve_pa_smpl_per_frame = []
pve_pa_graph_per_frame = []
if 'pve-t' in metrics:
pvet_sum = 0.0
pvet_per_frame = []
if 'pve-t_scale_corrected' in metrics:
pvet_scale_corrected_sum = 0.0
pvet_scale_corrected_per_frame = []
if 'mpjpe' in metrics:
mpjpe_smpl_sum = 0.0
mpjpe_graph_sum = 0.0
mpjpe_smpl_per_frame = []
mpjpe_graph_per_frame = []
if 'mpjpe_scale_corrected' in metrics:
mpjpe_scale_corrected_smpl_sum = 0.0
mpjpe_scale_corrected_graph_sum = 0.0
mpjpe_scale_corrected_smpl_per_frame = []
mpjpe_scale_corrected_graph_per_frame = []
if 'j3d_rec_err' in metrics:
j3d_rec_err_smpl_sum = 0.0
j3d_rec_err_graph_sum = 0.0
j3d_rec_err_smpl_per_frame = []
j3d_rec_err_graph_per_frame = []
if 'pve_2d' in metrics:
pve_2d_smpl_sum = 0.0
pve_2d_graph_sum = 0.0
if 'pve_2d_scale_corrected' in metrics:
pve_2d_scale_corrected_smpl_sum = 0.0
pve_2d_scale_corrected_graph_sum = 0.0
if 'pve_2d_pa' in metrics:
pve_2d_pa_smpl_sum = 0.0
pve_2d_pa_graph_sum = 0.0
num_samples = 0
num_vertices = 6890
num_joints3d = 14
model.eval()
for batch_num, samples_batch in enumerate(tqdm(eval_dataloader)):
# ------------------------------- TARGETS and INPUTS -------------------------------
input = samples_batch['input']
input = input.to(device)
target_pose = samples_batch['pose'].to(device)
target_shape = samples_batch['shape'].to(device)
target_gender = samples_batch['gender'][0]
if target_gender == 'm':
target_smpl_output = smpl_male(body_pose=target_pose[:, 3:],
global_orient=target_pose[:, :3],
betas=target_shape)
target_vertices = target_smpl_output.vertices
target_reposed_smpl_output = smpl_male(betas=target_shape)
target_reposed_vertices = target_reposed_smpl_output.vertices
target_joints_h36m = torch.matmul(J_regressor_batch, target_vertices)
target_joints_h36mlsp = target_joints_h36m[:, config.H36M_TO_J14, :]
elif target_gender == 'f':
target_smpl_output = smpl_female(body_pose=target_pose[:, 3:],
global_orient=target_pose[:, :3],
betas=target_shape)
target_vertices = target_smpl_output.vertices
target_reposed_smpl_output = smpl_female(betas=target_shape)
target_reposed_vertices = target_reposed_smpl_output.vertices
target_joints_h36m = torch.matmul(J_regressor_batch, target_vertices)
target_joints_h36mlsp = target_joints_h36m[:, config.H36M_TO_J14, :]
# ------------------------------- PREDICTIONS -------------------------------
pred_vertices, pred_vertices_smpl, pred_camera, pred_rotmat, pred_betas = model(input)
pred_vertices_projected2d = orthographic_project_torch(pred_vertices, pred_camera)
pred_vertices_projected2d = undo_keypoint_normalisation(pred_vertices_projected2d, input.shape[-1])
pred_vertices_smpl_projected2d = orthographic_project_torch(pred_vertices_smpl, pred_camera)
pred_vertices_smpl_projected2d = undo_keypoint_normalisation(pred_vertices_smpl_projected2d, input.shape[-1])
pred_reposed_smpl_output = smpl(betas=pred_betas)
pred_reposed_vertices = pred_reposed_smpl_output.vertices
pred_joints_h36m = torch.matmul(J_regressor_batch, pred_vertices)
pred_joints_h36mlsp = pred_joints_h36m[:, config.H36M_TO_J14, :]
pred_joints_smpl_h36m = torch.matmul(J_regressor_batch, pred_vertices_smpl)
pred_joints_smpl_h36mlsp = pred_joints_smpl_h36m[:, config.H36M_TO_J14, :]
# Numpy-fying
target_vertices = target_vertices.cpu().detach().numpy()
target_reposed_vertices = target_reposed_vertices.cpu().detach().numpy()
target_joints_h36mlsp = target_joints_h36mlsp.cpu().detach().numpy()
pred_vertices = pred_vertices.cpu().detach().numpy()
pred_vertices_smpl = pred_vertices_smpl.cpu().detach().numpy()
pred_vertices_projected2d = pred_vertices_projected2d.cpu().detach().numpy()
pred_vertices_smpl_projected2d = pred_vertices_smpl_projected2d.cpu().detach().numpy()
pred_reposed_vertices = pred_reposed_vertices.cpu().detach().numpy()
pred_joints_h36mlsp = pred_joints_h36mlsp.cpu().detach().numpy()
pred_joints_smpl_h36mlsp = pred_joints_smpl_h36mlsp.cpu().detach().numpy()
# ------------------------------- METRICS -------------------------------
if 'pve' in metrics:
pve_smpl_batch = np.linalg.norm(pred_vertices_smpl - target_vertices, axis=-1) # (1, 6890)
pve_graph_batch = np.linalg.norm(pred_vertices - target_vertices, axis=-1)
pve_smpl_sum += np.sum(pve_smpl_batch) # scalar
pve_graph_sum += np.sum(pve_graph_batch)
pve_smpl_per_frame.append(np.mean(pve_smpl_batch, axis=-1))
pve_graph_per_frame.append(np.mean(pve_graph_batch, axis=-1))
# Scale and translation correction
if 'pve_scale_corrected' in metrics:
pred_vertices_smpl_sc = scale_and_translation_transform_batch(pred_vertices_smpl,
target_vertices)
pred_vertices_sc = scale_and_translation_transform_batch(pred_vertices,
target_vertices)
pve_sc_smpl_batch = np.linalg.norm(pred_vertices_smpl_sc - target_vertices,
axis=-1) # (1, 6890)
pve_sc_graph_batch = np.linalg.norm(pred_vertices_sc - target_vertices,
axis=-1) # (1, 6890)
pve_scale_corrected_smpl_sum += np.sum(pve_sc_smpl_batch) # scalar
pve_scale_corrected_graph_sum += np.sum(pve_sc_graph_batch) # scalar
pve_scale_corrected_smpl_per_frame.append(np.mean(pve_sc_smpl_batch, axis=-1))
pve_scale_corrected_graph_per_frame.append(np.mean(pve_sc_graph_batch, axis=-1))
# Procrustes analysis
if 'pve_pa' in metrics:
pred_vertices_smpl_pa = compute_similarity_transform_batch(pred_vertices_smpl, target_vertices)
pred_vertices_pa = compute_similarity_transform_batch(pred_vertices, target_vertices)
pve_pa_smpl_batch = np.linalg.norm(pred_vertices_smpl_pa - target_vertices, axis=-1) # (1, 6890)
pve_pa_graph_batch = np.linalg.norm(pred_vertices_pa - target_vertices, axis=-1) # (1, 6890)
pve_pa_smpl_sum += np.sum(pve_pa_smpl_batch) # scalar
pve_pa_graph_sum += np.sum(pve_pa_graph_batch) # scalar
pve_pa_smpl_per_frame.append(np.mean(pve_pa_smpl_batch, axis=-1))
pve_pa_graph_per_frame.append(np.mean(pve_pa_graph_batch, axis=-1))
if 'pve-t' in metrics:
pvet_batch = np.linalg.norm(pred_reposed_vertices - target_reposed_vertices, axis=-1)
pvet_sum += np.sum(pvet_batch)
pvet_per_frame.append(np.mean(pvet_batch, axis=-1))
# Scale and translation correction
if 'pve-t_scale_corrected' in metrics:
pred_reposed_vertices_sc = scale_and_translation_transform_batch(pred_reposed_vertices,
target_reposed_vertices)
pvet_scale_corrected_batch = np.linalg.norm(pred_reposed_vertices_sc - target_reposed_vertices,
axis=-1) # (bs, 6890)
pvet_scale_corrected_sum += np.sum(pvet_scale_corrected_batch) # scalar
pvet_scale_corrected_per_frame.append(np.mean(pvet_scale_corrected_batch, axis=-1))
if 'mpjpe' in metrics:
mpjpe_smpl_batch = np.linalg.norm(pred_joints_smpl_h36mlsp - target_joints_h36mlsp, axis=-1) # (bs, 14)
mpjpe_graph_batch = np.linalg.norm(pred_joints_h36mlsp - target_joints_h36mlsp, axis=-1) # (bs, 14)
mpjpe_smpl_sum += np.sum(mpjpe_smpl_batch)
mpjpe_graph_sum += np.sum(mpjpe_graph_batch)
mpjpe_smpl_per_frame.append(np.mean(mpjpe_smpl_batch, axis=-1))
mpjpe_graph_per_frame.append(np.mean(mpjpe_graph_batch, axis=-1))
# Scale and translation correction
if 'mpjpe_scale_corrected' in metrics:
pred_joints_smpl_h36mlsp_sc = scale_and_translation_transform_batch(pred_joints_smpl_h36mlsp,
target_joints_h36mlsp)
pred_joints_h36mlsp_sc = scale_and_translation_transform_batch(pred_joints_h36mlsp,
target_joints_h36mlsp)
mpjpe_scale_corrected_smpl_batch = np.linalg.norm(pred_joints_smpl_h36mlsp_sc - target_joints_h36mlsp,
axis=-1) # (bs, 14)
mpjpe_scale_corrected_graph_batch = np.linalg.norm(pred_joints_h36mlsp_sc - target_joints_h36mlsp,
axis=-1) # (bs, 14)
mpjpe_scale_corrected_smpl_sum += np.sum(mpjpe_scale_corrected_smpl_batch)
mpjpe_scale_corrected_graph_sum += np.sum(mpjpe_scale_corrected_graph_batch)
mpjpe_scale_corrected_smpl_per_frame.append(np.mean(mpjpe_scale_corrected_smpl_batch, axis=-1))
mpjpe_scale_corrected_graph_per_frame.append(np.mean(mpjpe_scale_corrected_graph_batch, axis=-1))
# Procrustes analysis
if 'j3d_rec_err' in metrics:
pred_joints_smpl_h36mlsp_pa = compute_similarity_transform_batch(pred_joints_smpl_h36mlsp,
target_joints_h36mlsp)
pred_joints_h36mlsp_pa = compute_similarity_transform_batch(pred_joints_h36mlsp, target_joints_h36mlsp)
j3d_rec_err_smpl_batch = np.linalg.norm(pred_joints_smpl_h36mlsp_pa - target_joints_h36mlsp, axis=-1) # (bs, 14)
j3d_rec_err_graph_batch = np.linalg.norm(pred_joints_h36mlsp_pa - target_joints_h36mlsp, axis=-1) # (bs, 14)
j3d_rec_err_smpl_sum += np.sum(j3d_rec_err_smpl_batch)
j3d_rec_err_graph_sum += np.sum(j3d_rec_err_graph_batch)
j3d_rec_err_smpl_per_frame.append(np.mean(j3d_rec_err_smpl_batch, axis=-1))
j3d_rec_err_graph_per_frame.append(np.mean(j3d_rec_err_graph_batch, axis=-1))
if 'pve_2d' in metrics:
pred_vertices_smpl_2d = pred_vertices_smpl[:, :, :2]
pred_vertices_2d = pred_vertices[:, :, :2]
target_vertices_2d = target_vertices[:, :, :2]
pve_2d_smpl_batch = np.linalg.norm(pred_vertices_smpl_2d - target_vertices_2d, axis=-1) # (bs, 6890)
pve_2d_graph_batch = np.linalg.norm(pred_vertices_2d - target_vertices_2d, axis=-1) # (bs, 6890)
pve_2d_smpl_sum += np.sum(pve_2d_smpl_batch)
pve_2d_graph_sum += np.sum(pve_2d_graph_batch)
# Scale and translation correction
if 'pve_2d_scale_corrected' in metrics:
pred_vertices_smpl_sc = scale_and_translation_transform_batch(pred_vertices_smpl,
target_vertices)
pred_vertices_sc = scale_and_translation_transform_batch(pred_vertices,
target_vertices)
pred_vertices_smpl_2d_sc = pred_vertices_smpl_sc[:, :, :2]
pred_vertices_2d_sc = pred_vertices_sc[:, :, :2]
target_vertices_2d = target_vertices[:, :, :2]
pve_2d_sc_smpl_batch = np.linalg.norm(pred_vertices_smpl_2d_sc - target_vertices_2d,
axis=-1) # (bs, 6890)
pve_2d_sc_graph_batch = np.linalg.norm(pred_vertices_2d_sc - target_vertices_2d,
axis=-1) # (bs, 6890)
pve_2d_scale_corrected_smpl_sum += np.sum(pve_2d_sc_smpl_batch)
pve_2d_scale_corrected_graph_sum += np.sum(pve_2d_sc_graph_batch)
# Procrustes analysis
if 'pve_2d_pa' in metrics:
pred_vertices_smpl_pa = compute_similarity_transform_batch(pred_vertices_smpl, target_vertices)
pred_vertices_pa = compute_similarity_transform_batch(pred_vertices, target_vertices)
pred_vertices_smpl_2d_pa = pred_vertices_smpl_pa[:, :, :2]
pred_vertices_2d_pa = pred_vertices_pa[:, :, :2]
target_vertices_2d = target_vertices[:, :, :2]
pve_2d_pa_smpl_batch = np.linalg.norm(pred_vertices_smpl_2d_pa - target_vertices_2d, axis=-1) # (bs, 6890)
pve_2d_pa_graph_batch = np.linalg.norm(pred_vertices_2d_pa - target_vertices_2d, axis=-1) # (bs, 6890)
pve_2d_pa_smpl_sum += np.sum(pve_2d_pa_smpl_batch)
pve_2d_pa_graph_sum += np.sum(pve_2d_pa_graph_batch)
num_samples += target_pose.shape[0]
# ------------------------------- VISUALISE -------------------------------
if vis_every_n_batches is not None:
if batch_num % vis_every_n_batches == 0:
vis_imgs = samples_batch['vis_img'].numpy()
vis_imgs = np.transpose(vis_imgs, [0, 2, 3, 1])
fnames = samples_batch['fname']
plt.figure(figsize=(16, 12))
plt.subplot(341)
plt.imshow(vis_imgs[0])
plt.subplot(342)
plt.imshow(vis_imgs[0])
plt.scatter(pred_vertices_projected2d[0, :, 0], pred_vertices_projected2d[0, :, 1], s=0.1, c='r')
plt.subplot(343)
plt.imshow(vis_imgs[0])
plt.scatter(pred_vertices_smpl_projected2d[0, :, 0], pred_vertices_smpl_projected2d[0, :, 1], s=0.1, c='r')
plt.subplot(345)
plt.scatter(target_vertices[0, :, 0], target_vertices[0, :, 1], s=0.1, c='b')
plt.scatter(pred_vertices[0, :, 0], pred_vertices[0, :, 1], s=0.1, c='r')
plt.gca().invert_yaxis()
plt.gca().set_aspect('equal', adjustable='box')
plt.subplot(346)
plt.scatter(target_vertices[0, :, 0], target_vertices[0, :, 1], s=0.1, c='b')
plt.scatter(pred_vertices_smpl[0, :, 0], pred_vertices_smpl[0, :, 1], s=0.1, c='r')
plt.gca().invert_yaxis()
plt.gca().set_aspect('equal', adjustable='box')
plt.subplot(347)
plt.scatter(target_vertices[0, :, 0], target_vertices[0, :, 1], s=0.1, c='b')
plt.scatter(pred_vertices_pa[0, :, 0], pred_vertices_pa[0, :, 1], s=0.1, c='r')
plt.gca().invert_yaxis()
plt.gca().set_aspect('equal', adjustable='box')
plt.subplot(348)
plt.scatter(target_vertices[0, :, 0], target_vertices[0, :, 1], s=0.1, c='b')
plt.scatter(pred_vertices_smpl_pa[0, :, 0], pred_vertices_smpl_pa[0, :, 1], s=0.1, c='r')
plt.gca().invert_yaxis()
plt.gca().set_aspect('equal', adjustable='box')
plt.subplot(349)
plt.scatter(target_reposed_vertices[0, :, 0], target_reposed_vertices[0, :, 1], s=0.1, c='b')
plt.scatter(pred_reposed_vertices_sc[0, :, 0], pred_reposed_vertices_sc[0, :, 1], s=0.1, c='r')
plt.gca().set_aspect('equal', adjustable='box')
plt.subplot(3, 4, 10)
for j in range(num_joints3d):
plt.scatter(pred_joints_h36mlsp[0, j, 0], pred_joints_h36mlsp[0, j, 1], c='r')
plt.scatter(target_joints_h36mlsp[0, j, 0], target_joints_h36mlsp[0, j, 1], c='b')
plt.text(pred_joints_h36mlsp[0, j, 0], pred_joints_h36mlsp[0, j, 1], s=str(j))
plt.text(target_joints_h36mlsp[0, j, 0], target_joints_h36mlsp[0, j, 1], s=str(j))
plt.gca().invert_yaxis()
plt.gca().set_aspect('equal', adjustable='box')
plt.subplot(3, 4, 11)
for j in range(num_joints3d):
plt.scatter(pred_joints_h36mlsp_pa[0, j, 0], pred_joints_h36mlsp_pa[0, j, 1], c='r')
plt.scatter(target_joints_h36mlsp[0, j, 0], target_joints_h36mlsp[0, j, 1], c='b')
plt.text(pred_joints_h36mlsp_pa[0, j, 0], pred_joints_h36mlsp_pa[0, j, 1], s=str(j))
plt.text(target_joints_h36mlsp[0, j, 0], target_joints_h36mlsp[0, j, 1], s=str(j))
plt.gca().invert_yaxis()
plt.gca().set_aspect('equal', adjustable='box')
plt.subplot(3, 4, 12)
for j in range(num_joints3d):
plt.scatter(pred_joints_smpl_h36mlsp_pa[0, j, 0], pred_joints_smpl_h36mlsp_pa[0, j, 1], c='r')
plt.scatter(target_joints_h36mlsp[0, j, 0], target_joints_h36mlsp[0, j, 1], c='b')
plt.text(pred_joints_smpl_h36mlsp_pa[0, j, 0], pred_joints_smpl_h36mlsp_pa[0, j, 1], s=str(j))
plt.text(target_joints_h36mlsp[0, j, 0], target_joints_h36mlsp[0, j, 1], s=str(j))
plt.gca().invert_yaxis()
plt.gca().set_aspect('equal', adjustable='box')
# plt.show()
save_fig_path = os.path.join(vis_save_path, fnames[0])
plt.savefig(save_fig_path, bbox_inches='tight')
plt.close()
if 'pve' in metrics:
pve_smpl = pve_smpl_sum / (num_samples * num_vertices)
print('PVE SMPL: {:.5f}'.format(pve_smpl))
pve_graph = pve_graph_sum / (num_samples * num_vertices)
print('PVE GRAPH: {:.5f}'.format(pve_graph))
pve_smpl_per_frame = np.concatenate(pve_smpl_per_frame, axis=0)
pve_graph_per_frame = np.concatenate(pve_graph_per_frame, axis=0)
np.save(os.path.join(save_path, 'pve_per_frame.npy'), pve_smpl_per_frame)
np.save(os.path.join(save_path, 'pve_graph_per_frame.npy'), pve_graph_per_frame)
if 'pve_scale_corrected' in metrics:
pve_sc_smpl = pve_scale_corrected_smpl_sum / (num_samples * num_vertices)
print('PVE SC SMPL: {:.5f}'.format(pve_sc_smpl))
pve_sc_graph = pve_scale_corrected_graph_sum / (num_samples * num_vertices)
print('PVE SC GRAPH: {:.5f}'.format(pve_sc_graph))
pve_scale_corrected_smpl_per_frame = np.concatenate(pve_scale_corrected_smpl_per_frame, axis=0)
pve_scale_corrected_graph_per_frame = np.concatenate(pve_scale_corrected_graph_per_frame, axis=0)
np.save(os.path.join(save_path, 'pve_scale_corrected_per_frame.npy'),
pve_scale_corrected_smpl_per_frame)
np.save(os.path.join(save_path, 'pve_scale_corrected_graph_per_frame.npy'),
pve_scale_corrected_graph_per_frame)
if 'pve_pa' in metrics:
pve_pa_smpl = pve_pa_smpl_sum / (num_samples * num_vertices)
print('PVE PA SMPL: {:.5f}'.format(pve_pa_smpl))
pve_pa_graph = pve_pa_graph_sum / (num_samples * num_vertices)
print('PVE PA GRAPH: {:.5f}'.format(pve_pa_graph))
pve_pa_smpl_per_frame = np.concatenate(pve_pa_smpl_per_frame, axis=0)
pve_pa_graph_per_frame = np.concatenate(pve_pa_graph_per_frame, axis=0)
np.save(os.path.join(save_path, 'pve_pa_per_frame.npy'), pve_pa_smpl_per_frame)
np.save(os.path.join(save_path, 'pve_pa_graph_per_frame.npy'), pve_pa_graph_per_frame)
if 'pve-t' in metrics:
pvet = pvet_sum / (num_samples * num_vertices)
print('PVE-T: {:.5f}'.format(pvet))
pvet_per_frame = np.concatenate(pvet_per_frame, axis=0)
np.save(os.path.join(save_path, 'pvet_per_frame.npy'), pvet_per_frame)
if 'pve-t_scale_corrected' in metrics:
pvet_sc = pvet_scale_corrected_sum / (num_samples * num_vertices)
print('PVE-T SC: {:.5f}'.format(pvet_sc))
pvet_scale_corrected_per_frame = np.concatenate(pvet_scale_corrected_per_frame, axis=0)
np.save(os.path.join(save_path, 'pvet_scale_corrected_per_frame.npy'),
pvet_scale_corrected_per_frame)
if 'mpjpe' in metrics:
mpjpe_smpl = mpjpe_smpl_sum / (num_samples * num_joints3d)
print('MPJPE SMPL: {:.5f}'.format(mpjpe_smpl))
mpjpe_graph = mpjpe_graph_sum / (num_samples * num_joints3d)
print('MPJPE GRAPH: {:.5f}'.format(mpjpe_graph))
mpjpe_smpl_per_frame = np.concatenate(mpjpe_smpl_per_frame, axis=0)
mpjpe_graph_per_frame = np.concatenate(mpjpe_graph_per_frame, axis=0)
np.save(os.path.join(save_path, 'mpjpe_per_frame.npy'), mpjpe_smpl_per_frame)
np.save(os.path.join(save_path, 'mpjpe_graph_per_frame.npy'), mpjpe_graph_per_frame)
if 'mpjpe_scale_corrected' in metrics:
mpjpe_sc_smpl = mpjpe_scale_corrected_smpl_sum / (num_samples * num_joints3d)
print('MPJPE SC SMPL: {:.5f}'.format(mpjpe_sc_smpl))
mpjpe_sc_graph = mpjpe_scale_corrected_graph_sum / (num_samples * num_joints3d)
print('MPJPE SC GRAPH: {:.5f}'.format(mpjpe_sc_graph))
mpjpe_scale_corrected_smpl_per_frame = np.concatenate(
mpjpe_scale_corrected_smpl_per_frame, axis=0)
mpjpe_scale_corrected_graph_per_frame = np.concatenate(
mpjpe_scale_corrected_graph_per_frame, axis=0)
np.save(os.path.join(save_path, 'mpjpe_scale_corrected_per_frame.npy'),
mpjpe_scale_corrected_smpl_per_frame)
np.save(os.path.join(save_path, 'mpjpe_scale_corrected_graph_per_frame.npy'),
mpjpe_scale_corrected_graph_per_frame)
if 'j3d_rec_err' in metrics:
j3d_rec_err_smpl = j3d_rec_err_smpl_sum / (num_samples * num_joints3d)
print('Rec Err SMPL: {:.5f}'.format(j3d_rec_err_smpl))
j3d_rec_err_graph = j3d_rec_err_graph_sum / (num_samples * num_joints3d)
print('Rec Err GRAPH: {:.5f}'.format(j3d_rec_err_graph))
j3d_rec_err_smpl_per_frame = np.concatenate(j3d_rec_err_smpl_per_frame, axis=0)
j3d_rec_err_graph_per_frame = np.concatenate(j3d_rec_err_graph_per_frame, axis=0)
np.save(os.path.join(save_path, 'j3d_rec_err_per_frame.npy'),
j3d_rec_err_smpl_per_frame)
np.save(os.path.join(save_path, 'j3d_rec_err_graph_per_frame.npy'),
j3d_rec_err_graph_per_frame)
if 'pve_2d' in metrics:
pve_2d_smpl = pve_2d_smpl_sum / (num_samples * num_vertices)
print('PVE 2D SMPL: {:.5f}'.format(pve_2d_smpl))
pve_2d_graph = pve_2d_graph_sum / (num_samples * num_vertices)
print('PVE 2D GRAPH: {:.5f}'.format(pve_2d_graph))
if 'pve_2d_scale_corrected' in metrics:
pve_2d_sc_smpl = pve_2d_scale_corrected_smpl_sum / (num_samples * num_vertices)
print('PVE 2D SC SMPL: {:.5f}'.format(pve_2d_sc_smpl))
pve_2d_sc_graph = pve_2d_scale_corrected_graph_sum / (num_samples * num_vertices)
print('PVE 2D SC GRAPH: {:.5f}'.format(pve_2d_sc_graph))
if 'pve_2d_pa' in metrics:
pve_2d_pa_smpl = pve_2d_pa_smpl_sum / (num_samples * num_vertices)
print('PVE 2D PA SMPL: {:.5f}'.format(pve_2d_pa_smpl))
pve_2d_pa_graph = pve_2d_pa_graph_sum / (num_samples * num_vertices)
print('PVE 2D PA GRAPH: {:.5f}'.format(pve_2d_pa_graph))
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--checkpoint', default=None, help='Path to network checkpoint')
parser.add_argument('--gpu', default="0", type=str, help='GPU')
args = parser.parse_args()
# Device
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" # see issue #152
os.environ["CUDA_VISIBLE_DEVICES"] = args.gpu
device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
# Load model
mesh = Mesh(device=device)
# Our pretrained networks have 5 residual blocks with 256 channels.
# You might want to change this if you use a different architecture.
model = CMR(mesh, 5, 256, pretrained_checkpoint=args.checkpoint, device=device)
model.to(device)
model.eval()
# Setup evaluation dataset
dataset_path = '/scratch2/as2562/datasets/3DPW/test'
dataset = PW3DEvalDataset(dataset_path, img_wh=config.INPUT_RES)
print("Eval examples found:", len(dataset))
# Metrics
metrics = ['pve', 'pve-t', 'pve_pa', 'pve-t_pa', 'mpjpe', 'j3d_rec_err',
'pve_2d', 'pve_2d_pa', 'pve_2d_scale_corrected',
'pve_scale_corrected', 'pve-t_scale_corrected', 'mpjpe_scale_corrected']
save_path = '/data/cvfs/as2562/GraphCMR/evaluations/3dpw'
if not os.path.exists(save_path):
os.makedirs(save_path)
# Run evaluation
evaluate_3dpw(model=model,
eval_dataset=dataset,
metrics=metrics,
device=device,
vis_save_path=save_path,
num_workers=4,
pin_memory=True,
vis_every_n_batches=1000)
| 52.824663 | 125 | 0.633353 | import os
import numpy as np
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
import torch
from torch.utils.data import DataLoader
from tqdm import tqdm
import argparse
import cv2
import config
from utils import Mesh
from models import CMR
from models.smpl_from_lib import SMPL
from utils.pose_utils import compute_similarity_transform_batch, \
scale_and_translation_transform_batch
from utils.cam_utils import orthographic_project_torch, undo_keypoint_normalisation
from datasets.my_3dpw_eval_dataset import PW3DEvalDataset
def evaluate_3dpw(model,
eval_dataset,
metrics,
device,
vis_save_path,
num_workers=4,
pin_memory=True,
vis_every_n_batches=1000):
eval_dataloader = DataLoader(eval_dataset,
batch_size=1,
shuffle=False,
drop_last=True,
num_workers=num_workers,
pin_memory=pin_memory)
smpl = SMPL(config.SMPL_MODEL_DIR, batch_size=1)
smpl_male = SMPL(config.SMPL_MODEL_DIR, batch_size=1, gender='male')
smpl_female = SMPL(config.SMPL_MODEL_DIR, batch_size=1, gender='female')
smpl.to(device)
smpl_male.to(device)
smpl_female.to(device)
J_regressor = torch.from_numpy(np.load(config.JOINT_REGRESSOR_H36M)).float()
J_regressor_batch = J_regressor[None, :].to(device)
if 'pve' in metrics:
pve_smpl_sum = 0.0
pve_graph_sum = 0.0
pve_smpl_per_frame = []
pve_graph_per_frame = []
if 'pve_scale_corrected' in metrics:
pve_scale_corrected_smpl_sum = 0.0
pve_scale_corrected_graph_sum = 0.0
pve_scale_corrected_smpl_per_frame = []
pve_scale_corrected_graph_per_frame = []
if 'pve_pa' in metrics:
pve_pa_smpl_sum = 0.0
pve_pa_graph_sum = 0.0
pve_pa_smpl_per_frame = []
pve_pa_graph_per_frame = []
if 'pve-t' in metrics:
pvet_sum = 0.0
pvet_per_frame = []
if 'pve-t_scale_corrected' in metrics:
pvet_scale_corrected_sum = 0.0
pvet_scale_corrected_per_frame = []
if 'mpjpe' in metrics:
mpjpe_smpl_sum = 0.0
mpjpe_graph_sum = 0.0
mpjpe_smpl_per_frame = []
mpjpe_graph_per_frame = []
if 'mpjpe_scale_corrected' in metrics:
mpjpe_scale_corrected_smpl_sum = 0.0
mpjpe_scale_corrected_graph_sum = 0.0
mpjpe_scale_corrected_smpl_per_frame = []
mpjpe_scale_corrected_graph_per_frame = []
if 'j3d_rec_err' in metrics:
j3d_rec_err_smpl_sum = 0.0
j3d_rec_err_graph_sum = 0.0
j3d_rec_err_smpl_per_frame = []
j3d_rec_err_graph_per_frame = []
if 'pve_2d' in metrics:
pve_2d_smpl_sum = 0.0
pve_2d_graph_sum = 0.0
if 'pve_2d_scale_corrected' in metrics:
pve_2d_scale_corrected_smpl_sum = 0.0
pve_2d_scale_corrected_graph_sum = 0.0
if 'pve_2d_pa' in metrics:
pve_2d_pa_smpl_sum = 0.0
pve_2d_pa_graph_sum = 0.0
num_samples = 0
num_vertices = 6890
num_joints3d = 14
model.eval()
for batch_num, samples_batch in enumerate(tqdm(eval_dataloader)):
input = samples_batch['input']
input = input.to(device)
target_pose = samples_batch['pose'].to(device)
target_shape = samples_batch['shape'].to(device)
target_gender = samples_batch['gender'][0]
if target_gender == 'm':
target_smpl_output = smpl_male(body_pose=target_pose[:, 3:],
global_orient=target_pose[:, :3],
betas=target_shape)
target_vertices = target_smpl_output.vertices
target_reposed_smpl_output = smpl_male(betas=target_shape)
target_reposed_vertices = target_reposed_smpl_output.vertices
target_joints_h36m = torch.matmul(J_regressor_batch, target_vertices)
target_joints_h36mlsp = target_joints_h36m[:, config.H36M_TO_J14, :]
elif target_gender == 'f':
target_smpl_output = smpl_female(body_pose=target_pose[:, 3:],
global_orient=target_pose[:, :3],
betas=target_shape)
target_vertices = target_smpl_output.vertices
target_reposed_smpl_output = smpl_female(betas=target_shape)
target_reposed_vertices = target_reposed_smpl_output.vertices
target_joints_h36m = torch.matmul(J_regressor_batch, target_vertices)
target_joints_h36mlsp = target_joints_h36m[:, config.H36M_TO_J14, :]
pred_vertices, pred_vertices_smpl, pred_camera, pred_rotmat, pred_betas = model(input)
pred_vertices_projected2d = orthographic_project_torch(pred_vertices, pred_camera)
pred_vertices_projected2d = undo_keypoint_normalisation(pred_vertices_projected2d, input.shape[-1])
pred_vertices_smpl_projected2d = orthographic_project_torch(pred_vertices_smpl, pred_camera)
pred_vertices_smpl_projected2d = undo_keypoint_normalisation(pred_vertices_smpl_projected2d, input.shape[-1])
pred_reposed_smpl_output = smpl(betas=pred_betas)
pred_reposed_vertices = pred_reposed_smpl_output.vertices
pred_joints_h36m = torch.matmul(J_regressor_batch, pred_vertices)
pred_joints_h36mlsp = pred_joints_h36m[:, config.H36M_TO_J14, :]
pred_joints_smpl_h36m = torch.matmul(J_regressor_batch, pred_vertices_smpl)
pred_joints_smpl_h36mlsp = pred_joints_smpl_h36m[:, config.H36M_TO_J14, :]
target_vertices = target_vertices.cpu().detach().numpy()
target_reposed_vertices = target_reposed_vertices.cpu().detach().numpy()
target_joints_h36mlsp = target_joints_h36mlsp.cpu().detach().numpy()
pred_vertices = pred_vertices.cpu().detach().numpy()
pred_vertices_smpl = pred_vertices_smpl.cpu().detach().numpy()
pred_vertices_projected2d = pred_vertices_projected2d.cpu().detach().numpy()
pred_vertices_smpl_projected2d = pred_vertices_smpl_projected2d.cpu().detach().numpy()
pred_reposed_vertices = pred_reposed_vertices.cpu().detach().numpy()
pred_joints_h36mlsp = pred_joints_h36mlsp.cpu().detach().numpy()
pred_joints_smpl_h36mlsp = pred_joints_smpl_h36mlsp.cpu().detach().numpy()
if 'pve' in metrics:
pve_smpl_batch = np.linalg.norm(pred_vertices_smpl - target_vertices, axis=-1)
pve_graph_batch = np.linalg.norm(pred_vertices - target_vertices, axis=-1)
pve_smpl_sum += np.sum(pve_smpl_batch)
pve_graph_sum += np.sum(pve_graph_batch)
pve_smpl_per_frame.append(np.mean(pve_smpl_batch, axis=-1))
pve_graph_per_frame.append(np.mean(pve_graph_batch, axis=-1))
if 'pve_scale_corrected' in metrics:
pred_vertices_smpl_sc = scale_and_translation_transform_batch(pred_vertices_smpl,
target_vertices)
pred_vertices_sc = scale_and_translation_transform_batch(pred_vertices,
target_vertices)
pve_sc_smpl_batch = np.linalg.norm(pred_vertices_smpl_sc - target_vertices,
axis=-1)
pve_sc_graph_batch = np.linalg.norm(pred_vertices_sc - target_vertices,
axis=-1)
pve_scale_corrected_smpl_sum += np.sum(pve_sc_smpl_batch)
pve_scale_corrected_graph_sum += np.sum(pve_sc_graph_batch)
pve_scale_corrected_smpl_per_frame.append(np.mean(pve_sc_smpl_batch, axis=-1))
pve_scale_corrected_graph_per_frame.append(np.mean(pve_sc_graph_batch, axis=-1))
if 'pve_pa' in metrics:
pred_vertices_smpl_pa = compute_similarity_transform_batch(pred_vertices_smpl, target_vertices)
pred_vertices_pa = compute_similarity_transform_batch(pred_vertices, target_vertices)
pve_pa_smpl_batch = np.linalg.norm(pred_vertices_smpl_pa - target_vertices, axis=-1)
pve_pa_graph_batch = np.linalg.norm(pred_vertices_pa - target_vertices, axis=-1)
pve_pa_smpl_sum += np.sum(pve_pa_smpl_batch)
pve_pa_graph_sum += np.sum(pve_pa_graph_batch)
pve_pa_smpl_per_frame.append(np.mean(pve_pa_smpl_batch, axis=-1))
pve_pa_graph_per_frame.append(np.mean(pve_pa_graph_batch, axis=-1))
if 'pve-t' in metrics:
pvet_batch = np.linalg.norm(pred_reposed_vertices - target_reposed_vertices, axis=-1)
pvet_sum += np.sum(pvet_batch)
pvet_per_frame.append(np.mean(pvet_batch, axis=-1))
if 'pve-t_scale_corrected' in metrics:
pred_reposed_vertices_sc = scale_and_translation_transform_batch(pred_reposed_vertices,
target_reposed_vertices)
pvet_scale_corrected_batch = np.linalg.norm(pred_reposed_vertices_sc - target_reposed_vertices,
axis=-1)
pvet_scale_corrected_sum += np.sum(pvet_scale_corrected_batch)
pvet_scale_corrected_per_frame.append(np.mean(pvet_scale_corrected_batch, axis=-1))
if 'mpjpe' in metrics:
mpjpe_smpl_batch = np.linalg.norm(pred_joints_smpl_h36mlsp - target_joints_h36mlsp, axis=-1)
mpjpe_graph_batch = np.linalg.norm(pred_joints_h36mlsp - target_joints_h36mlsp, axis=-1)
mpjpe_smpl_sum += np.sum(mpjpe_smpl_batch)
mpjpe_graph_sum += np.sum(mpjpe_graph_batch)
mpjpe_smpl_per_frame.append(np.mean(mpjpe_smpl_batch, axis=-1))
mpjpe_graph_per_frame.append(np.mean(mpjpe_graph_batch, axis=-1))
if 'mpjpe_scale_corrected' in metrics:
pred_joints_smpl_h36mlsp_sc = scale_and_translation_transform_batch(pred_joints_smpl_h36mlsp,
target_joints_h36mlsp)
pred_joints_h36mlsp_sc = scale_and_translation_transform_batch(pred_joints_h36mlsp,
target_joints_h36mlsp)
mpjpe_scale_corrected_smpl_batch = np.linalg.norm(pred_joints_smpl_h36mlsp_sc - target_joints_h36mlsp,
axis=-1)
mpjpe_scale_corrected_graph_batch = np.linalg.norm(pred_joints_h36mlsp_sc - target_joints_h36mlsp,
axis=-1)
mpjpe_scale_corrected_smpl_sum += np.sum(mpjpe_scale_corrected_smpl_batch)
mpjpe_scale_corrected_graph_sum += np.sum(mpjpe_scale_corrected_graph_batch)
mpjpe_scale_corrected_smpl_per_frame.append(np.mean(mpjpe_scale_corrected_smpl_batch, axis=-1))
mpjpe_scale_corrected_graph_per_frame.append(np.mean(mpjpe_scale_corrected_graph_batch, axis=-1))
if 'j3d_rec_err' in metrics:
pred_joints_smpl_h36mlsp_pa = compute_similarity_transform_batch(pred_joints_smpl_h36mlsp,
target_joints_h36mlsp)
pred_joints_h36mlsp_pa = compute_similarity_transform_batch(pred_joints_h36mlsp, target_joints_h36mlsp)
j3d_rec_err_smpl_batch = np.linalg.norm(pred_joints_smpl_h36mlsp_pa - target_joints_h36mlsp, axis=-1)
j3d_rec_err_graph_batch = np.linalg.norm(pred_joints_h36mlsp_pa - target_joints_h36mlsp, axis=-1)
j3d_rec_err_smpl_sum += np.sum(j3d_rec_err_smpl_batch)
j3d_rec_err_graph_sum += np.sum(j3d_rec_err_graph_batch)
j3d_rec_err_smpl_per_frame.append(np.mean(j3d_rec_err_smpl_batch, axis=-1))
j3d_rec_err_graph_per_frame.append(np.mean(j3d_rec_err_graph_batch, axis=-1))
if 'pve_2d' in metrics:
pred_vertices_smpl_2d = pred_vertices_smpl[:, :, :2]
pred_vertices_2d = pred_vertices[:, :, :2]
target_vertices_2d = target_vertices[:, :, :2]
pve_2d_smpl_batch = np.linalg.norm(pred_vertices_smpl_2d - target_vertices_2d, axis=-1)
pve_2d_graph_batch = np.linalg.norm(pred_vertices_2d - target_vertices_2d, axis=-1)
pve_2d_smpl_sum += np.sum(pve_2d_smpl_batch)
pve_2d_graph_sum += np.sum(pve_2d_graph_batch)
if 'pve_2d_scale_corrected' in metrics:
pred_vertices_smpl_sc = scale_and_translation_transform_batch(pred_vertices_smpl,
target_vertices)
pred_vertices_sc = scale_and_translation_transform_batch(pred_vertices,
target_vertices)
pred_vertices_smpl_2d_sc = pred_vertices_smpl_sc[:, :, :2]
pred_vertices_2d_sc = pred_vertices_sc[:, :, :2]
target_vertices_2d = target_vertices[:, :, :2]
pve_2d_sc_smpl_batch = np.linalg.norm(pred_vertices_smpl_2d_sc - target_vertices_2d,
axis=-1)
pve_2d_sc_graph_batch = np.linalg.norm(pred_vertices_2d_sc - target_vertices_2d,
axis=-1)
pve_2d_scale_corrected_smpl_sum += np.sum(pve_2d_sc_smpl_batch)
pve_2d_scale_corrected_graph_sum += np.sum(pve_2d_sc_graph_batch)
if 'pve_2d_pa' in metrics:
pred_vertices_smpl_pa = compute_similarity_transform_batch(pred_vertices_smpl, target_vertices)
pred_vertices_pa = compute_similarity_transform_batch(pred_vertices, target_vertices)
pred_vertices_smpl_2d_pa = pred_vertices_smpl_pa[:, :, :2]
pred_vertices_2d_pa = pred_vertices_pa[:, :, :2]
target_vertices_2d = target_vertices[:, :, :2]
pve_2d_pa_smpl_batch = np.linalg.norm(pred_vertices_smpl_2d_pa - target_vertices_2d, axis=-1)
pve_2d_pa_graph_batch = np.linalg.norm(pred_vertices_2d_pa - target_vertices_2d, axis=-1)
pve_2d_pa_smpl_sum += np.sum(pve_2d_pa_smpl_batch)
pve_2d_pa_graph_sum += np.sum(pve_2d_pa_graph_batch)
num_samples += target_pose.shape[0]
if vis_every_n_batches is not None:
if batch_num % vis_every_n_batches == 0:
vis_imgs = samples_batch['vis_img'].numpy()
vis_imgs = np.transpose(vis_imgs, [0, 2, 3, 1])
fnames = samples_batch['fname']
plt.figure(figsize=(16, 12))
plt.subplot(341)
plt.imshow(vis_imgs[0])
plt.subplot(342)
plt.imshow(vis_imgs[0])
plt.scatter(pred_vertices_projected2d[0, :, 0], pred_vertices_projected2d[0, :, 1], s=0.1, c='r')
plt.subplot(343)
plt.imshow(vis_imgs[0])
plt.scatter(pred_vertices_smpl_projected2d[0, :, 0], pred_vertices_smpl_projected2d[0, :, 1], s=0.1, c='r')
plt.subplot(345)
plt.scatter(target_vertices[0, :, 0], target_vertices[0, :, 1], s=0.1, c='b')
plt.scatter(pred_vertices[0, :, 0], pred_vertices[0, :, 1], s=0.1, c='r')
plt.gca().invert_yaxis()
plt.gca().set_aspect('equal', adjustable='box')
plt.subplot(346)
plt.scatter(target_vertices[0, :, 0], target_vertices[0, :, 1], s=0.1, c='b')
plt.scatter(pred_vertices_smpl[0, :, 0], pred_vertices_smpl[0, :, 1], s=0.1, c='r')
plt.gca().invert_yaxis()
plt.gca().set_aspect('equal', adjustable='box')
plt.subplot(347)
plt.scatter(target_vertices[0, :, 0], target_vertices[0, :, 1], s=0.1, c='b')
plt.scatter(pred_vertices_pa[0, :, 0], pred_vertices_pa[0, :, 1], s=0.1, c='r')
plt.gca().invert_yaxis()
plt.gca().set_aspect('equal', adjustable='box')
plt.subplot(348)
plt.scatter(target_vertices[0, :, 0], target_vertices[0, :, 1], s=0.1, c='b')
plt.scatter(pred_vertices_smpl_pa[0, :, 0], pred_vertices_smpl_pa[0, :, 1], s=0.1, c='r')
plt.gca().invert_yaxis()
plt.gca().set_aspect('equal', adjustable='box')
plt.subplot(349)
plt.scatter(target_reposed_vertices[0, :, 0], target_reposed_vertices[0, :, 1], s=0.1, c='b')
plt.scatter(pred_reposed_vertices_sc[0, :, 0], pred_reposed_vertices_sc[0, :, 1], s=0.1, c='r')
plt.gca().set_aspect('equal', adjustable='box')
plt.subplot(3, 4, 10)
for j in range(num_joints3d):
plt.scatter(pred_joints_h36mlsp[0, j, 0], pred_joints_h36mlsp[0, j, 1], c='r')
plt.scatter(target_joints_h36mlsp[0, j, 0], target_joints_h36mlsp[0, j, 1], c='b')
plt.text(pred_joints_h36mlsp[0, j, 0], pred_joints_h36mlsp[0, j, 1], s=str(j))
plt.text(target_joints_h36mlsp[0, j, 0], target_joints_h36mlsp[0, j, 1], s=str(j))
plt.gca().invert_yaxis()
plt.gca().set_aspect('equal', adjustable='box')
plt.subplot(3, 4, 11)
for j in range(num_joints3d):
plt.scatter(pred_joints_h36mlsp_pa[0, j, 0], pred_joints_h36mlsp_pa[0, j, 1], c='r')
plt.scatter(target_joints_h36mlsp[0, j, 0], target_joints_h36mlsp[0, j, 1], c='b')
plt.text(pred_joints_h36mlsp_pa[0, j, 0], pred_joints_h36mlsp_pa[0, j, 1], s=str(j))
plt.text(target_joints_h36mlsp[0, j, 0], target_joints_h36mlsp[0, j, 1], s=str(j))
plt.gca().invert_yaxis()
plt.gca().set_aspect('equal', adjustable='box')
plt.subplot(3, 4, 12)
for j in range(num_joints3d):
plt.scatter(pred_joints_smpl_h36mlsp_pa[0, j, 0], pred_joints_smpl_h36mlsp_pa[0, j, 1], c='r')
plt.scatter(target_joints_h36mlsp[0, j, 0], target_joints_h36mlsp[0, j, 1], c='b')
plt.text(pred_joints_smpl_h36mlsp_pa[0, j, 0], pred_joints_smpl_h36mlsp_pa[0, j, 1], s=str(j))
plt.text(target_joints_h36mlsp[0, j, 0], target_joints_h36mlsp[0, j, 1], s=str(j))
plt.gca().invert_yaxis()
plt.gca().set_aspect('equal', adjustable='box')
save_fig_path = os.path.join(vis_save_path, fnames[0])
plt.savefig(save_fig_path, bbox_inches='tight')
plt.close()
if 'pve' in metrics:
pve_smpl = pve_smpl_sum / (num_samples * num_vertices)
print('PVE SMPL: {:.5f}'.format(pve_smpl))
pve_graph = pve_graph_sum / (num_samples * num_vertices)
print('PVE GRAPH: {:.5f}'.format(pve_graph))
pve_smpl_per_frame = np.concatenate(pve_smpl_per_frame, axis=0)
pve_graph_per_frame = np.concatenate(pve_graph_per_frame, axis=0)
np.save(os.path.join(save_path, 'pve_per_frame.npy'), pve_smpl_per_frame)
np.save(os.path.join(save_path, 'pve_graph_per_frame.npy'), pve_graph_per_frame)
if 'pve_scale_corrected' in metrics:
pve_sc_smpl = pve_scale_corrected_smpl_sum / (num_samples * num_vertices)
print('PVE SC SMPL: {:.5f}'.format(pve_sc_smpl))
pve_sc_graph = pve_scale_corrected_graph_sum / (num_samples * num_vertices)
print('PVE SC GRAPH: {:.5f}'.format(pve_sc_graph))
pve_scale_corrected_smpl_per_frame = np.concatenate(pve_scale_corrected_smpl_per_frame, axis=0)
pve_scale_corrected_graph_per_frame = np.concatenate(pve_scale_corrected_graph_per_frame, axis=0)
np.save(os.path.join(save_path, 'pve_scale_corrected_per_frame.npy'),
pve_scale_corrected_smpl_per_frame)
np.save(os.path.join(save_path, 'pve_scale_corrected_graph_per_frame.npy'),
pve_scale_corrected_graph_per_frame)
if 'pve_pa' in metrics:
pve_pa_smpl = pve_pa_smpl_sum / (num_samples * num_vertices)
print('PVE PA SMPL: {:.5f}'.format(pve_pa_smpl))
pve_pa_graph = pve_pa_graph_sum / (num_samples * num_vertices)
print('PVE PA GRAPH: {:.5f}'.format(pve_pa_graph))
pve_pa_smpl_per_frame = np.concatenate(pve_pa_smpl_per_frame, axis=0)
pve_pa_graph_per_frame = np.concatenate(pve_pa_graph_per_frame, axis=0)
np.save(os.path.join(save_path, 'pve_pa_per_frame.npy'), pve_pa_smpl_per_frame)
np.save(os.path.join(save_path, 'pve_pa_graph_per_frame.npy'), pve_pa_graph_per_frame)
if 'pve-t' in metrics:
pvet = pvet_sum / (num_samples * num_vertices)
print('PVE-T: {:.5f}'.format(pvet))
pvet_per_frame = np.concatenate(pvet_per_frame, axis=0)
np.save(os.path.join(save_path, 'pvet_per_frame.npy'), pvet_per_frame)
if 'pve-t_scale_corrected' in metrics:
pvet_sc = pvet_scale_corrected_sum / (num_samples * num_vertices)
print('PVE-T SC: {:.5f}'.format(pvet_sc))
pvet_scale_corrected_per_frame = np.concatenate(pvet_scale_corrected_per_frame, axis=0)
np.save(os.path.join(save_path, 'pvet_scale_corrected_per_frame.npy'),
pvet_scale_corrected_per_frame)
if 'mpjpe' in metrics:
mpjpe_smpl = mpjpe_smpl_sum / (num_samples * num_joints3d)
print('MPJPE SMPL: {:.5f}'.format(mpjpe_smpl))
mpjpe_graph = mpjpe_graph_sum / (num_samples * num_joints3d)
print('MPJPE GRAPH: {:.5f}'.format(mpjpe_graph))
mpjpe_smpl_per_frame = np.concatenate(mpjpe_smpl_per_frame, axis=0)
mpjpe_graph_per_frame = np.concatenate(mpjpe_graph_per_frame, axis=0)
np.save(os.path.join(save_path, 'mpjpe_per_frame.npy'), mpjpe_smpl_per_frame)
np.save(os.path.join(save_path, 'mpjpe_graph_per_frame.npy'), mpjpe_graph_per_frame)
if 'mpjpe_scale_corrected' in metrics:
mpjpe_sc_smpl = mpjpe_scale_corrected_smpl_sum / (num_samples * num_joints3d)
print('MPJPE SC SMPL: {:.5f}'.format(mpjpe_sc_smpl))
mpjpe_sc_graph = mpjpe_scale_corrected_graph_sum / (num_samples * num_joints3d)
print('MPJPE SC GRAPH: {:.5f}'.format(mpjpe_sc_graph))
mpjpe_scale_corrected_smpl_per_frame = np.concatenate(
mpjpe_scale_corrected_smpl_per_frame, axis=0)
mpjpe_scale_corrected_graph_per_frame = np.concatenate(
mpjpe_scale_corrected_graph_per_frame, axis=0)
np.save(os.path.join(save_path, 'mpjpe_scale_corrected_per_frame.npy'),
mpjpe_scale_corrected_smpl_per_frame)
np.save(os.path.join(save_path, 'mpjpe_scale_corrected_graph_per_frame.npy'),
mpjpe_scale_corrected_graph_per_frame)
if 'j3d_rec_err' in metrics:
j3d_rec_err_smpl = j3d_rec_err_smpl_sum / (num_samples * num_joints3d)
print('Rec Err SMPL: {:.5f}'.format(j3d_rec_err_smpl))
j3d_rec_err_graph = j3d_rec_err_graph_sum / (num_samples * num_joints3d)
print('Rec Err GRAPH: {:.5f}'.format(j3d_rec_err_graph))
j3d_rec_err_smpl_per_frame = np.concatenate(j3d_rec_err_smpl_per_frame, axis=0)
j3d_rec_err_graph_per_frame = np.concatenate(j3d_rec_err_graph_per_frame, axis=0)
np.save(os.path.join(save_path, 'j3d_rec_err_per_frame.npy'),
j3d_rec_err_smpl_per_frame)
np.save(os.path.join(save_path, 'j3d_rec_err_graph_per_frame.npy'),
j3d_rec_err_graph_per_frame)
if 'pve_2d' in metrics:
pve_2d_smpl = pve_2d_smpl_sum / (num_samples * num_vertices)
print('PVE 2D SMPL: {:.5f}'.format(pve_2d_smpl))
pve_2d_graph = pve_2d_graph_sum / (num_samples * num_vertices)
print('PVE 2D GRAPH: {:.5f}'.format(pve_2d_graph))
if 'pve_2d_scale_corrected' in metrics:
pve_2d_sc_smpl = pve_2d_scale_corrected_smpl_sum / (num_samples * num_vertices)
print('PVE 2D SC SMPL: {:.5f}'.format(pve_2d_sc_smpl))
pve_2d_sc_graph = pve_2d_scale_corrected_graph_sum / (num_samples * num_vertices)
print('PVE 2D SC GRAPH: {:.5f}'.format(pve_2d_sc_graph))
if 'pve_2d_pa' in metrics:
pve_2d_pa_smpl = pve_2d_pa_smpl_sum / (num_samples * num_vertices)
print('PVE 2D PA SMPL: {:.5f}'.format(pve_2d_pa_smpl))
pve_2d_pa_graph = pve_2d_pa_graph_sum / (num_samples * num_vertices)
print('PVE 2D PA GRAPH: {:.5f}'.format(pve_2d_pa_graph))
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--checkpoint', default=None, help='Path to network checkpoint')
parser.add_argument('--gpu', default="0", type=str, help='GPU')
args = parser.parse_args()
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" os.environ["CUDA_VISIBLE_DEVICES"] = args.gpu
device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
mesh = Mesh(device=device)
model = CMR(mesh, 5, 256, pretrained_checkpoint=args.checkpoint, device=device)
model.to(device)
model.eval()
dataset_path = '/scratch2/as2562/datasets/3DPW/test'
dataset = PW3DEvalDataset(dataset_path, img_wh=config.INPUT_RES)
print("Eval examples found:", len(dataset))
metrics = ['pve', 'pve-t', 'pve_pa', 'pve-t_pa', 'mpjpe', 'j3d_rec_err',
'pve_2d', 'pve_2d_pa', 'pve_2d_scale_corrected',
'pve_scale_corrected', 'pve-t_scale_corrected', 'mpjpe_scale_corrected']
save_path = '/data/cvfs/as2562/GraphCMR/evaluations/3dpw'
if not os.path.exists(save_path):
os.makedirs(save_path)
evaluate_3dpw(model=model,
eval_dataset=dataset,
metrics=metrics,
device=device,
vis_save_path=save_path,
num_workers=4,
pin_memory=True,
vis_every_n_batches=1000)
| true | true |
790bc953207ced07f54191f143f08a64efb6f56a | 1,017 | py | Python | my_site/users/admin.py | pshortt/my_site | b8b22e3138642e1509e4e476c678ac09615fecd8 | [
"MIT"
] | null | null | null | my_site/users/admin.py | pshortt/my_site | b8b22e3138642e1509e4e476c678ac09615fecd8 | [
"MIT"
] | 14 | 2022-01-21T05:22:47.000Z | 2022-03-31T05:29:24.000Z | my_site/users/admin.py | pshortt/my_site | b8b22e3138642e1509e4e476c678ac09615fecd8 | [
"MIT"
] | null | null | null | from django.contrib import admin
from django.contrib.auth import admin as auth_admin
from django.contrib.auth import get_user_model
from django.utils.translation import gettext_lazy as _
from my_site.users.forms import UserAdminChangeForm, UserAdminCreationForm
User = get_user_model()
@admin.register(User)
class UserAdmin(auth_admin.UserAdmin):
form = UserAdminChangeForm
add_form = UserAdminCreationForm
fieldsets = (
(None, {"fields": ("username", "password")}),
(_("Personal info"), {"fields": ("name", "email")}),
(
_("Permissions"),
{
"fields": (
"is_active",
"is_staff",
"is_superuser",
"groups",
"user_permissions",
),
},
),
(_("Important dates"), {"fields": ("last_login", "date_joined")}),
)
list_display = ["username", "name", "is_superuser"]
search_fields = ["name"]
| 29.057143 | 74 | 0.564405 | from django.contrib import admin
from django.contrib.auth import admin as auth_admin
from django.contrib.auth import get_user_model
from django.utils.translation import gettext_lazy as _
from my_site.users.forms import UserAdminChangeForm, UserAdminCreationForm
User = get_user_model()
@admin.register(User)
class UserAdmin(auth_admin.UserAdmin):
form = UserAdminChangeForm
add_form = UserAdminCreationForm
fieldsets = (
(None, {"fields": ("username", "password")}),
(_("Personal info"), {"fields": ("name", "email")}),
(
_("Permissions"),
{
"fields": (
"is_active",
"is_staff",
"is_superuser",
"groups",
"user_permissions",
),
},
),
(_("Important dates"), {"fields": ("last_login", "date_joined")}),
)
list_display = ["username", "name", "is_superuser"]
search_fields = ["name"]
| true | true |
790bc9c086190b6638eddd623ad4c7185a055404 | 5,264 | py | Python | SymbolExtractorAndRenamer/lldb/packages/Python/lldbsuite/test/lang/objc/objc-property/TestObjCProperty.py | Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | [
"Apache-2.0"
] | 427 | 2018-05-29T14:21:02.000Z | 2022-03-16T03:17:54.000Z | SymbolExtractorAndRenamer/lldb/packages/Python/lldbsuite/test/lang/objc/objc-property/TestObjCProperty.py | PolideaPlayground/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | [
"Apache-2.0"
] | 25 | 2018-07-23T08:34:15.000Z | 2021-11-05T07:13:36.000Z | SymbolExtractorAndRenamer/lldb/packages/Python/lldbsuite/test/lang/objc/objc-property/TestObjCProperty.py | PolideaPlayground/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | [
"Apache-2.0"
] | 52 | 2018-07-19T19:57:32.000Z | 2022-03-11T16:05:38.000Z | """
Use lldb Python API to verify that expression evaluation for property references uses the correct getters and setters
"""
from __future__ import print_function
import os
import time
import re
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class ObjCPropertyTestCase(TestBase):
mydir = TestBase.compute_mydir(__file__)
def setUp(self):
# Call super's setUp().
TestBase.setUp(self)
# Find the line number to break for main.c.
self.source_name = 'main.m'
@skipUnlessDarwin
@add_test_categories(['pyapi'])
def test_objc_properties(self):
"""Test that expr uses the correct property getters and setters"""
if self.getArchitecture() == 'i386':
self.skipTest("requires modern objc runtime")
self.build()
exe = os.path.join(os.getcwd(), "a.out")
# Create a target from the debugger.
target = self.dbg.CreateTarget(exe)
self.assertTrue(target, VALID_TARGET)
# Set up our breakpoints:
main_bkpt = target.BreakpointCreateBySourceRegex(
"Set a breakpoint here.", lldb.SBFileSpec(self.source_name))
self.assertTrue(main_bkpt and
main_bkpt.GetNumLocations() == 1,
VALID_BREAKPOINT)
# Now launch the process, and do not stop at the entry point.
process = target.LaunchSimple(
None, None, self.get_process_working_directory())
self.assertTrue(process.GetState() == lldb.eStateStopped,
PROCESS_STOPPED)
threads = lldbutil.get_threads_stopped_at_breakpoint(
process, main_bkpt)
self.assertTrue(len(threads) == 1)
thread = threads[0]
frame = thread.GetFrameAtIndex(0)
mine = frame.FindVariable("mine")
self.assertTrue(mine.IsValid())
access_count = mine.GetChildMemberWithName("_access_count")
self.assertTrue(access_count.IsValid())
start_access_count = access_count.GetValueAsUnsigned(123456)
self.assertTrue(start_access_count != 123456)
#
# The first set of tests test calling the getter & setter of
# a property that actually only has a getter & setter and no
# @property.
#
nonexistant_value = frame.EvaluateExpression(
"mine.nonexistantInt", False)
nonexistant_error = nonexistant_value.GetError()
self.assertTrue(nonexistant_error.Success())
nonexistant_int = nonexistant_value.GetValueAsUnsigned(123456)
self.assertTrue(nonexistant_int == 6)
# Calling the getter function would up the access count, so make sure
# that happened.
new_access_count = access_count.GetValueAsUnsigned(123456)
self.assertTrue(new_access_count - start_access_count == 1)
start_access_count = new_access_count
#
# Now call the setter, then make sure that
nonexistant_change = frame.EvaluateExpression(
"mine.nonexistantInt = 10", False)
nonexistant_error = nonexistant_change.GetError()
self.assertTrue(nonexistant_error.Success())
# Calling the setter function would up the access count, so make sure
# that happened.
new_access_count = access_count.GetValueAsUnsigned(123456)
self.assertTrue(new_access_count - start_access_count == 1)
start_access_count = new_access_count
#
# Now we call the getter of a property that is backed by an ivar,
# make sure it works and that we actually update the backing ivar.
#
backed_value = frame.EvaluateExpression("mine.backedInt", False)
backed_error = backed_value.GetError()
self.assertTrue(backed_error.Success())
backing_value = mine.GetChildMemberWithName("_backedInt")
self.assertTrue(backing_value.IsValid())
self.assertTrue(backed_value.GetValueAsUnsigned(12345)
== backing_value.GetValueAsUnsigned(23456))
unbacked_value = frame.EvaluateExpression("mine.unbackedInt", False)
unbacked_error = unbacked_value.GetError()
self.assertTrue(unbacked_error.Success())
idWithProtocol_value = frame.EvaluateExpression(
"mine.idWithProtocol", False)
idWithProtocol_error = idWithProtocol_value.GetError()
self.assertTrue(idWithProtocol_error.Success())
self.assertTrue(idWithProtocol_value.GetTypeName() == "id")
# Make sure that class property getter works as expected
value = frame.EvaluateExpression("BaseClass.classInt", False)
self.assertTrue(value.GetError().Success())
self.assertTrue(value.GetValueAsUnsigned(11111) == 123)
# Make sure that class property setter works as expected
value = frame.EvaluateExpression("BaseClass.classInt = 234", False)
self.assertTrue(value.GetError().Success())
# Verify that setter above actually worked
value = frame.EvaluateExpression("BaseClass.classInt", False)
self.assertTrue(value.GetError().Success())
self.assertTrue(value.GetValueAsUnsigned(11111) == 234)
| 37.6 | 117 | 0.671922 |
from __future__ import print_function
import os
import time
import re
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class ObjCPropertyTestCase(TestBase):
mydir = TestBase.compute_mydir(__file__)
def setUp(self):
TestBase.setUp(self)
# Find the line number to break for main.c.
self.source_name = 'main.m'
@skipUnlessDarwin
@add_test_categories(['pyapi'])
def test_objc_properties(self):
if self.getArchitecture() == 'i386':
self.skipTest("requires modern objc runtime")
self.build()
exe = os.path.join(os.getcwd(), "a.out")
# Create a target from the debugger.
target = self.dbg.CreateTarget(exe)
self.assertTrue(target, VALID_TARGET)
# Set up our breakpoints:
main_bkpt = target.BreakpointCreateBySourceRegex(
"Set a breakpoint here.", lldb.SBFileSpec(self.source_name))
self.assertTrue(main_bkpt and
main_bkpt.GetNumLocations() == 1,
VALID_BREAKPOINT)
# Now launch the process, and do not stop at the entry point.
process = target.LaunchSimple(
None, None, self.get_process_working_directory())
self.assertTrue(process.GetState() == lldb.eStateStopped,
PROCESS_STOPPED)
threads = lldbutil.get_threads_stopped_at_breakpoint(
process, main_bkpt)
self.assertTrue(len(threads) == 1)
thread = threads[0]
frame = thread.GetFrameAtIndex(0)
mine = frame.FindVariable("mine")
self.assertTrue(mine.IsValid())
access_count = mine.GetChildMemberWithName("_access_count")
self.assertTrue(access_count.IsValid())
start_access_count = access_count.GetValueAsUnsigned(123456)
self.assertTrue(start_access_count != 123456)
#
# The first set of tests test calling the getter & setter of
# a property that actually only has a getter & setter and no
# @property.
#
nonexistant_value = frame.EvaluateExpression(
"mine.nonexistantInt", False)
nonexistant_error = nonexistant_value.GetError()
self.assertTrue(nonexistant_error.Success())
nonexistant_int = nonexistant_value.GetValueAsUnsigned(123456)
self.assertTrue(nonexistant_int == 6)
# Calling the getter function would up the access count, so make sure
# that happened.
new_access_count = access_count.GetValueAsUnsigned(123456)
self.assertTrue(new_access_count - start_access_count == 1)
start_access_count = new_access_count
#
# Now call the setter, then make sure that
nonexistant_change = frame.EvaluateExpression(
"mine.nonexistantInt = 10", False)
nonexistant_error = nonexistant_change.GetError()
self.assertTrue(nonexistant_error.Success())
# Calling the setter function would up the access count, so make sure
# that happened.
new_access_count = access_count.GetValueAsUnsigned(123456)
self.assertTrue(new_access_count - start_access_count == 1)
start_access_count = new_access_count
#
# Now we call the getter of a property that is backed by an ivar,
# make sure it works and that we actually update the backing ivar.
#
backed_value = frame.EvaluateExpression("mine.backedInt", False)
backed_error = backed_value.GetError()
self.assertTrue(backed_error.Success())
backing_value = mine.GetChildMemberWithName("_backedInt")
self.assertTrue(backing_value.IsValid())
self.assertTrue(backed_value.GetValueAsUnsigned(12345)
== backing_value.GetValueAsUnsigned(23456))
unbacked_value = frame.EvaluateExpression("mine.unbackedInt", False)
unbacked_error = unbacked_value.GetError()
self.assertTrue(unbacked_error.Success())
idWithProtocol_value = frame.EvaluateExpression(
"mine.idWithProtocol", False)
idWithProtocol_error = idWithProtocol_value.GetError()
self.assertTrue(idWithProtocol_error.Success())
self.assertTrue(idWithProtocol_value.GetTypeName() == "id")
# Make sure that class property getter works as expected
value = frame.EvaluateExpression("BaseClass.classInt", False)
self.assertTrue(value.GetError().Success())
self.assertTrue(value.GetValueAsUnsigned(11111) == 123)
# Make sure that class property setter works as expected
value = frame.EvaluateExpression("BaseClass.classInt = 234", False)
self.assertTrue(value.GetError().Success())
# Verify that setter above actually worked
value = frame.EvaluateExpression("BaseClass.classInt", False)
self.assertTrue(value.GetError().Success())
self.assertTrue(value.GetValueAsUnsigned(11111) == 234)
| true | true |
790bca0d1f46d46e28ef4406eb3ecb240b0e1c9e | 1,581 | py | Python | torchvision/extension.py | jamt9000/vision | 598b61d93357139cec558af6eff38a77ac60cabc | [
"BSD-3-Clause"
] | 3 | 2019-11-03T01:31:37.000Z | 2020-01-08T10:48:31.000Z | torchvision/extension.py | JXQJ/vision | b6f28ec1a8c5fdb8d01cc61946e8f87dddcfa830 | [
"BSD-3-Clause"
] | 1 | 2019-03-02T06:43:20.000Z | 2019-03-02T06:43:20.000Z | torchvision/extension.py | JXQJ/vision | b6f28ec1a8c5fdb8d01cc61946e8f87dddcfa830 | [
"BSD-3-Clause"
] | 1 | 2020-09-11T20:54:56.000Z | 2020-09-11T20:54:56.000Z | _HAS_OPS = False
def _register_extensions():
import os
import imp
import torch
# load the custom_op_library and register the custom ops
lib_dir = os.path.dirname(__file__)
_, path, _ = imp.find_module("_C", [lib_dir])
torch.ops.load_library(path)
try:
_register_extensions()
_HAS_OPS = True
except (ImportError, OSError):
pass
def _check_cuda_version():
"""
Make sure that CUDA versions match between the pytorch install and torchvision install
"""
if not _HAS_OPS:
return -1
import torch
_version = torch.ops.torchvision._cuda_version()
if _version != -1 and torch.version.cuda is not None:
tv_version = str(_version)
if int(tv_version) < 10000:
tv_major = int(tv_version[0])
tv_minor = int(tv_version[2])
else:
tv_major = int(tv_version[0:2])
tv_minor = int(tv_version[3])
t_version = torch.version.cuda
t_version = t_version.split('.')
t_major = int(t_version[0])
t_minor = int(t_version[1])
if t_major != tv_major or t_minor != tv_minor:
raise RuntimeError("Detected that PyTorch and torchvision were compiled with different CUDA versions. "
"PyTorch has CUDA Version={}.{} and torchvision has CUDA Version={}.{}. "
"Please reinstall the torchvision that matches your PyTorch install."
.format(t_major, t_minor, tv_major, tv_minor))
return _version
_check_cuda_version()
| 31 | 115 | 0.619861 | _HAS_OPS = False
def _register_extensions():
import os
import imp
import torch
lib_dir = os.path.dirname(__file__)
_, path, _ = imp.find_module("_C", [lib_dir])
torch.ops.load_library(path)
try:
_register_extensions()
_HAS_OPS = True
except (ImportError, OSError):
pass
def _check_cuda_version():
if not _HAS_OPS:
return -1
import torch
_version = torch.ops.torchvision._cuda_version()
if _version != -1 and torch.version.cuda is not None:
tv_version = str(_version)
if int(tv_version) < 10000:
tv_major = int(tv_version[0])
tv_minor = int(tv_version[2])
else:
tv_major = int(tv_version[0:2])
tv_minor = int(tv_version[3])
t_version = torch.version.cuda
t_version = t_version.split('.')
t_major = int(t_version[0])
t_minor = int(t_version[1])
if t_major != tv_major or t_minor != tv_minor:
raise RuntimeError("Detected that PyTorch and torchvision were compiled with different CUDA versions. "
"PyTorch has CUDA Version={}.{} and torchvision has CUDA Version={}.{}. "
"Please reinstall the torchvision that matches your PyTorch install."
.format(t_major, t_minor, tv_major, tv_minor))
return _version
_check_cuda_version()
| true | true |
790bcb6e4ae0780250906478faa2909be47baeec | 846 | py | Python | tests/events_test.py | jjinno/pygerduty | 9624b7616a91ccfbaaff2a51bd19da9406c718b4 | [
"MIT"
] | 144 | 2015-01-30T08:49:52.000Z | 2022-02-02T15:06:05.000Z | tests/events_test.py | cugini-dbx/pygerduty | 1982aa4ccb33eb10b98b695056517f7bc5f4dff6 | [
"MIT"
] | 56 | 2015-01-02T20:50:42.000Z | 2020-06-23T18:30:22.000Z | tests/events_test.py | cugini-dbx/pygerduty | 1982aa4ccb33eb10b98b695056517f7bc5f4dff6 | [
"MIT"
] | 67 | 2015-01-13T02:34:42.000Z | 2021-04-19T22:34:08.000Z | import httpretty
import json
import textwrap
import pygerduty.events
from pygerduty.events import INTEGRATION_API_URL
from pygerduty.common import Requester
@httpretty.activate
def test_create_event():
body = textwrap.dedent("""
{
"status": "success",
"message": "Event processed",
"incident_key": "srv01/HTTP"
}
""")
httpretty.register_uri(
httpretty.POST, INTEGRATION_API_URL,
body=body, status=200)
requester = Requester()
p = pygerduty.events.Events('my_key', requester)
request_json = open('tests/fixtures/event_request.json').read()
request = json.loads(request_json)
response = p.create_event(
request['description'],
request['event_type'],
request['details'],
request['incident_key'],
)
assert response == 'srv01/HTTP'
| 22.263158 | 67 | 0.665485 | import httpretty
import json
import textwrap
import pygerduty.events
from pygerduty.events import INTEGRATION_API_URL
from pygerduty.common import Requester
@httpretty.activate
def test_create_event():
body = textwrap.dedent("""
{
"status": "success",
"message": "Event processed",
"incident_key": "srv01/HTTP"
}
""")
httpretty.register_uri(
httpretty.POST, INTEGRATION_API_URL,
body=body, status=200)
requester = Requester()
p = pygerduty.events.Events('my_key', requester)
request_json = open('tests/fixtures/event_request.json').read()
request = json.loads(request_json)
response = p.create_event(
request['description'],
request['event_type'],
request['details'],
request['incident_key'],
)
assert response == 'srv01/HTTP'
| true | true |
790bcbff1747cdc62f9caf9c4546926661711a3f | 1,209 | py | Python | reversing/pyast64++.rev/solver/solve.py | SECCON/SECCON2021_online_CTF | 628008ae2d150723352aed2c95abff41501c51f2 | [
"Apache-2.0"
] | 7 | 2022-02-07T10:15:22.000Z | 2022-02-10T07:13:07.000Z | reversing/pyast64++.rev/solver/solve.py | SECCON/SECCON2021_online_CTF | 628008ae2d150723352aed2c95abff41501c51f2 | [
"Apache-2.0"
] | null | null | null | reversing/pyast64++.rev/solver/solve.py | SECCON/SECCON2021_online_CTF | 628008ae2d150723352aed2c95abff41501c51f2 | [
"Apache-2.0"
] | null | null | null | cipher = [75, 203, 190, 126, 184, 169, 27, 74, 35, 83, 113, 65, 207, 193, 27, 137, 37, 98, 0, 68, 219, 113, 21, 180, 223, 135, 5, 129, 189, 200, 245, 100, 117, 62, 192, 101, 239, 92, 182, 136, 159, 235, 166, 90, 74, 133, 83, 78, 6, 225, 101, 103, 82, 78, 144, 205, 130, 238, 175, 245, 172, 62, 157, 176]
key = b"SECCON2021"
Sbox = [0xff - i for i in range(0x100)]
j = 0
for i in range(0x100):
j = (j + Sbox[i] + key[i % 10]) % 0x100
Sbox[i], Sbox[j] = Sbox[j], Sbox[i]
def FYinv(bits):
for i in range(63, -1, -1):
j = (i**3 % 67) % 64
bits[i], bits[j] = bits[j], bits[i]
def Pinv(data, length):
for i in range(length // 8):
bits = []
for j in range(8):
bits += [(data[i*8+j] >> k) & 1 for k in range(8)]
FYinv(bits)
for j in range(8):
c = 0
for k in range(8):
c |= bits[j*8+k] << k
data[i*8+j] = c
def Sinv(Sbox, data, length):
for i in range(length):
data[i] = Sbox.index(data[i])
for rnd in range(10):
for i in range(0x40):
cipher[i] ^= key[9 - rnd]
Pinv(cipher, 0x40)
Sinv(Sbox, cipher, 0x40)
print(cipher)
print(''.join(map(chr, cipher)))
| 31 | 303 | 0.507858 | cipher = [75, 203, 190, 126, 184, 169, 27, 74, 35, 83, 113, 65, 207, 193, 27, 137, 37, 98, 0, 68, 219, 113, 21, 180, 223, 135, 5, 129, 189, 200, 245, 100, 117, 62, 192, 101, 239, 92, 182, 136, 159, 235, 166, 90, 74, 133, 83, 78, 6, 225, 101, 103, 82, 78, 144, 205, 130, 238, 175, 245, 172, 62, 157, 176]
key = b"SECCON2021"
Sbox = [0xff - i for i in range(0x100)]
j = 0
for i in range(0x100):
j = (j + Sbox[i] + key[i % 10]) % 0x100
Sbox[i], Sbox[j] = Sbox[j], Sbox[i]
def FYinv(bits):
for i in range(63, -1, -1):
j = (i**3 % 67) % 64
bits[i], bits[j] = bits[j], bits[i]
def Pinv(data, length):
for i in range(length // 8):
bits = []
for j in range(8):
bits += [(data[i*8+j] >> k) & 1 for k in range(8)]
FYinv(bits)
for j in range(8):
c = 0
for k in range(8):
c |= bits[j*8+k] << k
data[i*8+j] = c
def Sinv(Sbox, data, length):
for i in range(length):
data[i] = Sbox.index(data[i])
for rnd in range(10):
for i in range(0x40):
cipher[i] ^= key[9 - rnd]
Pinv(cipher, 0x40)
Sinv(Sbox, cipher, 0x40)
print(cipher)
print(''.join(map(chr, cipher)))
| true | true |
790bcc558648dd4cdf9c42ece65a3798865e4af5 | 7,943 | py | Python | docs/conf.py | aryamccarthy/ANES | 29c56f8c46fd4e8b6725f329cb609f4f14a8acb0 | [
"MIT"
] | 1 | 2017-04-18T22:46:02.000Z | 2017-04-18T22:46:02.000Z | docs/conf.py | aryamccarthy/ANES | 29c56f8c46fd4e8b6725f329cb609f4f14a8acb0 | [
"MIT"
] | 1 | 2017-07-17T20:28:24.000Z | 2017-07-17T20:28:24.000Z | docs/conf.py | aryamccarthy/ANES | 29c56f8c46fd4e8b6725f329cb609f4f14a8acb0 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
#
# Political Dynamics documentation build configuration file, created by
# sphinx-quickstart.
#
# 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 os
import sys
# 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('.'))
# -- 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 = []
# 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'Political Dynamics'
# 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 = '0.1'
# The full version, including alpha/beta/rc tags.
release = '0.1'
# 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 = []
# -- 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 = 'political-dynamicsdoc'
# -- 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',
'political-dynamics.tex',
u'Political Dynamics Documentation',
u"Arya D. McCarthy", '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', 'political-dynamics', u'Political Dynamics Documentation',
[u"Arya D. McCarthy"], 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', 'political-dynamics', u'Political Dynamics Documentation',
u"Arya D. McCarthy", 'Political Dynamics',
'A differential equations perspective on American National Election Studies (ANES) over time.[D[D[D', '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'
| 32.420408 | 127 | 0.709178 |
import os
import sys
extensions = []
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'Political Dynamics'
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.1'
# The full version, including alpha/beta/rc tags.
release = '0.1'
# 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 = []
# -- 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 = 'political-dynamicsdoc'
# -- 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',
'political-dynamics.tex',
u'Political Dynamics Documentation',
u"Arya D. McCarthy", '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', 'political-dynamics', u'Political Dynamics Documentation',
[u"Arya D. McCarthy"], 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', 'political-dynamics', u'Political Dynamics Documentation',
u"Arya D. McCarthy", 'Political Dynamics',
'A differential equations perspective on American National Election Studies (ANES) over time.[D[D[D', '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'
| true | true |
790bce87491729f0ceb8329d462bd82770f80bc5 | 496 | py | Python | renzongxian/0001/0001.py | saurabh896/python-1 | f8d3aedf4c0fe6e24dfa3269ea7e642c9f7dd9b7 | [
"MIT"
] | 3,976 | 2015-01-01T15:49:39.000Z | 2022-03-31T03:47:56.000Z | renzongxian/0001/0001.py | dwh65416396/python | 1a7e3edd1cd3422cc0eaa55471a0b42e004a9a1a | [
"MIT"
] | 97 | 2015-01-11T02:59:46.000Z | 2022-03-16T14:01:56.000Z | renzongxian/0001/0001.py | dwh65416396/python | 1a7e3edd1cd3422cc0eaa55471a0b42e004a9a1a | [
"MIT"
] | 3,533 | 2015-01-01T06:19:30.000Z | 2022-03-28T13:14:54.000Z | # Source:https://github.com/Show-Me-the-Code/show-me-the-code
# Author:renzongxian
# Date:2014-11-30
# Python 3.4
"""
第 0001 题:做为 Apple Store App 独立开发者,你要搞限时促销,为你的应用生成激活码
(或者优惠券),使用 Python 如何生成 200 个激活码(或者优惠券)?
"""
import uuid
def generate_key():
key_list = []
for i in range(200):
uuid_key = uuid.uuid3(uuid.NAMESPACE_DNS, str(uuid.uuid1()))
key_list.append(str(uuid_key).replace('-', ''))
return key_list
if __name__ == '__main__':
print(generate_key())
| 19.076923 | 68 | 0.663306 |
import uuid
def generate_key():
key_list = []
for i in range(200):
uuid_key = uuid.uuid3(uuid.NAMESPACE_DNS, str(uuid.uuid1()))
key_list.append(str(uuid_key).replace('-', ''))
return key_list
if __name__ == '__main__':
print(generate_key())
| true | true |
790bd025072163898d8e1fd15588848834a0eba2 | 1,626 | py | Python | doc/gen_javadoc.py | ChillingVan/LocalHtmlSearchBox | 722f05b4efc660a8f8a6b81767493eb7a25c4d99 | [
"Apache-2.0"
] | 1 | 2019-07-13T02:33:45.000Z | 2019-07-13T02:33:45.000Z | doc/gen_javadoc.py | dxjia/LocalHtmlSearchBox | 722f05b4efc660a8f8a6b81767493eb7a25c4d99 | [
"Apache-2.0"
] | null | null | null | doc/gen_javadoc.py | dxjia/LocalHtmlSearchBox | 722f05b4efc660a8f8a6b81767493eb7a25c4d99 | [
"Apache-2.0"
] | 1 | 2019-07-13T02:33:46.000Z | 2019-07-13T02:33:46.000Z | import os
import sys
import gen_database as gendb
import json
from shutil import copyfile
def run_cmd(cmd):
cmd_pipe = os.popen(cmd)
cmd_print = cmd_pipe.read()
print(cmd_print)
if __name__ == '__main__':
print("")
root_read_dir = sys.argv[1]
if root_read_dir[-1] != r"/" or root_read_dir[-1] != "\\":
root_read_dir = root_read_dir + "/"
# Generate java doc by javadoc command
run_cmd(r"javadoc -locale en -encoding UTF-8 -charset UTF-8 -sourcepath "
+ r"../src ../src/main/java/com/chillingvan/docsearcher/Foooo.java ../src/main/java/com/chillingvan/docsearcher/foo/SubFoo.java"
+ r" -subpackages com -overview ./overview.html -d ../build/doc_java")
# copy js and css to target dir
copyfile('search.html', root_read_dir + 'search.html')
copyfile('docsearcher.css', root_read_dir + 'docsearcher.css')
copyfile('searchlib.js', root_read_dir + 'searchlib.js')
# Read the html documents under /com to generate json data to a .js
database_dir = root_read_dir
def on_read_file(path, resultArr):
if 'html' in path:
url = path[path.index(root_read_dir) + len(path):]
url = url.replace('\\', '/')
resultArr.extend(gendb.simple_read_one(path, url))
result_arr = []
gendb.read_files(root_read_dir + 'com/', on_read_file, result_arr)
final_result_arr = []
gendb.remove_same(result_arr, final_result_arr)
with open(database_dir + 'searchData.js', 'w') as fl:
fl.write("var searchData = " + json.dumps(final_result_arr))
| 36.133333 | 141 | 0.642681 | import os
import sys
import gen_database as gendb
import json
from shutil import copyfile
def run_cmd(cmd):
cmd_pipe = os.popen(cmd)
cmd_print = cmd_pipe.read()
print(cmd_print)
if __name__ == '__main__':
print("")
root_read_dir = sys.argv[1]
if root_read_dir[-1] != r"/" or root_read_dir[-1] != "\\":
root_read_dir = root_read_dir + "/"
run_cmd(r"javadoc -locale en -encoding UTF-8 -charset UTF-8 -sourcepath "
+ r"../src ../src/main/java/com/chillingvan/docsearcher/Foooo.java ../src/main/java/com/chillingvan/docsearcher/foo/SubFoo.java"
+ r" -subpackages com -overview ./overview.html -d ../build/doc_java")
copyfile('search.html', root_read_dir + 'search.html')
copyfile('docsearcher.css', root_read_dir + 'docsearcher.css')
copyfile('searchlib.js', root_read_dir + 'searchlib.js')
database_dir = root_read_dir
def on_read_file(path, resultArr):
if 'html' in path:
url = path[path.index(root_read_dir) + len(path):]
url = url.replace('\\', '/')
resultArr.extend(gendb.simple_read_one(path, url))
result_arr = []
gendb.read_files(root_read_dir + 'com/', on_read_file, result_arr)
final_result_arr = []
gendb.remove_same(result_arr, final_result_arr)
with open(database_dir + 'searchData.js', 'w') as fl:
fl.write("var searchData = " + json.dumps(final_result_arr))
| true | true |
790bd2032cd33f2ce921af7205594a5110c8e4cb | 6,952 | py | Python | node_modules/nuclide/pkg/nuclide-clang-rpc/python/outline.py | kevingatera/kgatewebapp | f0dbc50b7af2736e1f6c6f96f0a26fc7ff69db20 | [
"Unlicense"
] | 1 | 2017-08-19T08:13:28.000Z | 2017-08-19T08:13:28.000Z | node_modules/nuclide/pkg/nuclide-clang-rpc/python/outline.py | kevingatera/kgatewebapp | f0dbc50b7af2736e1f6c6f96f0a26fc7ff69db20 | [
"Unlicense"
] | null | null | null | node_modules/nuclide/pkg/nuclide-clang-rpc/python/outline.py | kevingatera/kgatewebapp | f0dbc50b7af2736e1f6c6f96f0a26fc7ff69db20 | [
"Unlicense"
] | null | null | null | #!/usr/bin/env python
# Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the LICENSE file in
# the root directory of this source tree.
from __future__ import print_function
from clang.cindex import Cursor, CursorKind, TokenKind
from utils import range_dict_relative
import ctypes
import itertools
import re
# Function/method cursor kinds.
FUNCTION_KINDS = set([
'FUNCTION_DECL',
'FUNCTION_TEMPLATE',
'CXX_METHOD',
'CONSTRUCTOR',
'DESTRUCTOR',
'OBJC_INSTANCE_METHOD_DECL',
'OBJC_CLASS_METHOD_DECL',
])
# Class-like cursors.
CLASS_KINDS = set([
'STRUCT_DECL',
'UNION_DECL',
'CLASS_DECL',
'ENUM_DECL',
'OBJC_INTERFACE_DECL',
'OBJC_CATEGORY_DECL',
'OBJC_PROTOCOL_DECL',
'OBJC_IMPLEMENTATION_DECL',
'OBJC_CATEGORY_IMPL_DECL',
'CLASS_TEMPLATE',
'CLASS_TEMPLATE_PARTIAL_SPECIALIZATION',
'NAMESPACE',
])
# (Possibly external) members of CLASS_KINDS.
MEMBER_KINDS = set([
'CXX_METHOD',
'CONSTRUCTOR',
'DESTRUCTOR',
'FIELD_DECL',
'VAR_DECL',
'ENUM_CONSTANT_DECL',
])
# Variables and fields.
VAR_KINDS = set([
'OBJC_IVAR_DECL',
'FIELD_DECL',
'VAR_DECL',
])
# Capture the ubiquitous GTest-style TEST/TEST_F macros.
GTEST_MACROS = set(['TEST', 'TEST_F'])
MACRO_INSTANTIATION = 'MACRO_INSTANTIATION'
OTHER_KINDS = set([
MACRO_INSTANTIATION,
])
# Record any of the cursor types listed above.
ALL_KINDS = FUNCTION_KINDS | CLASS_KINDS | MEMBER_KINDS | VAR_KINDS | OTHER_KINDS
# People like adding a '-' by convention, but strip that out.
PRAGMA_MARK_REGEX = re.compile(
'^[ \t]*#[ \t]*pragma[ \t]+mark[ \t]+(?:-[ \t]*)?(.+)$', re.MULTILINE)
def visit_cursor(libclang, cursor):
try:
kind = cursor.kind.name
except:
# Some cursor kinds aren't supported by the Python binding.
return None
if kind not in ALL_KINDS:
return None
# Skip symbols from other files.
if not libclang.clang_Location_isFromMainFile(cursor.location):
return None
# Names of function parameters.
params = None
# Names of template parameters.
tparams = None
children = None
name = cursor.spelling
# Display types for variables and typedefs.
cursor_type = cursor.type.spelling if kind in VAR_KINDS else None
if kind in FUNCTION_KINDS:
# We can't use displayname as it also includes the arguments.
params = []
tparams = []
for child in cursor.get_children():
if child.kind == CursorKind.PARM_DECL:
# Use the param name, but fall back to the raw type if unnamed.
params.append(child.spelling or child.type.spelling)
elif child.kind == CursorKind.TEMPLATE_TYPE_PARAMETER:
tparams.append(child.spelling)
# TODO(hansonw): non-type and "template template" params?
if kind in MEMBER_KINDS:
# Name should be fully qualified if outside the parent.
if cursor.semantic_parent != cursor.lexical_parent:
name = cursor.semantic_parent.spelling + '::' + name
elif kind in CLASS_KINDS:
# Include template information.
name = cursor.displayname
children = []
for child in cursor.get_children():
child_outline = visit_cursor(libclang, child)
if child_outline is not None:
children.append(child_outline)
if kind == MACRO_INSTANTIATION:
params = []
if name in GTEST_MACROS:
# Should look like TEST(id, id).
tokens = list(itertools.islice(cursor.get_tokens(), 1, 6))
if len(tokens) == 5 and (
tokens[0].kind == TokenKind.PUNCTUATION and
tokens[1].kind == TokenKind.IDENTIFIER and
tokens[2].kind == TokenKind.PUNCTUATION and
tokens[3].kind == TokenKind.IDENTIFIER and
tokens[4].kind == TokenKind.PUNCTUATION
):
params = [tokens[1].spelling, tokens[3].spelling]
else:
return None
else:
# TODO(hansonw): Handle other special macros like DEFINE_ params.
return None
ret = {
'name': name,
'cursor_kind': kind,
'cursor_type': cursor_type,
'extent': range_dict_relative(cursor.extent),
'params': params,
'tparams': tparams,
'children': children,
}
return {k: v for k, v in ret.items() if v is not None}
# Scan through the outline tree and insert pragma marks as we pass by them.
def insert_pragma_marks(marks, outline_tree, tree_end=None):
new_result = []
for node in outline_tree:
while len(marks) > 0:
if marks[-1]['extent']['start']['row'] > node['extent']['start']['row']:
break
new_result.append(marks.pop())
children = node.get('children')
if children:
children[:] = insert_pragma_marks(marks, children, node['extent']['end']['row'])
new_result.append(node)
# Consume all remaining marks included in this subtree.
while len(marks) > 0:
if tree_end is not None and marks[-1]['extent']['start']['row'] > tree_end:
break
new_result.append(marks.pop())
return new_result
def get_outline(libclang, translation_unit, contents):
root_cursor = translation_unit.cursor
# This is the same as Cursor.get_children minus an assert in visitor().
# This results in a ~2x speedup!
callback_type = ctypes.CFUNCTYPE(ctypes.c_int, Cursor, Cursor, ctypes.py_object)
def visitor(child, parent, result):
child._tu = translation_unit
child_outline = visit_cursor(libclang, child)
if child_outline is not None:
result.append(child_outline)
return 1 # continue
result = []
libclang.clang_visitChildren(root_cursor, callback_type(visitor), result)
# Look for pragma marks. These are not detectable in the AST.
line = 0
lastpos = 0
pragma_marks = []
for mark in PRAGMA_MARK_REGEX.finditer(contents):
while lastpos < mark.start():
if contents[lastpos] == '\n':
line += 1
lastpos += 1
pragma_marks.append({
'name': mark.group(1),
'cursor_kind': 'PRAGMA_MARK',
'extent': {
'start': {'row': line, 'column': 0},
'end': {'row': line + 1, 'column': 0},
},
})
# Top-level macro instantiations appear out of order.
result = sorted(result, key=lambda x: (
x['extent']['start']['row'],
x['extent']['start']['column'],
x['extent']['end']['row'],
x['extent']['end']['column'],
))
# Convert into a stack for efficient removal.
pragma_marks.reverse()
return insert_pragma_marks(pragma_marks, result)
| 31.035714 | 92 | 0.621116 |
from __future__ import print_function
from clang.cindex import Cursor, CursorKind, TokenKind
from utils import range_dict_relative
import ctypes
import itertools
import re
FUNCTION_KINDS = set([
'FUNCTION_DECL',
'FUNCTION_TEMPLATE',
'CXX_METHOD',
'CONSTRUCTOR',
'DESTRUCTOR',
'OBJC_INSTANCE_METHOD_DECL',
'OBJC_CLASS_METHOD_DECL',
])
CLASS_KINDS = set([
'STRUCT_DECL',
'UNION_DECL',
'CLASS_DECL',
'ENUM_DECL',
'OBJC_INTERFACE_DECL',
'OBJC_CATEGORY_DECL',
'OBJC_PROTOCOL_DECL',
'OBJC_IMPLEMENTATION_DECL',
'OBJC_CATEGORY_IMPL_DECL',
'CLASS_TEMPLATE',
'CLASS_TEMPLATE_PARTIAL_SPECIALIZATION',
'NAMESPACE',
])
MEMBER_KINDS = set([
'CXX_METHOD',
'CONSTRUCTOR',
'DESTRUCTOR',
'FIELD_DECL',
'VAR_DECL',
'ENUM_CONSTANT_DECL',
])
VAR_KINDS = set([
'OBJC_IVAR_DECL',
'FIELD_DECL',
'VAR_DECL',
])
GTEST_MACROS = set(['TEST', 'TEST_F'])
MACRO_INSTANTIATION = 'MACRO_INSTANTIATION'
OTHER_KINDS = set([
MACRO_INSTANTIATION,
])
ALL_KINDS = FUNCTION_KINDS | CLASS_KINDS | MEMBER_KINDS | VAR_KINDS | OTHER_KINDS
PRAGMA_MARK_REGEX = re.compile(
'^[ \t]*#[ \t]*pragma[ \t]+mark[ \t]+(?:-[ \t]*)?(.+)$', re.MULTILINE)
def visit_cursor(libclang, cursor):
try:
kind = cursor.kind.name
except:
return None
if kind not in ALL_KINDS:
return None
# Skip symbols from other files.
if not libclang.clang_Location_isFromMainFile(cursor.location):
return None
# Names of function parameters.
params = None
# Names of template parameters.
tparams = None
children = None
name = cursor.spelling
# Display types for variables and typedefs.
cursor_type = cursor.type.spelling if kind in VAR_KINDS else None
if kind in FUNCTION_KINDS:
# We can't use displayname as it also includes the arguments.
params = []
tparams = []
for child in cursor.get_children():
if child.kind == CursorKind.PARM_DECL:
params.append(child.spelling or child.type.spelling)
elif child.kind == CursorKind.TEMPLATE_TYPE_PARAMETER:
tparams.append(child.spelling)
if kind in MEMBER_KINDS:
if cursor.semantic_parent != cursor.lexical_parent:
name = cursor.semantic_parent.spelling + '::' + name
elif kind in CLASS_KINDS:
name = cursor.displayname
children = []
for child in cursor.get_children():
child_outline = visit_cursor(libclang, child)
if child_outline is not None:
children.append(child_outline)
if kind == MACRO_INSTANTIATION:
params = []
if name in GTEST_MACROS:
tokens = list(itertools.islice(cursor.get_tokens(), 1, 6))
if len(tokens) == 5 and (
tokens[0].kind == TokenKind.PUNCTUATION and
tokens[1].kind == TokenKind.IDENTIFIER and
tokens[2].kind == TokenKind.PUNCTUATION and
tokens[3].kind == TokenKind.IDENTIFIER and
tokens[4].kind == TokenKind.PUNCTUATION
):
params = [tokens[1].spelling, tokens[3].spelling]
else:
return None
else:
return None
ret = {
'name': name,
'cursor_kind': kind,
'cursor_type': cursor_type,
'extent': range_dict_relative(cursor.extent),
'params': params,
'tparams': tparams,
'children': children,
}
return {k: v for k, v in ret.items() if v is not None}
def insert_pragma_marks(marks, outline_tree, tree_end=None):
new_result = []
for node in outline_tree:
while len(marks) > 0:
if marks[-1]['extent']['start']['row'] > node['extent']['start']['row']:
break
new_result.append(marks.pop())
children = node.get('children')
if children:
children[:] = insert_pragma_marks(marks, children, node['extent']['end']['row'])
new_result.append(node)
while len(marks) > 0:
if tree_end is not None and marks[-1]['extent']['start']['row'] > tree_end:
break
new_result.append(marks.pop())
return new_result
def get_outline(libclang, translation_unit, contents):
root_cursor = translation_unit.cursor
callback_type = ctypes.CFUNCTYPE(ctypes.c_int, Cursor, Cursor, ctypes.py_object)
def visitor(child, parent, result):
child._tu = translation_unit
child_outline = visit_cursor(libclang, child)
if child_outline is not None:
result.append(child_outline)
return 1
result = []
libclang.clang_visitChildren(root_cursor, callback_type(visitor), result)
line = 0
lastpos = 0
pragma_marks = []
for mark in PRAGMA_MARK_REGEX.finditer(contents):
while lastpos < mark.start():
if contents[lastpos] == '\n':
line += 1
lastpos += 1
pragma_marks.append({
'name': mark.group(1),
'cursor_kind': 'PRAGMA_MARK',
'extent': {
'start': {'row': line, 'column': 0},
'end': {'row': line + 1, 'column': 0},
},
})
result = sorted(result, key=lambda x: (
x['extent']['start']['row'],
x['extent']['start']['column'],
x['extent']['end']['row'],
x['extent']['end']['column'],
))
pragma_marks.reverse()
return insert_pragma_marks(pragma_marks, result)
| true | true |
790bd4359eb7e0a3ca1113f4a548318acb5650c8 | 1,263 | py | Python | tests/test_set_random_seed.py | iblamedom/kuenstliche-intelligenz | 382ba611cb5f2ac108243d535be1d457023cc50c | [
"MIT"
] | 3 | 2020-08-28T21:55:42.000Z | 2022-03-28T10:29:19.000Z | tests/test_set_random_seed.py | xduan7/dl-project-template | 733ecdcfcb561aa1b39854b1b3632c0fda07f841 | [
"MIT"
] | 1 | 2022-02-27T17:06:21.000Z | 2022-02-27T17:06:21.000Z | tests/test_set_random_seed.py | xduan7/dl-project-template | 733ecdcfcb561aa1b39854b1b3632c0fda07f841 | [
"MIT"
] | null | null | null | import random
import unittest
from typing import Tuple
import torch
import numpy as np
from src.utilities import set_random_seed
_RANDOM_SEED: int = random.randint(0, 100)
_TEST_ARRAY_SIZE: Tuple[int, int] = (2, 2)
_TEST_TENSOR_SIZE: Tuple[int, int] = (2, 2)
def _set_random_seed():
set_random_seed(
random_seed=_RANDOM_SEED,
)
class TestSetRandomSeed(unittest.TestCase):
"""Unit test class for ``set_random_seed`` function.
The test checks the random seed function for Python random,
NumPy, and PyTorch by asserting the first random number, array,
or tensor is always the same after seeding.
"""
def test_random(self):
_set_random_seed()
_random = random.random()
_set_random_seed()
assert _random == random.random()
def test_numpy(self):
_set_random_seed()
_array = np.random.random(size=_TEST_ARRAY_SIZE)
_set_random_seed()
assert (_array == np.random.random(size=_TEST_ARRAY_SIZE)).all()
def test_torch(self):
_set_random_seed()
_tensor = torch.rand(size=_TEST_TENSOR_SIZE)
_set_random_seed()
assert (_tensor == torch.rand(size=_TEST_TENSOR_SIZE)).all()
if __name__ == '__main__':
unittest.main()
| 24.764706 | 72 | 0.684086 | import random
import unittest
from typing import Tuple
import torch
import numpy as np
from src.utilities import set_random_seed
_RANDOM_SEED: int = random.randint(0, 100)
_TEST_ARRAY_SIZE: Tuple[int, int] = (2, 2)
_TEST_TENSOR_SIZE: Tuple[int, int] = (2, 2)
def _set_random_seed():
set_random_seed(
random_seed=_RANDOM_SEED,
)
class TestSetRandomSeed(unittest.TestCase):
def test_random(self):
_set_random_seed()
_random = random.random()
_set_random_seed()
assert _random == random.random()
def test_numpy(self):
_set_random_seed()
_array = np.random.random(size=_TEST_ARRAY_SIZE)
_set_random_seed()
assert (_array == np.random.random(size=_TEST_ARRAY_SIZE)).all()
def test_torch(self):
_set_random_seed()
_tensor = torch.rand(size=_TEST_TENSOR_SIZE)
_set_random_seed()
assert (_tensor == torch.rand(size=_TEST_TENSOR_SIZE)).all()
if __name__ == '__main__':
unittest.main()
| true | true |
790bd481fc247599756784d878b515a933d57c7c | 416 | py | Python | Book/api/permissions.py | imran110219/Book_Review_App | 48655da14420af64a2b5460f1f635cd61ae30779 | [
"MIT"
] | 2 | 2019-05-24T21:08:54.000Z | 2021-12-29T11:29:45.000Z | Book/api/permissions.py | imran110219/Book_Review_App | 48655da14420af64a2b5460f1f635cd61ae30779 | [
"MIT"
] | 8 | 2019-04-17T05:46:40.000Z | 2022-03-11T23:17:20.000Z | Book/api/permissions.py | imran110219/Book_Review_App | 48655da14420af64a2b5460f1f635cd61ae30779 | [
"MIT"
] | 2 | 2018-02-04T10:16:40.000Z | 2019-06-24T19:43:01.000Z | from rest_framework.permissions import BasePermission, SAFE_METHODS
class IsOwnerOrReadOnly(BasePermission):
message = 'You must be the owner of this object.'
def has_object_permission(self, request, view, obj):
# member = Membership.objects.get(user=user.request)
# member.is_active
if request.method in SAFE_METHODS:
return True
return obj.user == request.user | 37.818182 | 67 | 0.706731 | from rest_framework.permissions import BasePermission, SAFE_METHODS
class IsOwnerOrReadOnly(BasePermission):
message = 'You must be the owner of this object.'
def has_object_permission(self, request, view, obj):
if request.method in SAFE_METHODS:
return True
return obj.user == request.user | true | true |
790bd48c4149fb209bc53ba278f357aee07eb98d | 23,669 | py | Python | sdk/python/pulumi_kubernetes/storage/v1beta1/CSIStorageCapacity.py | csssuf/pulumi-kubernetes | 8d007166d0e8968fcabaeecd0cee13f9c08d97f1 | [
"Apache-2.0"
] | null | null | null | sdk/python/pulumi_kubernetes/storage/v1beta1/CSIStorageCapacity.py | csssuf/pulumi-kubernetes | 8d007166d0e8968fcabaeecd0cee13f9c08d97f1 | [
"Apache-2.0"
] | null | null | null | sdk/python/pulumi_kubernetes/storage/v1beta1/CSIStorageCapacity.py | csssuf/pulumi-kubernetes | 8d007166d0e8968fcabaeecd0cee13f9c08d97f1 | [
"Apache-2.0"
] | null | null | null | # coding=utf-8
# *** WARNING: this file was generated by pulumigen. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
from ... import meta as _meta
__all__ = ['CSIStorageCapacityArgs', 'CSIStorageCapacity']
@pulumi.input_type
class CSIStorageCapacityArgs:
def __init__(__self__, *,
storage_class_name: pulumi.Input[str],
api_version: Optional[pulumi.Input[str]] = None,
capacity: Optional[pulumi.Input[str]] = None,
kind: Optional[pulumi.Input[str]] = None,
maximum_volume_size: Optional[pulumi.Input[str]] = None,
metadata: Optional[pulumi.Input['_meta.v1.ObjectMetaArgs']] = None,
node_topology: Optional[pulumi.Input['_meta.v1.LabelSelectorArgs']] = None):
"""
The set of arguments for constructing a CSIStorageCapacity resource.
:param pulumi.Input[str] storage_class_name: The name of the StorageClass that the reported capacity applies to. It must meet the same requirements as the name of a StorageClass object (non-empty, DNS subdomain). If that object no longer exists, the CSIStorageCapacity object is obsolete and should be removed by its creator. This field is immutable.
:param pulumi.Input[str] api_version: APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
:param pulumi.Input[str] capacity: Capacity is the value reported by the CSI driver in its GetCapacityResponse for a GetCapacityRequest with topology and parameters that match the previous fields.
The semantic is currently (CSI spec 1.2) defined as: The available capacity, in bytes, of the storage that can be used to provision volumes. If not set, that information is currently unavailable and treated like zero capacity.
:param pulumi.Input[str] kind: Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
:param pulumi.Input[str] maximum_volume_size: MaximumVolumeSize is the value reported by the CSI driver in its GetCapacityResponse for a GetCapacityRequest with topology and parameters that match the previous fields.
This is defined since CSI spec 1.4.0 as the largest size that may be used in a CreateVolumeRequest.capacity_range.required_bytes field to create a volume with the same parameters as those in GetCapacityRequest. The corresponding value in the Kubernetes API is ResourceRequirements.Requests in a volume claim.
:param pulumi.Input['_meta.v1.ObjectMetaArgs'] metadata: Standard object's metadata. The name has no particular meaning. It must be be a DNS subdomain (dots allowed, 253 characters). To ensure that there are no conflicts with other CSI drivers on the cluster, the recommendation is to use csisc-<uuid>, a generated name, or a reverse-domain name which ends with the unique CSI driver name.
Objects are namespaced.
More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
:param pulumi.Input['_meta.v1.LabelSelectorArgs'] node_topology: NodeTopology defines which nodes have access to the storage for which capacity was reported. If not set, the storage is not accessible from any node in the cluster. If empty, the storage is accessible from all nodes. This field is immutable.
"""
pulumi.set(__self__, "storage_class_name", storage_class_name)
if api_version is not None:
pulumi.set(__self__, "api_version", 'storage.k8s.io/v1beta1')
if capacity is not None:
pulumi.set(__self__, "capacity", capacity)
if kind is not None:
pulumi.set(__self__, "kind", 'CSIStorageCapacity')
if maximum_volume_size is not None:
pulumi.set(__self__, "maximum_volume_size", maximum_volume_size)
if metadata is not None:
pulumi.set(__self__, "metadata", metadata)
if node_topology is not None:
pulumi.set(__self__, "node_topology", node_topology)
@property
@pulumi.getter(name="storageClassName")
def storage_class_name(self) -> pulumi.Input[str]:
"""
The name of the StorageClass that the reported capacity applies to. It must meet the same requirements as the name of a StorageClass object (non-empty, DNS subdomain). If that object no longer exists, the CSIStorageCapacity object is obsolete and should be removed by its creator. This field is immutable.
"""
return pulumi.get(self, "storage_class_name")
@storage_class_name.setter
def storage_class_name(self, value: pulumi.Input[str]):
pulumi.set(self, "storage_class_name", value)
@property
@pulumi.getter(name="apiVersion")
def api_version(self) -> Optional[pulumi.Input[str]]:
"""
APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
"""
return pulumi.get(self, "api_version")
@api_version.setter
def api_version(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "api_version", value)
@property
@pulumi.getter
def capacity(self) -> Optional[pulumi.Input[str]]:
"""
Capacity is the value reported by the CSI driver in its GetCapacityResponse for a GetCapacityRequest with topology and parameters that match the previous fields.
The semantic is currently (CSI spec 1.2) defined as: The available capacity, in bytes, of the storage that can be used to provision volumes. If not set, that information is currently unavailable and treated like zero capacity.
"""
return pulumi.get(self, "capacity")
@capacity.setter
def capacity(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "capacity", value)
@property
@pulumi.getter
def kind(self) -> Optional[pulumi.Input[str]]:
"""
Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
"""
return pulumi.get(self, "kind")
@kind.setter
def kind(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "kind", value)
@property
@pulumi.getter(name="maximumVolumeSize")
def maximum_volume_size(self) -> Optional[pulumi.Input[str]]:
"""
MaximumVolumeSize is the value reported by the CSI driver in its GetCapacityResponse for a GetCapacityRequest with topology and parameters that match the previous fields.
This is defined since CSI spec 1.4.0 as the largest size that may be used in a CreateVolumeRequest.capacity_range.required_bytes field to create a volume with the same parameters as those in GetCapacityRequest. The corresponding value in the Kubernetes API is ResourceRequirements.Requests in a volume claim.
"""
return pulumi.get(self, "maximum_volume_size")
@maximum_volume_size.setter
def maximum_volume_size(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "maximum_volume_size", value)
@property
@pulumi.getter
def metadata(self) -> Optional[pulumi.Input['_meta.v1.ObjectMetaArgs']]:
"""
Standard object's metadata. The name has no particular meaning. It must be be a DNS subdomain (dots allowed, 253 characters). To ensure that there are no conflicts with other CSI drivers on the cluster, the recommendation is to use csisc-<uuid>, a generated name, or a reverse-domain name which ends with the unique CSI driver name.
Objects are namespaced.
More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
"""
return pulumi.get(self, "metadata")
@metadata.setter
def metadata(self, value: Optional[pulumi.Input['_meta.v1.ObjectMetaArgs']]):
pulumi.set(self, "metadata", value)
@property
@pulumi.getter(name="nodeTopology")
def node_topology(self) -> Optional[pulumi.Input['_meta.v1.LabelSelectorArgs']]:
"""
NodeTopology defines which nodes have access to the storage for which capacity was reported. If not set, the storage is not accessible from any node in the cluster. If empty, the storage is accessible from all nodes. This field is immutable.
"""
return pulumi.get(self, "node_topology")
@node_topology.setter
def node_topology(self, value: Optional[pulumi.Input['_meta.v1.LabelSelectorArgs']]):
pulumi.set(self, "node_topology", value)
class CSIStorageCapacity(pulumi.CustomResource):
@overload
def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
api_version: Optional[pulumi.Input[str]] = None,
capacity: Optional[pulumi.Input[str]] = None,
kind: Optional[pulumi.Input[str]] = None,
maximum_volume_size: Optional[pulumi.Input[str]] = None,
metadata: Optional[pulumi.Input[pulumi.InputType['_meta.v1.ObjectMetaArgs']]] = None,
node_topology: Optional[pulumi.Input[pulumi.InputType['_meta.v1.LabelSelectorArgs']]] = None,
storage_class_name: Optional[pulumi.Input[str]] = None,
__props__=None):
"""
CSIStorageCapacity stores the result of one CSI GetCapacity call. For a given StorageClass, this describes the available capacity in a particular topology segment. This can be used when considering where to instantiate new PersistentVolumes.
For example this can express things like: - StorageClass "standard" has "1234 GiB" available in "topology.kubernetes.io/zone=us-east1" - StorageClass "localssd" has "10 GiB" available in "kubernetes.io/hostname=knode-abc123"
The following three cases all imply that no capacity is available for a certain combination: - no object exists with suitable topology and storage class name - such an object exists, but the capacity is unset - such an object exists, but the capacity is zero
The producer of these objects can decide which approach is more suitable.
They are consumed by the kube-scheduler if the CSIStorageCapacity beta feature gate is enabled there and a CSI driver opts into capacity-aware scheduling with CSIDriver.StorageCapacity.
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[str] api_version: APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
:param pulumi.Input[str] capacity: Capacity is the value reported by the CSI driver in its GetCapacityResponse for a GetCapacityRequest with topology and parameters that match the previous fields.
The semantic is currently (CSI spec 1.2) defined as: The available capacity, in bytes, of the storage that can be used to provision volumes. If not set, that information is currently unavailable and treated like zero capacity.
:param pulumi.Input[str] kind: Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
:param pulumi.Input[str] maximum_volume_size: MaximumVolumeSize is the value reported by the CSI driver in its GetCapacityResponse for a GetCapacityRequest with topology and parameters that match the previous fields.
This is defined since CSI spec 1.4.0 as the largest size that may be used in a CreateVolumeRequest.capacity_range.required_bytes field to create a volume with the same parameters as those in GetCapacityRequest. The corresponding value in the Kubernetes API is ResourceRequirements.Requests in a volume claim.
:param pulumi.Input[pulumi.InputType['_meta.v1.ObjectMetaArgs']] metadata: Standard object's metadata. The name has no particular meaning. It must be be a DNS subdomain (dots allowed, 253 characters). To ensure that there are no conflicts with other CSI drivers on the cluster, the recommendation is to use csisc-<uuid>, a generated name, or a reverse-domain name which ends with the unique CSI driver name.
Objects are namespaced.
More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
:param pulumi.Input[pulumi.InputType['_meta.v1.LabelSelectorArgs']] node_topology: NodeTopology defines which nodes have access to the storage for which capacity was reported. If not set, the storage is not accessible from any node in the cluster. If empty, the storage is accessible from all nodes. This field is immutable.
:param pulumi.Input[str] storage_class_name: The name of the StorageClass that the reported capacity applies to. It must meet the same requirements as the name of a StorageClass object (non-empty, DNS subdomain). If that object no longer exists, the CSIStorageCapacity object is obsolete and should be removed by its creator. This field is immutable.
"""
...
@overload
def __init__(__self__,
resource_name: str,
args: CSIStorageCapacityArgs,
opts: Optional[pulumi.ResourceOptions] = None):
"""
CSIStorageCapacity stores the result of one CSI GetCapacity call. For a given StorageClass, this describes the available capacity in a particular topology segment. This can be used when considering where to instantiate new PersistentVolumes.
For example this can express things like: - StorageClass "standard" has "1234 GiB" available in "topology.kubernetes.io/zone=us-east1" - StorageClass "localssd" has "10 GiB" available in "kubernetes.io/hostname=knode-abc123"
The following three cases all imply that no capacity is available for a certain combination: - no object exists with suitable topology and storage class name - such an object exists, but the capacity is unset - such an object exists, but the capacity is zero
The producer of these objects can decide which approach is more suitable.
They are consumed by the kube-scheduler if the CSIStorageCapacity beta feature gate is enabled there and a CSI driver opts into capacity-aware scheduling with CSIDriver.StorageCapacity.
:param str resource_name: The name of the resource.
:param CSIStorageCapacityArgs args: The arguments to use to populate this resource's properties.
:param pulumi.ResourceOptions opts: Options for the resource.
"""
...
def __init__(__self__, resource_name: str, *args, **kwargs):
resource_args, opts = _utilities.get_resource_args_opts(CSIStorageCapacityArgs, pulumi.ResourceOptions, *args, **kwargs)
if resource_args is not None:
__self__._internal_init(resource_name, opts, **resource_args.__dict__)
else:
__self__._internal_init(resource_name, *args, **kwargs)
def _internal_init(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
api_version: Optional[pulumi.Input[str]] = None,
capacity: Optional[pulumi.Input[str]] = None,
kind: Optional[pulumi.Input[str]] = None,
maximum_volume_size: Optional[pulumi.Input[str]] = None,
metadata: Optional[pulumi.Input[pulumi.InputType['_meta.v1.ObjectMetaArgs']]] = None,
node_topology: Optional[pulumi.Input[pulumi.InputType['_meta.v1.LabelSelectorArgs']]] = None,
storage_class_name: Optional[pulumi.Input[str]] = None,
__props__=None):
if opts is None:
opts = pulumi.ResourceOptions()
if not isinstance(opts, pulumi.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
if opts.version is None:
opts.version = _utilities.get_version()
if opts.id is None:
if __props__ is not None:
raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')
__props__ = CSIStorageCapacityArgs.__new__(CSIStorageCapacityArgs)
__props__.__dict__["api_version"] = 'storage.k8s.io/v1beta1'
__props__.__dict__["capacity"] = capacity
__props__.__dict__["kind"] = 'CSIStorageCapacity'
__props__.__dict__["maximum_volume_size"] = maximum_volume_size
__props__.__dict__["metadata"] = metadata
__props__.__dict__["node_topology"] = node_topology
if storage_class_name is None and not opts.urn:
raise TypeError("Missing required property 'storage_class_name'")
__props__.__dict__["storage_class_name"] = storage_class_name
alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_="kubernetes:storage.k8s.io/v1alpha1:CSIStorageCapacity")])
opts = pulumi.ResourceOptions.merge(opts, alias_opts)
super(CSIStorageCapacity, __self__).__init__(
'kubernetes:storage.k8s.io/v1beta1:CSIStorageCapacity',
resource_name,
__props__,
opts)
@staticmethod
def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None) -> 'CSIStorageCapacity':
"""
Get an existing CSIStorageCapacity resource's state with the given name, id, and optional extra
properties used to qualify the lookup.
:param str resource_name: The unique name of the resulting resource.
:param pulumi.Input[str] id: The unique provider ID of the resource to lookup.
:param pulumi.ResourceOptions opts: Options for the resource.
"""
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = CSIStorageCapacityArgs.__new__(CSIStorageCapacityArgs)
__props__.__dict__["api_version"] = None
__props__.__dict__["capacity"] = None
__props__.__dict__["kind"] = None
__props__.__dict__["maximum_volume_size"] = None
__props__.__dict__["metadata"] = None
__props__.__dict__["node_topology"] = None
__props__.__dict__["storage_class_name"] = None
return CSIStorageCapacity(resource_name, opts=opts, __props__=__props__)
@property
@pulumi.getter(name="apiVersion")
def api_version(self) -> pulumi.Output[Optional[str]]:
"""
APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
"""
return pulumi.get(self, "api_version")
@property
@pulumi.getter
def capacity(self) -> pulumi.Output[Optional[str]]:
"""
Capacity is the value reported by the CSI driver in its GetCapacityResponse for a GetCapacityRequest with topology and parameters that match the previous fields.
The semantic is currently (CSI spec 1.2) defined as: The available capacity, in bytes, of the storage that can be used to provision volumes. If not set, that information is currently unavailable and treated like zero capacity.
"""
return pulumi.get(self, "capacity")
@property
@pulumi.getter
def kind(self) -> pulumi.Output[Optional[str]]:
"""
Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
"""
return pulumi.get(self, "kind")
@property
@pulumi.getter(name="maximumVolumeSize")
def maximum_volume_size(self) -> pulumi.Output[Optional[str]]:
"""
MaximumVolumeSize is the value reported by the CSI driver in its GetCapacityResponse for a GetCapacityRequest with topology and parameters that match the previous fields.
This is defined since CSI spec 1.4.0 as the largest size that may be used in a CreateVolumeRequest.capacity_range.required_bytes field to create a volume with the same parameters as those in GetCapacityRequest. The corresponding value in the Kubernetes API is ResourceRequirements.Requests in a volume claim.
"""
return pulumi.get(self, "maximum_volume_size")
@property
@pulumi.getter
def metadata(self) -> pulumi.Output[Optional['_meta.v1.outputs.ObjectMeta']]:
"""
Standard object's metadata. The name has no particular meaning. It must be be a DNS subdomain (dots allowed, 253 characters). To ensure that there are no conflicts with other CSI drivers on the cluster, the recommendation is to use csisc-<uuid>, a generated name, or a reverse-domain name which ends with the unique CSI driver name.
Objects are namespaced.
More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
"""
return pulumi.get(self, "metadata")
@property
@pulumi.getter(name="nodeTopology")
def node_topology(self) -> pulumi.Output[Optional['_meta.v1.outputs.LabelSelector']]:
"""
NodeTopology defines which nodes have access to the storage for which capacity was reported. If not set, the storage is not accessible from any node in the cluster. If empty, the storage is accessible from all nodes. This field is immutable.
"""
return pulumi.get(self, "node_topology")
@property
@pulumi.getter(name="storageClassName")
def storage_class_name(self) -> pulumi.Output[str]:
"""
The name of the StorageClass that the reported capacity applies to. It must meet the same requirements as the name of a StorageClass object (non-empty, DNS subdomain). If that object no longer exists, the CSIStorageCapacity object is obsolete and should be removed by its creator. This field is immutable.
"""
return pulumi.get(self, "storage_class_name")
| 68.014368 | 415 | 0.713634 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
from ... import meta as _meta
__all__ = ['CSIStorageCapacityArgs', 'CSIStorageCapacity']
@pulumi.input_type
class CSIStorageCapacityArgs:
def __init__(__self__, *,
storage_class_name: pulumi.Input[str],
api_version: Optional[pulumi.Input[str]] = None,
capacity: Optional[pulumi.Input[str]] = None,
kind: Optional[pulumi.Input[str]] = None,
maximum_volume_size: Optional[pulumi.Input[str]] = None,
metadata: Optional[pulumi.Input['_meta.v1.ObjectMetaArgs']] = None,
node_topology: Optional[pulumi.Input['_meta.v1.LabelSelectorArgs']] = None):
pulumi.set(__self__, "storage_class_name", storage_class_name)
if api_version is not None:
pulumi.set(__self__, "api_version", 'storage.k8s.io/v1beta1')
if capacity is not None:
pulumi.set(__self__, "capacity", capacity)
if kind is not None:
pulumi.set(__self__, "kind", 'CSIStorageCapacity')
if maximum_volume_size is not None:
pulumi.set(__self__, "maximum_volume_size", maximum_volume_size)
if metadata is not None:
pulumi.set(__self__, "metadata", metadata)
if node_topology is not None:
pulumi.set(__self__, "node_topology", node_topology)
@property
@pulumi.getter(name="storageClassName")
def storage_class_name(self) -> pulumi.Input[str]:
return pulumi.get(self, "storage_class_name")
@storage_class_name.setter
def storage_class_name(self, value: pulumi.Input[str]):
pulumi.set(self, "storage_class_name", value)
@property
@pulumi.getter(name="apiVersion")
def api_version(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "api_version")
@api_version.setter
def api_version(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "api_version", value)
@property
@pulumi.getter
def capacity(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "capacity")
@capacity.setter
def capacity(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "capacity", value)
@property
@pulumi.getter
def kind(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "kind")
@kind.setter
def kind(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "kind", value)
@property
@pulumi.getter(name="maximumVolumeSize")
def maximum_volume_size(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "maximum_volume_size")
@maximum_volume_size.setter
def maximum_volume_size(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "maximum_volume_size", value)
@property
@pulumi.getter
def metadata(self) -> Optional[pulumi.Input['_meta.v1.ObjectMetaArgs']]:
return pulumi.get(self, "metadata")
@metadata.setter
def metadata(self, value: Optional[pulumi.Input['_meta.v1.ObjectMetaArgs']]):
pulumi.set(self, "metadata", value)
@property
@pulumi.getter(name="nodeTopology")
def node_topology(self) -> Optional[pulumi.Input['_meta.v1.LabelSelectorArgs']]:
return pulumi.get(self, "node_topology")
@node_topology.setter
def node_topology(self, value: Optional[pulumi.Input['_meta.v1.LabelSelectorArgs']]):
pulumi.set(self, "node_topology", value)
class CSIStorageCapacity(pulumi.CustomResource):
@overload
def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
api_version: Optional[pulumi.Input[str]] = None,
capacity: Optional[pulumi.Input[str]] = None,
kind: Optional[pulumi.Input[str]] = None,
maximum_volume_size: Optional[pulumi.Input[str]] = None,
metadata: Optional[pulumi.Input[pulumi.InputType['_meta.v1.ObjectMetaArgs']]] = None,
node_topology: Optional[pulumi.Input[pulumi.InputType['_meta.v1.LabelSelectorArgs']]] = None,
storage_class_name: Optional[pulumi.Input[str]] = None,
__props__=None):
...
@overload
def __init__(__self__,
resource_name: str,
args: CSIStorageCapacityArgs,
opts: Optional[pulumi.ResourceOptions] = None):
...
def __init__(__self__, resource_name: str, *args, **kwargs):
resource_args, opts = _utilities.get_resource_args_opts(CSIStorageCapacityArgs, pulumi.ResourceOptions, *args, **kwargs)
if resource_args is not None:
__self__._internal_init(resource_name, opts, **resource_args.__dict__)
else:
__self__._internal_init(resource_name, *args, **kwargs)
def _internal_init(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
api_version: Optional[pulumi.Input[str]] = None,
capacity: Optional[pulumi.Input[str]] = None,
kind: Optional[pulumi.Input[str]] = None,
maximum_volume_size: Optional[pulumi.Input[str]] = None,
metadata: Optional[pulumi.Input[pulumi.InputType['_meta.v1.ObjectMetaArgs']]] = None,
node_topology: Optional[pulumi.Input[pulumi.InputType['_meta.v1.LabelSelectorArgs']]] = None,
storage_class_name: Optional[pulumi.Input[str]] = None,
__props__=None):
if opts is None:
opts = pulumi.ResourceOptions()
if not isinstance(opts, pulumi.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
if opts.version is None:
opts.version = _utilities.get_version()
if opts.id is None:
if __props__ is not None:
raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')
__props__ = CSIStorageCapacityArgs.__new__(CSIStorageCapacityArgs)
__props__.__dict__["api_version"] = 'storage.k8s.io/v1beta1'
__props__.__dict__["capacity"] = capacity
__props__.__dict__["kind"] = 'CSIStorageCapacity'
__props__.__dict__["maximum_volume_size"] = maximum_volume_size
__props__.__dict__["metadata"] = metadata
__props__.__dict__["node_topology"] = node_topology
if storage_class_name is None and not opts.urn:
raise TypeError("Missing required property 'storage_class_name'")
__props__.__dict__["storage_class_name"] = storage_class_name
alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_="kubernetes:storage.k8s.io/v1alpha1:CSIStorageCapacity")])
opts = pulumi.ResourceOptions.merge(opts, alias_opts)
super(CSIStorageCapacity, __self__).__init__(
'kubernetes:storage.k8s.io/v1beta1:CSIStorageCapacity',
resource_name,
__props__,
opts)
@staticmethod
def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None) -> 'CSIStorageCapacity':
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = CSIStorageCapacityArgs.__new__(CSIStorageCapacityArgs)
__props__.__dict__["api_version"] = None
__props__.__dict__["capacity"] = None
__props__.__dict__["kind"] = None
__props__.__dict__["maximum_volume_size"] = None
__props__.__dict__["metadata"] = None
__props__.__dict__["node_topology"] = None
__props__.__dict__["storage_class_name"] = None
return CSIStorageCapacity(resource_name, opts=opts, __props__=__props__)
@property
@pulumi.getter(name="apiVersion")
def api_version(self) -> pulumi.Output[Optional[str]]:
return pulumi.get(self, "api_version")
@property
@pulumi.getter
def capacity(self) -> pulumi.Output[Optional[str]]:
return pulumi.get(self, "capacity")
@property
@pulumi.getter
def kind(self) -> pulumi.Output[Optional[str]]:
return pulumi.get(self, "kind")
@property
@pulumi.getter(name="maximumVolumeSize")
def maximum_volume_size(self) -> pulumi.Output[Optional[str]]:
return pulumi.get(self, "maximum_volume_size")
@property
@pulumi.getter
def metadata(self) -> pulumi.Output[Optional['_meta.v1.outputs.ObjectMeta']]:
return pulumi.get(self, "metadata")
@property
@pulumi.getter(name="nodeTopology")
def node_topology(self) -> pulumi.Output[Optional['_meta.v1.outputs.LabelSelector']]:
return pulumi.get(self, "node_topology")
@property
@pulumi.getter(name="storageClassName")
def storage_class_name(self) -> pulumi.Output[str]:
return pulumi.get(self, "storage_class_name")
| true | true |
790bd5447db6bb621163c59dcbf310f1773cbef7 | 9,605 | py | Python | sdk/python/pulumi_azure_native/datafactory/private_endpoint_connection.py | sebtelko/pulumi-azure-native | 711ec021b5c73da05611c56c8a35adb0ce3244e4 | [
"Apache-2.0"
] | null | null | null | sdk/python/pulumi_azure_native/datafactory/private_endpoint_connection.py | sebtelko/pulumi-azure-native | 711ec021b5c73da05611c56c8a35adb0ce3244e4 | [
"Apache-2.0"
] | null | null | null | sdk/python/pulumi_azure_native/datafactory/private_endpoint_connection.py | sebtelko/pulumi-azure-native | 711ec021b5c73da05611c56c8a35adb0ce3244e4 | [
"Apache-2.0"
] | null | null | null | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from . import outputs
from ._inputs import *
__all__ = ['PrivateEndpointConnectionArgs', 'PrivateEndpointConnection']
@pulumi.input_type
class PrivateEndpointConnectionArgs:
def __init__(__self__, *,
factory_name: pulumi.Input[str],
resource_group_name: pulumi.Input[str],
private_endpoint_connection_name: Optional[pulumi.Input[str]] = None,
properties: Optional[pulumi.Input['PrivateLinkConnectionApprovalRequestArgs']] = None):
"""
The set of arguments for constructing a PrivateEndpointConnection resource.
:param pulumi.Input[str] factory_name: The factory name.
:param pulumi.Input[str] resource_group_name: The resource group name.
:param pulumi.Input[str] private_endpoint_connection_name: The private endpoint connection name.
:param pulumi.Input['PrivateLinkConnectionApprovalRequestArgs'] properties: Core resource properties
"""
pulumi.set(__self__, "factory_name", factory_name)
pulumi.set(__self__, "resource_group_name", resource_group_name)
if private_endpoint_connection_name is not None:
pulumi.set(__self__, "private_endpoint_connection_name", private_endpoint_connection_name)
if properties is not None:
pulumi.set(__self__, "properties", properties)
@property
@pulumi.getter(name="factoryName")
def factory_name(self) -> pulumi.Input[str]:
"""
The factory name.
"""
return pulumi.get(self, "factory_name")
@factory_name.setter
def factory_name(self, value: pulumi.Input[str]):
pulumi.set(self, "factory_name", value)
@property
@pulumi.getter(name="resourceGroupName")
def resource_group_name(self) -> pulumi.Input[str]:
"""
The resource group name.
"""
return pulumi.get(self, "resource_group_name")
@resource_group_name.setter
def resource_group_name(self, value: pulumi.Input[str]):
pulumi.set(self, "resource_group_name", value)
@property
@pulumi.getter(name="privateEndpointConnectionName")
def private_endpoint_connection_name(self) -> Optional[pulumi.Input[str]]:
"""
The private endpoint connection name.
"""
return pulumi.get(self, "private_endpoint_connection_name")
@private_endpoint_connection_name.setter
def private_endpoint_connection_name(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "private_endpoint_connection_name", value)
@property
@pulumi.getter
def properties(self) -> Optional[pulumi.Input['PrivateLinkConnectionApprovalRequestArgs']]:
"""
Core resource properties
"""
return pulumi.get(self, "properties")
@properties.setter
def properties(self, value: Optional[pulumi.Input['PrivateLinkConnectionApprovalRequestArgs']]):
pulumi.set(self, "properties", value)
class PrivateEndpointConnection(pulumi.CustomResource):
@overload
def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
factory_name: Optional[pulumi.Input[str]] = None,
private_endpoint_connection_name: Optional[pulumi.Input[str]] = None,
properties: Optional[pulumi.Input[pulumi.InputType['PrivateLinkConnectionApprovalRequestArgs']]] = None,
resource_group_name: Optional[pulumi.Input[str]] = None,
__props__=None):
"""
Private Endpoint Connection ARM resource.
API Version: 2018-06-01.
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[str] factory_name: The factory name.
:param pulumi.Input[str] private_endpoint_connection_name: The private endpoint connection name.
:param pulumi.Input[pulumi.InputType['PrivateLinkConnectionApprovalRequestArgs']] properties: Core resource properties
:param pulumi.Input[str] resource_group_name: The resource group name.
"""
...
@overload
def __init__(__self__,
resource_name: str,
args: PrivateEndpointConnectionArgs,
opts: Optional[pulumi.ResourceOptions] = None):
"""
Private Endpoint Connection ARM resource.
API Version: 2018-06-01.
:param str resource_name: The name of the resource.
:param PrivateEndpointConnectionArgs args: The arguments to use to populate this resource's properties.
:param pulumi.ResourceOptions opts: Options for the resource.
"""
...
def __init__(__self__, resource_name: str, *args, **kwargs):
resource_args, opts = _utilities.get_resource_args_opts(PrivateEndpointConnectionArgs, pulumi.ResourceOptions, *args, **kwargs)
if resource_args is not None:
__self__._internal_init(resource_name, opts, **resource_args.__dict__)
else:
__self__._internal_init(resource_name, *args, **kwargs)
def _internal_init(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
factory_name: Optional[pulumi.Input[str]] = None,
private_endpoint_connection_name: Optional[pulumi.Input[str]] = None,
properties: Optional[pulumi.Input[pulumi.InputType['PrivateLinkConnectionApprovalRequestArgs']]] = None,
resource_group_name: Optional[pulumi.Input[str]] = None,
__props__=None):
if opts is None:
opts = pulumi.ResourceOptions()
if not isinstance(opts, pulumi.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
if opts.version is None:
opts.version = _utilities.get_version()
if opts.id is None:
if __props__ is not None:
raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')
__props__ = PrivateEndpointConnectionArgs.__new__(PrivateEndpointConnectionArgs)
if factory_name is None and not opts.urn:
raise TypeError("Missing required property 'factory_name'")
__props__.__dict__["factory_name"] = factory_name
__props__.__dict__["private_endpoint_connection_name"] = private_endpoint_connection_name
__props__.__dict__["properties"] = properties
if resource_group_name is None and not opts.urn:
raise TypeError("Missing required property 'resource_group_name'")
__props__.__dict__["resource_group_name"] = resource_group_name
__props__.__dict__["etag"] = None
__props__.__dict__["name"] = None
__props__.__dict__["type"] = None
alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_="azure-nextgen:datafactory:PrivateEndpointConnection"), pulumi.Alias(type_="azure-native:datafactory/v20180601:PrivateEndpointConnection"), pulumi.Alias(type_="azure-nextgen:datafactory/v20180601:PrivateEndpointConnection")])
opts = pulumi.ResourceOptions.merge(opts, alias_opts)
super(PrivateEndpointConnection, __self__).__init__(
'azure-native:datafactory:PrivateEndpointConnection',
resource_name,
__props__,
opts)
@staticmethod
def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None) -> 'PrivateEndpointConnection':
"""
Get an existing PrivateEndpointConnection resource's state with the given name, id, and optional extra
properties used to qualify the lookup.
:param str resource_name: The unique name of the resulting resource.
:param pulumi.Input[str] id: The unique provider ID of the resource to lookup.
:param pulumi.ResourceOptions opts: Options for the resource.
"""
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = PrivateEndpointConnectionArgs.__new__(PrivateEndpointConnectionArgs)
__props__.__dict__["etag"] = None
__props__.__dict__["name"] = None
__props__.__dict__["properties"] = None
__props__.__dict__["type"] = None
return PrivateEndpointConnection(resource_name, opts=opts, __props__=__props__)
@property
@pulumi.getter
def etag(self) -> pulumi.Output[str]:
"""
Etag identifies change in the resource.
"""
return pulumi.get(self, "etag")
@property
@pulumi.getter
def name(self) -> pulumi.Output[str]:
"""
The resource name.
"""
return pulumi.get(self, "name")
@property
@pulumi.getter
def properties(self) -> pulumi.Output['outputs.RemotePrivateEndpointConnectionResponse']:
"""
Core resource properties
"""
return pulumi.get(self, "properties")
@property
@pulumi.getter
def type(self) -> pulumi.Output[str]:
"""
The resource type.
"""
return pulumi.get(self, "type")
| 43.659091 | 297 | 0.669755 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from . import outputs
from ._inputs import *
__all__ = ['PrivateEndpointConnectionArgs', 'PrivateEndpointConnection']
@pulumi.input_type
class PrivateEndpointConnectionArgs:
def __init__(__self__, *,
factory_name: pulumi.Input[str],
resource_group_name: pulumi.Input[str],
private_endpoint_connection_name: Optional[pulumi.Input[str]] = None,
properties: Optional[pulumi.Input['PrivateLinkConnectionApprovalRequestArgs']] = None):
pulumi.set(__self__, "factory_name", factory_name)
pulumi.set(__self__, "resource_group_name", resource_group_name)
if private_endpoint_connection_name is not None:
pulumi.set(__self__, "private_endpoint_connection_name", private_endpoint_connection_name)
if properties is not None:
pulumi.set(__self__, "properties", properties)
@property
@pulumi.getter(name="factoryName")
def factory_name(self) -> pulumi.Input[str]:
return pulumi.get(self, "factory_name")
@factory_name.setter
def factory_name(self, value: pulumi.Input[str]):
pulumi.set(self, "factory_name", value)
@property
@pulumi.getter(name="resourceGroupName")
def resource_group_name(self) -> pulumi.Input[str]:
return pulumi.get(self, "resource_group_name")
@resource_group_name.setter
def resource_group_name(self, value: pulumi.Input[str]):
pulumi.set(self, "resource_group_name", value)
@property
@pulumi.getter(name="privateEndpointConnectionName")
def private_endpoint_connection_name(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "private_endpoint_connection_name")
@private_endpoint_connection_name.setter
def private_endpoint_connection_name(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "private_endpoint_connection_name", value)
@property
@pulumi.getter
def properties(self) -> Optional[pulumi.Input['PrivateLinkConnectionApprovalRequestArgs']]:
return pulumi.get(self, "properties")
@properties.setter
def properties(self, value: Optional[pulumi.Input['PrivateLinkConnectionApprovalRequestArgs']]):
pulumi.set(self, "properties", value)
class PrivateEndpointConnection(pulumi.CustomResource):
@overload
def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
factory_name: Optional[pulumi.Input[str]] = None,
private_endpoint_connection_name: Optional[pulumi.Input[str]] = None,
properties: Optional[pulumi.Input[pulumi.InputType['PrivateLinkConnectionApprovalRequestArgs']]] = None,
resource_group_name: Optional[pulumi.Input[str]] = None,
__props__=None):
...
@overload
def __init__(__self__,
resource_name: str,
args: PrivateEndpointConnectionArgs,
opts: Optional[pulumi.ResourceOptions] = None):
...
def __init__(__self__, resource_name: str, *args, **kwargs):
resource_args, opts = _utilities.get_resource_args_opts(PrivateEndpointConnectionArgs, pulumi.ResourceOptions, *args, **kwargs)
if resource_args is not None:
__self__._internal_init(resource_name, opts, **resource_args.__dict__)
else:
__self__._internal_init(resource_name, *args, **kwargs)
def _internal_init(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
factory_name: Optional[pulumi.Input[str]] = None,
private_endpoint_connection_name: Optional[pulumi.Input[str]] = None,
properties: Optional[pulumi.Input[pulumi.InputType['PrivateLinkConnectionApprovalRequestArgs']]] = None,
resource_group_name: Optional[pulumi.Input[str]] = None,
__props__=None):
if opts is None:
opts = pulumi.ResourceOptions()
if not isinstance(opts, pulumi.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
if opts.version is None:
opts.version = _utilities.get_version()
if opts.id is None:
if __props__ is not None:
raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')
__props__ = PrivateEndpointConnectionArgs.__new__(PrivateEndpointConnectionArgs)
if factory_name is None and not opts.urn:
raise TypeError("Missing required property 'factory_name'")
__props__.__dict__["factory_name"] = factory_name
__props__.__dict__["private_endpoint_connection_name"] = private_endpoint_connection_name
__props__.__dict__["properties"] = properties
if resource_group_name is None and not opts.urn:
raise TypeError("Missing required property 'resource_group_name'")
__props__.__dict__["resource_group_name"] = resource_group_name
__props__.__dict__["etag"] = None
__props__.__dict__["name"] = None
__props__.__dict__["type"] = None
alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_="azure-nextgen:datafactory:PrivateEndpointConnection"), pulumi.Alias(type_="azure-native:datafactory/v20180601:PrivateEndpointConnection"), pulumi.Alias(type_="azure-nextgen:datafactory/v20180601:PrivateEndpointConnection")])
opts = pulumi.ResourceOptions.merge(opts, alias_opts)
super(PrivateEndpointConnection, __self__).__init__(
'azure-native:datafactory:PrivateEndpointConnection',
resource_name,
__props__,
opts)
@staticmethod
def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None) -> 'PrivateEndpointConnection':
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = PrivateEndpointConnectionArgs.__new__(PrivateEndpointConnectionArgs)
__props__.__dict__["etag"] = None
__props__.__dict__["name"] = None
__props__.__dict__["properties"] = None
__props__.__dict__["type"] = None
return PrivateEndpointConnection(resource_name, opts=opts, __props__=__props__)
@property
@pulumi.getter
def etag(self) -> pulumi.Output[str]:
return pulumi.get(self, "etag")
@property
@pulumi.getter
def name(self) -> pulumi.Output[str]:
return pulumi.get(self, "name")
@property
@pulumi.getter
def properties(self) -> pulumi.Output['outputs.RemotePrivateEndpointConnectionResponse']:
return pulumi.get(self, "properties")
@property
@pulumi.getter
def type(self) -> pulumi.Output[str]:
return pulumi.get(self, "type")
| true | true |
790bd583b0ced0d04970656e1a3968478d4e8aff | 6,596 | py | Python | federatedml/feature/feature_scale/standard_scale.py | chenj133/FATE | 7065fc73ab83f83e699efec69ff8efb499159ef4 | [
"Apache-2.0"
] | 3 | 2019-10-18T02:22:05.000Z | 2019-10-18T02:22:42.000Z | federatedml/feature/feature_scale/standard_scale.py | chenj133/FATE | 7065fc73ab83f83e699efec69ff8efb499159ef4 | [
"Apache-2.0"
] | 14 | 2020-01-28T23:02:45.000Z | 2022-02-10T00:22:08.000Z | federatedml/feature/feature_scale/standard_scale.py | chenj133/FATE | 7065fc73ab83f83e699efec69ff8efb499159ef4 | [
"Apache-2.0"
] | 2 | 2019-09-05T02:32:05.000Z | 2019-09-17T10:30:48.000Z | #
# Copyright 2019 The FATE Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import functools
import numpy as np
from arch.api.proto.feature_scale_meta_pb2 import ScaleMeta
from arch.api.proto.feature_scale_param_pb2 import ScaleParam
from arch.api.proto.feature_scale_param_pb2 import ColumnScaleParam
from arch.api.utils import log_utils
from federatedml.feature.feature_scale.base_scale import BaseScale
from federatedml.statistic.statics import MultivariateStatisticalSummary
LOGGER = log_utils.getLogger()
class StandardScale(BaseScale):
"""
Standardize features by removing the mean and scaling to unit variance. The standard score of a sample x is calculated as:
z = (x - u) / s, where u is the mean of the training samples, and s is the standard deviation of the training samples
"""
def __init__(self, params):
super().__init__(params)
self.with_mean = params.with_mean
self.with_std = params.with_std
self.mean = None
self.std = None
def set_param(self, mean, std):
self.mean = mean
self.std = std
@staticmethod
def __scale_with_column_range(data, column_upper, column_lower, mean, std, process_cols_list):
for i in process_cols_list:
value = data.features[i]
if value > column_upper[i]:
value = column_upper[i]
elif value < column_lower[i]:
value = column_lower[i]
data.features[i] = np.around((value - mean[i]) / std[i], 6)
return data
@staticmethod
def __scale(data, mean, std, process_cols_list):
for i in process_cols_list:
data.features[i] = np.around((data.features[i] - mean[i]) / std[i], 6)
return data
def fit(self, data):
"""
Apply standard scale for input data
Parameters
----------
data: data_instance, input data
Returns
----------
data:data_instance, data after scale
mean: list, each column mean value
std: list, each column standard deviation
"""
self.column_min_value, self.column_max_value = self._get_min_max_value(data)
self.scale_column_idx = self._get_scale_column_idx(data)
self.header = self._get_header(data)
self.data_shape = self._get_data_shape(data)
# fit column value if larger than parameter upper or less than parameter lower
data = self.fit_feature_range(data)
if not self.with_mean and not self.with_std:
self.mean = [0 for _ in range(self.data_shape)]
self.std = [1 for _ in range(self.data_shape)]
else:
self.summary_obj = MultivariateStatisticalSummary(data, -1)
if self.with_mean:
self.mean = self.summary_obj.get_mean()
self.mean = [self.mean[key] for key in self.header]
else:
self.mean = [0 for _ in range(self.data_shape)]
if self.with_std:
self.std = self.summary_obj.get_std_variance()
self.std = [self.std[key] for key in self.header]
for i, value in enumerate(self.std):
if np.abs(value - 0) < 1e-6:
self.std[i] = 1
else:
self.std = [1 for _ in range(self.data_shape)]
f = functools.partial(self.__scale, mean=self.mean, std=self.std, process_cols_list=self.scale_column_idx)
fit_data = data.mapValues(f)
return fit_data
def transform(self, data):
"""
Transform input data using standard scale with fit results
Parameters
----------
data: data_instance, input data
Returns
----------
transform_data:data_instance, data after transform
"""
f = functools.partial(self.__scale_with_column_range, column_upper=self.column_max_value,
column_lower=self.column_min_value,
mean=self.mean, std=self.std, process_cols_list=self.scale_column_idx)
transform_data = data.mapValues(f)
return transform_data
def __get_meta(self):
if self.header:
scale_column = [self.header[i] for i in self.scale_column_idx]
else:
scale_column = ["_".join(["col", str(i)]) for i in self.scale_column_idx]
if not self.data_shape:
self.data_shape = -1
meta_proto_obj = ScaleMeta(method="standard_scale",
area=self.area,
scale_column=scale_column,
feat_upper=self._get_upper(self.data_shape),
feat_lower=self._get_lower(self.data_shape),
with_mean=self.with_mean,
with_std=self.with_std
)
return meta_proto_obj
def __get_param(self, need_run):
column_scale_param_dict = {}
if self.header:
for i, header in enumerate(self.header):
if i in self.scale_column_idx:
param_obj = ColumnScaleParam(column_upper=self.column_max_value[i],
column_lower=self.column_min_value[i],
mean=self.mean[i],
std=self.std[i])
column_scale_param_dict[header] = param_obj
param_proto_obj = ScaleParam(col_scale_param=column_scale_param_dict,
header=self.header,
need_run=need_run)
return param_proto_obj
def export_model(self, need_run):
meta_obj = self.__get_meta()
param_obj = self.__get_param(need_run)
result = {
self.model_meta_name: meta_obj,
self.model_param_name: param_obj
}
return result
| 37.05618 | 126 | 0.595512 |
import functools
import numpy as np
from arch.api.proto.feature_scale_meta_pb2 import ScaleMeta
from arch.api.proto.feature_scale_param_pb2 import ScaleParam
from arch.api.proto.feature_scale_param_pb2 import ColumnScaleParam
from arch.api.utils import log_utils
from federatedml.feature.feature_scale.base_scale import BaseScale
from federatedml.statistic.statics import MultivariateStatisticalSummary
LOGGER = log_utils.getLogger()
class StandardScale(BaseScale):
def __init__(self, params):
super().__init__(params)
self.with_mean = params.with_mean
self.with_std = params.with_std
self.mean = None
self.std = None
def set_param(self, mean, std):
self.mean = mean
self.std = std
@staticmethod
def __scale_with_column_range(data, column_upper, column_lower, mean, std, process_cols_list):
for i in process_cols_list:
value = data.features[i]
if value > column_upper[i]:
value = column_upper[i]
elif value < column_lower[i]:
value = column_lower[i]
data.features[i] = np.around((value - mean[i]) / std[i], 6)
return data
@staticmethod
def __scale(data, mean, std, process_cols_list):
for i in process_cols_list:
data.features[i] = np.around((data.features[i] - mean[i]) / std[i], 6)
return data
def fit(self, data):
self.column_min_value, self.column_max_value = self._get_min_max_value(data)
self.scale_column_idx = self._get_scale_column_idx(data)
self.header = self._get_header(data)
self.data_shape = self._get_data_shape(data)
data = self.fit_feature_range(data)
if not self.with_mean and not self.with_std:
self.mean = [0 for _ in range(self.data_shape)]
self.std = [1 for _ in range(self.data_shape)]
else:
self.summary_obj = MultivariateStatisticalSummary(data, -1)
if self.with_mean:
self.mean = self.summary_obj.get_mean()
self.mean = [self.mean[key] for key in self.header]
else:
self.mean = [0 for _ in range(self.data_shape)]
if self.with_std:
self.std = self.summary_obj.get_std_variance()
self.std = [self.std[key] for key in self.header]
for i, value in enumerate(self.std):
if np.abs(value - 0) < 1e-6:
self.std[i] = 1
else:
self.std = [1 for _ in range(self.data_shape)]
f = functools.partial(self.__scale, mean=self.mean, std=self.std, process_cols_list=self.scale_column_idx)
fit_data = data.mapValues(f)
return fit_data
def transform(self, data):
f = functools.partial(self.__scale_with_column_range, column_upper=self.column_max_value,
column_lower=self.column_min_value,
mean=self.mean, std=self.std, process_cols_list=self.scale_column_idx)
transform_data = data.mapValues(f)
return transform_data
def __get_meta(self):
if self.header:
scale_column = [self.header[i] for i in self.scale_column_idx]
else:
scale_column = ["_".join(["col", str(i)]) for i in self.scale_column_idx]
if not self.data_shape:
self.data_shape = -1
meta_proto_obj = ScaleMeta(method="standard_scale",
area=self.area,
scale_column=scale_column,
feat_upper=self._get_upper(self.data_shape),
feat_lower=self._get_lower(self.data_shape),
with_mean=self.with_mean,
with_std=self.with_std
)
return meta_proto_obj
def __get_param(self, need_run):
column_scale_param_dict = {}
if self.header:
for i, header in enumerate(self.header):
if i in self.scale_column_idx:
param_obj = ColumnScaleParam(column_upper=self.column_max_value[i],
column_lower=self.column_min_value[i],
mean=self.mean[i],
std=self.std[i])
column_scale_param_dict[header] = param_obj
param_proto_obj = ScaleParam(col_scale_param=column_scale_param_dict,
header=self.header,
need_run=need_run)
return param_proto_obj
def export_model(self, need_run):
meta_obj = self.__get_meta()
param_obj = self.__get_param(need_run)
result = {
self.model_meta_name: meta_obj,
self.model_param_name: param_obj
}
return result
| true | true |
790bd7a07442994e0ce4b5b0c893be3b7b309cb5 | 2,171 | py | Python | file/py/result_mashara.py | piscalpratama/KMSV2 | 7677d26c83236c25007f375a7157989e1322e9f9 | [
"MIT"
] | null | null | null | file/py/result_mashara.py | piscalpratama/KMSV2 | 7677d26c83236c25007f375a7157989e1322e9f9 | [
"MIT"
] | null | null | null | file/py/result_mashara.py | piscalpratama/KMSV2 | 7677d26c83236c25007f375a7157989e1322e9f9 | [
"MIT"
] | null | null | null | import sys
import json
import scrapapps
import scrapping
from textrank import TextRankSentences
import preprocessing
import summ
import textrankkeyword
import bss4
url = sys.argv[1]
# url = request.POST.get('web_link', None)
#web_link = scrapapps.scrap_data(url)
web_link = scrapping.scrap_data(url)
#Get Title
judul = scrapping.get_title(url)
raw_text = str(web_link)
# Preprocessing View
lower = preprocessing.text_lowercase(str(web_link))
rnumber = preprocessing.remove_numbers(lower)
white_space = preprocessing.remove_whitespace(rnumber)
stopword_list = preprocessing.remove_stopwords(white_space)
new_sentence = ' '.join(stopword_list)
stagging = preprocessing.stagging_text(new_sentence)
stop_plus = preprocessing.stopword_plus(new_sentence)
kalimat = ' '.join(stop_plus)
# Skenario 1
# n = 10;
# if len(stagging) < 10:
# n = 5
# if len(stagging) == 10:
# n = len(stagging) - 2
# if len(stagging) > 30:
# n = 15
# if len(stagging) < 5:
# n = len(stagging) - 1
# if len(stagging) == 1:
# n = len(stagging)
# Skenario 2
n = 7
if len(stagging) < 7:
n = len(stagging) - 1
if len(stagging) == 1:
n = len(stagging)
textrank = TextRankSentences()
text = textrank.analyze(str(new_sentence))
text = textrank.get_top_sentences(n)
# View Similarity Matriks
sim_mat = textrank._build_similarity_matrix(stagging)
#View Hasil Perhitungan Textrank
top_rank = textrank._run_page_rank(sim_mat)
result = textrank._run_page_rank(sim_mat)
# Clean Hasil
ringkasan = preprocessing.remove_punctuation(text)
# Panjang Plaintext
len_raw = len(str(web_link))
# Jumlah Text
len_text = len(str(text))
# Jumlah Kalimat
len_kalimat = len(stagging)
#Presentase Reduce
presentase = round(((len_text/len_raw)*100))
# keyphrases = textrankkeyword.extract_key_phrases(raw_text)
data = {
'raw_text' : raw_text,
'url' : url,
'judul' : judul,
'ringkasan':ringkasan,
'text':text,
'len_raw':len_raw,
'len_text':len_text,
'len_kalimat':len_kalimat,
'stagging':stagging,
'new_sentence':new_sentence,
# 'sim_mat':sim_mat,
# 'result':result,
'presentase':presentase,
'keyword':'-',
}
print(json.dumps(data)) | 19.558559 | 60 | 0.722248 | import sys
import json
import scrapapps
import scrapping
from textrank import TextRankSentences
import preprocessing
import summ
import textrankkeyword
import bss4
url = sys.argv[1]
web_link = scrapping.scrap_data(url)
judul = scrapping.get_title(url)
raw_text = str(web_link)
lower = preprocessing.text_lowercase(str(web_link))
rnumber = preprocessing.remove_numbers(lower)
white_space = preprocessing.remove_whitespace(rnumber)
stopword_list = preprocessing.remove_stopwords(white_space)
new_sentence = ' '.join(stopword_list)
stagging = preprocessing.stagging_text(new_sentence)
stop_plus = preprocessing.stopword_plus(new_sentence)
kalimat = ' '.join(stop_plus)
n = 7
if len(stagging) < 7:
n = len(stagging) - 1
if len(stagging) == 1:
n = len(stagging)
textrank = TextRankSentences()
text = textrank.analyze(str(new_sentence))
text = textrank.get_top_sentences(n)
sim_mat = textrank._build_similarity_matrix(stagging)
top_rank = textrank._run_page_rank(sim_mat)
result = textrank._run_page_rank(sim_mat)
ringkasan = preprocessing.remove_punctuation(text)
len_raw = len(str(web_link))
len_text = len(str(text))
len_kalimat = len(stagging)
presentase = round(((len_text/len_raw)*100))
data = {
'raw_text' : raw_text,
'url' : url,
'judul' : judul,
'ringkasan':ringkasan,
'text':text,
'len_raw':len_raw,
'len_text':len_text,
'len_kalimat':len_kalimat,
'stagging':stagging,
'new_sentence':new_sentence,
'presentase':presentase,
'keyword':'-',
}
print(json.dumps(data)) | true | true |
790bd80c1f90e56a600eccb4cc68bcd75db2dae5 | 6,839 | py | Python | src/datadog_api_client/v2/model/security_filter_exclusion_filter.py | rchenzheng/datadog-api-client-python | 2e86ac098c6f0c7fdd90ed218224587c0f8eafef | [
"Apache-2.0"
] | null | null | null | src/datadog_api_client/v2/model/security_filter_exclusion_filter.py | rchenzheng/datadog-api-client-python | 2e86ac098c6f0c7fdd90ed218224587c0f8eafef | [
"Apache-2.0"
] | null | null | null | src/datadog_api_client/v2/model/security_filter_exclusion_filter.py | rchenzheng/datadog-api-client-python | 2e86ac098c6f0c7fdd90ed218224587c0f8eafef | [
"Apache-2.0"
] | null | null | null | # Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License.
# This product includes software developed at Datadog (https://www.datadoghq.com/).
# Copyright 2019-Present Datadog, Inc.
import re # noqa: F401
import sys # noqa: F401
from datadog_api_client.v2.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 SecurityFilterExclusionFilter(ModelNormal):
"""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.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
discriminator_value_class_map (dict): A dict to go from the discriminator
variable value to the discriminator class name.
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 = {}
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 {
"name": (str,), # noqa: E501
"query": (str,), # noqa: E501
}
@cached_property
def discriminator():
return None
attribute_map = {
"name": "name", # noqa: E501
"query": "query", # noqa: E501
}
_composed_schemas = {}
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, name, query, *args, **kwargs): # noqa: E501
"""SecurityFilterExclusionFilter - a model defined in OpenAPI
Args:
name (str): Exclusion filter name.
query (str): Exclusion filter query. Logs that match this query are excluded from the security filter.
Keyword Args:
_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,)
"""
_check_type = kwargs.pop("_check_type", True)
_spec_property_naming = kwargs.pop("_spec_property_naming", False)
_path_to_item = kwargs.pop("_path_to_item", ())
_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.name = name
self.query = query
for var_name, var_value in kwargs.items():
if (
var_name not in self.attribute_map
and self._configuration is not None
and self._configuration.discard_unknown_keys
and self.additional_properties_type is None
):
# discard variable.
continue
setattr(self, var_name, var_value)
| 39.994152 | 114 | 0.583126 |
import re
import sys
from datadog_api_client.v2.model_utils import (
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 SecurityFilterExclusionFilter(ModelNormal):
allowed_values = {}
validations = {}
additional_properties_type = None
_nullable = False
@cached_property
def openapi_types():
return {
"name": (str,),
"query": (str,),
}
@cached_property
def discriminator():
return None
attribute_map = {
"name": "name",
"query": "query",
}
_composed_schemas = {}
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, name, query, *args, **kwargs):
_check_type = kwargs.pop("_check_type", True)
_spec_property_naming = kwargs.pop("_spec_property_naming", False)
_path_to_item = kwargs.pop("_path_to_item", ())
_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.name = name
self.query = query
for var_name, var_value in kwargs.items():
if (
var_name not in self.attribute_map
and self._configuration is not None
and self._configuration.discard_unknown_keys
and self.additional_properties_type is None
):
continue
setattr(self, var_name, var_value)
| true | true |
790bd8399ffdc82443bb930b63332f494e70a964 | 19,287 | py | Python | linkedin_api/linkedin.py | cicizh/linkedin-api | 1609ec705c95d5e05c0622db154be6dbac1eecb4 | [
"MIT"
] | null | null | null | linkedin_api/linkedin.py | cicizh/linkedin-api | 1609ec705c95d5e05c0622db154be6dbac1eecb4 | [
"MIT"
] | null | null | null | linkedin_api/linkedin.py | cicizh/linkedin-api | 1609ec705c95d5e05c0622db154be6dbac1eecb4 | [
"MIT"
] | 1 | 2019-09-04T16:09:15.000Z | 2019-09-04T16:09:15.000Z | """
Provides linkedin api-related code
"""
import random
import logging
from time import sleep
import json
from linkedin_api.utils.helpers import get_id_from_urn
from linkedin_api.client import Client
logger = logging.getLogger(__name__)
class Linkedin(object):
"""
Class for accessing Linkedin API.
"""
_MAX_UPDATE_COUNT = 100 # max seems to be 100
_MAX_SEARCH_COUNT = 49 # max seems to be 49
_MAX_REPEATED_REQUESTS = (
200
) # VERY conservative max requests count to avoid rate-limit
def __init__(self, username, password):
self.client = Client(debug=True)
self.client.authenticate(username, password)
self.logger = logger
def search(self, params, max_results=None, results=[]):
"""
Do a search.
"""
sleep(
random.randint(0, 1)
) # sleep a random duration to try and evade suspention
count = (
max_results
if max_results and max_results <= Linkedin._MAX_SEARCH_COUNT
else Linkedin._MAX_SEARCH_COUNT
)
default_params = {
"count": count,
"guides": "List()",
"origin": "GLOBAL_SEARCH_HEADER",
"q": "guided",
"start": len(results),
}
default_params.update(params)
res = self.client.session.get(
f"{self.client.API_BASE_URL}/search/cluster", params=default_params
)
data = res.json()
total_found = data.get("paging", {}).get("total")
# recursive base case
if (
len(data["elements"]) == 0
or (max_results is not None and len(results) >= max_results)
or total_found is None
or len(results) >= total_found
or (max_results is not None and len(results) / max_results >= Linkedin._MAX_REPEATED_REQUESTS)
):
return results
results.extend(data["elements"][0]["elements"])
self.logger.debug(f"results grew: {len(results)}")
return self.search(params, results=results, max_results=max_results)
def search_people(
self,
keywords=None,
connection_of=None,
network_depth=None,
regions=None,
industries=None,
):
"""
Do a people search.
"""
guides = ["v->PEOPLE"]
if connection_of:
guides.append(f"facetConnectionOf->{connection_of}")
if network_depth:
guides.append(f"facetNetwork->{network_depth}")
if regions:
guides.append(f'facetGeoRegion->{"|".join(regions)}')
if industries:
guides.append(f'facetIndustry->{"|".join(industries)}')
params = {"guides": "List({})".format(",".join(guides))}
if keywords:
params["keywords"] = keywords
data = self.search(params)
results = []
for item in data:
search_profile = item["hitInfo"][
"com.linkedin.voyager.search.SearchProfile"
]
profile_id = search_profile["id"]
distance = search_profile["distance"]["value"]
results.append(
{
"urn_id": profile_id,
"distance": distance,
"public_id": search_profile["miniProfile"]["publicIdentifier"],
}
)
return results
def search_companies(self, max_results=None, results=[]):
"""
Do a company search
Note: try swap from blended search to cluster
"""
sleep(
random.randint(2, 5)
) # sleep a random duration to try and evade suspention
#Search params from main search, here for reference
'''
default_params = {
"count": count,
"guides": "List()",
"origin": "GLOBAL_SEARCH_HEADER",
"q": "guided",
"start": len(results),
}
'''
default_params = {
"origin": "GLOBAL_SEARCH_HEADER",
"guides": "List(resultType->companies)",
"count": "10",
"q": "guided",
"filters": "List(resultType->companies)",
"start": len(results)
}
res = self.client.session.get(
f"{self.client.API_BASE_URL}/search/blended?keywords=s&origin=GLOBAL_SEARCH_HEADER&count=10&guides=List(resultType-%3Ecompanies)&q=all&filters=List(resultType-%3Ecompanies)&start={len(results)}"
)
data = res.json()
total_found = data.get("paging", {}).get("total")
if (
len(data["elements"]) == 0 or
len(data["elements"][0]["elements"]) == 0
or total_found is None
or (max_results is not None and len(results) >= max_results)
or (max_results is not None and len(results) / max_results >= Linkedin._MAX_REPEATED_REQUESTS)
):
return results
results.extend(data["elements"][0]["elements"])
self.logger.debug(f"results grew: {len(results)}")
return self.search_companies(max_results=max_results, results=results)
def get_profile_contact_info(self, public_id=None, urn_id=None):
"""
Return data for a single profile.
[public_id] - public identifier i.e. tom-quirk-1928345
[urn_id] - id provided by the related URN
"""
res = self.client.session.get(
f"{self.client.API_BASE_URL}/identity/profiles/{public_id or urn_id}/profileContactInfo"
)
data = res.json()
contact_info = {
"email_address": data.get("emailAddress"),
"websites": [],
"phone_numbers": data.get("phoneNumbers", []),
}
websites = data.get("websites", [])
for item in websites:
if "com.linkedin.voyager.identity.profile.StandardWebsite" in item["type"]:
item["label"] = item["type"][
"com.linkedin.voyager.identity.profile.StandardWebsite"
]["category"]
elif "" in item["type"]:
item["label"] = item["type"][
"com.linkedin.voyager.identity.profile.CustomWebsite"
]["label"]
del item["type"]
contact_info["websites"] = websites
return contact_info
def get_profile(self, public_id=None, urn_id=None):
"""
Return data for a single profile.
[public_id] - public identifier i.e. tom-quirk-1928345
[urn_id] - id provided by the related URN
"""
sleep(
random.randint(2, 5)
) # sleep a random duration to try and evade suspention
res = self.client.session.get(
f"{self.client.API_BASE_URL}/identity/profiles/{public_id or urn_id}/profileView"
)
data = res.json()
if data and "status" in data and data["status"] != 200:
self.logger.info("request failed: {}".format(data["message"]))
return {}
# massage [profile] data
profile = data["profile"]
if "miniProfile" in profile:
if "picture" in profile["miniProfile"]:
profile["displayPictureUrl"] = profile["miniProfile"]["picture"][
"com.linkedin.common.VectorImage"
]["rootUrl"]
profile["profile_id"] = get_id_from_urn(profile["miniProfile"]["entityUrn"])
del profile["miniProfile"]
del profile["defaultLocale"]
del profile["supportedLocales"]
del profile["versionTag"]
del profile["showEducationOnProfileTopCard"]
# massage [experience] data
experience = data["positionView"]["elements"]
for item in experience:
if "company" in item and "miniCompany" in item["company"]:
if "logo" in item["company"]["miniCompany"]:
logo = item["company"]["miniCompany"]["logo"].get(
"com.linkedin.common.VectorImage"
)
if logo:
item["companyLogoUrl"] = logo["rootUrl"]
del item["company"]["miniCompany"]
profile["experience"] = experience
# massage [skills] data
skills = [item["name"] for item in data["skillView"]["elements"]]
profile["skills"] = skills
# massage [education] data
education = data["educationView"]["elements"]
for item in education:
if "school" in item:
if "logo" in item["school"]:
item["school"]["logoUrl"] = item["school"]["logo"][
"com.linkedin.common.VectorImage"
]["rootUrl"]
del item["school"]["logo"]
profile["education"] = education
return profile
def get_profile_connections(self, urn_id):
"""
Return a list of profile ids connected to profile of given [urn_id]
"""
return self.search_people(connection_of=urn_id, network_depth="F")
def get_profile_networkinfo(self, urn_id):
"""
Return the nework info connected to the profile of the given [urn_id]
"""
sleep(
random.randint(2, 5)
) # sleep a random duration to try and evade suspention
res = self.client.session.get(
f"{self.client.API_BASE_URL}/identity/profiles/{urn_id}/networkinfo"
)
return res.json()
def get_company_updates(self, public_id=None, urn_id=None, max_results=None, results=[]):
""""
Return a list of company posts
[public_id] - public identifier ie - microsoft
[urn_id] - id provided by the related URN
"""
sleep(
random.randint(2, 5)
) # sleep a random duration to try and evade suspention
params = {
"companyUniversalName": {public_id or urn_id},
"q": "companyFeedByUniversalName",
"moduleKey": "member-share",
"count": Linkedin._MAX_UPDATE_COUNT,
"start": len(results),
}
res = self.client.session.get(
f"{self.client.API_BASE_URL}/feed/updates", params=params
)
data = res.json()
if (
len(data["elements"]) == 0
or (max_results is not None and len(results) >= max_results)
or (max_results is not None and len(results) / max_results >= Linkedin._MAX_REPEATED_REQUESTS)
):
return results
results.extend(data["elements"])
self.logger.debug(f"results grew: {len(results)}")
return self.get_company_updates(public_id=public_id, urn_id=urn_id, results=results, max_results=max_results)
def get_profile_updates(self, public_id=None, urn_id=None, max_results=None, results=[]):
""""
Return a list of profile posts
[public_id] - public identifier i.e. tom-quirk-1928345
[urn_id] - id provided by the related URN
"""
sleep(
random.randint(2, 5)
) # sleep a random duration to try and evade suspention
params = {
"profileId": {public_id or urn_id},
"q": "memberShareFeed",
"moduleKey": "member-share",
"count": Linkedin._MAX_UPDATE_COUNT,
"start": len(results),
}
res = self.client.session.get(
f"{self.client.API_BASE_URL}/feed/updates", params=params
)
data = res.json()
if (
len(data["elements"]) == 0
or (max_results is not None and len(results) >= max_results)
or (max_results is not None and len(results) / max_results >= Linkedin._MAX_REPEATED_REQUESTS)
):
return results
results.extend(data["elements"])
self.logger.debug(f"results grew: {len(results)}")
return self.get_profile_updates(public_id=public_id, urn_id=urn_id, results=results, max_results=max_results)
def get_current_profile_views(self):
"""
Get profile view statistics, including chart data.
"""
res = self.client.session.get(
f"{self.client.API_BASE_URL}/identity/panels"
)
data = res.json()
return data['elements'][0]['value']['com.linkedin.voyager.identity.me.ProfileViewsByTimePanel']
def get_school(self, public_id):
"""
Return data for a single school.
[public_id] - public identifier i.e. uq
"""
sleep(
random.randint(2, 5)
) # sleep a random duration to try and evade suspention
params = {
"decoration": (
"""
(
autoGenerated,backgroundCoverImage,
companyEmployeesSearchPageUrl,companyPageUrl,confirmedLocations*,coverPhoto,dataVersion,description,
entityUrn,followingInfo,foundedOn,headquarter,jobSearchPageUrl,lcpTreatment,logo,name,type,overviewPhoto,
paidCompany,partnerCompanyUrl,partnerLogo,partnerLogoImage,rankForTopCompanies,salesNavigatorCompanyUrl,
school,showcase,staffCount,staffCountRange,staffingCompany,topCompaniesListName,universalName,url,
companyIndustries*,industries,specialities,
acquirerCompany~(entityUrn,logo,name,industries,followingInfo,url,paidCompany,universalName),
affiliatedCompanies*~(entityUrn,logo,name,industries,followingInfo,url,paidCompany,universalName),
groups*~(entityUrn,largeLogo,groupName,memberCount,websiteUrl,url),
showcasePages*~(entityUrn,logo,name,industries,followingInfo,url,description,universalName)
)
"""
),
"q": "universalName",
"universalName": public_id,
}
res = self.client.session.get(
f"{self.client.API_BASE_URL}/organization/companies", params=params
)
data = res.json()
if data and "status" in data and data["status"] != 200:
self.logger.info("request failed: {}".format(data["message"]))
return {}
school = data["elements"][0]
return school
def get_similar_companies(self, public_id):
"""
Return similar companies for a single company.
[public_id] - public identifier i.e. univeristy-of-queensland
"""
sleep(
random.randint(2, 5)
) # sleep a random duration to try and evade suspention
res = self.client.session.get(
f"{self.client.API_BASE_URL}/organization/companies?count={Linkedin._MAX_SEARCH_COUNT}&companyUniversalName={public_id}&q=similarCompanies&start=0&decorationId=com.linkedin.voyager.deco.organization.web.WebSimilarCompanyCardWithRelevanceReason-3"
)
data = res.json()
return data
def get_company(self, public_id):
"""
Return data for a single company.
[public_id] - public identifier i.e. univeristy-of-queensland
"""
sleep(
random.randint(2, 5)
) # sleep a random duration to try and evade suspention
params = {
"decoration": (
"""
(
affiliatedCompaniesWithEmployeesRollup,affiliatedCompaniesWithJobsRollup,articlePermalinkForTopCompanies,
autoGenerated,backgroundCoverImage,companyEmployeesSearchPageUrl,
companyPageUrl,confirmedLocations*,coverPhoto,dataVersion,description,entityUrn,followingInfo,
foundedOn,headquarter,jobSearchPageUrl,lcpTreatment,logo,name,type,overviewPhoto,paidCompany,
partnerCompanyUrl,partnerLogo,partnerLogoImage,permissions,rankForTopCompanies,
salesNavigatorCompanyUrl,school,showcase,staffCount,staffCountRange,staffingCompany,
topCompaniesListName,universalName,url,companyIndustries*,industries,specialities,
acquirerCompany~(entityUrn,logo,name,industries,followingInfo,url,paidCompany,universalName),
affiliatedCompanies*~(entityUrn,logo,name,industries,followingInfo,url,paidCompany,universalName),
groups*~(entityUrn,largeLogo,groupName,memberCount,websiteUrl,url),
showcasePages*~(entityUrn,logo,name,industries,followingInfo,url,description,universalName)
)
"""
),
"q": "universalName",
"universalName": public_id,
}
res = self.client.session.get(
f"{self.client.API_BASE_URL}/organization/companies", params=params
)
data = res.json()
if data and "status" in data and data["status"] != 200:
self.logger.info("request failed: {}".format(data["message"]))
return {}
company = data["elements"][0]
return company
def get_conversation_details(self, profile_urn_id):
"""
Return the conversation (or "message thread") details for a given [public_profile_id]
"""
# passing `params` doesn't work properly, think it's to do with List().
# Might be a bug in `requests`?
res = self.client.session.get(
f"{self.client.API_BASE_URL}/messaging/conversations?\
keyVersion=LEGACY_INBOX&q=participants&recipients=List({profile_urn_id})"
)
data = res.json()
item = data["elements"][0]
item["id"] = get_id_from_urn(item["entityUrn"])
return item
def get_conversations(self):
"""
Return list of conversations the user is in.
"""
params = {"keyVersion": "LEGACY_INBOX"}
res = self.client.session.get(
f"{self.client.API_BASE_URL}/messaging/conversations", params=params
)
return res.json()
def get_conversation(self, conversation_urn_id):
"""
Return the full conversation at a given [conversation_urn_id]
"""
res = self.client.session.get(
f"{self.client.API_BASE_URL}/messaging/conversations/{conversation_urn_id}/events"
)
return res.json()
def send_message(self, conversation_urn_id, message_body):
"""
Return the full conversation at a given [conversation_urn_id]
"""
params = {"action": "create"}
payload = json.dumps(
{
"eventCreate": {
"value": {
"com.linkedin.voyager.messaging.create.MessageCreate": {
"body": message_body,
"attachments": [],
"attributedBody": {"text": message_body, "attributes": []},
"mediaAttachments": [],
}
}
}
}
)
res = self.client.session.post(
f"{self.client.API_BASE_URL}/messaging/conversations/{conversation_urn_id}/events",
params=params,
data=payload,
)
return res.status_code == 201
| 34.379679 | 258 | 0.575932 | import random
import logging
from time import sleep
import json
from linkedin_api.utils.helpers import get_id_from_urn
from linkedin_api.client import Client
logger = logging.getLogger(__name__)
class Linkedin(object):
_MAX_UPDATE_COUNT = 100
_MAX_SEARCH_COUNT = 49
_MAX_REPEATED_REQUESTS = (
200
)
def __init__(self, username, password):
self.client = Client(debug=True)
self.client.authenticate(username, password)
self.logger = logger
def search(self, params, max_results=None, results=[]):
sleep(
random.randint(0, 1)
)
count = (
max_results
if max_results and max_results <= Linkedin._MAX_SEARCH_COUNT
else Linkedin._MAX_SEARCH_COUNT
)
default_params = {
"count": count,
"guides": "List()",
"origin": "GLOBAL_SEARCH_HEADER",
"q": "guided",
"start": len(results),
}
default_params.update(params)
res = self.client.session.get(
f"{self.client.API_BASE_URL}/search/cluster", params=default_params
)
data = res.json()
total_found = data.get("paging", {}).get("total")
if (
len(data["elements"]) == 0
or (max_results is not None and len(results) >= max_results)
or total_found is None
or len(results) >= total_found
or (max_results is not None and len(results) / max_results >= Linkedin._MAX_REPEATED_REQUESTS)
):
return results
results.extend(data["elements"][0]["elements"])
self.logger.debug(f"results grew: {len(results)}")
return self.search(params, results=results, max_results=max_results)
def search_people(
self,
keywords=None,
connection_of=None,
network_depth=None,
regions=None,
industries=None,
):
guides = ["v->PEOPLE"]
if connection_of:
guides.append(f"facetConnectionOf->{connection_of}")
if network_depth:
guides.append(f"facetNetwork->{network_depth}")
if regions:
guides.append(f'facetGeoRegion->{"|".join(regions)}')
if industries:
guides.append(f'facetIndustry->{"|".join(industries)}')
params = {"guides": "List({})".format(",".join(guides))}
if keywords:
params["keywords"] = keywords
data = self.search(params)
results = []
for item in data:
search_profile = item["hitInfo"][
"com.linkedin.voyager.search.SearchProfile"
]
profile_id = search_profile["id"]
distance = search_profile["distance"]["value"]
results.append(
{
"urn_id": profile_id,
"distance": distance,
"public_id": search_profile["miniProfile"]["publicIdentifier"],
}
)
return results
def search_companies(self, max_results=None, results=[]):
sleep(
random.randint(2, 5)
)
default_params = {
"origin": "GLOBAL_SEARCH_HEADER",
"guides": "List(resultType->companies)",
"count": "10",
"q": "guided",
"filters": "List(resultType->companies)",
"start": len(results)
}
res = self.client.session.get(
f"{self.client.API_BASE_URL}/search/blended?keywords=s&origin=GLOBAL_SEARCH_HEADER&count=10&guides=List(resultType-%3Ecompanies)&q=all&filters=List(resultType-%3Ecompanies)&start={len(results)}"
)
data = res.json()
total_found = data.get("paging", {}).get("total")
if (
len(data["elements"]) == 0 or
len(data["elements"][0]["elements"]) == 0
or total_found is None
or (max_results is not None and len(results) >= max_results)
or (max_results is not None and len(results) / max_results >= Linkedin._MAX_REPEATED_REQUESTS)
):
return results
results.extend(data["elements"][0]["elements"])
self.logger.debug(f"results grew: {len(results)}")
return self.search_companies(max_results=max_results, results=results)
def get_profile_contact_info(self, public_id=None, urn_id=None):
res = self.client.session.get(
f"{self.client.API_BASE_URL}/identity/profiles/{public_id or urn_id}/profileContactInfo"
)
data = res.json()
contact_info = {
"email_address": data.get("emailAddress"),
"websites": [],
"phone_numbers": data.get("phoneNumbers", []),
}
websites = data.get("websites", [])
for item in websites:
if "com.linkedin.voyager.identity.profile.StandardWebsite" in item["type"]:
item["label"] = item["type"][
"com.linkedin.voyager.identity.profile.StandardWebsite"
]["category"]
elif "" in item["type"]:
item["label"] = item["type"][
"com.linkedin.voyager.identity.profile.CustomWebsite"
]["label"]
del item["type"]
contact_info["websites"] = websites
return contact_info
def get_profile(self, public_id=None, urn_id=None):
sleep(
random.randint(2, 5)
)
res = self.client.session.get(
f"{self.client.API_BASE_URL}/identity/profiles/{public_id or urn_id}/profileView"
)
data = res.json()
if data and "status" in data and data["status"] != 200:
self.logger.info("request failed: {}".format(data["message"]))
return {}
profile = data["profile"]
if "miniProfile" in profile:
if "picture" in profile["miniProfile"]:
profile["displayPictureUrl"] = profile["miniProfile"]["picture"][
"com.linkedin.common.VectorImage"
]["rootUrl"]
profile["profile_id"] = get_id_from_urn(profile["miniProfile"]["entityUrn"])
del profile["miniProfile"]
del profile["defaultLocale"]
del profile["supportedLocales"]
del profile["versionTag"]
del profile["showEducationOnProfileTopCard"]
experience = data["positionView"]["elements"]
for item in experience:
if "company" in item and "miniCompany" in item["company"]:
if "logo" in item["company"]["miniCompany"]:
logo = item["company"]["miniCompany"]["logo"].get(
"com.linkedin.common.VectorImage"
)
if logo:
item["companyLogoUrl"] = logo["rootUrl"]
del item["company"]["miniCompany"]
profile["experience"] = experience
skills = [item["name"] for item in data["skillView"]["elements"]]
profile["skills"] = skills
education = data["educationView"]["elements"]
for item in education:
if "school" in item:
if "logo" in item["school"]:
item["school"]["logoUrl"] = item["school"]["logo"][
"com.linkedin.common.VectorImage"
]["rootUrl"]
del item["school"]["logo"]
profile["education"] = education
return profile
def get_profile_connections(self, urn_id):
return self.search_people(connection_of=urn_id, network_depth="F")
def get_profile_networkinfo(self, urn_id):
sleep(
random.randint(2, 5)
)
res = self.client.session.get(
f"{self.client.API_BASE_URL}/identity/profiles/{urn_id}/networkinfo"
)
return res.json()
def get_company_updates(self, public_id=None, urn_id=None, max_results=None, results=[]):
sleep(
random.randint(2, 5)
)
params = {
"companyUniversalName": {public_id or urn_id},
"q": "companyFeedByUniversalName",
"moduleKey": "member-share",
"count": Linkedin._MAX_UPDATE_COUNT,
"start": len(results),
}
res = self.client.session.get(
f"{self.client.API_BASE_URL}/feed/updates", params=params
)
data = res.json()
if (
len(data["elements"]) == 0
or (max_results is not None and len(results) >= max_results)
or (max_results is not None and len(results) / max_results >= Linkedin._MAX_REPEATED_REQUESTS)
):
return results
results.extend(data["elements"])
self.logger.debug(f"results grew: {len(results)}")
return self.get_company_updates(public_id=public_id, urn_id=urn_id, results=results, max_results=max_results)
def get_profile_updates(self, public_id=None, urn_id=None, max_results=None, results=[]):
sleep(
random.randint(2, 5)
)
params = {
"profileId": {public_id or urn_id},
"q": "memberShareFeed",
"moduleKey": "member-share",
"count": Linkedin._MAX_UPDATE_COUNT,
"start": len(results),
}
res = self.client.session.get(
f"{self.client.API_BASE_URL}/feed/updates", params=params
)
data = res.json()
if (
len(data["elements"]) == 0
or (max_results is not None and len(results) >= max_results)
or (max_results is not None and len(results) / max_results >= Linkedin._MAX_REPEATED_REQUESTS)
):
return results
results.extend(data["elements"])
self.logger.debug(f"results grew: {len(results)}")
return self.get_profile_updates(public_id=public_id, urn_id=urn_id, results=results, max_results=max_results)
def get_current_profile_views(self):
res = self.client.session.get(
f"{self.client.API_BASE_URL}/identity/panels"
)
data = res.json()
return data['elements'][0]['value']['com.linkedin.voyager.identity.me.ProfileViewsByTimePanel']
def get_school(self, public_id):
sleep(
random.randint(2, 5)
)
params = {
"decoration": (
"""
(
autoGenerated,backgroundCoverImage,
companyEmployeesSearchPageUrl,companyPageUrl,confirmedLocations*,coverPhoto,dataVersion,description,
entityUrn,followingInfo,foundedOn,headquarter,jobSearchPageUrl,lcpTreatment,logo,name,type,overviewPhoto,
paidCompany,partnerCompanyUrl,partnerLogo,partnerLogoImage,rankForTopCompanies,salesNavigatorCompanyUrl,
school,showcase,staffCount,staffCountRange,staffingCompany,topCompaniesListName,universalName,url,
companyIndustries*,industries,specialities,
acquirerCompany~(entityUrn,logo,name,industries,followingInfo,url,paidCompany,universalName),
affiliatedCompanies*~(entityUrn,logo,name,industries,followingInfo,url,paidCompany,universalName),
groups*~(entityUrn,largeLogo,groupName,memberCount,websiteUrl,url),
showcasePages*~(entityUrn,logo,name,industries,followingInfo,url,description,universalName)
)
"""
),
"q": "universalName",
"universalName": public_id,
}
res = self.client.session.get(
f"{self.client.API_BASE_URL}/organization/companies", params=params
)
data = res.json()
if data and "status" in data and data["status"] != 200:
self.logger.info("request failed: {}".format(data["message"]))
return {}
school = data["elements"][0]
return school
def get_similar_companies(self, public_id):
sleep(
random.randint(2, 5)
)
res = self.client.session.get(
f"{self.client.API_BASE_URL}/organization/companies?count={Linkedin._MAX_SEARCH_COUNT}&companyUniversalName={public_id}&q=similarCompanies&start=0&decorationId=com.linkedin.voyager.deco.organization.web.WebSimilarCompanyCardWithRelevanceReason-3"
)
data = res.json()
return data
def get_company(self, public_id):
sleep(
random.randint(2, 5)
)
params = {
"decoration": (
"""
(
affiliatedCompaniesWithEmployeesRollup,affiliatedCompaniesWithJobsRollup,articlePermalinkForTopCompanies,
autoGenerated,backgroundCoverImage,companyEmployeesSearchPageUrl,
companyPageUrl,confirmedLocations*,coverPhoto,dataVersion,description,entityUrn,followingInfo,
foundedOn,headquarter,jobSearchPageUrl,lcpTreatment,logo,name,type,overviewPhoto,paidCompany,
partnerCompanyUrl,partnerLogo,partnerLogoImage,permissions,rankForTopCompanies,
salesNavigatorCompanyUrl,school,showcase,staffCount,staffCountRange,staffingCompany,
topCompaniesListName,universalName,url,companyIndustries*,industries,specialities,
acquirerCompany~(entityUrn,logo,name,industries,followingInfo,url,paidCompany,universalName),
affiliatedCompanies*~(entityUrn,logo,name,industries,followingInfo,url,paidCompany,universalName),
groups*~(entityUrn,largeLogo,groupName,memberCount,websiteUrl,url),
showcasePages*~(entityUrn,logo,name,industries,followingInfo,url,description,universalName)
)
"""
),
"q": "universalName",
"universalName": public_id,
}
res = self.client.session.get(
f"{self.client.API_BASE_URL}/organization/companies", params=params
)
data = res.json()
if data and "status" in data and data["status"] != 200:
self.logger.info("request failed: {}".format(data["message"]))
return {}
company = data["elements"][0]
return company
def get_conversation_details(self, profile_urn_id):
res = self.client.session.get(
f"{self.client.API_BASE_URL}/messaging/conversations?\
keyVersion=LEGACY_INBOX&q=participants&recipients=List({profile_urn_id})"
)
data = res.json()
item = data["elements"][0]
item["id"] = get_id_from_urn(item["entityUrn"])
return item
def get_conversations(self):
params = {"keyVersion": "LEGACY_INBOX"}
res = self.client.session.get(
f"{self.client.API_BASE_URL}/messaging/conversations", params=params
)
return res.json()
def get_conversation(self, conversation_urn_id):
res = self.client.session.get(
f"{self.client.API_BASE_URL}/messaging/conversations/{conversation_urn_id}/events"
)
return res.json()
def send_message(self, conversation_urn_id, message_body):
params = {"action": "create"}
payload = json.dumps(
{
"eventCreate": {
"value": {
"com.linkedin.voyager.messaging.create.MessageCreate": {
"body": message_body,
"attachments": [],
"attributedBody": {"text": message_body, "attributes": []},
"mediaAttachments": [],
}
}
}
}
)
res = self.client.session.post(
f"{self.client.API_BASE_URL}/messaging/conversations/{conversation_urn_id}/events",
params=params,
data=payload,
)
return res.status_code == 201
| true | true |
790bd849eabb113e5268e23dadba301216d44dda | 24 | py | Python | views/stations/__init__.py | atzorvas/droughtmeteo | 265282ea5a333dd303747df6b13155789dfc938e | [
"MIT"
] | null | null | null | views/stations/__init__.py | atzorvas/droughtmeteo | 265282ea5a333dd303747df6b13155789dfc938e | [
"MIT"
] | null | null | null | views/stations/__init__.py | atzorvas/droughtmeteo | 265282ea5a333dd303747df6b13155789dfc938e | [
"MIT"
] | null | null | null | __author__ = 'atzorvas'
| 12 | 23 | 0.75 | __author__ = 'atzorvas'
| true | true |
790bd893e8c7366add01d0ac757b05d1c2bdbefa | 159 | py | Python | python/testData/refactoring/makeFunctionTopLevel/localFunctionSimple.after.py | jnthn/intellij-community | 8fa7c8a3ace62400c838e0d5926a7be106aa8557 | [
"Apache-2.0"
] | 2 | 2019-04-28T07:48:50.000Z | 2020-12-11T14:18:08.000Z | python/testData/refactoring/makeFunctionTopLevel/localFunctionSimple.after.py | Cyril-lamirand/intellij-community | 60ab6c61b82fc761dd68363eca7d9d69663cfa39 | [
"Apache-2.0"
] | 173 | 2018-07-05T13:59:39.000Z | 2018-08-09T01:12:03.000Z | python/testData/refactoring/makeFunctionTopLevel/localFunctionSimple.after.py | Cyril-lamirand/intellij-community | 60ab6c61b82fc761dd68363eca7d9d69663cfa39 | [
"Apache-2.0"
] | 2 | 2020-03-15T08:57:37.000Z | 2020-04-07T04:48:14.000Z | global_var = 'spam'
def enclosing(p1, p2):
x = 42
local(p1, x, 'foo')
def local(p1, x, p):
def nested():
print(p, x)
print(p1, p) | 11.357143 | 23 | 0.503145 | global_var = 'spam'
def enclosing(p1, p2):
x = 42
local(p1, x, 'foo')
def local(p1, x, p):
def nested():
print(p, x)
print(p1, p) | true | true |
790bd8d07d28713b742fcfa0ad6e9fe885cbc3fd | 4,051 | py | Python | data/modules/graphic/two_D/player_gui/health.py | Sheidaas/gamee | 434db4648e1719a648b8784f201b03b4c8e243c3 | [
"CC-BY-3.0"
] | null | null | null | data/modules/graphic/two_D/player_gui/health.py | Sheidaas/gamee | 434db4648e1719a648b8784f201b03b4c8e243c3 | [
"CC-BY-3.0"
] | null | null | null | data/modules/graphic/two_D/player_gui/health.py | Sheidaas/gamee | 434db4648e1719a648b8784f201b03b4c8e243c3 | [
"CC-BY-3.0"
] | null | null | null | import pygame
from .gui_abstract_object import GuiAbstractObject
class Health(GuiAbstractObject):
def __init__(self, x, y, player, screen):
super().__init__()
self.player = player
self.position = (x, y, 400, 40)
self.rects_pos = {
'main': ((), ()),
'black_hp': ((), ()),
'hp': ((), ()),
}
self.string = {
'hp': (None, ())
}
self.screen = screen
def create(self):
position = (self.position[0] * self.screen.engine.settings.graphic['screen']['resolution_scale'][0],
self.position[1] * self.screen.engine.settings.graphic['screen']['resolution_scale'][1],
self.position[2] * self.screen.engine.settings.graphic['screen']['resolution_scale'][0],
self.position[3] * self.screen.engine.settings.graphic['screen']['resolution_scale'][1])
self.rects_pos['main'] = (position, (255, 255, 255))
pygame.draw.rect(self.screen.screen, self.rects_pos['main'][1], self.rects_pos['main'][0])
position = ((self.position[0] + 10) * self.screen.engine.settings.graphic['screen']['resolution_scale'][0],
(self.position[1] + 10) * self.screen.engine.settings.graphic['screen']['resolution_scale'][1],
380 * self.screen.engine.settings.graphic['screen']['resolution_scale'][0],
20 * self.screen.engine.settings.graphic['screen']['resolution_scale'][1])
self.rects_pos['black_hp'] = (position, (0, 0, 0))
pygame.draw.rect(self.screen.screen, self.rects_pos['black_hp'][1], self.rects_pos['black_hp'][0])
text = str(self.player.statistics.health_points) + '/' + str(self.player.statistics.max_health_points)
self.string['hp'] = (text, position)
health_percent = (self.player.statistics.health_points / self.player.statistics.max_health_points) * 100
self.render_text(self.string['hp'][1][0], self.string['hp'][1][2],
self.string['hp'][1][1], self.string['hp'][1][3], self.string['hp'][0])
position = ((self.position[0] + 10) * self.screen.engine.settings.graphic['screen']['resolution_scale'][0],
(self.position[1] + 30) * self.screen.engine.settings.graphic['screen']['resolution_scale'][1],
((380 / 100) * health_percent) * self.screen.engine.settings.graphic['screen']['resolution_scale'][0],
20 * self.screen.engine.settings.graphic['screen']['resolution_scale'][1])
self.rects_pos['hp'] = (position, (200, 0, 0))
pygame.draw.rect(self.screen.screen, (200, 0, 0), position)
def render_text(self, x1, x2, y1, y2, string):
x = x2 - x1
y = y2 - y1
x /= 2
y /= 2
x += x1
y += y1
string = self.screen.font.render(string, self.screen.engine.settings.graphic['screen']['antialias'], (0, 0, 0))
#self.screen.screen.blit(string, (x, y))
def render(self):
pygame.draw.rect(self.screen.screen, self.rects_pos['main'][1], self.rects_pos['main'][0])
pygame.draw.rect(self.screen.screen, self.rects_pos['black_hp'][1], self.rects_pos['black_hp'][0])
self.render_text(self.string['hp'][1][0], self.string['hp'][1][2],
self.string['hp'][1][1], self.string['hp'][1][3], self.string['hp'][0])
health_percent = (self.player.statistics.health_points / self.player.statistics.max_health_points) * 100
position = ((self.position[0] + 10) * self.screen.engine.settings.graphic['screen']['resolution_scale'][0],
(self.position[1] + 10) * self.screen.engine.settings.graphic['screen']['resolution_scale'][1],
((380 / 100) * health_percent) * self.screen.engine.settings.graphic['screen']['resolution_scale'][0],
20 * self.screen.engine.settings.graphic['screen']['resolution_scale'][1])
pygame.draw.rect(self.screen.screen, (200, 0, 0), position)
| 52.61039 | 122 | 0.59294 | import pygame
from .gui_abstract_object import GuiAbstractObject
class Health(GuiAbstractObject):
def __init__(self, x, y, player, screen):
super().__init__()
self.player = player
self.position = (x, y, 400, 40)
self.rects_pos = {
'main': ((), ()),
'black_hp': ((), ()),
'hp': ((), ()),
}
self.string = {
'hp': (None, ())
}
self.screen = screen
def create(self):
position = (self.position[0] * self.screen.engine.settings.graphic['screen']['resolution_scale'][0],
self.position[1] * self.screen.engine.settings.graphic['screen']['resolution_scale'][1],
self.position[2] * self.screen.engine.settings.graphic['screen']['resolution_scale'][0],
self.position[3] * self.screen.engine.settings.graphic['screen']['resolution_scale'][1])
self.rects_pos['main'] = (position, (255, 255, 255))
pygame.draw.rect(self.screen.screen, self.rects_pos['main'][1], self.rects_pos['main'][0])
position = ((self.position[0] + 10) * self.screen.engine.settings.graphic['screen']['resolution_scale'][0],
(self.position[1] + 10) * self.screen.engine.settings.graphic['screen']['resolution_scale'][1],
380 * self.screen.engine.settings.graphic['screen']['resolution_scale'][0],
20 * self.screen.engine.settings.graphic['screen']['resolution_scale'][1])
self.rects_pos['black_hp'] = (position, (0, 0, 0))
pygame.draw.rect(self.screen.screen, self.rects_pos['black_hp'][1], self.rects_pos['black_hp'][0])
text = str(self.player.statistics.health_points) + '/' + str(self.player.statistics.max_health_points)
self.string['hp'] = (text, position)
health_percent = (self.player.statistics.health_points / self.player.statistics.max_health_points) * 100
self.render_text(self.string['hp'][1][0], self.string['hp'][1][2],
self.string['hp'][1][1], self.string['hp'][1][3], self.string['hp'][0])
position = ((self.position[0] + 10) * self.screen.engine.settings.graphic['screen']['resolution_scale'][0],
(self.position[1] + 30) * self.screen.engine.settings.graphic['screen']['resolution_scale'][1],
((380 / 100) * health_percent) * self.screen.engine.settings.graphic['screen']['resolution_scale'][0],
20 * self.screen.engine.settings.graphic['screen']['resolution_scale'][1])
self.rects_pos['hp'] = (position, (200, 0, 0))
pygame.draw.rect(self.screen.screen, (200, 0, 0), position)
def render_text(self, x1, x2, y1, y2, string):
x = x2 - x1
y = y2 - y1
x /= 2
y /= 2
x += x1
y += y1
string = self.screen.font.render(string, self.screen.engine.settings.graphic['screen']['antialias'], (0, 0, 0))
def render(self):
pygame.draw.rect(self.screen.screen, self.rects_pos['main'][1], self.rects_pos['main'][0])
pygame.draw.rect(self.screen.screen, self.rects_pos['black_hp'][1], self.rects_pos['black_hp'][0])
self.render_text(self.string['hp'][1][0], self.string['hp'][1][2],
self.string['hp'][1][1], self.string['hp'][1][3], self.string['hp'][0])
health_percent = (self.player.statistics.health_points / self.player.statistics.max_health_points) * 100
position = ((self.position[0] + 10) * self.screen.engine.settings.graphic['screen']['resolution_scale'][0],
(self.position[1] + 10) * self.screen.engine.settings.graphic['screen']['resolution_scale'][1],
((380 / 100) * health_percent) * self.screen.engine.settings.graphic['screen']['resolution_scale'][0],
20 * self.screen.engine.settings.graphic['screen']['resolution_scale'][1])
pygame.draw.rect(self.screen.screen, (200, 0, 0), position)
| true | true |
790bd96b30fe676462081306a479a799d322e3be | 1,192 | py | Python | app/api/v1/models/bucketlist.py | johnseremba/bucket-list | 079b8bd0c775240aec8b417731643b27a3bb3cc7 | [
"MIT"
] | 1 | 2017-07-18T18:03:28.000Z | 2017-07-18T18:03:28.000Z | app/api/v1/models/bucketlist.py | SerryJohns/bucket-list | 079b8bd0c775240aec8b417731643b27a3bb3cc7 | [
"MIT"
] | 7 | 2017-07-18T10:16:44.000Z | 2019-10-18T17:02:56.000Z | app/api/v1/models/bucketlist.py | johnseremba/bucket-list | 079b8bd0c775240aec8b417731643b27a3bb3cc7 | [
"MIT"
] | 1 | 2017-06-29T08:03:36.000Z | 2017-06-29T08:03:36.000Z | import datetime
from app import db
class BucketList(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(100), unique=True)
description = db.Column(db.Text, nullable=True)
interests = db.Column(db.String(120), nullable=True)
date_created = db.Column(db.DateTime, default=datetime.datetime.utcnow())
date_modified = db.Column(db.DateTime)
created_by = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
items = db.relationship('Item', backref='bucket_list_items', lazy='dynamic')
def __repr__(self):
return "<Bucketlist {}>".format(self.name)
class Item(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(100), unique=True)
description = db.Column(db.Text)
status = db.Column(db.Text)
date_accomplished = db.Column(db.DateTime)
date_created = db.Column(db.DateTime, default=datetime.datetime.utcnow())
date_modified = db.Column(db.DateTime)
bucketlists = db.Column(db.Integer, db.ForeignKey('bucket_list.id'), nullable=False)
def __repr__(self):
return "<Items {}>".format(self.name)
| 38.451613 | 88 | 0.703859 | import datetime
from app import db
class BucketList(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(100), unique=True)
description = db.Column(db.Text, nullable=True)
interests = db.Column(db.String(120), nullable=True)
date_created = db.Column(db.DateTime, default=datetime.datetime.utcnow())
date_modified = db.Column(db.DateTime)
created_by = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
items = db.relationship('Item', backref='bucket_list_items', lazy='dynamic')
def __repr__(self):
return "<Bucketlist {}>".format(self.name)
class Item(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(100), unique=True)
description = db.Column(db.Text)
status = db.Column(db.Text)
date_accomplished = db.Column(db.DateTime)
date_created = db.Column(db.DateTime, default=datetime.datetime.utcnow())
date_modified = db.Column(db.DateTime)
bucketlists = db.Column(db.Integer, db.ForeignKey('bucket_list.id'), nullable=False)
def __repr__(self):
return "<Items {}>".format(self.name)
| true | true |
790bd993fa52900079da534f0eddbaf962ef1c89 | 16,037 | py | Python | desktop/libs/metadata/src/metadata/optimizer_api.py | maulikjs/hue | 59ac879b55bb6fb26ecb4e85f4c70836fc21173f | [
"Apache-2.0"
] | 1 | 2020-05-17T06:40:33.000Z | 2020-05-17T06:40:33.000Z | desktop/libs/metadata/src/metadata/optimizer_api.py | zks888/hue | 93a8c370713e70b216c428caa2f75185ef809deb | [
"Apache-2.0"
] | 4 | 2021-03-11T04:02:00.000Z | 2022-03-27T08:31:56.000Z | desktop/libs/metadata/src/metadata/optimizer_api.py | zks888/hue | 93a8c370713e70b216c428caa2f75185ef809deb | [
"Apache-2.0"
] | 1 | 2017-11-09T09:31:28.000Z | 2017-11-09T09:31:28.000Z | #!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you 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 base64
import json
import logging
import struct
from django.http import Http404
from django.utils.translation import ugettext as _
from django.views.decorators.http import require_POST
from desktop.lib.django_util import JsonResponse
from desktop.lib.i18n import force_unicode
from desktop.models import Document2
from libsentry.privilege_checker import MissingSentryPrivilegeException
from notebook.api import _get_statement
from notebook.models import Notebook
from metadata.optimizer_client import OptimizerApi, NavOptException, _get_table_name, _clean_query
from metadata.conf import OPTIMIZER
from desktop.auth.backend import is_admin
LOG = logging.getLogger(__name__)
try:
from beeswax.api import get_table_stats
from beeswax.design import hql_query
from metastore.views import _get_db
except ImportError, e:
LOG.warn("Hive lib not enabled")
def error_handler(view_fn):
def decorator(*args, **kwargs):
try:
return view_fn(*args, **kwargs)
except Http404, e:
raise e
except NavOptException, e:
LOG.exception(e)
response = {
'status': -1,
'message': e.message
}
except MissingSentryPrivilegeException, e:
LOG.exception(e)
response = {
'status': -1,
'message': 'Missing privileges for %s' % force_unicode(str(e))
}
except Exception, e:
LOG.exception(e)
response = {
'status': -1,
'message': force_unicode(str(e))
}
return JsonResponse(response, status=500)
return decorator
@require_POST
@error_handler
def get_tenant(request):
response = {'status': -1}
cluster_id = request.POST.get('cluster_id')
api = OptimizerApi(request.user)
data = api.get_tenant(cluster_id=cluster_id)
if data:
response['status'] = 0
response['data'] = data['tenant']
else:
response['message'] = 'Optimizer: %s' % data['details']
return JsonResponse(response)
@require_POST
@error_handler
def top_tables(request):
response = {'status': -1}
database = request.POST.get('database', 'default')
limit = request.POST.get('len', 1000)
api = OptimizerApi(user=request.user)
data = api.top_tables(database_name=database, page_size=limit)
tables = [{
'eid': table['eid'],
'database': _get_table_name(table['name'])['database'],
'name': _get_table_name(table['name'])['table'],
'popularity': table['workloadPercent'],
'column_count': table['columnCount'],
'patternCount': table['patternCount'],
'total': table['total'],
'is_fact': table['type'] != 'Dimension'
} for table in data['results']
]
response['top_tables'] = tables
response['status'] = 0
return JsonResponse(response)
@require_POST
@error_handler
def table_details(request):
response = {'status': -1}
database_name = request.POST.get('databaseName')
table_name = request.POST.get('tableName')
api = OptimizerApi(request.user)
data = api.table_details(database_name=database_name, table_name=table_name)
if data:
response['status'] = 0
response['details'] = data
else:
response['message'] = 'Optimizer: %s' % data['details']
return JsonResponse(response)
@require_POST
@error_handler
def query_compatibility(request):
response = {'status': -1}
source_platform = request.POST.get('sourcePlatform')
target_platform = request.POST.get('targetPlatform')
query = request.POST.get('query')
api = OptimizerApi(request.user)
data = api.query_compatibility(source_platform=source_platform, target_platform=target_platform, query=query)
if data:
response['status'] = 0
response['query_compatibility'] = data
else:
response['message'] = 'Optimizer: %s' % data
return JsonResponse(response)
@require_POST
@error_handler
def query_risk(request):
response = {'status': -1}
query = json.loads(request.POST.get('query'))
source_platform = request.POST.get('sourcePlatform')
db_name = request.POST.get('dbName')
api = OptimizerApi(request.user)
data = api.query_risk(query=query, source_platform=source_platform, db_name=db_name)
if data:
response['status'] = 0
response['query_risk'] = data
else:
response['message'] = 'Optimizer: %s' % data
return JsonResponse(response)
@require_POST
@error_handler
def similar_queries(request):
response = {'status': -1}
source_platform = request.POST.get('sourcePlatform')
query = json.loads(request.POST.get('query'))
api = OptimizerApi(request.user)
data = api.similar_queries(source_platform=source_platform, query=query)
if data:
response['status'] = 0
response['similar_queries'] = data
else:
response['message'] = 'Optimizer: %s' % data
return JsonResponse(response)
@require_POST
@error_handler
def top_filters(request):
response = {'status': -1}
db_tables = json.loads(request.POST.get('dbTables'), '[]')
column_name = request.POST.get('columnName') # Unused
api = OptimizerApi(request.user)
data = api.top_filters(db_tables=db_tables)
if data:
response['status'] = 0
response['values'] = data['results']
else:
response['message'] = 'Optimizer: %s' % data
return JsonResponse(response)
@require_POST
@error_handler
def top_joins(request):
response = {'status': -1}
db_tables = json.loads(request.POST.get('dbTables'), '[]')
api = OptimizerApi(request.user)
data = api.top_joins(db_tables=db_tables)
if data:
response['status'] = 0
response['values'] = data['results']
else:
response['message'] = 'Optimizer: %s' % data
return JsonResponse(response)
@require_POST
@error_handler
def top_aggs(request):
response = {'status': -1}
db_tables = json.loads(request.POST.get('dbTables'), '[]')
api = OptimizerApi(request.user)
data = api.top_aggs(db_tables=db_tables)
if data:
response['status'] = 0
response['values'] = data['results']
else:
response['message'] = 'Optimizer: %s' % data
return JsonResponse(response)
@require_POST
@error_handler
def top_databases(request):
response = {'status': -1}
api = OptimizerApi(request.user)
data = api.top_databases()
if data:
response['status'] = 0
response['values'] = data['results']
else:
response['message'] = 'Optimizer: %s' % data
return JsonResponse(response)
@require_POST
@error_handler
def top_columns(request):
response = {'status': -1}
db_tables = json.loads(request.POST.get('dbTables'), '[]')
api = OptimizerApi(request.user)
data = api.top_columns(db_tables=db_tables)
if data:
response['status'] = 0
response['values'] = data
else:
response['message'] = 'Optimizer: %s' % data
return JsonResponse(response)
def _convert_queries(queries_data):
queries = []
for query_data in queries_data:
try:
snippet = query_data['snippets'][0]
if 'guid' in snippet['result']['handle']: # Not failed query
original_query_id = '%s:%s' % struct.unpack(b"QQ", base64.decodestring(snippet['result']['handle']['guid'])) # unpack_guid uses '%016x:%016x' while optmizer api uses '%s:%s'.
execution_time = snippet['result']['executionTime'] * 100 if snippet['status'] in ('available', 'expired') else -1
statement = _clean_query(_get_statement(query_data))
queries.append((original_query_id, execution_time, statement, snippet.get('database', 'default').strip()))
except Exception, e:
LOG.warning('Skipping upload of %s: %s' % (query_data['uuid'], e))
return queries
@require_POST
@error_handler
def upload_history(request):
response = {'status': -1}
if is_admin(request.user):
api = OptimizerApi(request.user)
histories = []
upload_stats = {}
if request.POST.get('sourcePlatform'):
n = min(request.POST.get('n', OPTIMIZER.QUERY_HISTORY_UPLOAD_LIMIT.get()))
source_platform = request.POST.get('sourcePlatform', 'hive')
histories = [(source_platform, Document2.objects.get_history(doc_type='query-%s' % source_platform, user=request.user)[:n])]
elif OPTIMIZER.QUERY_HISTORY_UPLOAD_LIMIT.get() > 0:
histories = [
(source_platform, Document2.objects.filter(type='query-%s' % source_platform, is_history=True, is_managed=False, is_trashed=False).order_by('-last_modified')[:OPTIMIZER.QUERY_HISTORY_UPLOAD_LIMIT.get()])
for source_platform in ['hive', 'impala']
]
for source_platform, history in histories:
queries = _convert_queries([Notebook(document=doc).get_data() for doc in history])
upload_stats[source_platform] = api.upload(data=queries, data_type='queries', source_platform=source_platform)
response['upload_history'] = upload_stats
response['status'] = 0
else:
response['message'] = _('Query history upload requires Admin privileges or feature is disabled.')
return JsonResponse(response)
@require_POST
@error_handler
def upload_query(request):
response = {'status': -1}
source_platform = request.POST.get('sourcePlatform', 'default')
query_id = request.POST.get('query_id')
if OPTIMIZER.AUTO_UPLOAD_QUERIES.get() and source_platform in ('hive', 'impala') and query_id:
try:
doc = Document2.objects.document(request.user, doc_id=query_id)
query_data = Notebook(document=doc).get_data()
queries = _convert_queries([query_data])
source_platform = query_data['snippets'][0]['type']
api = OptimizerApi(request.user)
response['query_upload'] = api.upload(data=queries, data_type='queries', source_platform=source_platform)
except Document2.DoesNotExist:
response['query_upload'] = _('Skipped as task query')
else:
response['query_upload'] = _('Skipped')
response['status'] = 0
return JsonResponse(response)
@require_POST
@error_handler
def upload_table_stats(request):
response = {'status': -1}
db_tables = json.loads(request.POST.get('db_tables'), '[]')
source_platform = json.loads(request.POST.get('sourcePlatform', '"hive"'))
with_ddl = json.loads(request.POST.get('with_ddl', 'false'))
with_table_stats = json.loads(request.POST.get('with_table', 'false'))
with_columns_stats = json.loads(request.POST.get('with_columns', 'false'))
table_ddls = []
table_stats = []
column_stats = []
if not OPTIMIZER.AUTO_UPLOAD_DDL.get():
with_ddl = False
if not OPTIMIZER.AUTO_UPLOAD_STATS.get():
with_table_stats = with_columns_stats = False
for db_table in db_tables:
path = _get_table_name(db_table)
try:
if with_ddl:
db = _get_db(request.user, source_type=source_platform)
query = hql_query('SHOW CREATE TABLE `%(database)s`.`%(table)s`' % path)
handle = db.execute_and_wait(query, timeout_sec=5.0)
if handle:
result = db.fetch(handle, rows=5000)
db.close(handle)
table_ddls.append((0, 0, ' '.join([row[0] for row in result.rows()]), path['database']))
if with_table_stats:
mock_request = MockRequest(user=request.user, source_platform=source_platform)
full_table_stats = json.loads(get_table_stats(mock_request, database=path['database'], table=path['table']).content)
stats = dict((stat['data_type'], stat['comment']) for stat in full_table_stats['stats'])
table_stats.append({
'table_name': '%(database)s.%(table)s' % path, # DB Prefix
'num_rows': stats.get('numRows', -1),
'last_modified_time': stats.get('transient_lastDdlTime', -1),
'total_size': stats.get('totalSize', -1),
'raw_data_size': stats.get('rawDataSize', -1),
'num_files': stats.get('numFiles', -1),
'num_partitions': stats.get('numPartitions', -1),
# bytes_cached
# cache_replication
# format
})
if with_columns_stats:
if source_platform == 'impala':
colum_stats = json.loads(get_table_stats(mock_request, database=path['database'], table=path['table'], column=-1).content)['stats']
else:
colum_stats = [
json.loads(get_table_stats(mock_request, database=path['database'], table=path['table'], column=col).content)['stats']
for col in full_table_stats['columns'][:25]
]
raw_column_stats = [dict([(key, val if val is not None else '') for col_stat in col for key, val in col_stat.iteritems()]) for col in colum_stats]
for col_stats in raw_column_stats:
column_stats.append({
'table_name': '%(database)s.%(table)s' % path, # DB Prefix
'column_name': col_stats['col_name'],
'data_type': col_stats['data_type'],
"num_distinct": int(col_stats.get('distinct_count')) if col_stats.get('distinct_count') != '' else -1,
"num_nulls": int(col_stats['num_nulls']) if col_stats['num_nulls'] != '' else -1,
"avg_col_len": int(float(col_stats['avg_col_len'])) if col_stats['avg_col_len'] != '' else -1,
"max_size": int(float(col_stats['max_col_len'])) if col_stats['max_col_len'] != '' else -1,
"min": col_stats['min'] if col_stats.get('min', '') != '' else -1,
"max": col_stats['max'] if col_stats.get('max', '') != '' else -1,
"num_trues": col_stats['num_trues'] if col_stats.get('num_trues', '') != '' else -1,
"num_falses": col_stats['num_falses'] if col_stats.get('num_falses', '') != '' else -1,
})
except Exception, e:
LOG.exception('Skipping upload of %s: %s' % (db_table, e))
api = OptimizerApi(request.user)
response['status'] = 0
if table_stats:
response['upload_table_stats'] = api.upload(data=table_stats, data_type='table_stats', source_platform=source_platform)
response['upload_table_stats_status'] = 0 if response['upload_table_stats']['status']['state'] in ('WAITING', 'FINISHED', 'IN_PROGRESS') else -1
response['status'] = response['upload_table_stats_status']
if column_stats:
response['upload_cols_stats'] = api.upload(data=column_stats, data_type='cols_stats', source_platform=source_platform)
response['upload_cols_stats_status'] = response['status'] if response['upload_cols_stats']['status']['state'] in ('WAITING', 'FINISHED', 'IN_PROGRESS') else -1
if response['upload_cols_stats_status'] != 0:
response['status'] = response['upload_cols_stats_status']
if table_ddls:
response['upload_table_ddl'] = api.upload(data=table_ddls, data_type='queries', source_platform=source_platform)
response['upload_table_ddl_status'] = response['status'] if response['upload_table_ddl']['status']['state'] in ('WAITING', 'FINISHED', 'IN_PROGRESS') else -1
if response['upload_table_ddl_status'] != 0:
response['status'] = response['upload_table_ddl_status']
return JsonResponse(response)
@require_POST
@error_handler
def upload_status(request):
response = {'status': -1}
workload_id = request.POST.get('workloadId')
api = OptimizerApi(request.user)
response['upload_status'] = api.upload_status(workload_id=workload_id)
response['status'] = 0
return JsonResponse(response)
class MockRequest():
def __init__(self, user, source_platform):
self.user = user
self.path = '/%s/' % source_platform if source_platform != 'hive' else 'beeswax'
| 31.506876 | 211 | 0.685477 |
import base64
import json
import logging
import struct
from django.http import Http404
from django.utils.translation import ugettext as _
from django.views.decorators.http import require_POST
from desktop.lib.django_util import JsonResponse
from desktop.lib.i18n import force_unicode
from desktop.models import Document2
from libsentry.privilege_checker import MissingSentryPrivilegeException
from notebook.api import _get_statement
from notebook.models import Notebook
from metadata.optimizer_client import OptimizerApi, NavOptException, _get_table_name, _clean_query
from metadata.conf import OPTIMIZER
from desktop.auth.backend import is_admin
LOG = logging.getLogger(__name__)
try:
from beeswax.api import get_table_stats
from beeswax.design import hql_query
from metastore.views import _get_db
except ImportError, e:
LOG.warn("Hive lib not enabled")
def error_handler(view_fn):
def decorator(*args, **kwargs):
try:
return view_fn(*args, **kwargs)
except Http404, e:
raise e
except NavOptException, e:
LOG.exception(e)
response = {
'status': -1,
'message': e.message
}
except MissingSentryPrivilegeException, e:
LOG.exception(e)
response = {
'status': -1,
'message': 'Missing privileges for %s' % force_unicode(str(e))
}
except Exception, e:
LOG.exception(e)
response = {
'status': -1,
'message': force_unicode(str(e))
}
return JsonResponse(response, status=500)
return decorator
@require_POST
@error_handler
def get_tenant(request):
response = {'status': -1}
cluster_id = request.POST.get('cluster_id')
api = OptimizerApi(request.user)
data = api.get_tenant(cluster_id=cluster_id)
if data:
response['status'] = 0
response['data'] = data['tenant']
else:
response['message'] = 'Optimizer: %s' % data['details']
return JsonResponse(response)
@require_POST
@error_handler
def top_tables(request):
response = {'status': -1}
database = request.POST.get('database', 'default')
limit = request.POST.get('len', 1000)
api = OptimizerApi(user=request.user)
data = api.top_tables(database_name=database, page_size=limit)
tables = [{
'eid': table['eid'],
'database': _get_table_name(table['name'])['database'],
'name': _get_table_name(table['name'])['table'],
'popularity': table['workloadPercent'],
'column_count': table['columnCount'],
'patternCount': table['patternCount'],
'total': table['total'],
'is_fact': table['type'] != 'Dimension'
} for table in data['results']
]
response['top_tables'] = tables
response['status'] = 0
return JsonResponse(response)
@require_POST
@error_handler
def table_details(request):
response = {'status': -1}
database_name = request.POST.get('databaseName')
table_name = request.POST.get('tableName')
api = OptimizerApi(request.user)
data = api.table_details(database_name=database_name, table_name=table_name)
if data:
response['status'] = 0
response['details'] = data
else:
response['message'] = 'Optimizer: %s' % data['details']
return JsonResponse(response)
@require_POST
@error_handler
def query_compatibility(request):
response = {'status': -1}
source_platform = request.POST.get('sourcePlatform')
target_platform = request.POST.get('targetPlatform')
query = request.POST.get('query')
api = OptimizerApi(request.user)
data = api.query_compatibility(source_platform=source_platform, target_platform=target_platform, query=query)
if data:
response['status'] = 0
response['query_compatibility'] = data
else:
response['message'] = 'Optimizer: %s' % data
return JsonResponse(response)
@require_POST
@error_handler
def query_risk(request):
response = {'status': -1}
query = json.loads(request.POST.get('query'))
source_platform = request.POST.get('sourcePlatform')
db_name = request.POST.get('dbName')
api = OptimizerApi(request.user)
data = api.query_risk(query=query, source_platform=source_platform, db_name=db_name)
if data:
response['status'] = 0
response['query_risk'] = data
else:
response['message'] = 'Optimizer: %s' % data
return JsonResponse(response)
@require_POST
@error_handler
def similar_queries(request):
response = {'status': -1}
source_platform = request.POST.get('sourcePlatform')
query = json.loads(request.POST.get('query'))
api = OptimizerApi(request.user)
data = api.similar_queries(source_platform=source_platform, query=query)
if data:
response['status'] = 0
response['similar_queries'] = data
else:
response['message'] = 'Optimizer: %s' % data
return JsonResponse(response)
@require_POST
@error_handler
def top_filters(request):
response = {'status': -1}
db_tables = json.loads(request.POST.get('dbTables'), '[]')
column_name = request.POST.get('columnName')
api = OptimizerApi(request.user)
data = api.top_filters(db_tables=db_tables)
if data:
response['status'] = 0
response['values'] = data['results']
else:
response['message'] = 'Optimizer: %s' % data
return JsonResponse(response)
@require_POST
@error_handler
def top_joins(request):
response = {'status': -1}
db_tables = json.loads(request.POST.get('dbTables'), '[]')
api = OptimizerApi(request.user)
data = api.top_joins(db_tables=db_tables)
if data:
response['status'] = 0
response['values'] = data['results']
else:
response['message'] = 'Optimizer: %s' % data
return JsonResponse(response)
@require_POST
@error_handler
def top_aggs(request):
response = {'status': -1}
db_tables = json.loads(request.POST.get('dbTables'), '[]')
api = OptimizerApi(request.user)
data = api.top_aggs(db_tables=db_tables)
if data:
response['status'] = 0
response['values'] = data['results']
else:
response['message'] = 'Optimizer: %s' % data
return JsonResponse(response)
@require_POST
@error_handler
def top_databases(request):
response = {'status': -1}
api = OptimizerApi(request.user)
data = api.top_databases()
if data:
response['status'] = 0
response['values'] = data['results']
else:
response['message'] = 'Optimizer: %s' % data
return JsonResponse(response)
@require_POST
@error_handler
def top_columns(request):
response = {'status': -1}
db_tables = json.loads(request.POST.get('dbTables'), '[]')
api = OptimizerApi(request.user)
data = api.top_columns(db_tables=db_tables)
if data:
response['status'] = 0
response['values'] = data
else:
response['message'] = 'Optimizer: %s' % data
return JsonResponse(response)
def _convert_queries(queries_data):
queries = []
for query_data in queries_data:
try:
snippet = query_data['snippets'][0]
if 'guid' in snippet['result']['handle']:
original_query_id = '%s:%s' % struct.unpack(b"QQ", base64.decodestring(snippet['result']['handle']['guid']))
execution_time = snippet['result']['executionTime'] * 100 if snippet['status'] in ('available', 'expired') else -1
statement = _clean_query(_get_statement(query_data))
queries.append((original_query_id, execution_time, statement, snippet.get('database', 'default').strip()))
except Exception, e:
LOG.warning('Skipping upload of %s: %s' % (query_data['uuid'], e))
return queries
@require_POST
@error_handler
def upload_history(request):
response = {'status': -1}
if is_admin(request.user):
api = OptimizerApi(request.user)
histories = []
upload_stats = {}
if request.POST.get('sourcePlatform'):
n = min(request.POST.get('n', OPTIMIZER.QUERY_HISTORY_UPLOAD_LIMIT.get()))
source_platform = request.POST.get('sourcePlatform', 'hive')
histories = [(source_platform, Document2.objects.get_history(doc_type='query-%s' % source_platform, user=request.user)[:n])]
elif OPTIMIZER.QUERY_HISTORY_UPLOAD_LIMIT.get() > 0:
histories = [
(source_platform, Document2.objects.filter(type='query-%s' % source_platform, is_history=True, is_managed=False, is_trashed=False).order_by('-last_modified')[:OPTIMIZER.QUERY_HISTORY_UPLOAD_LIMIT.get()])
for source_platform in ['hive', 'impala']
]
for source_platform, history in histories:
queries = _convert_queries([Notebook(document=doc).get_data() for doc in history])
upload_stats[source_platform] = api.upload(data=queries, data_type='queries', source_platform=source_platform)
response['upload_history'] = upload_stats
response['status'] = 0
else:
response['message'] = _('Query history upload requires Admin privileges or feature is disabled.')
return JsonResponse(response)
@require_POST
@error_handler
def upload_query(request):
response = {'status': -1}
source_platform = request.POST.get('sourcePlatform', 'default')
query_id = request.POST.get('query_id')
if OPTIMIZER.AUTO_UPLOAD_QUERIES.get() and source_platform in ('hive', 'impala') and query_id:
try:
doc = Document2.objects.document(request.user, doc_id=query_id)
query_data = Notebook(document=doc).get_data()
queries = _convert_queries([query_data])
source_platform = query_data['snippets'][0]['type']
api = OptimizerApi(request.user)
response['query_upload'] = api.upload(data=queries, data_type='queries', source_platform=source_platform)
except Document2.DoesNotExist:
response['query_upload'] = _('Skipped as task query')
else:
response['query_upload'] = _('Skipped')
response['status'] = 0
return JsonResponse(response)
@require_POST
@error_handler
def upload_table_stats(request):
response = {'status': -1}
db_tables = json.loads(request.POST.get('db_tables'), '[]')
source_platform = json.loads(request.POST.get('sourcePlatform', '"hive"'))
with_ddl = json.loads(request.POST.get('with_ddl', 'false'))
with_table_stats = json.loads(request.POST.get('with_table', 'false'))
with_columns_stats = json.loads(request.POST.get('with_columns', 'false'))
table_ddls = []
table_stats = []
column_stats = []
if not OPTIMIZER.AUTO_UPLOAD_DDL.get():
with_ddl = False
if not OPTIMIZER.AUTO_UPLOAD_STATS.get():
with_table_stats = with_columns_stats = False
for db_table in db_tables:
path = _get_table_name(db_table)
try:
if with_ddl:
db = _get_db(request.user, source_type=source_platform)
query = hql_query('SHOW CREATE TABLE `%(database)s`.`%(table)s`' % path)
handle = db.execute_and_wait(query, timeout_sec=5.0)
if handle:
result = db.fetch(handle, rows=5000)
db.close(handle)
table_ddls.append((0, 0, ' '.join([row[0] for row in result.rows()]), path['database']))
if with_table_stats:
mock_request = MockRequest(user=request.user, source_platform=source_platform)
full_table_stats = json.loads(get_table_stats(mock_request, database=path['database'], table=path['table']).content)
stats = dict((stat['data_type'], stat['comment']) for stat in full_table_stats['stats'])
table_stats.append({
'table_name': '%(database)s.%(table)s' % path,
'num_rows': stats.get('numRows', -1),
'last_modified_time': stats.get('transient_lastDdlTime', -1),
'total_size': stats.get('totalSize', -1),
'raw_data_size': stats.get('rawDataSize', -1),
'num_files': stats.get('numFiles', -1),
'num_partitions': stats.get('numPartitions', -1),
})
if with_columns_stats:
if source_platform == 'impala':
colum_stats = json.loads(get_table_stats(mock_request, database=path['database'], table=path['table'], column=-1).content)['stats']
else:
colum_stats = [
json.loads(get_table_stats(mock_request, database=path['database'], table=path['table'], column=col).content)['stats']
for col in full_table_stats['columns'][:25]
]
raw_column_stats = [dict([(key, val if val is not None else '') for col_stat in col for key, val in col_stat.iteritems()]) for col in colum_stats]
for col_stats in raw_column_stats:
column_stats.append({
'table_name': '%(database)s.%(table)s' % path,
'column_name': col_stats['col_name'],
'data_type': col_stats['data_type'],
"num_distinct": int(col_stats.get('distinct_count')) if col_stats.get('distinct_count') != '' else -1,
"num_nulls": int(col_stats['num_nulls']) if col_stats['num_nulls'] != '' else -1,
"avg_col_len": int(float(col_stats['avg_col_len'])) if col_stats['avg_col_len'] != '' else -1,
"max_size": int(float(col_stats['max_col_len'])) if col_stats['max_col_len'] != '' else -1,
"min": col_stats['min'] if col_stats.get('min', '') != '' else -1,
"max": col_stats['max'] if col_stats.get('max', '') != '' else -1,
"num_trues": col_stats['num_trues'] if col_stats.get('num_trues', '') != '' else -1,
"num_falses": col_stats['num_falses'] if col_stats.get('num_falses', '') != '' else -1,
})
except Exception, e:
LOG.exception('Skipping upload of %s: %s' % (db_table, e))
api = OptimizerApi(request.user)
response['status'] = 0
if table_stats:
response['upload_table_stats'] = api.upload(data=table_stats, data_type='table_stats', source_platform=source_platform)
response['upload_table_stats_status'] = 0 if response['upload_table_stats']['status']['state'] in ('WAITING', 'FINISHED', 'IN_PROGRESS') else -1
response['status'] = response['upload_table_stats_status']
if column_stats:
response['upload_cols_stats'] = api.upload(data=column_stats, data_type='cols_stats', source_platform=source_platform)
response['upload_cols_stats_status'] = response['status'] if response['upload_cols_stats']['status']['state'] in ('WAITING', 'FINISHED', 'IN_PROGRESS') else -1
if response['upload_cols_stats_status'] != 0:
response['status'] = response['upload_cols_stats_status']
if table_ddls:
response['upload_table_ddl'] = api.upload(data=table_ddls, data_type='queries', source_platform=source_platform)
response['upload_table_ddl_status'] = response['status'] if response['upload_table_ddl']['status']['state'] in ('WAITING', 'FINISHED', 'IN_PROGRESS') else -1
if response['upload_table_ddl_status'] != 0:
response['status'] = response['upload_table_ddl_status']
return JsonResponse(response)
@require_POST
@error_handler
def upload_status(request):
response = {'status': -1}
workload_id = request.POST.get('workloadId')
api = OptimizerApi(request.user)
response['upload_status'] = api.upload_status(workload_id=workload_id)
response['status'] = 0
return JsonResponse(response)
class MockRequest():
def __init__(self, user, source_platform):
self.user = user
self.path = '/%s/' % source_platform if source_platform != 'hive' else 'beeswax'
| false | true |
790bd9b739afc6a41dfca6fa5848442a73392a1a | 3,761 | py | Python | icepyx/tests/test_visualization.py | nsidc/icepyx | 7f387073a0d6c9e9f5fba90ba10dd2ad4ff04c8b | [
"BSD-3-Clause"
] | 113 | 2019-11-19T17:17:11.000Z | 2022-03-28T13:52:42.000Z | icepyx/tests/test_visualization.py | nsidc/icepyx | 7f387073a0d6c9e9f5fba90ba10dd2ad4ff04c8b | [
"BSD-3-Clause"
] | 211 | 2020-01-08T20:18:19.000Z | 2022-03-31T19:53:39.000Z | icepyx/tests/test_visualization.py | nsidc/icepyx | 7f387073a0d6c9e9f5fba90ba10dd2ad4ff04c8b | [
"BSD-3-Clause"
] | 90 | 2019-12-28T01:29:25.000Z | 2022-03-25T22:27:56.000Z | import pytest
from icepyx.core.visualization import Visualize
import icepyx.core.visualization as vis
@pytest.mark.parametrize(
"n, exp",
[
(
1,
[
"ATL06_20200702014158_01020810_004_01.h5",
"ATL06_20200703011618_01170810_004_01.h5",
],
),
(
2,
[
"ATL06_20200612151119_11920712_004_01.h5",
"ATL06_20200616021517_12450710_004_01.h5",
"ATL06_20200702014158_01020810_004_01.h5",
"ATL06_20200703011618_01170810_004_01.h5",
],
),
(
3,
[
"ATL06_20200612151119_11920712_004_01.h5",
"ATL06_20200616021517_12450710_004_01.h5",
"ATL06_20200702014158_01020810_004_01.h5",
"ATL06_20200703011618_01170810_004_01.h5",
],
),
],
)
def test_files_in_latest_cycles(n, exp):
files = [
"ATL06_20190710071617_01860412_004_01.h5",
"ATL06_20190713182016_02390410_004_01.h5",
"ATL06_20200612151119_11920712_004_01.h5",
"ATL06_20200616021517_12450710_004_01.h5",
"ATL06_20200702014158_01020810_004_01.h5",
"ATL06_20200703011618_01170810_004_01.h5",
]
cycles = [8, 7, 4]
obs = vis.files_in_latest_n_cycles(files, cycles=cycles, n=n)
assert obs == exp
@pytest.mark.parametrize(
"filename, expect",
[
('ATL06_20190525202604_08790310_004_01.h5', [879, 3, '2019-05-25']),
('ATL06_20190614194425_11840310_004_01.h5', [1184, 3, '2019-06-14']),
('ATL07-02_20190624063616_13290301_004_01.h5', [1329, 3, '2019-06-24']),
('ATL07-02_20190602190916_10010301_004_01.h5', [1001, 3, '2019-06-02']),
('ATL10-02_20190611072656_11310301_004_01.h5', [1131, 3, '2019-06-11']),
('ATL10-02_20190731045538_05060401_004_01.h5', [506, 4, '2019-07-31']),
('ATL12_20190615023544_11890301_004_01.h5', [1189, 3, '2019-06-15']),
('ATL12_20190721170332_03610401_004_01.h5', [361, 4, '2019-07-21']),
],
)
def test_gran_paras(filename, expect):
para_list = vis.gran_paras(filename)
assert para_list == expect
@pytest.mark.parametrize(
"product, date_range, bbox, expect",
[
("ATL06", ["2019-6-15", "2019-7-1"], [-64.5, -66, -63.5, -65], 3240),
("ATL07", ["2019-7-1", "2019-8-1"], [-65, -66, -64.5, -65], 7160),
("ATL08", ["2019-6-15", "2019-7-1"], [-18, 63, -17, 64], 852),
("ATL10", ["2019-8-1", "2019-9-1"], [-64, -67, -60, -60], 7375),
("ATL12", ["2019-7-1", "2019-10-1"], [-65.5, -65.5, -64.5, -65], 95),
("ATL13", ["2019-6-1", "2019-12-1"], [-75, -51, -74, -50], 20),
],
)
def test_visualization_date_range(product, date_range, bbox, expect):
region_viz = Visualize(product=product, spatial_extent=bbox, date_range=date_range)
data_size = region_viz.parallel_request_OA().size
assert data_size == expect
@pytest.mark.parametrize(
"product, bbox, cycles, tracks, expect",
[
("ATL06", [-64.5, -66, -63.5, -65], ["03"], ["1306"], 3240),
("ATL07", [-65, -66, -64.5, -65], ["04"], ["0186"], 7130),
("ATL08", [-18, 63, -17, 64], ["03"], ["1320"], 852),
("ATL10", [-64, -67, -60, -60], ["04"], ["0681"], 6015),
("ATL12", [-65.5, -65.5, -64.5, -65], ["05"], ["0041"], 95),
("ATL13", [-75, -51, -74, -50], ["05"], ["0293"], 20),
],
)
def test_visualization_orbits(product, bbox, cycles, tracks, expect):
region_viz = Visualize(
product=product, spatial_extent=bbox, cycles=cycles, tracks=tracks
)
data_size = region_viz.parallel_request_OA().size
assert data_size == expect
| 34.504587 | 87 | 0.576442 | import pytest
from icepyx.core.visualization import Visualize
import icepyx.core.visualization as vis
@pytest.mark.parametrize(
"n, exp",
[
(
1,
[
"ATL06_20200702014158_01020810_004_01.h5",
"ATL06_20200703011618_01170810_004_01.h5",
],
),
(
2,
[
"ATL06_20200612151119_11920712_004_01.h5",
"ATL06_20200616021517_12450710_004_01.h5",
"ATL06_20200702014158_01020810_004_01.h5",
"ATL06_20200703011618_01170810_004_01.h5",
],
),
(
3,
[
"ATL06_20200612151119_11920712_004_01.h5",
"ATL06_20200616021517_12450710_004_01.h5",
"ATL06_20200702014158_01020810_004_01.h5",
"ATL06_20200703011618_01170810_004_01.h5",
],
),
],
)
def test_files_in_latest_cycles(n, exp):
files = [
"ATL06_20190710071617_01860412_004_01.h5",
"ATL06_20190713182016_02390410_004_01.h5",
"ATL06_20200612151119_11920712_004_01.h5",
"ATL06_20200616021517_12450710_004_01.h5",
"ATL06_20200702014158_01020810_004_01.h5",
"ATL06_20200703011618_01170810_004_01.h5",
]
cycles = [8, 7, 4]
obs = vis.files_in_latest_n_cycles(files, cycles=cycles, n=n)
assert obs == exp
@pytest.mark.parametrize(
"filename, expect",
[
('ATL06_20190525202604_08790310_004_01.h5', [879, 3, '2019-05-25']),
('ATL06_20190614194425_11840310_004_01.h5', [1184, 3, '2019-06-14']),
('ATL07-02_20190624063616_13290301_004_01.h5', [1329, 3, '2019-06-24']),
('ATL07-02_20190602190916_10010301_004_01.h5', [1001, 3, '2019-06-02']),
('ATL10-02_20190611072656_11310301_004_01.h5', [1131, 3, '2019-06-11']),
('ATL10-02_20190731045538_05060401_004_01.h5', [506, 4, '2019-07-31']),
('ATL12_20190615023544_11890301_004_01.h5', [1189, 3, '2019-06-15']),
('ATL12_20190721170332_03610401_004_01.h5', [361, 4, '2019-07-21']),
],
)
def test_gran_paras(filename, expect):
para_list = vis.gran_paras(filename)
assert para_list == expect
@pytest.mark.parametrize(
"product, date_range, bbox, expect",
[
("ATL06", ["2019-6-15", "2019-7-1"], [-64.5, -66, -63.5, -65], 3240),
("ATL07", ["2019-7-1", "2019-8-1"], [-65, -66, -64.5, -65], 7160),
("ATL08", ["2019-6-15", "2019-7-1"], [-18, 63, -17, 64], 852),
("ATL10", ["2019-8-1", "2019-9-1"], [-64, -67, -60, -60], 7375),
("ATL12", ["2019-7-1", "2019-10-1"], [-65.5, -65.5, -64.5, -65], 95),
("ATL13", ["2019-6-1", "2019-12-1"], [-75, -51, -74, -50], 20),
],
)
def test_visualization_date_range(product, date_range, bbox, expect):
region_viz = Visualize(product=product, spatial_extent=bbox, date_range=date_range)
data_size = region_viz.parallel_request_OA().size
assert data_size == expect
@pytest.mark.parametrize(
"product, bbox, cycles, tracks, expect",
[
("ATL06", [-64.5, -66, -63.5, -65], ["03"], ["1306"], 3240),
("ATL07", [-65, -66, -64.5, -65], ["04"], ["0186"], 7130),
("ATL08", [-18, 63, -17, 64], ["03"], ["1320"], 852),
("ATL10", [-64, -67, -60, -60], ["04"], ["0681"], 6015),
("ATL12", [-65.5, -65.5, -64.5, -65], ["05"], ["0041"], 95),
("ATL13", [-75, -51, -74, -50], ["05"], ["0293"], 20),
],
)
def test_visualization_orbits(product, bbox, cycles, tracks, expect):
region_viz = Visualize(
product=product, spatial_extent=bbox, cycles=cycles, tracks=tracks
)
data_size = region_viz.parallel_request_OA().size
assert data_size == expect
| true | true |
790bdc2b49eb80e85b1daeec29291b189a50693c | 15,985 | py | Python | lite/examples/model_personalization/converter/tfltransfer/model_correctness_test.py | non778/examples | d1eed1a6a987b0ebbb0341925a480dc3e60489ee | [
"Apache-2.0"
] | 3 | 2020-09-15T13:00:51.000Z | 2020-10-07T17:43:51.000Z | lite/examples/model_personalization/converter/tfltransfer/model_correctness_test.py | non778/examples | d1eed1a6a987b0ebbb0341925a480dc3e60489ee | [
"Apache-2.0"
] | 7 | 2020-11-13T19:02:15.000Z | 2022-03-12T00:43:42.000Z | lite/examples/model_personalization/converter/tfltransfer/model_correctness_test.py | non778/examples | d1eed1a6a987b0ebbb0341925a480dc3e60489ee | [
"Apache-2.0"
] | 8 | 2021-05-01T04:50:58.000Z | 2021-05-01T07:57:04.000Z | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""End-to-end tests that check model correctness."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import tempfile
import unittest
import numpy as np
import tensorflow as tf
from tensorflow.compat import v1 as tfv1
# pylint: disable=g-bad-import-order
from tfltransfer import bases
from tfltransfer import optimizers
from tfltransfer import heads
from tfltransfer import tflite_transfer_converter
# pylint: enable=g-bad-import-order
IMAGE_SIZE = 224
BATCH_SIZE = 128
NUM_CLASSES = 5
VALIDATION_SPLIT = 0.2
LEARNING_RATE = 0.001
BOTTLENECK_SHAPE = (7, 7, 1280)
DATASET_URL = 'https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz'
class TransferModel(object):
"""Test consumer of models generated by the converter."""
def __init__(self, dataset_dir, base_model, head_model, optimizer):
"""Creates a wrapper for a set of models and a data set."""
self.dataset_dir = dataset_dir
datagen = tf.keras.preprocessing.image.ImageDataGenerator(
rescale=1. / 255, validation_split=VALIDATION_SPLIT)
self.train_img_generator = datagen.flow_from_directory(
self.dataset_dir,
target_size=(IMAGE_SIZE, IMAGE_SIZE),
batch_size=BATCH_SIZE,
subset='training')
self.val_img_generator = datagen.flow_from_directory(
self.dataset_dir,
target_size=(IMAGE_SIZE, IMAGE_SIZE),
batch_size=BATCH_SIZE,
subset='validation')
converter = tflite_transfer_converter.TFLiteTransferConverter(
NUM_CLASSES, base_model, head_model, optimizer, BATCH_SIZE)
models = converter._convert()
self.initialize_model = models['initialize']
self.bottleneck_model = models['bottleneck']
self.train_head_model = models['train_head']
self.inference_model = models['inference']
self.optimizer_model = models['optimizer']
self.variables = self._generate_initial_variables()
optim_state_shapes = self._optimizer_state_shapes()
self.optim_state = [
np.zeros(shape, dtype=np.float32) for shape in optim_state_shapes
]
def _generate_initial_variables(self):
"""Generates the initial model variables."""
interpreter = tf.lite.Interpreter(model_content=self.initialize_model)
zero_in = interpreter.get_input_details()[0]
variable_outs = interpreter.get_output_details()
interpreter.allocate_tensors()
interpreter.set_tensor(zero_in['index'], np.float32(0.))
interpreter.invoke()
return [interpreter.get_tensor(var['index']) for var in variable_outs]
def _optimizer_state_shapes(self):
"""Reads the shapes of the optimizer parameters (mutable state)."""
interpreter = tf.lite.Interpreter(model_content=self.optimizer_model)
num_variables = len(self.variables)
optim_state_inputs = interpreter.get_input_details()[num_variables * 2:]
return [input_['shape'] for input_ in optim_state_inputs]
def prepare_bottlenecks(self):
"""Passes all images through the base model and save the bottlenecks.
This method has to be called before any training or inference.
"""
self.train_bottlenecks, self.train_labels = (
self._collect_and_generate_bottlenecks(self.train_img_generator))
self.val_bottlenecks, self.val_labels = (
self._collect_and_generate_bottlenecks(self.val_img_generator))
def _collect_and_generate_bottlenecks(self, image_gen):
"""Consumes a generator and converts all images to bottlenecks.
Args:
image_gen: A Keras data generator for images to process
Returns:
Two NumPy arrays: (bottlenecks, labels).
"""
collected_bottlenecks = np.zeros(
(image_gen.samples,) + BOTTLENECK_SHAPE, dtype=np.float32)
collected_labels = np.zeros((image_gen.samples, NUM_CLASSES),
dtype=np.float32)
next_idx = 0
for bottlenecks, truth in self._generate_bottlenecks(
make_finite(image_gen)):
batch_size = bottlenecks.shape[0]
collected_bottlenecks[next_idx:next_idx + batch_size] = bottlenecks
collected_labels[next_idx:next_idx + batch_size] = truth
next_idx += batch_size
return collected_bottlenecks, collected_labels
def _generate_bottlenecks(self, image_gen):
"""Generator adapter that passes images through the bottleneck model.
Args:
image_gen: A generator that returns images to be processed. Images are
paired with ground truth labels.
Yields:
Bottlenecks from input images, paired with ground truth labels.
"""
interpreter = tf.lite.Interpreter(model_content=self.bottleneck_model)
[x_in] = interpreter.get_input_details()
[bottleneck_out] = interpreter.get_output_details()
for (x, y) in image_gen:
batch_size = x.shape[0]
interpreter.resize_tensor_input(x_in['index'],
(batch_size, IMAGE_SIZE, IMAGE_SIZE, 3))
interpreter.allocate_tensors()
interpreter.set_tensor(x_in['index'], x)
interpreter.invoke()
bottleneck = interpreter.get_tensor(bottleneck_out['index'])
yield bottleneck, y
def train_head(self, num_epochs):
"""Trains the head model for a given number of epochs.
SGD is used as an optimizer.
Args:
num_epochs: how many epochs should be trained
Returns:
A list of train_loss values after every epoch trained.
Raises:
RuntimeError: when prepare_bottlenecks() has not been called.
"""
if not hasattr(self, 'train_bottlenecks'):
raise RuntimeError('prepare_bottlenecks has not been called')
results = []
for _ in range(num_epochs):
loss = self._train_one_epoch(
self._generate_batches(self.train_bottlenecks, self.train_labels))
results.append(loss)
return results
def _generate_batches(self, x, y):
"""Creates a generator that iterates over the data in batches."""
num_total = x.shape[0]
for begin in range(0, num_total, BATCH_SIZE):
end = min(begin + BATCH_SIZE, num_total)
yield x[begin:end], y[begin:end]
def _train_one_epoch(self, train_gen):
"""Performs one training epoch."""
interpreter = tf.lite.Interpreter(model_content=self.train_head_model)
interpreter.allocate_tensors()
x_in, y_in = interpreter.get_input_details()[:2]
variable_ins = interpreter.get_input_details()[2:]
loss_out = interpreter.get_output_details()[0]
gradient_outs = interpreter.get_output_details()[1:]
epoch_loss = 0.
num_processed = 0
for bottlenecks, truth in train_gen:
batch_size = bottlenecks.shape[0]
if batch_size < BATCH_SIZE:
bottlenecks = pad_batch(bottlenecks, BATCH_SIZE)
truth = pad_batch(truth, BATCH_SIZE)
interpreter.set_tensor(x_in['index'], bottlenecks)
interpreter.set_tensor(y_in['index'], truth)
for variable_in, variable_value in zip(variable_ins, self.variables):
interpreter.set_tensor(variable_in['index'], variable_value)
interpreter.invoke()
loss = interpreter.get_tensor(loss_out['index'])
gradients = [
interpreter.get_tensor(gradient_out['index'])
for gradient_out in gradient_outs
]
self._apply_gradients(gradients)
epoch_loss += loss * batch_size
num_processed += batch_size
epoch_loss /= num_processed
return epoch_loss
def _apply_gradients(self, gradients):
"""Applies the optimizer to the model parameters."""
interpreter = tf.lite.Interpreter(model_content=self.optimizer_model)
interpreter.allocate_tensors()
num_variables = len(self.variables)
variable_ins = interpreter.get_input_details()[:num_variables]
gradient_ins = interpreter.get_input_details()[num_variables:num_variables *
2]
state_ins = interpreter.get_input_details()[num_variables * 2:]
variable_outs = interpreter.get_output_details()[:num_variables]
state_outs = interpreter.get_output_details()[num_variables:]
for variable, gradient, variable_in, gradient_in in zip(
self.variables, gradients, variable_ins, gradient_ins):
interpreter.set_tensor(variable_in['index'], variable)
interpreter.set_tensor(gradient_in['index'], gradient)
for optim_state_elem, state_in in zip(self.optim_state, state_ins):
interpreter.set_tensor(state_in['index'], optim_state_elem)
interpreter.invoke()
self.variables = [
interpreter.get_tensor(variable_out['index'])
for variable_out in variable_outs
]
self.optim_state = [
interpreter.get_tensor(state_out['index']) for state_out in state_outs
]
def measure_inference_accuracy(self):
"""Runs the inference model and measures accuracy on the validation set."""
interpreter = tf.lite.Interpreter(model_content=self.inference_model)
bottleneck_in = interpreter.get_input_details()[0]
variable_ins = interpreter.get_input_details()[1:]
[y_out] = interpreter.get_output_details()
inference_accuracy = 0.
num_processed = 0
for bottleneck, truth in self._generate_batches(self.val_bottlenecks,
self.val_labels):
batch_size = bottleneck.shape[0]
interpreter.resize_tensor_input(bottleneck_in['index'],
(batch_size,) + BOTTLENECK_SHAPE)
interpreter.allocate_tensors()
interpreter.set_tensor(bottleneck_in['index'], bottleneck)
for variable_in, variable_value in zip(variable_ins, self.variables):
interpreter.set_tensor(variable_in['index'], variable_value)
interpreter.invoke()
preds = interpreter.get_tensor(y_out['index'])
acc = (np.argmax(preds, axis=1) == np.argmax(truth,
axis=1)).sum() / batch_size
inference_accuracy += acc * batch_size
num_processed += batch_size
inference_accuracy /= num_processed
return inference_accuracy
def make_finite(data_gen):
"""An adapter for Keras data generators that makes them finite.
The default behavior in Keras is to keep looping infinitely through
the data.
Args:
data_gen: An infinite Keras data generator.
Yields:
Same values as the parameter generator.
"""
num_samples = data_gen.samples
num_processed = 0
for batch in data_gen:
batch_size = batch[0].shape[0]
if batch_size + num_processed > num_samples:
batch_size = num_samples - num_processed
should_stop = True
else:
should_stop = False
if batch_size == 0:
return
batch = tuple(x[:batch_size] for x in batch)
yield batch
num_processed += batch_size
if should_stop:
return
# TODO(b/135138207) investigate if we can get rid of this.
def pad_batch(batch, batch_size):
"""Resize batch to a given size, tiling present samples over missing.
Example:
Suppose batch_size is 5, batch is [1, 2].
Then the return value is [1, 2, 1, 2, 1].
Args:
batch: An ndarray with first dimension size <= batch_size.
batch_size: Desired size for first dimension.
Returns:
An ndarray of the same shape, except first dimension has
the desired size.
"""
padded = np.zeros((batch_size,) + batch.shape[1:], dtype=batch.dtype)
next_idx = 0
while next_idx < batch_size:
fill_len = min(batch.shape[0], batch_size - next_idx)
padded[next_idx:next_idx + fill_len] = batch[:fill_len]
next_idx += fill_len
return padded
class ModelCorrectnessTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
super(ModelCorrectnessTest, cls).setUpClass()
zip_file = tf.keras.utils.get_file(
origin=DATASET_URL, fname='flower_photos.tgz', extract=True)
cls.dataset_dir = os.path.join(os.path.dirname(zip_file), 'flower_photos')
mobilenet_dir = tempfile.mkdtemp('tflite-transfer-test')
mobilenet_keras = tf.keras.applications.MobileNetV2(
input_shape=(IMAGE_SIZE, IMAGE_SIZE, 3),
include_top=False,
weights='imagenet')
tfv1.keras.experimental.export_saved_model(mobilenet_keras, mobilenet_dir)
cls.mobilenet_dir = mobilenet_dir
def setUp(self):
super(ModelCorrectnessTest, self).setUp()
self.mobilenet_dir = ModelCorrectnessTest.mobilenet_dir
self.dataset_dir = ModelCorrectnessTest.dataset_dir
def test_mobilenet_v2_saved_model_and_softmax_classifier(self):
base_model = bases.SavedModelBase(self.mobilenet_dir)
head_model = heads.SoftmaxClassifierHead(BATCH_SIZE, BOTTLENECK_SHAPE,
NUM_CLASSES)
optimizer = optimizers.SGD(LEARNING_RATE)
model = TransferModel(self.dataset_dir, base_model, head_model, optimizer)
self.assertModelAchievesAccuracy(model, 0.80)
def test_mobilenet_v2_saved_model_quantized_and_softmax_classifier(self):
base_model = bases.SavedModelBase(self.mobilenet_dir, quantize=True)
head_model = heads.SoftmaxClassifierHead(BATCH_SIZE, BOTTLENECK_SHAPE,
NUM_CLASSES)
optimizer = optimizers.SGD(LEARNING_RATE)
model = TransferModel(self.dataset_dir, base_model, head_model, optimizer)
self.assertModelAchievesAccuracy(model, 0.80)
def test_mobilenet_v2_base_and_softmax_classifier(self):
base_model = bases.MobileNetV2Base()
head_model = heads.SoftmaxClassifierHead(BATCH_SIZE, BOTTLENECK_SHAPE,
NUM_CLASSES)
optimizer = optimizers.SGD(LEARNING_RATE)
model = TransferModel(self.dataset_dir, base_model, head_model, optimizer)
self.assertModelAchievesAccuracy(model, 0.80)
def test_mobilenet_v2_base_and_softmax_classifier_l2(self):
base_model = bases.MobileNetV2Base()
head_model = heads.SoftmaxClassifierHead(
BATCH_SIZE, BOTTLENECK_SHAPE, NUM_CLASSES, l2_reg=0.1)
optimizer = optimizers.SGD(LEARNING_RATE)
model = TransferModel(self.dataset_dir, base_model, head_model, optimizer)
self.assertModelAchievesAccuracy(model, 0.80)
def test_mobilenet_v2_base_quantized_and_softmax_classifier(self):
base_model = bases.MobileNetV2Base(quantize=True)
head_model = heads.SoftmaxClassifierHead(BATCH_SIZE, BOTTLENECK_SHAPE,
NUM_CLASSES)
optimizer = optimizers.SGD(LEARNING_RATE)
model = TransferModel(self.dataset_dir, base_model, head_model, optimizer)
self.assertModelAchievesAccuracy(model, 0.80)
def test_mobilenet_v2_base_and_softmax_classifier_adam(self):
base_model = bases.MobileNetV2Base()
head_model = heads.SoftmaxClassifierHead(BATCH_SIZE, BOTTLENECK_SHAPE,
NUM_CLASSES)
optimizer = optimizers.Adam()
model = TransferModel(self.dataset_dir, base_model, head_model, optimizer)
self.assertModelAchievesAccuracy(model, 0.80)
def assertModelAchievesAccuracy(self, model, target_accuracy, num_epochs=30):
model.prepare_bottlenecks()
print('Bottlenecks prepared')
history = model.train_head(num_epochs)
print('Training completed, history = {}'.format(history))
accuracy = model.measure_inference_accuracy()
print('Final accuracy = {:.2f}'.format(accuracy))
self.assertGreater(accuracy, target_accuracy)
if __name__ == '__main__':
unittest.main()
| 38.059524 | 103 | 0.714983 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import tempfile
import unittest
import numpy as np
import tensorflow as tf
from tensorflow.compat import v1 as tfv1
from tfltransfer import bases
from tfltransfer import optimizers
from tfltransfer import heads
from tfltransfer import tflite_transfer_converter
IMAGE_SIZE = 224
BATCH_SIZE = 128
NUM_CLASSES = 5
VALIDATION_SPLIT = 0.2
LEARNING_RATE = 0.001
BOTTLENECK_SHAPE = (7, 7, 1280)
DATASET_URL = 'https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz'
class TransferModel(object):
def __init__(self, dataset_dir, base_model, head_model, optimizer):
self.dataset_dir = dataset_dir
datagen = tf.keras.preprocessing.image.ImageDataGenerator(
rescale=1. / 255, validation_split=VALIDATION_SPLIT)
self.train_img_generator = datagen.flow_from_directory(
self.dataset_dir,
target_size=(IMAGE_SIZE, IMAGE_SIZE),
batch_size=BATCH_SIZE,
subset='training')
self.val_img_generator = datagen.flow_from_directory(
self.dataset_dir,
target_size=(IMAGE_SIZE, IMAGE_SIZE),
batch_size=BATCH_SIZE,
subset='validation')
converter = tflite_transfer_converter.TFLiteTransferConverter(
NUM_CLASSES, base_model, head_model, optimizer, BATCH_SIZE)
models = converter._convert()
self.initialize_model = models['initialize']
self.bottleneck_model = models['bottleneck']
self.train_head_model = models['train_head']
self.inference_model = models['inference']
self.optimizer_model = models['optimizer']
self.variables = self._generate_initial_variables()
optim_state_shapes = self._optimizer_state_shapes()
self.optim_state = [
np.zeros(shape, dtype=np.float32) for shape in optim_state_shapes
]
def _generate_initial_variables(self):
interpreter = tf.lite.Interpreter(model_content=self.initialize_model)
zero_in = interpreter.get_input_details()[0]
variable_outs = interpreter.get_output_details()
interpreter.allocate_tensors()
interpreter.set_tensor(zero_in['index'], np.float32(0.))
interpreter.invoke()
return [interpreter.get_tensor(var['index']) for var in variable_outs]
def _optimizer_state_shapes(self):
interpreter = tf.lite.Interpreter(model_content=self.optimizer_model)
num_variables = len(self.variables)
optim_state_inputs = interpreter.get_input_details()[num_variables * 2:]
return [input_['shape'] for input_ in optim_state_inputs]
def prepare_bottlenecks(self):
self.train_bottlenecks, self.train_labels = (
self._collect_and_generate_bottlenecks(self.train_img_generator))
self.val_bottlenecks, self.val_labels = (
self._collect_and_generate_bottlenecks(self.val_img_generator))
def _collect_and_generate_bottlenecks(self, image_gen):
collected_bottlenecks = np.zeros(
(image_gen.samples,) + BOTTLENECK_SHAPE, dtype=np.float32)
collected_labels = np.zeros((image_gen.samples, NUM_CLASSES),
dtype=np.float32)
next_idx = 0
for bottlenecks, truth in self._generate_bottlenecks(
make_finite(image_gen)):
batch_size = bottlenecks.shape[0]
collected_bottlenecks[next_idx:next_idx + batch_size] = bottlenecks
collected_labels[next_idx:next_idx + batch_size] = truth
next_idx += batch_size
return collected_bottlenecks, collected_labels
def _generate_bottlenecks(self, image_gen):
interpreter = tf.lite.Interpreter(model_content=self.bottleneck_model)
[x_in] = interpreter.get_input_details()
[bottleneck_out] = interpreter.get_output_details()
for (x, y) in image_gen:
batch_size = x.shape[0]
interpreter.resize_tensor_input(x_in['index'],
(batch_size, IMAGE_SIZE, IMAGE_SIZE, 3))
interpreter.allocate_tensors()
interpreter.set_tensor(x_in['index'], x)
interpreter.invoke()
bottleneck = interpreter.get_tensor(bottleneck_out['index'])
yield bottleneck, y
def train_head(self, num_epochs):
if not hasattr(self, 'train_bottlenecks'):
raise RuntimeError('prepare_bottlenecks has not been called')
results = []
for _ in range(num_epochs):
loss = self._train_one_epoch(
self._generate_batches(self.train_bottlenecks, self.train_labels))
results.append(loss)
return results
def _generate_batches(self, x, y):
num_total = x.shape[0]
for begin in range(0, num_total, BATCH_SIZE):
end = min(begin + BATCH_SIZE, num_total)
yield x[begin:end], y[begin:end]
def _train_one_epoch(self, train_gen):
interpreter = tf.lite.Interpreter(model_content=self.train_head_model)
interpreter.allocate_tensors()
x_in, y_in = interpreter.get_input_details()[:2]
variable_ins = interpreter.get_input_details()[2:]
loss_out = interpreter.get_output_details()[0]
gradient_outs = interpreter.get_output_details()[1:]
epoch_loss = 0.
num_processed = 0
for bottlenecks, truth in train_gen:
batch_size = bottlenecks.shape[0]
if batch_size < BATCH_SIZE:
bottlenecks = pad_batch(bottlenecks, BATCH_SIZE)
truth = pad_batch(truth, BATCH_SIZE)
interpreter.set_tensor(x_in['index'], bottlenecks)
interpreter.set_tensor(y_in['index'], truth)
for variable_in, variable_value in zip(variable_ins, self.variables):
interpreter.set_tensor(variable_in['index'], variable_value)
interpreter.invoke()
loss = interpreter.get_tensor(loss_out['index'])
gradients = [
interpreter.get_tensor(gradient_out['index'])
for gradient_out in gradient_outs
]
self._apply_gradients(gradients)
epoch_loss += loss * batch_size
num_processed += batch_size
epoch_loss /= num_processed
return epoch_loss
def _apply_gradients(self, gradients):
interpreter = tf.lite.Interpreter(model_content=self.optimizer_model)
interpreter.allocate_tensors()
num_variables = len(self.variables)
variable_ins = interpreter.get_input_details()[:num_variables]
gradient_ins = interpreter.get_input_details()[num_variables:num_variables *
2]
state_ins = interpreter.get_input_details()[num_variables * 2:]
variable_outs = interpreter.get_output_details()[:num_variables]
state_outs = interpreter.get_output_details()[num_variables:]
for variable, gradient, variable_in, gradient_in in zip(
self.variables, gradients, variable_ins, gradient_ins):
interpreter.set_tensor(variable_in['index'], variable)
interpreter.set_tensor(gradient_in['index'], gradient)
for optim_state_elem, state_in in zip(self.optim_state, state_ins):
interpreter.set_tensor(state_in['index'], optim_state_elem)
interpreter.invoke()
self.variables = [
interpreter.get_tensor(variable_out['index'])
for variable_out in variable_outs
]
self.optim_state = [
interpreter.get_tensor(state_out['index']) for state_out in state_outs
]
def measure_inference_accuracy(self):
interpreter = tf.lite.Interpreter(model_content=self.inference_model)
bottleneck_in = interpreter.get_input_details()[0]
variable_ins = interpreter.get_input_details()[1:]
[y_out] = interpreter.get_output_details()
inference_accuracy = 0.
num_processed = 0
for bottleneck, truth in self._generate_batches(self.val_bottlenecks,
self.val_labels):
batch_size = bottleneck.shape[0]
interpreter.resize_tensor_input(bottleneck_in['index'],
(batch_size,) + BOTTLENECK_SHAPE)
interpreter.allocate_tensors()
interpreter.set_tensor(bottleneck_in['index'], bottleneck)
for variable_in, variable_value in zip(variable_ins, self.variables):
interpreter.set_tensor(variable_in['index'], variable_value)
interpreter.invoke()
preds = interpreter.get_tensor(y_out['index'])
acc = (np.argmax(preds, axis=1) == np.argmax(truth,
axis=1)).sum() / batch_size
inference_accuracy += acc * batch_size
num_processed += batch_size
inference_accuracy /= num_processed
return inference_accuracy
def make_finite(data_gen):
num_samples = data_gen.samples
num_processed = 0
for batch in data_gen:
batch_size = batch[0].shape[0]
if batch_size + num_processed > num_samples:
batch_size = num_samples - num_processed
should_stop = True
else:
should_stop = False
if batch_size == 0:
return
batch = tuple(x[:batch_size] for x in batch)
yield batch
num_processed += batch_size
if should_stop:
return
def pad_batch(batch, batch_size):
padded = np.zeros((batch_size,) + batch.shape[1:], dtype=batch.dtype)
next_idx = 0
while next_idx < batch_size:
fill_len = min(batch.shape[0], batch_size - next_idx)
padded[next_idx:next_idx + fill_len] = batch[:fill_len]
next_idx += fill_len
return padded
class ModelCorrectnessTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
super(ModelCorrectnessTest, cls).setUpClass()
zip_file = tf.keras.utils.get_file(
origin=DATASET_URL, fname='flower_photos.tgz', extract=True)
cls.dataset_dir = os.path.join(os.path.dirname(zip_file), 'flower_photos')
mobilenet_dir = tempfile.mkdtemp('tflite-transfer-test')
mobilenet_keras = tf.keras.applications.MobileNetV2(
input_shape=(IMAGE_SIZE, IMAGE_SIZE, 3),
include_top=False,
weights='imagenet')
tfv1.keras.experimental.export_saved_model(mobilenet_keras, mobilenet_dir)
cls.mobilenet_dir = mobilenet_dir
def setUp(self):
super(ModelCorrectnessTest, self).setUp()
self.mobilenet_dir = ModelCorrectnessTest.mobilenet_dir
self.dataset_dir = ModelCorrectnessTest.dataset_dir
def test_mobilenet_v2_saved_model_and_softmax_classifier(self):
base_model = bases.SavedModelBase(self.mobilenet_dir)
head_model = heads.SoftmaxClassifierHead(BATCH_SIZE, BOTTLENECK_SHAPE,
NUM_CLASSES)
optimizer = optimizers.SGD(LEARNING_RATE)
model = TransferModel(self.dataset_dir, base_model, head_model, optimizer)
self.assertModelAchievesAccuracy(model, 0.80)
def test_mobilenet_v2_saved_model_quantized_and_softmax_classifier(self):
base_model = bases.SavedModelBase(self.mobilenet_dir, quantize=True)
head_model = heads.SoftmaxClassifierHead(BATCH_SIZE, BOTTLENECK_SHAPE,
NUM_CLASSES)
optimizer = optimizers.SGD(LEARNING_RATE)
model = TransferModel(self.dataset_dir, base_model, head_model, optimizer)
self.assertModelAchievesAccuracy(model, 0.80)
def test_mobilenet_v2_base_and_softmax_classifier(self):
base_model = bases.MobileNetV2Base()
head_model = heads.SoftmaxClassifierHead(BATCH_SIZE, BOTTLENECK_SHAPE,
NUM_CLASSES)
optimizer = optimizers.SGD(LEARNING_RATE)
model = TransferModel(self.dataset_dir, base_model, head_model, optimizer)
self.assertModelAchievesAccuracy(model, 0.80)
def test_mobilenet_v2_base_and_softmax_classifier_l2(self):
base_model = bases.MobileNetV2Base()
head_model = heads.SoftmaxClassifierHead(
BATCH_SIZE, BOTTLENECK_SHAPE, NUM_CLASSES, l2_reg=0.1)
optimizer = optimizers.SGD(LEARNING_RATE)
model = TransferModel(self.dataset_dir, base_model, head_model, optimizer)
self.assertModelAchievesAccuracy(model, 0.80)
def test_mobilenet_v2_base_quantized_and_softmax_classifier(self):
base_model = bases.MobileNetV2Base(quantize=True)
head_model = heads.SoftmaxClassifierHead(BATCH_SIZE, BOTTLENECK_SHAPE,
NUM_CLASSES)
optimizer = optimizers.SGD(LEARNING_RATE)
model = TransferModel(self.dataset_dir, base_model, head_model, optimizer)
self.assertModelAchievesAccuracy(model, 0.80)
def test_mobilenet_v2_base_and_softmax_classifier_adam(self):
base_model = bases.MobileNetV2Base()
head_model = heads.SoftmaxClassifierHead(BATCH_SIZE, BOTTLENECK_SHAPE,
NUM_CLASSES)
optimizer = optimizers.Adam()
model = TransferModel(self.dataset_dir, base_model, head_model, optimizer)
self.assertModelAchievesAccuracy(model, 0.80)
def assertModelAchievesAccuracy(self, model, target_accuracy, num_epochs=30):
model.prepare_bottlenecks()
print('Bottlenecks prepared')
history = model.train_head(num_epochs)
print('Training completed, history = {}'.format(history))
accuracy = model.measure_inference_accuracy()
print('Final accuracy = {:.2f}'.format(accuracy))
self.assertGreater(accuracy, target_accuracy)
if __name__ == '__main__':
unittest.main()
| true | true |
790bdc3ea34a2bbf34251dec2df58f723df4e0a4 | 35,323 | py | Python | flair/models/tars_model.py | marleneDebatin/flair | 4d17509f358158f66d43e85db1b6990523b0b095 | [
"MIT"
] | 1 | 2022-02-06T04:04:27.000Z | 2022-02-06T04:04:27.000Z | flair/models/tars_model.py | marleneDebatin/flair | 4d17509f358158f66d43e85db1b6990523b0b095 | [
"MIT"
] | null | null | null | flair/models/tars_model.py | marleneDebatin/flair | 4d17509f358158f66d43e85db1b6990523b0b095 | [
"MIT"
] | null | null | null | import logging
from collections import OrderedDict
from pathlib import Path
from typing import List, Optional, Set, Tuple, Union
import numpy as np
import torch
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.preprocessing import minmax_scale
from tqdm import tqdm
import flair
from flair.data import Dictionary, Sentence, Span, SpanLabel
from flair.datasets import DataLoader, FlairDatapointDataset
from flair.embeddings import (
TokenEmbeddings,
TransformerDocumentEmbeddings,
TransformerWordEmbeddings,
)
from flair.file_utils import cached_path
from flair.models.sequence_tagger_model import SequenceTagger
from flair.models.text_classification_model import TextClassifier
from flair.training_utils import store_embeddings
log = logging.getLogger("flair")
class FewshotClassifier(flair.nn.Classifier[Sentence]):
def __init__(self):
self._current_task = None
self._task_specific_attributes = {}
self.label_nearest_map = None
self.tars_model: flair.nn.Classifier[Sentence]
super(FewshotClassifier, self).__init__()
def forward_loss(
self, data_points: Union[List[Sentence], Sentence]
) -> Union[torch.Tensor, Tuple[torch.Tensor, int]]:
if not isinstance(data_points, list):
data_points = [data_points]
# Transform input data into TARS format
sentences = self._get_tars_formatted_sentences(data_points)
loss = self.tars_model.forward_loss(sentences)
return loss
@property
def tars_embeddings(self):
raise NotImplementedError
def _get_tars_formatted_sentence(self, label, sentence):
raise NotImplementedError
def _get_tars_formatted_sentences(self, sentences: List[Sentence]):
label_text_pairs = []
all_labels = [label.decode("utf-8") for label in self.get_current_label_dictionary().idx2item]
for sentence in sentences:
label_text_pairs_for_sentence = []
if self.training and self.num_negative_labels_to_sample is not None:
positive_labels = list(
OrderedDict.fromkeys([label.value for label in sentence.get_labels(self.label_type)])
)
sampled_negative_labels = self._get_nearest_labels_for(positive_labels)
for label in positive_labels:
label_text_pairs_for_sentence.append(self._get_tars_formatted_sentence(label, sentence))
for label in sampled_negative_labels:
label_text_pairs_for_sentence.append(self._get_tars_formatted_sentence(label, sentence))
else:
for label in all_labels:
label_text_pairs_for_sentence.append(self._get_tars_formatted_sentence(label, sentence))
label_text_pairs.extend(label_text_pairs_for_sentence)
return label_text_pairs
def _get_nearest_labels_for(self, labels):
# if there are no labels, return a random sample as negatives
if len(labels) == 0:
tags = self.get_current_label_dictionary().get_items()
import random
sample = random.sample(tags, k=self.num_negative_labels_to_sample)
return sample
already_sampled_negative_labels = set()
# otherwise, go through all labels
for label in labels:
plausible_labels = []
plausible_label_probabilities = []
for plausible_label in self.label_nearest_map[label]:
if plausible_label in already_sampled_negative_labels or plausible_label in labels:
continue
else:
plausible_labels.append(plausible_label)
plausible_label_probabilities.append(self.label_nearest_map[label][plausible_label])
# make sure the probabilities always sum up to 1
plausible_label_probabilities = np.array(plausible_label_probabilities, dtype="float64")
plausible_label_probabilities += 1e-08
plausible_label_probabilities /= np.sum(plausible_label_probabilities)
if len(plausible_labels) > 0:
num_samples = min(self.num_negative_labels_to_sample, len(plausible_labels))
sampled_negative_labels = np.random.choice(
plausible_labels,
num_samples,
replace=False,
p=plausible_label_probabilities,
)
already_sampled_negative_labels.update(sampled_negative_labels)
return already_sampled_negative_labels
def train(self, mode=True):
"""Populate label similarity map based on cosine similarity before running epoch
If the `num_negative_labels_to_sample` is set to an integer value then before starting
each epoch the model would create a similarity measure between the label names based
on cosine distances between their BERT encoded embeddings.
"""
if mode and self.num_negative_labels_to_sample is not None:
self._compute_label_similarity_for_current_epoch()
super().train(mode)
super().train(mode)
def _compute_label_similarity_for_current_epoch(self):
"""
Compute the similarity between all labels for better sampling of negatives
"""
# get and embed all labels by making a Sentence object that contains only the label text
all_labels = [label.decode("utf-8") for label in self.get_current_label_dictionary().idx2item]
label_sentences = [Sentence(label) for label in all_labels]
self.tars_embeddings.eval() # TODO: check if this is necessary
self.tars_embeddings.embed(label_sentences)
self.tars_embeddings.train()
# get each label embedding and scale between 0 and 1
if isinstance(self.tars_embeddings, TokenEmbeddings):
encodings_np = [sentence[0].get_embedding().cpu().detach().numpy() for sentence in label_sentences]
else:
encodings_np = [sentence.get_embedding().cpu().detach().numpy() for sentence in label_sentences]
normalized_encoding = minmax_scale(encodings_np)
# compute similarity matrix
similarity_matrix = cosine_similarity(normalized_encoding)
# the higher the similarity, the greater the chance that a label is
# sampled as negative example
negative_label_probabilities = {}
for row_index, label in enumerate(all_labels):
negative_label_probabilities[label] = {}
for column_index, other_label in enumerate(all_labels):
if label != other_label:
negative_label_probabilities[label][other_label] = similarity_matrix[row_index][column_index]
self.label_nearest_map = negative_label_probabilities
def get_current_label_dictionary(self):
label_dictionary = self._task_specific_attributes[self._current_task]["label_dictionary"]
return label_dictionary
def get_current_label_type(self):
return self._task_specific_attributes[self._current_task]["label_type"]
def is_current_task_multi_label(self):
return self._task_specific_attributes[self._current_task]["multi_label"]
def add_and_switch_to_new_task(
self,
task_name,
label_dictionary: Union[List, Set, Dictionary, str],
label_type: str,
multi_label: bool = True,
force_switch: bool = False,
):
"""
Adds a new task to an existing TARS model. Sets necessary attributes and finally 'switches'
to the new task. Parameters are similar to the constructor except for model choice, batch
size and negative sampling. This method does not store the resultant model onto disk.
:param task_name: a string depicting the name of the task
:param label_dictionary: dictionary of the labels you want to predict
:param label_type: string to identify the label type ('ner', 'sentiment', etc.)
:param multi_label: whether this task is a multi-label prediction problem
:param force_switch: if True, will overwrite existing task with same name
"""
if task_name in self._task_specific_attributes and not force_switch:
log.warning("Task `%s` already exists in TARS model. Switching to it.", task_name)
else:
# make label dictionary if no Dictionary object is passed
if isinstance(label_dictionary, Dictionary):
label_dictionary = label_dictionary.get_items()
if type(label_dictionary) == str:
label_dictionary = [label_dictionary]
# prepare dictionary of tags (without B- I- prefixes and without UNK)
tag_dictionary = Dictionary(add_unk=False)
for tag in label_dictionary:
if tag == "<unk>" or tag == "O":
continue
if tag[1] == "-":
tag = tag[2:]
tag_dictionary.add_item(tag)
else:
tag_dictionary.add_item(tag)
self._task_specific_attributes[task_name] = {
"label_dictionary": tag_dictionary,
"label_type": label_type,
"multi_label": multi_label,
}
self.switch_to_task(task_name)
def list_existing_tasks(self) -> Set[str]:
"""
Lists existing tasks in the loaded TARS model on the console.
"""
return set(self._task_specific_attributes.keys())
def switch_to_task(self, task_name):
"""
Switches to a task which was previously added.
"""
if task_name not in self._task_specific_attributes:
log.error(
"Provided `%s` does not exist in the model. Consider calling " "`add_and_switch_to_new_task` first.",
task_name,
)
else:
self._current_task = task_name
def _drop_task(self, task_name):
if task_name in self._task_specific_attributes:
if self._current_task == task_name:
log.error(
"`%s` is the current task." " Switch to some other task before dropping this.",
task_name,
)
else:
self._task_specific_attributes.pop(task_name)
else:
log.warning("No task exists with the name `%s`.", task_name)
@staticmethod
def _filter_empty_sentences(sentences: List[Sentence]) -> List[Sentence]:
filtered_sentences = [sentence for sentence in sentences if sentence.tokens]
if len(sentences) != len(filtered_sentences):
log.warning(f"Ignore {len(sentences) - len(filtered_sentences)} sentence(s) with no tokens.")
return filtered_sentences
@property
def label_type(self):
return self.get_current_label_type()
def predict_zero_shot(
self,
sentences: Union[List[Sentence], Sentence],
candidate_label_set: Union[List[str], Set[str], str],
multi_label: bool = True,
):
"""
Method to make zero shot predictions from the TARS model
:param sentences: input sentence objects to classify
:param candidate_label_set: set of candidate labels
:param multi_label: indicates whether multi-label or single class prediction. Defaults to True.
"""
# check if candidate_label_set is empty
if candidate_label_set is None or len(candidate_label_set) == 0:
log.warning("Provided candidate_label_set is empty")
return
# make list if only one candidate label is passed
if isinstance(candidate_label_set, str):
candidate_label_set = {candidate_label_set}
# create label dictionary
label_dictionary = Dictionary(add_unk=False)
for label in candidate_label_set:
label_dictionary.add_item(label)
# note current task
existing_current_task = self._current_task
# create a temporary task
self.add_and_switch_to_new_task(
task_name="ZeroShot",
label_dictionary=label_dictionary,
label_type="-".join(label_dictionary.get_items()),
multi_label=multi_label,
)
try:
# make zero shot predictions
self.predict(sentences)
finally:
# switch to the pre-existing task
self.switch_to_task(existing_current_task)
self._drop_task("ZeroShot")
return
class TARSTagger(FewshotClassifier):
"""
TARS model for sequence tagging. In the backend, the model uses a BERT based 5-class
sequence labeler which given a <label, text> pair predicts the probability for each word
to belong to one of the BIOES classes. The input data is a usual Sentence object which is inflated
by the model internally before pushing it through the transformer stack of BERT.
"""
static_label_type = "tars_label"
def __init__(
self,
task_name: Optional[str] = None,
label_dictionary: Optional[Dictionary] = None,
label_type: Optional[str] = None,
embeddings: Union[TransformerWordEmbeddings, str] = "bert-base-uncased",
num_negative_labels_to_sample: int = 2,
prefix: bool = True,
**tagger_args,
):
"""
Initializes a TextClassifier
:param task_name: a string depicting the name of the task
:param label_dictionary: dictionary of labels you want to predict
:param embeddings: name of the pre-trained transformer model e.g.,
'bert-base-uncased' etc
:param num_negative_labels_to_sample: number of negative labels to sample for each
positive labels against a sentence during training. Defaults to 2 negative
labels for each positive label. The model would sample all the negative labels
if None is passed. That slows down the training considerably.
"""
super(TARSTagger, self).__init__()
if isinstance(embeddings, str):
embeddings = TransformerWordEmbeddings(
model=embeddings,
fine_tune=True,
layers="-1",
layer_mean=False,
)
# prepare TARS dictionary
tars_dictionary = Dictionary(add_unk=False)
tars_dictionary.add_item("entity")
tars_dictionary.span_labels = True
# initialize a bare-bones sequence tagger
self.tars_model: SequenceTagger = SequenceTagger(
hidden_size=123,
embeddings=embeddings,
tag_dictionary=tars_dictionary,
tag_type=self.static_label_type,
use_crf=False,
use_rnn=False,
reproject_embeddings=False,
**tagger_args,
)
# transformer separator
self.separator = str(self.tars_embeddings.tokenizer.sep_token)
if self.tars_embeddings.tokenizer._bos_token:
self.separator += str(self.tars_embeddings.tokenizer.bos_token)
self.prefix = prefix
self.num_negative_labels_to_sample = num_negative_labels_to_sample
if task_name and label_dictionary and label_type:
# Store task specific labels since TARS can handle multiple tasks
self.add_and_switch_to_new_task(task_name, label_dictionary, label_type)
else:
log.info(
"TARS initialized without a task. You need to call .add_and_switch_to_new_task() "
"before training this model"
)
def _get_tars_formatted_sentence(self, label, sentence):
original_text = sentence.to_tokenized_string()
label_text_pair = (
f"{label} {self.separator} {original_text}" if self.prefix else f"{original_text} {self.separator} {label}"
)
label_length = 0 if not self.prefix else len(label.split(" ")) + len(self.separator.split(" "))
# make a tars sentence where all labels are O by default
tars_sentence = Sentence(label_text_pair, use_tokenizer=False)
for entity_label in sentence.get_labels(self.label_type):
if entity_label.value == label:
new_span = [tars_sentence.get_token(token.idx + label_length) for token in entity_label.span]
tars_sentence.add_complex_label(self.static_label_type, SpanLabel(Span(new_span), value="entity"))
return tars_sentence
def _get_state_dict(self):
model_state = {
"state_dict": self.state_dict(),
"current_task": self._current_task,
"tag_type": self.get_current_label_type(),
"tag_dictionary": self.get_current_label_dictionary(),
"tars_model": self.tars_model,
"num_negative_labels_to_sample": self.num_negative_labels_to_sample,
"prefix": self.prefix,
"task_specific_attributes": self._task_specific_attributes,
}
return model_state
@staticmethod
def _fetch_model(model_name) -> str:
if model_name == "tars-ner":
cache_dir = Path("models")
model_name = cached_path(
"https://nlp.informatik.hu-berlin.de/resources/models/tars-ner/tars-ner.pt",
cache_dir=cache_dir,
)
return model_name
@staticmethod
def _init_model_with_state_dict(state):
# init new TARS classifier
model = TARSTagger(
task_name=state["current_task"],
label_dictionary=state["tag_dictionary"],
label_type=state["tag_type"],
embeddings=state["tars_model"].embeddings,
num_negative_labels_to_sample=state["num_negative_labels_to_sample"],
prefix=state["prefix"],
)
# set all task information
model._task_specific_attributes = state["task_specific_attributes"]
# linear layers of internal classifier
model.load_state_dict(state["state_dict"])
return model
@property
def tars_embeddings(self):
return self.tars_model.embeddings
def predict(
self,
sentences: Union[List[Sentence], Sentence],
mini_batch_size=32,
return_probabilities_for_all_classes: bool = False,
verbose: bool = False,
label_name: Optional[str] = None,
return_loss=False,
embedding_storage_mode="none",
most_probable_first: bool = True,
):
# return
"""
Predict sequence tags for Named Entity Recognition task
:param sentences: a Sentence or a List of Sentence
:param mini_batch_size: size of the minibatch, usually bigger is more rapid but consume more memory,
up to a point when it has no more effect.
:param all_tag_prob: True to compute the score for each tag on each token,
otherwise only the score of the best tag is returned
:param verbose: set to True to display a progress bar
:param return_loss: set to True to return loss
:param label_name: set this to change the name of the label type that is predicted
:param embedding_storage_mode: default is 'none' which is always best. Only set to 'cpu' or 'gpu' if
you wish to not only predict, but also keep the generated embeddings in CPU or GPU memory respectively.
'gpu' to store embeddings in GPU memory.
"""
if label_name is None:
label_name = self.get_current_label_type()
# with torch.no_grad():
if not sentences:
return sentences
if not isinstance(sentences, list):
sentences = [sentences]
reordered_sentences = sorted(sentences, key=lambda s: len(s), reverse=True)
dataloader = DataLoader(
dataset=FlairDatapointDataset(reordered_sentences),
batch_size=mini_batch_size,
)
# progress bar for verbosity
if verbose:
dataloader = tqdm(dataloader)
overall_loss = 0
overall_count = 0
with torch.no_grad():
for batch in dataloader:
batch = self._filter_empty_sentences(batch)
# stop if all sentences are empty
if not batch:
continue
# go through each sentence in the batch
for sentence in batch:
# always remove tags first
sentence.remove_labels(label_name)
all_labels = [label.decode("utf-8") for label in self.get_current_label_dictionary().idx2item]
all_detected = {}
for label in all_labels:
tars_sentence = self._get_tars_formatted_sentence(label, sentence)
loss_and_count = self.tars_model.predict(
tars_sentence,
label_name=label_name,
return_loss=True,
)
overall_loss += loss_and_count[0].item()
overall_count += loss_and_count[1]
for predicted in tars_sentence.get_labels(label_name):
predicted.value = label
all_detected[predicted] = predicted.score
if most_probable_first:
import operator
already_set_indices: List[int] = []
sorted_x = sorted(all_detected.items(), key=operator.itemgetter(1))
sorted_x.reverse()
for tuple in sorted_x:
# get the span and its label
label = tuple[0]
# label = span.get_labels("tars_temp_label")[0].value
label_length = (
0 if not self.prefix else len(label.value.split(" ")) + len(self.separator.split(" "))
)
# determine whether tokens in this span already have a label
tag_this = True
for token in label.span:
corresponding_token = sentence.get_token(token.idx - label_length)
if corresponding_token is None:
tag_this = False
continue
if token.idx in already_set_indices:
tag_this = False
continue
# only add if all tokens have no label
if tag_this:
already_set_indices.extend(token.idx for token in label.span)
predicted_span = [sentence.get_token(token.idx - label_length) for token in label.span]
sentence.add_complex_label(
label_name,
label=SpanLabel(Span(predicted_span), value=label.value, score=label.score),
)
# clearing token embeddings to save memory
store_embeddings(batch, storage_mode=embedding_storage_mode)
if return_loss:
return overall_loss, overall_count
class TARSClassifier(FewshotClassifier):
"""
TARS model for text classification. In the backend, the model uses a BERT based binary
text classifier which given a <label, text> pair predicts the probability of two classes
"True", and "False". The input data is a usual Sentence object which is inflated
by the model internally before pushing it through the transformer stack of BERT.
"""
static_label_type = "tars_label"
LABEL_MATCH = "YES"
LABEL_NO_MATCH = "NO"
def __init__(
self,
task_name: Optional[str] = None,
label_dictionary: Optional[Dictionary] = None,
label_type: Optional[str] = None,
embeddings: Union[TransformerDocumentEmbeddings, str] = "bert-base-uncased",
num_negative_labels_to_sample: int = 2,
prefix: bool = True,
**tagger_args,
):
"""
Initializes a TextClassifier
:param task_name: a string depicting the name of the task
:param label_dictionary: dictionary of labels you want to predict
:param embeddings: name of the pre-trained transformer model e.g.,
'bert-base-uncased' etc
:param num_negative_labels_to_sample: number of negative labels to sample for each
positive labels against a sentence during training. Defaults to 2 negative
labels for each positive label. The model would sample all the negative labels
if None is passed. That slows down the training considerably.
:param multi_label: auto-detected by default, but you can set this to True
to force multi-label predictionor False to force single-label prediction
:param multi_label_threshold: If multi-label you can set the threshold to make predictions
:param beta: Parameter for F-beta score for evaluation and training annealing
"""
super(TARSClassifier, self).__init__()
if isinstance(embeddings, str):
embeddings = TransformerDocumentEmbeddings(
model=embeddings,
fine_tune=True,
layers="-1",
layer_mean=False,
)
# prepare TARS dictionary
tars_dictionary = Dictionary(add_unk=False)
tars_dictionary.add_item(self.LABEL_NO_MATCH)
tars_dictionary.add_item(self.LABEL_MATCH)
# initialize a bare-bones sequence tagger
self.tars_model = TextClassifier(
document_embeddings=embeddings,
label_dictionary=tars_dictionary,
label_type=self.static_label_type,
**tagger_args,
)
# transformer separator
self.separator = str(self.tars_embeddings.tokenizer.sep_token)
if self.tars_embeddings.tokenizer._bos_token:
self.separator += str(self.tars_embeddings.tokenizer.bos_token)
self.prefix = prefix
self.num_negative_labels_to_sample = num_negative_labels_to_sample
if task_name and label_dictionary and label_type:
# Store task specific labels since TARS can handle multiple tasks
self.add_and_switch_to_new_task(task_name, label_dictionary, label_type)
else:
log.info(
"TARS initialized without a task. You need to call .add_and_switch_to_new_task() "
"before training this model"
)
self.clean_up_labels = True
def _clean(self, label_value: str) -> str:
if self.clean_up_labels:
return label_value.replace("_", " ")
else:
return label_value
def _get_tars_formatted_sentence(self, label, sentence):
label = self._clean(label)
original_text = sentence.to_tokenized_string()
label_text_pair = (
f"{label} {self.separator} {original_text}" if self.prefix else f"{original_text} {self.separator} {label}"
)
sentence_labels = [self._clean(label.value) for label in sentence.get_labels(self.get_current_label_type())]
tars_label = self.LABEL_MATCH if label in sentence_labels else self.LABEL_NO_MATCH
tars_sentence = Sentence(label_text_pair, use_tokenizer=False).add_label(self.static_label_type, tars_label)
return tars_sentence
def _get_state_dict(self):
model_state = {
"state_dict": self.state_dict(),
"current_task": self._current_task,
"label_type": self.get_current_label_type(),
"label_dictionary": self.get_current_label_dictionary(),
"tars_model": self.tars_model,
"num_negative_labels_to_sample": self.num_negative_labels_to_sample,
"task_specific_attributes": self._task_specific_attributes,
}
return model_state
@staticmethod
def _init_model_with_state_dict(state):
# init new TARS classifier
label_dictionary = state["label_dictionary"]
label_type = "default_label" if not state["label_type"] else state["label_type"]
model: TARSClassifier = TARSClassifier(
task_name=state["current_task"],
label_dictionary=label_dictionary,
label_type=label_type,
embeddings=state["tars_model"].document_embeddings,
num_negative_labels_to_sample=state["num_negative_labels_to_sample"],
)
# set all task information
model._task_specific_attributes = state["task_specific_attributes"]
# linear layers of internal classifier
model.load_state_dict(state["state_dict"])
return model
@staticmethod
def _fetch_model(model_name) -> str:
model_map = {}
hu_path: str = "https://nlp.informatik.hu-berlin.de/resources/models"
model_map["tars-base"] = "/".join([hu_path, "tars-base", "tars-base-v8.pt"])
cache_dir = Path("models")
if model_name in model_map:
model_name = cached_path(model_map[model_name], cache_dir=cache_dir)
return model_name
@property
def tars_embeddings(self):
return self.tars_model.document_embeddings
def predict(
self,
sentences: Union[List[Sentence], Sentence],
mini_batch_size=32,
return_probabilities_for_all_classes: bool = False,
verbose: bool = False,
label_name: Optional[str] = None,
return_loss=False,
embedding_storage_mode="none",
label_threshold: float = 0.5,
multi_label: Optional[bool] = None,
):
"""
Predict sequence tags for Named Entity Recognition task
:param sentences: a Sentence or a List of Sentence
:param mini_batch_size: size of the minibatch, usually bigger is more rapid but consume more memory,
up to a point when it has no more effect.
:param all_tag_prob: True to compute the score for each tag on each token,
otherwise only the score of the best tag is returned
:param verbose: set to True to display a progress bar
:param return_loss: set to True to return loss
:param label_name: set this to change the name of the label type that is predicted
:param embedding_storage_mode: default is 'none' which is always best. Only set to 'cpu' or 'gpu' if
you wish to not only predict, but also keep the generated embeddings in CPU or GPU memory respectively.
'gpu' to store embeddings in GPU memory.
"""
if label_name is None:
label_name = self.get_current_label_type()
if multi_label is None:
multi_label = self.is_current_task_multi_label()
# with torch.no_grad():
if not sentences:
return sentences
if isinstance(sentences, Sentence):
sentences = [sentences]
# set context if not set already
previous_sentence = None
for sentence in sentences:
if sentence.is_context_set():
continue
sentence._previous_sentence = previous_sentence
sentence._next_sentence = None
if previous_sentence:
previous_sentence._next_sentence = sentence
previous_sentence = sentence
reordered_sentences = sorted(sentences, key=lambda s: len(s), reverse=True)
dataloader = DataLoader(
dataset=FlairDatapointDataset(reordered_sentences),
batch_size=mini_batch_size,
)
# progress bar for verbosity
if verbose:
progressbar = tqdm(dataloader)
progressbar.set_description("Batch inference")
dataloader = progressbar
overall_loss = 0
overall_count = 0
batch_no = 0
with torch.no_grad():
for batch in dataloader:
batch_no += 1
batch = self._filter_empty_sentences(batch)
# stop if all sentences are empty
if not batch:
continue
# go through each sentence in the batch
for sentence in batch:
# always remove tags first
sentence.remove_labels(label_name)
all_labels = [label.decode("utf-8") for label in self.get_current_label_dictionary().idx2item]
best_label = None
for label in all_labels:
tars_sentence = self._get_tars_formatted_sentence(label, sentence)
loss_and_count = self.tars_model.predict(
tars_sentence,
label_name=label_name,
return_loss=True,
return_probabilities_for_all_classes=True if label_threshold < 0.5 else False,
)
overall_loss += loss_and_count[0].item()
overall_count += loss_and_count[1]
# add all labels that according to TARS match the text and are above threshold
for predicted_tars_label in tars_sentence.get_labels(label_name):
if (
predicted_tars_label.value == self.LABEL_MATCH
and predicted_tars_label.score > label_threshold
):
# do not add labels below confidence threshold
sentence.add_label(label_name, label, predicted_tars_label.score)
# only use label with highest confidence if enforcing single-label predictions
if not multi_label:
if len(sentence.get_labels(label_name)) > 0:
# get all label scores and do an argmax to get the best label
label_scores = torch.tensor(
[label.score for label in sentence.get_labels(label_name)],
dtype=torch.float,
)
best_label = sentence.get_labels(label_name)[torch.argmax(label_scores)]
# remove previously added labels and only add the best label
sentence.remove_labels(label_name)
sentence.add_label(
typename=label_name,
value=best_label.value,
score=best_label.score,
)
# clearing token embeddings to save memory
store_embeddings(batch, storage_mode=embedding_storage_mode)
if return_loss:
return overall_loss, overall_count
| 40.6947 | 119 | 0.621436 | import logging
from collections import OrderedDict
from pathlib import Path
from typing import List, Optional, Set, Tuple, Union
import numpy as np
import torch
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.preprocessing import minmax_scale
from tqdm import tqdm
import flair
from flair.data import Dictionary, Sentence, Span, SpanLabel
from flair.datasets import DataLoader, FlairDatapointDataset
from flair.embeddings import (
TokenEmbeddings,
TransformerDocumentEmbeddings,
TransformerWordEmbeddings,
)
from flair.file_utils import cached_path
from flair.models.sequence_tagger_model import SequenceTagger
from flair.models.text_classification_model import TextClassifier
from flair.training_utils import store_embeddings
log = logging.getLogger("flair")
class FewshotClassifier(flair.nn.Classifier[Sentence]):
def __init__(self):
self._current_task = None
self._task_specific_attributes = {}
self.label_nearest_map = None
self.tars_model: flair.nn.Classifier[Sentence]
super(FewshotClassifier, self).__init__()
def forward_loss(
self, data_points: Union[List[Sentence], Sentence]
) -> Union[torch.Tensor, Tuple[torch.Tensor, int]]:
if not isinstance(data_points, list):
data_points = [data_points]
sentences = self._get_tars_formatted_sentences(data_points)
loss = self.tars_model.forward_loss(sentences)
return loss
@property
def tars_embeddings(self):
raise NotImplementedError
def _get_tars_formatted_sentence(self, label, sentence):
raise NotImplementedError
def _get_tars_formatted_sentences(self, sentences: List[Sentence]):
label_text_pairs = []
all_labels = [label.decode("utf-8") for label in self.get_current_label_dictionary().idx2item]
for sentence in sentences:
label_text_pairs_for_sentence = []
if self.training and self.num_negative_labels_to_sample is not None:
positive_labels = list(
OrderedDict.fromkeys([label.value for label in sentence.get_labels(self.label_type)])
)
sampled_negative_labels = self._get_nearest_labels_for(positive_labels)
for label in positive_labels:
label_text_pairs_for_sentence.append(self._get_tars_formatted_sentence(label, sentence))
for label in sampled_negative_labels:
label_text_pairs_for_sentence.append(self._get_tars_formatted_sentence(label, sentence))
else:
for label in all_labels:
label_text_pairs_for_sentence.append(self._get_tars_formatted_sentence(label, sentence))
label_text_pairs.extend(label_text_pairs_for_sentence)
return label_text_pairs
def _get_nearest_labels_for(self, labels):
if len(labels) == 0:
tags = self.get_current_label_dictionary().get_items()
import random
sample = random.sample(tags, k=self.num_negative_labels_to_sample)
return sample
already_sampled_negative_labels = set()
for label in labels:
plausible_labels = []
plausible_label_probabilities = []
for plausible_label in self.label_nearest_map[label]:
if plausible_label in already_sampled_negative_labels or plausible_label in labels:
continue
else:
plausible_labels.append(plausible_label)
plausible_label_probabilities.append(self.label_nearest_map[label][plausible_label])
plausible_label_probabilities = np.array(plausible_label_probabilities, dtype="float64")
plausible_label_probabilities += 1e-08
plausible_label_probabilities /= np.sum(plausible_label_probabilities)
if len(plausible_labels) > 0:
num_samples = min(self.num_negative_labels_to_sample, len(plausible_labels))
sampled_negative_labels = np.random.choice(
plausible_labels,
num_samples,
replace=False,
p=plausible_label_probabilities,
)
already_sampled_negative_labels.update(sampled_negative_labels)
return already_sampled_negative_labels
def train(self, mode=True):
if mode and self.num_negative_labels_to_sample is not None:
self._compute_label_similarity_for_current_epoch()
super().train(mode)
super().train(mode)
def _compute_label_similarity_for_current_epoch(self):
all_labels = [label.decode("utf-8") for label in self.get_current_label_dictionary().idx2item]
label_sentences = [Sentence(label) for label in all_labels]
self.tars_embeddings.eval()
self.tars_embeddings.embed(label_sentences)
self.tars_embeddings.train()
if isinstance(self.tars_embeddings, TokenEmbeddings):
encodings_np = [sentence[0].get_embedding().cpu().detach().numpy() for sentence in label_sentences]
else:
encodings_np = [sentence.get_embedding().cpu().detach().numpy() for sentence in label_sentences]
normalized_encoding = minmax_scale(encodings_np)
similarity_matrix = cosine_similarity(normalized_encoding)
negative_label_probabilities = {}
for row_index, label in enumerate(all_labels):
negative_label_probabilities[label] = {}
for column_index, other_label in enumerate(all_labels):
if label != other_label:
negative_label_probabilities[label][other_label] = similarity_matrix[row_index][column_index]
self.label_nearest_map = negative_label_probabilities
def get_current_label_dictionary(self):
label_dictionary = self._task_specific_attributes[self._current_task]["label_dictionary"]
return label_dictionary
def get_current_label_type(self):
return self._task_specific_attributes[self._current_task]["label_type"]
def is_current_task_multi_label(self):
return self._task_specific_attributes[self._current_task]["multi_label"]
def add_and_switch_to_new_task(
self,
task_name,
label_dictionary: Union[List, Set, Dictionary, str],
label_type: str,
multi_label: bool = True,
force_switch: bool = False,
):
if task_name in self._task_specific_attributes and not force_switch:
log.warning("Task `%s` already exists in TARS model. Switching to it.", task_name)
else:
if isinstance(label_dictionary, Dictionary):
label_dictionary = label_dictionary.get_items()
if type(label_dictionary) == str:
label_dictionary = [label_dictionary]
tag_dictionary = Dictionary(add_unk=False)
for tag in label_dictionary:
if tag == "<unk>" or tag == "O":
continue
if tag[1] == "-":
tag = tag[2:]
tag_dictionary.add_item(tag)
else:
tag_dictionary.add_item(tag)
self._task_specific_attributes[task_name] = {
"label_dictionary": tag_dictionary,
"label_type": label_type,
"multi_label": multi_label,
}
self.switch_to_task(task_name)
def list_existing_tasks(self) -> Set[str]:
return set(self._task_specific_attributes.keys())
def switch_to_task(self, task_name):
if task_name not in self._task_specific_attributes:
log.error(
"Provided `%s` does not exist in the model. Consider calling " "`add_and_switch_to_new_task` first.",
task_name,
)
else:
self._current_task = task_name
def _drop_task(self, task_name):
if task_name in self._task_specific_attributes:
if self._current_task == task_name:
log.error(
"`%s` is the current task." " Switch to some other task before dropping this.",
task_name,
)
else:
self._task_specific_attributes.pop(task_name)
else:
log.warning("No task exists with the name `%s`.", task_name)
@staticmethod
def _filter_empty_sentences(sentences: List[Sentence]) -> List[Sentence]:
filtered_sentences = [sentence for sentence in sentences if sentence.tokens]
if len(sentences) != len(filtered_sentences):
log.warning(f"Ignore {len(sentences) - len(filtered_sentences)} sentence(s) with no tokens.")
return filtered_sentences
@property
def label_type(self):
return self.get_current_label_type()
def predict_zero_shot(
self,
sentences: Union[List[Sentence], Sentence],
candidate_label_set: Union[List[str], Set[str], str],
multi_label: bool = True,
):
if candidate_label_set is None or len(candidate_label_set) == 0:
log.warning("Provided candidate_label_set is empty")
return
if isinstance(candidate_label_set, str):
candidate_label_set = {candidate_label_set}
label_dictionary = Dictionary(add_unk=False)
for label in candidate_label_set:
label_dictionary.add_item(label)
existing_current_task = self._current_task
self.add_and_switch_to_new_task(
task_name="ZeroShot",
label_dictionary=label_dictionary,
label_type="-".join(label_dictionary.get_items()),
multi_label=multi_label,
)
try:
self.predict(sentences)
finally:
self.switch_to_task(existing_current_task)
self._drop_task("ZeroShot")
return
class TARSTagger(FewshotClassifier):
static_label_type = "tars_label"
def __init__(
self,
task_name: Optional[str] = None,
label_dictionary: Optional[Dictionary] = None,
label_type: Optional[str] = None,
embeddings: Union[TransformerWordEmbeddings, str] = "bert-base-uncased",
num_negative_labels_to_sample: int = 2,
prefix: bool = True,
**tagger_args,
):
super(TARSTagger, self).__init__()
if isinstance(embeddings, str):
embeddings = TransformerWordEmbeddings(
model=embeddings,
fine_tune=True,
layers="-1",
layer_mean=False,
)
tars_dictionary = Dictionary(add_unk=False)
tars_dictionary.add_item("entity")
tars_dictionary.span_labels = True
self.tars_model: SequenceTagger = SequenceTagger(
hidden_size=123,
embeddings=embeddings,
tag_dictionary=tars_dictionary,
tag_type=self.static_label_type,
use_crf=False,
use_rnn=False,
reproject_embeddings=False,
**tagger_args,
)
self.separator = str(self.tars_embeddings.tokenizer.sep_token)
if self.tars_embeddings.tokenizer._bos_token:
self.separator += str(self.tars_embeddings.tokenizer.bos_token)
self.prefix = prefix
self.num_negative_labels_to_sample = num_negative_labels_to_sample
if task_name and label_dictionary and label_type:
self.add_and_switch_to_new_task(task_name, label_dictionary, label_type)
else:
log.info(
"TARS initialized without a task. You need to call .add_and_switch_to_new_task() "
"before training this model"
)
def _get_tars_formatted_sentence(self, label, sentence):
original_text = sentence.to_tokenized_string()
label_text_pair = (
f"{label} {self.separator} {original_text}" if self.prefix else f"{original_text} {self.separator} {label}"
)
label_length = 0 if not self.prefix else len(label.split(" ")) + len(self.separator.split(" "))
tars_sentence = Sentence(label_text_pair, use_tokenizer=False)
for entity_label in sentence.get_labels(self.label_type):
if entity_label.value == label:
new_span = [tars_sentence.get_token(token.idx + label_length) for token in entity_label.span]
tars_sentence.add_complex_label(self.static_label_type, SpanLabel(Span(new_span), value="entity"))
return tars_sentence
def _get_state_dict(self):
model_state = {
"state_dict": self.state_dict(),
"current_task": self._current_task,
"tag_type": self.get_current_label_type(),
"tag_dictionary": self.get_current_label_dictionary(),
"tars_model": self.tars_model,
"num_negative_labels_to_sample": self.num_negative_labels_to_sample,
"prefix": self.prefix,
"task_specific_attributes": self._task_specific_attributes,
}
return model_state
@staticmethod
def _fetch_model(model_name) -> str:
if model_name == "tars-ner":
cache_dir = Path("models")
model_name = cached_path(
"https://nlp.informatik.hu-berlin.de/resources/models/tars-ner/tars-ner.pt",
cache_dir=cache_dir,
)
return model_name
@staticmethod
def _init_model_with_state_dict(state):
model = TARSTagger(
task_name=state["current_task"],
label_dictionary=state["tag_dictionary"],
label_type=state["tag_type"],
embeddings=state["tars_model"].embeddings,
num_negative_labels_to_sample=state["num_negative_labels_to_sample"],
prefix=state["prefix"],
)
model._task_specific_attributes = state["task_specific_attributes"]
model.load_state_dict(state["state_dict"])
return model
@property
def tars_embeddings(self):
return self.tars_model.embeddings
def predict(
self,
sentences: Union[List[Sentence], Sentence],
mini_batch_size=32,
return_probabilities_for_all_classes: bool = False,
verbose: bool = False,
label_name: Optional[str] = None,
return_loss=False,
embedding_storage_mode="none",
most_probable_first: bool = True,
):
if label_name is None:
label_name = self.get_current_label_type()
if not sentences:
return sentences
if not isinstance(sentences, list):
sentences = [sentences]
reordered_sentences = sorted(sentences, key=lambda s: len(s), reverse=True)
dataloader = DataLoader(
dataset=FlairDatapointDataset(reordered_sentences),
batch_size=mini_batch_size,
)
if verbose:
dataloader = tqdm(dataloader)
overall_loss = 0
overall_count = 0
with torch.no_grad():
for batch in dataloader:
batch = self._filter_empty_sentences(batch)
if not batch:
continue
for sentence in batch:
sentence.remove_labels(label_name)
all_labels = [label.decode("utf-8") for label in self.get_current_label_dictionary().idx2item]
all_detected = {}
for label in all_labels:
tars_sentence = self._get_tars_formatted_sentence(label, sentence)
loss_and_count = self.tars_model.predict(
tars_sentence,
label_name=label_name,
return_loss=True,
)
overall_loss += loss_and_count[0].item()
overall_count += loss_and_count[1]
for predicted in tars_sentence.get_labels(label_name):
predicted.value = label
all_detected[predicted] = predicted.score
if most_probable_first:
import operator
already_set_indices: List[int] = []
sorted_x = sorted(all_detected.items(), key=operator.itemgetter(1))
sorted_x.reverse()
for tuple in sorted_x:
label = tuple[0]
label_length = (
0 if not self.prefix else len(label.value.split(" ")) + len(self.separator.split(" "))
)
tag_this = True
for token in label.span:
corresponding_token = sentence.get_token(token.idx - label_length)
if corresponding_token is None:
tag_this = False
continue
if token.idx in already_set_indices:
tag_this = False
continue
if tag_this:
already_set_indices.extend(token.idx for token in label.span)
predicted_span = [sentence.get_token(token.idx - label_length) for token in label.span]
sentence.add_complex_label(
label_name,
label=SpanLabel(Span(predicted_span), value=label.value, score=label.score),
)
store_embeddings(batch, storage_mode=embedding_storage_mode)
if return_loss:
return overall_loss, overall_count
class TARSClassifier(FewshotClassifier):
static_label_type = "tars_label"
LABEL_MATCH = "YES"
LABEL_NO_MATCH = "NO"
def __init__(
self,
task_name: Optional[str] = None,
label_dictionary: Optional[Dictionary] = None,
label_type: Optional[str] = None,
embeddings: Union[TransformerDocumentEmbeddings, str] = "bert-base-uncased",
num_negative_labels_to_sample: int = 2,
prefix: bool = True,
**tagger_args,
):
super(TARSClassifier, self).__init__()
if isinstance(embeddings, str):
embeddings = TransformerDocumentEmbeddings(
model=embeddings,
fine_tune=True,
layers="-1",
layer_mean=False,
)
tars_dictionary = Dictionary(add_unk=False)
tars_dictionary.add_item(self.LABEL_NO_MATCH)
tars_dictionary.add_item(self.LABEL_MATCH)
self.tars_model = TextClassifier(
document_embeddings=embeddings,
label_dictionary=tars_dictionary,
label_type=self.static_label_type,
**tagger_args,
)
self.separator = str(self.tars_embeddings.tokenizer.sep_token)
if self.tars_embeddings.tokenizer._bos_token:
self.separator += str(self.tars_embeddings.tokenizer.bos_token)
self.prefix = prefix
self.num_negative_labels_to_sample = num_negative_labels_to_sample
if task_name and label_dictionary and label_type:
self.add_and_switch_to_new_task(task_name, label_dictionary, label_type)
else:
log.info(
"TARS initialized without a task. You need to call .add_and_switch_to_new_task() "
"before training this model"
)
self.clean_up_labels = True
def _clean(self, label_value: str) -> str:
if self.clean_up_labels:
return label_value.replace("_", " ")
else:
return label_value
def _get_tars_formatted_sentence(self, label, sentence):
label = self._clean(label)
original_text = sentence.to_tokenized_string()
label_text_pair = (
f"{label} {self.separator} {original_text}" if self.prefix else f"{original_text} {self.separator} {label}"
)
sentence_labels = [self._clean(label.value) for label in sentence.get_labels(self.get_current_label_type())]
tars_label = self.LABEL_MATCH if label in sentence_labels else self.LABEL_NO_MATCH
tars_sentence = Sentence(label_text_pair, use_tokenizer=False).add_label(self.static_label_type, tars_label)
return tars_sentence
def _get_state_dict(self):
model_state = {
"state_dict": self.state_dict(),
"current_task": self._current_task,
"label_type": self.get_current_label_type(),
"label_dictionary": self.get_current_label_dictionary(),
"tars_model": self.tars_model,
"num_negative_labels_to_sample": self.num_negative_labels_to_sample,
"task_specific_attributes": self._task_specific_attributes,
}
return model_state
@staticmethod
def _init_model_with_state_dict(state):
label_dictionary = state["label_dictionary"]
label_type = "default_label" if not state["label_type"] else state["label_type"]
model: TARSClassifier = TARSClassifier(
task_name=state["current_task"],
label_dictionary=label_dictionary,
label_type=label_type,
embeddings=state["tars_model"].document_embeddings,
num_negative_labels_to_sample=state["num_negative_labels_to_sample"],
)
model._task_specific_attributes = state["task_specific_attributes"]
model.load_state_dict(state["state_dict"])
return model
@staticmethod
def _fetch_model(model_name) -> str:
model_map = {}
hu_path: str = "https://nlp.informatik.hu-berlin.de/resources/models"
model_map["tars-base"] = "/".join([hu_path, "tars-base", "tars-base-v8.pt"])
cache_dir = Path("models")
if model_name in model_map:
model_name = cached_path(model_map[model_name], cache_dir=cache_dir)
return model_name
@property
def tars_embeddings(self):
return self.tars_model.document_embeddings
def predict(
self,
sentences: Union[List[Sentence], Sentence],
mini_batch_size=32,
return_probabilities_for_all_classes: bool = False,
verbose: bool = False,
label_name: Optional[str] = None,
return_loss=False,
embedding_storage_mode="none",
label_threshold: float = 0.5,
multi_label: Optional[bool] = None,
):
if label_name is None:
label_name = self.get_current_label_type()
if multi_label is None:
multi_label = self.is_current_task_multi_label()
if not sentences:
return sentences
if isinstance(sentences, Sentence):
sentences = [sentences]
previous_sentence = None
for sentence in sentences:
if sentence.is_context_set():
continue
sentence._previous_sentence = previous_sentence
sentence._next_sentence = None
if previous_sentence:
previous_sentence._next_sentence = sentence
previous_sentence = sentence
reordered_sentences = sorted(sentences, key=lambda s: len(s), reverse=True)
dataloader = DataLoader(
dataset=FlairDatapointDataset(reordered_sentences),
batch_size=mini_batch_size,
)
if verbose:
progressbar = tqdm(dataloader)
progressbar.set_description("Batch inference")
dataloader = progressbar
overall_loss = 0
overall_count = 0
batch_no = 0
with torch.no_grad():
for batch in dataloader:
batch_no += 1
batch = self._filter_empty_sentences(batch)
if not batch:
continue
for sentence in batch:
sentence.remove_labels(label_name)
all_labels = [label.decode("utf-8") for label in self.get_current_label_dictionary().idx2item]
best_label = None
for label in all_labels:
tars_sentence = self._get_tars_formatted_sentence(label, sentence)
loss_and_count = self.tars_model.predict(
tars_sentence,
label_name=label_name,
return_loss=True,
return_probabilities_for_all_classes=True if label_threshold < 0.5 else False,
)
overall_loss += loss_and_count[0].item()
overall_count += loss_and_count[1]
for predicted_tars_label in tars_sentence.get_labels(label_name):
if (
predicted_tars_label.value == self.LABEL_MATCH
and predicted_tars_label.score > label_threshold
):
sentence.add_label(label_name, label, predicted_tars_label.score)
if not multi_label:
if len(sentence.get_labels(label_name)) > 0:
label_scores = torch.tensor(
[label.score for label in sentence.get_labels(label_name)],
dtype=torch.float,
)
best_label = sentence.get_labels(label_name)[torch.argmax(label_scores)]
sentence.remove_labels(label_name)
sentence.add_label(
typename=label_name,
value=best_label.value,
score=best_label.score,
)
store_embeddings(batch, storage_mode=embedding_storage_mode)
if return_loss:
return overall_loss, overall_count
| true | true |
790bddf374f1b0f87510fa0b5072d6a169218040 | 508 | py | Python | satchmo/apps/payment/modules/cod/urls.py | pyarun/satchmo | 78fc9a923aada312924c1476e4653ee6527c11ef | [
"BSD-3-Clause"
] | 16 | 2015-03-06T14:42:27.000Z | 2019-12-23T21:37:01.000Z | satchmo/apps/payment/modules/cod/urls.py | pyarun/satchmo | 78fc9a923aada312924c1476e4653ee6527c11ef | [
"BSD-3-Clause"
] | null | null | null | satchmo/apps/payment/modules/cod/urls.py | pyarun/satchmo | 78fc9a923aada312924c1476e4653ee6527c11ef | [
"BSD-3-Clause"
] | 8 | 2015-01-28T16:02:37.000Z | 2022-03-03T21:29:40.000Z | from django.conf.urls.defaults import patterns
from satchmo_store.shop.satchmo_settings import get_satchmo_setting
ssl = get_satchmo_setting('SSL', default_value=False)
urlpatterns = patterns('',
(r'^$', 'payment.modules.cod.views.pay_ship_info', {'SSL':ssl}, 'COD_satchmo_checkout-step2'),
(r'^confirm/$', 'payment.modules.cod.views.confirm_info', {'SSL':ssl}, 'COD_satchmo_checkout-step3'),
(r'^success/$', 'payment.views.checkout.success', {'SSL':ssl}, 'COD_satchmo_checkout-success'),
)
| 46.181818 | 106 | 0.732283 | from django.conf.urls.defaults import patterns
from satchmo_store.shop.satchmo_settings import get_satchmo_setting
ssl = get_satchmo_setting('SSL', default_value=False)
urlpatterns = patterns('',
(r'^$', 'payment.modules.cod.views.pay_ship_info', {'SSL':ssl}, 'COD_satchmo_checkout-step2'),
(r'^confirm/$', 'payment.modules.cod.views.confirm_info', {'SSL':ssl}, 'COD_satchmo_checkout-step3'),
(r'^success/$', 'payment.views.checkout.success', {'SSL':ssl}, 'COD_satchmo_checkout-success'),
)
| true | true |
790bde4c8f915dec0c95f3c3f81e6ec9e79321d8 | 25,965 | py | Python | python/Lib/test/test_compileall.py | jasam/ciclo_vida_datos_scraping | 3f7cffc944a0a0752a502dc7868cf43c4144f16c | [
"MIT"
] | null | null | null | python/Lib/test/test_compileall.py | jasam/ciclo_vida_datos_scraping | 3f7cffc944a0a0752a502dc7868cf43c4144f16c | [
"MIT"
] | null | null | null | python/Lib/test/test_compileall.py | jasam/ciclo_vida_datos_scraping | 3f7cffc944a0a0752a502dc7868cf43c4144f16c | [
"MIT"
] | null | null | null | import sys
import compileall
import importlib.util
import test.test_importlib.util
import os
import pathlib
import py_compile
import shutil
import struct
import tempfile
import time
import unittest
import io
from unittest import mock, skipUnless
try:
from concurrent.futures import ProcessPoolExecutor
_have_multiprocessing = True
except ImportError:
_have_multiprocessing = False
from test import support
from test.support import script_helper
from .test_py_compile import without_source_date_epoch
from .test_py_compile import SourceDateEpochTestMeta
class CompileallTestsBase:
def setUp(self):
self.directory = tempfile.mkdtemp()
self.source_path = os.path.join(self.directory, '_test.py')
self.bc_path = importlib.util.cache_from_source(self.source_path)
with open(self.source_path, 'w') as file:
file.write('x = 123\n')
self.source_path2 = os.path.join(self.directory, '_test2.py')
self.bc_path2 = importlib.util.cache_from_source(self.source_path2)
shutil.copyfile(self.source_path, self.source_path2)
self.subdirectory = os.path.join(self.directory, '_subdir')
os.mkdir(self.subdirectory)
self.source_path3 = os.path.join(self.subdirectory, '_test3.py')
shutil.copyfile(self.source_path, self.source_path3)
def tearDown(self):
shutil.rmtree(self.directory)
def add_bad_source_file(self):
self.bad_source_path = os.path.join(self.directory, '_test_bad.py')
with open(self.bad_source_path, 'w') as file:
file.write('x (\n')
def timestamp_metadata(self):
with open(self.bc_path, 'rb') as file:
data = file.read(12)
mtime = int(os.stat(self.source_path).st_mtime)
compare = struct.pack('<4sll', importlib.util.MAGIC_NUMBER, 0, mtime)
return data, compare
def recreation_check(self, metadata):
"""Check that compileall recreates bytecode when the new metadata is
used."""
if os.environ.get('SOURCE_DATE_EPOCH'):
raise unittest.SkipTest('SOURCE_DATE_EPOCH is set')
py_compile.compile(self.source_path)
self.assertEqual(*self.timestamp_metadata())
with open(self.bc_path, 'rb') as file:
bc = file.read()[len(metadata):]
with open(self.bc_path, 'wb') as file:
file.write(metadata)
file.write(bc)
self.assertNotEqual(*self.timestamp_metadata())
compileall.compile_dir(self.directory, force=False, quiet=True)
self.assertTrue(*self.timestamp_metadata())
def test_mtime(self):
# Test a change in mtime leads to a new .pyc.
self.recreation_check(struct.pack('<4sll', importlib.util.MAGIC_NUMBER,
0, 1))
def test_magic_number(self):
# Test a change in mtime leads to a new .pyc.
self.recreation_check(b'\0\0\0\0')
def test_compile_files(self):
# Test compiling a single file, and complete directory
for fn in (self.bc_path, self.bc_path2):
try:
os.unlink(fn)
except:
pass
self.assertTrue(compileall.compile_file(self.source_path,
force=False, quiet=True))
self.assertTrue(os.path.isfile(self.bc_path) and
not os.path.isfile(self.bc_path2))
os.unlink(self.bc_path)
self.assertTrue(compileall.compile_dir(self.directory, force=False,
quiet=True))
self.assertTrue(os.path.isfile(self.bc_path) and
os.path.isfile(self.bc_path2))
os.unlink(self.bc_path)
os.unlink(self.bc_path2)
# Test against bad files
self.add_bad_source_file()
self.assertFalse(compileall.compile_file(self.bad_source_path,
force=False, quiet=2))
self.assertFalse(compileall.compile_dir(self.directory,
force=False, quiet=2))
def test_compile_file_pathlike(self):
self.assertFalse(os.path.isfile(self.bc_path))
# we should also test the output
with support.captured_stdout() as stdout:
self.assertTrue(compileall.compile_file(pathlib.Path(self.source_path)))
self.assertRegex(stdout.getvalue(), r'Compiling ([^WindowsPath|PosixPath].*)')
self.assertTrue(os.path.isfile(self.bc_path))
def test_compile_file_pathlike_ddir(self):
self.assertFalse(os.path.isfile(self.bc_path))
self.assertTrue(compileall.compile_file(pathlib.Path(self.source_path),
ddir=pathlib.Path('ddir_path'),
quiet=2))
self.assertTrue(os.path.isfile(self.bc_path))
def test_compile_path(self):
with test.test_importlib.util.import_state(path=[self.directory]):
self.assertTrue(compileall.compile_path(quiet=2))
with test.test_importlib.util.import_state(path=[self.directory]):
self.add_bad_source_file()
self.assertFalse(compileall.compile_path(skip_curdir=False,
force=True, quiet=2))
def test_no_pycache_in_non_package(self):
# Bug 8563 reported that __pycache__ directories got created by
# compile_file() for non-.py files.
data_dir = os.path.join(self.directory, 'data')
data_file = os.path.join(data_dir, 'file')
os.mkdir(data_dir)
# touch data/file
with open(data_file, 'w'):
pass
compileall.compile_file(data_file)
self.assertFalse(os.path.exists(os.path.join(data_dir, '__pycache__')))
def test_optimize(self):
# make sure compiling with different optimization settings than the
# interpreter's creates the correct file names
optimize, opt = (1, 1) if __debug__ else (0, '')
compileall.compile_dir(self.directory, quiet=True, optimize=optimize)
cached = importlib.util.cache_from_source(self.source_path,
optimization=opt)
self.assertTrue(os.path.isfile(cached))
cached2 = importlib.util.cache_from_source(self.source_path2,
optimization=opt)
self.assertTrue(os.path.isfile(cached2))
cached3 = importlib.util.cache_from_source(self.source_path3,
optimization=opt)
self.assertTrue(os.path.isfile(cached3))
def test_compile_dir_pathlike(self):
self.assertFalse(os.path.isfile(self.bc_path))
with support.captured_stdout() as stdout:
compileall.compile_dir(pathlib.Path(self.directory))
line = stdout.getvalue().splitlines()[0]
self.assertRegex(line, r'Listing ([^WindowsPath|PosixPath].*)')
self.assertTrue(os.path.isfile(self.bc_path))
@mock.patch('concurrent.futures.ProcessPoolExecutor')
def test_compile_pool_called(self, pool_mock):
compileall.compile_dir(self.directory, quiet=True, workers=5)
self.assertTrue(pool_mock.called)
def test_compile_workers_non_positive(self):
with self.assertRaisesRegex(ValueError,
"workers must be greater or equal to 0"):
compileall.compile_dir(self.directory, workers=-1)
@mock.patch('concurrent.futures.ProcessPoolExecutor')
def test_compile_workers_cpu_count(self, pool_mock):
compileall.compile_dir(self.directory, quiet=True, workers=0)
self.assertEqual(pool_mock.call_args[1]['max_workers'], None)
@mock.patch('concurrent.futures.ProcessPoolExecutor')
@mock.patch('compileall.compile_file')
def test_compile_one_worker(self, compile_file_mock, pool_mock):
compileall.compile_dir(self.directory, quiet=True)
self.assertFalse(pool_mock.called)
self.assertTrue(compile_file_mock.called)
@mock.patch('concurrent.futures.ProcessPoolExecutor', new=None)
@mock.patch('compileall.compile_file')
def test_compile_missing_multiprocessing(self, compile_file_mock):
compileall.compile_dir(self.directory, quiet=True, workers=5)
self.assertTrue(compile_file_mock.called)
class CompileallTestsWithSourceEpoch(CompileallTestsBase,
unittest.TestCase,
metaclass=SourceDateEpochTestMeta,
source_date_epoch=True):
pass
class CompileallTestsWithoutSourceEpoch(CompileallTestsBase,
unittest.TestCase,
metaclass=SourceDateEpochTestMeta,
source_date_epoch=False):
pass
class EncodingTest(unittest.TestCase):
"""Issue 6716: compileall should escape source code when printing errors
to stdout."""
def setUp(self):
self.directory = tempfile.mkdtemp()
self.source_path = os.path.join(self.directory, '_test.py')
with open(self.source_path, 'w', encoding='utf-8') as file:
file.write('# -*- coding: utf-8 -*-\n')
file.write('print u"\u20ac"\n')
def tearDown(self):
shutil.rmtree(self.directory)
def test_error(self):
try:
orig_stdout = sys.stdout
sys.stdout = io.TextIOWrapper(io.BytesIO(),encoding='ascii')
compileall.compile_dir(self.directory)
finally:
sys.stdout = orig_stdout
class CommandLineTestsBase:
"""Test compileall's CLI."""
@classmethod
def setUpClass(cls):
for path in filter(os.path.isdir, sys.path):
directory_created = False
directory = pathlib.Path(path) / '__pycache__'
path = directory / 'test.try'
try:
if not directory.is_dir():
directory.mkdir()
directory_created = True
with path.open('w') as file:
file.write('# for test_compileall')
except OSError:
sys_path_writable = False
break
finally:
support.unlink(str(path))
if directory_created:
directory.rmdir()
else:
sys_path_writable = True
cls._sys_path_writable = sys_path_writable
def _skip_if_sys_path_not_writable(self):
if not self._sys_path_writable:
raise unittest.SkipTest('not all entries on sys.path are writable')
def _get_run_args(self, args):
return [*support.optim_args_from_interpreter_flags(),
'-S', '-m', 'compileall',
*args]
def assertRunOK(self, *args, **env_vars):
rc, out, err = script_helper.assert_python_ok(
*self._get_run_args(args), **env_vars)
self.assertEqual(b'', err)
return out
def assertRunNotOK(self, *args, **env_vars):
rc, out, err = script_helper.assert_python_failure(
*self._get_run_args(args), **env_vars)
return rc, out, err
def assertCompiled(self, fn):
path = importlib.util.cache_from_source(fn)
self.assertTrue(os.path.exists(path))
def assertNotCompiled(self, fn):
path = importlib.util.cache_from_source(fn)
self.assertFalse(os.path.exists(path))
def setUp(self):
self.directory = tempfile.mkdtemp()
self.addCleanup(support.rmtree, self.directory)
self.pkgdir = os.path.join(self.directory, 'foo')
os.mkdir(self.pkgdir)
self.pkgdir_cachedir = os.path.join(self.pkgdir, '__pycache__')
# Create the __init__.py and a package module.
self.initfn = script_helper.make_script(self.pkgdir, '__init__', '')
self.barfn = script_helper.make_script(self.pkgdir, 'bar', '')
def test_no_args_compiles_path(self):
# Note that -l is implied for the no args case.
self._skip_if_sys_path_not_writable()
bazfn = script_helper.make_script(self.directory, 'baz', '')
self.assertRunOK(PYTHONPATH=self.directory)
self.assertCompiled(bazfn)
self.assertNotCompiled(self.initfn)
self.assertNotCompiled(self.barfn)
@without_source_date_epoch # timestamp invalidation test
def test_no_args_respects_force_flag(self):
self._skip_if_sys_path_not_writable()
bazfn = script_helper.make_script(self.directory, 'baz', '')
self.assertRunOK(PYTHONPATH=self.directory)
pycpath = importlib.util.cache_from_source(bazfn)
# Set atime/mtime backward to avoid file timestamp resolution issues
os.utime(pycpath, (time.time()-60,)*2)
mtime = os.stat(pycpath).st_mtime
# Without force, no recompilation
self.assertRunOK(PYTHONPATH=self.directory)
mtime2 = os.stat(pycpath).st_mtime
self.assertEqual(mtime, mtime2)
# Now force it.
self.assertRunOK('-f', PYTHONPATH=self.directory)
mtime2 = os.stat(pycpath).st_mtime
self.assertNotEqual(mtime, mtime2)
def test_no_args_respects_quiet_flag(self):
self._skip_if_sys_path_not_writable()
script_helper.make_script(self.directory, 'baz', '')
noisy = self.assertRunOK(PYTHONPATH=self.directory)
self.assertIn(b'Listing ', noisy)
quiet = self.assertRunOK('-q', PYTHONPATH=self.directory)
self.assertNotIn(b'Listing ', quiet)
# Ensure that the default behavior of compileall's CLI is to create
# PEP 3147/PEP 488 pyc files.
for name, ext, switch in [
('normal', 'pyc', []),
('optimize', 'opt-1.pyc', ['-O']),
('doubleoptimize', 'opt-2.pyc', ['-OO']),
]:
def f(self, ext=ext, switch=switch):
script_helper.assert_python_ok(*(switch +
['-m', 'compileall', '-q', self.pkgdir]))
# Verify the __pycache__ directory contents.
self.assertTrue(os.path.exists(self.pkgdir_cachedir))
expected = sorted(base.format(sys.implementation.cache_tag, ext)
for base in ('__init__.{}.{}', 'bar.{}.{}'))
self.assertEqual(sorted(os.listdir(self.pkgdir_cachedir)), expected)
# Make sure there are no .pyc files in the source directory.
self.assertFalse([fn for fn in os.listdir(self.pkgdir)
if fn.endswith(ext)])
locals()['test_pep3147_paths_' + name] = f
def test_legacy_paths(self):
# Ensure that with the proper switch, compileall leaves legacy
# pyc files, and no __pycache__ directory.
self.assertRunOK('-b', '-q', self.pkgdir)
# Verify the __pycache__ directory contents.
self.assertFalse(os.path.exists(self.pkgdir_cachedir))
expected = sorted(['__init__.py', '__init__.pyc', 'bar.py',
'bar.pyc'])
self.assertEqual(sorted(os.listdir(self.pkgdir)), expected)
def test_multiple_runs(self):
# Bug 8527 reported that multiple calls produced empty
# __pycache__/__pycache__ directories.
self.assertRunOK('-q', self.pkgdir)
# Verify the __pycache__ directory contents.
self.assertTrue(os.path.exists(self.pkgdir_cachedir))
cachecachedir = os.path.join(self.pkgdir_cachedir, '__pycache__')
self.assertFalse(os.path.exists(cachecachedir))
# Call compileall again.
self.assertRunOK('-q', self.pkgdir)
self.assertTrue(os.path.exists(self.pkgdir_cachedir))
self.assertFalse(os.path.exists(cachecachedir))
@without_source_date_epoch # timestamp invalidation test
def test_force(self):
self.assertRunOK('-q', self.pkgdir)
pycpath = importlib.util.cache_from_source(self.barfn)
# set atime/mtime backward to avoid file timestamp resolution issues
os.utime(pycpath, (time.time()-60,)*2)
mtime = os.stat(pycpath).st_mtime
# without force, no recompilation
self.assertRunOK('-q', self.pkgdir)
mtime2 = os.stat(pycpath).st_mtime
self.assertEqual(mtime, mtime2)
# now force it.
self.assertRunOK('-q', '-f', self.pkgdir)
mtime2 = os.stat(pycpath).st_mtime
self.assertNotEqual(mtime, mtime2)
def test_recursion_control(self):
subpackage = os.path.join(self.pkgdir, 'spam')
os.mkdir(subpackage)
subinitfn = script_helper.make_script(subpackage, '__init__', '')
hamfn = script_helper.make_script(subpackage, 'ham', '')
self.assertRunOK('-q', '-l', self.pkgdir)
self.assertNotCompiled(subinitfn)
self.assertFalse(os.path.exists(os.path.join(subpackage, '__pycache__')))
self.assertRunOK('-q', self.pkgdir)
self.assertCompiled(subinitfn)
self.assertCompiled(hamfn)
def test_recursion_limit(self):
subpackage = os.path.join(self.pkgdir, 'spam')
subpackage2 = os.path.join(subpackage, 'ham')
subpackage3 = os.path.join(subpackage2, 'eggs')
for pkg in (subpackage, subpackage2, subpackage3):
script_helper.make_pkg(pkg)
subinitfn = os.path.join(subpackage, '__init__.py')
hamfn = script_helper.make_script(subpackage, 'ham', '')
spamfn = script_helper.make_script(subpackage2, 'spam', '')
eggfn = script_helper.make_script(subpackage3, 'egg', '')
self.assertRunOK('-q', '-r 0', self.pkgdir)
self.assertNotCompiled(subinitfn)
self.assertFalse(
os.path.exists(os.path.join(subpackage, '__pycache__')))
self.assertRunOK('-q', '-r 1', self.pkgdir)
self.assertCompiled(subinitfn)
self.assertCompiled(hamfn)
self.assertNotCompiled(spamfn)
self.assertRunOK('-q', '-r 2', self.pkgdir)
self.assertCompiled(subinitfn)
self.assertCompiled(hamfn)
self.assertCompiled(spamfn)
self.assertNotCompiled(eggfn)
self.assertRunOK('-q', '-r 5', self.pkgdir)
self.assertCompiled(subinitfn)
self.assertCompiled(hamfn)
self.assertCompiled(spamfn)
self.assertCompiled(eggfn)
def test_quiet(self):
noisy = self.assertRunOK(self.pkgdir)
quiet = self.assertRunOK('-q', self.pkgdir)
self.assertNotEqual(b'', noisy)
self.assertEqual(b'', quiet)
def test_silent(self):
script_helper.make_script(self.pkgdir, 'crunchyfrog', 'bad(syntax')
_, quiet, _ = self.assertRunNotOK('-q', self.pkgdir)
_, silent, _ = self.assertRunNotOK('-qq', self.pkgdir)
self.assertNotEqual(b'', quiet)
self.assertEqual(b'', silent)
def test_regexp(self):
self.assertRunOK('-q', '-x', r'ba[^\\/]*$', self.pkgdir)
self.assertNotCompiled(self.barfn)
self.assertCompiled(self.initfn)
def test_multiple_dirs(self):
pkgdir2 = os.path.join(self.directory, 'foo2')
os.mkdir(pkgdir2)
init2fn = script_helper.make_script(pkgdir2, '__init__', '')
bar2fn = script_helper.make_script(pkgdir2, 'bar2', '')
self.assertRunOK('-q', self.pkgdir, pkgdir2)
self.assertCompiled(self.initfn)
self.assertCompiled(self.barfn)
self.assertCompiled(init2fn)
self.assertCompiled(bar2fn)
def test_d_compile_error(self):
script_helper.make_script(self.pkgdir, 'crunchyfrog', 'bad(syntax')
rc, out, err = self.assertRunNotOK('-q', '-d', 'dinsdale', self.pkgdir)
self.assertRegex(out, b'File "dinsdale')
def test_d_runtime_error(self):
bazfn = script_helper.make_script(self.pkgdir, 'baz', 'raise Exception')
self.assertRunOK('-q', '-d', 'dinsdale', self.pkgdir)
fn = script_helper.make_script(self.pkgdir, 'bing', 'import baz')
pyc = importlib.util.cache_from_source(bazfn)
os.rename(pyc, os.path.join(self.pkgdir, 'baz.pyc'))
os.remove(bazfn)
rc, out, err = script_helper.assert_python_failure(fn, __isolated=False)
self.assertRegex(err, b'File "dinsdale')
def test_include_bad_file(self):
rc, out, err = self.assertRunNotOK(
'-i', os.path.join(self.directory, 'nosuchfile'), self.pkgdir)
self.assertRegex(out, b'rror.*nosuchfile')
self.assertNotRegex(err, b'Traceback')
self.assertFalse(os.path.exists(importlib.util.cache_from_source(
self.pkgdir_cachedir)))
def test_include_file_with_arg(self):
f1 = script_helper.make_script(self.pkgdir, 'f1', '')
f2 = script_helper.make_script(self.pkgdir, 'f2', '')
f3 = script_helper.make_script(self.pkgdir, 'f3', '')
f4 = script_helper.make_script(self.pkgdir, 'f4', '')
with open(os.path.join(self.directory, 'l1'), 'w') as l1:
l1.write(os.path.join(self.pkgdir, 'f1.py')+os.linesep)
l1.write(os.path.join(self.pkgdir, 'f2.py')+os.linesep)
self.assertRunOK('-i', os.path.join(self.directory, 'l1'), f4)
self.assertCompiled(f1)
self.assertCompiled(f2)
self.assertNotCompiled(f3)
self.assertCompiled(f4)
def test_include_file_no_arg(self):
f1 = script_helper.make_script(self.pkgdir, 'f1', '')
f2 = script_helper.make_script(self.pkgdir, 'f2', '')
f3 = script_helper.make_script(self.pkgdir, 'f3', '')
f4 = script_helper.make_script(self.pkgdir, 'f4', '')
with open(os.path.join(self.directory, 'l1'), 'w') as l1:
l1.write(os.path.join(self.pkgdir, 'f2.py')+os.linesep)
self.assertRunOK('-i', os.path.join(self.directory, 'l1'))
self.assertNotCompiled(f1)
self.assertCompiled(f2)
self.assertNotCompiled(f3)
self.assertNotCompiled(f4)
def test_include_on_stdin(self):
f1 = script_helper.make_script(self.pkgdir, 'f1', '')
f2 = script_helper.make_script(self.pkgdir, 'f2', '')
f3 = script_helper.make_script(self.pkgdir, 'f3', '')
f4 = script_helper.make_script(self.pkgdir, 'f4', '')
p = script_helper.spawn_python(*(self._get_run_args(()) + ['-i', '-']))
p.stdin.write((f3+os.linesep).encode('ascii'))
script_helper.kill_python(p)
self.assertNotCompiled(f1)
self.assertNotCompiled(f2)
self.assertCompiled(f3)
self.assertNotCompiled(f4)
def test_compiles_as_much_as_possible(self):
bingfn = script_helper.make_script(self.pkgdir, 'bing', 'syntax(error')
rc, out, err = self.assertRunNotOK('nosuchfile', self.initfn,
bingfn, self.barfn)
self.assertRegex(out, b'rror')
self.assertNotCompiled(bingfn)
self.assertCompiled(self.initfn)
self.assertCompiled(self.barfn)
def test_invalid_arg_produces_message(self):
out = self.assertRunOK('badfilename')
self.assertRegex(out, b"Can't list 'badfilename'")
def test_pyc_invalidation_mode(self):
script_helper.make_script(self.pkgdir, 'f1', '')
pyc = importlib.util.cache_from_source(
os.path.join(self.pkgdir, 'f1.py'))
self.assertRunOK('--invalidation-mode=checked-hash', self.pkgdir)
with open(pyc, 'rb') as fp:
data = fp.read()
self.assertEqual(int.from_bytes(data[4:8], 'little'), 0b11)
self.assertRunOK('--invalidation-mode=unchecked-hash', self.pkgdir)
with open(pyc, 'rb') as fp:
data = fp.read()
self.assertEqual(int.from_bytes(data[4:8], 'little'), 0b01)
@skipUnless(_have_multiprocessing, "requires multiprocessing")
def test_workers(self):
bar2fn = script_helper.make_script(self.directory, 'bar2', '')
files = []
for suffix in range(5):
pkgdir = os.path.join(self.directory, 'foo{}'.format(suffix))
os.mkdir(pkgdir)
fn = script_helper.make_script(pkgdir, '__init__', '')
files.append(script_helper.make_script(pkgdir, 'bar2', ''))
self.assertRunOK(self.directory, '-j', '0')
self.assertCompiled(bar2fn)
for file in files:
self.assertCompiled(file)
@mock.patch('compileall.compile_dir')
def test_workers_available_cores(self, compile_dir):
with mock.patch("sys.argv",
new=[sys.executable, self.directory, "-j0"]):
compileall.main()
self.assertTrue(compile_dir.called)
self.assertEqual(compile_dir.call_args[-1]['workers'], 0)
class CommmandLineTestsWithSourceEpoch(CommandLineTestsBase,
unittest.TestCase,
metaclass=SourceDateEpochTestMeta,
source_date_epoch=True):
pass
class CommmandLineTestsNoSourceEpoch(CommandLineTestsBase,
unittest.TestCase,
metaclass=SourceDateEpochTestMeta,
source_date_epoch=False):
pass
if __name__ == "__main__":
unittest.main()
| 43.419732 | 87 | 0.611708 | import sys
import compileall
import importlib.util
import test.test_importlib.util
import os
import pathlib
import py_compile
import shutil
import struct
import tempfile
import time
import unittest
import io
from unittest import mock, skipUnless
try:
from concurrent.futures import ProcessPoolExecutor
_have_multiprocessing = True
except ImportError:
_have_multiprocessing = False
from test import support
from test.support import script_helper
from .test_py_compile import without_source_date_epoch
from .test_py_compile import SourceDateEpochTestMeta
class CompileallTestsBase:
def setUp(self):
self.directory = tempfile.mkdtemp()
self.source_path = os.path.join(self.directory, '_test.py')
self.bc_path = importlib.util.cache_from_source(self.source_path)
with open(self.source_path, 'w') as file:
file.write('x = 123\n')
self.source_path2 = os.path.join(self.directory, '_test2.py')
self.bc_path2 = importlib.util.cache_from_source(self.source_path2)
shutil.copyfile(self.source_path, self.source_path2)
self.subdirectory = os.path.join(self.directory, '_subdir')
os.mkdir(self.subdirectory)
self.source_path3 = os.path.join(self.subdirectory, '_test3.py')
shutil.copyfile(self.source_path, self.source_path3)
def tearDown(self):
shutil.rmtree(self.directory)
def add_bad_source_file(self):
self.bad_source_path = os.path.join(self.directory, '_test_bad.py')
with open(self.bad_source_path, 'w') as file:
file.write('x (\n')
def timestamp_metadata(self):
with open(self.bc_path, 'rb') as file:
data = file.read(12)
mtime = int(os.stat(self.source_path).st_mtime)
compare = struct.pack('<4sll', importlib.util.MAGIC_NUMBER, 0, mtime)
return data, compare
def recreation_check(self, metadata):
if os.environ.get('SOURCE_DATE_EPOCH'):
raise unittest.SkipTest('SOURCE_DATE_EPOCH is set')
py_compile.compile(self.source_path)
self.assertEqual(*self.timestamp_metadata())
with open(self.bc_path, 'rb') as file:
bc = file.read()[len(metadata):]
with open(self.bc_path, 'wb') as file:
file.write(metadata)
file.write(bc)
self.assertNotEqual(*self.timestamp_metadata())
compileall.compile_dir(self.directory, force=False, quiet=True)
self.assertTrue(*self.timestamp_metadata())
def test_mtime(self):
self.recreation_check(struct.pack('<4sll', importlib.util.MAGIC_NUMBER,
0, 1))
def test_magic_number(self):
self.recreation_check(b'\0\0\0\0')
def test_compile_files(self):
for fn in (self.bc_path, self.bc_path2):
try:
os.unlink(fn)
except:
pass
self.assertTrue(compileall.compile_file(self.source_path,
force=False, quiet=True))
self.assertTrue(os.path.isfile(self.bc_path) and
not os.path.isfile(self.bc_path2))
os.unlink(self.bc_path)
self.assertTrue(compileall.compile_dir(self.directory, force=False,
quiet=True))
self.assertTrue(os.path.isfile(self.bc_path) and
os.path.isfile(self.bc_path2))
os.unlink(self.bc_path)
os.unlink(self.bc_path2)
self.add_bad_source_file()
self.assertFalse(compileall.compile_file(self.bad_source_path,
force=False, quiet=2))
self.assertFalse(compileall.compile_dir(self.directory,
force=False, quiet=2))
def test_compile_file_pathlike(self):
self.assertFalse(os.path.isfile(self.bc_path))
with support.captured_stdout() as stdout:
self.assertTrue(compileall.compile_file(pathlib.Path(self.source_path)))
self.assertRegex(stdout.getvalue(), r'Compiling ([^WindowsPath|PosixPath].*)')
self.assertTrue(os.path.isfile(self.bc_path))
def test_compile_file_pathlike_ddir(self):
self.assertFalse(os.path.isfile(self.bc_path))
self.assertTrue(compileall.compile_file(pathlib.Path(self.source_path),
ddir=pathlib.Path('ddir_path'),
quiet=2))
self.assertTrue(os.path.isfile(self.bc_path))
def test_compile_path(self):
with test.test_importlib.util.import_state(path=[self.directory]):
self.assertTrue(compileall.compile_path(quiet=2))
with test.test_importlib.util.import_state(path=[self.directory]):
self.add_bad_source_file()
self.assertFalse(compileall.compile_path(skip_curdir=False,
force=True, quiet=2))
def test_no_pycache_in_non_package(self):
data_dir = os.path.join(self.directory, 'data')
data_file = os.path.join(data_dir, 'file')
os.mkdir(data_dir)
with open(data_file, 'w'):
pass
compileall.compile_file(data_file)
self.assertFalse(os.path.exists(os.path.join(data_dir, '__pycache__')))
def test_optimize(self):
optimize, opt = (1, 1) if __debug__ else (0, '')
compileall.compile_dir(self.directory, quiet=True, optimize=optimize)
cached = importlib.util.cache_from_source(self.source_path,
optimization=opt)
self.assertTrue(os.path.isfile(cached))
cached2 = importlib.util.cache_from_source(self.source_path2,
optimization=opt)
self.assertTrue(os.path.isfile(cached2))
cached3 = importlib.util.cache_from_source(self.source_path3,
optimization=opt)
self.assertTrue(os.path.isfile(cached3))
def test_compile_dir_pathlike(self):
self.assertFalse(os.path.isfile(self.bc_path))
with support.captured_stdout() as stdout:
compileall.compile_dir(pathlib.Path(self.directory))
line = stdout.getvalue().splitlines()[0]
self.assertRegex(line, r'Listing ([^WindowsPath|PosixPath].*)')
self.assertTrue(os.path.isfile(self.bc_path))
@mock.patch('concurrent.futures.ProcessPoolExecutor')
def test_compile_pool_called(self, pool_mock):
compileall.compile_dir(self.directory, quiet=True, workers=5)
self.assertTrue(pool_mock.called)
def test_compile_workers_non_positive(self):
with self.assertRaisesRegex(ValueError,
"workers must be greater or equal to 0"):
compileall.compile_dir(self.directory, workers=-1)
@mock.patch('concurrent.futures.ProcessPoolExecutor')
def test_compile_workers_cpu_count(self, pool_mock):
compileall.compile_dir(self.directory, quiet=True, workers=0)
self.assertEqual(pool_mock.call_args[1]['max_workers'], None)
@mock.patch('concurrent.futures.ProcessPoolExecutor')
@mock.patch('compileall.compile_file')
def test_compile_one_worker(self, compile_file_mock, pool_mock):
compileall.compile_dir(self.directory, quiet=True)
self.assertFalse(pool_mock.called)
self.assertTrue(compile_file_mock.called)
@mock.patch('concurrent.futures.ProcessPoolExecutor', new=None)
@mock.patch('compileall.compile_file')
def test_compile_missing_multiprocessing(self, compile_file_mock):
compileall.compile_dir(self.directory, quiet=True, workers=5)
self.assertTrue(compile_file_mock.called)
class CompileallTestsWithSourceEpoch(CompileallTestsBase,
unittest.TestCase,
metaclass=SourceDateEpochTestMeta,
source_date_epoch=True):
pass
class CompileallTestsWithoutSourceEpoch(CompileallTestsBase,
unittest.TestCase,
metaclass=SourceDateEpochTestMeta,
source_date_epoch=False):
pass
class EncodingTest(unittest.TestCase):
def setUp(self):
self.directory = tempfile.mkdtemp()
self.source_path = os.path.join(self.directory, '_test.py')
with open(self.source_path, 'w', encoding='utf-8') as file:
file.write('
file.write('print u"\u20ac"\n')
def tearDown(self):
shutil.rmtree(self.directory)
def test_error(self):
try:
orig_stdout = sys.stdout
sys.stdout = io.TextIOWrapper(io.BytesIO(),encoding='ascii')
compileall.compile_dir(self.directory)
finally:
sys.stdout = orig_stdout
class CommandLineTestsBase:
@classmethod
def setUpClass(cls):
for path in filter(os.path.isdir, sys.path):
directory_created = False
directory = pathlib.Path(path) / '__pycache__'
path = directory / 'test.try'
try:
if not directory.is_dir():
directory.mkdir()
directory_created = True
with path.open('w') as file:
file.write('
except OSError:
sys_path_writable = False
break
finally:
support.unlink(str(path))
if directory_created:
directory.rmdir()
else:
sys_path_writable = True
cls._sys_path_writable = sys_path_writable
def _skip_if_sys_path_not_writable(self):
if not self._sys_path_writable:
raise unittest.SkipTest('not all entries on sys.path are writable')
def _get_run_args(self, args):
return [*support.optim_args_from_interpreter_flags(),
'-S', '-m', 'compileall',
*args]
def assertRunOK(self, *args, **env_vars):
rc, out, err = script_helper.assert_python_ok(
*self._get_run_args(args), **env_vars)
self.assertEqual(b'', err)
return out
def assertRunNotOK(self, *args, **env_vars):
rc, out, err = script_helper.assert_python_failure(
*self._get_run_args(args), **env_vars)
return rc, out, err
def assertCompiled(self, fn):
path = importlib.util.cache_from_source(fn)
self.assertTrue(os.path.exists(path))
def assertNotCompiled(self, fn):
path = importlib.util.cache_from_source(fn)
self.assertFalse(os.path.exists(path))
def setUp(self):
self.directory = tempfile.mkdtemp()
self.addCleanup(support.rmtree, self.directory)
self.pkgdir = os.path.join(self.directory, 'foo')
os.mkdir(self.pkgdir)
self.pkgdir_cachedir = os.path.join(self.pkgdir, '__pycache__')
# Create the __init__.py and a package module.
self.initfn = script_helper.make_script(self.pkgdir, '__init__', '')
self.barfn = script_helper.make_script(self.pkgdir, 'bar', '')
def test_no_args_compiles_path(self):
# Note that -l is implied for the no args case.
self._skip_if_sys_path_not_writable()
bazfn = script_helper.make_script(self.directory, 'baz', '')
self.assertRunOK(PYTHONPATH=self.directory)
self.assertCompiled(bazfn)
self.assertNotCompiled(self.initfn)
self.assertNotCompiled(self.barfn)
@without_source_date_epoch # timestamp invalidation test
def test_no_args_respects_force_flag(self):
self._skip_if_sys_path_not_writable()
bazfn = script_helper.make_script(self.directory, 'baz', '')
self.assertRunOK(PYTHONPATH=self.directory)
pycpath = importlib.util.cache_from_source(bazfn)
# Set atime/mtime backward to avoid file timestamp resolution issues
os.utime(pycpath, (time.time()-60,)*2)
mtime = os.stat(pycpath).st_mtime
# Without force, no recompilation
self.assertRunOK(PYTHONPATH=self.directory)
mtime2 = os.stat(pycpath).st_mtime
self.assertEqual(mtime, mtime2)
# Now force it.
self.assertRunOK('-f', PYTHONPATH=self.directory)
mtime2 = os.stat(pycpath).st_mtime
self.assertNotEqual(mtime, mtime2)
def test_no_args_respects_quiet_flag(self):
self._skip_if_sys_path_not_writable()
script_helper.make_script(self.directory, 'baz', '')
noisy = self.assertRunOK(PYTHONPATH=self.directory)
self.assertIn(b'Listing ', noisy)
quiet = self.assertRunOK('-q', PYTHONPATH=self.directory)
self.assertNotIn(b'Listing ', quiet)
# Ensure that the default behavior of compileall's CLI is to create
for name, ext, switch in [
('normal', 'pyc', []),
('optimize', 'opt-1.pyc', ['-O']),
('doubleoptimize', 'opt-2.pyc', ['-OO']),
]:
def f(self, ext=ext, switch=switch):
script_helper.assert_python_ok(*(switch +
['-m', 'compileall', '-q', self.pkgdir]))
self.assertTrue(os.path.exists(self.pkgdir_cachedir))
expected = sorted(base.format(sys.implementation.cache_tag, ext)
for base in ('__init__.{}.{}', 'bar.{}.{}'))
self.assertEqual(sorted(os.listdir(self.pkgdir_cachedir)), expected)
self.assertFalse([fn for fn in os.listdir(self.pkgdir)
if fn.endswith(ext)])
locals()['test_pep3147_paths_' + name] = f
def test_legacy_paths(self):
self.assertRunOK('-b', '-q', self.pkgdir)
self.assertFalse(os.path.exists(self.pkgdir_cachedir))
expected = sorted(['__init__.py', '__init__.pyc', 'bar.py',
'bar.pyc'])
self.assertEqual(sorted(os.listdir(self.pkgdir)), expected)
def test_multiple_runs(self):
self.assertRunOK('-q', self.pkgdir)
self.assertTrue(os.path.exists(self.pkgdir_cachedir))
cachecachedir = os.path.join(self.pkgdir_cachedir, '__pycache__')
self.assertFalse(os.path.exists(cachecachedir))
self.assertRunOK('-q', self.pkgdir)
self.assertTrue(os.path.exists(self.pkgdir_cachedir))
self.assertFalse(os.path.exists(cachecachedir))
@without_source_date_epoch
def test_force(self):
self.assertRunOK('-q', self.pkgdir)
pycpath = importlib.util.cache_from_source(self.barfn)
os.utime(pycpath, (time.time()-60,)*2)
mtime = os.stat(pycpath).st_mtime
self.assertRunOK('-q', self.pkgdir)
mtime2 = os.stat(pycpath).st_mtime
self.assertEqual(mtime, mtime2)
self.assertRunOK('-q', '-f', self.pkgdir)
mtime2 = os.stat(pycpath).st_mtime
self.assertNotEqual(mtime, mtime2)
def test_recursion_control(self):
subpackage = os.path.join(self.pkgdir, 'spam')
os.mkdir(subpackage)
subinitfn = script_helper.make_script(subpackage, '__init__', '')
hamfn = script_helper.make_script(subpackage, 'ham', '')
self.assertRunOK('-q', '-l', self.pkgdir)
self.assertNotCompiled(subinitfn)
self.assertFalse(os.path.exists(os.path.join(subpackage, '__pycache__')))
self.assertRunOK('-q', self.pkgdir)
self.assertCompiled(subinitfn)
self.assertCompiled(hamfn)
def test_recursion_limit(self):
subpackage = os.path.join(self.pkgdir, 'spam')
subpackage2 = os.path.join(subpackage, 'ham')
subpackage3 = os.path.join(subpackage2, 'eggs')
for pkg in (subpackage, subpackage2, subpackage3):
script_helper.make_pkg(pkg)
subinitfn = os.path.join(subpackage, '__init__.py')
hamfn = script_helper.make_script(subpackage, 'ham', '')
spamfn = script_helper.make_script(subpackage2, 'spam', '')
eggfn = script_helper.make_script(subpackage3, 'egg', '')
self.assertRunOK('-q', '-r 0', self.pkgdir)
self.assertNotCompiled(subinitfn)
self.assertFalse(
os.path.exists(os.path.join(subpackage, '__pycache__')))
self.assertRunOK('-q', '-r 1', self.pkgdir)
self.assertCompiled(subinitfn)
self.assertCompiled(hamfn)
self.assertNotCompiled(spamfn)
self.assertRunOK('-q', '-r 2', self.pkgdir)
self.assertCompiled(subinitfn)
self.assertCompiled(hamfn)
self.assertCompiled(spamfn)
self.assertNotCompiled(eggfn)
self.assertRunOK('-q', '-r 5', self.pkgdir)
self.assertCompiled(subinitfn)
self.assertCompiled(hamfn)
self.assertCompiled(spamfn)
self.assertCompiled(eggfn)
def test_quiet(self):
noisy = self.assertRunOK(self.pkgdir)
quiet = self.assertRunOK('-q', self.pkgdir)
self.assertNotEqual(b'', noisy)
self.assertEqual(b'', quiet)
def test_silent(self):
script_helper.make_script(self.pkgdir, 'crunchyfrog', 'bad(syntax')
_, quiet, _ = self.assertRunNotOK('-q', self.pkgdir)
_, silent, _ = self.assertRunNotOK('-qq', self.pkgdir)
self.assertNotEqual(b'', quiet)
self.assertEqual(b'', silent)
def test_regexp(self):
self.assertRunOK('-q', '-x', r'ba[^\\/]*$', self.pkgdir)
self.assertNotCompiled(self.barfn)
self.assertCompiled(self.initfn)
def test_multiple_dirs(self):
pkgdir2 = os.path.join(self.directory, 'foo2')
os.mkdir(pkgdir2)
init2fn = script_helper.make_script(pkgdir2, '__init__', '')
bar2fn = script_helper.make_script(pkgdir2, 'bar2', '')
self.assertRunOK('-q', self.pkgdir, pkgdir2)
self.assertCompiled(self.initfn)
self.assertCompiled(self.barfn)
self.assertCompiled(init2fn)
self.assertCompiled(bar2fn)
def test_d_compile_error(self):
script_helper.make_script(self.pkgdir, 'crunchyfrog', 'bad(syntax')
rc, out, err = self.assertRunNotOK('-q', '-d', 'dinsdale', self.pkgdir)
self.assertRegex(out, b'File "dinsdale')
def test_d_runtime_error(self):
bazfn = script_helper.make_script(self.pkgdir, 'baz', 'raise Exception')
self.assertRunOK('-q', '-d', 'dinsdale', self.pkgdir)
fn = script_helper.make_script(self.pkgdir, 'bing', 'import baz')
pyc = importlib.util.cache_from_source(bazfn)
os.rename(pyc, os.path.join(self.pkgdir, 'baz.pyc'))
os.remove(bazfn)
rc, out, err = script_helper.assert_python_failure(fn, __isolated=False)
self.assertRegex(err, b'File "dinsdale')
def test_include_bad_file(self):
rc, out, err = self.assertRunNotOK(
'-i', os.path.join(self.directory, 'nosuchfile'), self.pkgdir)
self.assertRegex(out, b'rror.*nosuchfile')
self.assertNotRegex(err, b'Traceback')
self.assertFalse(os.path.exists(importlib.util.cache_from_source(
self.pkgdir_cachedir)))
def test_include_file_with_arg(self):
f1 = script_helper.make_script(self.pkgdir, 'f1', '')
f2 = script_helper.make_script(self.pkgdir, 'f2', '')
f3 = script_helper.make_script(self.pkgdir, 'f3', '')
f4 = script_helper.make_script(self.pkgdir, 'f4', '')
with open(os.path.join(self.directory, 'l1'), 'w') as l1:
l1.write(os.path.join(self.pkgdir, 'f1.py')+os.linesep)
l1.write(os.path.join(self.pkgdir, 'f2.py')+os.linesep)
self.assertRunOK('-i', os.path.join(self.directory, 'l1'), f4)
self.assertCompiled(f1)
self.assertCompiled(f2)
self.assertNotCompiled(f3)
self.assertCompiled(f4)
def test_include_file_no_arg(self):
f1 = script_helper.make_script(self.pkgdir, 'f1', '')
f2 = script_helper.make_script(self.pkgdir, 'f2', '')
f3 = script_helper.make_script(self.pkgdir, 'f3', '')
f4 = script_helper.make_script(self.pkgdir, 'f4', '')
with open(os.path.join(self.directory, 'l1'), 'w') as l1:
l1.write(os.path.join(self.pkgdir, 'f2.py')+os.linesep)
self.assertRunOK('-i', os.path.join(self.directory, 'l1'))
self.assertNotCompiled(f1)
self.assertCompiled(f2)
self.assertNotCompiled(f3)
self.assertNotCompiled(f4)
def test_include_on_stdin(self):
f1 = script_helper.make_script(self.pkgdir, 'f1', '')
f2 = script_helper.make_script(self.pkgdir, 'f2', '')
f3 = script_helper.make_script(self.pkgdir, 'f3', '')
f4 = script_helper.make_script(self.pkgdir, 'f4', '')
p = script_helper.spawn_python(*(self._get_run_args(()) + ['-i', '-']))
p.stdin.write((f3+os.linesep).encode('ascii'))
script_helper.kill_python(p)
self.assertNotCompiled(f1)
self.assertNotCompiled(f2)
self.assertCompiled(f3)
self.assertNotCompiled(f4)
def test_compiles_as_much_as_possible(self):
bingfn = script_helper.make_script(self.pkgdir, 'bing', 'syntax(error')
rc, out, err = self.assertRunNotOK('nosuchfile', self.initfn,
bingfn, self.barfn)
self.assertRegex(out, b'rror')
self.assertNotCompiled(bingfn)
self.assertCompiled(self.initfn)
self.assertCompiled(self.barfn)
def test_invalid_arg_produces_message(self):
out = self.assertRunOK('badfilename')
self.assertRegex(out, b"Can't list 'badfilename'")
def test_pyc_invalidation_mode(self):
script_helper.make_script(self.pkgdir, 'f1', '')
pyc = importlib.util.cache_from_source(
os.path.join(self.pkgdir, 'f1.py'))
self.assertRunOK('--invalidation-mode=checked-hash', self.pkgdir)
with open(pyc, 'rb') as fp:
data = fp.read()
self.assertEqual(int.from_bytes(data[4:8], 'little'), 0b11)
self.assertRunOK('--invalidation-mode=unchecked-hash', self.pkgdir)
with open(pyc, 'rb') as fp:
data = fp.read()
self.assertEqual(int.from_bytes(data[4:8], 'little'), 0b01)
@skipUnless(_have_multiprocessing, "requires multiprocessing")
def test_workers(self):
bar2fn = script_helper.make_script(self.directory, 'bar2', '')
files = []
for suffix in range(5):
pkgdir = os.path.join(self.directory, 'foo{}'.format(suffix))
os.mkdir(pkgdir)
fn = script_helper.make_script(pkgdir, '__init__', '')
files.append(script_helper.make_script(pkgdir, 'bar2', ''))
self.assertRunOK(self.directory, '-j', '0')
self.assertCompiled(bar2fn)
for file in files:
self.assertCompiled(file)
@mock.patch('compileall.compile_dir')
def test_workers_available_cores(self, compile_dir):
with mock.patch("sys.argv",
new=[sys.executable, self.directory, "-j0"]):
compileall.main()
self.assertTrue(compile_dir.called)
self.assertEqual(compile_dir.call_args[-1]['workers'], 0)
class CommmandLineTestsWithSourceEpoch(CommandLineTestsBase,
unittest.TestCase,
metaclass=SourceDateEpochTestMeta,
source_date_epoch=True):
pass
class CommmandLineTestsNoSourceEpoch(CommandLineTestsBase,
unittest.TestCase,
metaclass=SourceDateEpochTestMeta,
source_date_epoch=False):
pass
if __name__ == "__main__":
unittest.main()
| true | true |
790bde71f32ef92a78d6f1c5ef6f9b6e506297fb | 1,166 | py | Python | ml/Graph/pieChart2.py | Shivams9/pythoncodecamp | e6cd27f4704a407ee360414a8c9236b254117a59 | [
"MIT"
] | 6 | 2021-08-04T08:15:22.000Z | 2022-02-02T11:15:56.000Z | ML/Graph/pieChart2.py | Maurya232Abhishek/Python-repository-for-basics | 3dcec5c529a0847df07c9dcc1424675754ce6376 | [
"MIT"
] | 14 | 2021-08-02T06:28:00.000Z | 2022-03-25T10:44:15.000Z | ML/Graph/pieChart2.py | Maurya232Abhishek/Python-repository-for-basics | 3dcec5c529a0847df07c9dcc1424675754ce6376 | [
"MIT"
] | 6 | 2021-07-16T04:56:41.000Z | 2022-02-16T04:40:06.000Z | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
def f(x):
return 1-x
data=pd.read_csv("test.csv")
print(data)
roll=data["Rollno"]
t1 =data["t1"]
t2 = data["t2"]
print(roll,t1,t2)
plt.pie(t1,labels=roll,autopct="%1.2f%%")
plt.title("Marks in test1")
plt.show()
plt.pie(t2,labels=roll,autopct="%1.2f%%")
plt.title("Marks in test2")
plt.show()
data["t2-t1"]=data["t2"]-data["t1"]
print(data)
plt.title("Marks in test1")
benefit=0
notbenefit=0
for i in data['t2-t1']:
if i>0:
benefit +=1
else:
notbenefit +=1
print(benefit,notbenefit)
plt.pie([benefit,notbenefit],labels=["Benefitted","Not Benefitted"],autopct="%1.2f%%",explode=[0.1,0.1])
plt.title("Deciding")
plt.show()
range=["0-15","15-18","18-21","21-23","23-26"]
n = [0,0,0,0,0]
for i in data["t1"]:
if i < 15:
n[0] += 1
elif i < 18:
n[1] += 1
elif i < 21:
n[2] += 1
elif i < 23:
n[3] += 1
elif i < 26:
n[4] += 1
plt.pie(n,labels=range,autopct="%1.2f%%")
plt.show()
x = np.linspace(0,1,100)
plt.plot(x,f(x),color="red")
plt.xlim(0,1)
plt.ylim(0,1)
plt.title("happening Vs Not happening")
plt.show()
| 20.821429 | 104 | 0.596913 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
def f(x):
return 1-x
data=pd.read_csv("test.csv")
print(data)
roll=data["Rollno"]
t1 =data["t1"]
t2 = data["t2"]
print(roll,t1,t2)
plt.pie(t1,labels=roll,autopct="%1.2f%%")
plt.title("Marks in test1")
plt.show()
plt.pie(t2,labels=roll,autopct="%1.2f%%")
plt.title("Marks in test2")
plt.show()
data["t2-t1"]=data["t2"]-data["t1"]
print(data)
plt.title("Marks in test1")
benefit=0
notbenefit=0
for i in data['t2-t1']:
if i>0:
benefit +=1
else:
notbenefit +=1
print(benefit,notbenefit)
plt.pie([benefit,notbenefit],labels=["Benefitted","Not Benefitted"],autopct="%1.2f%%",explode=[0.1,0.1])
plt.title("Deciding")
plt.show()
range=["0-15","15-18","18-21","21-23","23-26"]
n = [0,0,0,0,0]
for i in data["t1"]:
if i < 15:
n[0] += 1
elif i < 18:
n[1] += 1
elif i < 21:
n[2] += 1
elif i < 23:
n[3] += 1
elif i < 26:
n[4] += 1
plt.pie(n,labels=range,autopct="%1.2f%%")
plt.show()
x = np.linspace(0,1,100)
plt.plot(x,f(x),color="red")
plt.xlim(0,1)
plt.ylim(0,1)
plt.title("happening Vs Not happening")
plt.show()
| true | true |
790bdeca139be6e684caea747631d810625a0bf6 | 25,834 | py | Python | magenta/models/score2perf/score2perf.py | flyingleafe/magenta | 2eb641e8f48c52e78d6b44fcbe9a7d168f787616 | [
"Apache-2.0"
] | null | null | null | magenta/models/score2perf/score2perf.py | flyingleafe/magenta | 2eb641e8f48c52e78d6b44fcbe9a7d168f787616 | [
"Apache-2.0"
] | null | null | null | magenta/models/score2perf/score2perf.py | flyingleafe/magenta | 2eb641e8f48c52e78d6b44fcbe9a7d168f787616 | [
"Apache-2.0"
] | null | null | null | # Copyright 2020 The Magenta Authors.
#
# 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.
"""Performance generation from score in Tensor2Tensor."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import functools
import itertools
from magenta.models.score2perf import datagen_beam
from magenta.models.score2perf import modalities
from magenta.models.score2perf import music_encoders
from note_seq import chord_symbols_lib
from note_seq import sequences_lib
from tensor2tensor.data_generators import problem
from tensor2tensor.layers import modalities as t2t_modalities
from tensor2tensor.models import transformer
from tensor2tensor.utils import registry
import tensorflow.compat.v1 as tf
# TODO(iansimon): figure out the best way not to hard-code these constants
NUM_VELOCITY_BINS = 32
STEPS_PER_SECOND = 100
MIN_PITCH = 21
MAX_PITCH = 108
# pylint: disable=line-too-long
MAESTRO_TFRECORD_PATHS = {
'train': 'gs://magentadata/datasets/maestro/v1.0.0/maestro-v1.0.0_train.tfrecord',
'dev': 'gs://magentadata/datasets/maestro/v1.0.0/maestro-v1.0.0_validation.tfrecord',
'test': 'gs://magentadata/datasets/maestro/v1.0.0/maestro-v1.0.0_test.tfrecord'
}
# pylint: enable=line-too-long
class Score2PerfProblem(problem.Problem):
"""Base class for musical score-to-performance problems.
Data files contain tf.Example protos with encoded performance in 'targets' and
optional encoded score in 'inputs'.
"""
@property
def splits(self):
"""Dictionary of split names and probabilities. Must sum to one."""
raise NotImplementedError()
@property
def min_hop_size_seconds(self):
"""Minimum hop size in seconds at which to split input performances."""
raise NotImplementedError()
@property
def max_hop_size_seconds(self):
"""Maximum hop size in seconds at which to split input performances."""
raise NotImplementedError()
@property
def num_replications(self):
"""Number of times entire input performances will be split."""
return 1
@property
def add_eos_symbol(self):
"""Whether to append EOS to encoded performances."""
raise NotImplementedError()
@property
def absolute_timing(self):
"""Whether or not score should use absolute (vs. tempo-relative) timing."""
return False
@property
def stretch_factors(self):
"""Temporal stretch factors for data augmentation (in datagen)."""
return [1.0]
@property
def transpose_amounts(self):
"""Pitch transposition amounts for data augmentation (in datagen)."""
return [0]
@property
def random_crop_length_in_datagen(self):
"""Randomly crop targets to this length in datagen."""
return None
@property
def random_crop_in_train(self):
"""Whether to randomly crop each training example when preprocessing."""
return False
@property
def split_in_eval(self):
"""Whether to split each eval example when preprocessing."""
return False
def performances_input_transform(self, tmp_dir):
"""Input performances beam transform (or dictionary thereof) for datagen."""
raise NotImplementedError()
def generate_data(self, data_dir, tmp_dir, task_id=-1):
del task_id
def augment_note_sequence(ns, stretch_factor, transpose_amount):
"""Augment a NoteSequence by time stretch and pitch transposition."""
augmented_ns = sequences_lib.stretch_note_sequence(
ns, stretch_factor, in_place=False)
try:
_, num_deleted_notes = sequences_lib.transpose_note_sequence(
augmented_ns, transpose_amount,
min_allowed_pitch=MIN_PITCH, max_allowed_pitch=MAX_PITCH,
in_place=True)
except chord_symbols_lib.ChordSymbolError:
raise datagen_beam.DataAugmentationError(
'Transposition of chord symbol(s) failed.')
if num_deleted_notes:
raise datagen_beam.DataAugmentationError(
'Transposition caused out-of-range pitch(es).')
return augmented_ns
augment_params = itertools.product(
self.stretch_factors, self.transpose_amounts)
augment_fns = [
functools.partial(augment_note_sequence,
stretch_factor=s, transpose_amount=t)
for s, t in augment_params
]
datagen_beam.generate_examples(
input_transform=self.performances_input_transform(tmp_dir),
output_dir=data_dir,
problem_name=self.dataset_filename(),
splits=self.splits,
min_hop_size_seconds=self.min_hop_size_seconds,
max_hop_size_seconds=self.max_hop_size_seconds,
min_pitch=MIN_PITCH,
max_pitch=MAX_PITCH,
num_replications=self.num_replications,
encode_performance_fn=self.performance_encoder().encode_note_sequence,
encode_score_fns=dict((name, encoder.encode_note_sequence)
for name, encoder in self.score_encoders()),
augment_fns=augment_fns,
absolute_timing=self.absolute_timing,
random_crop_length=self.random_crop_length_in_datagen)
def hparams(self, defaults, model_hparams):
del model_hparams # unused
perf_encoder = self.get_feature_encoders()['targets']
defaults.modality = {'targets': t2t_modalities.ModalityType.SYMBOL}
defaults.vocab_size = {'targets': perf_encoder.vocab_size}
if self.has_inputs:
score_encoder = self.get_feature_encoders()['inputs']
if isinstance(score_encoder.vocab_size, list):
# TODO(trandustin): We default to not applying any transformation; to
# apply one, pass modalities.bottom to the model's hparams.bottom. In
# future, refactor the tuple of the "inputs" feature to be part of the
# features dict itself, i.e., have multiple inputs each with its own
# modality and vocab size.
modality_cls = t2t_modalities.ModalityType.IDENTITY
else:
modality_cls = t2t_modalities.ModalityType.SYMBOL
defaults.modality['inputs'] = modality_cls
defaults.vocab_size['inputs'] = score_encoder.vocab_size
def performance_encoder(self):
"""Encoder for target performances."""
return music_encoders.MidiPerformanceEncoder(
steps_per_second=STEPS_PER_SECOND,
num_velocity_bins=NUM_VELOCITY_BINS,
min_pitch=MIN_PITCH,
max_pitch=MAX_PITCH,
add_eos=self.add_eos_symbol)
def score_encoders(self):
"""List of (name, encoder) tuples for input score components."""
return []
def feature_encoders(self, data_dir):
del data_dir
encoders = {
'targets': self.performance_encoder()
}
score_encoders = self.score_encoders()
if score_encoders:
if len(score_encoders) > 1:
# Create a composite score encoder, only used for inference.
encoders['inputs'] = music_encoders.CompositeScoreEncoder(
[encoder for _, encoder in score_encoders])
else:
# If only one score component, just use its encoder.
_, encoders['inputs'] = score_encoders[0]
return encoders
def example_reading_spec(self):
data_fields = {
'targets': tf.VarLenFeature(tf.int64)
}
for name, _ in self.score_encoders():
data_fields[name] = tf.VarLenFeature(tf.int64)
# We don't actually "decode" anything here; the encodings are simply read as
# tensors.
data_items_to_decoders = None
return data_fields, data_items_to_decoders
def preprocess_example(self, example, mode, hparams):
if self.has_inputs:
# Stack encoded score components depthwise as inputs.
inputs = []
for name, _ in self.score_encoders():
inputs.append(tf.expand_dims(example[name], axis=1))
del example[name]
example['inputs'] = tf.stack(inputs, axis=2)
if self.random_crop_in_train and mode == tf.estimator.ModeKeys.TRAIN:
# Take a random crop of the training example.
assert not self.has_inputs
max_offset = tf.maximum(
tf.shape(example['targets'])[0] - hparams.max_target_seq_length, 0)
offset = tf.cond(
max_offset > 0,
lambda: tf.random_uniform([], maxval=max_offset, dtype=tf.int32),
lambda: 0
)
example['targets'] = (
example['targets'][offset:offset + hparams.max_target_seq_length])
return example
elif self.split_in_eval and mode == tf.estimator.ModeKeys.EVAL:
# Split the example into non-overlapping segments.
assert not self.has_inputs
length = tf.shape(example['targets'])[0]
extra_length = tf.mod(length, hparams.max_target_seq_length)
examples = {
'targets': tf.reshape(
example['targets'][:length - extra_length],
[-1, hparams.max_target_seq_length, 1, 1])
}
extra_example = {
'targets': tf.reshape(
example['targets'][-extra_length:], [1, -1, 1, 1])
}
dataset = tf.data.Dataset.from_tensor_slices(examples)
extra_dataset = tf.data.Dataset.from_tensor_slices(extra_example)
return dataset.concatenate(extra_dataset)
else:
# If not cropping or splitting, do standard preprocessing.
return super(Score2PerfProblem, self).preprocess_example(
example, mode, hparams)
class ConditionalScore2PerfProblem(Score2PerfProblem):
"""Lightweight version of base class for musical score-to-performance problems.
This version incorporates one performance conditioning signal.
Data files contain tf.Example protos with encoded performance in 'targets' and
optional encoded score in 'inputs'.
"""
def generate_data(self, data_dir, tmp_dir, task_id=-1):
del task_id
def augment_note_sequence(ns, stretch_factor, transpose_amount):
"""Augment a NoteSequence by time stretch and pitch transposition."""
augmented_ns = sequences_lib.stretch_note_sequence(
ns, stretch_factor, in_place=False)
try:
_, num_deleted_notes = sequences_lib.transpose_note_sequence(
augmented_ns, transpose_amount,
min_allowed_pitch=MIN_PITCH, max_allowed_pitch=MAX_PITCH,
in_place=True)
except chord_symbols_lib.ChordSymbolError:
raise datagen_beam.DataAugmentationError(
'Transposition of chord symbol(s) failed.')
if num_deleted_notes:
raise datagen_beam.DataAugmentationError(
'Transposition caused out-of-range pitch(es).')
return augmented_ns
augment_params = itertools.product(
self.stretch_factors, self.transpose_amounts)
augment_fns = [
functools.partial(augment_note_sequence,
stretch_factor=s, transpose_amount=t)
for s, t in augment_params
]
datagen_beam.generate_conditional_examples(
input_transform=self.performances_input_transform(tmp_dir),
output_dir=data_dir,
problem_name=self.dataset_filename(),
splits=self.splits,
min_pitch=MIN_PITCH,
max_pitch=MAX_PITCH,
melody=False,
noisy=False,
encode_performance_fn=self.performance_encoder().encode_note_sequence,
encode_score_fns=dict((name, encoder.encode_note_sequence)
for name, encoder in self.score_encoders()),
augment_fns=augment_fns,
num_replications=self.num_replications)
def example_reading_spec(self):
data_fields = {
'inputs': tf.VarLenFeature(tf.int64),
'targets': tf.VarLenFeature(tf.int64)
}
for name, _ in self.score_encoders():
data_fields[name] = tf.VarLenFeature(tf.int64)
# We don't actually "decode" anything here; the encodings are simply read as
# tensors.
data_items_to_decoders = None
return data_fields, data_items_to_decoders
def preprocess_example(self, example, mode, hparams):
return problem.preprocess_example_common(example, mode, hparams)
class ConditionalMelodyScore2PerfProblem(Score2PerfProblem):
"""Lightweight version of base class for musical score-to-performance problems.
This version incorporates one performance conditioning signal.
Data files contain tf.Example protos with encoded performance in 'targets' and
encoded score in 'melody' and 'performance'.
"""
def generate_data(self, data_dir, tmp_dir, task_id=-1):
del task_id
def augment_note_sequence(ns, stretch_factor, transpose_amount):
"""Augment a NoteSequence by time stretch and pitch transposition."""
augmented_ns = sequences_lib.stretch_note_sequence(
ns, stretch_factor, in_place=False)
try:
_, num_deleted_notes = sequences_lib.transpose_note_sequence(
augmented_ns, transpose_amount,
min_allowed_pitch=MIN_PITCH, max_allowed_pitch=MAX_PITCH,
in_place=True)
except chord_symbols_lib.ChordSymbolError:
raise datagen_beam.DataAugmentationError(
'Transposition of chord symbol(s) failed.')
if num_deleted_notes:
raise datagen_beam.DataAugmentationError(
'Transposition caused out-of-range pitch(es).')
return augmented_ns
augment_params = itertools.product(
self.stretch_factors, self.transpose_amounts)
augment_fns = [
functools.partial(augment_note_sequence,
stretch_factor=s, transpose_amount=t)
for s, t in augment_params
]
datagen_beam.generate_conditional_examples(
input_transform=self.performances_input_transform(tmp_dir),
output_dir=data_dir,
problem_name=self.dataset_filename(),
splits=self.splits,
min_pitch=MIN_PITCH,
max_pitch=MAX_PITCH,
melody=True,
noisy=False,
encode_performance_fn=self.performance_encoder().encode_note_sequence,
encode_score_fns=dict((name, encoder.encode_note_sequence)
for name, encoder in self.score_encoders()),
augment_fns=augment_fns,
num_replications=self.num_replications)
def hparams(self, defaults, model_hparams):
del model_hparams # unused
perf_encoder = self.get_feature_encoders()['targets']
defaults.modality = {'targets': t2t_modalities.ModalityType.SYMBOL}
defaults.vocab_size = {'targets': perf_encoder.vocab_size}
if self.has_inputs:
score_encoder = self.score_encoders()
# iterate over each score encoder and update modality/vocab_size
for name, se in score_encoder:
defaults.modality[name] = t2t_modalities.ModalityType.SYMBOL
defaults.vocab_size[name] = se.vocab_size
def feature_encoders(self, data_dir):
del data_dir
encoders = {
'targets': self.performance_encoder()
}
score_encoders = self.score_encoders()
# CompositeScoreEncoder is tricky, so using a list of encoders instead.
if len(score_encoders) > 1:
for name, encoder in score_encoders:
encoders[name] = encoder
else:
# If only one score component, just use its encoder.
_, encoders['inputs'] = score_encoders[0]
return encoders
def example_reading_spec(self):
data_fields = {
'targets': tf.VarLenFeature(tf.int64),
}
for name, _ in self.score_encoders():
data_fields[name] = tf.VarLenFeature(tf.int64)
# We don't actually "decode" anything here; the encodings are simply read as
# tensors.
data_items_to_decoders = None
return data_fields, data_items_to_decoders
def preprocess_example(self, example, mode, hparams):
return problem.preprocess_example_common(example, mode, hparams)
class ConditionalMelodyNoisyScore2PerfProblem(
ConditionalMelodyScore2PerfProblem):
"""Lightweight version of base class for musical score-to-performance problems.
This version incorporates one performance conditioning signal.
Data files contain tf.Example protos with encoded performance in 'targets' and
encoded score in 'melody' and 'performance'.
"""
def generate_data(self, data_dir, tmp_dir, task_id=-1):
del task_id
def augment_note_sequence(ns, stretch_factor, transpose_amount):
"""Augment a NoteSequence by time stretch and pitch transposition."""
augmented_ns = sequences_lib.stretch_note_sequence(
ns, stretch_factor, in_place=False)
try:
_, num_deleted_notes = sequences_lib.transpose_note_sequence(
augmented_ns, transpose_amount,
min_allowed_pitch=MIN_PITCH, max_allowed_pitch=MAX_PITCH,
in_place=True)
except chord_symbols_lib.ChordSymbolError:
raise datagen_beam.DataAugmentationError(
'Transposition of chord symbol(s) failed.')
if num_deleted_notes:
raise datagen_beam.DataAugmentationError(
'Transposition caused out-of-range pitch(es).')
return augmented_ns
augment_params = itertools.product(
self.stretch_factors, self.transpose_amounts)
augment_fns = [
functools.partial(augment_note_sequence,
stretch_factor=s, transpose_amount=t)
for s, t in augment_params
]
datagen_beam.generate_conditional_examples(
input_transform=self.performances_input_transform(tmp_dir),
output_dir=data_dir,
problem_name=self.dataset_filename(),
splits=self.splits,
min_pitch=MIN_PITCH,
max_pitch=MAX_PITCH,
melody=True,
noisy=True,
encode_performance_fn=self.performance_encoder().encode_note_sequence,
encode_score_fns=dict((name, encoder.encode_note_sequence)
for name, encoder in self.score_encoders()),
augment_fns=augment_fns,
num_replications=self.num_replications)
class Chords2PerfProblem(Score2PerfProblem):
"""Base class for musical chords-to-performance problems."""
def score_encoders(self):
return [('chords', music_encoders.TextChordsEncoder(steps_per_quarter=1))]
class Melody2PerfProblem(Score2PerfProblem):
"""Base class for musical melody-to-performance problems."""
def score_encoders(self):
return [
('melody', music_encoders.TextMelodyEncoder(
steps_per_quarter=4, min_pitch=MIN_PITCH, max_pitch=MAX_PITCH))
]
class AbsoluteMelody2PerfProblem(Score2PerfProblem):
"""Base class for musical (absolute-timed) melody-to-performance problems."""
@property
def absolute_timing(self):
return True
def score_encoders(self):
return [
('melody', music_encoders.TextMelodyEncoderAbsolute(
steps_per_second=10, min_pitch=MIN_PITCH, max_pitch=MAX_PITCH))
]
class LeadSheet2PerfProblem(Score2PerfProblem):
"""Base class for musical lead-sheet-to-performance problems."""
def score_encoders(self):
return [
('chords', music_encoders.TextChordsEncoder(steps_per_quarter=4)),
('melody', music_encoders.TextMelodyEncoder(
steps_per_quarter=4, min_pitch=MIN_PITCH, max_pitch=MAX_PITCH))
]
@registry.register_problem('score2perf_maestro_language_uncropped_aug')
class Score2PerfMaestroLanguageUncroppedAug(Score2PerfProblem):
"""Piano performance language model on the MAESTRO dataset."""
def performances_input_transform(self, tmp_dir):
del tmp_dir
return dict(
(split_name, datagen_beam.ReadNoteSequencesFromTFRecord(tfrecord_path))
for split_name, tfrecord_path in MAESTRO_TFRECORD_PATHS.items())
@property
def splits(self):
return None
@property
def min_hop_size_seconds(self):
return 0.0
@property
def max_hop_size_seconds(self):
return 0.0
@property
def add_eos_symbol(self):
return False
@property
def stretch_factors(self):
# Stretch by -5%, -2.5%, 0%, 2.5%, and 5%.
return [0.95, 0.975, 1.0, 1.025, 1.05]
@property
def transpose_amounts(self):
# Transpose no more than a minor third.
return [-3, -2, -1, 0, 1, 2, 3]
@property
def random_crop_in_train(self):
return True
@property
def split_in_eval(self):
return True
@registry.register_problem('score2perf_maestro_absmel2perf_5s_to_30s_aug10x')
class Score2PerfMaestroAbsMel2Perf5sTo30sAug10x(AbsoluteMelody2PerfProblem):
"""Generate performances from an absolute-timed melody, with augmentation."""
def performances_input_transform(self, tmp_dir):
del tmp_dir
return dict(
(split_name, datagen_beam.ReadNoteSequencesFromTFRecord(tfrecord_path))
for split_name, tfrecord_path in MAESTRO_TFRECORD_PATHS.items())
@property
def splits(self):
return None
@property
def min_hop_size_seconds(self):
return 5.0
@property
def max_hop_size_seconds(self):
return 30.0
@property
def num_replications(self):
return 10
@property
def add_eos_symbol(self):
return True
@property
def stretch_factors(self):
# Stretch by -5%, -2.5%, 0%, 2.5%, and 5%.
return [0.95, 0.975, 1.0, 1.025, 1.05]
@property
def transpose_amounts(self):
# Transpose no more than a minor third.
return [-3, -2, -1, 0, 1, 2, 3]
@registry.register_problem('score2perf_maestro_perf_conditional_aug_10x')
class Score2PerfMaestroPerfConditionalAug10x(ConditionalScore2PerfProblem):
"""Generate performances from scratch (or from primer)."""
def performances_input_transform(self, tmp_dir):
del tmp_dir
return dict(
(split_name, datagen_beam.ReadNoteSequencesFromTFRecord(tfrecord_path))
for split_name, tfrecord_path in MAESTRO_TFRECORD_PATHS.items())
@property
def splits(self):
return
@property
def num_replications(self):
return 10
@property
def add_eos_symbol(self):
return False
@property
def stretch_factors(self):
# Stretch by -5%, -2.5%, 0%, 2.5%, and 5%.
return [0.95, 0.975, 1.0, 1.025, 1.05]
@property
def transpose_amounts(self):
# Transpose no more than a minor third.
return [-3, -2, -1, 0, 1, 2, 3]
@property
def has_inputs(self):
encoders = self.get_feature_encoders()
return ('performance' in encoders) or ('inputs' in encoders)
def score_encoders(self):
return [
('performance', music_encoders.MidiPerformanceEncoder(
steps_per_second=100,
num_velocity_bins=32,
min_pitch=21,
max_pitch=108,
add_eos=self.add_eos_symbol))
]
@registry.register_problem('score2perf_maestro_mel_perf_conditional_aug_10x')
class Score2PerfMaestroMelPerfConditionalAug10x(
ConditionalMelodyScore2PerfProblem):
"""Generate performances from scratch (or from primer)."""
def performances_input_transform(self, tmp_dir):
del tmp_dir
return dict(
(split_name, datagen_beam.ReadNoteSequencesFromTFRecord(tfrecord_path))
for split_name, tfrecord_path in MAESTRO_TFRECORD_PATHS.items())
@property
def splits(self):
return
@property
def num_replications(self):
return 10
@property
def add_eos_symbol(self):
return False
@property
def stretch_factors(self):
# Stretch by -5%, -2.5%, 0%, 2.5%, and 5%.
return [0.95, 0.975, 1.0, 1.025, 1.05]
@property
def transpose_amounts(self):
# Transpose no more than a minor third.
return [-3, -2, -1, 0, 1, 2, 3]
@property
def has_inputs(self):
encoders = self.get_feature_encoders()
return ('performance' in encoders) or ('inputs' in encoders)
def score_encoders(self):
return [
('performance', music_encoders.MidiPerformanceEncoder(
steps_per_second=100,
num_velocity_bins=32,
min_pitch=21,
max_pitch=108,
add_eos=self.add_eos_symbol)),
('melody', music_encoders.TextMelodyEncoderAbsolute(
steps_per_second=10, min_pitch=21, max_pitch=108))
]
@registry.register_problem('score2perf_maestro_mel_perf_conditional_noisy_10x')
class Score2PerfMaestroMelPerfConditionalNoisy10x(
ConditionalMelodyNoisyScore2PerfProblem):
"""Generate performances from scratch (or from primer)."""
def performances_input_transform(self, tmp_dir):
del tmp_dir
return dict(
(split_name, datagen_beam.ReadNoteSequencesFromTFRecord(tfrecord_path))
for split_name, tfrecord_path in MAESTRO_TFRECORD_PATHS.items())
@property
def splits(self):
return
@property
def num_replications(self):
return 10
@property
def add_eos_symbol(self):
return False
@property
def stretch_factors(self):
# Stretch by -5%, -2.5%, 0%, 2.5%, and 5%.
return [0.95, 0.975, 1.0, 1.025, 1.05]
@property
def transpose_amounts(self):
# Transpose no more than a minor third.
return [-3, -2, -1, 0, 1, 2, 3]
@property
def has_inputs(self):
encoders = self.get_feature_encoders()
return ('performance' in encoders) or ('inputs' in encoders)
def score_encoders(self):
return [
('performance', music_encoders.MidiPerformanceEncoder(
steps_per_second=100,
num_velocity_bins=32,
min_pitch=21,
max_pitch=108,
add_eos=self.add_eos_symbol)),
('melody', music_encoders.TextMelodyEncoderAbsolute(
steps_per_second=10, min_pitch=21, max_pitch=108))
]
@registry.register_hparams
def score2perf_transformer_base():
hparams = transformer.transformer_base()
hparams.bottom['inputs'] = modalities.bottom
return hparams
| 33.594278 | 89 | 0.70384 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import functools
import itertools
from magenta.models.score2perf import datagen_beam
from magenta.models.score2perf import modalities
from magenta.models.score2perf import music_encoders
from note_seq import chord_symbols_lib
from note_seq import sequences_lib
from tensor2tensor.data_generators import problem
from tensor2tensor.layers import modalities as t2t_modalities
from tensor2tensor.models import transformer
from tensor2tensor.utils import registry
import tensorflow.compat.v1 as tf
NUM_VELOCITY_BINS = 32
STEPS_PER_SECOND = 100
MIN_PITCH = 21
MAX_PITCH = 108
MAESTRO_TFRECORD_PATHS = {
'train': 'gs://magentadata/datasets/maestro/v1.0.0/maestro-v1.0.0_train.tfrecord',
'dev': 'gs://magentadata/datasets/maestro/v1.0.0/maestro-v1.0.0_validation.tfrecord',
'test': 'gs://magentadata/datasets/maestro/v1.0.0/maestro-v1.0.0_test.tfrecord'
}
class Score2PerfProblem(problem.Problem):
@property
def splits(self):
raise NotImplementedError()
@property
def min_hop_size_seconds(self):
raise NotImplementedError()
@property
def max_hop_size_seconds(self):
raise NotImplementedError()
@property
def num_replications(self):
return 1
@property
def add_eos_symbol(self):
raise NotImplementedError()
@property
def absolute_timing(self):
return False
@property
def stretch_factors(self):
return [1.0]
@property
def transpose_amounts(self):
return [0]
@property
def random_crop_length_in_datagen(self):
return None
@property
def random_crop_in_train(self):
return False
@property
def split_in_eval(self):
return False
def performances_input_transform(self, tmp_dir):
raise NotImplementedError()
def generate_data(self, data_dir, tmp_dir, task_id=-1):
del task_id
def augment_note_sequence(ns, stretch_factor, transpose_amount):
augmented_ns = sequences_lib.stretch_note_sequence(
ns, stretch_factor, in_place=False)
try:
_, num_deleted_notes = sequences_lib.transpose_note_sequence(
augmented_ns, transpose_amount,
min_allowed_pitch=MIN_PITCH, max_allowed_pitch=MAX_PITCH,
in_place=True)
except chord_symbols_lib.ChordSymbolError:
raise datagen_beam.DataAugmentationError(
'Transposition of chord symbol(s) failed.')
if num_deleted_notes:
raise datagen_beam.DataAugmentationError(
'Transposition caused out-of-range pitch(es).')
return augmented_ns
augment_params = itertools.product(
self.stretch_factors, self.transpose_amounts)
augment_fns = [
functools.partial(augment_note_sequence,
stretch_factor=s, transpose_amount=t)
for s, t in augment_params
]
datagen_beam.generate_examples(
input_transform=self.performances_input_transform(tmp_dir),
output_dir=data_dir,
problem_name=self.dataset_filename(),
splits=self.splits,
min_hop_size_seconds=self.min_hop_size_seconds,
max_hop_size_seconds=self.max_hop_size_seconds,
min_pitch=MIN_PITCH,
max_pitch=MAX_PITCH,
num_replications=self.num_replications,
encode_performance_fn=self.performance_encoder().encode_note_sequence,
encode_score_fns=dict((name, encoder.encode_note_sequence)
for name, encoder in self.score_encoders()),
augment_fns=augment_fns,
absolute_timing=self.absolute_timing,
random_crop_length=self.random_crop_length_in_datagen)
def hparams(self, defaults, model_hparams):
del model_hparams
perf_encoder = self.get_feature_encoders()['targets']
defaults.modality = {'targets': t2t_modalities.ModalityType.SYMBOL}
defaults.vocab_size = {'targets': perf_encoder.vocab_size}
if self.has_inputs:
score_encoder = self.get_feature_encoders()['inputs']
if isinstance(score_encoder.vocab_size, list):
# future, refactor the tuple of the "inputs" feature to be part of the
# features dict itself, i.e., have multiple inputs each with its own
# modality and vocab size.
modality_cls = t2t_modalities.ModalityType.IDENTITY
else:
modality_cls = t2t_modalities.ModalityType.SYMBOL
defaults.modality['inputs'] = modality_cls
defaults.vocab_size['inputs'] = score_encoder.vocab_size
def performance_encoder(self):
return music_encoders.MidiPerformanceEncoder(
steps_per_second=STEPS_PER_SECOND,
num_velocity_bins=NUM_VELOCITY_BINS,
min_pitch=MIN_PITCH,
max_pitch=MAX_PITCH,
add_eos=self.add_eos_symbol)
def score_encoders(self):
return []
def feature_encoders(self, data_dir):
del data_dir
encoders = {
'targets': self.performance_encoder()
}
score_encoders = self.score_encoders()
if score_encoders:
if len(score_encoders) > 1:
# Create a composite score encoder, only used for inference.
encoders['inputs'] = music_encoders.CompositeScoreEncoder(
[encoder for _, encoder in score_encoders])
else:
# If only one score component, just use its encoder.
_, encoders['inputs'] = score_encoders[0]
return encoders
def example_reading_spec(self):
data_fields = {
'targets': tf.VarLenFeature(tf.int64)
}
for name, _ in self.score_encoders():
data_fields[name] = tf.VarLenFeature(tf.int64)
# We don't actually "decode" anything here; the encodings are simply read as
data_items_to_decoders = None
return data_fields, data_items_to_decoders
def preprocess_example(self, example, mode, hparams):
if self.has_inputs:
inputs = []
for name, _ in self.score_encoders():
inputs.append(tf.expand_dims(example[name], axis=1))
del example[name]
example['inputs'] = tf.stack(inputs, axis=2)
if self.random_crop_in_train and mode == tf.estimator.ModeKeys.TRAIN:
assert not self.has_inputs
max_offset = tf.maximum(
tf.shape(example['targets'])[0] - hparams.max_target_seq_length, 0)
offset = tf.cond(
max_offset > 0,
lambda: tf.random_uniform([], maxval=max_offset, dtype=tf.int32),
lambda: 0
)
example['targets'] = (
example['targets'][offset:offset + hparams.max_target_seq_length])
return example
elif self.split_in_eval and mode == tf.estimator.ModeKeys.EVAL:
assert not self.has_inputs
length = tf.shape(example['targets'])[0]
extra_length = tf.mod(length, hparams.max_target_seq_length)
examples = {
'targets': tf.reshape(
example['targets'][:length - extra_length],
[-1, hparams.max_target_seq_length, 1, 1])
}
extra_example = {
'targets': tf.reshape(
example['targets'][-extra_length:], [1, -1, 1, 1])
}
dataset = tf.data.Dataset.from_tensor_slices(examples)
extra_dataset = tf.data.Dataset.from_tensor_slices(extra_example)
return dataset.concatenate(extra_dataset)
else:
return super(Score2PerfProblem, self).preprocess_example(
example, mode, hparams)
class ConditionalScore2PerfProblem(Score2PerfProblem):
def generate_data(self, data_dir, tmp_dir, task_id=-1):
del task_id
def augment_note_sequence(ns, stretch_factor, transpose_amount):
augmented_ns = sequences_lib.stretch_note_sequence(
ns, stretch_factor, in_place=False)
try:
_, num_deleted_notes = sequences_lib.transpose_note_sequence(
augmented_ns, transpose_amount,
min_allowed_pitch=MIN_PITCH, max_allowed_pitch=MAX_PITCH,
in_place=True)
except chord_symbols_lib.ChordSymbolError:
raise datagen_beam.DataAugmentationError(
'Transposition of chord symbol(s) failed.')
if num_deleted_notes:
raise datagen_beam.DataAugmentationError(
'Transposition caused out-of-range pitch(es).')
return augmented_ns
augment_params = itertools.product(
self.stretch_factors, self.transpose_amounts)
augment_fns = [
functools.partial(augment_note_sequence,
stretch_factor=s, transpose_amount=t)
for s, t in augment_params
]
datagen_beam.generate_conditional_examples(
input_transform=self.performances_input_transform(tmp_dir),
output_dir=data_dir,
problem_name=self.dataset_filename(),
splits=self.splits,
min_pitch=MIN_PITCH,
max_pitch=MAX_PITCH,
melody=False,
noisy=False,
encode_performance_fn=self.performance_encoder().encode_note_sequence,
encode_score_fns=dict((name, encoder.encode_note_sequence)
for name, encoder in self.score_encoders()),
augment_fns=augment_fns,
num_replications=self.num_replications)
def example_reading_spec(self):
data_fields = {
'inputs': tf.VarLenFeature(tf.int64),
'targets': tf.VarLenFeature(tf.int64)
}
for name, _ in self.score_encoders():
data_fields[name] = tf.VarLenFeature(tf.int64)
# tensors.
data_items_to_decoders = None
return data_fields, data_items_to_decoders
def preprocess_example(self, example, mode, hparams):
return problem.preprocess_example_common(example, mode, hparams)
class ConditionalMelodyScore2PerfProblem(Score2PerfProblem):
def generate_data(self, data_dir, tmp_dir, task_id=-1):
del task_id
def augment_note_sequence(ns, stretch_factor, transpose_amount):
augmented_ns = sequences_lib.stretch_note_sequence(
ns, stretch_factor, in_place=False)
try:
_, num_deleted_notes = sequences_lib.transpose_note_sequence(
augmented_ns, transpose_amount,
min_allowed_pitch=MIN_PITCH, max_allowed_pitch=MAX_PITCH,
in_place=True)
except chord_symbols_lib.ChordSymbolError:
raise datagen_beam.DataAugmentationError(
'Transposition of chord symbol(s) failed.')
if num_deleted_notes:
raise datagen_beam.DataAugmentationError(
'Transposition caused out-of-range pitch(es).')
return augmented_ns
augment_params = itertools.product(
self.stretch_factors, self.transpose_amounts)
augment_fns = [
functools.partial(augment_note_sequence,
stretch_factor=s, transpose_amount=t)
for s, t in augment_params
]
datagen_beam.generate_conditional_examples(
input_transform=self.performances_input_transform(tmp_dir),
output_dir=data_dir,
problem_name=self.dataset_filename(),
splits=self.splits,
min_pitch=MIN_PITCH,
max_pitch=MAX_PITCH,
melody=True,
noisy=False,
encode_performance_fn=self.performance_encoder().encode_note_sequence,
encode_score_fns=dict((name, encoder.encode_note_sequence)
for name, encoder in self.score_encoders()),
augment_fns=augment_fns,
num_replications=self.num_replications)
def hparams(self, defaults, model_hparams):
del model_hparams # unused
perf_encoder = self.get_feature_encoders()['targets']
defaults.modality = {'targets': t2t_modalities.ModalityType.SYMBOL}
defaults.vocab_size = {'targets': perf_encoder.vocab_size}
if self.has_inputs:
score_encoder = self.score_encoders()
# iterate over each score encoder and update modality/vocab_size
for name, se in score_encoder:
defaults.modality[name] = t2t_modalities.ModalityType.SYMBOL
defaults.vocab_size[name] = se.vocab_size
def feature_encoders(self, data_dir):
del data_dir
encoders = {
'targets': self.performance_encoder()
}
score_encoders = self.score_encoders()
# CompositeScoreEncoder is tricky, so using a list of encoders instead.
if len(score_encoders) > 1:
for name, encoder in score_encoders:
encoders[name] = encoder
else:
# If only one score component, just use its encoder.
_, encoders['inputs'] = score_encoders[0]
return encoders
def example_reading_spec(self):
data_fields = {
'targets': tf.VarLenFeature(tf.int64),
}
for name, _ in self.score_encoders():
data_fields[name] = tf.VarLenFeature(tf.int64)
# We don't actually "decode" anything here; the encodings are simply read as
data_items_to_decoders = None
return data_fields, data_items_to_decoders
def preprocess_example(self, example, mode, hparams):
return problem.preprocess_example_common(example, mode, hparams)
class ConditionalMelodyNoisyScore2PerfProblem(
ConditionalMelodyScore2PerfProblem):
def generate_data(self, data_dir, tmp_dir, task_id=-1):
del task_id
def augment_note_sequence(ns, stretch_factor, transpose_amount):
augmented_ns = sequences_lib.stretch_note_sequence(
ns, stretch_factor, in_place=False)
try:
_, num_deleted_notes = sequences_lib.transpose_note_sequence(
augmented_ns, transpose_amount,
min_allowed_pitch=MIN_PITCH, max_allowed_pitch=MAX_PITCH,
in_place=True)
except chord_symbols_lib.ChordSymbolError:
raise datagen_beam.DataAugmentationError(
'Transposition of chord symbol(s) failed.')
if num_deleted_notes:
raise datagen_beam.DataAugmentationError(
'Transposition caused out-of-range pitch(es).')
return augmented_ns
augment_params = itertools.product(
self.stretch_factors, self.transpose_amounts)
augment_fns = [
functools.partial(augment_note_sequence,
stretch_factor=s, transpose_amount=t)
for s, t in augment_params
]
datagen_beam.generate_conditional_examples(
input_transform=self.performances_input_transform(tmp_dir),
output_dir=data_dir,
problem_name=self.dataset_filename(),
splits=self.splits,
min_pitch=MIN_PITCH,
max_pitch=MAX_PITCH,
melody=True,
noisy=True,
encode_performance_fn=self.performance_encoder().encode_note_sequence,
encode_score_fns=dict((name, encoder.encode_note_sequence)
for name, encoder in self.score_encoders()),
augment_fns=augment_fns,
num_replications=self.num_replications)
class Chords2PerfProblem(Score2PerfProblem):
def score_encoders(self):
return [('chords', music_encoders.TextChordsEncoder(steps_per_quarter=1))]
class Melody2PerfProblem(Score2PerfProblem):
def score_encoders(self):
return [
('melody', music_encoders.TextMelodyEncoder(
steps_per_quarter=4, min_pitch=MIN_PITCH, max_pitch=MAX_PITCH))
]
class AbsoluteMelody2PerfProblem(Score2PerfProblem):
@property
def absolute_timing(self):
return True
def score_encoders(self):
return [
('melody', music_encoders.TextMelodyEncoderAbsolute(
steps_per_second=10, min_pitch=MIN_PITCH, max_pitch=MAX_PITCH))
]
class LeadSheet2PerfProblem(Score2PerfProblem):
def score_encoders(self):
return [
('chords', music_encoders.TextChordsEncoder(steps_per_quarter=4)),
('melody', music_encoders.TextMelodyEncoder(
steps_per_quarter=4, min_pitch=MIN_PITCH, max_pitch=MAX_PITCH))
]
@registry.register_problem('score2perf_maestro_language_uncropped_aug')
class Score2PerfMaestroLanguageUncroppedAug(Score2PerfProblem):
def performances_input_transform(self, tmp_dir):
del tmp_dir
return dict(
(split_name, datagen_beam.ReadNoteSequencesFromTFRecord(tfrecord_path))
for split_name, tfrecord_path in MAESTRO_TFRECORD_PATHS.items())
@property
def splits(self):
return None
@property
def min_hop_size_seconds(self):
return 0.0
@property
def max_hop_size_seconds(self):
return 0.0
@property
def add_eos_symbol(self):
return False
@property
def stretch_factors(self):
return [0.95, 0.975, 1.0, 1.025, 1.05]
@property
def transpose_amounts(self):
return [-3, -2, -1, 0, 1, 2, 3]
@property
def random_crop_in_train(self):
return True
@property
def split_in_eval(self):
return True
@registry.register_problem('score2perf_maestro_absmel2perf_5s_to_30s_aug10x')
class Score2PerfMaestroAbsMel2Perf5sTo30sAug10x(AbsoluteMelody2PerfProblem):
def performances_input_transform(self, tmp_dir):
del tmp_dir
return dict(
(split_name, datagen_beam.ReadNoteSequencesFromTFRecord(tfrecord_path))
for split_name, tfrecord_path in MAESTRO_TFRECORD_PATHS.items())
@property
def splits(self):
return None
@property
def min_hop_size_seconds(self):
return 5.0
@property
def max_hop_size_seconds(self):
return 30.0
@property
def num_replications(self):
return 10
@property
def add_eos_symbol(self):
return True
@property
def stretch_factors(self):
return [0.95, 0.975, 1.0, 1.025, 1.05]
@property
def transpose_amounts(self):
return [-3, -2, -1, 0, 1, 2, 3]
@registry.register_problem('score2perf_maestro_perf_conditional_aug_10x')
class Score2PerfMaestroPerfConditionalAug10x(ConditionalScore2PerfProblem):
def performances_input_transform(self, tmp_dir):
del tmp_dir
return dict(
(split_name, datagen_beam.ReadNoteSequencesFromTFRecord(tfrecord_path))
for split_name, tfrecord_path in MAESTRO_TFRECORD_PATHS.items())
@property
def splits(self):
return
@property
def num_replications(self):
return 10
@property
def add_eos_symbol(self):
return False
@property
def stretch_factors(self):
return [0.95, 0.975, 1.0, 1.025, 1.05]
@property
def transpose_amounts(self):
return [-3, -2, -1, 0, 1, 2, 3]
@property
def has_inputs(self):
encoders = self.get_feature_encoders()
return ('performance' in encoders) or ('inputs' in encoders)
def score_encoders(self):
return [
('performance', music_encoders.MidiPerformanceEncoder(
steps_per_second=100,
num_velocity_bins=32,
min_pitch=21,
max_pitch=108,
add_eos=self.add_eos_symbol))
]
@registry.register_problem('score2perf_maestro_mel_perf_conditional_aug_10x')
class Score2PerfMaestroMelPerfConditionalAug10x(
ConditionalMelodyScore2PerfProblem):
def performances_input_transform(self, tmp_dir):
del tmp_dir
return dict(
(split_name, datagen_beam.ReadNoteSequencesFromTFRecord(tfrecord_path))
for split_name, tfrecord_path in MAESTRO_TFRECORD_PATHS.items())
@property
def splits(self):
return
@property
def num_replications(self):
return 10
@property
def add_eos_symbol(self):
return False
@property
def stretch_factors(self):
return [0.95, 0.975, 1.0, 1.025, 1.05]
@property
def transpose_amounts(self):
return [-3, -2, -1, 0, 1, 2, 3]
@property
def has_inputs(self):
encoders = self.get_feature_encoders()
return ('performance' in encoders) or ('inputs' in encoders)
def score_encoders(self):
return [
('performance', music_encoders.MidiPerformanceEncoder(
steps_per_second=100,
num_velocity_bins=32,
min_pitch=21,
max_pitch=108,
add_eos=self.add_eos_symbol)),
('melody', music_encoders.TextMelodyEncoderAbsolute(
steps_per_second=10, min_pitch=21, max_pitch=108))
]
@registry.register_problem('score2perf_maestro_mel_perf_conditional_noisy_10x')
class Score2PerfMaestroMelPerfConditionalNoisy10x(
ConditionalMelodyNoisyScore2PerfProblem):
def performances_input_transform(self, tmp_dir):
del tmp_dir
return dict(
(split_name, datagen_beam.ReadNoteSequencesFromTFRecord(tfrecord_path))
for split_name, tfrecord_path in MAESTRO_TFRECORD_PATHS.items())
@property
def splits(self):
return
@property
def num_replications(self):
return 10
@property
def add_eos_symbol(self):
return False
@property
def stretch_factors(self):
return [0.95, 0.975, 1.0, 1.025, 1.05]
@property
def transpose_amounts(self):
return [-3, -2, -1, 0, 1, 2, 3]
@property
def has_inputs(self):
encoders = self.get_feature_encoders()
return ('performance' in encoders) or ('inputs' in encoders)
def score_encoders(self):
return [
('performance', music_encoders.MidiPerformanceEncoder(
steps_per_second=100,
num_velocity_bins=32,
min_pitch=21,
max_pitch=108,
add_eos=self.add_eos_symbol)),
('melody', music_encoders.TextMelodyEncoderAbsolute(
steps_per_second=10, min_pitch=21, max_pitch=108))
]
@registry.register_hparams
def score2perf_transformer_base():
hparams = transformer.transformer_base()
hparams.bottom['inputs'] = modalities.bottom
return hparams
| true | true |
790bdef2fee711a5826e4d0648860796c9a44151 | 1,302 | py | Python | src/virtual-wan/azext_vwan/vendored_sdks/v2018_08_01/v2018_08_01/models/subnet_association.py | Mannan2812/azure-cli-extensions | e2b34efe23795f6db9c59100534a40f0813c3d95 | [
"MIT"
] | 207 | 2017-11-29T06:59:41.000Z | 2022-03-31T10:00:53.000Z | src/virtual-wan/azext_vwan/vendored_sdks/v2018_08_01/v2018_08_01/models/subnet_association.py | Mannan2812/azure-cli-extensions | e2b34efe23795f6db9c59100534a40f0813c3d95 | [
"MIT"
] | 4,061 | 2017-10-27T23:19:56.000Z | 2022-03-31T23:18:30.000Z | src/virtual-wan/azext_vwan/vendored_sdks/v2018_08_01/v2018_08_01/models/subnet_association.py | Mannan2812/azure-cli-extensions | e2b34efe23795f6db9c59100534a40f0813c3d95 | [
"MIT"
] | 802 | 2017-10-11T17:36:26.000Z | 2022-03-31T22:24:32.000Z | # 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 msrest.serialization import Model
class SubnetAssociation(Model):
"""Network interface and its custom security rules.
Variables are only populated by the server, and will be ignored when
sending a request.
:ivar id: Subnet ID.
:vartype id: str
:param security_rules: Collection of custom security rules.
:type security_rules:
list[~azure.mgmt.network.v2018_08_01.models.SecurityRule]
"""
_validation = {
'id': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'security_rules': {'key': 'securityRules', 'type': '[SecurityRule]'},
}
def __init__(self, **kwargs):
super(SubnetAssociation, self).__init__(**kwargs)
self.id = None
self.security_rules = kwargs.get('security_rules', None)
| 31.756098 | 77 | 0.596774 |
from msrest.serialization import Model
class SubnetAssociation(Model):
_validation = {
'id': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'security_rules': {'key': 'securityRules', 'type': '[SecurityRule]'},
}
def __init__(self, **kwargs):
super(SubnetAssociation, self).__init__(**kwargs)
self.id = None
self.security_rules = kwargs.get('security_rules', None)
| true | true |
790be1d5689871179d2d10998e06a2ab2217b9a2 | 684 | py | Python | 00_DataPreprocessing/data_preprocessing_template.py | sreecodeslayer/udemy-machine-learning | 11fb166358a29993ed352fb204ab79e04bd9c05e | [
"MIT"
] | null | null | null | 00_DataPreprocessing/data_preprocessing_template.py | sreecodeslayer/udemy-machine-learning | 11fb166358a29993ed352fb204ab79e04bd9c05e | [
"MIT"
] | null | null | null | 00_DataPreprocessing/data_preprocessing_template.py | sreecodeslayer/udemy-machine-learning | 11fb166358a29993ed352fb204ab79e04bd9c05e | [
"MIT"
] | null | null | null | # Data Preprocessing Template
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Data.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 3].values
# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)
# Feature Scaling
"""from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler()
X_train = sc_X.fit_transform(X_train)
X_test = sc_X.transform(X_test)
sc_y = StandardScaler()
y_train = sc_y.fit_transform(y_train)""" | 29.73913 | 92 | 0.773392 |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
dataset = pd.read_csv('Data.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 3].values
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)
| true | true |
790be4aed0c2212da622c520d11a1ff8026b2e72 | 563 | py | Python | ex100 sorteio e soma.py | joaoschweikart/python_projects | a30361551ec71ac3bef6d38e4b6ffc7bad21f1cc | [
"MIT"
] | null | null | null | ex100 sorteio e soma.py | joaoschweikart/python_projects | a30361551ec71ac3bef6d38e4b6ffc7bad21f1cc | [
"MIT"
] | null | null | null | ex100 sorteio e soma.py | joaoschweikart/python_projects | a30361551ec71ac3bef6d38e4b6ffc7bad21f1cc | [
"MIT"
] | null | null | null | from time import sleep
from random import randint
numeros = []
def sorteio():
c = 0
while True:
n = randint(0, 20)
numeros.append(n)
c = c+1
if c == 5:
break
print('=-'*20)
print('SORTEANDO OS 5 VALORES DA LISTA:', end=' ')
for n in numeros:
sleep(0.5)
print(n, end=' ')
print()
def somapar():
soma = 0
for n in numeros:
if n % 2 == 0:
soma = soma + n
sleep(2)
print(f'Somando os valores PARES de {numeros}: {soma}')
sorteio()
somapar()
| 17.060606 | 59 | 0.50444 | from time import sleep
from random import randint
numeros = []
def sorteio():
c = 0
while True:
n = randint(0, 20)
numeros.append(n)
c = c+1
if c == 5:
break
print('=-'*20)
print('SORTEANDO OS 5 VALORES DA LISTA:', end=' ')
for n in numeros:
sleep(0.5)
print(n, end=' ')
print()
def somapar():
soma = 0
for n in numeros:
if n % 2 == 0:
soma = soma + n
sleep(2)
print(f'Somando os valores PARES de {numeros}: {soma}')
sorteio()
somapar()
| true | true |
790be57a235f32004113fc9be553d302c4d5fdd5 | 564 | py | Python | roster/migrations/0022_auto_20181206_1148.py | ankanb240/otis-web | 45eda65b419705c65c02b15872a137969d53d8e9 | [
"MIT"
] | 15 | 2021-08-28T18:18:37.000Z | 2022-03-13T07:48:15.000Z | roster/migrations/0022_auto_20181206_1148.py | ankanb240/otis-web | 45eda65b419705c65c02b15872a137969d53d8e9 | [
"MIT"
] | 65 | 2021-08-20T02:37:27.000Z | 2022-02-07T17:19:23.000Z | roster/migrations/0022_auto_20181206_1148.py | ankanb240/otis-web | 45eda65b419705c65c02b15872a137969d53d8e9 | [
"MIT"
] | 31 | 2020-01-09T02:35:29.000Z | 2022-03-13T07:48:18.000Z | # -*- coding: utf-8 -*-
# Generated by Django 1.11.9 on 2018-12-06 16:48
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('roster', '0021_auto_20180825_1843'),
]
operations = [
migrations.AlterField(
model_name='student',
name='track',
field=models.CharField(choices=[('A', 'Weekly'), ('B', 'Biweekly'), ('C', 'Correspondence'), ('E', 'External'), ('N', 'Not applicable')], max_length=5),
),
]
| 26.857143 | 164 | 0.597518 |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('roster', '0021_auto_20180825_1843'),
]
operations = [
migrations.AlterField(
model_name='student',
name='track',
field=models.CharField(choices=[('A', 'Weekly'), ('B', 'Biweekly'), ('C', 'Correspondence'), ('E', 'External'), ('N', 'Not applicable')], max_length=5),
),
]
| true | true |
790be5b201bc1b61342d9239a85b912577a4564c | 22,936 | py | Python | traci_pedestrian_crossing/movexy_ped.py | KarlRong/Safe-RL-for-Driving | 67484911ca8ad9f1476e96043c379c01cd5ced8c | [
"Apache-2.0"
] | null | null | null | traci_pedestrian_crossing/movexy_ped.py | KarlRong/Safe-RL-for-Driving | 67484911ca8ad9f1476e96043c379c01cd5ced8c | [
"Apache-2.0"
] | null | null | null | traci_pedestrian_crossing/movexy_ped.py | KarlRong/Safe-RL-for-Driving | 67484911ca8ad9f1476e96043c379c01cd5ced8c | [
"Apache-2.0"
] | null | null | null | # the TestEnv environment is used to simply simulate the network
from flow.envs import TestEnv
# the Experiment class is used for running simulations
from flow.core.experiment import Experiment
# the base network class
from flow.networks import Network
from flow.envs.base import Env
# all other imports are standard
from flow.core.params import VehicleParams, SumoCarFollowingParams, SumoLaneChangeParams
from flow.controllers import IDMController
from flow.core.params import InFlows
from flow.core.params import NetParams
from flow.core.params import TrafficLightParams
from flow.core.params import InitialConfig
from flow.core.params import EnvParams
from flow.controllers import IDMController, RLController, StaticLaneChanger
from gym.spaces.box import Box
import numpy as np
import collections
# create some default parameters parameters
HORIZON = 3000
env_params = EnvParams(
horizon=HORIZON,
sims_per_step=1,
warmup_steps=0,
additional_params={
"max_accel": 3,
"max_decel": -2,
"target_velocity": 20,
"lane_change_duration": 4,
"num_rl": 5,
})
initial_config = InitialConfig(edges_distribution=['highway_0'])
vehicles = VehicleParams()
vehicles.add(
veh_id="human",
acceleration_controller=(IDMController, {
"noise": 0.2
}),
# lane_change_controller=(StaticLaneChanger, {}),
car_following_params=SumoCarFollowingParams(
speed_mode="obey_safe_speed",
),
lane_change_params=SumoLaneChangeParams(
lane_change_mode=1621,
model="SL2015",
lc_impatience="0.1",
lc_time_to_impatience="1.0"
))
vehicles.add(
veh_id="rl",
acceleration_controller=(RLController, {}),
lane_change_controller=(StaticLaneChanger, {}),
# routing_controller=(HighwayRouter, {}),
car_following_params=SumoCarFollowingParams(
speed_mode="obey_safe_speed",
),
lane_change_params=SumoLaneChangeParams(
lane_change_mode=256,
model="SL2015",
lc_impatience="0.1",
lc_time_to_impatience="1.0"
),
num_vehicles=0)
from flow.core.params import SumoParams
sim_params = SumoParams(
sim_step=0.2,
render=True,
lateral_resolution=1.0,
restart_instance=True,
)
import os
inflow = InFlows()
inflow.add(veh_type="human",
edge="WC",
# depart_lane="best",
depart_lane=1,
arrivalLane=0,
probability=0.1,
depart_speed="random",
)
inflow.add(veh_type="human",
edge="WC",
# depart_lane="best",
depart_lane=0,
arrivalLane=1,
probability=0.1,
depart_speed="random",
)
inflow.add(veh_type="human",
edge="EC",
# depart_lane="best",
# vehs_per_hour=2000,
depart_lane=1,
arrivalLane=0,
probability=0.1,
depart_speed="random",
)
inflow.add(veh_type="human",
edge="EC",
# depart_lane="best",
# vehs_per_hour=2000,
depart_lane=0,
arrivalLane=1,
probability=0.1,
depart_speed="random",
)
inflow.add(
veh_type="rl",
edge="WC",
vehs_per_hour=100,
depart_lane="free",
depart_speed=5)
net_params = NetParams(
template={
"net":"/home/rong/Safe-RL-for-Driving/traci_pedestrian_crossing/pedcrossing.net.xml",
# features associated with the routes vehicles take
"vtype": "/home/rong/Safe-RL-for-Driving/traci_pedestrian_crossing/pedcrossing.add.xml",
# 和下方specify_routes一致
"rou":"/home/rong/Safe-RL-for-Driving/traci_pedestrian_crossing/data/pedcrossing.rou.xml",
"trip":"/home/rong/Safe-RL-for-Driving/traci_pedestrian_crossing/pedestrians.trip.xml"
},
inflows=inflow,
)
# specify the edges vehicles can originate on
initial_config = InitialConfig(
edges_distribution=["WC"]
)
tl_logic = TrafficLightParams(baseline=False)
phases = [{"duration": "100000", "state": "GGGGr"},
{"duration": "4", "state": "yyyyr"},
{"duration": "10", "state": "rrrrG"},
{"duration": "10", "state": "rrrrr"}]
tl_logic.add("C", phases=phases, programID="custom", offset="0")
# specify the routes for vehicles in the network
class PedCrossing(Network):
def specify_routes(self, net_params):
return {'EC': ['EC', 'CW'],
'WC': ['WC', 'CE']}
class MoveXYPedEnv(Env):
def __init__(self, env_params, sim_params, network, simulator='traci'):
super().__init__(env_params, sim_params, network, simulator)
# 环境相关
self.activeRequest = False
self.greenTimeSoFar = 0
# minimum green time for the vehicles
self.MIN_GREEN_TIME = 15
# the first phase in tls plan. see 'pedcrossing.tll.xml'
self.VEHICLE_GREEN_PHASE = 0
self.PEDESTRIAN_GREEN_PHASE = 2
# the id of the traffic light (there is only one). This is identical to the
# id of the controlled intersection (by default)
self.TLSID = 'C'
# pedestrian edges at the controlled intersection
self.WALKINGAREAS = [':C_w0', ':C_w1']
self.CROSSINGS = [':C_c0']
# Move xy相关
self.num_lanes = max(self.k.network.num_lanes(edge)
for edge in self.k.network.get_edge_list())
self.visible = []
self.stuck = False
# variables used to sort vehicles by their initial position plus
# distance traveled
self.prev_pos = dict()
self.absolute_position = dict()
# maximum number of controlled vehicles
self.num_rl = env_params.additional_params["num_rl"]
# queue of rl vehicles waiting to be controlled
self.rl_queue = collections.deque()
# names of the rl vehicles controlled at any step
self.rl_veh = []
# used for visualization: the vehicles behind and after RL vehicles
# (ie the observed vehicles) will have a different color
self.leader = []
self.follower = []
@property
def action_space(self):
"""See class definition."""
max_decel = self.env_params.additional_params["max_decel"]
max_accel = self.env_params.additional_params["max_accel"]
lb = [1, -0.2] * self.num_rl
ub = [2, 0.2] * self.num_rl
# print("num_rl_vehicles:", self.num_rl)
return Box(np.array(lb), np.array(ub), dtype=np.float32)
@property
def observation_space(self):
"""See class definition."""
# print("observation sapce shape: ", 4 * self.num_rl *
# self.num_lanes + self.num_rl)
return Box(
low=-1000,
high=3000,
shape=(4 * self.num_rl *
self.num_lanes + 2 * self.num_rl, ),
dtype=np.float32)
def compute_reward(self, rl_actions, **kwargs):
"""See class definition."""
reward = 0
# rl 车辆向前,并惩罚停止
rl_velocity = np.array(self.k.vehicle.get_speed(self.rl_veh))
target_vel = self.env_params.additional_params['target_velocity']
max_cost = np.array([target_vel] * self.num_rl)
max_cost = np.linalg.norm(max_cost)
cost = rl_velocity - target_vel
cost = np.linalg.norm(cost)
# epsilon term (to deal with ZeroDivisionError exceptions)
eps = np.finfo(np.float32).eps
reward += max(max_cost - cost, 0) / (max_cost + eps)
gain = 0.5
thresh = 0.3
penalize = len(rl_velocity[rl_velocity < thresh])
reward -= gain * penalize
# punish excessive lane changes by reducing the reward by a set value
# every time an rl car changes lanes (10% of max reward)
for veh_id in self.rl_veh:
if self.k.vehicle.get_last_lc(veh_id) == self.time_counter:
reward -= 10
if self.stuck:
reward -= 100
# print("reward: ", reward)
return reward
def _apply_rl_actions(self, actions):
"""See class definition."""
acceleration = actions[::2]
direction = actions[1::2]
# represents vehicles that are allowed to change lanes
# non_lane_changing_veh = []
# non_lane_changing_veh = \
# [self.time_counter <=
# self.env_params.additional_params["lane_change_duration"]
# + self.k.vehicle.get_last_lc(veh_id)
# for veh_id in self.rl_veh]
# # vehicle that are not allowed to change have their directions set to 0
# print(non_lane_changing_veh)
# direction[non_lane_changing_veh] = \
# np.array([0] * sum(non_lane_changing_veh))
for i, veh_id in enumerate(self.rl_veh):
if self.time_counter <= self.env_params.additional_params["lane_change_duration"]\
+ self.k.vehicle.get_last_lc(veh_id):
direction[i] = 0
x, y = self.k.vehicle.kernel_api.vehicle.getPosition(veh_id)
print(x, y)
print("edgeID", self.k.vehicle.get_edge(veh_id))
print("lane", self.k.vehicle.get_lane(veh_id))
self.k.vehicle.kernel_api.vehicle.moveToXY(vehID=veh_id,
edgeID="highway_1",
lane=1,
x=x+acceleration[i],
y=y+direction[i],
keepRoute=2)
for x in np.nditer(direction, op_flags=['readwrite']):
if x > 0.7:
x[...] = 1
elif x < -0.7:
x[...] = -1
else:
x[...] = 0
# print("actions:", actions)
# print("veh id: ", self.rl_veh)
# print("acceleration: ", acceleration)
# print("direction", direction)
# self.k.vehicle.apply_acceleration(self.rl_veh, acc=acceleration)
# self.k.vehicle.apply_lane_change(self.rl_veh, direction=direction)
def get_state(self):
"""See class definition."""
obs = [
0
for _ in range(4 * self.num_rl * self.num_lanes + 2 * self.num_rl)
]
# print("rl veh id: ", self.rl_veh)
self.visible = []
self.update_veh_id()
speeds = []
for i, rl_id in enumerate(self.rl_veh):
# x, y = self.k.vehicle.kernel_api.vehicle.getPosition(rl_id)
# print(x, y)
# print("edgeID", self.k.vehicle.get_edge(rl_id))
# print("lane", self.k.vehicle.get_lane(rl_id))
# self.k.vehicle.kernel_api.vehicle.moveToXY(vehID=[rl_id, rl_id], edgeID="highway_1", lane=1, x=600, y=134)
# add the speed for the ego rl vehicle
x = self.k.vehicle.get_x_by_id(rl_id)
if x == -1001:
continue
speed = self.k.vehicle.get_speed(rl_id)
obs[-2*i - 1] = speed
speeds.append(speed)
obs[-2*i - 2] = x
# if rl_id not in self.k.vehicle.get_ids():
# print("not in:", rl_id)
# self.additional_command()
# normalizers
max_length = self.k.network.length()
max_speed = self.k.network.max_speed()
# set to 1000 since the absence of a vehicle implies a large
# headway
headway = [1] * self.num_lanes
tailway = [1] * self.num_lanes
vel_in_front = [0] * self.num_lanes
vel_behind = [0] * self.num_lanes
lane_leaders = self.k.vehicle.get_lane_leaders(rl_id)
lane_followers = self.k.vehicle.get_lane_followers(rl_id)
lane_headways = self.k.vehicle.get_lane_headways(rl_id)
lane_tailways = self.k.vehicle.get_lane_tailways(rl_id)
headway[0:len(lane_headways)] = lane_headways
tailway[0:len(lane_tailways)] = lane_tailways
for j, lane_leader in enumerate(lane_leaders):
if lane_leader != '':
lane_headways[j] /= max_length
vel_in_front[j] = self.k.vehicle.get_speed(lane_leader) \
/ max_speed
self.visible.extend([lane_leader])
for j, lane_follower in enumerate(lane_followers):
if lane_follower != '':
lane_headways[j] /= max_length
vel_behind[j] = self.k.vehicle.get_speed(lane_follower) \
/ max_speed
self.visible.extend([lane_follower])
# add the headways, tailways, and speed for all lane leaders
# and followers
obs[4*self.num_lanes*i:4*self.num_lanes*(i+1)] = \
np.concatenate((headway, tailway, vel_in_front, vel_behind))
# if len(speeds) > 3:
# self.stuck = True
# for speed in speeds:
# if speed != 0:
# self.stuck = False
obs = np.array(obs)
# print("observation: ", obs)
# print("observation shape: ", obs.shape)
np.clip(obs, -1000, 3000, out=obs)
return obs
def additional_command(self):
# 红绿灯相关
# decide wether there is a waiting pedestrian and switch if the green
# phase for the vehicles exceeds its minimum duration
if not self.activeRequest:
self.activeRequest = self.checkWaitingPersons()
if self.k.kernel_api.trafficlight.getPhase(self.TLSID) == self.VEHICLE_GREEN_PHASE:
self.greenTimeSoFar += 1
if self.greenTimeSoFar > self.MIN_GREEN_TIME:
# check whether someone has pushed the button
if self.activeRequest:
# switch to the next phase
self.k.kernel_api.trafficlight.setPhase(
self.TLSID, self.VEHICLE_GREEN_PHASE + 1)
# reset state
self.activeRequest = False
# MOVE XY相关
# specify observed vehicles
for veh_id in self.leader + self.follower:
self.k.vehicle.set_observed(veh_id)
# update the "absolute_position" variable
for veh_id in self.k.vehicle.get_ids():
this_pos = self.k.vehicle.get_x_by_id(veh_id)
if this_pos == -1001:
# in case the vehicle isn't in the network
self.absolute_position[veh_id] = -1001
else:
change = this_pos - self.prev_pos.get(veh_id, this_pos)
self.absolute_position[veh_id] = \
(self.absolute_position.get(veh_id, this_pos) + change) \
% self.k.network.length()
self.prev_pos[veh_id] = this_pos
return
def update_veh_id(self):
# add rl vehicles that just entered the network into the rl queue
for veh_id in self.k.vehicle.get_rl_ids():
if veh_id not in list(self.rl_queue) + self.rl_veh:
self.rl_queue.append(veh_id)
# remove rl vehicles that exited the network
for veh_id in list(self.rl_queue):
if veh_id not in self.k.vehicle.get_rl_ids() or veh_id not in self.k.vehicle.get_ids():
self.rl_queue.remove(veh_id)
for veh_id in self.rl_veh:
if veh_id not in self.k.vehicle.get_rl_ids() or veh_id not in self.k.vehicle.get_ids():
# print("rm veh_id", veh_id)
self.rl_veh.remove(veh_id)
# fil up rl_veh until they are enough controlled vehicles
while len(self.rl_queue) > 0 and len(self.rl_veh) < self.num_rl:
rl_id = self.rl_queue.popleft()
self.rl_veh.append(rl_id)
# print("add rl_veh:", rl_id)
# print("update_veh_id, self.rl_veh:", self.rl_veh)
def checkWaitingPersons(self):
"""check whether a person has requested to cross the street"""
# check both sides of the crossing
for edge in self.WALKINGAREAS:
peds = self.k.kernel_api.edge.getLastStepPersonIDs(edge)
# check who is waiting at the crossing
# we assume that pedestrians push the button upon
# standing still for 1s
for ped in peds:
if (self.k.kernel_api.person.getWaitingTime(ped) == 1 and
self.k.kernel_api.person.getNextEdge(ped) in self.CROSSINGS):
numWaiting = self.k.kernel_api.trafficlight.getServedPersonCount(self.TLSID, self.PEDESTRIAN_GREEN_PHASE)
print("%s: pedestrian %s pushes the button (waiting: %s)" %
(self.k.kernel_api.simulation.getTime(), ped, numWaiting))
return True
return False
def step(self, rl_actions):
"""Advance the environment by one step.
Assigns actions to autonomous and human-driven agents (i.e. vehicles,
traffic lights, etc...). Actions that are not assigned are left to the
control of the simulator. The actions are then used to advance the
simulator by the number of time steps requested per environment step.
Results from the simulations are processed through various classes,
such as the Vehicle and TrafficLight kernels, to produce standardized
methods for identifying specific network state features. Finally,
results from the simulator are used to generate appropriate
observations.
Parameters
----------
rl_actions : array_like
an list of actions provided by the rl algorithm
Returns
-------
observation : array_like
agent's observation of the current environment
reward : float
amount of reward associated with the previous state/action pair
done : bool
indicates whether the episode has ended
info : dict
contains other diagnostic information from the previous action
"""
for _ in range(self.env_params.sims_per_step):
self.time_counter += 1
self.step_counter += 1
# perform acceleration actions for controlled human-driven vehicles
if len(self.k.vehicle.get_controlled_ids()) > 0:
accel = []
for veh_id in self.k.vehicle.get_controlled_ids():
action = self.k.vehicle.get_acc_controller(
veh_id).get_action(self)
accel.append(action)
self.k.vehicle.apply_acceleration(
self.k.vehicle.get_controlled_ids(), accel)
# perform lane change actions for controlled human-driven vehicles
if len(self.k.vehicle.get_controlled_lc_ids()) > 0:
direction = []
for veh_id in self.k.vehicle.get_controlled_lc_ids():
target_lane = self.k.vehicle.get_lane_changing_controller(
veh_id).get_action(self)
direction.append(target_lane)
self.k.vehicle.apply_lane_change(
self.k.vehicle.get_controlled_lc_ids(),
direction=direction)
# perform (optionally) routing actions for all vehicles in the
# network, including RL and SUMO-controlled vehicles
routing_ids = []
routing_actions = []
for veh_id in self.k.vehicle.get_ids():
if self.k.vehicle.get_routing_controller(veh_id) \
is not None:
routing_ids.append(veh_id)
route_contr = self.k.vehicle.get_routing_controller(
veh_id)
routing_actions.append(route_contr.choose_route(self))
self.k.vehicle.choose_routes(routing_ids, routing_actions)
self.apply_rl_actions(rl_actions)
self.additional_command()
# advance the simulation in the simulator by one step
self.k.simulation.simulation_step()
# store new observations in the vehicles and traffic lights class
self.k.update(reset=False)
# update the colors of vehicles
if self.sim_params.render:
self.k.vehicle.update_vehicle_colors()
# crash encodes whether the simulator experienced a collision
crash = self.k.simulation.check_collision()
# stop collecting new simulation steps if there is a collision
if crash:
break
# render a frame
self.render()
states = self.get_state()
# collect information of the state of the network based on the
# environment class used
self.state = np.asarray(states).T
# collect observation new state associated with action
next_observation = np.copy(states)
# test if the environment should terminate due to a collision or the
# time horizon being met
done = (self.time_counter >= self.env_params.warmup_steps +
self.env_params.horizon) or self.stuck
if done:
print("done")
if self.stuck:
print("stuck")
else:
print("time up")
# compute the info for each agent
infos = {}
# compute the reward
if self.env_params.clip_actions:
rl_clipped = self.clip_actions(rl_actions)
reward = self.compute_reward(rl_clipped, fail=crash)
else:
reward = self.compute_reward(rl_actions, fail=crash)
return next_observation, reward, done, infos
def reset(self):
"""See parent class.
This also includes updating the initial absolute position and previous
position.
"""
self.rl_queue.clear()
self.rl_veh.clear()
obs = super().reset()
print("reset")
for veh_id in self.k.vehicle.get_ids():
self.absolute_position[veh_id] = self.k.vehicle.get_x_by_id(veh_id)
self.prev_pos[veh_id] = self.k.vehicle.get_x_by_id(veh_id)
self.leader = []
self.follower = []
return obs
if __name__ == "__main__":
flow_params = dict(
exp_tag='template',
env_name=MoveXYPedEnv,
network=PedCrossing,
simulator='traci',
sim=sim_params,
env=env_params,
net=net_params,
veh=vehicles,
initial=initial_config,
tls=tl_logic,
)
# number of time steps
flow_params['env'].horizon = 10000
exp = Experiment(flow_params)
# run the sumo simulation
_ = exp.run(1)
| 37.053312 | 125 | 0.588158 |
from flow.envs import TestEnv
from flow.core.experiment import Experiment
from flow.networks import Network
from flow.envs.base import Env
from flow.core.params import VehicleParams, SumoCarFollowingParams, SumoLaneChangeParams
from flow.controllers import IDMController
from flow.core.params import InFlows
from flow.core.params import NetParams
from flow.core.params import TrafficLightParams
from flow.core.params import InitialConfig
from flow.core.params import EnvParams
from flow.controllers import IDMController, RLController, StaticLaneChanger
from gym.spaces.box import Box
import numpy as np
import collections
HORIZON = 3000
env_params = EnvParams(
horizon=HORIZON,
sims_per_step=1,
warmup_steps=0,
additional_params={
"max_accel": 3,
"max_decel": -2,
"target_velocity": 20,
"lane_change_duration": 4,
"num_rl": 5,
})
initial_config = InitialConfig(edges_distribution=['highway_0'])
vehicles = VehicleParams()
vehicles.add(
veh_id="human",
acceleration_controller=(IDMController, {
"noise": 0.2
}),
car_following_params=SumoCarFollowingParams(
speed_mode="obey_safe_speed",
),
lane_change_params=SumoLaneChangeParams(
lane_change_mode=1621,
model="SL2015",
lc_impatience="0.1",
lc_time_to_impatience="1.0"
))
vehicles.add(
veh_id="rl",
acceleration_controller=(RLController, {}),
lane_change_controller=(StaticLaneChanger, {}),
car_following_params=SumoCarFollowingParams(
speed_mode="obey_safe_speed",
),
lane_change_params=SumoLaneChangeParams(
lane_change_mode=256,
model="SL2015",
lc_impatience="0.1",
lc_time_to_impatience="1.0"
),
num_vehicles=0)
from flow.core.params import SumoParams
sim_params = SumoParams(
sim_step=0.2,
render=True,
lateral_resolution=1.0,
restart_instance=True,
)
import os
inflow = InFlows()
inflow.add(veh_type="human",
edge="WC",
depart_lane=1,
arrivalLane=0,
probability=0.1,
depart_speed="random",
)
inflow.add(veh_type="human",
edge="WC",
depart_lane=0,
arrivalLane=1,
probability=0.1,
depart_speed="random",
)
inflow.add(veh_type="human",
edge="EC",
depart_lane=1,
arrivalLane=0,
probability=0.1,
depart_speed="random",
)
inflow.add(veh_type="human",
edge="EC",
depart_lane=0,
arrivalLane=1,
probability=0.1,
depart_speed="random",
)
inflow.add(
veh_type="rl",
edge="WC",
vehs_per_hour=100,
depart_lane="free",
depart_speed=5)
net_params = NetParams(
template={
"net":"/home/rong/Safe-RL-for-Driving/traci_pedestrian_crossing/pedcrossing.net.xml",
"vtype": "/home/rong/Safe-RL-for-Driving/traci_pedestrian_crossing/pedcrossing.add.xml",
"rou":"/home/rong/Safe-RL-for-Driving/traci_pedestrian_crossing/data/pedcrossing.rou.xml",
"trip":"/home/rong/Safe-RL-for-Driving/traci_pedestrian_crossing/pedestrians.trip.xml"
},
inflows=inflow,
)
initial_config = InitialConfig(
edges_distribution=["WC"]
)
tl_logic = TrafficLightParams(baseline=False)
phases = [{"duration": "100000", "state": "GGGGr"},
{"duration": "4", "state": "yyyyr"},
{"duration": "10", "state": "rrrrG"},
{"duration": "10", "state": "rrrrr"}]
tl_logic.add("C", phases=phases, programID="custom", offset="0")
class PedCrossing(Network):
def specify_routes(self, net_params):
return {'EC': ['EC', 'CW'],
'WC': ['WC', 'CE']}
class MoveXYPedEnv(Env):
def __init__(self, env_params, sim_params, network, simulator='traci'):
super().__init__(env_params, sim_params, network, simulator)
self.activeRequest = False
self.greenTimeSoFar = 0
self.MIN_GREEN_TIME = 15
self.VEHICLE_GREEN_PHASE = 0
self.PEDESTRIAN_GREEN_PHASE = 2
self.TLSID = 'C'
self.WALKINGAREAS = [':C_w0', ':C_w1']
self.CROSSINGS = [':C_c0']
self.num_lanes = max(self.k.network.num_lanes(edge)
for edge in self.k.network.get_edge_list())
self.visible = []
self.stuck = False
self.prev_pos = dict()
self.absolute_position = dict()
self.num_rl = env_params.additional_params["num_rl"]
self.rl_queue = collections.deque()
self.rl_veh = []
self.leader = []
self.follower = []
@property
def action_space(self):
max_decel = self.env_params.additional_params["max_decel"]
max_accel = self.env_params.additional_params["max_accel"]
lb = [1, -0.2] * self.num_rl
ub = [2, 0.2] * self.num_rl
return Box(np.array(lb), np.array(ub), dtype=np.float32)
@property
def observation_space(self):
return Box(
low=-1000,
high=3000,
shape=(4 * self.num_rl *
self.num_lanes + 2 * self.num_rl, ),
dtype=np.float32)
def compute_reward(self, rl_actions, **kwargs):
reward = 0
rl_velocity = np.array(self.k.vehicle.get_speed(self.rl_veh))
target_vel = self.env_params.additional_params['target_velocity']
max_cost = np.array([target_vel] * self.num_rl)
max_cost = np.linalg.norm(max_cost)
cost = rl_velocity - target_vel
cost = np.linalg.norm(cost)
eps = np.finfo(np.float32).eps
reward += max(max_cost - cost, 0) / (max_cost + eps)
gain = 0.5
thresh = 0.3
penalize = len(rl_velocity[rl_velocity < thresh])
reward -= gain * penalize
for veh_id in self.rl_veh:
if self.k.vehicle.get_last_lc(veh_id) == self.time_counter:
reward -= 10
if self.stuck:
reward -= 100
return reward
def _apply_rl_actions(self, actions):
acceleration = actions[::2]
direction = actions[1::2]
veh):
if self.time_counter <= self.env_params.additional_params["lane_change_duration"]\
+ self.k.vehicle.get_last_lc(veh_id):
direction[i] = 0
x, y = self.k.vehicle.kernel_api.vehicle.getPosition(veh_id)
print(x, y)
print("edgeID", self.k.vehicle.get_edge(veh_id))
print("lane", self.k.vehicle.get_lane(veh_id))
self.k.vehicle.kernel_api.vehicle.moveToXY(vehID=veh_id,
edgeID="highway_1",
lane=1,
x=x+acceleration[i],
y=y+direction[i],
keepRoute=2)
for x in np.nditer(direction, op_flags=['readwrite']):
if x > 0.7:
x[...] = 1
elif x < -0.7:
x[...] = -1
else:
x[...] = 0
def get_state(self):
obs = [
0
for _ in range(4 * self.num_rl * self.num_lanes + 2 * self.num_rl)
]
self.visible = []
self.update_veh_id()
speeds = []
for i, rl_id in enumerate(self.rl_veh):
x = self.k.vehicle.get_x_by_id(rl_id)
if x == -1001:
continue
speed = self.k.vehicle.get_speed(rl_id)
obs[-2*i - 1] = speed
speeds.append(speed)
obs[-2*i - 2] = x
max_length = self.k.network.length()
max_speed = self.k.network.max_speed()
headway = [1] * self.num_lanes
tailway = [1] * self.num_lanes
vel_in_front = [0] * self.num_lanes
vel_behind = [0] * self.num_lanes
lane_leaders = self.k.vehicle.get_lane_leaders(rl_id)
lane_followers = self.k.vehicle.get_lane_followers(rl_id)
lane_headways = self.k.vehicle.get_lane_headways(rl_id)
lane_tailways = self.k.vehicle.get_lane_tailways(rl_id)
headway[0:len(lane_headways)] = lane_headways
tailway[0:len(lane_tailways)] = lane_tailways
for j, lane_leader in enumerate(lane_leaders):
if lane_leader != '':
lane_headways[j] /= max_length
vel_in_front[j] = self.k.vehicle.get_speed(lane_leader) \
/ max_speed
self.visible.extend([lane_leader])
for j, lane_follower in enumerate(lane_followers):
if lane_follower != '':
lane_headways[j] /= max_length
vel_behind[j] = self.k.vehicle.get_speed(lane_follower) \
/ max_speed
self.visible.extend([lane_follower])
obs[4*self.num_lanes*i:4*self.num_lanes*(i+1)] = \
np.concatenate((headway, tailway, vel_in_front, vel_behind))
obs = np.array(obs)
np.clip(obs, -1000, 3000, out=obs)
return obs
def additional_command(self):
if not self.activeRequest:
self.activeRequest = self.checkWaitingPersons()
if self.k.kernel_api.trafficlight.getPhase(self.TLSID) == self.VEHICLE_GREEN_PHASE:
self.greenTimeSoFar += 1
if self.greenTimeSoFar > self.MIN_GREEN_TIME:
if self.activeRequest:
self.k.kernel_api.trafficlight.setPhase(
self.TLSID, self.VEHICLE_GREEN_PHASE + 1)
self.activeRequest = False
for veh_id in self.leader + self.follower:
self.k.vehicle.set_observed(veh_id)
for veh_id in self.k.vehicle.get_ids():
this_pos = self.k.vehicle.get_x_by_id(veh_id)
if this_pos == -1001:
self.absolute_position[veh_id] = -1001
else:
change = this_pos - self.prev_pos.get(veh_id, this_pos)
self.absolute_position[veh_id] = \
(self.absolute_position.get(veh_id, this_pos) + change) \
% self.k.network.length()
self.prev_pos[veh_id] = this_pos
return
def update_veh_id(self):
# add rl vehicles that just entered the network into the rl queue
for veh_id in self.k.vehicle.get_rl_ids():
if veh_id not in list(self.rl_queue) + self.rl_veh:
self.rl_queue.append(veh_id)
# remove rl vehicles that exited the network
for veh_id in list(self.rl_queue):
if veh_id not in self.k.vehicle.get_rl_ids() or veh_id not in self.k.vehicle.get_ids():
self.rl_queue.remove(veh_id)
for veh_id in self.rl_veh:
if veh_id not in self.k.vehicle.get_rl_ids() or veh_id not in self.k.vehicle.get_ids():
# print("rm veh_id", veh_id)
self.rl_veh.remove(veh_id)
# fil up rl_veh until they are enough controlled vehicles
while len(self.rl_queue) > 0 and len(self.rl_veh) < self.num_rl:
rl_id = self.rl_queue.popleft()
self.rl_veh.append(rl_id)
# print("add rl_veh:", rl_id)
# print("update_veh_id, self.rl_veh:", self.rl_veh)
def checkWaitingPersons(self):
# check both sides of the crossing
for edge in self.WALKINGAREAS:
peds = self.k.kernel_api.edge.getLastStepPersonIDs(edge)
# check who is waiting at the crossing
# we assume that pedestrians push the button upon
# standing still for 1s
for ped in peds:
if (self.k.kernel_api.person.getWaitingTime(ped) == 1 and
self.k.kernel_api.person.getNextEdge(ped) in self.CROSSINGS):
numWaiting = self.k.kernel_api.trafficlight.getServedPersonCount(self.TLSID, self.PEDESTRIAN_GREEN_PHASE)
print("%s: pedestrian %s pushes the button (waiting: %s)" %
(self.k.kernel_api.simulation.getTime(), ped, numWaiting))
return True
return False
def step(self, rl_actions):
for _ in range(self.env_params.sims_per_step):
self.time_counter += 1
self.step_counter += 1
# perform acceleration actions for controlled human-driven vehicles
if len(self.k.vehicle.get_controlled_ids()) > 0:
accel = []
for veh_id in self.k.vehicle.get_controlled_ids():
action = self.k.vehicle.get_acc_controller(
veh_id).get_action(self)
accel.append(action)
self.k.vehicle.apply_acceleration(
self.k.vehicle.get_controlled_ids(), accel)
# perform lane change actions for controlled human-driven vehicles
if len(self.k.vehicle.get_controlled_lc_ids()) > 0:
direction = []
for veh_id in self.k.vehicle.get_controlled_lc_ids():
target_lane = self.k.vehicle.get_lane_changing_controller(
veh_id).get_action(self)
direction.append(target_lane)
self.k.vehicle.apply_lane_change(
self.k.vehicle.get_controlled_lc_ids(),
direction=direction)
# perform (optionally) routing actions for all vehicles in the
# network, including RL and SUMO-controlled vehicles
routing_ids = []
routing_actions = []
for veh_id in self.k.vehicle.get_ids():
if self.k.vehicle.get_routing_controller(veh_id) \
is not None:
routing_ids.append(veh_id)
route_contr = self.k.vehicle.get_routing_controller(
veh_id)
routing_actions.append(route_contr.choose_route(self))
self.k.vehicle.choose_routes(routing_ids, routing_actions)
self.apply_rl_actions(rl_actions)
self.additional_command()
# advance the simulation in the simulator by one step
self.k.simulation.simulation_step()
# store new observations in the vehicles and traffic lights class
self.k.update(reset=False)
# update the colors of vehicles
if self.sim_params.render:
self.k.vehicle.update_vehicle_colors()
# crash encodes whether the simulator experienced a collision
crash = self.k.simulation.check_collision()
# stop collecting new simulation steps if there is a collision
if crash:
break
# render a frame
self.render()
states = self.get_state()
# collect information of the state of the network based on the
# environment class used
self.state = np.asarray(states).T
# collect observation new state associated with action
next_observation = np.copy(states)
# test if the environment should terminate due to a collision or the
# time horizon being met
done = (self.time_counter >= self.env_params.warmup_steps +
self.env_params.horizon) or self.stuck
if done:
print("done")
if self.stuck:
print("stuck")
else:
print("time up")
# compute the info for each agent
infos = {}
# compute the reward
if self.env_params.clip_actions:
rl_clipped = self.clip_actions(rl_actions)
reward = self.compute_reward(rl_clipped, fail=crash)
else:
reward = self.compute_reward(rl_actions, fail=crash)
return next_observation, reward, done, infos
def reset(self):
self.rl_queue.clear()
self.rl_veh.clear()
obs = super().reset()
print("reset")
for veh_id in self.k.vehicle.get_ids():
self.absolute_position[veh_id] = self.k.vehicle.get_x_by_id(veh_id)
self.prev_pos[veh_id] = self.k.vehicle.get_x_by_id(veh_id)
self.leader = []
self.follower = []
return obs
if __name__ == "__main__":
flow_params = dict(
exp_tag='template',
env_name=MoveXYPedEnv,
network=PedCrossing,
simulator='traci',
sim=sim_params,
env=env_params,
net=net_params,
veh=vehicles,
initial=initial_config,
tls=tl_logic,
)
# number of time steps
flow_params['env'].horizon = 10000
exp = Experiment(flow_params)
# run the sumo simulation
_ = exp.run(1)
| true | true |
790be614a340f7ba78a86e453628b9bbc3592651 | 2,805 | py | Python | sdk/storage/azure-mgmt-storage/azure/mgmt/storage/v2018_11_01/models/update_history_property.py | pjquirk/azure-sdk-for-python | cbf02ec4f177b96eae1dbbba87c34c2c93880150 | [
"MIT"
] | 1 | 2021-09-07T18:36:04.000Z | 2021-09-07T18:36:04.000Z | sdk/storage/azure-mgmt-storage/azure/mgmt/storage/v2018_11_01/models/update_history_property.py | pjquirk/azure-sdk-for-python | cbf02ec4f177b96eae1dbbba87c34c2c93880150 | [
"MIT"
] | 2 | 2019-10-02T23:37:38.000Z | 2020-10-02T01:17:31.000Z | azure-mgmt-storage/azure/mgmt/storage/v2018_11_01/models/update_history_property.py | xiafu-msft/azure-sdk-for-python | 4d9560cfd519ee60667f3cc2f5295a58c18625db | [
"MIT"
] | null | null | null | # 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 msrest.serialization import Model
class UpdateHistoryProperty(Model):
"""An update history of the ImmutabilityPolicy of a blob container.
Variables are only populated by the server, and will be ignored when
sending a request.
:ivar update: The ImmutabilityPolicy update type of a blob container,
possible values include: put, lock and extend. Possible values include:
'put', 'lock', 'extend'
:vartype update: str or
~azure.mgmt.storage.v2018_11_01.models.ImmutabilityPolicyUpdateType
:ivar immutability_period_since_creation_in_days: The immutability period
for the blobs in the container since the policy creation, in days.
:vartype immutability_period_since_creation_in_days: int
:ivar timestamp: Returns the date and time the ImmutabilityPolicy was
updated.
:vartype timestamp: datetime
:ivar object_identifier: Returns the Object ID of the user who updated the
ImmutabilityPolicy.
:vartype object_identifier: str
:ivar tenant_id: Returns the Tenant ID that issued the token for the user
who updated the ImmutabilityPolicy.
:vartype tenant_id: str
:ivar upn: Returns the User Principal Name of the user who updated the
ImmutabilityPolicy.
:vartype upn: str
"""
_validation = {
'update': {'readonly': True},
'immutability_period_since_creation_in_days': {'readonly': True},
'timestamp': {'readonly': True},
'object_identifier': {'readonly': True},
'tenant_id': {'readonly': True},
'upn': {'readonly': True},
}
_attribute_map = {
'update': {'key': 'update', 'type': 'str'},
'immutability_period_since_creation_in_days': {'key': 'immutabilityPeriodSinceCreationInDays', 'type': 'int'},
'timestamp': {'key': 'timestamp', 'type': 'iso-8601'},
'object_identifier': {'key': 'objectIdentifier', 'type': 'str'},
'tenant_id': {'key': 'tenantId', 'type': 'str'},
'upn': {'key': 'upn', 'type': 'str'},
}
def __init__(self, **kwargs):
super(UpdateHistoryProperty, self).__init__(**kwargs)
self.update = None
self.immutability_period_since_creation_in_days = None
self.timestamp = None
self.object_identifier = None
self.tenant_id = None
self.upn = None
| 40.652174 | 118 | 0.647772 |
from msrest.serialization import Model
class UpdateHistoryProperty(Model):
_validation = {
'update': {'readonly': True},
'immutability_period_since_creation_in_days': {'readonly': True},
'timestamp': {'readonly': True},
'object_identifier': {'readonly': True},
'tenant_id': {'readonly': True},
'upn': {'readonly': True},
}
_attribute_map = {
'update': {'key': 'update', 'type': 'str'},
'immutability_period_since_creation_in_days': {'key': 'immutabilityPeriodSinceCreationInDays', 'type': 'int'},
'timestamp': {'key': 'timestamp', 'type': 'iso-8601'},
'object_identifier': {'key': 'objectIdentifier', 'type': 'str'},
'tenant_id': {'key': 'tenantId', 'type': 'str'},
'upn': {'key': 'upn', 'type': 'str'},
}
def __init__(self, **kwargs):
super(UpdateHistoryProperty, self).__init__(**kwargs)
self.update = None
self.immutability_period_since_creation_in_days = None
self.timestamp = None
self.object_identifier = None
self.tenant_id = None
self.upn = None
| true | true |
790be61c348d5993e377955e149fd1abe0c7fda9 | 1,592 | bzl | Python | sqldelight.bzl | ThomasCJY/sqldelight_bazel_rules | 07171e39d5340861123368607e6118de9f2b140e | [
"Apache-2.0"
] | null | null | null | sqldelight.bzl | ThomasCJY/sqldelight_bazel_rules | 07171e39d5340861123368607e6118de9f2b140e | [
"Apache-2.0"
] | null | null | null | sqldelight.bzl | ThomasCJY/sqldelight_bazel_rules | 07171e39d5340861123368607e6118de9f2b140e | [
"Apache-2.0"
] | null | null | null | """provides an sqldelight compiler"""
def _sqldelight_codegen_impl(ctx):
srcjar = ctx.outputs.srcjar
args = ctx.actions.args()
args.add("-o", srcjar)
if not ctx.attr.module_name or not ctx.attr.package_name:
fail("Non-legacy SQLDelightc requires both module_name and package_name set.")
args.add("--module_name", ctx.attr.module_name)
args.add("--package_name", ctx.attr.package_name)
args.add_all(ctx.files.srcs)
src_roots = {}
for f in ctx.files.srcs:
(pre, src, rel_name) = f.short_path.partition(ctx.attr.src_dir)
src_roots[pre + src] = True
args.add_joined("--src_dirs", src_roots.keys(), join_with = ",")
ctx.actions.run(
executable = ctx.executable._sqldelight_compiler,
inputs = ctx.files.srcs,
outputs = [srcjar],
arguments = [args],
)
return struct(
providers = [DefaultInfo(files = depset([srcjar]))],
)
sqldelight_codegen = rule(
_sqldelight_codegen_impl,
attrs = {
"_sqldelight_compiler": attr.label(
default = Label("@rules_sqldelight//:sqldelightc"),
executable = True,
cfg = "host",
),
"srcs": attr.label_list(allow_files = [".sq"]),
"src_dir": attr.string(
mandatory = True,
doc = "root directory of the source tree, used to derived the classnames.",
),
"module_name": attr.string(),
"package_name": attr.string(),
},
output_to_genfiles = True,
outputs = {
"srcjar": "%{name}_sqldelight.srcjar",
},
)
| 30.615385 | 87 | 0.606156 |
def _sqldelight_codegen_impl(ctx):
srcjar = ctx.outputs.srcjar
args = ctx.actions.args()
args.add("-o", srcjar)
if not ctx.attr.module_name or not ctx.attr.package_name:
fail("Non-legacy SQLDelightc requires both module_name and package_name set.")
args.add("--module_name", ctx.attr.module_name)
args.add("--package_name", ctx.attr.package_name)
args.add_all(ctx.files.srcs)
src_roots = {}
for f in ctx.files.srcs:
(pre, src, rel_name) = f.short_path.partition(ctx.attr.src_dir)
src_roots[pre + src] = True
args.add_joined("--src_dirs", src_roots.keys(), join_with = ",")
ctx.actions.run(
executable = ctx.executable._sqldelight_compiler,
inputs = ctx.files.srcs,
outputs = [srcjar],
arguments = [args],
)
return struct(
providers = [DefaultInfo(files = depset([srcjar]))],
)
sqldelight_codegen = rule(
_sqldelight_codegen_impl,
attrs = {
"_sqldelight_compiler": attr.label(
default = Label("@rules_sqldelight//:sqldelightc"),
executable = True,
cfg = "host",
),
"srcs": attr.label_list(allow_files = [".sq"]),
"src_dir": attr.string(
mandatory = True,
doc = "root directory of the source tree, used to derived the classnames.",
),
"module_name": attr.string(),
"package_name": attr.string(),
},
output_to_genfiles = True,
outputs = {
"srcjar": "%{name}_sqldelight.srcjar",
},
)
| true | true |
790be68617a1d612e24c1bf1fb4470a66869f5bf | 1,917 | py | Python | dataPrepare.py | asterberova/unet | 7cac389f9176a59f8f2d136be0751631361dcaf8 | [
"MIT"
] | null | null | null | dataPrepare.py | asterberova/unet | 7cac389f9176a59f8f2d136be0751631361dcaf8 | [
"MIT"
] | null | null | null | dataPrepare.py | asterberova/unet | 7cac389f9176a59f8f2d136be0751631361dcaf8 | [
"MIT"
] | null | null | null | from data import *
# data augmentation
#In deep learning tasks, a lot of data is need to train DNN model, when the dataset is not big enough, data augmentation should be applied.
#keras.preprocessing.image.ImageDataGenerator is a data generator, which can feed the DNN with data like : (data,label), it can also do data augmentation at the same time.
#It is very convenient for us to use keras.preprocessing.image.ImageDataGenerator to do data augmentation by implement image rotation, shift, rescale and so on... see [keras documentation](https://keras.io/preprocessing/image/) for detail.
#For image segmentation tasks, the image and mask must be transformed **together!!**
## define your data generator
# If you want to visualize your data augmentation result, set save_to_dir = your path
#if you don't want to do data augmentation, set data_gen_args as an empty dict.
#data_gen_args = dict()
data_gen_args = dict(rotation_range=0.2,
width_shift_range=0.05,
height_shift_range=0.05,
shear_range=0.05,
zoom_range=0.05,
horizontal_flip=True,
fill_mode='nearest')
myGenerator = trainGenerator(20, '/data/s2732815/unet/data/train', 'image', 'label',
data_gen_args, save_to_dir = '/data/s2732815/unet/data/train/aug')
## visualize your data augmentation result
#you will see 60 transformed images and their masks in data/membrane/train/aug
num_batch = 3
for i,batch in enumerate(myGenerator):
if(i >= num_batch):
break
## create .npy data
# If your computer has enough memory, you can create npy files containing all your images and masks, and feed your DNN with them.
# image_arr, mask_arr = geneTrainNpy("data/membrane/train/aug/", "data/membrane/train/aug/")
# np.save("data/image_arr.npy",image_arr)
# np.save("data/mask_arr.npy",mask_arr)
| 42.6 | 239 | 0.70579 | from data import *
data_gen_args = dict(rotation_range=0.2,
width_shift_range=0.05,
height_shift_range=0.05,
shear_range=0.05,
zoom_range=0.05,
horizontal_flip=True,
fill_mode='nearest')
myGenerator = trainGenerator(20, '/data/s2732815/unet/data/train', 'image', 'label',
data_gen_args, save_to_dir = '/data/s2732815/unet/data/train/aug')
## visualize your data augmentation result
#you will see 60 transformed images and their masks in data/membrane/train/aug
num_batch = 3
for i,batch in enumerate(myGenerator):
if(i >= num_batch):
break
## create .npy data
# If your computer has enough memory, you can create npy files containing all your images and masks, and feed your DNN with them.
# image_arr, mask_arr = geneTrainNpy("data/membrane/train/aug/", "data/membrane/train/aug/")
# np.save("data/image_arr.npy",image_arr)
# np.save("data/mask_arr.npy",mask_arr)
| true | true |
790be6df526f235235b1c80f97047dec72f18cc7 | 915 | py | Python | tests/test_stormtrack/test_core/test_features/data/circle_on_globe_clat-00_rad-800_delta-1.0_pyproj.py | ruestefa/stormtrack | e9378f013c406d387ea944c97e5adc68df864dee | [
"MIT"
] | null | null | null | tests/test_stormtrack/test_core/test_features/data/circle_on_globe_clat-00_rad-800_delta-1.0_pyproj.py | ruestefa/stormtrack | e9378f013c406d387ea944c97e5adc68df864dee | [
"MIT"
] | 2 | 2021-01-06T17:37:42.000Z | 2021-02-05T18:40:52.000Z | tests/test_stormtrack/test_core/test_features/data/circle_on_globe_clat-00_rad-800_delta-1.0_pyproj.py | ruestefa/stormtrack | e9378f013c406d387ea944c97e5adc68df864dee | [
"MIT"
] | null | null | null | import numpy as np
# fmt: off
clon, clat = 0.0, 0.0
rad_km = 800.0
area_km2 = np.pi*rad_km**2
nlat, nlon = 17, 17
lat1d = np.linspace(-8.0, 8.0, nlat)
lon1d = np.linspace(-8.0, 8.0, nlon)
lat2d, lon2d = np.meshgrid(lat1d, lon1d)
_, X = 0, 1
mask = np.array([
[_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_],
[_,_,_,_,_,X,X,X,X,X,X,X,_,_,_,_,_],
[_,_,_,X,X,X,X,X,X,X,X,X,X,X,_,_,_],
[_,_,X,X,X,X,X,X,X,X,X,X,X,X,X,_,_],
[_,_,X,X,X,X,X,X,X,X,X,X,X,X,X,_,_],
[_,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,_],
[_,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,_],
[_,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,_],
[_,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,_],
[_,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,_],
[_,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,_],
[_,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,_],
[_,_,X,X,X,X,X,X,X,X,X,X,X,X,X,_,_],
[_,_,X,X,X,X,X,X,X,X,X,X,X,X,X,_,_],
[_,_,_,X,X,X,X,X,X,X,X,X,X,X,_,_,_],
[_,_,_,_,_,X,X,X,X,X,X,X,_,_,_,_,_],
[_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_],
], np.bool).T[:, ::-1]
| 26.911765 | 40 | 0.504918 | import numpy as np
clon, clat = 0.0, 0.0
rad_km = 800.0
area_km2 = np.pi*rad_km**2
nlat, nlon = 17, 17
lat1d = np.linspace(-8.0, 8.0, nlat)
lon1d = np.linspace(-8.0, 8.0, nlon)
lat2d, lon2d = np.meshgrid(lat1d, lon1d)
_, X = 0, 1
mask = np.array([
[_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_],
[_,_,_,_,_,X,X,X,X,X,X,X,_,_,_,_,_],
[_,_,_,X,X,X,X,X,X,X,X,X,X,X,_,_,_],
[_,_,X,X,X,X,X,X,X,X,X,X,X,X,X,_,_],
[_,_,X,X,X,X,X,X,X,X,X,X,X,X,X,_,_],
[_,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,_],
[_,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,_],
[_,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,_],
[_,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,_],
[_,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,_],
[_,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,_],
[_,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,_],
[_,_,X,X,X,X,X,X,X,X,X,X,X,X,X,_,_],
[_,_,X,X,X,X,X,X,X,X,X,X,X,X,X,_,_],
[_,_,_,X,X,X,X,X,X,X,X,X,X,X,_,_,_],
[_,_,_,_,_,X,X,X,X,X,X,X,_,_,_,_,_],
[_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_],
], np.bool).T[:, ::-1]
| true | true |
790be748b1fd7585742d5a6611ef913bb380cf05 | 8,267 | py | Python | wagtail/wagtailadmin/tests/test_rich_text.py | Girbons/wagtail | 8a055addad739ff73f6e84ba553b28389122299f | [
"BSD-3-Clause"
] | 1 | 2019-11-06T10:51:42.000Z | 2019-11-06T10:51:42.000Z | wagtail/wagtailadmin/tests/test_rich_text.py | Girbons/wagtail | 8a055addad739ff73f6e84ba553b28389122299f | [
"BSD-3-Clause"
] | null | null | null | wagtail/wagtailadmin/tests/test_rich_text.py | Girbons/wagtail | 8a055addad739ff73f6e84ba553b28389122299f | [
"BSD-3-Clause"
] | 2 | 2017-08-08T01:39:02.000Z | 2018-05-06T06:16:10.000Z | from __future__ import absolute_import, unicode_literals
from django.conf import settings
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.test.utils import override_settings
from wagtail.tests.testapp.models import SingleEventPage
from wagtail.tests.testapp.rich_text import CustomRichTextArea
from wagtail.tests.utils import WagtailTestUtils
from wagtail.wagtailadmin.rich_text import HalloRichTextArea, get_rich_text_editor_widget
from wagtail.wagtailcore.models import Page, get_page_models
from wagtail.wagtailcore.rich_text import RichText
class BaseRichTextEditHandlerTestCase(TestCase):
def _clear_edit_handler_cache(self):
"""
These tests generate new EditHandlers with different settings. The
cached edit handlers should be cleared before and after each test run
to ensure that no changes leak through to other tests.
"""
from wagtail.tests.testapp.models import DefaultRichBlockFieldPage
block_page_edit_handler = DefaultRichBlockFieldPage.get_edit_handler()
if block_page_edit_handler._form_class:
rich_text_block = block_page_edit_handler._form_class.base_fields['body'].block.child_blocks['rich_text']
if hasattr(rich_text_block, 'field'):
del rich_text_block.field
for page_class in get_page_models():
page_class.get_edit_handler.cache_clear()
def setUp(self):
super(BaseRichTextEditHandlerTestCase, self).setUp()
self._clear_edit_handler_cache()
def tearDown(self):
self._clear_edit_handler_cache()
super(BaseRichTextEditHandlerTestCase, self).tearDown()
class TestGetRichTextEditorWidget(TestCase):
@override_settings()
def test_default(self):
# Simulate the absence of a setting
if hasattr(settings, 'WAGTAILADMIN_RICH_TEXT_EDITORS'):
del settings.WAGTAILADMIN_RICH_TEXT_EDITORS
self.assertIsInstance(get_rich_text_editor_widget(), HalloRichTextArea)
@override_settings(WAGTAILADMIN_RICH_TEXT_EDITORS={
'default': {
'WIDGET': 'wagtail.tests.testapp.rich_text.CustomRichTextArea'
},
})
def test_overridden_default_editor(self):
self.assertIsInstance(get_rich_text_editor_widget(), CustomRichTextArea)
@override_settings(WAGTAILADMIN_RICH_TEXT_EDITORS={
'custom': {
'WIDGET': 'wagtail.tests.testapp.rich_text.CustomRichTextArea'
},
})
def test_custom_editor_without_default(self):
self.assertIsInstance(get_rich_text_editor_widget('custom'), CustomRichTextArea)
@override_settings(WAGTAILADMIN_RICH_TEXT_EDITORS={
'default': {
'WIDGET': 'wagtail.wagtailadmin.rich_text.HalloRichTextArea'
},
'custom': {
'WIDGET': 'wagtail.tests.testapp.rich_text.CustomRichTextArea'
},
})
def test_custom_editor_with_default(self):
self.assertIsInstance(get_rich_text_editor_widget(), HalloRichTextArea)
self.assertIsInstance(get_rich_text_editor_widget('custom'), CustomRichTextArea)
@override_settings()
class TestDefaultRichText(BaseRichTextEditHandlerTestCase, WagtailTestUtils):
def setUp(self):
super(TestDefaultRichText, self).setUp()
# Find root page
self.root_page = Page.objects.get(id=2)
self.login()
# Simulate the absence of a setting
if hasattr(settings, 'WAGTAILADMIN_RICH_TEXT_EDITORS'):
del settings.WAGTAILADMIN_RICH_TEXT_EDITORS
def test_default_editor_in_rich_text_field(self):
response = self.client.get(reverse(
'wagtailadmin_pages:add', args=('tests', 'defaultrichtextfieldpage', self.root_page.id)
))
# Check status code
self.assertEqual(response.status_code, 200)
# Check that hallo (default editor by now)
self.assertContains(response, 'makeHalloRichTextEditable("id_body");')
def test_default_editor_in_rich_text_block(self):
response = self.client.get(reverse(
'wagtailadmin_pages:add', args=('tests', 'defaultrichblockfieldpage', self.root_page.id)
))
# Check status code
self.assertEqual(response.status_code, 200)
# Check that hallo (default editor by now)
self.assertContains(response, 'makeHalloRichTextEditable("__PREFIX__-value");')
@override_settings(WAGTAILADMIN_RICH_TEXT_EDITORS={
'default': {
'WIDGET': 'wagtail.tests.testapp.rich_text.CustomRichTextArea'
},
})
class TestOverriddenDefaultRichText(BaseRichTextEditHandlerTestCase, WagtailTestUtils):
def setUp(self):
super(TestOverriddenDefaultRichText, self).setUp()
# Find root page
self.root_page = Page.objects.get(id=2)
self.login()
def test_overridden_default_editor_in_rich_text_field(self):
response = self.client.get(reverse(
'wagtailadmin_pages:add', args=('tests', 'defaultrichtextfieldpage', self.root_page.id)
))
# Check status code
self.assertEqual(response.status_code, 200)
# Check that hallo (default editor by now) was replaced with fake editor
self.assertNotContains(response, 'makeHalloRichTextEditable("id_body");')
self.assertContains(response, 'customEditorInitScript("id_body");')
def test_overridden_default_editor_in_rich_text_block(self):
response = self.client.get(reverse(
'wagtailadmin_pages:add', args=('tests', 'defaultrichblockfieldpage', self.root_page.id)
))
# Check status code
self.assertEqual(response.status_code, 200)
# Check that hallo (default editor by now) was replaced with fake editor
self.assertNotContains(response, 'makeHalloRichTextEditable("__PREFIX__-value");')
self.assertContains(response, 'customEditorInitScript("__PREFIX__-value");')
@override_settings(WAGTAILADMIN_RICH_TEXT_EDITORS={
'default': {
'WIDGET': 'wagtail.wagtailadmin.rich_text.HalloRichTextArea'
},
'custom': {
'WIDGET': 'wagtail.tests.testapp.rich_text.CustomRichTextArea'
},
})
class TestCustomDefaultRichText(BaseRichTextEditHandlerTestCase, WagtailTestUtils):
def setUp(self):
super(TestCustomDefaultRichText, self).setUp()
# Find root page
self.root_page = Page.objects.get(id=2)
self.login()
def test_custom_editor_in_rich_text_field(self):
response = self.client.get(reverse(
'wagtailadmin_pages:add', args=('tests', 'customrichtextfieldpage', self.root_page.id)
))
# Check status code
self.assertEqual(response.status_code, 200)
# Check that hallo (default editor by now) was replaced with fake editor
self.assertNotContains(response, 'makeHalloRichTextEditable("id_body");')
self.assertContains(response, 'customEditorInitScript("id_body");')
def test_custom_editor_in_rich_text_block(self):
response = self.client.get(reverse(
'wagtailadmin_pages:add', args=('tests', 'customrichblockfieldpage', self.root_page.id)
))
# Check status code
self.assertEqual(response.status_code, 200)
# Check that hallo (default editor by now) was replaced with fake editor
self.assertNotContains(response, 'makeHalloRichTextEditable("__PREFIX__-value");')
self.assertContains(response, 'customEditorInitScript("__PREFIX__-value");')
class TestRichTextValue(TestCase):
def setUp(self):
self.root_page = Page.objects.get(id=2)
self.single_event_page = SingleEventPage(
title="foo",
location='the moon', audience='public',
cost='free', date_from='2001-01-01',
)
self.root_page.add_child(instance=self.single_event_page)
def test_render(self):
text = '<p>To the <a linktype="page" id="{}">moon</a>!</p>'.format(
self.single_event_page.id
)
value = RichText(text)
result = str(value)
expected = (
'<div class="rich-text"><p>To the <a href="'
'/foo/pointless-suffix/">moon</a>!</p></div>')
self.assertEqual(result, expected)
| 36.90625 | 117 | 0.697835 | from __future__ import absolute_import, unicode_literals
from django.conf import settings
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.test.utils import override_settings
from wagtail.tests.testapp.models import SingleEventPage
from wagtail.tests.testapp.rich_text import CustomRichTextArea
from wagtail.tests.utils import WagtailTestUtils
from wagtail.wagtailadmin.rich_text import HalloRichTextArea, get_rich_text_editor_widget
from wagtail.wagtailcore.models import Page, get_page_models
from wagtail.wagtailcore.rich_text import RichText
class BaseRichTextEditHandlerTestCase(TestCase):
def _clear_edit_handler_cache(self):
from wagtail.tests.testapp.models import DefaultRichBlockFieldPage
block_page_edit_handler = DefaultRichBlockFieldPage.get_edit_handler()
if block_page_edit_handler._form_class:
rich_text_block = block_page_edit_handler._form_class.base_fields['body'].block.child_blocks['rich_text']
if hasattr(rich_text_block, 'field'):
del rich_text_block.field
for page_class in get_page_models():
page_class.get_edit_handler.cache_clear()
def setUp(self):
super(BaseRichTextEditHandlerTestCase, self).setUp()
self._clear_edit_handler_cache()
def tearDown(self):
self._clear_edit_handler_cache()
super(BaseRichTextEditHandlerTestCase, self).tearDown()
class TestGetRichTextEditorWidget(TestCase):
@override_settings()
def test_default(self):
if hasattr(settings, 'WAGTAILADMIN_RICH_TEXT_EDITORS'):
del settings.WAGTAILADMIN_RICH_TEXT_EDITORS
self.assertIsInstance(get_rich_text_editor_widget(), HalloRichTextArea)
@override_settings(WAGTAILADMIN_RICH_TEXT_EDITORS={
'default': {
'WIDGET': 'wagtail.tests.testapp.rich_text.CustomRichTextArea'
},
})
def test_overridden_default_editor(self):
self.assertIsInstance(get_rich_text_editor_widget(), CustomRichTextArea)
@override_settings(WAGTAILADMIN_RICH_TEXT_EDITORS={
'custom': {
'WIDGET': 'wagtail.tests.testapp.rich_text.CustomRichTextArea'
},
})
def test_custom_editor_without_default(self):
self.assertIsInstance(get_rich_text_editor_widget('custom'), CustomRichTextArea)
@override_settings(WAGTAILADMIN_RICH_TEXT_EDITORS={
'default': {
'WIDGET': 'wagtail.wagtailadmin.rich_text.HalloRichTextArea'
},
'custom': {
'WIDGET': 'wagtail.tests.testapp.rich_text.CustomRichTextArea'
},
})
def test_custom_editor_with_default(self):
self.assertIsInstance(get_rich_text_editor_widget(), HalloRichTextArea)
self.assertIsInstance(get_rich_text_editor_widget('custom'), CustomRichTextArea)
@override_settings()
class TestDefaultRichText(BaseRichTextEditHandlerTestCase, WagtailTestUtils):
def setUp(self):
super(TestDefaultRichText, self).setUp()
self.root_page = Page.objects.get(id=2)
self.login()
if hasattr(settings, 'WAGTAILADMIN_RICH_TEXT_EDITORS'):
del settings.WAGTAILADMIN_RICH_TEXT_EDITORS
def test_default_editor_in_rich_text_field(self):
response = self.client.get(reverse(
'wagtailadmin_pages:add', args=('tests', 'defaultrichtextfieldpage', self.root_page.id)
))
self.assertEqual(response.status_code, 200)
self.assertContains(response, 'makeHalloRichTextEditable("id_body");')
def test_default_editor_in_rich_text_block(self):
response = self.client.get(reverse(
'wagtailadmin_pages:add', args=('tests', 'defaultrichblockfieldpage', self.root_page.id)
))
self.assertEqual(response.status_code, 200)
self.assertContains(response, 'makeHalloRichTextEditable("__PREFIX__-value");')
@override_settings(WAGTAILADMIN_RICH_TEXT_EDITORS={
'default': {
'WIDGET': 'wagtail.tests.testapp.rich_text.CustomRichTextArea'
},
})
class TestOverriddenDefaultRichText(BaseRichTextEditHandlerTestCase, WagtailTestUtils):
def setUp(self):
super(TestOverriddenDefaultRichText, self).setUp()
self.root_page = Page.objects.get(id=2)
self.login()
def test_overridden_default_editor_in_rich_text_field(self):
response = self.client.get(reverse(
'wagtailadmin_pages:add', args=('tests', 'defaultrichtextfieldpage', self.root_page.id)
))
self.assertEqual(response.status_code, 200)
self.assertNotContains(response, 'makeHalloRichTextEditable("id_body");')
self.assertContains(response, 'customEditorInitScript("id_body");')
def test_overridden_default_editor_in_rich_text_block(self):
response = self.client.get(reverse(
'wagtailadmin_pages:add', args=('tests', 'defaultrichblockfieldpage', self.root_page.id)
))
self.assertEqual(response.status_code, 200)
self.assertNotContains(response, 'makeHalloRichTextEditable("__PREFIX__-value");')
self.assertContains(response, 'customEditorInitScript("__PREFIX__-value");')
@override_settings(WAGTAILADMIN_RICH_TEXT_EDITORS={
'default': {
'WIDGET': 'wagtail.wagtailadmin.rich_text.HalloRichTextArea'
},
'custom': {
'WIDGET': 'wagtail.tests.testapp.rich_text.CustomRichTextArea'
},
})
class TestCustomDefaultRichText(BaseRichTextEditHandlerTestCase, WagtailTestUtils):
def setUp(self):
super(TestCustomDefaultRichText, self).setUp()
self.root_page = Page.objects.get(id=2)
self.login()
def test_custom_editor_in_rich_text_field(self):
response = self.client.get(reverse(
'wagtailadmin_pages:add', args=('tests', 'customrichtextfieldpage', self.root_page.id)
))
self.assertEqual(response.status_code, 200)
self.assertNotContains(response, 'makeHalloRichTextEditable("id_body");')
self.assertContains(response, 'customEditorInitScript("id_body");')
def test_custom_editor_in_rich_text_block(self):
response = self.client.get(reverse(
'wagtailadmin_pages:add', args=('tests', 'customrichblockfieldpage', self.root_page.id)
))
self.assertEqual(response.status_code, 200)
self.assertNotContains(response, 'makeHalloRichTextEditable("__PREFIX__-value");')
self.assertContains(response, 'customEditorInitScript("__PREFIX__-value");')
class TestRichTextValue(TestCase):
def setUp(self):
self.root_page = Page.objects.get(id=2)
self.single_event_page = SingleEventPage(
title="foo",
location='the moon', audience='public',
cost='free', date_from='2001-01-01',
)
self.root_page.add_child(instance=self.single_event_page)
def test_render(self):
text = '<p>To the <a linktype="page" id="{}">moon</a>!</p>'.format(
self.single_event_page.id
)
value = RichText(text)
result = str(value)
expected = (
'<div class="rich-text"><p>To the <a href="'
'/foo/pointless-suffix/">moon</a>!</p></div>')
self.assertEqual(result, expected)
| true | true |
790be92e1e25a0d3e40d9053ddaae04fab3592ef | 2,359 | py | Python | virtual_env/lib/python3.5/site-packages/google/auth/_service_account_info.py | straydag/To_Due_Backend | ac91f5ebabe8e4f2b6db7faa5ccbd30ebdb4e3f6 | [
"MIT"
] | 3 | 2020-10-12T15:47:01.000Z | 2022-01-14T19:51:26.000Z | virtual_env/lib/python3.5/site-packages/google/auth/_service_account_info.py | straydag/To_Due_Backend | ac91f5ebabe8e4f2b6db7faa5ccbd30ebdb4e3f6 | [
"MIT"
] | 16 | 2021-03-19T09:44:52.000Z | 2022-03-12T00:22:14.000Z | virtual_env/lib/python3.5/site-packages/google/auth/_service_account_info.py | straydag/To_Due_Backend | ac91f5ebabe8e4f2b6db7faa5ccbd30ebdb4e3f6 | [
"MIT"
] | 2 | 2019-11-13T05:27:48.000Z | 2020-01-21T06:35:19.000Z | # Copyright 2016 Google Inc.
#
# 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.
"""Helper functions for loading data from a Google service account file."""
import io
import json
import six
from google.auth import crypt
def from_dict(data, require=None):
"""Validates a dictionary containing Google service account data.
Creates and returns a :class:`google.auth.crypt.Signer` instance from the
private key specified in the data.
Args:
data (Mapping[str, str]): The service account data
require (Sequence[str]): List of keys required to be present in the
info.
Returns:
google.auth.crypt.Signer: A signer created from the private key in the
service account file.
Raises:
ValueError: if the data was in the wrong format, or if one of the
required keys is missing.
"""
keys_needed = set(require if require is not None else [])
missing = keys_needed.difference(six.iterkeys(data))
if missing:
raise ValueError(
"Service account info was not in the expected format, missing "
"fields {}.".format(", ".join(missing))
)
# Create a signer.
signer = crypt.RSASigner.from_service_account_info(data)
return signer
def from_filename(filename, require=None):
"""Reads a Google service account JSON file and returns its parsed info.
Args:
filename (str): The path to the service account .json file.
require (Sequence[str]): List of keys required to be present in the
info.
Returns:
Tuple[ Mapping[str, str], google.auth.crypt.Signer ]: The verified
info and a signer instance.
"""
with io.open(filename, "r", encoding="utf-8") as json_file:
data = json.load(json_file)
return data, from_dict(data, require=require)
| 31.453333 | 78 | 0.680797 |
import io
import json
import six
from google.auth import crypt
def from_dict(data, require=None):
keys_needed = set(require if require is not None else [])
missing = keys_needed.difference(six.iterkeys(data))
if missing:
raise ValueError(
"Service account info was not in the expected format, missing "
"fields {}.".format(", ".join(missing))
)
signer = crypt.RSASigner.from_service_account_info(data)
return signer
def from_filename(filename, require=None):
with io.open(filename, "r", encoding="utf-8") as json_file:
data = json.load(json_file)
return data, from_dict(data, require=require)
| true | true |
790be99f361b330bc9299b73af97971e2e715eb6 | 33,313 | py | Python | electrum_vestx/plugins/revealer/qt.py | anonymouszar/electrum-vestx | ca1dd0fc9ca8fc547d9def1934018b1a4acd7ecb | [
"MIT"
] | 1 | 2021-04-30T10:50:54.000Z | 2021-04-30T10:50:54.000Z | electrum_vestx/plugins/revealer/qt.py | anonymouszar/electrum-vestx | ca1dd0fc9ca8fc547d9def1934018b1a4acd7ecb | [
"MIT"
] | 2 | 2021-06-01T23:47:48.000Z | 2021-11-15T17:48:49.000Z | electrum_vestx/plugins/revealer/qt.py | anonymouszar/electrum-vestx | ca1dd0fc9ca8fc547d9def1934018b1a4acd7ecb | [
"MIT"
] | 2 | 2019-07-04T02:49:33.000Z | 2021-11-24T09:27:47.000Z | '''
Revealer
Do you have something to hide?
Secret backup plug-in for the electrum wallet.
Tiago Romagnani Silveira, 2017
'''
import os
import random
import traceback
from decimal import Decimal
from functools import partial
import sys
import qrcode
from PyQt5.QtPrintSupport import QPrinter
from PyQt5.QtCore import Qt, QRectF, QRect, QSizeF, QUrl, QPoint, QSize
from PyQt5.QtGui import (QPixmap, QImage, QBitmap, QPainter, QFontDatabase, QPen, QFont,
QColor, QDesktopServices, qRgba, QPainterPath)
from PyQt5.QtWidgets import (QGridLayout, QVBoxLayout, QHBoxLayout, QLabel,
QPushButton, QLineEdit)
from electrum_vestx.plugin import hook
from electrum_vestx.i18n import _
from electrum_vestx.util import make_dir, InvalidPassword, UserCancelled
from electrum_vestx.gui.qt.util import (read_QIcon, EnterButton, WWLabel, icon_path,
WindowModalDialog, Buttons, CloseButton, OkButton)
from electrum_vestx.gui.qt.qrtextedit import ScanQRTextEdit
from electrum_vestx.gui.qt.main_window import StatusBarButton
from .revealer import RevealerPlugin
class Plugin(RevealerPlugin):
MAX_PLAINTEXT_LEN = 189 # chars
def __init__(self, parent, config, name):
RevealerPlugin.__init__(self, parent, config, name)
self.base_dir = os.path.join(config.electrum_path(), 'revealer')
if self.config.get('calibration_h') is None:
self.config.set_key('calibration_h', 0)
if self.config.get('calibration_v') is None:
self.config.set_key('calibration_v', 0)
self.calibration_h = self.config.get('calibration_h')
self.calibration_v = self.config.get('calibration_v')
self.f_size = QSize(1014*2, 642*2)
self.abstand_h = 21
self.abstand_v = 34
self.calibration_noise = int('10' * 128)
self.rawnoise = False
make_dir(self.base_dir)
self.extension = False
@hook
def create_status_bar(self, parent):
b = StatusBarButton(read_QIcon('revealer.png'), "Revealer "+_("secret backup utility"),
partial(self.setup_dialog, parent))
parent.addPermanentWidget(b)
def requires_settings(self):
return True
def settings_widget(self, window):
return EnterButton(_('Printer Calibration'), partial(self.calibration_dialog, window))
def password_dialog(self, msg=None, parent=None):
from electrum_vestx.gui.qt.password_dialog import PasswordDialog
parent = parent or self
d = PasswordDialog(parent, msg)
return d.run()
def get_seed(self):
password = None
if self.wallet.has_keystore_encryption():
password = self.password_dialog(parent=self.d.parent())
if not password:
raise UserCancelled()
keystore = self.wallet.get_keystore()
if not keystore or not keystore.has_seed():
return
self.extension = bool(keystore.get_passphrase(password))
return keystore.get_seed(password)
def setup_dialog(self, window):
self.wallet = window.parent().wallet
self.update_wallet_name(self.wallet)
self.user_input = False
self.d = WindowModalDialog(window, "Setup Dialog")
self.d.setMinimumWidth(500)
self.d.setMinimumHeight(210)
self.d.setMaximumHeight(320)
self.d.setContentsMargins(11,11,1,1)
self.hbox = QHBoxLayout(self.d)
vbox = QVBoxLayout()
logo = QLabel()
self.hbox.addWidget(logo)
logo.setPixmap(QPixmap(icon_path('revealer.png')))
logo.setAlignment(Qt.AlignLeft)
self.hbox.addSpacing(16)
vbox.addWidget(WWLabel("<b>"+_("Revealer Secret Backup Plugin")+"</b><br>"
+_("To encrypt your backup, first we need to load some noise.")+"<br/>"))
vbox.addSpacing(7)
bcreate = QPushButton(_("Create a new Revealer"))
bcreate.setMaximumWidth(181)
bcreate.setDefault(True)
vbox.addWidget(bcreate, Qt.AlignCenter)
self.load_noise = ScanQRTextEdit()
self.load_noise.setTabChangesFocus(True)
self.load_noise.textChanged.connect(self.on_edit)
self.load_noise.setMaximumHeight(33)
self.hbox.addLayout(vbox)
vbox.addWidget(WWLabel(_("or type an existing revealer code below and click 'next':")))
vbox.addWidget(self.load_noise)
vbox.addSpacing(3)
self.next_button = QPushButton(_("Next"), self.d)
self.next_button.setEnabled(False)
vbox.addLayout(Buttons(self.next_button))
self.next_button.clicked.connect(self.d.close)
self.next_button.clicked.connect(partial(self.cypherseed_dialog, window))
vbox.addWidget(
QLabel("<b>" + _("Warning") + "</b>: " + _("Each revealer should be used only once.")
+"<br>"+_("more information at <a href=\"https://revealer.cc/faq\">https://revealer.cc/faq</a>")))
def mk_digital():
try:
self.make_digital(self.d)
except Exception:
self.logger.exception('')
else:
self.cypherseed_dialog(window)
bcreate.clicked.connect(mk_digital)
return bool(self.d.exec_())
def get_noise(self):
text = self.load_noise.text()
return ''.join(text.split()).lower()
def on_edit(self):
txt = self.get_noise()
versioned_seed = self.get_versioned_seed_from_user_input(txt)
if versioned_seed:
self.versioned_seed = versioned_seed
self.user_input = bool(versioned_seed)
self.next_button.setEnabled(bool(versioned_seed))
def make_digital(self, dialog):
self.make_rawnoise(True)
self.bdone(dialog)
self.d.close()
def get_path_to_revealer_file(self, ext: str= '') -> str:
version = self.versioned_seed.version
code_id = self.versioned_seed.checksum
filename = self.filename_prefix + version + "_" + code_id + ext
path = os.path.join(self.base_dir, filename)
return os.path.normcase(os.path.abspath(path))
def get_path_to_calibration_file(self):
path = os.path.join(self.base_dir, 'calibration.pdf')
return os.path.normcase(os.path.abspath(path))
def bcrypt(self, dialog):
self.rawnoise = False
version = self.versioned_seed.version
code_id = self.versioned_seed.checksum
dialog.show_message(''.join([_("{} encrypted for Revealer {}_{} saved as PNG and PDF at: ").format(self.was, version, code_id),
"<b>", self.get_path_to_revealer_file(), "</b>", "<br/>",
"<br/>", "<b>", _("Always check your backups.")]),
rich_text=True)
dialog.close()
def ext_warning(self, dialog):
dialog.show_message(''.join(["<b>",_("Warning"), ": </b>",
_("your seed extension will <b>not</b> be included in the encrypted backup.")]),
rich_text=True)
dialog.close()
def bdone(self, dialog):
version = self.versioned_seed.version
code_id = self.versioned_seed.checksum
dialog.show_message(''.join([_("Digital Revealer ({}_{}) saved as PNG and PDF at:").format(version, code_id),
"<br/>","<b>", self.get_path_to_revealer_file(), '</b>']),
rich_text=True)
def customtxt_limits(self):
txt = self.text.text()
self.max_chars.setVisible(False)
self.char_count.setText(f"({len(txt)}/{self.MAX_PLAINTEXT_LEN})")
if len(txt)>0:
self.ctext.setEnabled(True)
if len(txt) > self.MAX_PLAINTEXT_LEN:
self.text.setPlainText(txt[:self.MAX_PLAINTEXT_LEN])
self.max_chars.setVisible(True)
def t(self):
self.txt = self.text.text()
self.seed_img(is_seed=False)
def warn_old_revealer(self):
if self.versioned_seed.version == '0':
link = "https://revealer.cc/revealer-warning-and-upgrade/"
self.d.show_warning(("<b>{warning}: </b>{ver0}<br>"
"{url}<br>"
"{risk}")
.format(warning=_("Warning"),
ver0=_("Revealers starting with 0 are not secure due to a vulnerability."),
url=_("More info at: {}").format(f'<a href="{link}">{link}</a>'),
risk=_("Proceed at your own risk.")),
rich_text=True)
def cypherseed_dialog(self, window):
self.warn_old_revealer()
d = WindowModalDialog(window, "Encryption Dialog")
d.setMinimumWidth(500)
d.setMinimumHeight(210)
d.setMaximumHeight(450)
d.setContentsMargins(11, 11, 1, 1)
self.c_dialog = d
hbox = QHBoxLayout(d)
self.vbox = QVBoxLayout()
logo = QLabel()
hbox.addWidget(logo)
logo.setPixmap(QPixmap(icon_path('revealer.png')))
logo.setAlignment(Qt.AlignLeft)
hbox.addSpacing(16)
self.vbox.addWidget(WWLabel("<b>" + _("Revealer Secret Backup Plugin") + "</b><br>"
+ _("Ready to encrypt for revealer {}")
.format(self.versioned_seed.version+'_'+self.versioned_seed.checksum)))
self.vbox.addSpacing(11)
hbox.addLayout(self.vbox)
grid = QGridLayout()
self.vbox.addLayout(grid)
cprint = QPushButton(_("Encrypt {}'s seed").format(self.wallet_name))
cprint.setMaximumWidth(250)
cprint.clicked.connect(partial(self.seed_img, True))
self.vbox.addWidget(cprint)
self.vbox.addSpacing(1)
self.vbox.addWidget(WWLabel("<b>"+_("OR")+"</b> "+_("type a custom alphanumerical secret below:")))
self.text = ScanQRTextEdit()
self.text.setTabChangesFocus(True)
self.text.setMaximumHeight(70)
self.text.textChanged.connect(self.customtxt_limits)
self.vbox.addWidget(self.text)
self.char_count = WWLabel("")
self.char_count.setAlignment(Qt.AlignRight)
self.vbox.addWidget(self.char_count)
self.max_chars = WWLabel("<font color='red'>"
+ _("This version supports a maximum of {} characters.").format(self.MAX_PLAINTEXT_LEN)
+"</font>")
self.vbox.addWidget(self.max_chars)
self.max_chars.setVisible(False)
self.ctext = QPushButton(_("Encrypt custom secret"))
self.ctext.clicked.connect(self.t)
self.vbox.addWidget(self.ctext)
self.ctext.setEnabled(False)
self.vbox.addSpacing(11)
self.vbox.addLayout(Buttons(CloseButton(d)))
return bool(d.exec_())
def update_wallet_name(self, name):
self.wallet_name = str(name)
def seed_img(self, is_seed = True):
if is_seed:
try:
cseed = self.get_seed()
except UserCancelled:
return
except InvalidPassword as e:
self.d.show_error(str(e))
return
if not cseed:
self.d.show_message(_("This wallet has no seed"))
return
txt = cseed.upper()
else:
txt = self.txt.upper()
img = QImage(self.SIZE[0], self.SIZE[1], QImage.Format_Mono)
bitmap = QBitmap.fromImage(img, Qt.MonoOnly)
bitmap.fill(Qt.white)
painter = QPainter()
painter.begin(bitmap)
QFontDatabase.addApplicationFont(os.path.join(os.path.dirname(__file__), 'SourceSansPro-Bold.otf') )
if len(txt) < 102 :
fontsize = 15
linespace = 15
max_letters = 17
max_lines = 6
max_words = 3
else:
fontsize = 12
linespace = 10
max_letters = 21
max_lines = 9
max_words = int(max_letters/4)
font = QFont('Source Sans Pro', fontsize, QFont.Bold)
font.setLetterSpacing(QFont.PercentageSpacing, 100)
font.setPixelSize(fontsize)
painter.setFont(font)
seed_array = txt.split(' ')
for n in range(max_lines):
nwords = max_words
temp_seed = seed_array[:nwords]
while len(' '.join(map(str, temp_seed))) > max_letters:
nwords = nwords - 1
temp_seed = seed_array[:nwords]
painter.drawText(QRect(0, linespace*n , self.SIZE[0], self.SIZE[1]), Qt.AlignHCenter, ' '.join(map(str, temp_seed)))
del seed_array[:nwords]
painter.end()
img = bitmap.toImage()
if (self.rawnoise == False):
self.make_rawnoise()
self.make_cypherseed(img, self.rawnoise, False, is_seed)
return img
def make_rawnoise(self, create_revealer=False):
if not self.user_input:
self.versioned_seed = self.gen_random_versioned_seed()
assert self.versioned_seed
w, h = self.SIZE
rawnoise = QImage(w, h, QImage.Format_Mono)
noise_map = self.get_noise_map(self.versioned_seed)
for (x,y), pixel in noise_map.items():
rawnoise.setPixel(x, y, pixel)
self.rawnoise = rawnoise
if create_revealer:
self.make_revealer()
def make_calnoise(self):
random.seed(self.calibration_noise)
w, h = self.SIZE
rawnoise = QImage(w, h, QImage.Format_Mono)
for x in range(w):
for y in range(h):
rawnoise.setPixel(x,y,random.randint(0, 1))
self.calnoise = self.pixelcode_2x2(rawnoise)
def make_revealer(self):
revealer = self.pixelcode_2x2(self.rawnoise)
revealer.invertPixels()
revealer = QBitmap.fromImage(revealer)
revealer = revealer.scaled(self.f_size, Qt.KeepAspectRatio)
revealer = self.overlay_marks(revealer)
self.filename_prefix = 'revealer_'
revealer.save(self.get_path_to_revealer_file('.png'))
self.toPdf(QImage(revealer))
QDesktopServices.openUrl(QUrl.fromLocalFile(self.get_path_to_revealer_file('.pdf')))
def make_cypherseed(self, img, rawnoise, calibration=False, is_seed = True):
img = img.convertToFormat(QImage.Format_Mono)
p = QPainter()
p.begin(img)
p.setCompositionMode(26) #xor
p.drawImage(0, 0, rawnoise)
p.end()
cypherseed = self.pixelcode_2x2(img)
cypherseed = QBitmap.fromImage(cypherseed)
cypherseed = cypherseed.scaled(self.f_size, Qt.KeepAspectRatio)
cypherseed = self.overlay_marks(cypherseed, True, calibration)
if not is_seed:
self.filename_prefix = 'custom_secret_'
self.was = _('Custom secret')
else:
self.filename_prefix = self.wallet_name + '_seed_'
self.was = self.wallet_name + ' ' + _('seed')
if self.extension:
self.ext_warning(self.c_dialog)
if not calibration:
self.toPdf(QImage(cypherseed))
QDesktopServices.openUrl(QUrl.fromLocalFile(self.get_path_to_revealer_file('.pdf')))
cypherseed.save(self.get_path_to_revealer_file('.png'))
self.bcrypt(self.c_dialog)
return cypherseed
def calibration(self):
img = QImage(self.SIZE[0], self.SIZE[1], QImage.Format_Mono)
bitmap = QBitmap.fromImage(img, Qt.MonoOnly)
bitmap.fill(Qt.black)
self.make_calnoise()
img = self.overlay_marks(self.calnoise.scaledToHeight(self.f_size.height()), False, True)
self.calibration_pdf(img)
QDesktopServices.openUrl(QUrl.fromLocalFile(self.get_path_to_calibration_file()))
return img
def toPdf(self, image):
printer = QPrinter()
printer.setPaperSize(QSizeF(210, 297), QPrinter.Millimeter)
printer.setResolution(600)
printer.setOutputFormat(QPrinter.PdfFormat)
printer.setOutputFileName(self.get_path_to_revealer_file('.pdf'))
printer.setPageMargins(0,0,0,0,6)
painter = QPainter()
painter.begin(printer)
delta_h = round(image.width()/self.abstand_v)
delta_v = round(image.height()/self.abstand_h)
size_h = 2028+((int(self.calibration_h)*2028/(2028-(delta_h*2)+int(self.calibration_h)))/2)
size_v = 1284+((int(self.calibration_v)*1284/(1284-(delta_v*2)+int(self.calibration_v)))/2)
image = image.scaled(size_h, size_v)
painter.drawImage(553,533, image)
wpath = QPainterPath()
wpath.addRoundedRect(QRectF(553,533, size_h, size_v), 19, 19)
painter.setPen(QPen(Qt.black, 1))
painter.drawPath(wpath)
painter.end()
def calibration_pdf(self, image):
printer = QPrinter()
printer.setPaperSize(QSizeF(210, 297), QPrinter.Millimeter)
printer.setResolution(600)
printer.setOutputFormat(QPrinter.PdfFormat)
printer.setOutputFileName(self.get_path_to_calibration_file())
printer.setPageMargins(0,0,0,0,6)
painter = QPainter()
painter.begin(printer)
painter.drawImage(553,533, image)
font = QFont('Source Sans Pro', 10, QFont.Bold)
painter.setFont(font)
painter.drawText(254,277, _("Calibration sheet"))
font = QFont('Source Sans Pro', 7, QFont.Bold)
painter.setFont(font)
painter.drawText(600,2077, _("Instructions:"))
font = QFont('Source Sans Pro', 7, QFont.Normal)
painter.setFont(font)
painter.drawText(700, 2177, _("1. Place this paper on a flat and well iluminated surface."))
painter.drawText(700, 2277, _("2. Align your Revealer borderlines to the dashed lines on the top and left."))
painter.drawText(700, 2377, _("3. Press slightly the Revealer against the paper and read the numbers that best "
"match on the opposite sides. "))
painter.drawText(700, 2477, _("4. Type the numbers in the software"))
painter.end()
def pixelcode_2x2(self, img):
result = QImage(img.width()*2, img.height()*2, QImage.Format_ARGB32 )
white = qRgba(255,255,255,0)
black = qRgba(0,0,0,255)
for x in range(img.width()):
for y in range(img.height()):
c = img.pixel(QPoint(x,y))
colors = QColor(c).getRgbF()
if colors[0]:
result.setPixel(x*2+1,y*2+1, black)
result.setPixel(x*2,y*2+1, white)
result.setPixel(x*2+1,y*2, white)
result.setPixel(x*2, y*2, black)
else:
result.setPixel(x*2+1,y*2+1, white)
result.setPixel(x*2,y*2+1, black)
result.setPixel(x*2+1,y*2, black)
result.setPixel(x*2, y*2, white)
return result
def overlay_marks(self, img, is_cseed=False, calibration_sheet=False):
border_color = Qt.white
base_img = QImage(self.f_size.width(),self.f_size.height(), QImage.Format_ARGB32)
base_img.fill(border_color)
img = QImage(img)
painter = QPainter()
painter.begin(base_img)
total_distance_h = round(base_img.width() / self.abstand_v)
dist_v = round(total_distance_h) / 2
dist_h = round(total_distance_h) / 2
img = img.scaledToWidth(base_img.width() - (2 * (total_distance_h)))
painter.drawImage(total_distance_h,
total_distance_h,
img)
#frame around image
pen = QPen(Qt.black, 2)
painter.setPen(pen)
#horz
painter.drawLine(0, total_distance_h, base_img.width(), total_distance_h)
painter.drawLine(0, base_img.height()-(total_distance_h), base_img.width(), base_img.height()-(total_distance_h))
#vert
painter.drawLine(total_distance_h, 0, total_distance_h, base_img.height())
painter.drawLine(base_img.width()-(total_distance_h), 0, base_img.width()-(total_distance_h), base_img.height())
#border around img
border_thick = 6
Rpath = QPainterPath()
Rpath.addRect(QRectF((total_distance_h)+(border_thick/2),
(total_distance_h)+(border_thick/2),
base_img.width()-((total_distance_h)*2)-((border_thick)-1),
(base_img.height()-((total_distance_h))*2)-((border_thick)-1)))
pen = QPen(Qt.black, border_thick)
pen.setJoinStyle (Qt.MiterJoin)
painter.setPen(pen)
painter.drawPath(Rpath)
Bpath = QPainterPath()
Bpath.addRect(QRectF((total_distance_h), (total_distance_h),
base_img.width()-((total_distance_h)*2), (base_img.height()-((total_distance_h))*2)))
pen = QPen(Qt.black, 1)
painter.setPen(pen)
painter.drawPath(Bpath)
pen = QPen(Qt.black, 1)
painter.setPen(pen)
painter.drawLine(0, base_img.height()/2, total_distance_h, base_img.height()/2)
painter.drawLine(base_img.width()/2, 0, base_img.width()/2, total_distance_h)
painter.drawLine(base_img.width()-total_distance_h, base_img.height()/2, base_img.width(), base_img.height()/2)
painter.drawLine(base_img.width()/2, base_img.height(), base_img.width()/2, base_img.height() - total_distance_h)
#print code
f_size = 37
QFontDatabase.addApplicationFont(os.path.join(os.path.dirname(__file__), 'DejaVuSansMono-Bold.ttf'))
font = QFont("DejaVu Sans Mono", f_size-11, QFont.Bold)
font.setPixelSize(35)
painter.setFont(font)
if not calibration_sheet:
if is_cseed: #its a secret
painter.setPen(QPen(Qt.black, 1, Qt.DashDotDotLine))
painter.drawLine(0, dist_v, base_img.width(), dist_v)
painter.drawLine(dist_h, 0, dist_h, base_img.height())
painter.drawLine(0, base_img.height()-dist_v, base_img.width(), base_img.height()-(dist_v))
painter.drawLine(base_img.width()-(dist_h), 0, base_img.width()-(dist_h), base_img.height())
painter.drawImage(((total_distance_h))+11, ((total_distance_h))+11,
QImage(icon_path('electrumb.png')).scaledToWidth(2.1*(total_distance_h), Qt.SmoothTransformation))
painter.setPen(QPen(Qt.white, border_thick*8))
painter.drawLine(base_img.width()-((total_distance_h))-(border_thick*8)/2-(border_thick/2)-2,
(base_img.height()-((total_distance_h)))-((border_thick*8)/2)-(border_thick/2)-2,
base_img.width()-((total_distance_h))-(border_thick*8)/2-(border_thick/2)-2 - 77,
(base_img.height()-((total_distance_h)))-((border_thick*8)/2)-(border_thick/2)-2)
painter.setPen(QColor(0,0,0,255))
painter.drawText(QRect(0, base_img.height()-107, base_img.width()-total_distance_h - border_thick - 11,
base_img.height()-total_distance_h - border_thick), Qt.AlignRight,
self.versioned_seed.version + '_'+self.versioned_seed.checksum)
painter.end()
else: # revealer
painter.setPen(QPen(border_color, 17))
painter.drawLine(0, dist_v, base_img.width(), dist_v)
painter.drawLine(dist_h, 0, dist_h, base_img.height())
painter.drawLine(0, base_img.height()-dist_v, base_img.width(), base_img.height()-(dist_v))
painter.drawLine(base_img.width()-(dist_h), 0, base_img.width()-(dist_h), base_img.height())
painter.setPen(QPen(Qt.black, 2))
painter.drawLine(0, dist_v, base_img.width(), dist_v)
painter.drawLine(dist_h, 0, dist_h, base_img.height())
painter.drawLine(0, base_img.height()-dist_v, base_img.width(), base_img.height()-(dist_v))
painter.drawLine(base_img.width()-(dist_h), 0, base_img.width()-(dist_h), base_img.height())
logo = QImage(icon_path('revealer_c.png')).scaledToWidth(1.3*(total_distance_h))
painter.drawImage((total_distance_h)+ (border_thick), ((total_distance_h))+ (border_thick), logo, Qt.SmoothTransformation)
#frame around logo
painter.setPen(QPen(Qt.black, border_thick))
painter.drawLine(total_distance_h+border_thick, total_distance_h+logo.height()+3*(border_thick/2),
total_distance_h+logo.width()+border_thick, total_distance_h+logo.height()+3*(border_thick/2))
painter.drawLine(logo.width()+total_distance_h+3*(border_thick/2), total_distance_h+(border_thick),
total_distance_h+logo.width()+3*(border_thick/2), total_distance_h+logo.height()+(border_thick))
#frame around code/qr
qr_size = 179
painter.drawLine((base_img.width()-((total_distance_h))-(border_thick/2)-2)-qr_size,
(base_img.height()-((total_distance_h)))-((border_thick*8))-(border_thick/2)-2,
(base_img.width()/2+(total_distance_h/2)-border_thick-(border_thick*8)/2)-qr_size,
(base_img.height()-((total_distance_h)))-((border_thick*8))-(border_thick/2)-2)
painter.drawLine((base_img.width()/2+(total_distance_h/2)-border_thick-(border_thick*8)/2)-qr_size,
(base_img.height()-((total_distance_h)))-((border_thick*8))-(border_thick/2)-2,
base_img.width()/2 + (total_distance_h/2)-border_thick-(border_thick*8)/2-qr_size,
((base_img.height()-((total_distance_h)))-(border_thick/2)-2))
painter.setPen(QPen(Qt.white, border_thick * 8))
painter.drawLine(
base_img.width() - ((total_distance_h)) - (border_thick * 8) / 2 - (border_thick / 2) - 2,
(base_img.height() - ((total_distance_h))) - ((border_thick * 8) / 2) - (border_thick / 2) - 2,
base_img.width() / 2 + (total_distance_h / 2) - border_thick - qr_size,
(base_img.height() - ((total_distance_h))) - ((border_thick * 8) / 2) - (border_thick / 2) - 2)
painter.setPen(QColor(0,0,0,255))
painter.drawText(QRect(((base_img.width()/2) +21)-qr_size, base_img.height()-107,
base_img.width()-total_distance_h - border_thick -93,
base_img.height()-total_distance_h - border_thick), Qt.AlignLeft, self.versioned_seed.get_ui_string_version_plus_seed())
painter.drawText(QRect(0, base_img.height()-107, base_img.width()-total_distance_h - border_thick -3 -qr_size,
base_img.height()-total_distance_h - border_thick), Qt.AlignRight, self.versioned_seed.checksum)
# draw qr code
qr_qt = self.paintQR(self.versioned_seed.get_ui_string_version_plus_seed()
+ self.versioned_seed.checksum)
target = QRectF(base_img.width()-65-qr_size,
base_img.height()-65-qr_size,
qr_size, qr_size )
painter.drawImage(target, qr_qt)
painter.setPen(QPen(Qt.black, 4))
painter.drawLine(base_img.width()-65-qr_size,
base_img.height()-65-qr_size,
base_img.width() - 65 - qr_size,
(base_img.height() - ((total_distance_h))) - ((border_thick * 8)) - (border_thick / 2) - 4
)
painter.drawLine(base_img.width()-65-qr_size,
base_img.height()-65-qr_size,
base_img.width() - 65,
base_img.height()-65-qr_size
)
painter.end()
else: # calibration only
painter.end()
cal_img = QImage(self.f_size.width() + 100, self.f_size.height() + 100,
QImage.Format_ARGB32)
cal_img.fill(Qt.white)
cal_painter = QPainter()
cal_painter.begin(cal_img)
cal_painter.drawImage(0,0, base_img)
#black lines in the middle of border top left only
cal_painter.setPen(QPen(Qt.black, 1, Qt.DashDotDotLine))
cal_painter.drawLine(0, dist_v, base_img.width(), dist_v)
cal_painter.drawLine(dist_h, 0, dist_h, base_img.height())
pen = QPen(Qt.black, 2, Qt.DashDotDotLine)
cal_painter.setPen(pen)
n=15
cal_painter.setFont(QFont("DejaVu Sans Mono", 21, QFont.Bold))
for x in range(-n,n):
#lines on bottom (vertical calibration)
cal_painter.drawLine((((base_img.width())/(n*2)) *(x))+ (base_img.width()/2)-13,
x+2+base_img.height()-(dist_v),
(((base_img.width())/(n*2)) *(x))+ (base_img.width()/2)+13,
x+2+base_img.height()-(dist_v))
num_pos = 9
if x > 9 : num_pos = 17
if x < 0 : num_pos = 20
if x < -9: num_pos = 27
cal_painter.drawText((((base_img.width())/(n*2)) *(x))+ (base_img.width()/2)-num_pos,
50+base_img.height()-(dist_v),
str(x))
#lines on the right (horizontal calibrations)
cal_painter.drawLine(x+2+(base_img.width()-(dist_h)),
((base_img.height()/(2*n)) *(x))+ (base_img.height()/n)+(base_img.height()/2)-13,
x+2+(base_img.width()-(dist_h)),
((base_img.height()/(2*n)) *(x))+ (base_img.height()/n)+(base_img.height()/2)+13)
cal_painter.drawText(30+(base_img.width()-(dist_h)),
((base_img.height()/(2*n)) *(x))+ (base_img.height()/2)+13, str(x))
cal_painter.end()
base_img = cal_img
return base_img
def paintQR(self, data):
if not data:
return
qr = qrcode.QRCode()
qr.add_data(data)
matrix = qr.get_matrix()
k = len(matrix)
border_color = Qt.white
base_img = QImage(k * 5, k * 5, QImage.Format_ARGB32)
base_img.fill(border_color)
qrpainter = QPainter()
qrpainter.begin(base_img)
boxsize = 5
size = k * boxsize
left = (base_img.width() - size)/2
top = (base_img.height() - size)/2
qrpainter.setBrush(Qt.black)
qrpainter.setPen(Qt.black)
for r in range(k):
for c in range(k):
if matrix[r][c]:
qrpainter.drawRect(left+c*boxsize, top+r*boxsize, boxsize - 1, boxsize - 1)
qrpainter.end()
return base_img
def calibration_dialog(self, window):
d = WindowModalDialog(window, _("Revealer - Printer calibration settings"))
d.setMinimumSize(100, 200)
vbox = QVBoxLayout(d)
vbox.addWidget(QLabel(''.join(["<br/>", _("If you have an old printer, or want optimal precision"),"<br/>",
_("print the calibration pdf and follow the instructions "), "<br/>","<br/>",
])))
self.calibration_h = self.config.get('calibration_h')
self.calibration_v = self.config.get('calibration_v')
cprint = QPushButton(_("Open calibration pdf"))
cprint.clicked.connect(self.calibration)
vbox.addWidget(cprint)
vbox.addWidget(QLabel(_('Calibration values:')))
grid = QGridLayout()
vbox.addLayout(grid)
grid.addWidget(QLabel(_('Right side')), 0, 0)
horizontal = QLineEdit()
horizontal.setText(str(self.calibration_h))
grid.addWidget(horizontal, 0, 1)
grid.addWidget(QLabel(_('Bottom')), 1, 0)
vertical = QLineEdit()
vertical.setText(str(self.calibration_v))
grid.addWidget(vertical, 1, 1)
vbox.addStretch()
vbox.addSpacing(13)
vbox.addLayout(Buttons(CloseButton(d), OkButton(d)))
if not d.exec_():
return
self.calibration_h = int(Decimal(horizontal.text()))
self.config.set_key('calibration_h', self.calibration_h)
self.calibration_v = int(Decimal(vertical.text()))
self.config.set_key('calibration_v', self.calibration_v)
| 43.717848 | 159 | 0.584877 |
import os
import random
import traceback
from decimal import Decimal
from functools import partial
import sys
import qrcode
from PyQt5.QtPrintSupport import QPrinter
from PyQt5.QtCore import Qt, QRectF, QRect, QSizeF, QUrl, QPoint, QSize
from PyQt5.QtGui import (QPixmap, QImage, QBitmap, QPainter, QFontDatabase, QPen, QFont,
QColor, QDesktopServices, qRgba, QPainterPath)
from PyQt5.QtWidgets import (QGridLayout, QVBoxLayout, QHBoxLayout, QLabel,
QPushButton, QLineEdit)
from electrum_vestx.plugin import hook
from electrum_vestx.i18n import _
from electrum_vestx.util import make_dir, InvalidPassword, UserCancelled
from electrum_vestx.gui.qt.util import (read_QIcon, EnterButton, WWLabel, icon_path,
WindowModalDialog, Buttons, CloseButton, OkButton)
from electrum_vestx.gui.qt.qrtextedit import ScanQRTextEdit
from electrum_vestx.gui.qt.main_window import StatusBarButton
from .revealer import RevealerPlugin
class Plugin(RevealerPlugin):
MAX_PLAINTEXT_LEN = 189
def __init__(self, parent, config, name):
RevealerPlugin.__init__(self, parent, config, name)
self.base_dir = os.path.join(config.electrum_path(), 'revealer')
if self.config.get('calibration_h') is None:
self.config.set_key('calibration_h', 0)
if self.config.get('calibration_v') is None:
self.config.set_key('calibration_v', 0)
self.calibration_h = self.config.get('calibration_h')
self.calibration_v = self.config.get('calibration_v')
self.f_size = QSize(1014*2, 642*2)
self.abstand_h = 21
self.abstand_v = 34
self.calibration_noise = int('10' * 128)
self.rawnoise = False
make_dir(self.base_dir)
self.extension = False
@hook
def create_status_bar(self, parent):
b = StatusBarButton(read_QIcon('revealer.png'), "Revealer "+_("secret backup utility"),
partial(self.setup_dialog, parent))
parent.addPermanentWidget(b)
def requires_settings(self):
return True
def settings_widget(self, window):
return EnterButton(_('Printer Calibration'), partial(self.calibration_dialog, window))
def password_dialog(self, msg=None, parent=None):
from electrum_vestx.gui.qt.password_dialog import PasswordDialog
parent = parent or self
d = PasswordDialog(parent, msg)
return d.run()
def get_seed(self):
password = None
if self.wallet.has_keystore_encryption():
password = self.password_dialog(parent=self.d.parent())
if not password:
raise UserCancelled()
keystore = self.wallet.get_keystore()
if not keystore or not keystore.has_seed():
return
self.extension = bool(keystore.get_passphrase(password))
return keystore.get_seed(password)
def setup_dialog(self, window):
self.wallet = window.parent().wallet
self.update_wallet_name(self.wallet)
self.user_input = False
self.d = WindowModalDialog(window, "Setup Dialog")
self.d.setMinimumWidth(500)
self.d.setMinimumHeight(210)
self.d.setMaximumHeight(320)
self.d.setContentsMargins(11,11,1,1)
self.hbox = QHBoxLayout(self.d)
vbox = QVBoxLayout()
logo = QLabel()
self.hbox.addWidget(logo)
logo.setPixmap(QPixmap(icon_path('revealer.png')))
logo.setAlignment(Qt.AlignLeft)
self.hbox.addSpacing(16)
vbox.addWidget(WWLabel("<b>"+_("Revealer Secret Backup Plugin")+"</b><br>"
+_("To encrypt your backup, first we need to load some noise.")+"<br/>"))
vbox.addSpacing(7)
bcreate = QPushButton(_("Create a new Revealer"))
bcreate.setMaximumWidth(181)
bcreate.setDefault(True)
vbox.addWidget(bcreate, Qt.AlignCenter)
self.load_noise = ScanQRTextEdit()
self.load_noise.setTabChangesFocus(True)
self.load_noise.textChanged.connect(self.on_edit)
self.load_noise.setMaximumHeight(33)
self.hbox.addLayout(vbox)
vbox.addWidget(WWLabel(_("or type an existing revealer code below and click 'next':")))
vbox.addWidget(self.load_noise)
vbox.addSpacing(3)
self.next_button = QPushButton(_("Next"), self.d)
self.next_button.setEnabled(False)
vbox.addLayout(Buttons(self.next_button))
self.next_button.clicked.connect(self.d.close)
self.next_button.clicked.connect(partial(self.cypherseed_dialog, window))
vbox.addWidget(
QLabel("<b>" + _("Warning") + "</b>: " + _("Each revealer should be used only once.")
+"<br>"+_("more information at <a href=\"https://revealer.cc/faq\">https://revealer.cc/faq</a>")))
def mk_digital():
try:
self.make_digital(self.d)
except Exception:
self.logger.exception('')
else:
self.cypherseed_dialog(window)
bcreate.clicked.connect(mk_digital)
return bool(self.d.exec_())
def get_noise(self):
text = self.load_noise.text()
return ''.join(text.split()).lower()
def on_edit(self):
txt = self.get_noise()
versioned_seed = self.get_versioned_seed_from_user_input(txt)
if versioned_seed:
self.versioned_seed = versioned_seed
self.user_input = bool(versioned_seed)
self.next_button.setEnabled(bool(versioned_seed))
def make_digital(self, dialog):
self.make_rawnoise(True)
self.bdone(dialog)
self.d.close()
def get_path_to_revealer_file(self, ext: str= '') -> str:
version = self.versioned_seed.version
code_id = self.versioned_seed.checksum
filename = self.filename_prefix + version + "_" + code_id + ext
path = os.path.join(self.base_dir, filename)
return os.path.normcase(os.path.abspath(path))
def get_path_to_calibration_file(self):
path = os.path.join(self.base_dir, 'calibration.pdf')
return os.path.normcase(os.path.abspath(path))
def bcrypt(self, dialog):
self.rawnoise = False
version = self.versioned_seed.version
code_id = self.versioned_seed.checksum
dialog.show_message(''.join([_("{} encrypted for Revealer {}_{} saved as PNG and PDF at: ").format(self.was, version, code_id),
"<b>", self.get_path_to_revealer_file(), "</b>", "<br/>",
"<br/>", "<b>", _("Always check your backups.")]),
rich_text=True)
dialog.close()
def ext_warning(self, dialog):
dialog.show_message(''.join(["<b>",_("Warning"), ": </b>",
_("your seed extension will <b>not</b> be included in the encrypted backup.")]),
rich_text=True)
dialog.close()
def bdone(self, dialog):
version = self.versioned_seed.version
code_id = self.versioned_seed.checksum
dialog.show_message(''.join([_("Digital Revealer ({}_{}) saved as PNG and PDF at:").format(version, code_id),
"<br/>","<b>", self.get_path_to_revealer_file(), '</b>']),
rich_text=True)
def customtxt_limits(self):
txt = self.text.text()
self.max_chars.setVisible(False)
self.char_count.setText(f"({len(txt)}/{self.MAX_PLAINTEXT_LEN})")
if len(txt)>0:
self.ctext.setEnabled(True)
if len(txt) > self.MAX_PLAINTEXT_LEN:
self.text.setPlainText(txt[:self.MAX_PLAINTEXT_LEN])
self.max_chars.setVisible(True)
def t(self):
self.txt = self.text.text()
self.seed_img(is_seed=False)
def warn_old_revealer(self):
if self.versioned_seed.version == '0':
link = "https://revealer.cc/revealer-warning-and-upgrade/"
self.d.show_warning(("<b>{warning}: </b>{ver0}<br>"
"{url}<br>"
"{risk}")
.format(warning=_("Warning"),
ver0=_("Revealers starting with 0 are not secure due to a vulnerability."),
url=_("More info at: {}").format(f'<a href="{link}">{link}</a>'),
risk=_("Proceed at your own risk.")),
rich_text=True)
def cypherseed_dialog(self, window):
self.warn_old_revealer()
d = WindowModalDialog(window, "Encryption Dialog")
d.setMinimumWidth(500)
d.setMinimumHeight(210)
d.setMaximumHeight(450)
d.setContentsMargins(11, 11, 1, 1)
self.c_dialog = d
hbox = QHBoxLayout(d)
self.vbox = QVBoxLayout()
logo = QLabel()
hbox.addWidget(logo)
logo.setPixmap(QPixmap(icon_path('revealer.png')))
logo.setAlignment(Qt.AlignLeft)
hbox.addSpacing(16)
self.vbox.addWidget(WWLabel("<b>" + _("Revealer Secret Backup Plugin") + "</b><br>"
+ _("Ready to encrypt for revealer {}")
.format(self.versioned_seed.version+'_'+self.versioned_seed.checksum)))
self.vbox.addSpacing(11)
hbox.addLayout(self.vbox)
grid = QGridLayout()
self.vbox.addLayout(grid)
cprint = QPushButton(_("Encrypt {}'s seed").format(self.wallet_name))
cprint.setMaximumWidth(250)
cprint.clicked.connect(partial(self.seed_img, True))
self.vbox.addWidget(cprint)
self.vbox.addSpacing(1)
self.vbox.addWidget(WWLabel("<b>"+_("OR")+"</b> "+_("type a custom alphanumerical secret below:")))
self.text = ScanQRTextEdit()
self.text.setTabChangesFocus(True)
self.text.setMaximumHeight(70)
self.text.textChanged.connect(self.customtxt_limits)
self.vbox.addWidget(self.text)
self.char_count = WWLabel("")
self.char_count.setAlignment(Qt.AlignRight)
self.vbox.addWidget(self.char_count)
self.max_chars = WWLabel("<font color='red'>"
+ _("This version supports a maximum of {} characters.").format(self.MAX_PLAINTEXT_LEN)
+"</font>")
self.vbox.addWidget(self.max_chars)
self.max_chars.setVisible(False)
self.ctext = QPushButton(_("Encrypt custom secret"))
self.ctext.clicked.connect(self.t)
self.vbox.addWidget(self.ctext)
self.ctext.setEnabled(False)
self.vbox.addSpacing(11)
self.vbox.addLayout(Buttons(CloseButton(d)))
return bool(d.exec_())
def update_wallet_name(self, name):
self.wallet_name = str(name)
def seed_img(self, is_seed = True):
if is_seed:
try:
cseed = self.get_seed()
except UserCancelled:
return
except InvalidPassword as e:
self.d.show_error(str(e))
return
if not cseed:
self.d.show_message(_("This wallet has no seed"))
return
txt = cseed.upper()
else:
txt = self.txt.upper()
img = QImage(self.SIZE[0], self.SIZE[1], QImage.Format_Mono)
bitmap = QBitmap.fromImage(img, Qt.MonoOnly)
bitmap.fill(Qt.white)
painter = QPainter()
painter.begin(bitmap)
QFontDatabase.addApplicationFont(os.path.join(os.path.dirname(__file__), 'SourceSansPro-Bold.otf') )
if len(txt) < 102 :
fontsize = 15
linespace = 15
max_letters = 17
max_lines = 6
max_words = 3
else:
fontsize = 12
linespace = 10
max_letters = 21
max_lines = 9
max_words = int(max_letters/4)
font = QFont('Source Sans Pro', fontsize, QFont.Bold)
font.setLetterSpacing(QFont.PercentageSpacing, 100)
font.setPixelSize(fontsize)
painter.setFont(font)
seed_array = txt.split(' ')
for n in range(max_lines):
nwords = max_words
temp_seed = seed_array[:nwords]
while len(' '.join(map(str, temp_seed))) > max_letters:
nwords = nwords - 1
temp_seed = seed_array[:nwords]
painter.drawText(QRect(0, linespace*n , self.SIZE[0], self.SIZE[1]), Qt.AlignHCenter, ' '.join(map(str, temp_seed)))
del seed_array[:nwords]
painter.end()
img = bitmap.toImage()
if (self.rawnoise == False):
self.make_rawnoise()
self.make_cypherseed(img, self.rawnoise, False, is_seed)
return img
def make_rawnoise(self, create_revealer=False):
if not self.user_input:
self.versioned_seed = self.gen_random_versioned_seed()
assert self.versioned_seed
w, h = self.SIZE
rawnoise = QImage(w, h, QImage.Format_Mono)
noise_map = self.get_noise_map(self.versioned_seed)
for (x,y), pixel in noise_map.items():
rawnoise.setPixel(x, y, pixel)
self.rawnoise = rawnoise
if create_revealer:
self.make_revealer()
def make_calnoise(self):
random.seed(self.calibration_noise)
w, h = self.SIZE
rawnoise = QImage(w, h, QImage.Format_Mono)
for x in range(w):
for y in range(h):
rawnoise.setPixel(x,y,random.randint(0, 1))
self.calnoise = self.pixelcode_2x2(rawnoise)
def make_revealer(self):
revealer = self.pixelcode_2x2(self.rawnoise)
revealer.invertPixels()
revealer = QBitmap.fromImage(revealer)
revealer = revealer.scaled(self.f_size, Qt.KeepAspectRatio)
revealer = self.overlay_marks(revealer)
self.filename_prefix = 'revealer_'
revealer.save(self.get_path_to_revealer_file('.png'))
self.toPdf(QImage(revealer))
QDesktopServices.openUrl(QUrl.fromLocalFile(self.get_path_to_revealer_file('.pdf')))
def make_cypherseed(self, img, rawnoise, calibration=False, is_seed = True):
img = img.convertToFormat(QImage.Format_Mono)
p = QPainter()
p.begin(img)
p.setCompositionMode(26) #xor
p.drawImage(0, 0, rawnoise)
p.end()
cypherseed = self.pixelcode_2x2(img)
cypherseed = QBitmap.fromImage(cypherseed)
cypherseed = cypherseed.scaled(self.f_size, Qt.KeepAspectRatio)
cypherseed = self.overlay_marks(cypherseed, True, calibration)
if not is_seed:
self.filename_prefix = 'custom_secret_'
self.was = _('Custom secret')
else:
self.filename_prefix = self.wallet_name + '_seed_'
self.was = self.wallet_name + ' ' + _('seed')
if self.extension:
self.ext_warning(self.c_dialog)
if not calibration:
self.toPdf(QImage(cypherseed))
QDesktopServices.openUrl(QUrl.fromLocalFile(self.get_path_to_revealer_file('.pdf')))
cypherseed.save(self.get_path_to_revealer_file('.png'))
self.bcrypt(self.c_dialog)
return cypherseed
def calibration(self):
img = QImage(self.SIZE[0], self.SIZE[1], QImage.Format_Mono)
bitmap = QBitmap.fromImage(img, Qt.MonoOnly)
bitmap.fill(Qt.black)
self.make_calnoise()
img = self.overlay_marks(self.calnoise.scaledToHeight(self.f_size.height()), False, True)
self.calibration_pdf(img)
QDesktopServices.openUrl(QUrl.fromLocalFile(self.get_path_to_calibration_file()))
return img
def toPdf(self, image):
printer = QPrinter()
printer.setPaperSize(QSizeF(210, 297), QPrinter.Millimeter)
printer.setResolution(600)
printer.setOutputFormat(QPrinter.PdfFormat)
printer.setOutputFileName(self.get_path_to_revealer_file('.pdf'))
printer.setPageMargins(0,0,0,0,6)
painter = QPainter()
painter.begin(printer)
delta_h = round(image.width()/self.abstand_v)
delta_v = round(image.height()/self.abstand_h)
size_h = 2028+((int(self.calibration_h)*2028/(2028-(delta_h*2)+int(self.calibration_h)))/2)
size_v = 1284+((int(self.calibration_v)*1284/(1284-(delta_v*2)+int(self.calibration_v)))/2)
image = image.scaled(size_h, size_v)
painter.drawImage(553,533, image)
wpath = QPainterPath()
wpath.addRoundedRect(QRectF(553,533, size_h, size_v), 19, 19)
painter.setPen(QPen(Qt.black, 1))
painter.drawPath(wpath)
painter.end()
def calibration_pdf(self, image):
printer = QPrinter()
printer.setPaperSize(QSizeF(210, 297), QPrinter.Millimeter)
printer.setResolution(600)
printer.setOutputFormat(QPrinter.PdfFormat)
printer.setOutputFileName(self.get_path_to_calibration_file())
printer.setPageMargins(0,0,0,0,6)
painter = QPainter()
painter.begin(printer)
painter.drawImage(553,533, image)
font = QFont('Source Sans Pro', 10, QFont.Bold)
painter.setFont(font)
painter.drawText(254,277, _("Calibration sheet"))
font = QFont('Source Sans Pro', 7, QFont.Bold)
painter.setFont(font)
painter.drawText(600,2077, _("Instructions:"))
font = QFont('Source Sans Pro', 7, QFont.Normal)
painter.setFont(font)
painter.drawText(700, 2177, _("1. Place this paper on a flat and well iluminated surface."))
painter.drawText(700, 2277, _("2. Align your Revealer borderlines to the dashed lines on the top and left."))
painter.drawText(700, 2377, _("3. Press slightly the Revealer against the paper and read the numbers that best "
"match on the opposite sides. "))
painter.drawText(700, 2477, _("4. Type the numbers in the software"))
painter.end()
def pixelcode_2x2(self, img):
result = QImage(img.width()*2, img.height()*2, QImage.Format_ARGB32 )
white = qRgba(255,255,255,0)
black = qRgba(0,0,0,255)
for x in range(img.width()):
for y in range(img.height()):
c = img.pixel(QPoint(x,y))
colors = QColor(c).getRgbF()
if colors[0]:
result.setPixel(x*2+1,y*2+1, black)
result.setPixel(x*2,y*2+1, white)
result.setPixel(x*2+1,y*2, white)
result.setPixel(x*2, y*2, black)
else:
result.setPixel(x*2+1,y*2+1, white)
result.setPixel(x*2,y*2+1, black)
result.setPixel(x*2+1,y*2, black)
result.setPixel(x*2, y*2, white)
return result
def overlay_marks(self, img, is_cseed=False, calibration_sheet=False):
border_color = Qt.white
base_img = QImage(self.f_size.width(),self.f_size.height(), QImage.Format_ARGB32)
base_img.fill(border_color)
img = QImage(img)
painter = QPainter()
painter.begin(base_img)
total_distance_h = round(base_img.width() / self.abstand_v)
dist_v = round(total_distance_h) / 2
dist_h = round(total_distance_h) / 2
img = img.scaledToWidth(base_img.width() - (2 * (total_distance_h)))
painter.drawImage(total_distance_h,
total_distance_h,
img)
#frame around image
pen = QPen(Qt.black, 2)
painter.setPen(pen)
#horz
painter.drawLine(0, total_distance_h, base_img.width(), total_distance_h)
painter.drawLine(0, base_img.height()-(total_distance_h), base_img.width(), base_img.height()-(total_distance_h))
#vert
painter.drawLine(total_distance_h, 0, total_distance_h, base_img.height())
painter.drawLine(base_img.width()-(total_distance_h), 0, base_img.width()-(total_distance_h), base_img.height())
#border around img
border_thick = 6
Rpath = QPainterPath()
Rpath.addRect(QRectF((total_distance_h)+(border_thick/2),
(total_distance_h)+(border_thick/2),
base_img.width()-((total_distance_h)*2)-((border_thick)-1),
(base_img.height()-((total_distance_h))*2)-((border_thick)-1)))
pen = QPen(Qt.black, border_thick)
pen.setJoinStyle (Qt.MiterJoin)
painter.setPen(pen)
painter.drawPath(Rpath)
Bpath = QPainterPath()
Bpath.addRect(QRectF((total_distance_h), (total_distance_h),
base_img.width()-((total_distance_h)*2), (base_img.height()-((total_distance_h))*2)))
pen = QPen(Qt.black, 1)
painter.setPen(pen)
painter.drawPath(Bpath)
pen = QPen(Qt.black, 1)
painter.setPen(pen)
painter.drawLine(0, base_img.height()/2, total_distance_h, base_img.height()/2)
painter.drawLine(base_img.width()/2, 0, base_img.width()/2, total_distance_h)
painter.drawLine(base_img.width()-total_distance_h, base_img.height()/2, base_img.width(), base_img.height()/2)
painter.drawLine(base_img.width()/2, base_img.height(), base_img.width()/2, base_img.height() - total_distance_h)
#print code
f_size = 37
QFontDatabase.addApplicationFont(os.path.join(os.path.dirname(__file__), 'DejaVuSansMono-Bold.ttf'))
font = QFont("DejaVu Sans Mono", f_size-11, QFont.Bold)
font.setPixelSize(35)
painter.setFont(font)
if not calibration_sheet:
if is_cseed: #its a secret
painter.setPen(QPen(Qt.black, 1, Qt.DashDotDotLine))
painter.drawLine(0, dist_v, base_img.width(), dist_v)
painter.drawLine(dist_h, 0, dist_h, base_img.height())
painter.drawLine(0, base_img.height()-dist_v, base_img.width(), base_img.height()-(dist_v))
painter.drawLine(base_img.width()-(dist_h), 0, base_img.width()-(dist_h), base_img.height())
painter.drawImage(((total_distance_h))+11, ((total_distance_h))+11,
QImage(icon_path('electrumb.png')).scaledToWidth(2.1*(total_distance_h), Qt.SmoothTransformation))
painter.setPen(QPen(Qt.white, border_thick*8))
painter.drawLine(base_img.width()-((total_distance_h))-(border_thick*8)/2-(border_thick/2)-2,
(base_img.height()-((total_distance_h)))-((border_thick*8)/2)-(border_thick/2)-2,
base_img.width()-((total_distance_h))-(border_thick*8)/2-(border_thick/2)-2 - 77,
(base_img.height()-((total_distance_h)))-((border_thick*8)/2)-(border_thick/2)-2)
painter.setPen(QColor(0,0,0,255))
painter.drawText(QRect(0, base_img.height()-107, base_img.width()-total_distance_h - border_thick - 11,
base_img.height()-total_distance_h - border_thick), Qt.AlignRight,
self.versioned_seed.version + '_'+self.versioned_seed.checksum)
painter.end()
else: # revealer
painter.setPen(QPen(border_color, 17))
painter.drawLine(0, dist_v, base_img.width(), dist_v)
painter.drawLine(dist_h, 0, dist_h, base_img.height())
painter.drawLine(0, base_img.height()-dist_v, base_img.width(), base_img.height()-(dist_v))
painter.drawLine(base_img.width()-(dist_h), 0, base_img.width()-(dist_h), base_img.height())
painter.setPen(QPen(Qt.black, 2))
painter.drawLine(0, dist_v, base_img.width(), dist_v)
painter.drawLine(dist_h, 0, dist_h, base_img.height())
painter.drawLine(0, base_img.height()-dist_v, base_img.width(), base_img.height()-(dist_v))
painter.drawLine(base_img.width()-(dist_h), 0, base_img.width()-(dist_h), base_img.height())
logo = QImage(icon_path('revealer_c.png')).scaledToWidth(1.3*(total_distance_h))
painter.drawImage((total_distance_h)+ (border_thick), ((total_distance_h))+ (border_thick), logo, Qt.SmoothTransformation)
#frame around logo
painter.setPen(QPen(Qt.black, border_thick))
painter.drawLine(total_distance_h+border_thick, total_distance_h+logo.height()+3*(border_thick/2),
total_distance_h+logo.width()+border_thick, total_distance_h+logo.height()+3*(border_thick/2))
painter.drawLine(logo.width()+total_distance_h+3*(border_thick/2), total_distance_h+(border_thick),
total_distance_h+logo.width()+3*(border_thick/2), total_distance_h+logo.height()+(border_thick))
#frame around code/qr
qr_size = 179
painter.drawLine((base_img.width()-((total_distance_h))-(border_thick/2)-2)-qr_size,
(base_img.height()-((total_distance_h)))-((border_thick*8))-(border_thick/2)-2,
(base_img.width()/2+(total_distance_h/2)-border_thick-(border_thick*8)/2)-qr_size,
(base_img.height()-((total_distance_h)))-((border_thick*8))-(border_thick/2)-2)
painter.drawLine((base_img.width()/2+(total_distance_h/2)-border_thick-(border_thick*8)/2)-qr_size,
(base_img.height()-((total_distance_h)))-((border_thick*8))-(border_thick/2)-2,
base_img.width()/2 + (total_distance_h/2)-border_thick-(border_thick*8)/2-qr_size,
((base_img.height()-((total_distance_h)))-(border_thick/2)-2))
painter.setPen(QPen(Qt.white, border_thick * 8))
painter.drawLine(
base_img.width() - ((total_distance_h)) - (border_thick * 8) / 2 - (border_thick / 2) - 2,
(base_img.height() - ((total_distance_h))) - ((border_thick * 8) / 2) - (border_thick / 2) - 2,
base_img.width() / 2 + (total_distance_h / 2) - border_thick - qr_size,
(base_img.height() - ((total_distance_h))) - ((border_thick * 8) / 2) - (border_thick / 2) - 2)
painter.setPen(QColor(0,0,0,255))
painter.drawText(QRect(((base_img.width()/2) +21)-qr_size, base_img.height()-107,
base_img.width()-total_distance_h - border_thick -93,
base_img.height()-total_distance_h - border_thick), Qt.AlignLeft, self.versioned_seed.get_ui_string_version_plus_seed())
painter.drawText(QRect(0, base_img.height()-107, base_img.width()-total_distance_h - border_thick -3 -qr_size,
base_img.height()-total_distance_h - border_thick), Qt.AlignRight, self.versioned_seed.checksum)
# draw qr code
qr_qt = self.paintQR(self.versioned_seed.get_ui_string_version_plus_seed()
+ self.versioned_seed.checksum)
target = QRectF(base_img.width()-65-qr_size,
base_img.height()-65-qr_size,
qr_size, qr_size )
painter.drawImage(target, qr_qt)
painter.setPen(QPen(Qt.black, 4))
painter.drawLine(base_img.width()-65-qr_size,
base_img.height()-65-qr_size,
base_img.width() - 65 - qr_size,
(base_img.height() - ((total_distance_h))) - ((border_thick * 8)) - (border_thick / 2) - 4
)
painter.drawLine(base_img.width()-65-qr_size,
base_img.height()-65-qr_size,
base_img.width() - 65,
base_img.height()-65-qr_size
)
painter.end()
else: # calibration only
painter.end()
cal_img = QImage(self.f_size.width() + 100, self.f_size.height() + 100,
QImage.Format_ARGB32)
cal_img.fill(Qt.white)
cal_painter = QPainter()
cal_painter.begin(cal_img)
cal_painter.drawImage(0,0, base_img)
#black lines in the middle of border top left only
cal_painter.setPen(QPen(Qt.black, 1, Qt.DashDotDotLine))
cal_painter.drawLine(0, dist_v, base_img.width(), dist_v)
cal_painter.drawLine(dist_h, 0, dist_h, base_img.height())
pen = QPen(Qt.black, 2, Qt.DashDotDotLine)
cal_painter.setPen(pen)
n=15
cal_painter.setFont(QFont("DejaVu Sans Mono", 21, QFont.Bold))
for x in range(-n,n):
#lines on bottom (vertical calibration)
cal_painter.drawLine((((base_img.width())/(n*2)) *(x))+ (base_img.width()/2)-13,
x+2+base_img.height()-(dist_v),
(((base_img.width())/(n*2)) *(x))+ (base_img.width()/2)+13,
x+2+base_img.height()-(dist_v))
num_pos = 9
if x > 9 : num_pos = 17
if x < 0 : num_pos = 20
if x < -9: num_pos = 27
cal_painter.drawText((((base_img.width())/(n*2)) *(x))+ (base_img.width()/2)-num_pos,
50+base_img.height()-(dist_v),
str(x))
#lines on the right (horizontal calibrations)
cal_painter.drawLine(x+2+(base_img.width()-(dist_h)),
((base_img.height()/(2*n)) *(x))+ (base_img.height()/n)+(base_img.height()/2)-13,
x+2+(base_img.width()-(dist_h)),
((base_img.height()/(2*n)) *(x))+ (base_img.height()/n)+(base_img.height()/2)+13)
cal_painter.drawText(30+(base_img.width()-(dist_h)),
((base_img.height()/(2*n)) *(x))+ (base_img.height()/2)+13, str(x))
cal_painter.end()
base_img = cal_img
return base_img
def paintQR(self, data):
if not data:
return
qr = qrcode.QRCode()
qr.add_data(data)
matrix = qr.get_matrix()
k = len(matrix)
border_color = Qt.white
base_img = QImage(k * 5, k * 5, QImage.Format_ARGB32)
base_img.fill(border_color)
qrpainter = QPainter()
qrpainter.begin(base_img)
boxsize = 5
size = k * boxsize
left = (base_img.width() - size)/2
top = (base_img.height() - size)/2
qrpainter.setBrush(Qt.black)
qrpainter.setPen(Qt.black)
for r in range(k):
for c in range(k):
if matrix[r][c]:
qrpainter.drawRect(left+c*boxsize, top+r*boxsize, boxsize - 1, boxsize - 1)
qrpainter.end()
return base_img
def calibration_dialog(self, window):
d = WindowModalDialog(window, _("Revealer - Printer calibration settings"))
d.setMinimumSize(100, 200)
vbox = QVBoxLayout(d)
vbox.addWidget(QLabel(''.join(["<br/>", _("If you have an old printer, or want optimal precision"),"<br/>",
_("print the calibration pdf and follow the instructions "), "<br/>","<br/>",
])))
self.calibration_h = self.config.get('calibration_h')
self.calibration_v = self.config.get('calibration_v')
cprint = QPushButton(_("Open calibration pdf"))
cprint.clicked.connect(self.calibration)
vbox.addWidget(cprint)
vbox.addWidget(QLabel(_('Calibration values:')))
grid = QGridLayout()
vbox.addLayout(grid)
grid.addWidget(QLabel(_('Right side')), 0, 0)
horizontal = QLineEdit()
horizontal.setText(str(self.calibration_h))
grid.addWidget(horizontal, 0, 1)
grid.addWidget(QLabel(_('Bottom')), 1, 0)
vertical = QLineEdit()
vertical.setText(str(self.calibration_v))
grid.addWidget(vertical, 1, 1)
vbox.addStretch()
vbox.addSpacing(13)
vbox.addLayout(Buttons(CloseButton(d), OkButton(d)))
if not d.exec_():
return
self.calibration_h = int(Decimal(horizontal.text()))
self.config.set_key('calibration_h', self.calibration_h)
self.calibration_v = int(Decimal(vertical.text()))
self.config.set_key('calibration_v', self.calibration_v)
| true | true |
790bea5cfa99570e690f18ab6edf2a2b4ec861fe | 11,546 | py | Python | gru.py | KingPixil/gram-rnn | b109e653d6b2657955931ee28553a61ac05271b0 | [
"MIT"
] | 4 | 2017-03-11T02:25:34.000Z | 2017-08-01T17:19:08.000Z | gru.py | KingPixil/text-rnn | b109e653d6b2657955931ee28553a61ac05271b0 | [
"MIT"
] | null | null | null | gru.py | KingPixil/text-rnn | b109e653d6b2657955931ee28553a61ac05271b0 | [
"MIT"
] | null | null | null | import numpy as np
import pickle
def unique(seq):
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))]
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def softmax(x, temperature=1.0):
exp_x = np.exp(x / temperature)
return exp_x / np.sum(exp_x)
class TextRNN(object):
def __init__(self, hiddenLayers=300, sequenceLength=100):
# Hidden Layers
self.hiddenLayers = hiddenLayers
# Learning Rate
self.learningRate = 2e-3
# Hidden State
self.h = {}
# Internal cursor
self.cursor = 0
# Sequence Length
self.sequenceLength = sequenceLength
def train(self, text, ngrams=7, delimiter=" "):
# Setup delimiter
self.delimiter = delimiter
# Split by delimiter
grams = text.split(delimiter) if delimiter != "" else list(text)
# Setup Data by Ngrams
self.data = [delimiter.join(grams[i:i+ngrams]) for i in range(len(grams))[::ngrams]]
# Get Unique Data
self.uniqueData = unique(self.data)
# Get Vocab Maps
self.indexToGram = {i:gram for i, gram in enumerate(self.uniqueData)}
self.gramToIndex = {gram:i for i, gram in enumerate(self.uniqueData)}
# Get vocab size
self.vocabSize = len(self.uniqueData)
# Setup Inputs
inputs = []
outputs = []
inputGrams = [self.gramToIndex[gram] for gram in self.data]
outputGrams = [self.gramToIndex[gram] for gram in self.data[1:]]
for i, inputGram in enumerate(inputGrams[0:-1]):
X = np.zeros((self.vocabSize, 1))
X[inputGram, 0] = 1
y = np.zeros((self.vocabSize, 1))
y[outputGrams[i], 0] = 1
inputs.append(X)
outputs.append(y)
self.inputs = inputs
self.outputs = outputs
# Input Weights
self.WXZ = np.random.randn(self.hiddenLayers, self.vocabSize) * 0.1 # Update Gate
self.WXR = np.random.randn(self.hiddenLayers, self.vocabSize) * 0.1 # Reset Gate
self.WXC = np.random.randn(self.hiddenLayers, self.vocabSize) * 0.1 # Candidate
# Hidden Layer Weights
self.WHZ = np.random.randn(self.hiddenLayers, self.hiddenLayers) * 0.1 # Update Gate
self.WHR = np.random.randn(self.hiddenLayers, self.hiddenLayers) * 0.1 # Reset Gate
self.WHC = np.random.randn(self.hiddenLayers, self.hiddenLayers) * 0.1 # Candidate Gate
# Biases
self.bC = np.zeros((self.hiddenLayers, 1)) # Candidate Gate
self.bR = np.zeros((self.hiddenLayers, 1)) # Reset Gate
self.bZ = np.zeros((self.hiddenLayers, 1)) # Update Gate
self.bY = np.zeros((self.vocabSize, 1)) # Output
# Output Layer Weights
self.WY = np.random.randn(self.vocabSize, self.hiddenLayers) * 0.1
# Cache for Update
self.dXZM = np.zeros_like(self.WXZ)
self.dXRM = np.zeros_like(self.WXR)
self.dXCM = np.zeros_like(self.WXC)
self.dHZM = np.zeros_like(self.WHZ)
self.dHRM = np.zeros_like(self.WHR)
self.dHCM = np.zeros_like(self.WHC)
self.dbZM = np.zeros_like(self.bZ)
self.dbRM = np.zeros_like(self.bR)
self.dbCM = np.zeros_like(self.bC)
self.dYM = np.zeros_like(self.WY)
self.dXZV = np.zeros_like(self.WXZ)
self.dXRV = np.zeros_like(self.WXR)
self.dXCV = np.zeros_like(self.WXC)
self.dHZV = np.zeros_like(self.WHZ)
self.dHRV = np.zeros_like(self.WHR)
self.dHCV = np.zeros_like(self.WHC)
self.dbZV = np.zeros_like(self.bZ)
self.dbRV = np.zeros_like(self.bR)
self.dbCV = np.zeros_like(self.bC)
self.dYV = np.zeros_like(self.WY)
def forward(self, X, hPrev, temperature=1.0):
# Update Gate
zbar = np.dot(self.WXZ, X) + np.dot(self.WHZ, hPrev) + self.bZ
z = sigmoid(zbar)
# Reset Gate
rbar = np.dot(self.WXR, X) + np.dot(self.WHR, hPrev) + self.bR
r = sigmoid(rbar)
# Candidate
cbar = np.dot(self.WXC, X) + np.dot(self.WHC, np.multiply(r, hPrev)) + self.bC
c = np.tanh(cbar)
# Hidden State
h = np.multiply(c, z) + np.multiply(hPrev, 1 - z)
# h = np.multiply(z, hPrev) + np.multiply((1 - z), c)
# Output
o = softmax(np.dot(self.WY, h) + self.bY, temperature)
return z, zbar, r, rbar, c, cbar, h, o
def step(self):
# Hidden State
self.h = {}
self.h[-1] = np.zeros((self.hiddenLayers, 1))
# Update Gates
z = {}
zbars = {}
# Reset Gates
r = {}
rbars = {}
# Candidates
c = {}
cbars = {}
# Inputs
x = {}
# Outputs
o = {}
# Target Indexes
targets = {}
# Timesteps to Unroll
totalLen = len(self.inputs)
if self.cursor + self.sequenceLength > totalLen:
self.cursor = 0
# Total Loss
loss = 0
for i in xrange(self.sequenceLength):
# Get inputs and outputs
X = self.inputs[self.cursor + i]
y = self.outputs[self.cursor + i]
# Move inputs forward through network
z[i], zbars[i], r[i], rbars[i], c[i], cbars[i], self.h[i], o[i] = self.forward(X, self.h[i - 1])
# Calculate loss
target = np.argmax(y)
loss += -np.log(o[i][target, 0])
x[i] = X
targets[i] = target
# Back Propagation
dXZ = np.zeros_like(self.WXZ)
dXR = np.zeros_like(self.WXR)
dXC = np.zeros_like(self.WXC)
dHZ = np.zeros_like(self.WHZ)
dHR = np.zeros_like(self.WHR)
dHC = np.zeros_like(self.WHC)
dbZ = np.zeros_like(self.bZ)
dbR = np.zeros_like(self.bR)
dbC = np.zeros_like(self.bC)
dbY = np.zeros_like(self.bY)
dY = np.zeros_like(self.WY)
dhnext = np.zeros_like(self.h[0])
dzbarnext = np.zeros_like(zbars[0])
drbarnext = np.zeros_like(rbars[0])
dcbarnext = np.zeros_like(cbars[0])
z[self.sequenceLength] = np.zeros_like(z[0])
r[self.sequenceLength] = np.zeros_like(r[0])
for i in reversed(xrange(self.sequenceLength)):
# Back Propagate Through Y
dSY = np.copy(o[i])
dSY[targets[i]] -= 1
dY += np.dot(dSY, self.h[i].T)
dbY += dSY
# Back Propagate Through H and X
dha = np.multiply(dhnext, 1 - z[i + 1]) # Through Update Gate
dhb = np.dot(self.WHR.T, drbarnext) # Weights into rbar
dhc = np.dot(self.WHZ.T, dzbarnext) # Weights into zbar
dhd = np.multiply(r[i + 1], np.dot(self.WHC.T, dcbarnext)) # Weights into cbar
dhe = np.dot(self.WY.T, dSY) # Weights at output
dh = dha + dhb + dhc + dhd + dhe
dcbar = np.multiply(np.multiply(dh, z[i]) , 1 - np.square(c[i]))
drbar = np.multiply(np.multiply(self.h[i - 1], np.dot(self.WHC.T, dcbar)), np.multiply(r[i] , (1 - r[i])))
dzbar = np.multiply(np.multiply(dh, (c[i] - self.h[i - 1])), np.multiply(z[i], (1 - z[i])))
dXZ += np.dot(dzbar, x[i].T)
dXR += np.dot(drbar, x[i].T)
dXC += np.dot(dcbar, x[i].T)
dHZ += np.dot(dzbar, self.h[i - 1].T)
dHR += np.dot(drbar, self.h[i - 1].T)
dHC += np.dot(dcbar, np.multiply(r[i], self.h[i - 1]).T)
dbZ += dzbar
dbR += drbar
dbC += dcbar
dhnext = dh
drbarnext = drbar
dzbarnext = dzbar
dcbarnext = dcbar
# Parameter Update (Adam)
for param, delta, m, v in zip([self.WXZ, self.WXR, self.WXC, self.WHZ, self.WHR, self.WHC, self.WY, self.bZ, self.bR, self.bC],
[dXZ, dXR, dXC, dHZ, dHR, dHC, dY, dbZ, dbR, dbC],
[self.dXZM, self.dXRM, self.dXCM, self.dHZM, self.dHRM, self.dHCM, self.dYM, self.dbZM, self.dbRM, self.dbCM],
[self.dXZV, self.dXRV, self.dXCV, self.dHZV, self.dHRV, self.dHCV, self.dYV, self.dbZV, self.dbRV, self.dbCV]):
m = 0.9 * m + 0.1 * delta
v = 0.99 * v + 0.01 * (delta ** 2)
param += -self.learningRate * m / (np.sqrt(v) + 1e-8)
# Update cursor
self.cursor += self.sequenceLength
return loss
def sample(self, num=100, temperature=1.0, start=False):
# Output
output = ""
# Sample hidden state
h = {}
h[-1] = np.zeros((self.hiddenLayers, 1))
# Sample Update Gate
z = {}
zbar = {}
# Sample Reset Gate
r = {}
rbar = {}
# Sample Candidate Gate
c = {}
cbar = {}
# Make inputs from seed
if start == False:
lastCursor = self.cursor - self.sequenceLength
seedIdx = lastCursor if lastCursor >= 0 else 0
seed = self.data[seedIdx]
else:
seedIdx = self.gramToIndex[start]
seed = start
X = np.zeros((self.vocabSize, 1))
X[self.gramToIndex[seed], 0] = 1
# Add seed to output
output += seed
# Generate sample
for i in xrange(num - 1):
# Move through network
z[i], zbar[i], r[i], rbar[i], c[i], cbar[i], h[i], prediction = self.forward(X, h[i - 1], temperature)
# Pick ngram using probabilities
idx = np.random.choice(range(self.vocabSize), p=prediction.ravel())
# Add to output
output += self.delimiter + self.indexToGram[idx]
# Update input to feed back in
X = np.zeros((self.vocabSize, 1))
X[idx, 0] = 1
return output
def run(self, iterations=1000, size=100, temperatures=[1.0], sampleFile=False, printSample=5, seed=False):
if sampleFile != False:
sampleFile = open(sampleFile, 'w')
for i in xrange(iterations):
loss = bot.step()
if i % printSample == 0:
for temperature in temperatures:
print '======= Temperature: ' + str(temperature) + ' ======='
sample = bot.sample(size, temperature, seed)
print sample
if(sampleFile != False):
sampleFile.write(sample + '\n\n\n')
print '\n'
print '======= Iteration ' + str(i + 1) + ' ======='
print '======= Samples Seen: ' + str(self.cursor) + ' ======='
print '======= Loss: ' + str(loss) + ' ======='
if sampleFile != False:
sampleFile.close()
def save(self, small=True):
savedObj = {item:value for item, value in self.__dict__.iteritems()}
if small == True:
for param in ["data", "uniqueData", "indexToGram", "gramToIndex", "inputs", "outputs"]:
del savedObj[param]
pickle.dump(savedObj, open("TEXT_RNN_DUMP3", "w+"))
def load(self, dump):
newSelf = pickle.load(dump)
for item, value in newSelf.iteritems():
setattr(self, item, value)
data = open('data.txt').read().lower()
bot = TextRNN()
bot.train(data, 1, '')
bot.run()
bot.save(True)
| 31.807163 | 150 | 0.529188 | import numpy as np
import pickle
def unique(seq):
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))]
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def softmax(x, temperature=1.0):
exp_x = np.exp(x / temperature)
return exp_x / np.sum(exp_x)
class TextRNN(object):
def __init__(self, hiddenLayers=300, sequenceLength=100):
self.hiddenLayers = hiddenLayers
self.learningRate = 2e-3
self.h = {}
self.cursor = 0
self.sequenceLength = sequenceLength
def train(self, text, ngrams=7, delimiter=" "):
self.delimiter = delimiter
grams = text.split(delimiter) if delimiter != "" else list(text)
self.data = [delimiter.join(grams[i:i+ngrams]) for i in range(len(grams))[::ngrams]]
self.uniqueData = unique(self.data)
self.indexToGram = {i:gram for i, gram in enumerate(self.uniqueData)}
self.gramToIndex = {gram:i for i, gram in enumerate(self.uniqueData)}
self.vocabSize = len(self.uniqueData)
inputs = []
outputs = []
inputGrams = [self.gramToIndex[gram] for gram in self.data]
outputGrams = [self.gramToIndex[gram] for gram in self.data[1:]]
for i, inputGram in enumerate(inputGrams[0:-1]):
X = np.zeros((self.vocabSize, 1))
X[inputGram, 0] = 1
y = np.zeros((self.vocabSize, 1))
y[outputGrams[i], 0] = 1
inputs.append(X)
outputs.append(y)
self.inputs = inputs
self.outputs = outputs
self.WXZ = np.random.randn(self.hiddenLayers, self.vocabSize) * 0.1
self.WXR = np.random.randn(self.hiddenLayers, self.vocabSize) * 0.1
self.WXC = np.random.randn(self.hiddenLayers, self.vocabSize) * 0.1
self.WHZ = np.random.randn(self.hiddenLayers, self.hiddenLayers) * 0.1
self.WHR = np.random.randn(self.hiddenLayers, self.hiddenLayers) * 0.1
self.WHC = np.random.randn(self.hiddenLayers, self.hiddenLayers) * 0.1
self.bC = np.zeros((self.hiddenLayers, 1))
self.bR = np.zeros((self.hiddenLayers, 1))
self.bZ = np.zeros((self.hiddenLayers, 1))
self.bY = np.zeros((self.vocabSize, 1))
self.WY = np.random.randn(self.vocabSize, self.hiddenLayers) * 0.1
self.dXZM = np.zeros_like(self.WXZ)
self.dXRM = np.zeros_like(self.WXR)
self.dXCM = np.zeros_like(self.WXC)
self.dHZM = np.zeros_like(self.WHZ)
self.dHRM = np.zeros_like(self.WHR)
self.dHCM = np.zeros_like(self.WHC)
self.dbZM = np.zeros_like(self.bZ)
self.dbRM = np.zeros_like(self.bR)
self.dbCM = np.zeros_like(self.bC)
self.dYM = np.zeros_like(self.WY)
self.dXZV = np.zeros_like(self.WXZ)
self.dXRV = np.zeros_like(self.WXR)
self.dXCV = np.zeros_like(self.WXC)
self.dHZV = np.zeros_like(self.WHZ)
self.dHRV = np.zeros_like(self.WHR)
self.dHCV = np.zeros_like(self.WHC)
self.dbZV = np.zeros_like(self.bZ)
self.dbRV = np.zeros_like(self.bR)
self.dbCV = np.zeros_like(self.bC)
self.dYV = np.zeros_like(self.WY)
def forward(self, X, hPrev, temperature=1.0):
zbar = np.dot(self.WXZ, X) + np.dot(self.WHZ, hPrev) + self.bZ
z = sigmoid(zbar)
rbar = np.dot(self.WXR, X) + np.dot(self.WHR, hPrev) + self.bR
r = sigmoid(rbar)
cbar = np.dot(self.WXC, X) + np.dot(self.WHC, np.multiply(r, hPrev)) + self.bC
c = np.tanh(cbar)
h = np.multiply(c, z) + np.multiply(hPrev, 1 - z)
o = softmax(np.dot(self.WY, h) + self.bY, temperature)
return z, zbar, r, rbar, c, cbar, h, o
def step(self):
self.h = {}
self.h[-1] = np.zeros((self.hiddenLayers, 1))
z = {}
zbars = {}
r = {}
rbars = {}
c = {}
cbars = {}
x = {}
o = {}
targets = {}
totalLen = len(self.inputs)
if self.cursor + self.sequenceLength > totalLen:
self.cursor = 0
loss = 0
for i in xrange(self.sequenceLength):
X = self.inputs[self.cursor + i]
y = self.outputs[self.cursor + i]
z[i], zbars[i], r[i], rbars[i], c[i], cbars[i], self.h[i], o[i] = self.forward(X, self.h[i - 1])
target = np.argmax(y)
loss += -np.log(o[i][target, 0])
x[i] = X
targets[i] = target
dXZ = np.zeros_like(self.WXZ)
dXR = np.zeros_like(self.WXR)
dXC = np.zeros_like(self.WXC)
dHZ = np.zeros_like(self.WHZ)
dHR = np.zeros_like(self.WHR)
dHC = np.zeros_like(self.WHC)
dbZ = np.zeros_like(self.bZ)
dbR = np.zeros_like(self.bR)
dbC = np.zeros_like(self.bC)
dbY = np.zeros_like(self.bY)
dY = np.zeros_like(self.WY)
dhnext = np.zeros_like(self.h[0])
dzbarnext = np.zeros_like(zbars[0])
drbarnext = np.zeros_like(rbars[0])
dcbarnext = np.zeros_like(cbars[0])
z[self.sequenceLength] = np.zeros_like(z[0])
r[self.sequenceLength] = np.zeros_like(r[0])
for i in reversed(xrange(self.sequenceLength)):
dSY = np.copy(o[i])
dSY[targets[i]] -= 1
dY += np.dot(dSY, self.h[i].T)
dbY += dSY
dha = np.multiply(dhnext, 1 - z[i + 1])
dhb = np.dot(self.WHR.T, drbarnext)
dhc = np.dot(self.WHZ.T, dzbarnext)
dhd = np.multiply(r[i + 1], np.dot(self.WHC.T, dcbarnext))
dhe = np.dot(self.WY.T, dSY)
dh = dha + dhb + dhc + dhd + dhe
dcbar = np.multiply(np.multiply(dh, z[i]) , 1 - np.square(c[i]))
drbar = np.multiply(np.multiply(self.h[i - 1], np.dot(self.WHC.T, dcbar)), np.multiply(r[i] , (1 - r[i])))
dzbar = np.multiply(np.multiply(dh, (c[i] - self.h[i - 1])), np.multiply(z[i], (1 - z[i])))
dXZ += np.dot(dzbar, x[i].T)
dXR += np.dot(drbar, x[i].T)
dXC += np.dot(dcbar, x[i].T)
dHZ += np.dot(dzbar, self.h[i - 1].T)
dHR += np.dot(drbar, self.h[i - 1].T)
dHC += np.dot(dcbar, np.multiply(r[i], self.h[i - 1]).T)
dbZ += dzbar
dbR += drbar
dbC += dcbar
dhnext = dh
drbarnext = drbar
dzbarnext = dzbar
dcbarnext = dcbar
for param, delta, m, v in zip([self.WXZ, self.WXR, self.WXC, self.WHZ, self.WHR, self.WHC, self.WY, self.bZ, self.bR, self.bC],
[dXZ, dXR, dXC, dHZ, dHR, dHC, dY, dbZ, dbR, dbC],
[self.dXZM, self.dXRM, self.dXCM, self.dHZM, self.dHRM, self.dHCM, self.dYM, self.dbZM, self.dbRM, self.dbCM],
[self.dXZV, self.dXRV, self.dXCV, self.dHZV, self.dHRV, self.dHCV, self.dYV, self.dbZV, self.dbRV, self.dbCV]):
m = 0.9 * m + 0.1 * delta
v = 0.99 * v + 0.01 * (delta ** 2)
param += -self.learningRate * m / (np.sqrt(v) + 1e-8)
self.cursor += self.sequenceLength
return loss
def sample(self, num=100, temperature=1.0, start=False):
output = ""
h = {}
h[-1] = np.zeros((self.hiddenLayers, 1))
z = {}
zbar = {}
r = {}
rbar = {}
c = {}
cbar = {}
if start == False:
lastCursor = self.cursor - self.sequenceLength
seedIdx = lastCursor if lastCursor >= 0 else 0
seed = self.data[seedIdx]
else:
seedIdx = self.gramToIndex[start]
seed = start
X = np.zeros((self.vocabSize, 1))
X[self.gramToIndex[seed], 0] = 1
output += seed
for i in xrange(num - 1):
z[i], zbar[i], r[i], rbar[i], c[i], cbar[i], h[i], prediction = self.forward(X, h[i - 1], temperature)
idx = np.random.choice(range(self.vocabSize), p=prediction.ravel())
output += self.delimiter + self.indexToGram[idx]
X = np.zeros((self.vocabSize, 1))
X[idx, 0] = 1
return output
def run(self, iterations=1000, size=100, temperatures=[1.0], sampleFile=False, printSample=5, seed=False):
if sampleFile != False:
sampleFile = open(sampleFile, 'w')
for i in xrange(iterations):
loss = bot.step()
if i % printSample == 0:
for temperature in temperatures:
print '======= Temperature: ' + str(temperature) + ' ======='
sample = bot.sample(size, temperature, seed)
print sample
if(sampleFile != False):
sampleFile.write(sample + '\n\n\n')
print '\n'
print '======= Iteration ' + str(i + 1) + ' ======='
print '======= Samples Seen: ' + str(self.cursor) + ' ======='
print '======= Loss: ' + str(loss) + ' ======='
if sampleFile != False:
sampleFile.close()
def save(self, small=True):
savedObj = {item:value for item, value in self.__dict__.iteritems()}
if small == True:
for param in ["data", "uniqueData", "indexToGram", "gramToIndex", "inputs", "outputs"]:
del savedObj[param]
pickle.dump(savedObj, open("TEXT_RNN_DUMP3", "w+"))
def load(self, dump):
newSelf = pickle.load(dump)
for item, value in newSelf.iteritems():
setattr(self, item, value)
data = open('data.txt').read().lower()
bot = TextRNN()
bot.train(data, 1, '')
bot.run()
bot.save(True)
| false | true |
790beba750f1c9ac459c484fc1795a670c0a4bda | 154 | py | Python | tests/urls.py | sflems/django-rest-friendship | c096372e65b1282859ccfb0db2b7d1058631ffa0 | [
"ISC"
] | 1 | 2022-01-26T05:46:21.000Z | 2022-01-26T05:46:21.000Z | tests/urls.py | sflems/django-rest-friendship | c096372e65b1282859ccfb0db2b7d1058631ffa0 | [
"ISC"
] | null | null | null | tests/urls.py | sflems/django-rest-friendship | c096372e65b1282859ccfb0db2b7d1058631ffa0 | [
"ISC"
] | null | null | null | from django.urls import path, include
urlpatterns = [
path('', include(('rest_friendship.urls', 'rest_friendship'), namespace='rest_friendship')),
]
| 25.666667 | 96 | 0.720779 | from django.urls import path, include
urlpatterns = [
path('', include(('rest_friendship.urls', 'rest_friendship'), namespace='rest_friendship')),
]
| true | true |
790beca3a983ecb26cd665db044e84e01f5e1d86 | 4,024 | py | Python | hotelrooms/hotelrooms/settings.py | atombrella/hotel-room-reservation | 5dade1e95bb27e2847d03c03c4d00e707a50438e | [
"MIT"
] | null | null | null | hotelrooms/hotelrooms/settings.py | atombrella/hotel-room-reservation | 5dade1e95bb27e2847d03c03c4d00e707a50438e | [
"MIT"
] | 3 | 2021-06-04T23:18:26.000Z | 2021-09-22T19:07:30.000Z | hotelrooms/hotelrooms/settings.py | atombrella/hotel-room-reservation | 5dade1e95bb27e2847d03c03c4d00e707a50438e | [
"MIT"
] | null | null | null | """
Django settings for hotelrooms project.
Generated by 'django-admin startproject' using Django 3.0.6.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '^b7=e99!2(t7csio=(lospr6ebgbp-2(*n^il4vt8dotctorm*'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.postgres',
'booking',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'hotelrooms.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, "hotelrooms", "templates"),
os.path.join(BASE_DIR, "booking", "templates"),
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'hotelrooms.wsgi.application'
PROJECT_DIR = os.path.dirname(__file__)
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'hotelrooms',
'PORT': 5433,
'HOST': os.getenv("DB_HOST", "localhost"),
'USER': 'django',
'PASSWORD': 'hotelrooms',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
DATE_INPUT_FORMATS = [
'%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06'
'%b %d %Y', '%b %d, %Y', # 'Oct 25 2006', 'Oct 25, 2006'
'%d %b %Y', '%d %b, %Y', # '25 Oct 2006', '25 Oct, 2006'
'%B %d %Y', '%B %d, %Y', # 'October 25 2006', 'October 25, 2006'
'%d %B %Y', '%d %B, %Y', # '25 October 2006', '25 October, 2006'
]
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_ROOT = os.path.join(PROJECT_DIR, 'static/')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
| 27.751724 | 91 | 0.65333 |
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = '^b7=e99!2(t7csio=(lospr6ebgbp-2(*n^il4vt8dotctorm*'
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.postgres',
'booking',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'hotelrooms.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, "hotelrooms", "templates"),
os.path.join(BASE_DIR, "booking", "templates"),
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'hotelrooms.wsgi.application'
PROJECT_DIR = os.path.dirname(__file__)
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'hotelrooms',
'PORT': 5433,
'HOST': os.getenv("DB_HOST", "localhost"),
'USER': 'django',
'PASSWORD': 'hotelrooms',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
DATE_INPUT_FORMATS = [
'%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06'
'%b %d %Y', '%b %d, %Y', # 'Oct 25 2006', 'Oct 25, 2006'
'%d %b %Y', '%d %b, %Y', # '25 Oct 2006', '25 Oct, 2006'
'%B %d %Y', '%B %d, %Y', # 'October 25 2006', 'October 25, 2006'
'%d %B %Y', '%d %B, %Y', # '25 October 2006', '25 October, 2006'
]
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_ROOT = os.path.join(PROJECT_DIR, 'static/')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
| true | true |
790bed39f912fbb80665860e34afb05d378a6e59 | 1,787 | py | Python | Chapter11/webapp/blog/models.py | jayakumardhananjayan/pythonwebtut | a7547473fec5b90a91aea5395131e6eff245b495 | [
"MIT"
] | 135 | 2018-10-31T11:52:35.000Z | 2022-03-23T12:23:04.000Z | Chapter11/webapp/blog/models.py | jayakumardhananjayan/pythonwebtut | a7547473fec5b90a91aea5395131e6eff245b495 | [
"MIT"
] | 6 | 2019-03-21T02:04:43.000Z | 2022-03-22T11:07:25.000Z | Chapter11/webapp/blog/models.py | jayakumardhananjayan/pythonwebtut | a7547473fec5b90a91aea5395131e6eff245b495 | [
"MIT"
] | 109 | 2018-10-30T22:26:23.000Z | 2022-03-24T14:53:13.000Z | import datetime
from .. import db
tags = db.Table(
'post_tags',
db.Column('post_id', db.Integer, db.ForeignKey('post.id')),
db.Column('tag_id', db.Integer, db.ForeignKey('tag.id'))
)
class Post(db.Model):
id = db.Column(db.Integer(), primary_key=True)
title = db.Column(db.String(255), nullable=False)
text = db.Column(db.Text(), nullable=False)
publish_date = db.Column(db.DateTime(), default=datetime.datetime.now)
user_id = db.Column(db.Integer(), db.ForeignKey('user.id'))
youtube_id = db.Column(db.String(255))
comments = db.relationship('Comment', backref='post', lazy='dynamic')
tags = db.relationship('Tag', secondary=tags, backref=db.backref('posts', lazy='dynamic'))
def __init__(self, title=""):
self.title = title
def __repr__(self):
return "<Post '{}'>".format(self.title)
class Comment(db.Model):
id = db.Column(db.Integer(), primary_key=True)
name = db.Column(db.String(255), nullable=False)
text = db.Column(db.Text(), nullable=False)
date = db.Column(db.DateTime(), default=datetime.datetime.now)
post_id = db.Column(db.Integer(), db.ForeignKey('post.id'))
def __repr__(self):
return "<Comment '{}'>".format(self.text[:15])
class Tag(db.Model):
id = db.Column(db.Integer(), primary_key=True)
title = db.Column(db.String(255), nullable=False, unique=True)
def __init__(self, title=""):
self.title = title
def __repr__(self):
return "<Tag '{}'>".format(self.title)
class Reminder(db.Model):
id = db.Column(db.Integer(), primary_key=True)
date = db.Column(db.DateTime())
email = db.Column(db.String())
text = db.Column(db.Text())
def __repr__(self):
return "<Reminder '{}'>".format(self.text[:20])
| 30.810345 | 94 | 0.641858 | import datetime
from .. import db
tags = db.Table(
'post_tags',
db.Column('post_id', db.Integer, db.ForeignKey('post.id')),
db.Column('tag_id', db.Integer, db.ForeignKey('tag.id'))
)
class Post(db.Model):
id = db.Column(db.Integer(), primary_key=True)
title = db.Column(db.String(255), nullable=False)
text = db.Column(db.Text(), nullable=False)
publish_date = db.Column(db.DateTime(), default=datetime.datetime.now)
user_id = db.Column(db.Integer(), db.ForeignKey('user.id'))
youtube_id = db.Column(db.String(255))
comments = db.relationship('Comment', backref='post', lazy='dynamic')
tags = db.relationship('Tag', secondary=tags, backref=db.backref('posts', lazy='dynamic'))
def __init__(self, title=""):
self.title = title
def __repr__(self):
return "<Post '{}'>".format(self.title)
class Comment(db.Model):
id = db.Column(db.Integer(), primary_key=True)
name = db.Column(db.String(255), nullable=False)
text = db.Column(db.Text(), nullable=False)
date = db.Column(db.DateTime(), default=datetime.datetime.now)
post_id = db.Column(db.Integer(), db.ForeignKey('post.id'))
def __repr__(self):
return "<Comment '{}'>".format(self.text[:15])
class Tag(db.Model):
id = db.Column(db.Integer(), primary_key=True)
title = db.Column(db.String(255), nullable=False, unique=True)
def __init__(self, title=""):
self.title = title
def __repr__(self):
return "<Tag '{}'>".format(self.title)
class Reminder(db.Model):
id = db.Column(db.Integer(), primary_key=True)
date = db.Column(db.DateTime())
email = db.Column(db.String())
text = db.Column(db.Text())
def __repr__(self):
return "<Reminder '{}'>".format(self.text[:20])
| true | true |
790bed5fe2f8f36d830032650767d577aea42711 | 6,303 | py | Python | pcapng/flags.py | Boolean263/python-pcapng | 447c375456fc107376fd7f884f791d48a89f1f16 | [
"Apache-2.0"
] | null | null | null | pcapng/flags.py | Boolean263/python-pcapng | 447c375456fc107376fd7f884f791d48a89f1f16 | [
"Apache-2.0"
] | null | null | null | pcapng/flags.py | Boolean263/python-pcapng | 447c375456fc107376fd7f884f791d48a89f1f16 | [
"Apache-2.0"
] | null | null | null | """
Module to wrap an integer in bitwise flag/field accessors.
"""
from collections import OrderedDict
from pcapng.ngsix import namedtuple, Iterable
class FlagBase(object):
"""\
Base class for flag types to be used in a Flags object.
Handles the bitwise math so subclasses don't have to worry about it.
"""
__slots__ = [
'owner',
'offset',
'size',
'extra',
'mask',
]
def __init__(self, owner, offset, size, extra=None):
if size < 1:
raise TypeError('Flag must be at least 1 bit wide')
if size > owner._nbits:
raise TypeError('Flag must fit into owner size')
self.owner = owner
self.offset = offset
self.size = size
self.extra = extra
self.mask = ((1 << self.size)-1) << self.offset
def get_bits(self):
return (self.owner._value & self.mask) >> self.offset
def set_bits(self, val):
val &= (1 << self.size) - 1
self.owner._value &= ~self.mask
self.owner._value |= (val << self.offset)
class FlagBool(FlagBase):
"""Object representing a single boolean flag"""
def __init__(self, owner, offset, size, extra=None):
if size != 1:
raise TypeError('{cls} can only be 1 bit in size'.format(cls=self.__class__.__name__))
super(FlagBool, self).__init__(owner, offset, size)
def get(self):
return bool(self.get_bits())
def set(self, val):
self.set_bits(int(bool(val)))
class FlagUInt(FlagBase):
"""\
Object representing an unsigned integer of the given size stored in
a larger bitfield
"""
def get(self):
return self.get_bits()
def set(self, val):
self.set_bits(val)
class FlagEnum(FlagBase):
"""\
Object representing a range of values stored in part of a larger
bitfield
"""
def __init__(self, owner, offset, size, extra=None):
if not isinstance(extra, Iterable):
raise TypeError('{cls} needs an iterable of values'.format(cls=self.__class__.__name__))
extra = list(extra)
if len(extra) > 2**size:
raise TypeError('{cls} iterable has too many values (got {got}, {size} bits only address {max})'.format(cls=self.__class__.__name__, got=len(extra), size=size, max=2**size))
super(FlagEnum, self).__init__(owner, offset, size, extra)
def get(self):
val = self.get_bits()
try:
return self.extra[val]
except IndexError:
return '[invalid value]'
def set(self, val):
if val in self.extra:
self.set_bits(self.extra.index(val))
elif isinstance(val, int):
self.set_bits(val)
else:
raise TypeError('Invalid value {val} for {cls}'.format(val=val, cls=self.__class__.__name__))
# Class representing a single flag schema for FlagWord.
# 'nbits' defaults to 1, and 'extra' defaults to None.
FlagField = namedtuple('FlagField', ('name', 'ftype', 'nbits', 'extra'),
defaults=(1, None))
class FlagWord(object):
"""\
Class to wrap an integer in bitwise flag/field accessors.
"""
__slots__ = [
'_nbits',
'_value',
'_schema',
]
def __init__(self, schema, nbits=32, initial=0):
"""
:param schema:
A list of FlagField objects representing the values to be packed
into this object, in order from LSB to MSB of the underlying int
:param nbits:
An integer representing the total number of bits used for flags
:param initial:
The initial integer value of the flags field
"""
self._nbits = nbits
self._value = initial
self._schema = OrderedDict()
tot_bits = sum([item.nbits for item in schema])
if tot_bits > nbits:
raise TypeError("Too many fields for {nbits}-bit field (schema defines {tot} bits)".format(nbits=nbits, tot=tot_bits))
bitn = 0
for item in schema:
if not isinstance(item, FlagField):
raise TypeError('Schema must be composed of FlagField objects')
if not issubclass(item.ftype, FlagBase):
raise TypeError('Expected FlagBase, got {}'.format(item.ftype))
self._schema[item.name] = item.ftype(self, bitn, item.nbits, item.extra)
bitn += item.nbits
def __int__(self):
return self._value
def __repr__(self):
rv = '<{0} (value={1})'.format(self.__class__.__name__, self._value)
for k, v in self._schema.items():
rv += ' {0}={1}'.format(k, v.get())
return rv+'>'
def __getattr__(self, name):
try:
v = self._schema[name]
except KeyError:
raise AttributeError(name)
return v.get()
def __setattr__(self, name, val):
try:
return object.__setattr__(self, name, val)
except AttributeError:
pass
try:
v = self._schema[name]
except KeyError:
raise AttributeError(name)
return v.set(val)
if __name__ == '__main__':
f = FlagWord([
FlagField('inout', FlagEnum, 2, ('NA', 'inbound', 'outbound')),
FlagField('casttype', FlagEnum, 3, ('NA', 'unicast', 'multicast', 'broadcast', 'promiscuous')),
FlagField('fcslen', FlagUInt, 4),
FlagField('reserved', FlagUInt, 7),
FlagField('err_16', FlagBool),
FlagField('err_17', FlagBool),
FlagField('err_18', FlagBool),
FlagField('err_19', FlagBool),
FlagField('err_20', FlagBool),
FlagField('err_21', FlagBool),
FlagField('err_22', FlagBool),
FlagField('err_23', FlagBool),
FlagField('err_crc', FlagBool),
FlagField('err_long', FlagBool),
FlagField('err_short', FlagBool),
FlagField('err_frame_gap', FlagBool),
FlagField('err_frame_align', FlagBool),
FlagField('err_frame_delim', FlagBool),
FlagField('err_preamble', FlagBool),
FlagField('err_symbol', FlagBool),
])
f.fcslen = 12
print(f)
print(int(f))
| 30.746341 | 185 | 0.5802 |
from collections import OrderedDict
from pcapng.ngsix import namedtuple, Iterable
class FlagBase(object):
__slots__ = [
'owner',
'offset',
'size',
'extra',
'mask',
]
def __init__(self, owner, offset, size, extra=None):
if size < 1:
raise TypeError('Flag must be at least 1 bit wide')
if size > owner._nbits:
raise TypeError('Flag must fit into owner size')
self.owner = owner
self.offset = offset
self.size = size
self.extra = extra
self.mask = ((1 << self.size)-1) << self.offset
def get_bits(self):
return (self.owner._value & self.mask) >> self.offset
def set_bits(self, val):
val &= (1 << self.size) - 1
self.owner._value &= ~self.mask
self.owner._value |= (val << self.offset)
class FlagBool(FlagBase):
def __init__(self, owner, offset, size, extra=None):
if size != 1:
raise TypeError('{cls} can only be 1 bit in size'.format(cls=self.__class__.__name__))
super(FlagBool, self).__init__(owner, offset, size)
def get(self):
return bool(self.get_bits())
def set(self, val):
self.set_bits(int(bool(val)))
class FlagUInt(FlagBase):
def get(self):
return self.get_bits()
def set(self, val):
self.set_bits(val)
class FlagEnum(FlagBase):
def __init__(self, owner, offset, size, extra=None):
if not isinstance(extra, Iterable):
raise TypeError('{cls} needs an iterable of values'.format(cls=self.__class__.__name__))
extra = list(extra)
if len(extra) > 2**size:
raise TypeError('{cls} iterable has too many values (got {got}, {size} bits only address {max})'.format(cls=self.__class__.__name__, got=len(extra), size=size, max=2**size))
super(FlagEnum, self).__init__(owner, offset, size, extra)
def get(self):
val = self.get_bits()
try:
return self.extra[val]
except IndexError:
return '[invalid value]'
def set(self, val):
if val in self.extra:
self.set_bits(self.extra.index(val))
elif isinstance(val, int):
self.set_bits(val)
else:
raise TypeError('Invalid value {val} for {cls}'.format(val=val, cls=self.__class__.__name__))
FlagField = namedtuple('FlagField', ('name', 'ftype', 'nbits', 'extra'),
defaults=(1, None))
class FlagWord(object):
__slots__ = [
'_nbits',
'_value',
'_schema',
]
def __init__(self, schema, nbits=32, initial=0):
self._nbits = nbits
self._value = initial
self._schema = OrderedDict()
tot_bits = sum([item.nbits for item in schema])
if tot_bits > nbits:
raise TypeError("Too many fields for {nbits}-bit field (schema defines {tot} bits)".format(nbits=nbits, tot=tot_bits))
bitn = 0
for item in schema:
if not isinstance(item, FlagField):
raise TypeError('Schema must be composed of FlagField objects')
if not issubclass(item.ftype, FlagBase):
raise TypeError('Expected FlagBase, got {}'.format(item.ftype))
self._schema[item.name] = item.ftype(self, bitn, item.nbits, item.extra)
bitn += item.nbits
def __int__(self):
return self._value
def __repr__(self):
rv = '<{0} (value={1})'.format(self.__class__.__name__, self._value)
for k, v in self._schema.items():
rv += ' {0}={1}'.format(k, v.get())
return rv+'>'
def __getattr__(self, name):
try:
v = self._schema[name]
except KeyError:
raise AttributeError(name)
return v.get()
def __setattr__(self, name, val):
try:
return object.__setattr__(self, name, val)
except AttributeError:
pass
try:
v = self._schema[name]
except KeyError:
raise AttributeError(name)
return v.set(val)
if __name__ == '__main__':
f = FlagWord([
FlagField('inout', FlagEnum, 2, ('NA', 'inbound', 'outbound')),
FlagField('casttype', FlagEnum, 3, ('NA', 'unicast', 'multicast', 'broadcast', 'promiscuous')),
FlagField('fcslen', FlagUInt, 4),
FlagField('reserved', FlagUInt, 7),
FlagField('err_16', FlagBool),
FlagField('err_17', FlagBool),
FlagField('err_18', FlagBool),
FlagField('err_19', FlagBool),
FlagField('err_20', FlagBool),
FlagField('err_21', FlagBool),
FlagField('err_22', FlagBool),
FlagField('err_23', FlagBool),
FlagField('err_crc', FlagBool),
FlagField('err_long', FlagBool),
FlagField('err_short', FlagBool),
FlagField('err_frame_gap', FlagBool),
FlagField('err_frame_align', FlagBool),
FlagField('err_frame_delim', FlagBool),
FlagField('err_preamble', FlagBool),
FlagField('err_symbol', FlagBool),
])
f.fcslen = 12
print(f)
print(int(f))
| true | true |
790bed8d7cc85d9dfc7095934007a4938b817029 | 16,031 | py | Python | tfx/orchestration/kubeflow/kubeflow_dag_runner.py | TimoKerr/tfx | 10d13d57eeac21514fed73118cb43464dada67f1 | [
"Apache-2.0"
] | null | null | null | tfx/orchestration/kubeflow/kubeflow_dag_runner.py | TimoKerr/tfx | 10d13d57eeac21514fed73118cb43464dada67f1 | [
"Apache-2.0"
] | null | null | null | tfx/orchestration/kubeflow/kubeflow_dag_runner.py | TimoKerr/tfx | 10d13d57eeac21514fed73118cb43464dada67f1 | [
"Apache-2.0"
] | null | null | null | # Lint as: python2, python3
# Copyright 2019 Google LLC. 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.
"""TFX runner for Kubeflow."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import re
from typing import Callable, Dict, List, Optional, Text, Type, cast
from absl import logging
from kfp import compiler
from kfp import dsl
from kfp import gcp
from kubernetes import client as k8s_client
from tfx import version
from tfx.dsl.compiler import compiler as tfx_compiler
from tfx.dsl.components.base import base_component as tfx_base_component
from tfx.orchestration import data_types
from tfx.orchestration import pipeline as tfx_pipeline
from tfx.orchestration import tfx_runner
from tfx.orchestration.config import pipeline_config
from tfx.orchestration.kubeflow import base_component
from tfx.orchestration.kubeflow import utils
from tfx.orchestration.kubeflow.proto import kubeflow_pb2
from tfx.orchestration.launcher import base_component_launcher
from tfx.orchestration.launcher import in_process_component_launcher
from tfx.orchestration.launcher import kubernetes_component_launcher
from tfx.proto.orchestration import pipeline_pb2
from tfx.utils import json_utils
from tfx.utils import telemetry_utils
# OpFunc represents the type of a function that takes as input a
# dsl.ContainerOp and returns the same object. Common operations such as adding
# k8s secrets, mounting volumes, specifying the use of TPUs and so on can be
# specified as an OpFunc.
# See example usage here:
# https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/gcp.py
OpFunc = Callable[[dsl.ContainerOp], dsl.ContainerOp]
# Default secret name for GCP credentials. This secret is installed as part of
# a typical Kubeflow installation when the component is GKE.
_KUBEFLOW_GCP_SECRET_NAME = 'user-gcp-sa'
# Default TFX container image to use in KubeflowDagRunner.
DEFAULT_KUBEFLOW_TFX_IMAGE = 'tensorflow/tfx:%s' % (version.__version__,)
def _mount_config_map_op(config_map_name: Text) -> OpFunc:
"""Mounts all key-value pairs found in the named Kubernetes ConfigMap.
All key-value pairs in the ConfigMap are mounted as environment variables.
Args:
config_map_name: The name of the ConfigMap resource.
Returns:
An OpFunc for mounting the ConfigMap.
"""
def mount_config_map(container_op: dsl.ContainerOp):
config_map_ref = k8s_client.V1ConfigMapEnvSource(
name=config_map_name, optional=True)
container_op.container.add_env_from(
k8s_client.V1EnvFromSource(config_map_ref=config_map_ref))
return mount_config_map
def _mount_secret_op(secret_name: Text) -> OpFunc:
"""Mounts all key-value pairs found in the named Kubernetes Secret.
All key-value pairs in the Secret are mounted as environment variables.
Args:
secret_name: The name of the Secret resource.
Returns:
An OpFunc for mounting the Secret.
"""
def mount_secret(container_op: dsl.ContainerOp):
secret_ref = k8s_client.V1ConfigMapEnvSource(
name=secret_name, optional=True)
container_op.container.add_env_from(
k8s_client.V1EnvFromSource(secret_ref=secret_ref))
return mount_secret
def get_default_pipeline_operator_funcs(
use_gcp_sa: bool = False) -> List[OpFunc]:
"""Returns a default list of pipeline operator functions.
Args:
use_gcp_sa: If true, mount a GCP service account secret to each pod, with
the name _KUBEFLOW_GCP_SECRET_NAME.
Returns:
A list of functions with type OpFunc.
"""
# Enables authentication for GCP services if needed.
gcp_secret_op = gcp.use_gcp_secret(_KUBEFLOW_GCP_SECRET_NAME)
# Mounts configmap containing Metadata gRPC server configuration.
mount_config_map_op = _mount_config_map_op('metadata-grpc-configmap')
if use_gcp_sa:
return [gcp_secret_op, mount_config_map_op]
else:
return [mount_config_map_op]
def get_default_kubeflow_metadata_config(
) -> kubeflow_pb2.KubeflowMetadataConfig:
"""Returns the default metadata connection config for Kubeflow.
Returns:
A config proto that will be serialized as JSON and passed to the running
container so the TFX component driver is able to communicate with MLMD in
a Kubeflow cluster.
"""
# The default metadata configuration for a Kubeflow Pipelines cluster is
# codified as a Kubernetes ConfigMap
# https://github.com/kubeflow/pipelines/blob/master/manifests/kustomize/base/metadata/metadata-grpc-configmap.yaml
config = kubeflow_pb2.KubeflowMetadataConfig()
# The environment variable to use to obtain the Metadata gRPC service host in
# the cluster that is backing Kubeflow Metadata. Note that the key in the
# config map and therefore environment variable used, are lower-cased.
config.grpc_config.grpc_service_host.environment_variable = 'METADATA_GRPC_SERVICE_HOST'
# The environment variable to use to obtain the Metadata grpc service port in
# the cluster that is backing Kubeflow Metadata.
config.grpc_config.grpc_service_port.environment_variable = 'METADATA_GRPC_SERVICE_PORT'
return config
def get_default_pod_labels() -> Dict[Text, Text]:
"""Returns the default pod label dict for Kubeflow."""
# KFP default transformers add pod env:
# https://github.com/kubeflow/pipelines/blob/0.1.32/sdk/python/kfp/compiler/_default_transformers.py
result = {
'add-pod-env': 'true',
telemetry_utils.LABEL_KFP_SDK_ENV: 'tfx'
}
return result
def get_default_output_filename(pipeline_name: str) -> str:
return pipeline_name + '.tar.gz'
class KubeflowDagRunnerConfig(pipeline_config.PipelineConfig):
"""Runtime configuration parameters specific to execution on Kubeflow."""
def __init__(
self,
pipeline_operator_funcs: Optional[List[OpFunc]] = None,
tfx_image: Optional[Text] = None,
kubeflow_metadata_config: Optional[
kubeflow_pb2.KubeflowMetadataConfig] = None,
# TODO(b/143883035): Figure out the best practice to put the
# SUPPORTED_LAUNCHER_CLASSES
supported_launcher_classes: List[Type[
base_component_launcher.BaseComponentLauncher]] = None,
**kwargs):
"""Creates a KubeflowDagRunnerConfig object.
The user can use pipeline_operator_funcs to apply modifications to
ContainerOps used in the pipeline. For example, to ensure the pipeline
steps mount a GCP secret, and a Persistent Volume, one can create config
object like so:
from kfp import gcp, onprem
mount_secret_op = gcp.use_secret('my-secret-name)
mount_volume_op = onprem.mount_pvc(
"my-persistent-volume-claim",
"my-volume-name",
"/mnt/volume-mount-path")
config = KubeflowDagRunnerConfig(
pipeline_operator_funcs=[mount_secret_op, mount_volume_op]
)
Args:
pipeline_operator_funcs: A list of ContainerOp modifying functions that
will be applied to every container step in the pipeline.
tfx_image: The TFX container image to use in the pipeline.
kubeflow_metadata_config: Runtime configuration to use to connect to
Kubeflow metadata.
supported_launcher_classes: A list of component launcher classes that are
supported by the current pipeline. List sequence determines the order in
which launchers are chosen for each component being run.
**kwargs: keyword args for PipelineConfig.
"""
supported_launcher_classes = supported_launcher_classes or [
in_process_component_launcher.InProcessComponentLauncher,
kubernetes_component_launcher.KubernetesComponentLauncher,
]
super(KubeflowDagRunnerConfig, self).__init__(
supported_launcher_classes=supported_launcher_classes, **kwargs)
self.pipeline_operator_funcs = (
pipeline_operator_funcs or get_default_pipeline_operator_funcs())
self.tfx_image = tfx_image or DEFAULT_KUBEFLOW_TFX_IMAGE
self.kubeflow_metadata_config = (
kubeflow_metadata_config or get_default_kubeflow_metadata_config())
class KubeflowDagRunner(tfx_runner.TfxRunner):
"""Kubeflow Pipelines runner.
Constructs a pipeline definition YAML file based on the TFX logical pipeline.
"""
def __init__(
self,
output_dir: Optional[Text] = None,
output_filename: Optional[Text] = None,
config: Optional[KubeflowDagRunnerConfig] = None,
pod_labels_to_attach: Optional[Dict[Text, Text]] = None
):
"""Initializes KubeflowDagRunner for compiling a Kubeflow Pipeline.
Args:
output_dir: An optional output directory into which to output the pipeline
definition files. Defaults to the current working directory.
output_filename: An optional output file name for the pipeline definition
file. Defaults to pipeline_name.tar.gz when compiling a TFX pipeline.
Currently supports .tar.gz, .tgz, .zip, .yaml, .yml formats. See
https://github.com/kubeflow/pipelines/blob/181de66cf9fa87bcd0fe9291926790c400140783/sdk/python/kfp/compiler/compiler.py#L851
for format restriction.
config: An optional KubeflowDagRunnerConfig object to specify runtime
configuration when running the pipeline under Kubeflow.
pod_labels_to_attach: Optional set of pod labels to attach to GKE pod
spinned up for this pipeline. Default to the 3 labels:
1. add-pod-env: true,
2. pipeline SDK type,
3. pipeline unique ID,
where 2 and 3 are instrumentation of usage tracking.
"""
if config and not isinstance(config, KubeflowDagRunnerConfig):
raise TypeError('config must be type of KubeflowDagRunnerConfig.')
super(KubeflowDagRunner, self).__init__(config or KubeflowDagRunnerConfig())
self._config = cast(KubeflowDagRunnerConfig, self._config)
self._output_dir = output_dir or os.getcwd()
self._output_filename = output_filename
self._compiler = compiler.Compiler()
self._tfx_compiler = tfx_compiler.Compiler()
self._params = [] # List of dsl.PipelineParam used in this pipeline.
self._deduped_parameter_names = set() # Set of unique param names used.
if pod_labels_to_attach is None:
self._pod_labels_to_attach = get_default_pod_labels()
else:
self._pod_labels_to_attach = pod_labels_to_attach
def _parse_parameter_from_component(
self, component: base_component.BaseComponent) -> None:
"""Extract embedded RuntimeParameter placeholders from a component.
Extract embedded RuntimeParameter placeholders from a component, then append
the corresponding dsl.PipelineParam to KubeflowDagRunner.
Args:
component: a TFX component.
"""
serialized_component = json_utils.dumps(component)
placeholders = re.findall(data_types.RUNTIME_PARAMETER_PATTERN,
serialized_component)
for placeholder in placeholders:
placeholder = placeholder.replace('\\', '') # Clean escapes.
placeholder = utils.fix_brackets(placeholder) # Fix brackets if needed.
parameter = json_utils.loads(placeholder)
# Escape pipeline root because it will be added later.
if parameter.name == tfx_pipeline.ROOT_PARAMETER.name:
continue
if parameter.name not in self._deduped_parameter_names:
self._deduped_parameter_names.add(parameter.name)
# TODO(b/178436919): Create a test to cover default value rendering
# and move the external code reference over there.
# The default needs to be serialized then passed to dsl.PipelineParam.
# See
# https://github.com/kubeflow/pipelines/blob/f65391309650fdc967586529e79af178241b4c2c/sdk/python/kfp/dsl/_pipeline_param.py#L154
dsl_parameter = dsl.PipelineParam(
name=parameter.name, value=str(parameter.default))
self._params.append(dsl_parameter)
def _parse_parameter_from_pipeline(self,
pipeline: tfx_pipeline.Pipeline) -> None:
"""Extract all the RuntimeParameter placeholders from the pipeline."""
for component in pipeline.components:
self._parse_parameter_from_component(component)
def _construct_pipeline_graph(self, pipeline: tfx_pipeline.Pipeline,
pipeline_root: dsl.PipelineParam):
"""Constructs a Kubeflow Pipeline graph.
Args:
pipeline: The logical TFX pipeline to base the construction on.
pipeline_root: dsl.PipelineParam representing the pipeline root.
"""
component_to_kfp_op = {}
tfx_ir = self._generate_tfx_ir(pipeline)
# Assumption: There is a partial ordering of components in the list, i.e.,
# if component A depends on component B and C, then A appears after B and C
# in the list.
for component in pipeline.components:
# Keep track of the set of upstream dsl.ContainerOps for this component.
depends_on = set()
for upstream_component in component.upstream_nodes:
depends_on.add(component_to_kfp_op[upstream_component])
kfp_component = base_component.BaseComponent(
component=component,
depends_on=depends_on,
pipeline=pipeline,
pipeline_root=pipeline_root,
tfx_image=self._config.tfx_image,
kubeflow_metadata_config=self._config.kubeflow_metadata_config,
pod_labels_to_attach=self._pod_labels_to_attach,
tfx_ir=tfx_ir)
for operator in self._config.pipeline_operator_funcs:
kfp_component.container_op.apply(operator)
component_to_kfp_op[component] = kfp_component.container_op
def _generate_tfx_ir(
self, pipeline: tfx_pipeline.Pipeline) -> Optional[pipeline_pb2.Pipeline]:
result = self._tfx_compiler.compile(pipeline)
logging.info('Generated pipeline:\n %s', result)
return result
def run(self, pipeline: tfx_pipeline.Pipeline):
"""Compiles and outputs a Kubeflow Pipeline YAML definition file.
Args:
pipeline: The logical TFX pipeline to use when building the Kubeflow
pipeline.
"""
for component in pipeline.components:
# TODO(b/187122662): Pass through pip dependencies as a first-class
# component flag.
if isinstance(component, tfx_base_component.BaseComponent):
component._resolve_pip_dependencies( # pylint: disable=protected-access
pipeline.pipeline_info.pipeline_root)
# KFP DSL representation of pipeline root parameter.
dsl_pipeline_root = dsl.PipelineParam(
name=tfx_pipeline.ROOT_PARAMETER.name,
value=pipeline.pipeline_info.pipeline_root)
self._params.append(dsl_pipeline_root)
def _construct_pipeline():
"""Constructs a Kubeflow pipeline.
Creates Kubeflow ContainerOps for each TFX component encountered in the
logical pipeline definition.
"""
self._construct_pipeline_graph(pipeline, dsl_pipeline_root)
# Need to run this first to get self._params populated. Then KFP compiler
# can correctly match default value with PipelineParam.
self._parse_parameter_from_pipeline(pipeline)
file_name = self._output_filename or get_default_output_filename(
pipeline.pipeline_info.pipeline_name)
# Create workflow spec and write out to package.
self._compiler._create_and_write_workflow( # pylint: disable=protected-access
pipeline_func=_construct_pipeline,
pipeline_name=pipeline.pipeline_info.pipeline_name,
params_list=self._params,
package_path=os.path.join(self._output_dir, file_name))
| 40.895408 | 136 | 0.748487 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import re
from typing import Callable, Dict, List, Optional, Text, Type, cast
from absl import logging
from kfp import compiler
from kfp import dsl
from kfp import gcp
from kubernetes import client as k8s_client
from tfx import version
from tfx.dsl.compiler import compiler as tfx_compiler
from tfx.dsl.components.base import base_component as tfx_base_component
from tfx.orchestration import data_types
from tfx.orchestration import pipeline as tfx_pipeline
from tfx.orchestration import tfx_runner
from tfx.orchestration.config import pipeline_config
from tfx.orchestration.kubeflow import base_component
from tfx.orchestration.kubeflow import utils
from tfx.orchestration.kubeflow.proto import kubeflow_pb2
from tfx.orchestration.launcher import base_component_launcher
from tfx.orchestration.launcher import in_process_component_launcher
from tfx.orchestration.launcher import kubernetes_component_launcher
from tfx.proto.orchestration import pipeline_pb2
from tfx.utils import json_utils
from tfx.utils import telemetry_utils
OpFunc = Callable[[dsl.ContainerOp], dsl.ContainerOp]
_KUBEFLOW_GCP_SECRET_NAME = 'user-gcp-sa'
DEFAULT_KUBEFLOW_TFX_IMAGE = 'tensorflow/tfx:%s' % (version.__version__,)
def _mount_config_map_op(config_map_name: Text) -> OpFunc:
def mount_config_map(container_op: dsl.ContainerOp):
config_map_ref = k8s_client.V1ConfigMapEnvSource(
name=config_map_name, optional=True)
container_op.container.add_env_from(
k8s_client.V1EnvFromSource(config_map_ref=config_map_ref))
return mount_config_map
def _mount_secret_op(secret_name: Text) -> OpFunc:
def mount_secret(container_op: dsl.ContainerOp):
secret_ref = k8s_client.V1ConfigMapEnvSource(
name=secret_name, optional=True)
container_op.container.add_env_from(
k8s_client.V1EnvFromSource(secret_ref=secret_ref))
return mount_secret
def get_default_pipeline_operator_funcs(
use_gcp_sa: bool = False) -> List[OpFunc]:
gcp_secret_op = gcp.use_gcp_secret(_KUBEFLOW_GCP_SECRET_NAME)
mount_config_map_op = _mount_config_map_op('metadata-grpc-configmap')
if use_gcp_sa:
return [gcp_secret_op, mount_config_map_op]
else:
return [mount_config_map_op]
def get_default_kubeflow_metadata_config(
) -> kubeflow_pb2.KubeflowMetadataConfig:
config = kubeflow_pb2.KubeflowMetadataConfig()
config.grpc_config.grpc_service_host.environment_variable = 'METADATA_GRPC_SERVICE_HOST'
config.grpc_config.grpc_service_port.environment_variable = 'METADATA_GRPC_SERVICE_PORT'
return config
def get_default_pod_labels() -> Dict[Text, Text]:
result = {
'add-pod-env': 'true',
telemetry_utils.LABEL_KFP_SDK_ENV: 'tfx'
}
return result
def get_default_output_filename(pipeline_name: str) -> str:
return pipeline_name + '.tar.gz'
class KubeflowDagRunnerConfig(pipeline_config.PipelineConfig):
def __init__(
self,
pipeline_operator_funcs: Optional[List[OpFunc]] = None,
tfx_image: Optional[Text] = None,
kubeflow_metadata_config: Optional[
kubeflow_pb2.KubeflowMetadataConfig] = None,
supported_launcher_classes: List[Type[
base_component_launcher.BaseComponentLauncher]] = None,
**kwargs):
supported_launcher_classes = supported_launcher_classes or [
in_process_component_launcher.InProcessComponentLauncher,
kubernetes_component_launcher.KubernetesComponentLauncher,
]
super(KubeflowDagRunnerConfig, self).__init__(
supported_launcher_classes=supported_launcher_classes, **kwargs)
self.pipeline_operator_funcs = (
pipeline_operator_funcs or get_default_pipeline_operator_funcs())
self.tfx_image = tfx_image or DEFAULT_KUBEFLOW_TFX_IMAGE
self.kubeflow_metadata_config = (
kubeflow_metadata_config or get_default_kubeflow_metadata_config())
class KubeflowDagRunner(tfx_runner.TfxRunner):
def __init__(
self,
output_dir: Optional[Text] = None,
output_filename: Optional[Text] = None,
config: Optional[KubeflowDagRunnerConfig] = None,
pod_labels_to_attach: Optional[Dict[Text, Text]] = None
):
if config and not isinstance(config, KubeflowDagRunnerConfig):
raise TypeError('config must be type of KubeflowDagRunnerConfig.')
super(KubeflowDagRunner, self).__init__(config or KubeflowDagRunnerConfig())
self._config = cast(KubeflowDagRunnerConfig, self._config)
self._output_dir = output_dir or os.getcwd()
self._output_filename = output_filename
self._compiler = compiler.Compiler()
self._tfx_compiler = tfx_compiler.Compiler()
self._params = []
self._deduped_parameter_names = set()
if pod_labels_to_attach is None:
self._pod_labels_to_attach = get_default_pod_labels()
else:
self._pod_labels_to_attach = pod_labels_to_attach
def _parse_parameter_from_component(
self, component: base_component.BaseComponent) -> None:
serialized_component = json_utils.dumps(component)
placeholders = re.findall(data_types.RUNTIME_PARAMETER_PATTERN,
serialized_component)
for placeholder in placeholders:
placeholder = placeholder.replace('\\', '')
placeholder = utils.fix_brackets(placeholder)
parameter = json_utils.loads(placeholder)
if parameter.name == tfx_pipeline.ROOT_PARAMETER.name:
continue
if parameter.name not in self._deduped_parameter_names:
self._deduped_parameter_names.add(parameter.name)
dsl_parameter = dsl.PipelineParam(
name=parameter.name, value=str(parameter.default))
self._params.append(dsl_parameter)
def _parse_parameter_from_pipeline(self,
pipeline: tfx_pipeline.Pipeline) -> None:
for component in pipeline.components:
self._parse_parameter_from_component(component)
def _construct_pipeline_graph(self, pipeline: tfx_pipeline.Pipeline,
pipeline_root: dsl.PipelineParam):
component_to_kfp_op = {}
tfx_ir = self._generate_tfx_ir(pipeline)
for component in pipeline.components:
depends_on = set()
for upstream_component in component.upstream_nodes:
depends_on.add(component_to_kfp_op[upstream_component])
kfp_component = base_component.BaseComponent(
component=component,
depends_on=depends_on,
pipeline=pipeline,
pipeline_root=pipeline_root,
tfx_image=self._config.tfx_image,
kubeflow_metadata_config=self._config.kubeflow_metadata_config,
pod_labels_to_attach=self._pod_labels_to_attach,
tfx_ir=tfx_ir)
for operator in self._config.pipeline_operator_funcs:
kfp_component.container_op.apply(operator)
component_to_kfp_op[component] = kfp_component.container_op
def _generate_tfx_ir(
self, pipeline: tfx_pipeline.Pipeline) -> Optional[pipeline_pb2.Pipeline]:
result = self._tfx_compiler.compile(pipeline)
logging.info('Generated pipeline:\n %s', result)
return result
def run(self, pipeline: tfx_pipeline.Pipeline):
for component in pipeline.components:
if isinstance(component, tfx_base_component.BaseComponent):
component._resolve_pip_dependencies(
pipeline.pipeline_info.pipeline_root)
dsl_pipeline_root = dsl.PipelineParam(
name=tfx_pipeline.ROOT_PARAMETER.name,
value=pipeline.pipeline_info.pipeline_root)
self._params.append(dsl_pipeline_root)
def _construct_pipeline():
self._construct_pipeline_graph(pipeline, dsl_pipeline_root)
self._parse_parameter_from_pipeline(pipeline)
file_name = self._output_filename or get_default_output_filename(
pipeline.pipeline_info.pipeline_name)
self._compiler._create_and_write_workflow(
pipeline_func=_construct_pipeline,
pipeline_name=pipeline.pipeline_info.pipeline_name,
params_list=self._params,
package_path=os.path.join(self._output_dir, file_name))
| true | true |
790bedc36125b8b607589b033654f44942369dca | 3,220 | py | Python | multi_camera_multi_person_tracking/utils/network_wrappers.py | 565353780/open-vino | 362c11ca90026c0e1c21bb1f76f9dbfd339bdc05 | [
"MIT"
] | null | null | null | multi_camera_multi_person_tracking/utils/network_wrappers.py | 565353780/open-vino | 362c11ca90026c0e1c21bb1f76f9dbfd339bdc05 | [
"MIT"
] | null | null | null | multi_camera_multi_person_tracking/utils/network_wrappers.py | 565353780/open-vino | 362c11ca90026c0e1c21bb1f76f9dbfd339bdc05 | [
"MIT"
] | null | null | null | """
Copyright (c) 2019 Intel Corporation
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.
"""
from utils.ie_tools import load_ie_model
class Detector:
"""Wrapper class for detector"""
def __init__(self, model_path, conf=.6, device='CPU', ext_path='', max_num_frames=1):
self.net = load_ie_model(model_path, device, None, ext_path, num_reqs=max_num_frames)
self.confidence = conf
self.expand_ratio = (1., 1.)
self.max_num_frames = max_num_frames
def get_detections(self, frames):
"""Returns all detections on frames"""
assert len(frames) <= self.max_num_frames
all_detections = []
for i in range(len(frames)):
self.net.forward_async(frames[i])
outputs = self.net.grab_all_async()
for i, out in enumerate(outputs):
detections = self.__decode_detections(out, frames[i].shape)
all_detections.append(detections)
return all_detections
def __decode_detections(self, out, frame_shape):
"""Decodes raw SSD output"""
detections = []
for detection in out[0, 0]:
confidence = detection[2]
if confidence > self.confidence:
left = int(max(detection[3], 0) * frame_shape[1])
top = int(max(detection[4], 0) * frame_shape[0])
right = int(max(detection[5], 0) * frame_shape[1])
bottom = int(max(detection[6], 0) * frame_shape[0])
if self.expand_ratio != (1., 1.):
w = (right - left)
h = (bottom - top)
dw = w * (self.expand_ratio[0] - 1.) / 2
dh = h * (self.expand_ratio[1] - 1.) / 2
left = max(int(left - dw), 0)
right = int(right + dw)
top = max(int(top - dh), 0)
bottom = int(bottom + dh)
detections.append(((left, top, right, bottom), confidence))
if len(detections) > 1:
detections.sort(key=lambda x: x[1], reverse=True)
return detections
class VectorCNN:
"""Wrapper class for a network returning a vector"""
def __init__(self, model_path, device='CPU', max_reqs=100):
self.max_reqs = max_reqs
self.net = load_ie_model(model_path, device, None, num_reqs=self.max_reqs)
def forward(self, batch):
"""Performs forward of the underlying network on a given batch"""
assert len(batch) <= self.max_reqs
for frame in batch:
self.net.forward_async(frame)
outputs = self.net.grab_all_async()
return outputs
| 38.333333 | 94 | 0.590373 |
from utils.ie_tools import load_ie_model
class Detector:
def __init__(self, model_path, conf=.6, device='CPU', ext_path='', max_num_frames=1):
self.net = load_ie_model(model_path, device, None, ext_path, num_reqs=max_num_frames)
self.confidence = conf
self.expand_ratio = (1., 1.)
self.max_num_frames = max_num_frames
def get_detections(self, frames):
assert len(frames) <= self.max_num_frames
all_detections = []
for i in range(len(frames)):
self.net.forward_async(frames[i])
outputs = self.net.grab_all_async()
for i, out in enumerate(outputs):
detections = self.__decode_detections(out, frames[i].shape)
all_detections.append(detections)
return all_detections
def __decode_detections(self, out, frame_shape):
detections = []
for detection in out[0, 0]:
confidence = detection[2]
if confidence > self.confidence:
left = int(max(detection[3], 0) * frame_shape[1])
top = int(max(detection[4], 0) * frame_shape[0])
right = int(max(detection[5], 0) * frame_shape[1])
bottom = int(max(detection[6], 0) * frame_shape[0])
if self.expand_ratio != (1., 1.):
w = (right - left)
h = (bottom - top)
dw = w * (self.expand_ratio[0] - 1.) / 2
dh = h * (self.expand_ratio[1] - 1.) / 2
left = max(int(left - dw), 0)
right = int(right + dw)
top = max(int(top - dh), 0)
bottom = int(bottom + dh)
detections.append(((left, top, right, bottom), confidence))
if len(detections) > 1:
detections.sort(key=lambda x: x[1], reverse=True)
return detections
class VectorCNN:
def __init__(self, model_path, device='CPU', max_reqs=100):
self.max_reqs = max_reqs
self.net = load_ie_model(model_path, device, None, num_reqs=self.max_reqs)
def forward(self, batch):
assert len(batch) <= self.max_reqs
for frame in batch:
self.net.forward_async(frame)
outputs = self.net.grab_all_async()
return outputs
| true | true |
790bedfbdd1631e4090932e4cdaa29302ea59268 | 792 | py | Python | test_taster5.py | pythononwheels/opentoni | 666a014a956670ff6ec55a97b9a26bd3412353ad | [
"MIT"
] | null | null | null | test_taster5.py | pythononwheels/opentoni | 666a014a956670ff6ec55a97b9a26bd3412353ad | [
"MIT"
] | null | null | null | test_taster5.py | pythononwheels/opentoni | 666a014a956670ff6ec55a97b9a26bd3412353ad | [
"MIT"
] | null | null | null | import RPi.GPIO as gpio
import time
from subprocess import Popen, PIPE, call
pin =38
gpio.setmode(gpio.BOARD)
gpio.setup(pin, gpio.IN, pull_up_down = gpio.PUD_UP)
PRESSED = 0
prev_state = 1
pressed_time = 0.1
skip_song_mode = False
try:
while True:
cur_state = gpio.input(pin)
if cur_state == PRESSED:
pressed_time += 0.1
print "pressed : " + str( pressed_time)
if pressed_time > 1:
call(["espeak", "-ven", "shutting down"])
elif pressed_time == 0.1:
skip_song_mode = True
else:
skip_song_mode = False
else:
pressed_time = 0
if skip_song_mode == True:
call(["espeak", "-ven", "skip song"])
skip_song_mode = False
time.sleep(0.1)
finally:
gpio.cleanup()
| 24.75 | 53 | 0.60101 | import RPi.GPIO as gpio
import time
from subprocess import Popen, PIPE, call
pin =38
gpio.setmode(gpio.BOARD)
gpio.setup(pin, gpio.IN, pull_up_down = gpio.PUD_UP)
PRESSED = 0
prev_state = 1
pressed_time = 0.1
skip_song_mode = False
try:
while True:
cur_state = gpio.input(pin)
if cur_state == PRESSED:
pressed_time += 0.1
print "pressed : " + str( pressed_time)
if pressed_time > 1:
call(["espeak", "-ven", "shutting down"])
elif pressed_time == 0.1:
skip_song_mode = True
else:
skip_song_mode = False
else:
pressed_time = 0
if skip_song_mode == True:
call(["espeak", "-ven", "skip song"])
skip_song_mode = False
time.sleep(0.1)
finally:
gpio.cleanup()
| false | true |
790bee28635e8713588b60b8549f757d44bc9039 | 3,545 | py | Python | mlreflect/curve_fitter/minimizer.py | schreiber-lab/mlreflect | 88a80ccac48461cc8934a46041726b70e469c6b8 | [
"MIT"
] | null | null | null | mlreflect/curve_fitter/minimizer.py | schreiber-lab/mlreflect | 88a80ccac48461cc8934a46041726b70e469c6b8 | [
"MIT"
] | null | null | null | mlreflect/curve_fitter/minimizer.py | schreiber-lab/mlreflect | 88a80ccac48461cc8934a46041726b70e469c6b8 | [
"MIT"
] | null | null | null | import numpy as np
from scipy.optimize import curve_fit
from ..data_generation import interp_reflectivity, ReflectivityGenerator
def q_shift_variants(q_values_prediction, q_values_input, corrected_reflectivity, n_variants, scale=0.001):
"""Create ``n_variants`` interpolated reflectivity curve variants with randomly distributed q shifts."""
shift = np.random.normal(loc=0, size=n_variants, scale=scale).reshape(n_variants, 1)
shifted_qs = np.tile(q_values_input, (n_variants, 1)) + shift
interpolated_curves = np.zeros((n_variants, len(q_values_prediction)))
for i in range(n_variants):
interpolated_curves[i] = interp_reflectivity(q_values_prediction, shifted_qs[i], corrected_reflectivity)
return interpolated_curves, shift
def curve_scaling_variants(corrected_reflectivity, n_variants, scale=0.1):
"""Create ``n_variants`` reflectivity curve variants with randomly distributed scaling factors."""
scalings = np.random.normal(loc=1, size=n_variants, scale=scale).reshape(n_variants, 1)
scaled_curves = np.zeros((n_variants, len(corrected_reflectivity)))
for i in range(n_variants):
scaled_curves[i] = corrected_reflectivity.copy() * scalings[i]
return scaled_curves, scalings
def curve_variant_log_mse(curve, variant_curves):
"""Calculate the log MSE of a curve and a :class:`ndarray` of curves"""
errors = np.log10(curve) - np.log10(variant_curves)
return np.mean(errors ** 2, axis=1)
def least_log_mean_squares_fit(q_values, data, predicted_labels, sample, output_preprocessor,
fraction_bounds=(0.5, 0.5, 0.1)):
"""Fits the data with a model curve with ``scipy.optimize.curve_fit`` using ``predicted_labels`` as start values."""
prep_labels = output_preprocessor.apply_preprocessing(predicted_labels)[0]
start_values = np.array(prep_labels)[0]
bounds = ([val - bound * abs(val) for val, bound in zip(start_values, fraction_bounds)],
[val + bound * abs(val) for val, bound in zip(start_values, fraction_bounds)])
fit_result = curve_fit(fitting_model(q_values, sample, output_preprocessor), q_values, np.log10(data),
p0=start_values, bounds=bounds)
return output_preprocessor.restore_labels(np.atleast_2d(fit_result[0]))
def fitting_model(q_values, sample, output_preprocessor):
def log_refl_curve(q, *prep_labels):
generator = ReflectivityGenerator(q_values, sample)
restored_labels = output_preprocessor.restore_labels(np.atleast_2d(prep_labels))
model = generator.simulate_reflectivity(restored_labels, progress_bar=False)[0]
return np.log10(model)
return log_refl_curve
def log_mse_loss(prep_labels, data, generator, output_preprocessor):
"""MSE loss between a reflectivity curve and a model curve generated with the given normalized labels."""
restored_labels = output_preprocessor.restore_labels(np.atleast_2d(prep_labels))
model = generator.simulate_reflectivity(restored_labels,
progress_bar=False)[0]
loss = mean_squared_error(np.log10(data), np.log10(model))
return loss
def mean_squared_error(array1, array2):
"""Returns element-wise mean squared error between two arrays."""
if len(array1) != len(array2):
raise ValueError(f'array1 and array2 must be of same length ({len(array1)} != {len(array2)})')
else:
error = np.asarray(array1) - np.asarray(array2)
return np.mean(np.atleast_2d(error ** 2), axis=1)
| 49.929577 | 120 | 0.725811 | import numpy as np
from scipy.optimize import curve_fit
from ..data_generation import interp_reflectivity, ReflectivityGenerator
def q_shift_variants(q_values_prediction, q_values_input, corrected_reflectivity, n_variants, scale=0.001):
shift = np.random.normal(loc=0, size=n_variants, scale=scale).reshape(n_variants, 1)
shifted_qs = np.tile(q_values_input, (n_variants, 1)) + shift
interpolated_curves = np.zeros((n_variants, len(q_values_prediction)))
for i in range(n_variants):
interpolated_curves[i] = interp_reflectivity(q_values_prediction, shifted_qs[i], corrected_reflectivity)
return interpolated_curves, shift
def curve_scaling_variants(corrected_reflectivity, n_variants, scale=0.1):
scalings = np.random.normal(loc=1, size=n_variants, scale=scale).reshape(n_variants, 1)
scaled_curves = np.zeros((n_variants, len(corrected_reflectivity)))
for i in range(n_variants):
scaled_curves[i] = corrected_reflectivity.copy() * scalings[i]
return scaled_curves, scalings
def curve_variant_log_mse(curve, variant_curves):
errors = np.log10(curve) - np.log10(variant_curves)
return np.mean(errors ** 2, axis=1)
def least_log_mean_squares_fit(q_values, data, predicted_labels, sample, output_preprocessor,
fraction_bounds=(0.5, 0.5, 0.1)):
prep_labels = output_preprocessor.apply_preprocessing(predicted_labels)[0]
start_values = np.array(prep_labels)[0]
bounds = ([val - bound * abs(val) for val, bound in zip(start_values, fraction_bounds)],
[val + bound * abs(val) for val, bound in zip(start_values, fraction_bounds)])
fit_result = curve_fit(fitting_model(q_values, sample, output_preprocessor), q_values, np.log10(data),
p0=start_values, bounds=bounds)
return output_preprocessor.restore_labels(np.atleast_2d(fit_result[0]))
def fitting_model(q_values, sample, output_preprocessor):
def log_refl_curve(q, *prep_labels):
generator = ReflectivityGenerator(q_values, sample)
restored_labels = output_preprocessor.restore_labels(np.atleast_2d(prep_labels))
model = generator.simulate_reflectivity(restored_labels, progress_bar=False)[0]
return np.log10(model)
return log_refl_curve
def log_mse_loss(prep_labels, data, generator, output_preprocessor):
restored_labels = output_preprocessor.restore_labels(np.atleast_2d(prep_labels))
model = generator.simulate_reflectivity(restored_labels,
progress_bar=False)[0]
loss = mean_squared_error(np.log10(data), np.log10(model))
return loss
def mean_squared_error(array1, array2):
if len(array1) != len(array2):
raise ValueError(f'array1 and array2 must be of same length ({len(array1)} != {len(array2)})')
else:
error = np.asarray(array1) - np.asarray(array2)
return np.mean(np.atleast_2d(error ** 2), axis=1)
| true | true |
790bef11f686d55ca3e87f1884de366413f7cf15 | 5,296 | py | Python | vbridge/utils/entityset_helpers.py | sibyl-dev/VBridge | 5c4c49dad7cc1ad4e734dfac24b934088fc75bc6 | [
"MIT"
] | 5 | 2021-10-30T02:18:31.000Z | 2021-12-01T18:13:09.000Z | vbridge/utils/entityset_helpers.py | sibyl-dev/VBridge | 5c4c49dad7cc1ad4e734dfac24b934088fc75bc6 | [
"MIT"
] | null | null | null | vbridge/utils/entityset_helpers.py | sibyl-dev/VBridge | 5c4c49dad7cc1ad4e734dfac24b934088fc75bc6 | [
"MIT"
] | 1 | 2022-03-11T12:50:33.000Z | 2022-03-11T12:50:33.000Z | def remove_nan_entries(df, key_columns, verbose=True):
n_row = len(df)
for column in key_columns:
df = df[df[column] == df[column]]
if verbose:
print("Prune ({}/{}) rows.".format(n_row - len(df), n_row))
return df
def parse_relationship_path(relationship_path):
# TODO: get the relationship with a public function instead
relationship = relationship_path._relationships_with_direction[0][1]
return {
'parent_entity_id': relationship.parent_entity.id,
'parent_variable_id': relationship.parent_variable.id,
'child_entity_id': relationship.child_entity.id,
'child_variable_id': relationship.child_variable.id,
}
def get_forward_entities(entityset, entity_id):
ids = []
entity_id_pipe = [entity_id]
while len(entity_id_pipe):
entity_id = entity_id_pipe[0]
entity_id_pipe = entity_id_pipe[1:]
ids.append(entity_id)
for child_id, _ in entityset.get_forward_entities(entity_id):
entity_id_pipe.append(child_id)
return ids
def get_forward_attributes(entityset, target_entity, direct_id, interesting_ids=None):
info = []
entity_id_pipe = [(target_entity, direct_id)]
while len(entity_id_pipe):
entity_id, direct_id = entity_id_pipe.pop()
if interesting_ids is not None and entity_id not in interesting_ids:
continue
df = entityset[entity_id].df
info = [{'entityId': entity_id, 'items': df.loc[direct_id].fillna('N/A').to_dict()}] + info
for child_id, relationship_path in entityset.get_forward_entities(entity_id):
relation = parse_relationship_path(relationship_path)
entity_id_pipe.append((child_id, df.loc[direct_id][relation['parent_variable_id']]))
return info
def find_path(entityset, source_entity, target_entity):
"""Find a path of the source entity to the target_entity."""
nodes_pipe = [target_entity]
parent_dict = {target_entity: None}
while len(nodes_pipe):
parent_node = nodes_pipe.pop()
if parent_node == source_entity:
break
child_nodes = [e[0] for e in entityset.get_backward_entities(parent_node)] \
+ [e[0] for e in entityset.get_forward_entities(parent_node)]
for child in child_nodes:
if child not in parent_dict:
parent_dict[child] = parent_node
nodes_pipe.append(child)
node = source_entity
paths = [[node]]
while node != target_entity:
node = parent_dict[node]
paths.append(paths[-1] + [node])
return paths
def transfer_cutoff_times(entityset, cutoff_times, source_entity, target_entity,
reduce="latest"):
path = find_path(entityset, source_entity, target_entity)[-1]
for i, source in enumerate(path[:-1]):
target = path[i + 1]
options = list(filter(lambda r: (r.child_entity.id == source
and r.parent_entity.id == target)
or (r.parent_entity.id == source
and r.child_entity.id == target),
entityset.relationships))
if len(options) == 0:
raise ValueError("No Relationship between {} and {}".format(source, target))
r = options[0]
if target == r.child_entity.id:
# Transfer cutoff_times to "child", e.g., PATIENTS -> ADMISSIONS
child_df_index = r.child_entity.df[r.child_variable.id].values
cutoff_times = cutoff_times.loc[child_df_index]
cutoff_times.index = r.child_entity.df.index
elif source == r.child_entity.id:
# Transfer cutoff_times to "parent", e.g., ADMISSIONS -> PATIENTS
cutoff_times[r.child_variable.id] = r.child_entity.df[r.child_variable.id]
if reduce == "latest":
idx = cutoff_times.groupby(r.child_variable.id).time.idxmax().values
elif reduce == 'earist':
idx = cutoff_times.groupby(r.child_variable.id).time.idxmin().values
else:
raise ValueError("Unknown reduce option.")
cutoff_times = cutoff_times.loc[idx]
cutoff_times = cutoff_times.set_index(r.child_variable.id, drop=True)
return cutoff_times
def get_records(entityset, subject_id, entity_id, time_index=None, cutoff_time=None):
entity = entityset[entity_id].df
# select records by SUBJECT_ID
if 'SUBJECT_ID' in entity.columns:
entity_df = entity[entity['SUBJECT_ID'] == subject_id]
else:
entity_df = entity
# select records before or at the cutoff_time
if cutoff_time is not None and time_index is not None:
entity_df = entity_df[entity_df[time_index] <= cutoff_time]
# TODO filter records according to secondary time index
return entity_df
def get_item_dict(es):
item_dict = {'LABEVENTS': es['D_LABITEMS'].df.loc[:, 'LABEL'].to_dict()}
for entity_id in ['CHARTEVENTS', 'SURGERY_VITAL_SIGNS']:
df = es['D_ITEMS'].df
# TODO: Change 'LABEL' to 'LABEL_CN' for Chinese labels
items = df[df['LINKSTO'] == entity_id.lower()].loc[:, 'LABEL']
item_dict[entity_id] = items.to_dict()
return item_dict
| 41.375 | 99 | 0.643882 | def remove_nan_entries(df, key_columns, verbose=True):
n_row = len(df)
for column in key_columns:
df = df[df[column] == df[column]]
if verbose:
print("Prune ({}/{}) rows.".format(n_row - len(df), n_row))
return df
def parse_relationship_path(relationship_path):
relationship = relationship_path._relationships_with_direction[0][1]
return {
'parent_entity_id': relationship.parent_entity.id,
'parent_variable_id': relationship.parent_variable.id,
'child_entity_id': relationship.child_entity.id,
'child_variable_id': relationship.child_variable.id,
}
def get_forward_entities(entityset, entity_id):
ids = []
entity_id_pipe = [entity_id]
while len(entity_id_pipe):
entity_id = entity_id_pipe[0]
entity_id_pipe = entity_id_pipe[1:]
ids.append(entity_id)
for child_id, _ in entityset.get_forward_entities(entity_id):
entity_id_pipe.append(child_id)
return ids
def get_forward_attributes(entityset, target_entity, direct_id, interesting_ids=None):
info = []
entity_id_pipe = [(target_entity, direct_id)]
while len(entity_id_pipe):
entity_id, direct_id = entity_id_pipe.pop()
if interesting_ids is not None and entity_id not in interesting_ids:
continue
df = entityset[entity_id].df
info = [{'entityId': entity_id, 'items': df.loc[direct_id].fillna('N/A').to_dict()}] + info
for child_id, relationship_path in entityset.get_forward_entities(entity_id):
relation = parse_relationship_path(relationship_path)
entity_id_pipe.append((child_id, df.loc[direct_id][relation['parent_variable_id']]))
return info
def find_path(entityset, source_entity, target_entity):
nodes_pipe = [target_entity]
parent_dict = {target_entity: None}
while len(nodes_pipe):
parent_node = nodes_pipe.pop()
if parent_node == source_entity:
break
child_nodes = [e[0] for e in entityset.get_backward_entities(parent_node)] \
+ [e[0] for e in entityset.get_forward_entities(parent_node)]
for child in child_nodes:
if child not in parent_dict:
parent_dict[child] = parent_node
nodes_pipe.append(child)
node = source_entity
paths = [[node]]
while node != target_entity:
node = parent_dict[node]
paths.append(paths[-1] + [node])
return paths
def transfer_cutoff_times(entityset, cutoff_times, source_entity, target_entity,
reduce="latest"):
path = find_path(entityset, source_entity, target_entity)[-1]
for i, source in enumerate(path[:-1]):
target = path[i + 1]
options = list(filter(lambda r: (r.child_entity.id == source
and r.parent_entity.id == target)
or (r.parent_entity.id == source
and r.child_entity.id == target),
entityset.relationships))
if len(options) == 0:
raise ValueError("No Relationship between {} and {}".format(source, target))
r = options[0]
if target == r.child_entity.id:
child_df_index = r.child_entity.df[r.child_variable.id].values
cutoff_times = cutoff_times.loc[child_df_index]
cutoff_times.index = r.child_entity.df.index
elif source == r.child_entity.id:
cutoff_times[r.child_variable.id] = r.child_entity.df[r.child_variable.id]
if reduce == "latest":
idx = cutoff_times.groupby(r.child_variable.id).time.idxmax().values
elif reduce == 'earist':
idx = cutoff_times.groupby(r.child_variable.id).time.idxmin().values
else:
raise ValueError("Unknown reduce option.")
cutoff_times = cutoff_times.loc[idx]
cutoff_times = cutoff_times.set_index(r.child_variable.id, drop=True)
return cutoff_times
def get_records(entityset, subject_id, entity_id, time_index=None, cutoff_time=None):
entity = entityset[entity_id].df
if 'SUBJECT_ID' in entity.columns:
entity_df = entity[entity['SUBJECT_ID'] == subject_id]
else:
entity_df = entity
if cutoff_time is not None and time_index is not None:
entity_df = entity_df[entity_df[time_index] <= cutoff_time]
return entity_df
def get_item_dict(es):
item_dict = {'LABEVENTS': es['D_LABITEMS'].df.loc[:, 'LABEL'].to_dict()}
for entity_id in ['CHARTEVENTS', 'SURGERY_VITAL_SIGNS']:
df = es['D_ITEMS'].df
items = df[df['LINKSTO'] == entity_id.lower()].loc[:, 'LABEL']
item_dict[entity_id] = items.to_dict()
return item_dict
| true | true |
790bef5ee5ccf4aa4c38c98c4471cf856d2ee6f3 | 3,000 | py | Python | Fusion/fillet_polygon.py | HeNeos/autodesk_scripts | b0cf77915bc48eb3b27dc3739115d8f20a5ba434 | [
"MIT"
] | null | null | null | Fusion/fillet_polygon.py | HeNeos/autodesk_scripts | b0cf77915bc48eb3b27dc3739115d8f20a5ba434 | [
"MIT"
] | null | null | null | Fusion/fillet_polygon.py | HeNeos/autodesk_scripts | b0cf77915bc48eb3b27dc3739115d8f20a5ba434 | [
"MIT"
] | null | null | null | #Author-HeNeos
#Description-Many triangles, I love triangles
import adsk.core, adsk.fusion, adsk.cam, traceback
import math
def get_points(n, angle, r):
ans = [[0.0, 0.0]]*n
for i in range(0, n):
ans[i] = [r*math.cos(angle + 2*i*math.pi/n), r*math.sin(angle + 2*i*math.pi/n)]
return ans
def run(context):
try:
app = adsk.core.Application.get()
ui = app.userInterface
ui.messageBox('Are you ready')
product = app.activeProduct
design = adsk.fusion.Design.cast(product)
rootComp = design.rootComponent
sketches = rootComp.sketches
xyPlane = rootComp.xYConstructionPlane
# Create a new ObjectCollection.
revolves = rootComp.features.revolveFeatures
r = 4
loftFeats = rootComp.features.loftFeatures
loftInput = loftFeats.createInput(adsk.fusion.FeatureOperations.NewBodyFeatureOperation)
loftSectionsObj = loftInput.loftSections
n = 6
for i in range(0, 100):
angle = (math.pi)*abs(math.sin(i/10))
ctorPlanes = rootComp.constructionPlanes
plane = ctorPlanes.createInput()
offset = adsk.core.ValueInput.createByString(str(i)+" cm")
plane.setByOffset(xyPlane, offset)
Plane = ctorPlanes.add(plane)
sketch = sketches.add(Plane)
lines = sketch.sketchCurves.sketchLines
Points = []
Lines = []
p = get_points(n, angle, r)
for j in range(0, n):
point = adsk.core.Point3D.create(p[j][0], p[j][1], 0)
Points.append(point)
for j in range(0, n-1):
line = lines.addByTwoPoints(Points[j], Points[j+1])
Lines.append(line)
Lines.append(lines.addByTwoPoints(Points[n-1], Points[0]))
for i in range(0, n-1):
sketch.sketchCurves.sketchArcs.addFillet(Lines[i], Lines[i].endSketchPoint.geometry, Lines[i+1], Lines[i+1].startSketchPoint.geometry, 0.5)
sketch.sketchCurves.sketchArcs.addFillet(Lines[n-1], Lines[n-1].endSketchPoint.geometry, Lines[0], Lines[0].startSketchPoint.geometry, 0.5)
profile = sketch.profiles.item(0)
sketch.isVisible = False
Plane.isLightBulbOn = False
loftSectionsObj.add(profile)
loftInput.isSolid=True
loftFeats.add(loftInput)
except:
if ui:
ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
#axis = lines.addByTwoPoints(adsk.core.Point3D.create(-1,-4,0), adsk.core.Point3D.create(1,-4,0))
#circle1 = circles.addByCenterRadius(adsk.core.Point3D.create(0,0,0), 2)
def stop(context):
try:
app = adsk.core.Application.get()
ui = app.userInterface
ui.messageBox('Finished')
except:
if ui:
ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
| 35.714286 | 155 | 0.595 |
import adsk.core, adsk.fusion, adsk.cam, traceback
import math
def get_points(n, angle, r):
ans = [[0.0, 0.0]]*n
for i in range(0, n):
ans[i] = [r*math.cos(angle + 2*i*math.pi/n), r*math.sin(angle + 2*i*math.pi/n)]
return ans
def run(context):
try:
app = adsk.core.Application.get()
ui = app.userInterface
ui.messageBox('Are you ready')
product = app.activeProduct
design = adsk.fusion.Design.cast(product)
rootComp = design.rootComponent
sketches = rootComp.sketches
xyPlane = rootComp.xYConstructionPlane
revolves = rootComp.features.revolveFeatures
r = 4
loftFeats = rootComp.features.loftFeatures
loftInput = loftFeats.createInput(adsk.fusion.FeatureOperations.NewBodyFeatureOperation)
loftSectionsObj = loftInput.loftSections
n = 6
for i in range(0, 100):
angle = (math.pi)*abs(math.sin(i/10))
ctorPlanes = rootComp.constructionPlanes
plane = ctorPlanes.createInput()
offset = adsk.core.ValueInput.createByString(str(i)+" cm")
plane.setByOffset(xyPlane, offset)
Plane = ctorPlanes.add(plane)
sketch = sketches.add(Plane)
lines = sketch.sketchCurves.sketchLines
Points = []
Lines = []
p = get_points(n, angle, r)
for j in range(0, n):
point = adsk.core.Point3D.create(p[j][0], p[j][1], 0)
Points.append(point)
for j in range(0, n-1):
line = lines.addByTwoPoints(Points[j], Points[j+1])
Lines.append(line)
Lines.append(lines.addByTwoPoints(Points[n-1], Points[0]))
for i in range(0, n-1):
sketch.sketchCurves.sketchArcs.addFillet(Lines[i], Lines[i].endSketchPoint.geometry, Lines[i+1], Lines[i+1].startSketchPoint.geometry, 0.5)
sketch.sketchCurves.sketchArcs.addFillet(Lines[n-1], Lines[n-1].endSketchPoint.geometry, Lines[0], Lines[0].startSketchPoint.geometry, 0.5)
profile = sketch.profiles.item(0)
sketch.isVisible = False
Plane.isLightBulbOn = False
loftSectionsObj.add(profile)
loftInput.isSolid=True
loftFeats.add(loftInput)
except:
if ui:
ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
def stop(context):
try:
app = adsk.core.Application.get()
ui = app.userInterface
ui.messageBox('Finished')
except:
if ui:
ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
| true | true |
790bf08c8ddb1dfe491a43d811f87a660dedd594 | 5,103 | py | Python | src/ggrc/rbac/permissions_provider.py | sriharshakappala/ggrc-core | 7561ce27cd987d73468a44df5b6e2b7425f050ef | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2019-04-21T12:21:17.000Z | 2019-04-21T12:21:17.000Z | src/ggrc/rbac/permissions_provider.py | sriharshakappala/ggrc-core | 7561ce27cd987d73468a44df5b6e2b7425f050ef | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | src/ggrc/rbac/permissions_provider.py | sriharshakappala/ggrc-core | 7561ce27cd987d73468a44df5b6e2b7425f050ef | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | # Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: david@reciprocitylabs.com
# Maintained By: david@reciprocitylabs.com
from collections import namedtuple
from flask import session
from flask.ext.login import current_user
from .user_permissions import UserPermissions
from ggrc.models import get_model
Permission = namedtuple('Permission', 'action resource_type context_id')
_contributing_resource_types = {}
# Return a list of resource types using the same context space.
# This is needed because permissions may be given for, e.g., "Contract", but
# the restriction on join is done knowing only "Directive".
def get_contributing_resource_types(resource_type):
resource_types = _contributing_resource_types.get(resource_type, None)
if resource_types is None:
resource_types = [resource_type]
resource_model = get_model(resource_type)
if resource_model:
resource_manager = resource_model._sa_class_manager
resource_types.extend(
manager.class_.__name__ for manager in
resource_manager.subclass_managers(True))
_contributing_resource_types[resource_type] = resource_types
return resource_types
class DefaultUserPermissionsProvider(object):
def __init__(self, settings):
pass
def permissions_for(self, user):
return DefaultUserPermissions()
class DefaultUserPermissions(UserPermissions):
# super user, context_id 0 indicates all contexts
ADMIN_PERMISSION = Permission(
'__GGRC_ADMIN__',
'__GGRC_ALL__',
0,
)
def _admin_permission_for_context(self, context_id):
return Permission(
self.ADMIN_PERMISSION.action,
self.ADMIN_PERMISSION.resource_type,
context_id)
def _permission_match(self, permission, permissions):
return permission.context_id in \
permissions\
.get(permission.action, {})\
.get(permission.resource_type, [])
def _is_allowed(self, permission):
if 'permissions' not in session:
return True
permissions = session['permissions']
if permissions is None:
return True
if self._permission_match(permission, permissions):
return True
if self._permission_match(self.ADMIN_PERMISSION, permissions):
return True
return self._permission_match(
self._admin_permission_for_context(permission.context_id),
permissions)
def is_allowed_create(self, resource_type, context_id):
"""Whether or not the user is allowed to create a resource of the specified
type in the context."""
return self._is_allowed(Permission('create', resource_type, context_id))
def is_allowed_read(self, resource_type, context_id):
"""Whether or not the user is allowed to read a resource of the specified
type in the context."""
return self._is_allowed(Permission('read', resource_type, context_id))
def is_allowed_update(self, resource_type, context_id):
"""Whether or not the user is allowed to update a resource of the specified
type in the context."""
return self._is_allowed(Permission('update', resource_type, context_id))
def is_allowed_delete(self, resource_type, context_id):
"""Whether or not the user is allowed to delete a resource of the specified
type in the context."""
return self._is_allowed(Permission('delete', resource_type, context_id))
def _get_contexts_for(self, action, resource_type):
# FIXME: (Security) When applicable, we should explicitly assert that no
# permissions are expected (e.g. that every user has ADMIN_PERMISSION).
if 'permissions' not in session:
return None
permissions = session['permissions']
if permissions is None:
return None
if self._permission_match(self.ADMIN_PERMISSION, permissions):
return None
# Get the list of contexts for a given resource type and any
# superclasses
resource_types = get_contributing_resource_types(resource_type)
ret = []
for resource_type in resource_types:
ret.extend(permissions.get(action, {}).get(resource_type, ()))
# Extend with the list of all contexts for which the user is an ADMIN
admin_list = list(
permissions.get(self.ADMIN_PERMISSION.action, {})\
.get(self.ADMIN_PERMISSION.resource_type, ()))
ret.extend(admin_list)
return ret
def create_contexts_for(self, resource_type):
"""All contexts in which the user has create permission."""
return self._get_contexts_for('create', resource_type)
def read_contexts_for(self, resource_type):
"""All contexts in which the user has read permission."""
return self._get_contexts_for('read', resource_type)
def update_contexts_for(self, resource_type):
"""All contexts in which the user has update permission."""
return self._get_contexts_for('update', resource_type)
def delete_contexts_for(self, resource_type):
"""All contexts in which the user has delete permission."""
return self._get_contexts_for('delete', resource_type)
| 37.8 | 79 | 0.737997 |
from collections import namedtuple
from flask import session
from flask.ext.login import current_user
from .user_permissions import UserPermissions
from ggrc.models import get_model
Permission = namedtuple('Permission', 'action resource_type context_id')
_contributing_resource_types = {}
def get_contributing_resource_types(resource_type):
resource_types = _contributing_resource_types.get(resource_type, None)
if resource_types is None:
resource_types = [resource_type]
resource_model = get_model(resource_type)
if resource_model:
resource_manager = resource_model._sa_class_manager
resource_types.extend(
manager.class_.__name__ for manager in
resource_manager.subclass_managers(True))
_contributing_resource_types[resource_type] = resource_types
return resource_types
class DefaultUserPermissionsProvider(object):
def __init__(self, settings):
pass
def permissions_for(self, user):
return DefaultUserPermissions()
class DefaultUserPermissions(UserPermissions):
ADMIN_PERMISSION = Permission(
'__GGRC_ADMIN__',
'__GGRC_ALL__',
0,
)
def _admin_permission_for_context(self, context_id):
return Permission(
self.ADMIN_PERMISSION.action,
self.ADMIN_PERMISSION.resource_type,
context_id)
def _permission_match(self, permission, permissions):
return permission.context_id in \
permissions\
.get(permission.action, {})\
.get(permission.resource_type, [])
def _is_allowed(self, permission):
if 'permissions' not in session:
return True
permissions = session['permissions']
if permissions is None:
return True
if self._permission_match(permission, permissions):
return True
if self._permission_match(self.ADMIN_PERMISSION, permissions):
return True
return self._permission_match(
self._admin_permission_for_context(permission.context_id),
permissions)
def is_allowed_create(self, resource_type, context_id):
return self._is_allowed(Permission('create', resource_type, context_id))
def is_allowed_read(self, resource_type, context_id):
return self._is_allowed(Permission('read', resource_type, context_id))
def is_allowed_update(self, resource_type, context_id):
return self._is_allowed(Permission('update', resource_type, context_id))
def is_allowed_delete(self, resource_type, context_id):
return self._is_allowed(Permission('delete', resource_type, context_id))
def _get_contexts_for(self, action, resource_type):
if 'permissions' not in session:
return None
permissions = session['permissions']
if permissions is None:
return None
if self._permission_match(self.ADMIN_PERMISSION, permissions):
return None
resource_types = get_contributing_resource_types(resource_type)
ret = []
for resource_type in resource_types:
ret.extend(permissions.get(action, {}).get(resource_type, ()))
admin_list = list(
permissions.get(self.ADMIN_PERMISSION.action, {})\
.get(self.ADMIN_PERMISSION.resource_type, ()))
ret.extend(admin_list)
return ret
def create_contexts_for(self, resource_type):
return self._get_contexts_for('create', resource_type)
def read_contexts_for(self, resource_type):
return self._get_contexts_for('read', resource_type)
def update_contexts_for(self, resource_type):
return self._get_contexts_for('update', resource_type)
def delete_contexts_for(self, resource_type):
return self._get_contexts_for('delete', resource_type)
| true | true |
790bf17b6cb4944d81b66c46ddad1c11e994815f | 2,411 | py | Python | Python/Development/T-Bot_Tracking/getHSVThresh.py | garethnisbet/T-BOTS | 70e211191cc6c713084836bff89241e811667378 | [
"Apache-2.0"
] | 20 | 2018-07-16T21:34:35.000Z | 2022-01-07T02:33:10.000Z | Python/Development/T-Bot_Tracking/getHSVThresh.py | garethnisbet/T-BOTS | 70e211191cc6c713084836bff89241e811667378 | [
"Apache-2.0"
] | 5 | 2018-07-02T23:00:36.000Z | 2020-01-23T17:38:32.000Z | Python/Development/T-Bot_Tracking/getHSVThresh.py | garethnisbet/T-BOTS | 70e211191cc6c713084836bff89241e811667378 | [
"Apache-2.0"
] | 10 | 2018-05-15T10:38:40.000Z | 2021-06-03T07:07:21.000Z | #!/usr/bin/env python
import cv2
import numpy as np
# from scipy import ndimage
maskgridL = np.meshgrid(np.r_[0:359],np.r_[0:130])
maskgridR = np.meshgrid(np.r_[0:359],np.r_[639-130:639])
# key value
# cam.set(3 , 640) # width
# cam.set(4 , 480) # height
# cam.set(10, 120) # brightness min: 0 , max: 255 , increment:1
# cam.set(11, 50) # contrast min: 0 , max: 255 , increment:1
# cam.set(12, 70) # saturation min: 0 , max: 255 , increment:1
# cam.set(13, 13) # hue
# cam.set(14, 50) # gain min: 0 , max: 127 , increment:1
# cam.set(15, -3) # exposure min: -7 , max: -1 , increment:1
# cam.set(17, 5000) # white_balance min: 4000, max: 7000, increment:1
# cam.set(28, 0) # focus min: 0 , max: 255 , increment:5
def callback(value):
pass
def setup_trackbars(range_filter):
cv2.namedWindow("Thresholds",cv2.WINDOW_NORMAL)
cv2.resizeWindow("Thresholds", 720, 720)
for i in ["MIN", "MAX"]:
v = 0 if i == "MIN" else 255
for j in range_filter:
cv2.createTrackbar("%s_%s" % (j, i), "Thresholds", v, 255, callback)
def get_trackbar_values(range_filter):
values = []
for i in ["MIN", "MAX"]:
for j in range_filter:
v = cv2.getTrackbarPos("%s_%s" % (j, i), "Thresholds")
values.append(v)
return values
got_lowpass = 0
# range_filter = 'RGB'
range_filter = 'HSV'
cam = cv2.VideoCapture(0,cv2.CAP_V4L2)
cam.set(cv2.CAP_PROP_AUTOFOCUS, 0)
cam.set(28, 0)
cam.set(cv2.CAP_PROP_GAIN,0)
cam.set(cv2.CAP_PROP_BRIGHTNESS,0)
cam.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cam.set(cv2.CAP_PROP_FRAME_HEIGHT, 360)
cam.set(cv2.CAP_PROP_BRIGHTNESS, 100)
setup_trackbars(range_filter)
while True:
success, image = cam.read()
# image[maskgridL] = 0
# image[maskgridR] = 0
if range_filter == 'RGB':
frame_to_thresh = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
else:
frame_to_thresh = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
v1_min, v2_min, v3_min, v1_max, v2_max, v3_max = get_trackbar_values(range_filter)
thresh = cv2.inRange(frame_to_thresh, (v1_min, v2_min, v3_min), (v1_max, v2_max, v3_max))
preview = cv2.bitwise_and(image, image, mask=thresh)
cv2.imshow("Thresholds", preview)
if cv2.waitKey(1) & 0xFF is ord('q'):
cam.release()
cv2.destroyAllWindows()
break
| 33.027397 | 93 | 0.62754 |
import cv2
import numpy as np
maskgridL = np.meshgrid(np.r_[0:359],np.r_[0:130])
maskgridR = np.meshgrid(np.r_[0:359],np.r_[639-130:639])
s = []
for i in ["MIN", "MAX"]:
for j in range_filter:
v = cv2.getTrackbarPos("%s_%s" % (j, i), "Thresholds")
values.append(v)
return values
got_lowpass = 0
range_filter = 'HSV'
cam = cv2.VideoCapture(0,cv2.CAP_V4L2)
cam.set(cv2.CAP_PROP_AUTOFOCUS, 0)
cam.set(28, 0)
cam.set(cv2.CAP_PROP_GAIN,0)
cam.set(cv2.CAP_PROP_BRIGHTNESS,0)
cam.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cam.set(cv2.CAP_PROP_FRAME_HEIGHT, 360)
cam.set(cv2.CAP_PROP_BRIGHTNESS, 100)
setup_trackbars(range_filter)
while True:
success, image = cam.read()
if range_filter == 'RGB':
frame_to_thresh = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
else:
frame_to_thresh = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
v1_min, v2_min, v3_min, v1_max, v2_max, v3_max = get_trackbar_values(range_filter)
thresh = cv2.inRange(frame_to_thresh, (v1_min, v2_min, v3_min), (v1_max, v2_max, v3_max))
preview = cv2.bitwise_and(image, image, mask=thresh)
cv2.imshow("Thresholds", preview)
if cv2.waitKey(1) & 0xFF is ord('q'):
cam.release()
cv2.destroyAllWindows()
break
| true | true |
790bf25816a42104ab54d4f5d28003777a230e67 | 2,271 | py | Python | hathor/p2p/states/base.py | mbnunes/hathor-core | e5e0d4a627341e2a37ee46db5c9354ddb7f8dfb8 | [
"Apache-2.0"
] | 51 | 2019-12-28T03:33:27.000Z | 2022-03-10T14:03:03.000Z | hathor/p2p/states/base.py | mbnunes/hathor-core | e5e0d4a627341e2a37ee46db5c9354ddb7f8dfb8 | [
"Apache-2.0"
] | 316 | 2019-09-10T09:20:05.000Z | 2022-03-31T20:18:56.000Z | hathor/p2p/states/base.py | jansegre/hathor-core | 22b3de6be2518e7a0797edbf0e4f6eb1cf28d6fd | [
"Apache-2.0"
] | 19 | 2020-01-04T00:13:18.000Z | 2022-02-08T21:18:46.000Z | # Copyright 2021 Hathor Labs
#
# 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.
from typing import TYPE_CHECKING, Callable, Dict, Optional
from structlog import get_logger
from hathor.p2p.messages import ProtocolMessages
if TYPE_CHECKING:
from hathor.p2p.protocol import HathorProtocol # noqa: F401
logger = get_logger()
class BaseState:
protocol: 'HathorProtocol'
cmd_map: Dict[ProtocolMessages, Callable[[str], None]]
def __init__(self, protocol: 'HathorProtocol'):
self.log = logger.new(**protocol.get_logger_context())
self.protocol = protocol
self.cmd_map = {
ProtocolMessages.ERROR: self.handle_error,
ProtocolMessages.THROTTLE: self.handle_throttle,
}
# This variable is set by HathorProtocol after instantiating the state
self.state_name = None
def handle_error(self, payload: str) -> None:
self.protocol.handle_error(payload)
def handle_throttle(self, payload: str) -> None:
self.log.info('throttled', payload=payload)
def send_message(self, cmd: ProtocolMessages, payload: Optional[str] = None) -> None:
self.protocol.send_message(cmd, payload)
def send_throttle(self, key: str) -> None:
limit = self.protocol.ratelimit.get_limit(key)
if limit is None:
return
max_hits, window_seconds = limit
payload = '{} At most {} hits every {} seconds'.format(key, max_hits, window_seconds)
self.protocol.send_message(ProtocolMessages.THROTTLE, payload)
def on_enter(self) -> None:
raise NotImplementedError
def on_exit(self) -> None:
pass
def prepare_to_disconnect(self) -> None:
"""Called when we will disconnect with the peer."""
pass
| 33.397059 | 93 | 0.69749 |
from typing import TYPE_CHECKING, Callable, Dict, Optional
from structlog import get_logger
from hathor.p2p.messages import ProtocolMessages
if TYPE_CHECKING:
from hathor.p2p.protocol import HathorProtocol
logger = get_logger()
class BaseState:
protocol: 'HathorProtocol'
cmd_map: Dict[ProtocolMessages, Callable[[str], None]]
def __init__(self, protocol: 'HathorProtocol'):
self.log = logger.new(**protocol.get_logger_context())
self.protocol = protocol
self.cmd_map = {
ProtocolMessages.ERROR: self.handle_error,
ProtocolMessages.THROTTLE: self.handle_throttle,
}
self.state_name = None
def handle_error(self, payload: str) -> None:
self.protocol.handle_error(payload)
def handle_throttle(self, payload: str) -> None:
self.log.info('throttled', payload=payload)
def send_message(self, cmd: ProtocolMessages, payload: Optional[str] = None) -> None:
self.protocol.send_message(cmd, payload)
def send_throttle(self, key: str) -> None:
limit = self.protocol.ratelimit.get_limit(key)
if limit is None:
return
max_hits, window_seconds = limit
payload = '{} At most {} hits every {} seconds'.format(key, max_hits, window_seconds)
self.protocol.send_message(ProtocolMessages.THROTTLE, payload)
def on_enter(self) -> None:
raise NotImplementedError
def on_exit(self) -> None:
pass
def prepare_to_disconnect(self) -> None:
pass
| true | true |
790bf273115a1868208ab15d6177efe0aaf9a02d | 239 | py | Python | frontend-failure-model/frontend_failure.py | prl-tokyo/MAPE-validators | fd553c81fe45bd122ab339c286067c876d928d16 | [
"MIT"
] | null | null | null | frontend-failure-model/frontend_failure.py | prl-tokyo/MAPE-validators | fd553c81fe45bd122ab339c286067c876d928d16 | [
"MIT"
] | null | null | null | frontend-failure-model/frontend_failure.py | prl-tokyo/MAPE-validators | fd553c81fe45bd122ab339c286067c876d928d16 | [
"MIT"
] | null | null | null | """
A validator for a frontend failure model. The model contains all
the failing web frontends and their status, as well as the virtual
machines they run on.
"""
from vuluptuous import Schema
schema = Schema({
'web_frontends_failures'
})
| 21.727273 | 66 | 0.769874 | from vuluptuous import Schema
schema = Schema({
'web_frontends_failures'
})
| true | true |
790bf2c2ea1c72fa7902d6f10d78459299fecd85 | 146 | py | Python | 1080.py | gabriel1lima/Questoes---URI---Python | 4e88d76cf7ea68baf0464071bc4f72ced7d746cd | [
"MIT"
] | 1 | 2020-10-01T13:10:41.000Z | 2020-10-01T13:10:41.000Z | 1080.py | gabriel1lima/Questoes---URI---Python | 4e88d76cf7ea68baf0464071bc4f72ced7d746cd | [
"MIT"
] | null | null | null | 1080.py | gabriel1lima/Questoes---URI---Python | 4e88d76cf7ea68baf0464071bc4f72ced7d746cd | [
"MIT"
] | 7 | 2020-10-01T13:03:22.000Z | 2020-10-02T16:10:25.000Z | vet = []
i = 1
while(i <= 100):
valor = int(input())
vet.append(valor)
i = i + 1
print(max(vet))
print(vet.index(max(vet)) + 1)
| 9.733333 | 30 | 0.513699 | vet = []
i = 1
while(i <= 100):
valor = int(input())
vet.append(valor)
i = i + 1
print(max(vet))
print(vet.index(max(vet)) + 1)
| true | true |
790bf2cca1fa97e62bd819107a1e197a21f1aa97 | 4,428 | py | Python | test/functional/rpc_signrawtransaction.py | anandsinha095/JDCOIN | f77d87e7ba2b3d34d8b7425d33cdd1cf8a09f821 | [
"MIT"
] | null | null | null | test/functional/rpc_signrawtransaction.py | anandsinha095/JDCOIN | f77d87e7ba2b3d34d8b7425d33cdd1cf8a09f821 | [
"MIT"
] | null | null | null | test/functional/rpc_signrawtransaction.py | anandsinha095/JDCOIN | f77d87e7ba2b3d34d8b7425d33cdd1cf8a09f821 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
# Copyright (c) 2015-2017 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 transaction signing using the signrawtransaction RPC."""
from test_framework.test_framework import JdcoinTestFramework
from test_framework.util import *
class SignRawTransactionsTest(JdcoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
def successful_signing_test(self):
"""Create and sign a valid raw transaction with one input.
Expected results:
1) The transaction has a complete set of signatures
2) No script verification error occurred"""
privKeys = ['cUeKHd5orzT3mz8P9pxyREHfsWtVfgsfDjiZZBcjUBAaGk1BTj7N']
inputs = [
# Valid pay-to-pubkey script
{'txid': '9b907ef1e3c26fc71fe4a4b3580bc75264112f95050014157059c736f0202e71', 'vout': 0,
'scriptPubKey': '76a91460baa0f494b38ce3c940dea67f3804dc52d1fb9488ac'}
]
outputs = {'xwMWGTnBNUmGxMm8vfAdbL45bWXyVTYctd': 0.1}
rawTx = self.nodes[0].createrawtransaction(inputs, outputs)
rawTxSigned = self.nodes[0].signrawtransaction(rawTx, inputs, privKeys)
# 1) The transaction has a complete set of signatures
assert 'complete' in rawTxSigned
assert_equal(rawTxSigned['complete'], True)
# 2) No script verification error occurred
assert 'errors' not in rawTxSigned
def script_verification_error_test(self):
"""Create and sign a raw transaction with valid (vin 0), invalid (vin 1) and one missing (vin 2) input script.
Expected results:
3) The transaction has no complete set of signatures
4) Two script verification errors occurred
5) Script verification errors have certain properties ("txid", "vout", "scriptSig", "sequence", "error")
6) The verification errors refer to the invalid (vin 1) and missing input (vin 2)"""
privKeys = ['cUeKHd5orzT3mz8P9pxyREHfsWtVfgsfDjiZZBcjUBAaGk1BTj7N']
inputs = [
# Valid pay-to-pubkey script
{'txid': '9b907ef1e3c26fc71fe4a4b3580bc75264112f95050014157059c736f0202e71', 'vout': 0},
# Invalid script
{'txid': '5b8673686910442c644b1f4993d8f7753c7c8fcb5c87ee40d56eaeef25204547', 'vout': 7},
# Missing scriptPubKey
{'txid': '9b907ef1e3c26fc71fe4a4b3580bc75264112f95050014157059c736f0202e71', 'vout': 1},
]
scripts = [
# Valid pay-to-pubkey script
{'txid': '9b907ef1e3c26fc71fe4a4b3580bc75264112f95050014157059c736f0202e71', 'vout': 0,
'scriptPubKey': '76a91460baa0f494b38ce3c940dea67f3804dc52d1fb9488ac'},
# Invalid script
{'txid': '5b8673686910442c644b1f4993d8f7753c7c8fcb5c87ee40d56eaeef25204547', 'vout': 7,
'scriptPubKey': 'badbadbadbad'}
]
outputs = {'xwMWGTnBNUmGxMm8vfAdbL45bWXyVTYctd': 0.1}
rawTx = self.nodes[0].createrawtransaction(inputs, outputs)
rawTxSigned = self.nodes[0].signrawtransaction(rawTx, scripts, privKeys)
# 3) The transaction has no complete set of signatures
assert 'complete' in rawTxSigned
assert_equal(rawTxSigned['complete'], False)
# 4) Two script verification errors occurred
assert 'errors' in rawTxSigned
assert_equal(len(rawTxSigned['errors']), 2)
# 5) Script verification errors have certain properties
assert 'txid' in rawTxSigned['errors'][0]
assert 'vout' in rawTxSigned['errors'][0]
assert 'scriptSig' in rawTxSigned['errors'][0]
assert 'sequence' in rawTxSigned['errors'][0]
assert 'error' in rawTxSigned['errors'][0]
# 6) The verification errors refer to the invalid (vin 1) and missing input (vin 2)
assert_equal(rawTxSigned['errors'][0]['txid'], inputs[1]['txid'])
assert_equal(rawTxSigned['errors'][0]['vout'], inputs[1]['vout'])
assert_equal(rawTxSigned['errors'][1]['txid'], inputs[2]['txid'])
assert_equal(rawTxSigned['errors'][1]['vout'], inputs[2]['vout'])
def run_test(self):
self.successful_signing_test()
self.script_verification_error_test()
if __name__ == '__main__':
SignRawTransactionsTest().main()
| 42.171429 | 118 | 0.676603 |
from test_framework.test_framework import JdcoinTestFramework
from test_framework.util import *
class SignRawTransactionsTest(JdcoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
def successful_signing_test(self):
privKeys = ['cUeKHd5orzT3mz8P9pxyREHfsWtVfgsfDjiZZBcjUBAaGk1BTj7N']
inputs = [
{'txid': '9b907ef1e3c26fc71fe4a4b3580bc75264112f95050014157059c736f0202e71', 'vout': 0,
'scriptPubKey': '76a91460baa0f494b38ce3c940dea67f3804dc52d1fb9488ac'}
]
outputs = {'xwMWGTnBNUmGxMm8vfAdbL45bWXyVTYctd': 0.1}
rawTx = self.nodes[0].createrawtransaction(inputs, outputs)
rawTxSigned = self.nodes[0].signrawtransaction(rawTx, inputs, privKeys)
assert 'complete' in rawTxSigned
assert_equal(rawTxSigned['complete'], True)
assert 'errors' not in rawTxSigned
def script_verification_error_test(self):
privKeys = ['cUeKHd5orzT3mz8P9pxyREHfsWtVfgsfDjiZZBcjUBAaGk1BTj7N']
inputs = [
{'txid': '9b907ef1e3c26fc71fe4a4b3580bc75264112f95050014157059c736f0202e71', 'vout': 0},
{'txid': '5b8673686910442c644b1f4993d8f7753c7c8fcb5c87ee40d56eaeef25204547', 'vout': 7},
{'txid': '9b907ef1e3c26fc71fe4a4b3580bc75264112f95050014157059c736f0202e71', 'vout': 1},
]
scripts = [
{'txid': '9b907ef1e3c26fc71fe4a4b3580bc75264112f95050014157059c736f0202e71', 'vout': 0,
'scriptPubKey': '76a91460baa0f494b38ce3c940dea67f3804dc52d1fb9488ac'},
{'txid': '5b8673686910442c644b1f4993d8f7753c7c8fcb5c87ee40d56eaeef25204547', 'vout': 7,
'scriptPubKey': 'badbadbadbad'}
]
outputs = {'xwMWGTnBNUmGxMm8vfAdbL45bWXyVTYctd': 0.1}
rawTx = self.nodes[0].createrawtransaction(inputs, outputs)
rawTxSigned = self.nodes[0].signrawtransaction(rawTx, scripts, privKeys)
assert 'complete' in rawTxSigned
assert_equal(rawTxSigned['complete'], False)
assert 'errors' in rawTxSigned
assert_equal(len(rawTxSigned['errors']), 2)
assert 'txid' in rawTxSigned['errors'][0]
assert 'vout' in rawTxSigned['errors'][0]
assert 'scriptSig' in rawTxSigned['errors'][0]
assert 'sequence' in rawTxSigned['errors'][0]
assert 'error' in rawTxSigned['errors'][0]
assert_equal(rawTxSigned['errors'][0]['txid'], inputs[1]['txid'])
assert_equal(rawTxSigned['errors'][0]['vout'], inputs[1]['vout'])
assert_equal(rawTxSigned['errors'][1]['txid'], inputs[2]['txid'])
assert_equal(rawTxSigned['errors'][1]['vout'], inputs[2]['vout'])
def run_test(self):
self.successful_signing_test()
self.script_verification_error_test()
if __name__ == '__main__':
SignRawTransactionsTest().main()
| true | true |
790bf35d0bfdda69d1fb1a8ffe7ed80edc56e1c5 | 735 | py | Python | class3/exercise2/exercise2.py | papri-entropy/nornir-course | 122c5ecce19cca6c17a1eec0066be7c6b58e6eb5 | [
"MIT"
] | 1 | 2020-06-23T06:36:43.000Z | 2020-06-23T06:36:43.000Z | class3/exercise2/exercise2.py | papri-entropy/nornir-course | 122c5ecce19cca6c17a1eec0066be7c6b58e6eb5 | [
"MIT"
] | null | null | null | class3/exercise2/exercise2.py | papri-entropy/nornir-course | 122c5ecce19cca6c17a1eec0066be7c6b58e6eb5 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
# import general use modules
import os
from pprint import pprint as pp
# import nornir specifics
from nornir import InitNornir
from nornir.plugins.functions.text import print_result
from nornir.core.filter import F
nr = InitNornir()
hosts = nr.inventory.hosts
arista1_filter = nr.filter(name="arista1")
arista1 = arista1_filter.inventory.hosts
#print(hosts)
print(arista1)
wan_filter = nr.filter(role="WAN")
wan_filter = wan_filter.inventory.hosts
print(wan_filter)
wan_port_filter = nr.filter(role="WAN").filter(port=22)
wan_port_filter = wan_port_filter.inventory.hosts
print(wan_port_filter)
sfo_filter = nr.filter(F(groups__contains="sfo"))
sfo_filter = sfo_filter.inventory.hosts
print(sfo_filter)
| 21.617647 | 55 | 0.794558 |
import os
from pprint import pprint as pp
from nornir import InitNornir
from nornir.plugins.functions.text import print_result
from nornir.core.filter import F
nr = InitNornir()
hosts = nr.inventory.hosts
arista1_filter = nr.filter(name="arista1")
arista1 = arista1_filter.inventory.hosts
print(arista1)
wan_filter = nr.filter(role="WAN")
wan_filter = wan_filter.inventory.hosts
print(wan_filter)
wan_port_filter = nr.filter(role="WAN").filter(port=22)
wan_port_filter = wan_port_filter.inventory.hosts
print(wan_port_filter)
sfo_filter = nr.filter(F(groups__contains="sfo"))
sfo_filter = sfo_filter.inventory.hosts
print(sfo_filter)
| true | true |
790bf39686d8013c41bd21c7540eeadc3bc8e96b | 6,718 | py | Python | socketio/server.py | jykim16/gevent-socketio | 429424c5e738d442e509031e998c091c8b20a766 | [
"BSD-3-Clause"
] | 1 | 2018-12-11T23:06:06.000Z | 2018-12-11T23:06:06.000Z | socketio/server.py | jykim16/gevent-socketio | 429424c5e738d442e509031e998c091c8b20a766 | [
"BSD-3-Clause"
] | null | null | null | socketio/server.py | jykim16/gevent-socketio | 429424c5e738d442e509031e998c091c8b20a766 | [
"BSD-3-Clause"
] | 2 | 2018-09-06T20:57:45.000Z | 2018-09-06T21:18:31.000Z | import sys
import traceback
from socket import error
from gevent.pywsgi import WSGIServer
from socketio.handler import SocketIOHandler
from socketio.policyserver import FlashPolicyServer
from socketio.virtsocket import Socket
from geventwebsocket.handler import WebSocketHandler
__all__ = ['SocketIOServer']
class SocketIOServer(WSGIServer):
"""A WSGI Server with a resource that acts like an SocketIO."""
def __init__(self, *args, **kwargs):
"""This is just like the standard WSGIServer __init__, except with a
few additional ``kwargs``:
:param resource: The URL which has to be identified as a
socket.io request. Defaults to the /socket.io/ URL.
:param transports: Optional list of transports to allow. List of
strings, each string should be one of
handler.SocketIOHandler.handler_types.
:param policy_server: Boolean describing whether or not to use the
Flash policy server. Default True.
:param policy_listener: A tuple containing (host, port) for the
policy server. This is optional and used only if policy server
is set to true. The default value is 0.0.0.0:843
:param heartbeat_interval: int The timeout for the server, we
should receive a heartbeat from the client within this
interval. This should be less than the
``heartbeat_timeout``.
:param heartbeat_timeout: int The timeout for the client when
it should send a new heartbeat to the server. This value
is sent to the client after a successful handshake.
:param close_timeout: int The timeout for the client, when it
closes the connection it still X amounts of seconds to do
re open of the connection. This value is sent to the
client after a successful handshake.
:param log_file: str The file in which you want the PyWSGI
server to write its access log. If not specified, it
is sent to `stderr` (with gevent 0.13).
"""
self.sockets = {}
if 'namespace' in kwargs:
print("DEPRECATION WARNING: use resource instead of namespace")
self.resource = kwargs.pop('namespace', 'socket.io')
else:
self.resource = kwargs.pop('resource', 'socket.io')
self.transports = kwargs.pop('transports', None)
if kwargs.pop('policy_server', True):
wsock = args[0]
try:
address, port = wsock.getsockname()
except AttributeError:
try:
address = wsock[0]
except TypeError:
try:
address = wsock.address[0]
except AttributeError:
address = wsock.cfg_addr[0]
policylistener = kwargs.pop('policy_listener', (address, 10843))
self.policy_server = FlashPolicyServer(policylistener)
else:
self.policy_server = None
# Extract other config options
self.config = {
'heartbeat_timeout': 60,
'close_timeout': 60,
'heartbeat_interval': 25,
}
for f in ('heartbeat_timeout', 'heartbeat_interval', 'close_timeout'):
if f in kwargs:
self.config[f] = int(kwargs.pop(f))
if not 'handler_class' in kwargs:
kwargs['handler_class'] = SocketIOHandler
if not 'ws_handler_class' in kwargs:
self.ws_handler_class = WebSocketHandler
else:
self.ws_handler_class = kwargs.pop('ws_handler_class')
log_file = kwargs.pop('log_file', None)
if log_file:
kwargs['log'] = open(log_file, 'a')
super(SocketIOServer, self).__init__(*args, **kwargs)
def start_accepting(self):
if self.policy_server is not None:
try:
if not self.policy_server.started:
self.policy_server.start()
except error as ex:
sys.stderr.write(
'FAILED to start flash policy server: %s\n' % (ex, ))
except Exception:
traceback.print_exc()
sys.stderr.write('FAILED to start flash policy server.\n\n')
super(SocketIOServer, self).start_accepting()
def stop(self, timeout=None):
if self.policy_server is not None:
self.policy_server.stop()
super(SocketIOServer, self).stop(timeout=timeout)
def handle(self, socket, address):
# Pass in the config about timeouts, heartbeats, also...
handler = self.handler_class(self.config, socket, address, self)
handler.handle()
def get_socket(self, sessid=''):
"""Return an existing or new client Socket."""
socket = self.sockets.get(sessid)
if sessid and not socket:
return None # you ask for a session that doesn't exist!
if socket is None:
socket = Socket(self, self.config)
self.sockets[socket.sessid] = socket
else:
socket.incr_hits()
return socket
def serve(app, **kw):
_quiet = kw.pop('_quiet', False)
_resource = kw.pop('resource', 'socket.io')
if not _quiet: # pragma: no cover
# idempotent if logging has already been set up
import logging
logging.basicConfig()
host = kw.pop('host', '127.0.0.1')
port = int(kw.pop('port', 6543))
transports = kw.pop('transports', None)
if transports:
transports = [x.strip() for x in transports.split(',')]
policy_server = kw.pop('policy_server', False)
if policy_server in (True, 'True', 'true', 'enable', 'yes', 'on', '1'):
policy_server = True
policy_listener_host = kw.pop('policy_listener_host', host)
policy_listener_port = int(kw.pop('policy_listener_port', 10843))
kw['policy_listener'] = (policy_listener_host, policy_listener_port)
else:
policy_server = False
server = SocketIOServer((host, port),
app,
resource=_resource,
transports=transports,
policy_server=policy_server,
**kw)
if not _quiet:
print(('serving on http://%s:%s' % (host, port)))
server.serve_forever()
def serve_paste(app, global_conf, **kw):
"""pserve / paster serve / waitress replacement / integration
You can pass as parameters:
transports = websockets, xhr-multipart, xhr-longpolling, etc...
policy_server = True
"""
serve(app, **kw)
return 0
| 35.172775 | 78 | 0.601221 | import sys
import traceback
from socket import error
from gevent.pywsgi import WSGIServer
from socketio.handler import SocketIOHandler
from socketio.policyserver import FlashPolicyServer
from socketio.virtsocket import Socket
from geventwebsocket.handler import WebSocketHandler
__all__ = ['SocketIOServer']
class SocketIOServer(WSGIServer):
def __init__(self, *args, **kwargs):
self.sockets = {}
if 'namespace' in kwargs:
print("DEPRECATION WARNING: use resource instead of namespace")
self.resource = kwargs.pop('namespace', 'socket.io')
else:
self.resource = kwargs.pop('resource', 'socket.io')
self.transports = kwargs.pop('transports', None)
if kwargs.pop('policy_server', True):
wsock = args[0]
try:
address, port = wsock.getsockname()
except AttributeError:
try:
address = wsock[0]
except TypeError:
try:
address = wsock.address[0]
except AttributeError:
address = wsock.cfg_addr[0]
policylistener = kwargs.pop('policy_listener', (address, 10843))
self.policy_server = FlashPolicyServer(policylistener)
else:
self.policy_server = None
self.config = {
'heartbeat_timeout': 60,
'close_timeout': 60,
'heartbeat_interval': 25,
}
for f in ('heartbeat_timeout', 'heartbeat_interval', 'close_timeout'):
if f in kwargs:
self.config[f] = int(kwargs.pop(f))
if not 'handler_class' in kwargs:
kwargs['handler_class'] = SocketIOHandler
if not 'ws_handler_class' in kwargs:
self.ws_handler_class = WebSocketHandler
else:
self.ws_handler_class = kwargs.pop('ws_handler_class')
log_file = kwargs.pop('log_file', None)
if log_file:
kwargs['log'] = open(log_file, 'a')
super(SocketIOServer, self).__init__(*args, **kwargs)
def start_accepting(self):
if self.policy_server is not None:
try:
if not self.policy_server.started:
self.policy_server.start()
except error as ex:
sys.stderr.write(
'FAILED to start flash policy server: %s\n' % (ex, ))
except Exception:
traceback.print_exc()
sys.stderr.write('FAILED to start flash policy server.\n\n')
super(SocketIOServer, self).start_accepting()
def stop(self, timeout=None):
if self.policy_server is not None:
self.policy_server.stop()
super(SocketIOServer, self).stop(timeout=timeout)
def handle(self, socket, address):
handler = self.handler_class(self.config, socket, address, self)
handler.handle()
def get_socket(self, sessid=''):
socket = self.sockets.get(sessid)
if sessid and not socket:
return None
if socket is None:
socket = Socket(self, self.config)
self.sockets[socket.sessid] = socket
else:
socket.incr_hits()
return socket
def serve(app, **kw):
_quiet = kw.pop('_quiet', False)
_resource = kw.pop('resource', 'socket.io')
if not _quiet: # pragma: no cover
# idempotent if logging has already been set up
import logging
logging.basicConfig()
host = kw.pop('host', '127.0.0.1')
port = int(kw.pop('port', 6543))
transports = kw.pop('transports', None)
if transports:
transports = [x.strip() for x in transports.split(',')]
policy_server = kw.pop('policy_server', False)
if policy_server in (True, 'True', 'true', 'enable', 'yes', 'on', '1'):
policy_server = True
policy_listener_host = kw.pop('policy_listener_host', host)
policy_listener_port = int(kw.pop('policy_listener_port', 10843))
kw['policy_listener'] = (policy_listener_host, policy_listener_port)
else:
policy_server = False
server = SocketIOServer((host, port),
app,
resource=_resource,
transports=transports,
policy_server=policy_server,
**kw)
if not _quiet:
print(('serving on http://%s:%s' % (host, port)))
server.serve_forever()
def serve_paste(app, global_conf, **kw):
serve(app, **kw)
return 0
| true | true |
790bf42b4d5ef992d9d2d26dacefc8fde9a6b75d | 2,194 | py | Python | eahub/base/admin.py | rtcharity/eahub.org | 0abb235e9b99f3d35cf69c3d630aeea9496d9220 | [
"MIT"
] | 36 | 2019-02-22T23:07:14.000Z | 2022-02-10T13:24:27.000Z | eahub/base/admin.py | rtcharity/eahub.org | 0abb235e9b99f3d35cf69c3d630aeea9496d9220 | [
"MIT"
] | 717 | 2019-02-21T22:07:55.000Z | 2022-02-26T15:17:49.000Z | eahub/base/admin.py | rtcharity/eahub.org | 0abb235e9b99f3d35cf69c3d630aeea9496d9220 | [
"MIT"
] | 19 | 2019-04-14T14:37:56.000Z | 2022-02-14T22:05:16.000Z | from typing import Optional
import django_admin_relation_links
from adminutils import options
from authtools import admin as authtools_admin
from django.contrib import admin
from enumfields.admin import EnumFieldListFilter
from rangefilter.filter import DateRangeFilter
from solo.admin import SingletonModelAdmin
from eahub.base import models
from eahub.base.models import User
from eahub.profiles.models import Profile
@admin.register(models.User)
class UserAdmin(
django_admin_relation_links.AdminChangeLinksMixin, authtools_admin.UserAdmin
):
list_select_related = ["profile"]
list_display = [
"is_active",
"email",
"profile_link",
"is_profile_approved",
"date_joined",
"last_login",
"is_superuser",
"is_staff",
"get_visibility",
]
change_links = ["profile"]
list_filter = [
"is_superuser",
"is_staff",
"is_active",
"profile__is_approved",
("profile__visibility", EnumFieldListFilter),
("date_joined", DateRangeFilter),
("last_login", DateRangeFilter),
]
search_fields = ["email", "profile__first_name", "profile__last_name"]
@options(desc="Approved", boolean=True)
def is_profile_approved(self, user) -> Optional[bool]:
profile = get_profile(user)
if profile is None:
return None
return profile.is_approved
@options(desc="Visibility")
def get_visibility(self, user) -> str:
profile = get_profile(user)
if profile is None:
return ""
return profile.visibility.value
def get_profile(user: User) -> Optional[Profile]:
try:
return user.profile
except Profile.DoesNotExist:
return None
@admin.register(models.MessagingLog)
class MessagingLogAdmin(admin.ModelAdmin):
list_display = [
"sender_email",
"recipient_email",
"recipient_type",
"send_action_uuid",
"time",
]
list_filter = [
"recipient_type",
("time", DateRangeFilter),
]
search_fields = ["sender", "recipient"]
admin.site.register(models.FeedbackURLConfig, SingletonModelAdmin)
| 26.433735 | 80 | 0.667274 | from typing import Optional
import django_admin_relation_links
from adminutils import options
from authtools import admin as authtools_admin
from django.contrib import admin
from enumfields.admin import EnumFieldListFilter
from rangefilter.filter import DateRangeFilter
from solo.admin import SingletonModelAdmin
from eahub.base import models
from eahub.base.models import User
from eahub.profiles.models import Profile
@admin.register(models.User)
class UserAdmin(
django_admin_relation_links.AdminChangeLinksMixin, authtools_admin.UserAdmin
):
list_select_related = ["profile"]
list_display = [
"is_active",
"email",
"profile_link",
"is_profile_approved",
"date_joined",
"last_login",
"is_superuser",
"is_staff",
"get_visibility",
]
change_links = ["profile"]
list_filter = [
"is_superuser",
"is_staff",
"is_active",
"profile__is_approved",
("profile__visibility", EnumFieldListFilter),
("date_joined", DateRangeFilter),
("last_login", DateRangeFilter),
]
search_fields = ["email", "profile__first_name", "profile__last_name"]
@options(desc="Approved", boolean=True)
def is_profile_approved(self, user) -> Optional[bool]:
profile = get_profile(user)
if profile is None:
return None
return profile.is_approved
@options(desc="Visibility")
def get_visibility(self, user) -> str:
profile = get_profile(user)
if profile is None:
return ""
return profile.visibility.value
def get_profile(user: User) -> Optional[Profile]:
try:
return user.profile
except Profile.DoesNotExist:
return None
@admin.register(models.MessagingLog)
class MessagingLogAdmin(admin.ModelAdmin):
list_display = [
"sender_email",
"recipient_email",
"recipient_type",
"send_action_uuid",
"time",
]
list_filter = [
"recipient_type",
("time", DateRangeFilter),
]
search_fields = ["sender", "recipient"]
admin.site.register(models.FeedbackURLConfig, SingletonModelAdmin)
| true | true |
790bf477aba7e1ba5dca6e8b97e71ea572c0bdbf | 2,880 | py | Python | tests/test_adders.py | fgarci03/pylectronics | bfcbb60e2aa64bc0a97d43abe69c5a5c0dfa43f2 | [
"MIT"
] | 45 | 2021-08-30T03:21:58.000Z | 2021-10-31T01:18:00.000Z | tests/test_adders.py | thequux/pylectronics | 7d806afb59e5172ae710a13eb370ac64afa77a6d | [
"MIT"
] | 4 | 2021-08-30T02:23:41.000Z | 2021-10-07T02:35:44.000Z | tests/test_adders.py | fgarci03/pylectronics | bfcbb60e2aa64bc0a97d43abe69c5a5c0dfa43f2 | [
"MIT"
] | 2 | 2021-08-30T14:22:55.000Z | 2021-09-01T17:48:10.000Z | from unittest import TestCase
from src.adders import HalfAdder, FullAdder, FourBitFullAdder
from tests.utils import decimal_to_boolean_list
class HalfAdderTests(TestCase):
TRUTH_TABLE = (
# A B S Cout
((False, False), (False, False)),
((False, True), (True, False)),
((True, False), (True, False)),
((True, True), (False, True)),
)
def setUp(self):
self.half_adder = HalfAdder()
def test_truth_table(self):
for test_case in self.TRUTH_TABLE:
assert self.half_adder.set_inputs(*test_case[0]) == test_case[1]
class FullAdderTests(TestCase):
TRUTH_TABLE = (
# A B Cin S Cout
((False, False, False), (False, False)),
((False, False, True), (True, False)),
((False, True, False), (True, False)),
((False, True, True), (False, True)),
((True, False, False), (True, False)),
((True, False, True), (False, True)),
((True, True, False), (False, True)),
((True, True, True), (True, True)),
)
def setUp(self):
self.full_adder = FullAdder()
def test_truth_table(self):
for test_case in self.TRUTH_TABLE:
assert self.full_adder.set_inputs(*test_case[0]) == test_case[1]
class FourBitFullAdderTests(TestCase):
def setUp(self):
self.full_adder = FourBitFullAdder()
self.TRUTH_TABLE = []
# Generate the truth table, since it is HUGE for a 4 bit adder
# Note: it will generate items like:
# (((False, True, False, False), (False, False, True, True)), (False, False, True, True, True))
# and
# (((False, True, True, False), (False, True, True, True)), (False, True, True, False, True))
# for 4 + 3 = 7 and 6 + 7 = 13, respectively
for addend_1 in range(0, 16):
for addend_2 in range(0, 16):
self.TRUTH_TABLE.append(
(
(decimal_to_boolean_list(addend_1, padding=4), decimal_to_boolean_list(addend_2, padding=4)),
decimal_to_boolean_list(addend_1 + addend_2, padding=5),
)
)
def test_truth_table(self):
for test_case in self.TRUTH_TABLE:
# Note, generate the inputs arguments by setting both addends and the carry in (which is always 0 *false*)
inputs = (test_case[0][0], test_case[0][1], False)
assert self.full_adder.set_inputs(*inputs) == test_case[1]
# Test adding 15+15 with a carry in, which will result in 31
assert (
self.full_adder.set_inputs(
value_1=(True, True, True, True),
value_2=(True, True, True, True),
carry_in=True,
)
== (True, True, True, True, True)
)
| 35.121951 | 118 | 0.557292 | from unittest import TestCase
from src.adders import HalfAdder, FullAdder, FourBitFullAdder
from tests.utils import decimal_to_boolean_list
class HalfAdderTests(TestCase):
TRUTH_TABLE = (
((False, False), (False, False)),
((False, True), (True, False)),
((True, False), (True, False)),
((True, True), (False, True)),
)
def setUp(self):
self.half_adder = HalfAdder()
def test_truth_table(self):
for test_case in self.TRUTH_TABLE:
assert self.half_adder.set_inputs(*test_case[0]) == test_case[1]
class FullAdderTests(TestCase):
TRUTH_TABLE = (
((False, False, False), (False, False)),
((False, False, True), (True, False)),
((False, True, False), (True, False)),
((False, True, True), (False, True)),
((True, False, False), (True, False)),
((True, False, True), (False, True)),
((True, True, False), (False, True)),
((True, True, True), (True, True)),
)
def setUp(self):
self.full_adder = FullAdder()
def test_truth_table(self):
for test_case in self.TRUTH_TABLE:
assert self.full_adder.set_inputs(*test_case[0]) == test_case[1]
class FourBitFullAdderTests(TestCase):
def setUp(self):
self.full_adder = FourBitFullAdder()
self.TRUTH_TABLE = []
for addend_1 in range(0, 16):
for addend_2 in range(0, 16):
self.TRUTH_TABLE.append(
(
(decimal_to_boolean_list(addend_1, padding=4), decimal_to_boolean_list(addend_2, padding=4)),
decimal_to_boolean_list(addend_1 + addend_2, padding=5),
)
)
def test_truth_table(self):
for test_case in self.TRUTH_TABLE:
inputs = (test_case[0][0], test_case[0][1], False)
assert self.full_adder.set_inputs(*inputs) == test_case[1]
assert (
self.full_adder.set_inputs(
value_1=(True, True, True, True),
value_2=(True, True, True, True),
carry_in=True,
)
== (True, True, True, True, True)
)
| true | true |
790bf5338d4310ce89ee5d358060e44a01884d20 | 142,260 | py | Python | release/stubs/Autodesk/Civil/Settings.py | paoloemilioserra/ironpython-stubs | 49d92db7f28f25ccd3654c5f6ae83daa0c401fa1 | [
"MIT"
] | null | null | null | release/stubs/Autodesk/Civil/Settings.py | paoloemilioserra/ironpython-stubs | 49d92db7f28f25ccd3654c5f6ae83daa0c401fa1 | [
"MIT"
] | null | null | null | release/stubs/Autodesk/Civil/Settings.py | paoloemilioserra/ironpython-stubs | 49d92db7f28f25ccd3654c5f6ae83daa0c401fa1 | [
"MIT"
] | null | null | null | # encoding: utf-8
# module Autodesk.Civil.Settings calls itself Settings
# from AeccDbMgd, Version=13.3.854.0, Culture=neutral, PublicKeyToken=null, AeccPressurePipesMgd, Version=13.3.854.0, Culture=neutral, PublicKeyToken=null
# by generator 1.145
# no doc
# no imports
# no functions
# classes
class AbbreviationAlignmentEnhancedType(Enum):
""" enum AbbreviationAlignmentEnhancedType, values: AlignmentBeginningPoint (402706556), AlignmentEndPoint (402706557), CompoundSpiralLargeRadiusAtBeginning (402706566), CompoundSpiralLargeRadiusAtEnd (402706567), CompoundSpiralSmallRadiusAtBeginning (402706568), CompoundSpiralSmallRadiusAtEnd (402706569), CurveBeginning (402706560), CurveEnd (402706561), LineBeginning (402706558), LineEnd (402706559), SimpleSpiralLargeRadiusAtBeginning (402706562), SimpleSpiralLargeRadiusAtEnd (402706563), SimpleSpiralSmallRadiusAtBeginning (402706564), SimpleSpiralSmallRadiusAtEnd (402706565) """
AlignmentBeginningPoint = None
AlignmentEndPoint = None
CompoundSpiralLargeRadiusAtBeginning = None
CompoundSpiralLargeRadiusAtEnd = None
CompoundSpiralSmallRadiusAtBeginning = None
CompoundSpiralSmallRadiusAtEnd = None
CurveBeginning = None
CurveEnd = None
LineBeginning = None
LineEnd = None
SimpleSpiralLargeRadiusAtBeginning = None
SimpleSpiralLargeRadiusAtEnd = None
SimpleSpiralSmallRadiusAtBeginning = None
SimpleSpiralSmallRadiusAtEnd = None
value__ = None
class AbbreviationAlignmentType(Enum):
""" enum AbbreviationAlignmentType, values: AlignmentBeginning (67162235), AlignmentEnd (67162234), CompoundCurveCurveIntersect (67162197), CurveSpiralIntersect (67162201), CurveTangentIntersect (67162196), MidCurvePoint (67162254), ReverseCurveCurveIntersect (67162198), ReverseSpiralIntersect (67162204), SpiralCurveIntersect (67162202), SpiralSpiralIntersect (67162203), SpiralTangentIntersect (67162200), StationEquationDecreasing (67162253), StationEquationIncreasing (67162252), TangentCurveIntersect (67162195), TangentSpiralIntersect (67162199), TangentTangentIntersect (67162194) """
AlignmentBeginning = None
AlignmentEnd = None
CompoundCurveCurveIntersect = None
CurveSpiralIntersect = None
CurveTangentIntersect = None
MidCurvePoint = None
ReverseCurveCurveIntersect = None
ReverseSpiralIntersect = None
SpiralCurveIntersect = None
SpiralSpiralIntersect = None
SpiralTangentIntersect = None
StationEquationDecreasing = None
StationEquationIncreasing = None
TangentCurveIntersect = None
TangentSpiralIntersect = None
TangentTangentIntersect = None
value__ = None
class AbbreviationCantType(Enum):
""" enum AbbreviationCantType, values: BeginAlignment (67163513), BeginFullCant (67163510), BeginLevelRail (67163509), EndAlignment (67163514), EndFullCant (67163511), EndLevelRail (67163508), Manual (67163512) """
BeginAlignment = None
BeginFullCant = None
BeginLevelRail = None
EndAlignment = None
EndFullCant = None
EndLevelRail = None
Manual = None
value__ = None
class AbbreviationProfileType(Enum):
""" enum AbbreviationProfileType, values: BeginVerticalCurve (67173890), BeginVerticalCurveElevation (67173892), BeginVerticalCurveStation (67173891), CurveCoefficient (67173898), EndVerticalCurve (67173893), EndVerticalCurveElevation (67173895), EndVerticalCurveStation (67173894), GradeBreak (67173889), GradeChange (67173899), HighPoint (67173896), LowPoint (67173897), OverallHighPoint (67173909), OverallLowPoint (67173910), PointOfVerticalIntersection (67173888), ProfileEnd (67173902), ProfileStart (67173901), VerticalCompoundCurveIntersect (67173903), VerticalCompoundCurveIntersectElevation (67173906), VerticalCompoundCurveIntersectStation (67173905), VerticalReverseCurveIntersect (67173904), VerticalReverseCurveIntersectElevation (67173908), VerticalReverseCurveIntersectStation (67173907) """
BeginVerticalCurve = None
BeginVerticalCurveElevation = None
BeginVerticalCurveStation = None
CurveCoefficient = None
EndVerticalCurve = None
EndVerticalCurveElevation = None
EndVerticalCurveStation = None
GradeBreak = None
GradeChange = None
HighPoint = None
LowPoint = None
OverallHighPoint = None
OverallLowPoint = None
PointOfVerticalIntersection = None
ProfileEnd = None
ProfileStart = None
value__ = None
VerticalCompoundCurveIntersect = None
VerticalCompoundCurveIntersectElevation = None
VerticalCompoundCurveIntersectStation = None
VerticalReverseCurveIntersect = None
VerticalReverseCurveIntersectElevation = None
VerticalReverseCurveIntersectStation = None
class AbbreviationSuperelevationType(Enum):
""" enum AbbreviationSuperelevationType, values: BeginFullSuper (67163478), BeginNormalCrown (67163476), BeginNormalShoulder (67163480), BeginOfAlignment (67163474), BeginShoulderRollover (67163506), EndFullSuper (67163479), EndNormalCrown (67163477), EndNormalShoulder (67163481), EndOfAlignment (67163475), EndShoulderRollover (67163507), LevelCrown (67163482), LowShoulderMatch (67163483), Manual (67163486), ReverseCrown (67163484), ShoulderBreakover (67163485) """
BeginFullSuper = None
BeginNormalCrown = None
BeginNormalShoulder = None
BeginOfAlignment = None
BeginShoulderRollover = None
EndFullSuper = None
EndNormalCrown = None
EndNormalShoulder = None
EndOfAlignment = None
EndShoulderRollover = None
LevelCrown = None
LowShoulderMatch = None
Manual = None
ReverseCrown = None
ShoulderBreakover = None
value__ = None
class AutomaticManual(Enum):
""" enum AutomaticManual, values: Automatic (0), AutomaticObject (1), Manual (2), None (3) """
Automatic = None
AutomaticObject = None
Manual = None
None = None
value__ = None
class DrawingUnitType(Enum):
""" enum DrawingUnitType, values: Feet (30), Meters (2) """
Feet = None
Meters = None
value__ = None
class GeographicCoordinateType(Enum):
""" enum GeographicCoordinateType, values: LatLong (0), LongLat (1) """
LatLong = None
LongLat = None
value__ = None
class GridCoordinateType(Enum):
""" enum GridCoordinateType, values: EastingNorthing (0), NorthingEasting (1) """
EastingNorthing = None
NorthingEasting = None
value__ = None
class GridScaleFactorType(Enum):
""" enum GridScaleFactorType, values: PrismodialFormula (3), ReferencePoint (2), Unity (0), UserDefined (1) """
PrismodialFormula = None
ReferencePoint = None
Unity = None
UserDefined = None
value__ = None
class ImperialToMetricConversionType(Enum):
""" enum ImperialToMetricConversionType, values: InternationalFoot (536870912), UsSurveyFoot (1073741824) """
InternationalFoot = None
UsSurveyFoot = None
value__ = None
class LandXMLAngularUnits(Enum):
""" enum LandXMLAngularUnits, values: DegreesDecimal (0), DegreesDms (1), Grads (2), Radians (3) """
DegreesDecimal = None
DegreesDms = None
Grads = None
Radians = None
value__ = None
class LandXMLAttributeExportType(Enum):
""" enum LandXMLAttributeExportType, values: Disabled (0), FullDescription (2), RawDescription (1) """
Disabled = None
FullDescription = None
RawDescription = None
value__ = None
class LandXMLConflictResolutionType(Enum):
""" enum LandXMLConflictResolutionType, values: Append (2), Skip (0), Update (1) """
Append = None
Skip = None
Update = None
value__ = None
class LandXMLImperialUnitType(Enum):
""" enum LandXMLImperialUnitType, values: Foot (30), Inch (31), Mile (44), Yard (33) """
Foot = None
Inch = None
Mile = None
value__ = None
Yard = None
class LandXMLLinearUnits(Enum):
""" enum LandXMLLinearUnits, values: InternationalFoot (30), SurveyFoot (54) """
InternationalFoot = None
SurveyFoot = None
value__ = None
class LandXMLMetricUnitType(Enum):
""" enum LandXMLMetricUnitType, values: CentiMeter (24), DeciMeter (23), KiloMeter (20), Meter (2), MilliMeter (25) """
CentiMeter = None
DeciMeter = None
KiloMeter = None
Meter = None
MilliMeter = None
value__ = None
class LandXMLPointDescriptionType(Enum):
""" enum LandXMLPointDescriptionType, values: UseCodeThenDesc (2), UseCodeValue (0), UseDescThenCode (3), UseDescValue (1) """
UseCodeThenDesc = None
UseCodeValue = None
UseDescThenCode = None
UseDescValue = None
value__ = None
class LandXMLSurfaceDataExportType(Enum):
""" enum LandXMLSurfaceDataExportType, values: PointsAndFaces (1), PointsOnly (0) """
PointsAndFaces = None
PointsOnly = None
value__ = None
class LandXMLSurfaceDataImportType(Enum):
""" enum LandXMLSurfaceDataImportType, values: FullImport (1), QuickImport (0) """
FullImport = None
QuickImport = None
value__ = None
class LocalCoordinateType(Enum):
""" enum LocalCoordinateType, values: EastingNorthing (0), NorthingEasting (1), XY (2), YX (3) """
EastingNorthing = None
NorthingEasting = None
value__ = None
XY = None
YX = None
class MapcheckAngleType(Enum):
""" enum MapcheckAngleType, values: Angle (1), DeflectionAngle (2), Direction (0) """
Angle = None
DeflectionAngle = None
Direction = None
value__ = None
class MapcheckCurveDirectionType(Enum):
""" enum MapcheckCurveDirectionType, values: Clockwise (0), CounterClockwise (1) """
Clockwise = None
CounterClockwise = None
value__ = None
class MapcheckSideType(Enum):
""" enum MapcheckSideType, values: Curve (1), Line (0) """
Curve = None
Line = None
value__ = None
class MapcheckTraverseMethodType(Enum):
""" enum MapcheckTraverseMethodType, values: AcrossChord (0), ThroughRadius (1) """
AcrossChord = None
ThroughRadius = None
value__ = None
class ObjectLayerModifierType(Enum):
""" enum ObjectLayerModifierType, values: None (0), Prefix (1), Suffix (2) """
None = None
Prefix = None
Suffix = None
value__ = None
class SectionViewAnchorType(Enum):
""" enum SectionViewAnchorType, values: BottomCenter (7), BottomLeft (6), BottomRight (8), MiddleCenter (4), MiddleLeft (3), MiddleRight (5), TopCenter (1), TopLeft (0), TopRight (2) """
BottomCenter = None
BottomLeft = None
BottomRight = None
MiddleCenter = None
MiddleLeft = None
MiddleRight = None
TopCenter = None
TopLeft = None
TopRight = None
value__ = None
class SettingsAbbreviation(CivilWrapper<AcDbDatabase>):
# no doc
def Dispose(self):
""" Dispose(self: CivilWrapper<AcDbDatabase>, A_0: bool) """
pass
AlignmentGeoPointEntityData = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: AlignmentGeoPointEntityData(self: SettingsAbbreviation) -> SettingsAbbreviationAlignmentEnhanced
"""
AlignmentGeoPointText = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: AlignmentGeoPointText(self: SettingsAbbreviation) -> SettingsAbbreviationAlignment
"""
Cant = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Cant(self: SettingsAbbreviation) -> SettingsAbbreviationCant
"""
GeneralText = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: GeneralText(self: SettingsAbbreviation) -> SettingsAbbreviationGeneral
"""
Profile = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Profile(self: SettingsAbbreviation) -> SettingsAbbreviationProfile
"""
Superelevation = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Superelevation(self: SettingsAbbreviation) -> SettingsAbbreviationSuperelevation
"""
class SettingsAbbreviationAlignment(TreeOidWrapper):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
def GetAlignmentAbbreviation(self, type):
""" GetAlignmentAbbreviation(self: SettingsAbbreviationAlignment, type: AbbreviationAlignmentType) -> str """
pass
def SetAlignmentAbbreviation(self, type, value):
""" SetAlignmentAbbreviation(self: SettingsAbbreviationAlignment, type: AbbreviationAlignmentType, value: str) """
pass
class SettingsAbbreviationAlignmentEnhanced(TreeOidWrapper):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
def GetAlignmentEnhancedAbbreviation(self, type):
""" GetAlignmentEnhancedAbbreviation(self: SettingsAbbreviationAlignmentEnhanced, type: AbbreviationAlignmentEnhancedType) -> str """
pass
def SetAlignmentEnhancedAbbreviation(self, type, newValue):
""" SetAlignmentEnhancedAbbreviation(self: SettingsAbbreviationAlignmentEnhanced, type: AbbreviationAlignmentEnhancedType, newValue: str) """
pass
class SettingsAbbreviationCant(TreeOidWrapper):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
def GetCantAbbreviation(self, type):
""" GetCantAbbreviation(self: SettingsAbbreviationCant, type: AbbreviationCantType) -> str """
pass
def SetCantAbbreviation(self, type, newValue):
""" SetCantAbbreviation(self: SettingsAbbreviationCant, type: AbbreviationCantType, newValue: str) """
pass
class SettingsAbbreviationGeneral(TreeOidWrapper):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
Infinity = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Infinity(self: SettingsAbbreviationGeneral) -> str
Set: Infinity(self: SettingsAbbreviationGeneral) = value
"""
Left = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Left(self: SettingsAbbreviationGeneral) -> str
Set: Left(self: SettingsAbbreviationGeneral) = value
"""
Right = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Right(self: SettingsAbbreviationGeneral) -> str
Set: Right(self: SettingsAbbreviationGeneral) = value
"""
class SettingsAbbreviationProfile(TreeOidWrapper):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
def GetProfileAbbreviation(self, type):
""" GetProfileAbbreviation(self: SettingsAbbreviationProfile, type: AbbreviationProfileType) -> str """
pass
def SetProfileAbbreviation(self, type, newValue):
""" SetProfileAbbreviation(self: SettingsAbbreviationProfile, type: AbbreviationProfileType, newValue: str) """
pass
class SettingsAbbreviationSuperelevation(TreeOidWrapper):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
def GetSuperelevationAbbreviation(self, type):
""" GetSuperelevationAbbreviation(self: SettingsAbbreviationSuperelevation, type: AbbreviationSuperelevationType) -> str """
pass
def SetSuperelevationAbbreviation(self, type, newValue):
""" SetSuperelevationAbbreviation(self: SettingsAbbreviationSuperelevation, type: AbbreviationSuperelevationType, newValue: str) """
pass
class SettingsAmbient(TreeOidWrapper):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
@staticmethod # known case of __new__
def __new__(self, *args): #cannot find CLR constructor
""" __new__(cls: type, root: SettingsRoot, path: str) """
pass
Acceleration = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Acceleration(self: SettingsAmbient) -> SettingsAcceleration
"""
Angle = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Angle(self: SettingsAmbient) -> SettingsAngle
"""
Area = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Area(self: SettingsAmbient) -> SettingsArea
"""
Coordinate = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Coordinate(self: SettingsAmbient) -> SettingsCoordinate
"""
DegreeOfCurvature = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: DegreeOfCurvature(self: SettingsAmbient) -> SettingsDegreeOfCurvature
"""
Dimension = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Dimension(self: SettingsAmbient) -> SettingsDimension
"""
Direction = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Direction(self: SettingsAmbient) -> SettingsDirection
"""
Distance = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Distance(self: SettingsAmbient) -> SettingsDistance
"""
Elevation = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Elevation(self: SettingsAmbient) -> SettingsElevation
"""
General = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: General(self: SettingsAmbient) -> SettingsGeneral
"""
Grade = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Grade(self: SettingsAmbient) -> SettingsGrade
"""
GradeSlope = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: GradeSlope(self: SettingsAmbient) -> SettingsGradeSlope
"""
GridCoordinate = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: GridCoordinate(self: SettingsAmbient) -> SettingsGridCoordinate
"""
Labeling = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Labeling(self: SettingsAmbient) -> SettingsLabeling
"""
LatLong = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: LatLong(self: SettingsAmbient) -> SettingsLatLong
"""
Pressure = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Pressure(self: SettingsAmbient) -> SettingsPressure
"""
Slope = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Slope(self: SettingsAmbient) -> SettingsSlope
"""
Speed = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Speed(self: SettingsAmbient) -> SettingsSpeed
"""
Station = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Station(self: SettingsAmbient) -> SettingsStation
"""
Time = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Time(self: SettingsAmbient) -> SettingsTime
"""
TransparentCommands = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: TransparentCommands(self: SettingsAmbient) -> SettingsTransparentCommands
"""
Unitless = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Unitless(self: SettingsAmbient) -> SettingsUnitless
"""
Volume = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Volume(self: SettingsAmbient) -> SettingsVolume
"""
SettingsAcceleration = None
SettingsAngle = None
SettingsArea = None
SettingsCoordinate = None
SettingsDegreeOfCurvature = None
SettingsDimension = None
SettingsDirection = None
SettingsDistance = None
SettingsElevation = None
SettingsFormatNumber`1 = None
SettingsGeneral = None
SettingsGrade = None
SettingsGradeSlope = None
SettingsGridCoordinate = None
SettingsLabeling = None
SettingsLatLong = None
SettingsPressure = None
SettingsSlope = None
SettingsSpeed = None
SettingsStation = None
SettingsTime = None
SettingsTransparentCommands = None
SettingsUnitFormatNumber`2 = None
SettingsUnitless = None
SettingsUnitlessNumber = None
SettingsUnitNumber`1 = None
SettingsVolume = None
class SettingsAlignment(SettingsAmbient):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
AutomaticWideningAroundCurves = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: AutomaticWideningAroundCurves(self: SettingsAlignment) -> SettingsAutomaticWideningAroundCurves
"""
CantOptions = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: CantOptions(self: SettingsAlignment) -> SettingsCantOptions
"""
ConstraintEditing = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: ConstraintEditing(self: SettingsAlignment) -> SettingsConstraintEditing
"""
CriteriaBasedDesignOptions = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: CriteriaBasedDesignOptions(self: SettingsAlignment) -> SettingsCriteriaBasedDesignOptions
"""
Data = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Data(self: SettingsAlignment) -> SettingsData
"""
DefaultNameFormat = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: DefaultNameFormat(self: SettingsAlignment) -> SettingsDefaultNameFormat
"""
DynamicAlignmentHighlight = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: DynamicAlignmentHighlight(self: SettingsAlignment) -> SettingsDynamicAlignmentHighlight
"""
ImpliedPointOfIntersection = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: ImpliedPointOfIntersection(self: SettingsAlignment) -> SettingsImpliedPointOfIntersection
"""
RailOptions = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: RailOptions(self: SettingsAlignment) -> SettingsRailAlignmentOptions
"""
StationIndexing = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: StationIndexing(self: SettingsAlignment) -> SettingsStationIndexing
"""
StyleSettings = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: StyleSettings(self: SettingsAlignment) -> SettingsStyles
"""
SuperelevationOptions = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: SuperelevationOptions(self: SettingsAlignment) -> SettingsSuperelevationOptions
"""
SettingsAutomaticWideningAroundCurves = None
SettingsCantOptions = None
SettingsConstraintEditing = None
SettingsCriteriaBasedDesignOptions = None
SettingsData = None
SettingsDefaultNameFormat = None
SettingsDynamicAlignmentHighlight = None
SettingsImpliedPointOfIntersection = None
SettingsRailAlignmentOptions = None
SettingsStationIndexing = None
SettingsStyles = None
SettingsSuperelevationOptions = None
class SettingsAssembly(SettingsAmbient):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
NameFormat = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: NameFormat(self: SettingsAssembly) -> SettingsNameFormat
"""
Styles = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Styles(self: SettingsAssembly) -> SettingsStyles
"""
SettingsNameFormat = None
SettingsStyles = None
class SettingsBuildingSite(SettingsAmbient):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
NameFormat = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: NameFormat(self: SettingsBuildingSite) -> SettingsNameFormat
"""
Styles = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Styles(self: SettingsBuildingSite) -> SettingsStyles
"""
SettingsNameFormat = None
SettingsStyles = None
class SettingsCantView(SettingsAmbient):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
NameFormat = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: NameFormat(self: SettingsCantView) -> SettingsNameFormat
"""
Styles = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Styles(self: SettingsCantView) -> SettingsStyles
"""
SettingsNameFormat = None
SettingsStyles = None
class SettingsCatchment(SettingsAmbient):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
NameTemplate = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: NameTemplate(self: SettingsCatchment) -> PropertyString
"""
Styles = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Styles(self: SettingsCatchment) -> SettingsStyles
"""
SettingsStyles = None
class SettingsCmdAddAlignmentCurveTable(SettingsAlignment):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
TableCreation = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: TableCreation(self: SettingsCmdAddAlignmentCurveTable) -> SettingsCmdTableCreation
"""
SettingsCmdTableCreation = None
class SettingsCmdAddAlignmentLineTable(SettingsAlignment):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
TableCreation = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: TableCreation(self: SettingsCmdAddAlignmentLineTable) -> SettingsCmdTableCreation
"""
SettingsCmdTableCreation = None
class SettingsCmdAddAlignmentOffLbl(SettingsAlignment):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddAlignmentOffXYLbl(SettingsAlignment):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddAlignmentSegmentTable(SettingsAlignment):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
TableCreation = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: TableCreation(self: SettingsCmdAddAlignmentSegmentTable) -> SettingsCmdTableCreation
"""
SettingsCmdTableCreation = None
class SettingsCmdAddAlignmentSpiralTable(SettingsAlignment):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
TableCreation = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: TableCreation(self: SettingsCmdAddAlignmentSpiralTable) -> SettingsCmdTableCreation
"""
SettingsCmdTableCreation = None
class SettingsCmdAddAlignPointOfIntLbl(SettingsAlignment):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddAlignPointOfIntLbls(SettingsAlignment):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddAlignSegLbl(SettingsAlignment):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddAlignSegLbls(SettingsAlignment):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddAlignTagentLbl(SettingsAlignment):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddAlignTagentLbls(SettingsAlignment):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsPressureNetwork(SettingsAmbient):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
Cover = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Cover(self: SettingsPressureNetwork) -> SettingsDepthOfCover
"""
NameFormat = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: NameFormat(self: SettingsPressureNetwork) -> SettingsNameFormat
"""
ProfileLabelPlacement = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: ProfileLabelPlacement(self: SettingsPressureNetwork) -> SettingsProfileLabelPlacement
"""
SectionLabelPlacement = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: SectionLabelPlacement(self: SettingsPressureNetwork) -> SettingsSectionLabelPlacement
"""
Styles = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Styles(self: SettingsPressureNetwork) -> SettingsStyles
"""
SettingsDepthOfCover = None
SettingsNameFormat = None
SettingsProfileLabelPlacement = None
SettingsSectionLabelPlacement = None
SettingsStyles = None
class SettingsCmdAddAppurtTable(SettingsPressureNetwork):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
TableCreation = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: TableCreation(self: SettingsCmdAddAppurtTable) -> SettingsCmdTableCreation
"""
SettingsCmdTableCreation = None
class SettingsSurface(SettingsAmbient):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
ContourLabeling = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: ContourLabeling(self: SettingsSurface) -> SettingsContourLabeling
"""
Defaults = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Defaults(self: SettingsSurface) -> SettingsDefaults
"""
Styles = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Styles(self: SettingsSurface) -> SettingsStyles
"""
SettingsContourLabeling = None
SettingsDefaults = None
SettingsStyles = None
class SettingsCmdAddContourLabeling(SettingsSurface):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddContourLabelingGroup(SettingsSurface):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
AddContourLabeling = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: AddContourLabeling(self: SettingsCmdAddContourLabelingGroup) -> SettingsCmdAddContourLabeling
"""
SettingsCmdAddContourLabeling = None
class SettingsCmdAddContourLabelingSingle(SettingsSurface):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddFittingTable(SettingsPressureNetwork):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
TableCreation = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: TableCreation(self: SettingsCmdAddFittingTable) -> SettingsCmdTableCreation
"""
SettingsCmdTableCreation = None
class SettingsIntersection(SettingsAmbient):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
NameFormat = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: NameFormat(self: SettingsIntersection) -> SettingsNameFormat
"""
Styles = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Styles(self: SettingsIntersection) -> SettingsStyles
"""
SettingsNameFormat = None
SettingsStyles = None
class SettingsCmdAddIntersectionLabel(SettingsIntersection):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsGeneral(SettingsAmbient):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
Styles = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Styles(self: SettingsGeneral) -> SettingsStyles
"""
SettingsStyles = None
class SettingsCmdAddLineBetweenPoints(SettingsGeneral):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsQuantityTakeoff(SettingsAmbient):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
NameFormat = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: NameFormat(self: SettingsQuantityTakeoff) -> SettingsNameFormat
"""
Styles = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Styles(self: SettingsQuantityTakeoff) -> SettingsStyles
"""
SettingsNameFormat = None
SettingsStyles = None
class SettingsCmdAddMaterialVolumeTable(SettingsQuantityTakeoff):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
TableCreation = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: TableCreation(self: SettingsCmdAddMaterialVolumeTable) -> SettingsCmdTableCreation
"""
SettingsCmdTableCreation = None
class SettingsPipeNetwork(SettingsAmbient):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
Default = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Default(self: SettingsPipeNetwork) -> SettingsDefault
"""
NameFormat = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: NameFormat(self: SettingsPipeNetwork) -> SettingsNameFormat
"""
ProfileLabelPlacement = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: ProfileLabelPlacement(self: SettingsPipeNetwork) -> SettingsProfileLabelPlacement
"""
Rules = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Rules(self: SettingsPipeNetwork) -> SettingsRules
"""
SectionLabelPlacement = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: SectionLabelPlacement(self: SettingsPipeNetwork) -> SettingsSectionLabelPlacement
"""
StormSewersMigration = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: StormSewersMigration(self: SettingsPipeNetwork) -> SettingsStormSewersMigration
"""
Styles = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Styles(self: SettingsPipeNetwork) -> SettingsStyles
"""
SettingsDefault = None
SettingsNameFormat = None
SettingsProfileLabelPlacement = None
SettingsRules = None
SettingsSectionLabelPlacement = None
SettingsStormSewersMigration = None
SettingsStyles = None
class SettingsCmdAddNetworkPartPlanLabel(SettingsPipeNetwork):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddNetworkPartProfLabel(SettingsPipeNetwork):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddNetworkPartSectLabel(SettingsPipeNetwork):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddNetworkPartsToProf(SettingsPipeNetwork):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddNetworkPipeTable(SettingsPipeNetwork):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
TableCreation = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: TableCreation(self: SettingsCmdAddNetworkPipeTable) -> SettingsCmdTableCreation
"""
SettingsCmdTableCreation = None
class SettingsCmdAddNetworkPlanLabels(SettingsPipeNetwork):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddNetworkProfLabels(SettingsPipeNetwork):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddNetworkSectLabels(SettingsPipeNetwork):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddNetworkStructTable(SettingsPipeNetwork):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
TableCreation = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: TableCreation(self: SettingsCmdAddNetworkStructTable) -> SettingsCmdTableCreation
"""
SettingsCmdTableCreation = None
class SettingsCmdAddNoteLabel(SettingsGeneral):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsParcel(SettingsAmbient):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
Styles = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Styles(self: SettingsParcel) -> SettingsStyles
"""
SettingsStyles = None
class SettingsCmdAddParcelAreaLabel(SettingsParcel):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddParcelCurveTable(SettingsParcel):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
TableCreation = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: TableCreation(self: SettingsCmdAddParcelCurveTable) -> SettingsCmdTableCreation
"""
SettingsCmdTableCreation = None
class SettingsCmdAddParcelLineLabel(SettingsParcel):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddParcelLineTable(SettingsParcel):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
TableCreation = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: TableCreation(self: SettingsCmdAddParcelLineTable) -> SettingsCmdTableCreation
"""
SettingsCmdTableCreation = None
class SettingsCmdAddParcelSegmentLabels(SettingsParcel):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
Options = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Options(self: SettingsCmdAddParcelSegmentLabels) -> SettingsCmdOptions
"""
SettingsCmdOptions = None
class SettingsCmdAddParcelSegmentTable(SettingsParcel):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
TableCreation = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: TableCreation(self: SettingsCmdAddParcelSegmentTable) -> SettingsCmdTableCreation
"""
SettingsCmdTableCreation = None
class SettingsCmdAddParcelTable(SettingsParcel):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
TableCreation = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: TableCreation(self: SettingsCmdAddParcelTable) -> SettingsCmdTableCreation
"""
SettingsCmdTableCreation = None
class SettingsPointCloud(SettingsAmbient):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
DefaultNameFormat = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: DefaultNameFormat(self: SettingsPointCloud) -> SettingsDefaultNameFormat
"""
StyleSettings = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: StyleSettings(self: SettingsPointCloud) -> SettingsStyles
"""
SettingsDefaultNameFormat = None
SettingsStyles = None
class SettingsCmdAddPointCloudPoints(SettingsPointCloud):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
DefaultFileFormat = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: DefaultFileFormat(self: SettingsCmdAddPointCloudPoints) -> PropertyEnum[PointCloudDefaultFileExtensionType]
"""
class SettingsCmdAddPointsToSurface(SettingsPointCloud):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
MidOrdinateDistance = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: MidOrdinateDistance(self: SettingsCmdAddPointsToSurface) -> PropertyDouble
"""
RegionOption = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: RegionOption(self: SettingsCmdAddPointsToSurface) -> PropertyEnum[PointCloudRegionType]
"""
SurfaceOption = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: SurfaceOption(self: SettingsCmdAddPointsToSurface) -> PropertyEnum[PointCloudSurfaceType]
"""
class SettingsPoint(SettingsAmbient):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
NameFormat = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: NameFormat(self: SettingsPoint) -> SettingsNameFormat
"""
Styles = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Styles(self: SettingsPoint) -> SettingsStyles
"""
UpdatePoints = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: UpdatePoints(self: SettingsPoint) -> SettingsUpdatePoints
"""
SettingsNameFormat = None
SettingsStyles = None
SettingsUpdatePoints = None
class SettingsCmdAddPointTable(SettingsPoint):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
TableCreation = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: TableCreation(self: SettingsCmdAddPointTable) -> SettingsCmdTableCreation
"""
SettingsCmdTableCreation = None
class SettingsCmdAddPressurePartPlanLabel(SettingsPressureNetwork):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddPressurePartProfLabel(SettingsPressureNetwork):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddPressurePartsToProf(SettingsPressureNetwork):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddPressurePipeTable(SettingsPressureNetwork):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
TableCreation = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: TableCreation(self: SettingsCmdAddPressurePipeTable) -> SettingsCmdTableCreation
"""
SettingsCmdTableCreation = None
class SettingsCmdAddPressurePlanLabels(SettingsPressureNetwork):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddPressureProfLabels(SettingsPressureNetwork):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsProfileView(SettingsAmbient):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
Creation = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Creation(self: SettingsProfileView) -> SettingsCreation
"""
NameFormat = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: NameFormat(self: SettingsProfileView) -> SettingsNameFormat
"""
ProjectionLabelPlacement = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: ProjectionLabelPlacement(self: SettingsProfileView) -> SettingsProjectionLabelPlacement
"""
SplitOptions = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: SplitOptions(self: SettingsProfileView) -> SettingsSplitOptions
"""
StackedOptions = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: StackedOptions(self: SettingsProfileView) -> SettingsStackedOptions
"""
Styles = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Styles(self: SettingsProfileView) -> SettingsStyles
"""
SettingsCreation = None
SettingsNameFormat = None
SettingsProjectionLabelPlacement = None
SettingsSplitOptions = None
SettingsStackedOptions = None
SettingsStyles = None
class SettingsCmdAddProfileViewDepthLbl(SettingsProfileView):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddProfileViewStaElevLbl(SettingsProfileView):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsSectionView(SettingsAmbient):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
NameFormat = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: NameFormat(self: SettingsSectionView) -> SettingsNameFormat
"""
ProjectionLabelPlacement = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: ProjectionLabelPlacement(self: SettingsSectionView) -> SettingsProjectionLabelPlacement
"""
SectionViewCreation = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: SectionViewCreation(self: SettingsSectionView) -> SettingsSectionViewCreation
"""
Styles = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Styles(self: SettingsSectionView) -> SettingsStyles
"""
SettingsNameFormat = None
SettingsProjectionLabelPlacement = None
SettingsSectionViewCreation = None
SettingsStyles = None
class SettingsCmdAddSectionViewGradeLbl(SettingsSectionView):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddSectionViewOffElevLbl(SettingsSectionView):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddSegmentLabel(SettingsGeneral):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddSegmentLabels(SettingsGeneral):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddSpanningPipePlanLabel(SettingsPipeNetwork):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddSpanningPipeProfLabel(SettingsPipeNetwork):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddSpotElevLabelsOnGrid(SettingsSurface):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddSurfaceBoundaries(SettingsSurface):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
DataOptions = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: DataOptions(self: SettingsCmdAddSurfaceBoundaries) -> SettingsCmdAddDataOptions
"""
SettingsCmdAddDataOptions = None
class SettingsCmdAddSurfaceBreaklines(SettingsSurface):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
DataOptions = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: DataOptions(self: SettingsCmdAddSurfaceBreaklines) -> SettingsCmdAddDataOptions
"""
SettingsCmdAddDataOptions = None
class SettingsCmdAddSurfaceContours(SettingsSurface):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
AddDataOptions = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: AddDataOptions(self: SettingsCmdAddSurfaceContours) -> SettingsCmdAddDataOptions
"""
SettingsCmdAddDataOptions = None
class SettingsCmdAddSurfaceDemFile(SettingsSurface):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
ImportOptions = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: ImportOptions(self: SettingsCmdAddSurfaceDemFile) -> SettingsCmdImportOptions
"""
SettingsCmdImportOptions = None
class SettingsCmdAddSurfaceDrawingObjects(SettingsSurface):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
DataOptions = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: DataOptions(self: SettingsCmdAddSurfaceDrawingObjects) -> SettingsCmdAddDataOptions
"""
SettingsCmdAddDataOptions = None
class SettingsCmdAddSurfaceFigSurveyQuery(SettingsSurface):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
DataOptions = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: DataOptions(self: SettingsCmdAddSurfaceFigSurveyQuery) -> SettingsCmdAddDataOptions
"""
SettingsCmdAddDataOptions = None
class SettingsCmdAddSurfacePointSurveyQuery(SettingsSurface):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddSurfaceSlopeLabel(SettingsSurface):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddSurfaceSpotElevLabel(SettingsSurface):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsSurvey(SettingsAmbient):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
Styles = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Styles(self: SettingsSurvey) -> SettingsStyles
"""
SettingsStyles = None
class SettingsCmdAddSvFigureLabel(SettingsSurvey):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddSvFigureSegmentLabel(SettingsSurvey):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddSvFigureSegmentLabels(SettingsSurvey):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddTotalVolumeTable(SettingsQuantityTakeoff):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
TableCreation = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: TableCreation(self: SettingsCmdAddTotalVolumeTable) -> SettingsCmdTableCreation
"""
SettingsCmdTableCreation = None
class SettingsCmdAddWidening(SettingsAlignment):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
LinearTransitionAroundCurves = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: LinearTransitionAroundCurves(self: SettingsCmdAddWidening) -> SettingsCmdLinearTransitionAroundCurves
"""
WideningOptions = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: WideningOptions(self: SettingsCmdAddWidening) -> SettingsCmdWideningOptions
"""
SettingsCmdLinearTransitionAroundCurves = None
SettingsCmdWideningOptions = None
class SettingsCmdAssignPayItemToArea(SettingsQuantityTakeoff):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
AssignPayItemToAreaOption = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: AssignPayItemToAreaOption(self: SettingsCmdAssignPayItemToArea) -> SettingsCmdAssignPayItemToAreaOptions
"""
SettingsCmdAssignPayItemToAreaOptions = None
class SettingsCmdCatchmentArea(SettingsSurface):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
DischargePointStyle = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: DischargePointStyle(self: SettingsCmdCatchmentArea) -> PropertyString
"""
DischargePointStyleId = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: DischargePointStyleId(self: SettingsCmdCatchmentArea) -> PropertyObjectId
"""
DisplayDisChargePoint = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: DisplayDisChargePoint(self: SettingsCmdCatchmentArea) -> PropertyBoolean
"""
Layer = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Layer(self: SettingsCmdCatchmentArea) -> PropertyLayer
"""
ObjectType = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: ObjectType(self: SettingsCmdCatchmentArea) -> PropertyEnum[CatchmentObjectType]
"""
class SettingsCmdComputeMaterials(SettingsQuantityTakeoff):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
DefineMaterialOption = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: DefineMaterialOption(self: SettingsCmdComputeMaterials) -> SettingsCmdDefineMaterial
"""
SettingsCmdDefineMaterial = None
class SettingsCmdConvertPointstoSdskPoints(SettingsPoint):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
Layer = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Layer(self: SettingsCmdConvertPointstoSdskPoints) -> SettingsCmdLayer
"""
SettingsCmdLayer = None
class SettingsCorridor(SettingsAmbient):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
NameFormat = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: NameFormat(self: SettingsCorridor) -> SettingsNameFormat
"""
RegionHighlightGraphics = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: RegionHighlightGraphics(self: SettingsCorridor) -> SettingsRegionHighlightGraphics
"""
Styles = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Styles(self: SettingsCorridor) -> SettingsStyles
"""
SettingsNameFormat = None
SettingsRegionHighlightGraphics = None
SettingsStyles = None
class SettingsCmdCorridorExtractSurfaces(SettingsCorridor):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdCreateAlignFromCorridor(SettingsCorridor):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
AlignmentTypeOption = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: AlignmentTypeOption(self: SettingsCmdCreateAlignFromCorridor) -> SettingsCmdAlignmentTypeOption
"""
CriteriaBasedDesignOptions = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: CriteriaBasedDesignOptions(self: SettingsCmdCreateAlignFromCorridor) -> SettingsCmdCriteriaBasedDesignOptions
"""
ProfileCreationOption = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: ProfileCreationOption(self: SettingsCmdCreateAlignFromCorridor) -> SettingsCmdProfileCreationOption
"""
SettingsCmdAlignmentTypeOption = None
SettingsCmdCriteriaBasedDesignOptions = None
SettingsCmdProfileCreationOption = None
class SettingsCmdCreateAlignFromNetwork(SettingsPipeNetwork):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
AlignmentTypeOption = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: AlignmentTypeOption(self: SettingsCmdCreateAlignFromNetwork) -> SettingsCmdAlignmentTypeOption
"""
SettingsCmdAlignmentTypeOption = None
class SettingsCmdCreateAlignFromPressureNW(SettingsPressureNetwork):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
AlignmentTypeOption = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: AlignmentTypeOption(self: SettingsCmdCreateAlignFromPressureNW) -> SettingsCmdAlignmentTypeOption
"""
SettingsCmdAlignmentTypeOption = None
class SettingsCmdCreateAlignmentEntities(SettingsAlignment):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
AlignmentTypeOption = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: AlignmentTypeOption(self: SettingsCmdCreateAlignmentEntities) -> SettingsCmdAlignmentTypeOption
"""
CreateFromEntities = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: CreateFromEntities(self: SettingsCmdCreateAlignmentEntities) -> SettingsCmdCreateFromEntities
"""
SettingsCmdAlignmentTypeOption = None
SettingsCmdCreateFromEntities = None
class SettingsCmdCreateAlignmentLayout(SettingsAlignment):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
AlignmentTypeOption = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: AlignmentTypeOption(self: SettingsCmdCreateAlignmentLayout) -> SettingsCmdAlignmentTypeOption
"""
CurveAndSpiralSettings = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: CurveAndSpiralSettings(self: SettingsCmdCreateAlignmentLayout) -> SettingsCmdCurveAndSpiralSettings
"""
CurveTessellationOption = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: CurveTessellationOption(self: SettingsCmdCreateAlignmentLayout) -> SettingsCmdCurveTessellationOption
"""
RegressionGraphOption = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: RegressionGraphOption(self: SettingsCmdCreateAlignmentLayout) -> SettingsCmdRegressionGraphOption
"""
SettingsCmdAlignmentTypeOption = None
SettingsCmdCurveAndSpiralSettings = None
SettingsCmdCurveTessellationOption = None
SettingsCmdRegressionGraphOption = None
class SettingsCmdCreateAlignmentReference(SettingsAlignment):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdCreateArcByBestFit(SettingsGeneral):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
CurveTessellationOption = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: CurveTessellationOption(self: SettingsCmdCreateArcByBestFit) -> SettingsCmdCurveTessellationOption
"""
RegressionGraphOption = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: RegressionGraphOption(self: SettingsCmdCreateArcByBestFit) -> SettingsCmdRegressionGraphOption
"""
SettingsCmdCurveTessellationOption = None
SettingsCmdRegressionGraphOption = None
class SettingsCmdCreateAssembly(SettingsAssembly):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdCreateAssemblyTool(SettingsAssembly):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdCreateCantView(SettingsCantView):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdCreateCatchmentFromObject(SettingsCatchment):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
Catchment = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Catchment(self: SettingsCmdCreateCatchmentFromObject) -> SettingsCmdCatchment
"""
ChannelFlow = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: ChannelFlow(self: SettingsCmdCreateCatchmentFromObject) -> SettingsCmdChannelFlow
"""
HydrologicalProperties = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: HydrologicalProperties(self: SettingsCmdCreateCatchmentFromObject) -> SettingsCmdHydrologicalProperties
"""
ShallowConcentratedFlow = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: ShallowConcentratedFlow(self: SettingsCmdCreateCatchmentFromObject) -> SettingsCmdShallowConcentratedFlow
"""
SheetFlow = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: SheetFlow(self: SettingsCmdCreateCatchmentFromObject) -> SettingsCmdSheetFlow
"""
TimeOfConcentrationMethod = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: TimeOfConcentrationMethod(self: SettingsCmdCreateCatchmentFromObject) -> PropertyEnum[CatchmentTimeOfConcentrationMethodType]
"""
SettingsCmdCatchment = None
SettingsCmdChannelFlow = None
SettingsCmdHydrologicalProperties = None
SettingsCmdShallowConcentratedFlow = None
SettingsCmdSheetFlow = None
class SettingsCmdCreateCatchmentFromSurface(SettingsCatchment):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
Catchment = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Catchment(self: SettingsCmdCreateCatchmentFromSurface) -> SettingsCmdCatchment
"""
ChannelFlow = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: ChannelFlow(self: SettingsCmdCreateCatchmentFromSurface) -> SettingsCmdChannelFlow
"""
HydrologicalProperties = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: HydrologicalProperties(self: SettingsCmdCreateCatchmentFromSurface) -> SettingsCmdHydrologicalProperties
"""
ShallowConcentratedFlow = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: ShallowConcentratedFlow(self: SettingsCmdCreateCatchmentFromSurface) -> SettingsCmdShallowConcentratedFlow
"""
SheetFlow = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: SheetFlow(self: SettingsCmdCreateCatchmentFromSurface) -> SettingsCmdSheetFlow
"""
TimeOfConcentrationMethod = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: TimeOfConcentrationMethod(self: SettingsCmdCreateCatchmentFromSurface) -> PropertyEnum[CatchmentTimeOfConcentrationMethodType]
"""
SettingsCmdCatchment = None
SettingsCmdChannelFlow = None
SettingsCmdHydrologicalProperties = None
SettingsCmdShallowConcentratedFlow = None
SettingsCmdSheetFlow = None
class SettingsCmdCreateCatchmentGroup(SettingsCatchment):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdCreateCorridor(SettingsCorridor):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
AssemblyInsertion = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: AssemblyInsertion(self: SettingsCmdCreateCorridor) -> SettingsCmdAssemblyInsertion
"""
SettingsCmdAssemblyInsertion = None
class SettingsGrading(SettingsAmbient):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
NameFormat = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: NameFormat(self: SettingsGrading) -> SettingsNameFormat
"""
Styles = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Styles(self: SettingsGrading) -> SettingsStyles
"""
SettingsNameFormat = None
SettingsStyles = None
class SettingsCmdCreateFeatureLineFromAlign(SettingsGrading):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
FeatureLineCreation = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: FeatureLineCreation(self: SettingsCmdCreateFeatureLineFromAlign) -> SettingsCmdFeatureLineCreation
"""
SettingsCmdFeatureLineCreation = None
class SettingsCmdCreateFeatureLines(SettingsGrading):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
FeatureLineCreation = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: FeatureLineCreation(self: SettingsCmdCreateFeatureLines) -> SettingsCmdFeatureLineCreation
"""
SettingsCmdFeatureLineCreation = None
class SettingsCmdCreateFlowSegment(SettingsCatchment):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
ChannelFlow = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: ChannelFlow(self: SettingsCmdCreateFlowSegment) -> SettingsCmdChannelFlow
"""
ShallowConcentratedFlow = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: ShallowConcentratedFlow(self: SettingsCmdCreateFlowSegment) -> SettingsCmdShallowConcentratedFlow
"""
SheetFlow = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: SheetFlow(self: SettingsCmdCreateFlowSegment) -> SettingsCmdSheetFlow
"""
SettingsCmdChannelFlow = None
SettingsCmdShallowConcentratedFlow = None
SettingsCmdSheetFlow = None
class SettingsCmdCreateGrading(SettingsGrading):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
GradingCreation = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: GradingCreation(self: SettingsCmdCreateGrading) -> SettingsCmdGradingCreation
"""
SettingsCmdGradingCreation = None
class SettingsCmdCreateGradingGroup(SettingsGrading):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
GradingGroupCreation = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: GradingGroupCreation(self: SettingsCmdCreateGradingGroup) -> SettingsCmdGradingGroupCreation
"""
SettingsCmdGradingGroupCreation = None
class SettingsCmdCreateInterferenceCheck(SettingsPipeNetwork):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
InterferenceCriteria = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: InterferenceCriteria(self: SettingsCmdCreateInterferenceCheck) -> SettingsCmdInterferenceCriteria
"""
SettingsCmdInterferenceCriteria = None
class SettingsCmdCreateIntersection(SettingsIntersection):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
AssemblyInsertion = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: AssemblyInsertion(self: SettingsCmdCreateIntersection) -> SettingsCmdAssemblyInsertion
"""
CrossSlopes = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: CrossSlopes(self: SettingsCmdCreateIntersection) -> SettingsCmdCrossSlopes
"""
CurbReturnParameters = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: CurbReturnParameters(self: SettingsCmdCreateIntersection) -> SettingsCmdCurbReturnParameters
"""
CurbReturnProfileRules = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: CurbReturnProfileRules(self: SettingsCmdCreateIntersection) -> SettingsCmdCurbReturnProfileRules
"""
IntersectionOptions = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: IntersectionOptions(self: SettingsCmdCreateIntersection) -> SettingsCmdIntersectionOptions
"""
Offsets = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Offsets(self: SettingsCmdCreateIntersection) -> SettingsCmdOffsets
"""
SecondaryRoadProfileRules = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: SecondaryRoadProfileRules(self: SettingsCmdCreateIntersection) -> SettingsCmdSecondaryRoadProfileRules
"""
WideningParameters = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: WideningParameters(self: SettingsCmdCreateIntersection) -> SettingsCmdWideningParameters
"""
SettingsCmdAssemblyInsertion = None
SettingsCmdCrossSlopes = None
SettingsCmdCurbReturnParameters = None
SettingsCmdCurbReturnProfileRules = None
SettingsCmdIntersectionOptions = None
SettingsCmdOffsets = None
SettingsCmdSecondaryRoadProfileRules = None
SettingsCmdWideningParameters = None
class SettingsCmdCreateLineByBestFit(SettingsGeneral):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
CurveTessellationOption = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: CurveTessellationOption(self: SettingsCmdCreateLineByBestFit) -> SettingsCmdCurveTessellationOption
"""
RegressionGraphOption = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: RegressionGraphOption(self: SettingsCmdCreateLineByBestFit) -> SettingsCmdRegressionGraphOption
"""
SettingsCmdCurveTessellationOption = None
SettingsCmdRegressionGraphOption = None
class SettingsMassHaulView(SettingsAmbient):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
MassHaulCreation = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: MassHaulCreation(self: SettingsMassHaulView) -> SettingsMassHaulCreation
"""
NameFormat = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: NameFormat(self: SettingsMassHaulView) -> SettingsNameFormat
"""
Styles = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Styles(self: SettingsMassHaulView) -> SettingsStyles
"""
SettingsMassHaulCreation = None
SettingsNameFormat = None
SettingsStyles = None
class SettingsCmdCreateMassHaulDiagram(SettingsMassHaulView):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
MassHaulCreation = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: MassHaulCreation(self: SettingsCmdCreateMassHaulDiagram) -> SettingsCmdMassHaulCreation
"""
SettingsCmdMassHaulCreation = None
class SettingsCmdCreateMultipleProfileView(SettingsProfileView):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
MultipleProfileViewCreation = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: MultipleProfileViewCreation(self: SettingsCmdCreateMultipleProfileView) -> SettingsCmdMultipleProfileViewCreation
"""
SettingsCmdMultipleProfileViewCreation = None
class SettingsCmdCreateMultipleSectionView(SettingsSectionView):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
MultipleSectionViewCreation = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: MultipleSectionViewCreation(self: SettingsCmdCreateMultipleSectionView) -> SettingsCmdMultipleSectionViewCreation
"""
TableCreation = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: TableCreation(self: SettingsCmdCreateMultipleSectionView) -> SettingsCmdTableCreation
"""
SettingsCmdMultipleSectionViewCreation = None
SettingsCmdTableCreation = None
class SettingsCmdCreateNetwork(SettingsPipeNetwork):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
DefaultLayoutCommand = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: DefaultLayoutCommand(self: SettingsCmdCreateNetwork) -> PropertyEnum[NetworkDefaultLayoutCommandType]
"""
LabelNewParts = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: LabelNewParts(self: SettingsCmdCreateNetwork) -> SettingsCmdLabelNewParts
"""
SettingsCmdLabelNewParts = None
class SettingsCmdCreateNetworkFromObject(SettingsPipeNetwork):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdCreateNetworkPartsList(SettingsPipeNetwork):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdCreateNetworkPartsListFull(SettingsPipeNetwork):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdCreateNetworkReference(SettingsPipeNetwork):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdCreateOffsetAlignment(SettingsAlignment):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
OffsetAlignmentOptions = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: OffsetAlignmentOptions(self: SettingsCmdCreateOffsetAlignment) -> SettingsCmdOffsetAlignmentOptions
"""
SettingsCmdOffsetAlignmentOptions = None
class SettingsCmdCreateParabolaByBestFit(SettingsGeneral):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
CurveTessellationOption = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: CurveTessellationOption(self: SettingsCmdCreateParabolaByBestFit) -> SettingsCmdCurveTessellationOption
"""
RegressionGraphOption = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: RegressionGraphOption(self: SettingsCmdCreateParabolaByBestFit) -> SettingsCmdRegressionGraphOption
"""
SettingsCmdCurveTessellationOption = None
SettingsCmdRegressionGraphOption = None
class SettingsCmdCreateParcelByLayout(SettingsParcel):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
AutomaticLayout = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: AutomaticLayout(self: SettingsCmdCreateParcelByLayout) -> SettingsCmdAutomaticLayout
"""
ConvertFromEntities = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: ConvertFromEntities(self: SettingsCmdCreateParcelByLayout) -> SettingsCmdConvertFromEntities
"""
ParcelSizing = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: ParcelSizing(self: SettingsCmdCreateParcelByLayout) -> SettingsCmdParcelSizing
"""
PreviewGraphics = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: PreviewGraphics(self: SettingsCmdCreateParcelByLayout) -> SettingsCmdPreviewGraphics
"""
SettingsCmdAutomaticLayout = None
SettingsCmdConvertFromEntities = None
SettingsCmdParcelSizing = None
SettingsCmdPreviewGraphics = None
class SettingsCmdCreateParcelFromObjects(SettingsParcel):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
ConvertFromEntities = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: ConvertFromEntities(self: SettingsCmdCreateParcelFromObjects) -> SettingsCmdConvertFromEntities
"""
SettingsCmdConvertFromEntities = None
class SettingsCmdCreateParcelROW(SettingsParcel):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
CleanupAtAlignmentIntersections = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: CleanupAtAlignmentIntersections(self: SettingsCmdCreateParcelROW) -> SettingsCmdCleanupAtAlignmentIntersections
"""
CleanupAtParcelBoundaries = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: CleanupAtParcelBoundaries(self: SettingsCmdCreateParcelROW) -> SettingsCmdCleanupAtParcelBoundaries
"""
CreateParcelRightOfWay = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: CreateParcelRightOfWay(self: SettingsCmdCreateParcelROW) -> SettingsCmdCreateParcelRightOfWay
"""
SettingsCmdCleanupAtAlignmentIntersections = None
SettingsCmdCleanupAtParcelBoundaries = None
SettingsCmdCreateParcelRightOfWay = None
class SettingsCmdCreatePointCloud(SettingsPointCloud):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
DefaultLayer = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: DefaultLayer(self: SettingsCmdCreatePointCloud) -> SettingsCmdDefaultLayer
"""
FileFormat = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: FileFormat(self: SettingsCmdCreatePointCloud) -> PropertyEnum[PointCloudDefaultFileExtensionType]
"""
SettingsCmdDefaultLayer = None
class SettingsCmdCreatePointGroup(SettingsPoint):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdCreatePoints(SettingsPoint):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
Layer = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Layer(self: SettingsCmdCreatePoints) -> SettingsCmdLayer
"""
PointIdentity = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: PointIdentity(self: SettingsCmdCreatePoints) -> SettingsCmdPointIdentity
"""
PointsCreation = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: PointsCreation(self: SettingsCmdCreatePoints) -> SettingsCmdPointsCreation
"""
SettingsCmdLayer = None
SettingsCmdPointIdentity = None
SettingsCmdPointsCreation = None
class SettingsCmdCreatePointsFromCorridor(SettingsCorridor):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdCreatePolylineFromCorridor(SettingsCorridor):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsSuperelevationView(SettingsAmbient):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
NameFormat = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: NameFormat(self: SettingsSuperelevationView) -> SettingsNameFormat
"""
Styles = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Styles(self: SettingsSuperelevationView) -> SettingsStyles
"""
SettingsNameFormat = None
SettingsStyles = None
class SettingsCmdCreatePolylineFromSuper(SettingsSuperelevationView):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdCreatePressureFromIndModel(SettingsPressureNetwork):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdCreatePressureNetwork(SettingsPressureNetwork):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
DepthOfCover = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: DepthOfCover(self: SettingsCmdCreatePressureNetwork) -> SettingsCmdDepthOfCover
"""
LabelNewParts = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: LabelNewParts(self: SettingsCmdCreatePressureNetwork) -> SettingsCmdLabelNewParts
"""
SettingsCmdDepthOfCover = None
SettingsCmdLabelNewParts = None
class SettingsCmdCreatePressurePartList(SettingsPressureNetwork):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdCreatePressurePartListFull(SettingsPressureNetwork):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdCreateProfileFromCorridor(SettingsCorridor):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
CriteriaBasedDesignOptions = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: CriteriaBasedDesignOptions(self: SettingsCmdCreateProfileFromCorridor) -> SettingsCmdCriteriaBasedDesignOptions
"""
SettingsCmdCriteriaBasedDesignOptions = None
class SettingsProfile(SettingsAmbient):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
CriteriaBasedDesignOptions = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: CriteriaBasedDesignOptions(self: SettingsProfile) -> SettingsCriteriaBasedDesignOptions
"""
DefaultNameFormat = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: DefaultNameFormat(self: SettingsProfile) -> SettingsDefaultNameFormat
"""
ProfilesCreation = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: ProfilesCreation(self: SettingsProfile) -> SettingsProfileCreation
"""
StyleSettings = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: StyleSettings(self: SettingsProfile) -> SettingsStyles
"""
SettingsCriteriaBasedDesignOptions = None
SettingsDefaultNameFormat = None
SettingsProfileCreation = None
SettingsStyles = None
class SettingsCmdCreateProfileFromFile(SettingsProfile):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdCreateProfileFromSurface(SettingsProfile):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
Geometry = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Geometry(self: SettingsCmdCreateProfileFromSurface) -> SettingsCmdGeometry
"""
SettingsCmdGeometry = None
class SettingsCmdCreateProfileLayout(SettingsProfile):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
CurveTessellationOption = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: CurveTessellationOption(self: SettingsCmdCreateProfileLayout) -> SettingsCmdCurveTessellationOption
"""
RegressionGraphOption = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: RegressionGraphOption(self: SettingsCmdCreateProfileLayout) -> SettingsCmdRegressionGraphOption
"""
SettingsCmdCurveTessellationOption = None
SettingsCmdRegressionGraphOption = None
class SettingsCmdCreateProfileReference(SettingsProfile):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdCreateProfileView(SettingsProfileView):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdCreateQuickProfile(SettingsProfile):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
QuickProfile = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: QuickProfile(self: SettingsCmdCreateQuickProfile) -> SettingsCmdQuickProfile
"""
SettingsCmdQuickProfile = None
class SettingsSampleLine(SettingsAmbient):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
NameFormat = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: NameFormat(self: SettingsSampleLine) -> SettingsNameFormat
"""
Styles = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Styles(self: SettingsSampleLine) -> SettingsStyles
"""
SettingsNameFormat = None
SettingsStyles = None
class SettingsCmdCreateSampleLines(SettingsSampleLine):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
AdditionalSampleControls = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: AdditionalSampleControls(self: SettingsCmdCreateSampleLines) -> SettingsCmdAdditionalSampleControls
"""
Miscellaneous = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Miscellaneous(self: SettingsCmdCreateSampleLines) -> SettingsCmdMiscellaneous
"""
SamplingIncrements = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: SamplingIncrements(self: SettingsCmdCreateSampleLines) -> SettingsCmdSamplingIncrements
"""
SwathWidths = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: SwathWidths(self: SettingsCmdCreateSampleLines) -> SettingsCmdSwathWidths
"""
SettingsCmdAdditionalSampleControls = None
SettingsCmdMiscellaneous = None
SettingsCmdSamplingIncrements = None
SettingsCmdSwathWidths = None
class SettingsCmdCreateSectionSheets(SettingsSectionView):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
SheetCreation = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: SheetCreation(self: SettingsCmdCreateSectionSheets) -> SettingsCmdSheetCreation
"""
SettingsCmdSheetCreation = None
class SettingsCmdCreateSectionView(SettingsSectionView):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
TableCreation = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: TableCreation(self: SettingsCmdCreateSectionView) -> SettingsCmdTableCreation
"""
SettingsCmdTableCreation = None
class SettingsViewFrameGroup(SettingsAmbient):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
Information = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Information(self: SettingsViewFrameGroup) -> SettingsInformation
"""
NameFormat = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: NameFormat(self: SettingsViewFrameGroup) -> SettingsNameFormat
"""
Styles = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Styles(self: SettingsViewFrameGroup) -> SettingsStyles
"""
SettingsInformation = None
SettingsNameFormat = None
SettingsStyles = None
class SettingsCmdCreateSheets(SettingsViewFrameGroup):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
SheetCreation = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: SheetCreation(self: SettingsCmdCreateSheets) -> SettingsCmdSheetCreation
"""
SettingsCmdSheetCreation = None
class SettingsCmdCreateSimpleCorridor(SettingsCorridor):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
AssemblyInsertion = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: AssemblyInsertion(self: SettingsCmdCreateSimpleCorridor) -> SettingsCmdAssemblyInsertion
"""
SettingsCmdAssemblyInsertion = None
class SettingsCmdCreateSite(SettingsParcel):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
Alignment = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Alignment(self: SettingsCmdCreateSite) -> SettingsCmdAlignment
"""
FeatureLine = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: FeatureLine(self: SettingsCmdCreateSite) -> SettingsCmdFeatureLine
"""
Parcel = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Parcel(self: SettingsCmdCreateSite) -> SettingsCmdParcel
"""
SettingsCmdAlignment = None
SettingsCmdFeatureLine = None
SettingsCmdParcel = None
class SettingsSubassembly(SettingsAmbient):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
DefaultStyles = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: DefaultStyles(self: SettingsSubassembly) -> SettingsDefaultStyles
"""
NameFormat = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: NameFormat(self: SettingsSubassembly) -> SettingsNameFormat
"""
SettingsDefaultStyles = None
SettingsNameFormat = None
class SettingsCmdCreateSubassemblyTool(SettingsSubassembly):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
SubassemblyOptions = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: SubassemblyOptions(self: SettingsCmdCreateSubassemblyTool) -> SettingsCmdSubassemblyOptions
"""
SettingsCmdSubassemblyOptions = None
class SettingsCmdCreateSubFromPline(SettingsSubassembly):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
CreateFromEntities = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: CreateFromEntities(self: SettingsCmdCreateSubFromPline) -> SettingsCmdCreateFromEntities
"""
SettingsCmdCreateFromEntities = None
class SettingsCmdCreateSuperelevationView(SettingsSuperelevationView):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdCreateSurface(SettingsSurface):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
BuildOptions = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: BuildOptions(self: SettingsCmdCreateSurface) -> SettingsCmdBuildOptions
"""
NameFormat = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: NameFormat(self: SettingsCmdCreateSurface) -> SettingsNameFormat
"""
SurfaceCreation = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: SurfaceCreation(self: SettingsCmdCreateSurface) -> SettingsCmdSurfaceCreation
"""
SettingsCmdBuildOptions = None
SettingsCmdSurfaceCreation = None
SettingsNameFormat = None
class SettingsCmdCreateSurfaceFromTIN(SettingsSurface):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdCreateSurfaceGridFromDEM(SettingsSurface):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
BuildOptions = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: BuildOptions(self: SettingsCmdCreateSurfaceGridFromDEM) -> SettingsCmdBuildOptions
"""
ImportOptions = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: ImportOptions(self: SettingsCmdCreateSurfaceGridFromDEM) -> SettingsCmdImportOptions
"""
SettingsCmdBuildOptions = None
SettingsCmdImportOptions = None
class SettingsCmdCreateSurfaceReference(SettingsSurface):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
NameFormat = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: NameFormat(self: SettingsCmdCreateSurfaceReference) -> SettingsNameFormat
"""
SettingsNameFormat = None
class SettingsCmdCreateSurfaceWaterdrop(SettingsSurface):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
WaterdropMarker = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: WaterdropMarker(self: SettingsCmdCreateSurfaceWaterdrop) -> SettingsCmdWaterdropMarker
"""
WaterdropPath = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: WaterdropPath(self: SettingsCmdCreateSurfaceWaterdrop) -> SettingsCmdWaterdropPath
"""
SettingsCmdWaterdropMarker = None
SettingsCmdWaterdropPath = None
class SettingsCmdCreateViewFrames(SettingsViewFrameGroup):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
ViewFrameCreation = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: ViewFrameCreation(self: SettingsCmdCreateViewFrames) -> SettingsCmdViewFrameCreation
"""
SettingsCmdViewFrameCreation = None
class SettingsCmdDrawFeatureLine(SettingsGrading):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
FeatureLineCreation = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: FeatureLineCreation(self: SettingsCmdDrawFeatureLine) -> SettingsCmdFeatureLineCreation
"""
SettingsCmdFeatureLineCreation = None
class SettingsCmdEditFlowSegments(SettingsCatchment):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
ChannelFlow = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: ChannelFlow(self: SettingsCmdEditFlowSegments) -> SettingsCmdChannelFlow
"""
ShallowConcentratedFlow = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: ShallowConcentratedFlow(self: SettingsCmdEditFlowSegments) -> SettingsCmdShallowConcentratedFlow
"""
SheetFlow = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: SheetFlow(self: SettingsCmdEditFlowSegments) -> SettingsCmdSheetFlow
"""
SettingsCmdChannelFlow = None
SettingsCmdShallowConcentratedFlow = None
SettingsCmdSheetFlow = None
class SettingsCmdEditInStormSewers(SettingsPipeNetwork):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdEditSVGroupStyle(SettingsSectionView):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdExportParcelAnalysis(SettingsParcel):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
ParcelAnalysis = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: ParcelAnalysis(self: SettingsCmdExportParcelAnalysis) -> SettingsCmdParcelAnalysis
"""
SettingsCmdParcelAnalysis = None
class SettingsCmdExportStormSewerData(SettingsPipeNetwork):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdFeatureLinesFromCorridor(SettingsCorridor):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
FeatureLineCreation = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: FeatureLineCreation(self: SettingsCmdFeatureLinesFromCorridor) -> SettingsCmdFeatureLineCreation
"""
SettingsCmdFeatureLineCreation = None
class SettingsCmdFitCurveFeature(SettingsGrading):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
FeatureLineFitCurve = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: FeatureLineFitCurve(self: SettingsCmdFitCurveFeature) -> SettingsCmdFeatureLineFitCurve
"""
SettingsCmdFeatureLineFitCurve = None
class SettingsCmdGenerateQuantitiesReport(SettingsQuantityTakeoff):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
DisplayXmlReport = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: DisplayXmlReport(self: SettingsCmdGenerateQuantitiesReport) -> PropertyBoolean
"""
class SettingsCmdGradingElevEditor(SettingsGrading):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
GradingElevationEditor = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: GradingElevationEditor(self: SettingsCmdGradingElevEditor) -> SettingsCmdGradingElevationEditor
"""
SettingsCmdGradingElevationEditor = None
class SettingsCmdGradingTools(SettingsGrading):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
GradingLayoutTools = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: GradingLayoutTools(self: SettingsCmdGradingTools) -> SettingsCmdGradingLayoutTools
"""
SettingsCmdGradingLayoutTools = None
class SettingsCmdGradingVolumeTools(SettingsGrading):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
LimitFeatureSelectionToCurrentGroup = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: LimitFeatureSelectionToCurrentGroup(self: SettingsCmdGradingVolumeTools) -> PropertyBoolean
"""
RaiseLowerElevationIncrement = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: RaiseLowerElevationIncrement(self: SettingsCmdGradingVolumeTools) -> PropertyDouble
"""
class SettingsCmdImportBuildingSite(SettingsBuildingSite):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdImportGISData(SettingsGeneral):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
PipeNetwork = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: PipeNetwork(self: SettingsCmdImportGISData) -> SettingsCmdPipeNetwork
"""
SettingsCmdPipeNetwork = None
class SettingsCmdImportStormSewerData(SettingsPipeNetwork):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdJoinFeatures(SettingsGrading):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
FeatureLineJoin = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: FeatureLineJoin(self: SettingsCmdJoinFeatures) -> SettingsCmdFeatureLineJoin
"""
SettingsCmdFeatureLineJoin = None
class SettingsCmdLayoutSectionViewGroup(SettingsSectionView):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdMapCheck(SettingsGeneral):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
Mapcheck = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Mapcheck(self: SettingsCmdMapCheck) -> SettingsCmdMapcheck
"""
SettingsCmdMapcheck = None
class SettingsCmdMinimizeSurfaceFlatAreas(SettingsSurface):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
AddPointsToFlatEdges = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: AddPointsToFlatEdges(self: SettingsCmdMinimizeSurfaceFlatAreas) -> PropertyBoolean
"""
AddPointsToFlatTriangles = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: AddPointsToFlatTriangles(self: SettingsCmdMinimizeSurfaceFlatAreas) -> PropertyBoolean
"""
FillGapsInContour = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: FillGapsInContour(self: SettingsCmdMinimizeSurfaceFlatAreas) -> PropertyBoolean
"""
SwapEdges = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: SwapEdges(self: SettingsCmdMinimizeSurfaceFlatAreas) -> PropertyBoolean
"""
class SettingsCmdMoveBlockstoAttribElev(SettingsSurface):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdMoveBlocksToSurface(SettingsSurface):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdMoveTextToElevation(SettingsSurface):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdProjectObjectsToMultiSect(SettingsSectionView):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
ObjectSelectionOptions = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: ObjectSelectionOptions(self: SettingsCmdProjectObjectsToMultiSect) -> SettingsCmdObjectSelectionOptions
"""
SettingsCmdObjectSelectionOptions = None
class SettingsCmdProjectObjectsToProf(SettingsProfileView):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdProjectObjectsToSect(SettingsSectionView):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdReAddParcelAreaLabel(SettingsParcel):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdReAddParcelSegmentLabels(SettingsParcel):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdRenamePipeNetworkParts(SettingsPipeNetwork):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdResetAnchorPipe(SettingsPipeNetwork):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdReverseAlignmentDirection(SettingsAlignment):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdRunDepthCheck(SettingsPressureNetwork):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
DepthCheckOption = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: DepthCheckOption(self: SettingsCmdRunDepthCheck) -> SettingsCmdDepthCheckOption
"""
SettingsCmdDepthCheckOption = None
class SettingsCmdRunDesignCheck(SettingsPressureNetwork):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
DesignCheckOption = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: DesignCheckOption(self: SettingsCmdRunDesignCheck) -> SettingsCmdDesignCheckOption
"""
SettingsCmdDesignCheckOption = None
class SettingsCmdShowGeodeticCalculator(SettingsPoint):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdShowPointGroupProperties(SettingsPoint):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdShowSpanningPipes(SettingsPipeNetwork):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdSimplifySurface(SettingsSurface):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
MaximumChangeInElevation = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: MaximumChangeInElevation(self: SettingsCmdSimplifySurface) -> PropertyDouble
"""
PercentageOfPointsToRemove = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: PercentageOfPointsToRemove(self: SettingsCmdSimplifySurface) -> PropertyDouble
"""
RegionOptions = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: RegionOptions(self: SettingsCmdSimplifySurface) -> PropertyEnum[SurfaceRegionOptionsType]
"""
SimplifyMethod = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: SimplifyMethod(self: SettingsCmdSimplifySurface) -> PropertyEnum[SurfaceSimplifyType]
"""
UseMaximumChangeInElevation = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: UseMaximumChangeInElevation(self: SettingsCmdSimplifySurface) -> PropertyBoolean
"""
UsePercentageOfPointsToRemove = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: UsePercentageOfPointsToRemove(self: SettingsCmdSimplifySurface) -> PropertyBoolean
"""
class SettingsCmdSuperimposeProfile(SettingsProfile):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
SuperimposeProfile = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: SuperimposeProfile(self: SettingsCmdSuperimposeProfile) -> SettingsCmdSuperimposeProfileOption
"""
SettingsCmdSuperimposeProfileOption = None
class SettingsCmdSurfaceExportToDem(SettingsSurface):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
ExportOptions = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: ExportOptions(self: SettingsCmdSurfaceExportToDem) -> SettingsCmdExportOptions
"""
SettingsCmdExportOptions = None
class SettingsCmdSurfaceExtractObjects(SettingsSurface):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdTakeOff(SettingsQuantityTakeoff):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
ComputeTakeOffOption = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: ComputeTakeOffOption(self: SettingsCmdTakeOff) -> SettingsCmdComputeTakeOff
"""
SettingsCmdComputeTakeOff = None
class SettingsCmdViewEditCorridorSection(SettingsCorridor):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
GridSettings = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: GridSettings(self: SettingsCmdViewEditCorridorSection) -> SettingsCmdGridSettings
"""
GridTextSettings = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: GridTextSettings(self: SettingsCmdViewEditCorridorSection) -> SettingsCmdGridTextSettings
"""
SectionSliderInMultipleViewports = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: SectionSliderInMultipleViewports(self: SettingsCmdViewEditCorridorSection) -> SettingsCmdSectionSliderInMultipleViewports
"""
ViewEditOptions = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: ViewEditOptions(self: SettingsCmdViewEditCorridorSection) -> SettingsCmdViewEditOptions
"""
SettingsCmdGridSettings = None
SettingsCmdGridTextSettings = None
SettingsCmdSectionSliderInMultipleViewports = None
SettingsCmdViewEditOptions = None
class SettingsCmdVolumesDashboard(SettingsSurface):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
BoundedVolumeCreation = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: BoundedVolumeCreation(self: SettingsCmdVolumesDashboard) -> SettingsCmdBoundedVolumeCreation
"""
BuildOptions = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: BuildOptions(self: SettingsCmdVolumesDashboard) -> SettingsCmdBuildOptions
"""
DynamicHighlightOptions = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: DynamicHighlightOptions(self: SettingsCmdVolumesDashboard) -> SettingsCmdDynamicHighlightOptions
"""
VolumeSurfaceCreation = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: VolumeSurfaceCreation(self: SettingsCmdVolumesDashboard) -> SettingsCmdVolumeSurfaceCreation
"""
SettingsCmdBoundedVolumeCreation = None
SettingsCmdBuildOptions = None
SettingsCmdDynamicHighlightOptions = None
SettingsCmdVolumeSurfaceCreation = None
class SettingsCmdWeedFeatures(SettingsGrading):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
FeatureLineWeed = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: FeatureLineWeed(self: SettingsCmdWeedFeatures) -> SettingsCmdFeatureLineWeed
"""
SettingsCmdFeatureLineWeed = None
class SettingsCoordinateSystem(object):
# no doc
Category = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Category(self: SettingsCoordinateSystem) -> str
"""
Code = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Code(self: SettingsCoordinateSystem) -> str
"""
Datum = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Datum(self: SettingsCoordinateSystem) -> str
"""
Description = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Description(self: SettingsCoordinateSystem) -> str
"""
Projection = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Projection(self: SettingsCoordinateSystem) -> str
"""
Unit = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Unit(self: SettingsCoordinateSystem) -> str
"""
class SettingsDrawing(TreeOidWrapper):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
AbbreviationsSettings = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: AbbreviationsSettings(self: SettingsDrawing) -> SettingsAbbreviation
"""
AmbientSettings = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: AmbientSettings(self: SettingsDrawing) -> SettingsAmbient
"""
ApplyTransformSettings = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: ApplyTransformSettings(self: SettingsDrawing) -> bool
Set: ApplyTransformSettings(self: SettingsDrawing) = value
"""
ObjectLayerSettings = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: ObjectLayerSettings(self: SettingsDrawing) -> SettingsObjectLayers
"""
TransformationSettings = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: TransformationSettings(self: SettingsDrawing) -> SettingsTransformation
"""
UnitZoneSettings = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: UnitZoneSettings(self: SettingsDrawing) -> SettingsUnitZone
"""
class SettingsLandXML(TreeOidWrapper):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
Export = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Export(self: SettingsLandXML) -> SettingsLandXMLExport
"""
Import = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Import(self: SettingsLandXML) -> SettingsLandXMLImport
"""
class SettingsLandXMLExport(TreeOidWrapper):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
AlignmentExport = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: AlignmentExport(self: SettingsLandXMLExport) -> SettingsAlignmentExport
"""
Data = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Data(self: SettingsLandXMLExport) -> SettingsData
"""
FeatureLineExport = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: FeatureLineExport(self: SettingsLandXMLExport) -> SettingsFeatureLineExport
"""
Identification = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Identification(self: SettingsLandXMLExport) -> SettingsIdentification
"""
ParcelExport = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: ParcelExport(self: SettingsLandXMLExport) -> SettingsParcelExport
"""
PointExport = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: PointExport(self: SettingsLandXMLExport) -> SettingsPointExport
"""
SurfaceExport = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: SurfaceExport(self: SettingsLandXMLExport) -> SettingsSurfaceExport
"""
SettingsAlignmentExport = None
SettingsData = None
SettingsFeatureLineExport = None
SettingsIdentification = None
SettingsParcelExport = None
SettingsPointExport = None
SettingsSurfaceExport = None
class SettingsLandXMLImport(TreeOidWrapper):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
AlignmentImport = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: AlignmentImport(self: SettingsLandXMLImport) -> SettingsAlignmentImport
"""
ConflictResolution = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: ConflictResolution(self: SettingsLandXMLImport) -> SettingsConflictResolution
"""
DiameterUnits = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: DiameterUnits(self: SettingsLandXMLImport) -> SettingsDiameterUnits
"""
FeatureLineImport = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: FeatureLineImport(self: SettingsLandXMLImport) -> SettingsFeatureLineImport
"""
PipeNetwork = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: PipeNetwork(self: SettingsLandXMLImport) -> SettingsPipeNetwork
"""
PointImport = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: PointImport(self: SettingsLandXMLImport) -> SettingsPointImport
"""
PropertySetData = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: PropertySetData(self: SettingsLandXMLImport) -> SettingsPropertySetData
"""
Rotation = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Rotation(self: SettingsLandXMLImport) -> SettingsRotation
"""
SurfaceImport = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: SurfaceImport(self: SettingsLandXMLImport) -> SettingsSurfaceImport
"""
Translation = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Translation(self: SettingsLandXMLImport) -> SettingsTranslation
"""
SettingsAlignmentImport = None
SettingsConflictResolution = None
SettingsDiameterUnits = None
SettingsFeatureLineImport = None
SettingsPipeNetwork = None
SettingsPointImport = None
SettingsPropertySetData = None
SettingsRotation = None
SettingsSurfaceImport = None
SettingsTranslation = None
class SettingsMassHaulLine(SettingsAmbient):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsMatchLine(SettingsAmbient):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsObjectLayer(TreeOidWrapper):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
LayerId = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: LayerId(self: SettingsObjectLayer) -> ObjectId
Set: LayerId(self: SettingsObjectLayer) = value
"""
LayerName = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: LayerName(self: SettingsObjectLayer) -> str
Set: LayerName(self: SettingsObjectLayer) = value
"""
Locked = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Locked(self: SettingsObjectLayer) -> bool
Set: Locked(self: SettingsObjectLayer) = value
"""
Modifier = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Modifier(self: SettingsObjectLayer) -> ObjectLayerModifierType
Set: Modifier(self: SettingsObjectLayer) = value
"""
ModifierValue = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: ModifierValue(self: SettingsObjectLayer) -> str
Set: ModifierValue(self: SettingsObjectLayer) = value
"""
ObjectType = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: ObjectType(self: SettingsObjectLayer) -> SettingsObjectLayerType
"""
class SettingsObjectLayers(TreeOidWrapper):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
def GetObjectLayerSetting(self, settingsType):
""" GetObjectLayerSetting(self: SettingsObjectLayers, settingsType: SettingsObjectLayerType) -> SettingsObjectLayer """
pass
ObjectControlledByLayer = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: ObjectControlledByLayer(self: SettingsObjectLayers) -> bool
Set: ObjectControlledByLayer(self: SettingsObjectLayers) = value
"""
class SettingsObjectLayerType(Enum):
""" enum SettingsObjectLayerType, values: Alignment (0), AlignmentLabeling (1), AlignmentTable (2), Appurtenance (56), AppurtenanceLabeling (57), Assembly (3), BuildingSite (53), CantView (58), Catchment (59), CatchmentLabeling (60), Corridor (4), CorridorSection (5), FeatureLine (6), Fitting (61), FittingLabeling (62), GeneralNoteLabel (7), GeneralSegmentLabel (8), Grading (9), GradingLabeling (10), GridSurface (11), GridSurfaceLabeling (12), Interference (13), Intersection (54), IntersectionLabeling (55), MassHaulLine (14), MassHaulView (15), MatchLine (16), MatchLineLabeling (17), MaterialSection (18), MaterialTable (19), Parcel (20), ParcelLabeling (21), ParcelSegment (22), ParcelSegmentLabeling (23), ParcelTable (24), Pipe (25), PipeAndStructureTable (27), PipeLabeling (26), PipeNetworkSection (28), PipeOrStructureProfile (29), PointTable (30), PressureNetworkSection (63), PressurePartProfile (64), PressurePartTable (65), PressurePipe (66), PressurePipeLabeling (67), Profile (31), ProfileLabeling (32), ProfileView (33), ProfileViewLabeling (34), SampleLine (35), SampleLineLabeling (36), Section (37), SectionLabeling (38), SectionView (39), SectionViewLabeling (40), SectionViewQuantityTakeoffTable (41), Sheet (42), Structure (43), StructureLabeling (44), Subassembly (45), SuperelevationView (68), SurfaceLegendTable (46), SurveyFigure (47), SurveyFigureLabeling (69), SurveyFigureSegmentLable (70), SurveyNetwork (48), TinSurface (49), TinSurfaceLabeling (50), ViewFrame (51), ViewFrameLabeling (52) """
Alignment = None
AlignmentLabeling = None
AlignmentTable = None
Appurtenance = None
AppurtenanceLabeling = None
Assembly = None
BuildingSite = None
CantView = None
Catchment = None
CatchmentLabeling = None
Corridor = None
CorridorSection = None
FeatureLine = None
Fitting = None
FittingLabeling = None
GeneralNoteLabel = None
GeneralSegmentLabel = None
Grading = None
GradingLabeling = None
GridSurface = None
GridSurfaceLabeling = None
Interference = None
Intersection = None
IntersectionLabeling = None
MassHaulLine = None
MassHaulView = None
MatchLine = None
MatchLineLabeling = None
MaterialSection = None
MaterialTable = None
Parcel = None
ParcelLabeling = None
ParcelSegment = None
ParcelSegmentLabeling = None
ParcelTable = None
Pipe = None
PipeAndStructureTable = None
PipeLabeling = None
PipeNetworkSection = None
PipeOrStructureProfile = None
PointTable = None
PressureNetworkSection = None
PressurePartProfile = None
PressurePartTable = None
PressurePipe = None
PressurePipeLabeling = None
Profile = None
ProfileLabeling = None
ProfileView = None
ProfileViewLabeling = None
SampleLine = None
SampleLineLabeling = None
Section = None
SectionLabeling = None
SectionView = None
SectionViewLabeling = None
SectionViewQuantityTakeoffTable = None
Sheet = None
Structure = None
StructureLabeling = None
Subassembly = None
SuperelevationView = None
SurfaceLegendTable = None
SurveyFigure = None
SurveyFigureLabeling = None
SurveyFigureSegmentLable = None
SurveyNetwork = None
TinSurface = None
TinSurfaceLabeling = None
value__ = None
ViewFrame = None
ViewFrameLabeling = None
class SettingsPipe(SettingsAmbient):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsPressureAppurtenance(SettingsAmbient):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsPressureFitting(SettingsAmbient):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsPressurePipe(SettingsAmbient):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsRoot(TreeOidWrapper):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
def GetSettings(self):
# Error generating skeleton for function GetSettings: Method must be called on a Type for which Type.IsGenericParameter is false.
AssociateShortcutProjectId = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: AssociateShortcutProjectId(self: SettingsRoot) -> str
Set: AssociateShortcutProjectId(self: SettingsRoot) = value
"""
DrawingSettings = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: DrawingSettings(self: SettingsRoot) -> SettingsDrawing
"""
LandXMLSettings = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: LandXMLSettings(self: SettingsRoot) -> SettingsLandXML
"""
TagSettings = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: TagSettings(self: SettingsRoot) -> SettingsTag
"""
class SettingsSection(SettingsAmbient):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
NameFormat = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: NameFormat(self: SettingsSection) -> SettingsNameFormat
"""
Styles = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Styles(self: SettingsSection) -> SettingsStyles
"""
SettingsNameFormat = None
SettingsStyles = None
class SettingsStructure(SettingsAmbient):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsTag(TreeOidWrapper):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
Creation = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Creation(self: SettingsTag) -> SettingsCreation
"""
Renumbering = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: Renumbering(self: SettingsTag) -> SettingsRenumbering
"""
SettingsCreation = None
SettingsRenumbering = None
class SettingsTransformation(TreeOidWrapper):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
ApplySeaLevelScaleFactor = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: ApplySeaLevelScaleFactor(self: SettingsTransformation) -> bool
Set: ApplySeaLevelScaleFactor(self: SettingsTransformation) = value
"""
GridReferencePoint = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: GridReferencePoint(self: SettingsTransformation) -> Point2d
Set: GridReferencePoint(self: SettingsTransformation) = value
"""
GridRotationPoint = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: GridRotationPoint(self: SettingsTransformation) -> Point2d
Set: GridRotationPoint(self: SettingsTransformation) = value
"""
GridScaleFactor = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: GridScaleFactor(self: SettingsTransformation) -> float
Set: GridScaleFactor(self: SettingsTransformation) = value
"""
GridScaleFactorComputation = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: GridScaleFactorComputation(self: SettingsTransformation) -> GridScaleFactorType
Set: GridScaleFactorComputation(self: SettingsTransformation) = value
"""
LocalReferencePoint = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: LocalReferencePoint(self: SettingsTransformation) -> Point2d
Set: LocalReferencePoint(self: SettingsTransformation) = value
"""
LocalRotationPoint = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: LocalRotationPoint(self: SettingsTransformation) -> Point2d
Set: LocalRotationPoint(self: SettingsTransformation) = value
"""
RotationToGridAzimuth = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: RotationToGridAzimuth(self: SettingsTransformation) -> float
Set: RotationToGridAzimuth(self: SettingsTransformation) = value
"""
RotationToGridNorth = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: RotationToGridNorth(self: SettingsTransformation) -> float
Set: RotationToGridNorth(self: SettingsTransformation) = value
"""
SeaLevelScaleElevation = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: SeaLevelScaleElevation(self: SettingsTransformation) -> float
Set: SeaLevelScaleElevation(self: SettingsTransformation) = value
"""
SpecifyRotationType = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: SpecifyRotationType(self: SettingsTransformation) -> SpecifyRotationType
Set: SpecifyRotationType(self: SettingsTransformation) = value
"""
SpheroidRadius = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: SpheroidRadius(self: SettingsTransformation) -> float
"""
class SettingsUnitZone(TreeOidWrapper):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
@staticmethod
def GetAllCodes():
""" GetAllCodes() -> Array[str] """
pass
@staticmethod
def GetCoordinateSystemByCode(code):
""" GetCoordinateSystemByCode(code: str) -> SettingsCoordinateSystem """
pass
AngularUnits = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: AngularUnits(self: SettingsUnitZone) -> AngleUnitType
Set: AngularUnits(self: SettingsUnitZone) = value
"""
CoordinateSystemCode = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: CoordinateSystemCode(self: SettingsUnitZone) -> str
Set: CoordinateSystemCode(self: SettingsUnitZone) = value
"""
DrawingScale = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: DrawingScale(self: SettingsUnitZone) -> float
Set: DrawingScale(self: SettingsUnitZone) = value
"""
DrawingUnits = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: DrawingUnits(self: SettingsUnitZone) -> DrawingUnitType
Set: DrawingUnits(self: SettingsUnitZone) = value
"""
ImperialToMetricConversion = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: ImperialToMetricConversion(self: SettingsUnitZone) -> ImperialToMetricConversionType
Set: ImperialToMetricConversion(self: SettingsUnitZone) = value
"""
MatchAutoCADVariables = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: MatchAutoCADVariables(self: SettingsUnitZone) -> bool
Set: MatchAutoCADVariables(self: SettingsUnitZone) = value
"""
ScaleObjectsFromOtherDrawings = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Get: ScaleObjectsFromOtherDrawings(self: SettingsUnitZone) -> bool
Set: ScaleObjectsFromOtherDrawings(self: SettingsUnitZone) = value
"""
class SettingsViewFrame(SettingsAmbient):
# no doc
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SpecifyRotationType(Enum):
""" enum SpecifyRotationType, values: GridRotationAngle (1), RotationPoint (0) """
GridRotationAngle = None
RotationPoint = None
value__ = None
class TableAnchorType(Enum):
""" enum TableAnchorType, values: BottomCenter (7), BottomLeft (6), BottomRight (8), MiddleCenter (4), MiddleLeft (3), MiddleRight (5), TopCenter (1), TopLeft (0), TopRight (2) """
BottomCenter = None
BottomLeft = None
BottomRight = None
MiddleCenter = None
MiddleLeft = None
MiddleRight = None
TopCenter = None
TopLeft = None
TopRight = None
value__ = None
class TableLayoutType(Enum):
""" enum TableLayoutType, values: Horizontal (0), Vertical (1) """
Horizontal = None
value__ = None
Vertical = None
class TileDirectionType(Enum):
""" enum TileDirectionType, values: Across (0), Down (1) """
Across = None
Down = None
value__ = None
| 32.170963 | 1,533 | 0.679776 |
class AbbreviationAlignmentEnhancedType(Enum):
""" enum AbbreviationAlignmentEnhancedType, values: AlignmentBeginningPoint (402706556), AlignmentEndPoint (402706557), CompoundSpiralLargeRadiusAtBeginning (402706566), CompoundSpiralLargeRadiusAtEnd (402706567), CompoundSpiralSmallRadiusAtBeginning (402706568), CompoundSpiralSmallRadiusAtEnd (402706569), CurveBeginning (402706560), CurveEnd (402706561), LineBeginning (402706558), LineEnd (402706559), SimpleSpiralLargeRadiusAtBeginning (402706562), SimpleSpiralLargeRadiusAtEnd (402706563), SimpleSpiralSmallRadiusAtBeginning (402706564), SimpleSpiralSmallRadiusAtEnd (402706565) """
AlignmentBeginningPoint = None
AlignmentEndPoint = None
CompoundSpiralLargeRadiusAtBeginning = None
CompoundSpiralLargeRadiusAtEnd = None
CompoundSpiralSmallRadiusAtBeginning = None
CompoundSpiralSmallRadiusAtEnd = None
CurveBeginning = None
CurveEnd = None
LineBeginning = None
LineEnd = None
SimpleSpiralLargeRadiusAtBeginning = None
SimpleSpiralLargeRadiusAtEnd = None
SimpleSpiralSmallRadiusAtBeginning = None
SimpleSpiralSmallRadiusAtEnd = None
value__ = None
class AbbreviationAlignmentType(Enum):
""" enum AbbreviationAlignmentType, values: AlignmentBeginning (67162235), AlignmentEnd (67162234), CompoundCurveCurveIntersect (67162197), CurveSpiralIntersect (67162201), CurveTangentIntersect (67162196), MidCurvePoint (67162254), ReverseCurveCurveIntersect (67162198), ReverseSpiralIntersect (67162204), SpiralCurveIntersect (67162202), SpiralSpiralIntersect (67162203), SpiralTangentIntersect (67162200), StationEquationDecreasing (67162253), StationEquationIncreasing (67162252), TangentCurveIntersect (67162195), TangentSpiralIntersect (67162199), TangentTangentIntersect (67162194) """
AlignmentBeginning = None
AlignmentEnd = None
CompoundCurveCurveIntersect = None
CurveSpiralIntersect = None
CurveTangentIntersect = None
MidCurvePoint = None
ReverseCurveCurveIntersect = None
ReverseSpiralIntersect = None
SpiralCurveIntersect = None
SpiralSpiralIntersect = None
SpiralTangentIntersect = None
StationEquationDecreasing = None
StationEquationIncreasing = None
TangentCurveIntersect = None
TangentSpiralIntersect = None
TangentTangentIntersect = None
value__ = None
class AbbreviationCantType(Enum):
""" enum AbbreviationCantType, values: BeginAlignment (67163513), BeginFullCant (67163510), BeginLevelRail (67163509), EndAlignment (67163514), EndFullCant (67163511), EndLevelRail (67163508), Manual (67163512) """
BeginAlignment = None
BeginFullCant = None
BeginLevelRail = None
EndAlignment = None
EndFullCant = None
EndLevelRail = None
Manual = None
value__ = None
class AbbreviationProfileType(Enum):
""" enum AbbreviationProfileType, values: BeginVerticalCurve (67173890), BeginVerticalCurveElevation (67173892), BeginVerticalCurveStation (67173891), CurveCoefficient (67173898), EndVerticalCurve (67173893), EndVerticalCurveElevation (67173895), EndVerticalCurveStation (67173894), GradeBreak (67173889), GradeChange (67173899), HighPoint (67173896), LowPoint (67173897), OverallHighPoint (67173909), OverallLowPoint (67173910), PointOfVerticalIntersection (67173888), ProfileEnd (67173902), ProfileStart (67173901), VerticalCompoundCurveIntersect (67173903), VerticalCompoundCurveIntersectElevation (67173906), VerticalCompoundCurveIntersectStation (67173905), VerticalReverseCurveIntersect (67173904), VerticalReverseCurveIntersectElevation (67173908), VerticalReverseCurveIntersectStation (67173907) """
BeginVerticalCurve = None
BeginVerticalCurveElevation = None
BeginVerticalCurveStation = None
CurveCoefficient = None
EndVerticalCurve = None
EndVerticalCurveElevation = None
EndVerticalCurveStation = None
GradeBreak = None
GradeChange = None
HighPoint = None
LowPoint = None
OverallHighPoint = None
OverallLowPoint = None
PointOfVerticalIntersection = None
ProfileEnd = None
ProfileStart = None
value__ = None
VerticalCompoundCurveIntersect = None
VerticalCompoundCurveIntersectElevation = None
VerticalCompoundCurveIntersectStation = None
VerticalReverseCurveIntersect = None
VerticalReverseCurveIntersectElevation = None
VerticalReverseCurveIntersectStation = None
class AbbreviationSuperelevationType(Enum):
""" enum AbbreviationSuperelevationType, values: BeginFullSuper (67163478), BeginNormalCrown (67163476), BeginNormalShoulder (67163480), BeginOfAlignment (67163474), BeginShoulderRollover (67163506), EndFullSuper (67163479), EndNormalCrown (67163477), EndNormalShoulder (67163481), EndOfAlignment (67163475), EndShoulderRollover (67163507), LevelCrown (67163482), LowShoulderMatch (67163483), Manual (67163486), ReverseCrown (67163484), ShoulderBreakover (67163485) """
BeginFullSuper = None
BeginNormalCrown = None
BeginNormalShoulder = None
BeginOfAlignment = None
BeginShoulderRollover = None
EndFullSuper = None
EndNormalCrown = None
EndNormalShoulder = None
EndOfAlignment = None
EndShoulderRollover = None
LevelCrown = None
LowShoulderMatch = None
Manual = None
ReverseCrown = None
ShoulderBreakover = None
value__ = None
class AutomaticManual(Enum):
""" enum AutomaticManual, values: Automatic (0), AutomaticObject (1), Manual (2), None (3) """
Automatic = None
AutomaticObject = None
Manual = None
None = None
value__ = None
class DrawingUnitType(Enum):
""" enum DrawingUnitType, values: Feet (30), Meters (2) """
Feet = None
Meters = None
value__ = None
class GeographicCoordinateType(Enum):
""" enum GeographicCoordinateType, values: LatLong (0), LongLat (1) """
LatLong = None
LongLat = None
value__ = None
class GridCoordinateType(Enum):
""" enum GridCoordinateType, values: EastingNorthing (0), NorthingEasting (1) """
EastingNorthing = None
NorthingEasting = None
value__ = None
class GridScaleFactorType(Enum):
""" enum GridScaleFactorType, values: PrismodialFormula (3), ReferencePoint (2), Unity (0), UserDefined (1) """
PrismodialFormula = None
ReferencePoint = None
Unity = None
UserDefined = None
value__ = None
class ImperialToMetricConversionType(Enum):
""" enum ImperialToMetricConversionType, values: InternationalFoot (536870912), UsSurveyFoot (1073741824) """
InternationalFoot = None
UsSurveyFoot = None
value__ = None
class LandXMLAngularUnits(Enum):
""" enum LandXMLAngularUnits, values: DegreesDecimal (0), DegreesDms (1), Grads (2), Radians (3) """
DegreesDecimal = None
DegreesDms = None
Grads = None
Radians = None
value__ = None
class LandXMLAttributeExportType(Enum):
""" enum LandXMLAttributeExportType, values: Disabled (0), FullDescription (2), RawDescription (1) """
Disabled = None
FullDescription = None
RawDescription = None
value__ = None
class LandXMLConflictResolutionType(Enum):
""" enum LandXMLConflictResolutionType, values: Append (2), Skip (0), Update (1) """
Append = None
Skip = None
Update = None
value__ = None
class LandXMLImperialUnitType(Enum):
""" enum LandXMLImperialUnitType, values: Foot (30), Inch (31), Mile (44), Yard (33) """
Foot = None
Inch = None
Mile = None
value__ = None
Yard = None
class LandXMLLinearUnits(Enum):
""" enum LandXMLLinearUnits, values: InternationalFoot (30), SurveyFoot (54) """
InternationalFoot = None
SurveyFoot = None
value__ = None
class LandXMLMetricUnitType(Enum):
""" enum LandXMLMetricUnitType, values: CentiMeter (24), DeciMeter (23), KiloMeter (20), Meter (2), MilliMeter (25) """
CentiMeter = None
DeciMeter = None
KiloMeter = None
Meter = None
MilliMeter = None
value__ = None
class LandXMLPointDescriptionType(Enum):
""" enum LandXMLPointDescriptionType, values: UseCodeThenDesc (2), UseCodeValue (0), UseDescThenCode (3), UseDescValue (1) """
UseCodeThenDesc = None
UseCodeValue = None
UseDescThenCode = None
UseDescValue = None
value__ = None
class LandXMLSurfaceDataExportType(Enum):
""" enum LandXMLSurfaceDataExportType, values: PointsAndFaces (1), PointsOnly (0) """
PointsAndFaces = None
PointsOnly = None
value__ = None
class LandXMLSurfaceDataImportType(Enum):
""" enum LandXMLSurfaceDataImportType, values: FullImport (1), QuickImport (0) """
FullImport = None
QuickImport = None
value__ = None
class LocalCoordinateType(Enum):
""" enum LocalCoordinateType, values: EastingNorthing (0), NorthingEasting (1), XY (2), YX (3) """
EastingNorthing = None
NorthingEasting = None
value__ = None
XY = None
YX = None
class MapcheckAngleType(Enum):
""" enum MapcheckAngleType, values: Angle (1), DeflectionAngle (2), Direction (0) """
Angle = None
DeflectionAngle = None
Direction = None
value__ = None
class MapcheckCurveDirectionType(Enum):
""" enum MapcheckCurveDirectionType, values: Clockwise (0), CounterClockwise (1) """
Clockwise = None
CounterClockwise = None
value__ = None
class MapcheckSideType(Enum):
""" enum MapcheckSideType, values: Curve (1), Line (0) """
Curve = None
Line = None
value__ = None
class MapcheckTraverseMethodType(Enum):
""" enum MapcheckTraverseMethodType, values: AcrossChord (0), ThroughRadius (1) """
AcrossChord = None
ThroughRadius = None
value__ = None
class ObjectLayerModifierType(Enum):
""" enum ObjectLayerModifierType, values: None (0), Prefix (1), Suffix (2) """
None = None
Prefix = None
Suffix = None
value__ = None
class SectionViewAnchorType(Enum):
""" enum SectionViewAnchorType, values: BottomCenter (7), BottomLeft (6), BottomRight (8), MiddleCenter (4), MiddleLeft (3), MiddleRight (5), TopCenter (1), TopLeft (0), TopRight (2) """
BottomCenter = None
BottomLeft = None
BottomRight = None
MiddleCenter = None
MiddleLeft = None
MiddleRight = None
TopCenter = None
TopLeft = None
TopRight = None
value__ = None
class SettingsAbbreviation(CivilWrapper<AcDbDatabase>):
def Dispose(self):
""" Dispose(self: CivilWrapper<AcDbDatabase>, A_0: bool) """
pass
AlignmentGeoPointEntityData = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: AlignmentGeoPointEntityData(self: SettingsAbbreviation) -> SettingsAbbreviationAlignmentEnhanced
"""
AlignmentGeoPointText = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: AlignmentGeoPointText(self: SettingsAbbreviation) -> SettingsAbbreviationAlignment
"""
Cant = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Cant(self: SettingsAbbreviation) -> SettingsAbbreviationCant
"""
GeneralText = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: GeneralText(self: SettingsAbbreviation) -> SettingsAbbreviationGeneral
"""
Profile = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Profile(self: SettingsAbbreviation) -> SettingsAbbreviationProfile
"""
Superelevation = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Superelevation(self: SettingsAbbreviation) -> SettingsAbbreviationSuperelevation
"""
class SettingsAbbreviationAlignment(TreeOidWrapper):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
def GetAlignmentAbbreviation(self, type):
""" GetAlignmentAbbreviation(self: SettingsAbbreviationAlignment, type: AbbreviationAlignmentType) -> str """
pass
def SetAlignmentAbbreviation(self, type, value):
""" SetAlignmentAbbreviation(self: SettingsAbbreviationAlignment, type: AbbreviationAlignmentType, value: str) """
pass
class SettingsAbbreviationAlignmentEnhanced(TreeOidWrapper):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
def GetAlignmentEnhancedAbbreviation(self, type):
""" GetAlignmentEnhancedAbbreviation(self: SettingsAbbreviationAlignmentEnhanced, type: AbbreviationAlignmentEnhancedType) -> str """
pass
def SetAlignmentEnhancedAbbreviation(self, type, newValue):
""" SetAlignmentEnhancedAbbreviation(self: SettingsAbbreviationAlignmentEnhanced, type: AbbreviationAlignmentEnhancedType, newValue: str) """
pass
class SettingsAbbreviationCant(TreeOidWrapper):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
def GetCantAbbreviation(self, type):
""" GetCantAbbreviation(self: SettingsAbbreviationCant, type: AbbreviationCantType) -> str """
pass
def SetCantAbbreviation(self, type, newValue):
""" SetCantAbbreviation(self: SettingsAbbreviationCant, type: AbbreviationCantType, newValue: str) """
pass
class SettingsAbbreviationGeneral(TreeOidWrapper):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
Infinity = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Infinity(self: SettingsAbbreviationGeneral) -> str
Set: Infinity(self: SettingsAbbreviationGeneral) = value
"""
Left = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Left(self: SettingsAbbreviationGeneral) -> str
Set: Left(self: SettingsAbbreviationGeneral) = value
"""
Right = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Right(self: SettingsAbbreviationGeneral) -> str
Set: Right(self: SettingsAbbreviationGeneral) = value
"""
class SettingsAbbreviationProfile(TreeOidWrapper):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
def GetProfileAbbreviation(self, type):
""" GetProfileAbbreviation(self: SettingsAbbreviationProfile, type: AbbreviationProfileType) -> str """
pass
def SetProfileAbbreviation(self, type, newValue):
""" SetProfileAbbreviation(self: SettingsAbbreviationProfile, type: AbbreviationProfileType, newValue: str) """
pass
class SettingsAbbreviationSuperelevation(TreeOidWrapper):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
def GetSuperelevationAbbreviation(self, type):
""" GetSuperelevationAbbreviation(self: SettingsAbbreviationSuperelevation, type: AbbreviationSuperelevationType) -> str """
pass
def SetSuperelevationAbbreviation(self, type, newValue):
""" SetSuperelevationAbbreviation(self: SettingsAbbreviationSuperelevation, type: AbbreviationSuperelevationType, newValue: str) """
pass
class SettingsAmbient(TreeOidWrapper):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
@staticmethod
def __new__(self, *args):
""" __new__(cls: type, root: SettingsRoot, path: str) """
pass
Acceleration = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Acceleration(self: SettingsAmbient) -> SettingsAcceleration
"""
Angle = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Angle(self: SettingsAmbient) -> SettingsAngle
"""
Area = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Area(self: SettingsAmbient) -> SettingsArea
"""
Coordinate = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Coordinate(self: SettingsAmbient) -> SettingsCoordinate
"""
DegreeOfCurvature = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: DegreeOfCurvature(self: SettingsAmbient) -> SettingsDegreeOfCurvature
"""
Dimension = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Dimension(self: SettingsAmbient) -> SettingsDimension
"""
Direction = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Direction(self: SettingsAmbient) -> SettingsDirection
"""
Distance = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Distance(self: SettingsAmbient) -> SettingsDistance
"""
Elevation = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Elevation(self: SettingsAmbient) -> SettingsElevation
"""
General = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: General(self: SettingsAmbient) -> SettingsGeneral
"""
Grade = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Grade(self: SettingsAmbient) -> SettingsGrade
"""
GradeSlope = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: GradeSlope(self: SettingsAmbient) -> SettingsGradeSlope
"""
GridCoordinate = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: GridCoordinate(self: SettingsAmbient) -> SettingsGridCoordinate
"""
Labeling = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Labeling(self: SettingsAmbient) -> SettingsLabeling
"""
LatLong = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: LatLong(self: SettingsAmbient) -> SettingsLatLong
"""
Pressure = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Pressure(self: SettingsAmbient) -> SettingsPressure
"""
Slope = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Slope(self: SettingsAmbient) -> SettingsSlope
"""
Speed = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Speed(self: SettingsAmbient) -> SettingsSpeed
"""
Station = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Station(self: SettingsAmbient) -> SettingsStation
"""
Time = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Time(self: SettingsAmbient) -> SettingsTime
"""
TransparentCommands = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: TransparentCommands(self: SettingsAmbient) -> SettingsTransparentCommands
"""
Unitless = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Unitless(self: SettingsAmbient) -> SettingsUnitless
"""
Volume = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Volume(self: SettingsAmbient) -> SettingsVolume
"""
SettingsAcceleration = None
SettingsAngle = None
SettingsArea = None
SettingsCoordinate = None
SettingsDegreeOfCurvature = None
SettingsDimension = None
SettingsDirection = None
SettingsDistance = None
SettingsElevation = None
SettingsFormatNumber`1 = None
SettingsGeneral = None
SettingsGrade = None
SettingsGradeSlope = None
SettingsGridCoordinate = None
SettingsLabeling = None
SettingsLatLong = None
SettingsPressure = None
SettingsSlope = None
SettingsSpeed = None
SettingsStation = None
SettingsTime = None
SettingsTransparentCommands = None
SettingsUnitFormatNumber`2 = None
SettingsUnitless = None
SettingsUnitlessNumber = None
SettingsUnitNumber`1 = None
SettingsVolume = None
class SettingsAlignment(SettingsAmbient):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
AutomaticWideningAroundCurves = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: AutomaticWideningAroundCurves(self: SettingsAlignment) -> SettingsAutomaticWideningAroundCurves
"""
CantOptions = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: CantOptions(self: SettingsAlignment) -> SettingsCantOptions
"""
ConstraintEditing = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: ConstraintEditing(self: SettingsAlignment) -> SettingsConstraintEditing
"""
CriteriaBasedDesignOptions = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: CriteriaBasedDesignOptions(self: SettingsAlignment) -> SettingsCriteriaBasedDesignOptions
"""
Data = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Data(self: SettingsAlignment) -> SettingsData
"""
DefaultNameFormat = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: DefaultNameFormat(self: SettingsAlignment) -> SettingsDefaultNameFormat
"""
DynamicAlignmentHighlight = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: DynamicAlignmentHighlight(self: SettingsAlignment) -> SettingsDynamicAlignmentHighlight
"""
ImpliedPointOfIntersection = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: ImpliedPointOfIntersection(self: SettingsAlignment) -> SettingsImpliedPointOfIntersection
"""
RailOptions = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: RailOptions(self: SettingsAlignment) -> SettingsRailAlignmentOptions
"""
StationIndexing = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: StationIndexing(self: SettingsAlignment) -> SettingsStationIndexing
"""
StyleSettings = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: StyleSettings(self: SettingsAlignment) -> SettingsStyles
"""
SuperelevationOptions = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: SuperelevationOptions(self: SettingsAlignment) -> SettingsSuperelevationOptions
"""
SettingsAutomaticWideningAroundCurves = None
SettingsCantOptions = None
SettingsConstraintEditing = None
SettingsCriteriaBasedDesignOptions = None
SettingsData = None
SettingsDefaultNameFormat = None
SettingsDynamicAlignmentHighlight = None
SettingsImpliedPointOfIntersection = None
SettingsRailAlignmentOptions = None
SettingsStationIndexing = None
SettingsStyles = None
SettingsSuperelevationOptions = None
class SettingsAssembly(SettingsAmbient):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
NameFormat = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: NameFormat(self: SettingsAssembly) -> SettingsNameFormat
"""
Styles = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Styles(self: SettingsAssembly) -> SettingsStyles
"""
SettingsNameFormat = None
SettingsStyles = None
class SettingsBuildingSite(SettingsAmbient):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
NameFormat = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: NameFormat(self: SettingsBuildingSite) -> SettingsNameFormat
"""
Styles = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Styles(self: SettingsBuildingSite) -> SettingsStyles
"""
SettingsNameFormat = None
SettingsStyles = None
class SettingsCantView(SettingsAmbient):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
NameFormat = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: NameFormat(self: SettingsCantView) -> SettingsNameFormat
"""
Styles = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Styles(self: SettingsCantView) -> SettingsStyles
"""
SettingsNameFormat = None
SettingsStyles = None
class SettingsCatchment(SettingsAmbient):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
NameTemplate = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: NameTemplate(self: SettingsCatchment) -> PropertyString
"""
Styles = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Styles(self: SettingsCatchment) -> SettingsStyles
"""
SettingsStyles = None
class SettingsCmdAddAlignmentCurveTable(SettingsAlignment):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
TableCreation = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: TableCreation(self: SettingsCmdAddAlignmentCurveTable) -> SettingsCmdTableCreation
"""
SettingsCmdTableCreation = None
class SettingsCmdAddAlignmentLineTable(SettingsAlignment):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
TableCreation = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: TableCreation(self: SettingsCmdAddAlignmentLineTable) -> SettingsCmdTableCreation
"""
SettingsCmdTableCreation = None
class SettingsCmdAddAlignmentOffLbl(SettingsAlignment):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddAlignmentOffXYLbl(SettingsAlignment):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddAlignmentSegmentTable(SettingsAlignment):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
TableCreation = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: TableCreation(self: SettingsCmdAddAlignmentSegmentTable) -> SettingsCmdTableCreation
"""
SettingsCmdTableCreation = None
class SettingsCmdAddAlignmentSpiralTable(SettingsAlignment):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
TableCreation = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: TableCreation(self: SettingsCmdAddAlignmentSpiralTable) -> SettingsCmdTableCreation
"""
SettingsCmdTableCreation = None
class SettingsCmdAddAlignPointOfIntLbl(SettingsAlignment):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddAlignPointOfIntLbls(SettingsAlignment):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddAlignSegLbl(SettingsAlignment):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddAlignSegLbls(SettingsAlignment):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddAlignTagentLbl(SettingsAlignment):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddAlignTagentLbls(SettingsAlignment):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsPressureNetwork(SettingsAmbient):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
Cover = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Cover(self: SettingsPressureNetwork) -> SettingsDepthOfCover
"""
NameFormat = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: NameFormat(self: SettingsPressureNetwork) -> SettingsNameFormat
"""
ProfileLabelPlacement = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: ProfileLabelPlacement(self: SettingsPressureNetwork) -> SettingsProfileLabelPlacement
"""
SectionLabelPlacement = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: SectionLabelPlacement(self: SettingsPressureNetwork) -> SettingsSectionLabelPlacement
"""
Styles = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Styles(self: SettingsPressureNetwork) -> SettingsStyles
"""
SettingsDepthOfCover = None
SettingsNameFormat = None
SettingsProfileLabelPlacement = None
SettingsSectionLabelPlacement = None
SettingsStyles = None
class SettingsCmdAddAppurtTable(SettingsPressureNetwork):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
TableCreation = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: TableCreation(self: SettingsCmdAddAppurtTable) -> SettingsCmdTableCreation
"""
SettingsCmdTableCreation = None
class SettingsSurface(SettingsAmbient):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
ContourLabeling = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: ContourLabeling(self: SettingsSurface) -> SettingsContourLabeling
"""
Defaults = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Defaults(self: SettingsSurface) -> SettingsDefaults
"""
Styles = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Styles(self: SettingsSurface) -> SettingsStyles
"""
SettingsContourLabeling = None
SettingsDefaults = None
SettingsStyles = None
class SettingsCmdAddContourLabeling(SettingsSurface):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddContourLabelingGroup(SettingsSurface):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
AddContourLabeling = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: AddContourLabeling(self: SettingsCmdAddContourLabelingGroup) -> SettingsCmdAddContourLabeling
"""
SettingsCmdAddContourLabeling = None
class SettingsCmdAddContourLabelingSingle(SettingsSurface):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddFittingTable(SettingsPressureNetwork):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
TableCreation = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: TableCreation(self: SettingsCmdAddFittingTable) -> SettingsCmdTableCreation
"""
SettingsCmdTableCreation = None
class SettingsIntersection(SettingsAmbient):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
NameFormat = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: NameFormat(self: SettingsIntersection) -> SettingsNameFormat
"""
Styles = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Styles(self: SettingsIntersection) -> SettingsStyles
"""
SettingsNameFormat = None
SettingsStyles = None
class SettingsCmdAddIntersectionLabel(SettingsIntersection):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsGeneral(SettingsAmbient):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
Styles = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Styles(self: SettingsGeneral) -> SettingsStyles
"""
SettingsStyles = None
class SettingsCmdAddLineBetweenPoints(SettingsGeneral):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsQuantityTakeoff(SettingsAmbient):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
NameFormat = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: NameFormat(self: SettingsQuantityTakeoff) -> SettingsNameFormat
"""
Styles = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Styles(self: SettingsQuantityTakeoff) -> SettingsStyles
"""
SettingsNameFormat = None
SettingsStyles = None
class SettingsCmdAddMaterialVolumeTable(SettingsQuantityTakeoff):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
TableCreation = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: TableCreation(self: SettingsCmdAddMaterialVolumeTable) -> SettingsCmdTableCreation
"""
SettingsCmdTableCreation = None
class SettingsPipeNetwork(SettingsAmbient):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
Default = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Default(self: SettingsPipeNetwork) -> SettingsDefault
"""
NameFormat = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: NameFormat(self: SettingsPipeNetwork) -> SettingsNameFormat
"""
ProfileLabelPlacement = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: ProfileLabelPlacement(self: SettingsPipeNetwork) -> SettingsProfileLabelPlacement
"""
Rules = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Rules(self: SettingsPipeNetwork) -> SettingsRules
"""
SectionLabelPlacement = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: SectionLabelPlacement(self: SettingsPipeNetwork) -> SettingsSectionLabelPlacement
"""
StormSewersMigration = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: StormSewersMigration(self: SettingsPipeNetwork) -> SettingsStormSewersMigration
"""
Styles = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Styles(self: SettingsPipeNetwork) -> SettingsStyles
"""
SettingsDefault = None
SettingsNameFormat = None
SettingsProfileLabelPlacement = None
SettingsRules = None
SettingsSectionLabelPlacement = None
SettingsStormSewersMigration = None
SettingsStyles = None
class SettingsCmdAddNetworkPartPlanLabel(SettingsPipeNetwork):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddNetworkPartProfLabel(SettingsPipeNetwork):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddNetworkPartSectLabel(SettingsPipeNetwork):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddNetworkPartsToProf(SettingsPipeNetwork):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddNetworkPipeTable(SettingsPipeNetwork):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
TableCreation = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: TableCreation(self: SettingsCmdAddNetworkPipeTable) -> SettingsCmdTableCreation
"""
SettingsCmdTableCreation = None
class SettingsCmdAddNetworkPlanLabels(SettingsPipeNetwork):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddNetworkProfLabels(SettingsPipeNetwork):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddNetworkSectLabels(SettingsPipeNetwork):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddNetworkStructTable(SettingsPipeNetwork):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
TableCreation = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: TableCreation(self: SettingsCmdAddNetworkStructTable) -> SettingsCmdTableCreation
"""
SettingsCmdTableCreation = None
class SettingsCmdAddNoteLabel(SettingsGeneral):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsParcel(SettingsAmbient):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
Styles = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Styles(self: SettingsParcel) -> SettingsStyles
"""
SettingsStyles = None
class SettingsCmdAddParcelAreaLabel(SettingsParcel):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddParcelCurveTable(SettingsParcel):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
TableCreation = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: TableCreation(self: SettingsCmdAddParcelCurveTable) -> SettingsCmdTableCreation
"""
SettingsCmdTableCreation = None
class SettingsCmdAddParcelLineLabel(SettingsParcel):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddParcelLineTable(SettingsParcel):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
TableCreation = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: TableCreation(self: SettingsCmdAddParcelLineTable) -> SettingsCmdTableCreation
"""
SettingsCmdTableCreation = None
class SettingsCmdAddParcelSegmentLabels(SettingsParcel):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
Options = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Options(self: SettingsCmdAddParcelSegmentLabels) -> SettingsCmdOptions
"""
SettingsCmdOptions = None
class SettingsCmdAddParcelSegmentTable(SettingsParcel):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
TableCreation = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: TableCreation(self: SettingsCmdAddParcelSegmentTable) -> SettingsCmdTableCreation
"""
SettingsCmdTableCreation = None
class SettingsCmdAddParcelTable(SettingsParcel):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
TableCreation = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: TableCreation(self: SettingsCmdAddParcelTable) -> SettingsCmdTableCreation
"""
SettingsCmdTableCreation = None
class SettingsPointCloud(SettingsAmbient):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
DefaultNameFormat = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: DefaultNameFormat(self: SettingsPointCloud) -> SettingsDefaultNameFormat
"""
StyleSettings = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: StyleSettings(self: SettingsPointCloud) -> SettingsStyles
"""
SettingsDefaultNameFormat = None
SettingsStyles = None
class SettingsCmdAddPointCloudPoints(SettingsPointCloud):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
DefaultFileFormat = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: DefaultFileFormat(self: SettingsCmdAddPointCloudPoints) -> PropertyEnum[PointCloudDefaultFileExtensionType]
"""
class SettingsCmdAddPointsToSurface(SettingsPointCloud):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
MidOrdinateDistance = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: MidOrdinateDistance(self: SettingsCmdAddPointsToSurface) -> PropertyDouble
"""
RegionOption = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: RegionOption(self: SettingsCmdAddPointsToSurface) -> PropertyEnum[PointCloudRegionType]
"""
SurfaceOption = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: SurfaceOption(self: SettingsCmdAddPointsToSurface) -> PropertyEnum[PointCloudSurfaceType]
"""
class SettingsPoint(SettingsAmbient):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
NameFormat = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: NameFormat(self: SettingsPoint) -> SettingsNameFormat
"""
Styles = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Styles(self: SettingsPoint) -> SettingsStyles
"""
UpdatePoints = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: UpdatePoints(self: SettingsPoint) -> SettingsUpdatePoints
"""
SettingsNameFormat = None
SettingsStyles = None
SettingsUpdatePoints = None
class SettingsCmdAddPointTable(SettingsPoint):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
TableCreation = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: TableCreation(self: SettingsCmdAddPointTable) -> SettingsCmdTableCreation
"""
SettingsCmdTableCreation = None
class SettingsCmdAddPressurePartPlanLabel(SettingsPressureNetwork):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddPressurePartProfLabel(SettingsPressureNetwork):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddPressurePartsToProf(SettingsPressureNetwork):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddPressurePipeTable(SettingsPressureNetwork):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
TableCreation = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: TableCreation(self: SettingsCmdAddPressurePipeTable) -> SettingsCmdTableCreation
"""
SettingsCmdTableCreation = None
class SettingsCmdAddPressurePlanLabels(SettingsPressureNetwork):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddPressureProfLabels(SettingsPressureNetwork):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsProfileView(SettingsAmbient):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
Creation = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Creation(self: SettingsProfileView) -> SettingsCreation
"""
NameFormat = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: NameFormat(self: SettingsProfileView) -> SettingsNameFormat
"""
ProjectionLabelPlacement = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: ProjectionLabelPlacement(self: SettingsProfileView) -> SettingsProjectionLabelPlacement
"""
SplitOptions = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: SplitOptions(self: SettingsProfileView) -> SettingsSplitOptions
"""
StackedOptions = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: StackedOptions(self: SettingsProfileView) -> SettingsStackedOptions
"""
Styles = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Styles(self: SettingsProfileView) -> SettingsStyles
"""
SettingsCreation = None
SettingsNameFormat = None
SettingsProjectionLabelPlacement = None
SettingsSplitOptions = None
SettingsStackedOptions = None
SettingsStyles = None
class SettingsCmdAddProfileViewDepthLbl(SettingsProfileView):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddProfileViewStaElevLbl(SettingsProfileView):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsSectionView(SettingsAmbient):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
NameFormat = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: NameFormat(self: SettingsSectionView) -> SettingsNameFormat
"""
ProjectionLabelPlacement = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: ProjectionLabelPlacement(self: SettingsSectionView) -> SettingsProjectionLabelPlacement
"""
SectionViewCreation = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: SectionViewCreation(self: SettingsSectionView) -> SettingsSectionViewCreation
"""
Styles = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Styles(self: SettingsSectionView) -> SettingsStyles
"""
SettingsNameFormat = None
SettingsProjectionLabelPlacement = None
SettingsSectionViewCreation = None
SettingsStyles = None
class SettingsCmdAddSectionViewGradeLbl(SettingsSectionView):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddSectionViewOffElevLbl(SettingsSectionView):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddSegmentLabel(SettingsGeneral):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddSegmentLabels(SettingsGeneral):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddSpanningPipePlanLabel(SettingsPipeNetwork):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddSpanningPipeProfLabel(SettingsPipeNetwork):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddSpotElevLabelsOnGrid(SettingsSurface):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddSurfaceBoundaries(SettingsSurface):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
DataOptions = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: DataOptions(self: SettingsCmdAddSurfaceBoundaries) -> SettingsCmdAddDataOptions
"""
SettingsCmdAddDataOptions = None
class SettingsCmdAddSurfaceBreaklines(SettingsSurface):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
DataOptions = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: DataOptions(self: SettingsCmdAddSurfaceBreaklines) -> SettingsCmdAddDataOptions
"""
SettingsCmdAddDataOptions = None
class SettingsCmdAddSurfaceContours(SettingsSurface):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
AddDataOptions = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: AddDataOptions(self: SettingsCmdAddSurfaceContours) -> SettingsCmdAddDataOptions
"""
SettingsCmdAddDataOptions = None
class SettingsCmdAddSurfaceDemFile(SettingsSurface):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
ImportOptions = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: ImportOptions(self: SettingsCmdAddSurfaceDemFile) -> SettingsCmdImportOptions
"""
SettingsCmdImportOptions = None
class SettingsCmdAddSurfaceDrawingObjects(SettingsSurface):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
DataOptions = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: DataOptions(self: SettingsCmdAddSurfaceDrawingObjects) -> SettingsCmdAddDataOptions
"""
SettingsCmdAddDataOptions = None
class SettingsCmdAddSurfaceFigSurveyQuery(SettingsSurface):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
DataOptions = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: DataOptions(self: SettingsCmdAddSurfaceFigSurveyQuery) -> SettingsCmdAddDataOptions
"""
SettingsCmdAddDataOptions = None
class SettingsCmdAddSurfacePointSurveyQuery(SettingsSurface):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddSurfaceSlopeLabel(SettingsSurface):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddSurfaceSpotElevLabel(SettingsSurface):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsSurvey(SettingsAmbient):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
Styles = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Styles(self: SettingsSurvey) -> SettingsStyles
"""
SettingsStyles = None
class SettingsCmdAddSvFigureLabel(SettingsSurvey):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddSvFigureSegmentLabel(SettingsSurvey):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddSvFigureSegmentLabels(SettingsSurvey):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdAddTotalVolumeTable(SettingsQuantityTakeoff):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
TableCreation = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: TableCreation(self: SettingsCmdAddTotalVolumeTable) -> SettingsCmdTableCreation
"""
SettingsCmdTableCreation = None
class SettingsCmdAddWidening(SettingsAlignment):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
LinearTransitionAroundCurves = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: LinearTransitionAroundCurves(self: SettingsCmdAddWidening) -> SettingsCmdLinearTransitionAroundCurves
"""
WideningOptions = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: WideningOptions(self: SettingsCmdAddWidening) -> SettingsCmdWideningOptions
"""
SettingsCmdLinearTransitionAroundCurves = None
SettingsCmdWideningOptions = None
class SettingsCmdAssignPayItemToArea(SettingsQuantityTakeoff):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
AssignPayItemToAreaOption = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: AssignPayItemToAreaOption(self: SettingsCmdAssignPayItemToArea) -> SettingsCmdAssignPayItemToAreaOptions
"""
SettingsCmdAssignPayItemToAreaOptions = None
class SettingsCmdCatchmentArea(SettingsSurface):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
DischargePointStyle = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: DischargePointStyle(self: SettingsCmdCatchmentArea) -> PropertyString
"""
DischargePointStyleId = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: DischargePointStyleId(self: SettingsCmdCatchmentArea) -> PropertyObjectId
"""
DisplayDisChargePoint = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: DisplayDisChargePoint(self: SettingsCmdCatchmentArea) -> PropertyBoolean
"""
Layer = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Layer(self: SettingsCmdCatchmentArea) -> PropertyLayer
"""
ObjectType = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: ObjectType(self: SettingsCmdCatchmentArea) -> PropertyEnum[CatchmentObjectType]
"""
class SettingsCmdComputeMaterials(SettingsQuantityTakeoff):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
DefineMaterialOption = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: DefineMaterialOption(self: SettingsCmdComputeMaterials) -> SettingsCmdDefineMaterial
"""
SettingsCmdDefineMaterial = None
class SettingsCmdConvertPointstoSdskPoints(SettingsPoint):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
Layer = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Layer(self: SettingsCmdConvertPointstoSdskPoints) -> SettingsCmdLayer
"""
SettingsCmdLayer = None
class SettingsCorridor(SettingsAmbient):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
NameFormat = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: NameFormat(self: SettingsCorridor) -> SettingsNameFormat
"""
RegionHighlightGraphics = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: RegionHighlightGraphics(self: SettingsCorridor) -> SettingsRegionHighlightGraphics
"""
Styles = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Styles(self: SettingsCorridor) -> SettingsStyles
"""
SettingsNameFormat = None
SettingsRegionHighlightGraphics = None
SettingsStyles = None
class SettingsCmdCorridorExtractSurfaces(SettingsCorridor):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdCreateAlignFromCorridor(SettingsCorridor):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
AlignmentTypeOption = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: AlignmentTypeOption(self: SettingsCmdCreateAlignFromCorridor) -> SettingsCmdAlignmentTypeOption
"""
CriteriaBasedDesignOptions = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: CriteriaBasedDesignOptions(self: SettingsCmdCreateAlignFromCorridor) -> SettingsCmdCriteriaBasedDesignOptions
"""
ProfileCreationOption = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: ProfileCreationOption(self: SettingsCmdCreateAlignFromCorridor) -> SettingsCmdProfileCreationOption
"""
SettingsCmdAlignmentTypeOption = None
SettingsCmdCriteriaBasedDesignOptions = None
SettingsCmdProfileCreationOption = None
class SettingsCmdCreateAlignFromNetwork(SettingsPipeNetwork):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
AlignmentTypeOption = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: AlignmentTypeOption(self: SettingsCmdCreateAlignFromNetwork) -> SettingsCmdAlignmentTypeOption
"""
SettingsCmdAlignmentTypeOption = None
class SettingsCmdCreateAlignFromPressureNW(SettingsPressureNetwork):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
AlignmentTypeOption = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: AlignmentTypeOption(self: SettingsCmdCreateAlignFromPressureNW) -> SettingsCmdAlignmentTypeOption
"""
SettingsCmdAlignmentTypeOption = None
class SettingsCmdCreateAlignmentEntities(SettingsAlignment):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
AlignmentTypeOption = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: AlignmentTypeOption(self: SettingsCmdCreateAlignmentEntities) -> SettingsCmdAlignmentTypeOption
"""
CreateFromEntities = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: CreateFromEntities(self: SettingsCmdCreateAlignmentEntities) -> SettingsCmdCreateFromEntities
"""
SettingsCmdAlignmentTypeOption = None
SettingsCmdCreateFromEntities = None
class SettingsCmdCreateAlignmentLayout(SettingsAlignment):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
AlignmentTypeOption = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: AlignmentTypeOption(self: SettingsCmdCreateAlignmentLayout) -> SettingsCmdAlignmentTypeOption
"""
CurveAndSpiralSettings = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: CurveAndSpiralSettings(self: SettingsCmdCreateAlignmentLayout) -> SettingsCmdCurveAndSpiralSettings
"""
CurveTessellationOption = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: CurveTessellationOption(self: SettingsCmdCreateAlignmentLayout) -> SettingsCmdCurveTessellationOption
"""
RegressionGraphOption = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: RegressionGraphOption(self: SettingsCmdCreateAlignmentLayout) -> SettingsCmdRegressionGraphOption
"""
SettingsCmdAlignmentTypeOption = None
SettingsCmdCurveAndSpiralSettings = None
SettingsCmdCurveTessellationOption = None
SettingsCmdRegressionGraphOption = None
class SettingsCmdCreateAlignmentReference(SettingsAlignment):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdCreateArcByBestFit(SettingsGeneral):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
CurveTessellationOption = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: CurveTessellationOption(self: SettingsCmdCreateArcByBestFit) -> SettingsCmdCurveTessellationOption
"""
RegressionGraphOption = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: RegressionGraphOption(self: SettingsCmdCreateArcByBestFit) -> SettingsCmdRegressionGraphOption
"""
SettingsCmdCurveTessellationOption = None
SettingsCmdRegressionGraphOption = None
class SettingsCmdCreateAssembly(SettingsAssembly):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdCreateAssemblyTool(SettingsAssembly):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdCreateCantView(SettingsCantView):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdCreateCatchmentFromObject(SettingsCatchment):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
Catchment = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Catchment(self: SettingsCmdCreateCatchmentFromObject) -> SettingsCmdCatchment
"""
ChannelFlow = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: ChannelFlow(self: SettingsCmdCreateCatchmentFromObject) -> SettingsCmdChannelFlow
"""
HydrologicalProperties = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: HydrologicalProperties(self: SettingsCmdCreateCatchmentFromObject) -> SettingsCmdHydrologicalProperties
"""
ShallowConcentratedFlow = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: ShallowConcentratedFlow(self: SettingsCmdCreateCatchmentFromObject) -> SettingsCmdShallowConcentratedFlow
"""
SheetFlow = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: SheetFlow(self: SettingsCmdCreateCatchmentFromObject) -> SettingsCmdSheetFlow
"""
TimeOfConcentrationMethod = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: TimeOfConcentrationMethod(self: SettingsCmdCreateCatchmentFromObject) -> PropertyEnum[CatchmentTimeOfConcentrationMethodType]
"""
SettingsCmdCatchment = None
SettingsCmdChannelFlow = None
SettingsCmdHydrologicalProperties = None
SettingsCmdShallowConcentratedFlow = None
SettingsCmdSheetFlow = None
class SettingsCmdCreateCatchmentFromSurface(SettingsCatchment):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
Catchment = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Catchment(self: SettingsCmdCreateCatchmentFromSurface) -> SettingsCmdCatchment
"""
ChannelFlow = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: ChannelFlow(self: SettingsCmdCreateCatchmentFromSurface) -> SettingsCmdChannelFlow
"""
HydrologicalProperties = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: HydrologicalProperties(self: SettingsCmdCreateCatchmentFromSurface) -> SettingsCmdHydrologicalProperties
"""
ShallowConcentratedFlow = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: ShallowConcentratedFlow(self: SettingsCmdCreateCatchmentFromSurface) -> SettingsCmdShallowConcentratedFlow
"""
SheetFlow = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: SheetFlow(self: SettingsCmdCreateCatchmentFromSurface) -> SettingsCmdSheetFlow
"""
TimeOfConcentrationMethod = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: TimeOfConcentrationMethod(self: SettingsCmdCreateCatchmentFromSurface) -> PropertyEnum[CatchmentTimeOfConcentrationMethodType]
"""
SettingsCmdCatchment = None
SettingsCmdChannelFlow = None
SettingsCmdHydrologicalProperties = None
SettingsCmdShallowConcentratedFlow = None
SettingsCmdSheetFlow = None
class SettingsCmdCreateCatchmentGroup(SettingsCatchment):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdCreateCorridor(SettingsCorridor):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
AssemblyInsertion = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: AssemblyInsertion(self: SettingsCmdCreateCorridor) -> SettingsCmdAssemblyInsertion
"""
SettingsCmdAssemblyInsertion = None
class SettingsGrading(SettingsAmbient):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
NameFormat = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: NameFormat(self: SettingsGrading) -> SettingsNameFormat
"""
Styles = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Styles(self: SettingsGrading) -> SettingsStyles
"""
SettingsNameFormat = None
SettingsStyles = None
class SettingsCmdCreateFeatureLineFromAlign(SettingsGrading):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
FeatureLineCreation = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: FeatureLineCreation(self: SettingsCmdCreateFeatureLineFromAlign) -> SettingsCmdFeatureLineCreation
"""
SettingsCmdFeatureLineCreation = None
class SettingsCmdCreateFeatureLines(SettingsGrading):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
FeatureLineCreation = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: FeatureLineCreation(self: SettingsCmdCreateFeatureLines) -> SettingsCmdFeatureLineCreation
"""
SettingsCmdFeatureLineCreation = None
class SettingsCmdCreateFlowSegment(SettingsCatchment):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
ChannelFlow = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: ChannelFlow(self: SettingsCmdCreateFlowSegment) -> SettingsCmdChannelFlow
"""
ShallowConcentratedFlow = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: ShallowConcentratedFlow(self: SettingsCmdCreateFlowSegment) -> SettingsCmdShallowConcentratedFlow
"""
SheetFlow = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: SheetFlow(self: SettingsCmdCreateFlowSegment) -> SettingsCmdSheetFlow
"""
SettingsCmdChannelFlow = None
SettingsCmdShallowConcentratedFlow = None
SettingsCmdSheetFlow = None
class SettingsCmdCreateGrading(SettingsGrading):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
GradingCreation = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: GradingCreation(self: SettingsCmdCreateGrading) -> SettingsCmdGradingCreation
"""
SettingsCmdGradingCreation = None
class SettingsCmdCreateGradingGroup(SettingsGrading):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
GradingGroupCreation = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: GradingGroupCreation(self: SettingsCmdCreateGradingGroup) -> SettingsCmdGradingGroupCreation
"""
SettingsCmdGradingGroupCreation = None
class SettingsCmdCreateInterferenceCheck(SettingsPipeNetwork):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
InterferenceCriteria = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: InterferenceCriteria(self: SettingsCmdCreateInterferenceCheck) -> SettingsCmdInterferenceCriteria
"""
SettingsCmdInterferenceCriteria = None
class SettingsCmdCreateIntersection(SettingsIntersection):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
AssemblyInsertion = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: AssemblyInsertion(self: SettingsCmdCreateIntersection) -> SettingsCmdAssemblyInsertion
"""
CrossSlopes = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: CrossSlopes(self: SettingsCmdCreateIntersection) -> SettingsCmdCrossSlopes
"""
CurbReturnParameters = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: CurbReturnParameters(self: SettingsCmdCreateIntersection) -> SettingsCmdCurbReturnParameters
"""
CurbReturnProfileRules = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: CurbReturnProfileRules(self: SettingsCmdCreateIntersection) -> SettingsCmdCurbReturnProfileRules
"""
IntersectionOptions = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: IntersectionOptions(self: SettingsCmdCreateIntersection) -> SettingsCmdIntersectionOptions
"""
Offsets = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Offsets(self: SettingsCmdCreateIntersection) -> SettingsCmdOffsets
"""
SecondaryRoadProfileRules = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: SecondaryRoadProfileRules(self: SettingsCmdCreateIntersection) -> SettingsCmdSecondaryRoadProfileRules
"""
WideningParameters = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: WideningParameters(self: SettingsCmdCreateIntersection) -> SettingsCmdWideningParameters
"""
SettingsCmdAssemblyInsertion = None
SettingsCmdCrossSlopes = None
SettingsCmdCurbReturnParameters = None
SettingsCmdCurbReturnProfileRules = None
SettingsCmdIntersectionOptions = None
SettingsCmdOffsets = None
SettingsCmdSecondaryRoadProfileRules = None
SettingsCmdWideningParameters = None
class SettingsCmdCreateLineByBestFit(SettingsGeneral):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
CurveTessellationOption = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: CurveTessellationOption(self: SettingsCmdCreateLineByBestFit) -> SettingsCmdCurveTessellationOption
"""
RegressionGraphOption = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: RegressionGraphOption(self: SettingsCmdCreateLineByBestFit) -> SettingsCmdRegressionGraphOption
"""
SettingsCmdCurveTessellationOption = None
SettingsCmdRegressionGraphOption = None
class SettingsMassHaulView(SettingsAmbient):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
MassHaulCreation = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: MassHaulCreation(self: SettingsMassHaulView) -> SettingsMassHaulCreation
"""
NameFormat = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: NameFormat(self: SettingsMassHaulView) -> SettingsNameFormat
"""
Styles = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Styles(self: SettingsMassHaulView) -> SettingsStyles
"""
SettingsMassHaulCreation = None
SettingsNameFormat = None
SettingsStyles = None
class SettingsCmdCreateMassHaulDiagram(SettingsMassHaulView):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
MassHaulCreation = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: MassHaulCreation(self: SettingsCmdCreateMassHaulDiagram) -> SettingsCmdMassHaulCreation
"""
SettingsCmdMassHaulCreation = None
class SettingsCmdCreateMultipleProfileView(SettingsProfileView):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
MultipleProfileViewCreation = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: MultipleProfileViewCreation(self: SettingsCmdCreateMultipleProfileView) -> SettingsCmdMultipleProfileViewCreation
"""
SettingsCmdMultipleProfileViewCreation = None
class SettingsCmdCreateMultipleSectionView(SettingsSectionView):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
MultipleSectionViewCreation = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: MultipleSectionViewCreation(self: SettingsCmdCreateMultipleSectionView) -> SettingsCmdMultipleSectionViewCreation
"""
TableCreation = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: TableCreation(self: SettingsCmdCreateMultipleSectionView) -> SettingsCmdTableCreation
"""
SettingsCmdMultipleSectionViewCreation = None
SettingsCmdTableCreation = None
class SettingsCmdCreateNetwork(SettingsPipeNetwork):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
DefaultLayoutCommand = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: DefaultLayoutCommand(self: SettingsCmdCreateNetwork) -> PropertyEnum[NetworkDefaultLayoutCommandType]
"""
LabelNewParts = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: LabelNewParts(self: SettingsCmdCreateNetwork) -> SettingsCmdLabelNewParts
"""
SettingsCmdLabelNewParts = None
class SettingsCmdCreateNetworkFromObject(SettingsPipeNetwork):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdCreateNetworkPartsList(SettingsPipeNetwork):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdCreateNetworkPartsListFull(SettingsPipeNetwork):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdCreateNetworkReference(SettingsPipeNetwork):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdCreateOffsetAlignment(SettingsAlignment):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
OffsetAlignmentOptions = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: OffsetAlignmentOptions(self: SettingsCmdCreateOffsetAlignment) -> SettingsCmdOffsetAlignmentOptions
"""
SettingsCmdOffsetAlignmentOptions = None
class SettingsCmdCreateParabolaByBestFit(SettingsGeneral):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
CurveTessellationOption = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: CurveTessellationOption(self: SettingsCmdCreateParabolaByBestFit) -> SettingsCmdCurveTessellationOption
"""
RegressionGraphOption = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: RegressionGraphOption(self: SettingsCmdCreateParabolaByBestFit) -> SettingsCmdRegressionGraphOption
"""
SettingsCmdCurveTessellationOption = None
SettingsCmdRegressionGraphOption = None
class SettingsCmdCreateParcelByLayout(SettingsParcel):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
AutomaticLayout = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: AutomaticLayout(self: SettingsCmdCreateParcelByLayout) -> SettingsCmdAutomaticLayout
"""
ConvertFromEntities = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: ConvertFromEntities(self: SettingsCmdCreateParcelByLayout) -> SettingsCmdConvertFromEntities
"""
ParcelSizing = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: ParcelSizing(self: SettingsCmdCreateParcelByLayout) -> SettingsCmdParcelSizing
"""
PreviewGraphics = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: PreviewGraphics(self: SettingsCmdCreateParcelByLayout) -> SettingsCmdPreviewGraphics
"""
SettingsCmdAutomaticLayout = None
SettingsCmdConvertFromEntities = None
SettingsCmdParcelSizing = None
SettingsCmdPreviewGraphics = None
class SettingsCmdCreateParcelFromObjects(SettingsParcel):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
ConvertFromEntities = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: ConvertFromEntities(self: SettingsCmdCreateParcelFromObjects) -> SettingsCmdConvertFromEntities
"""
SettingsCmdConvertFromEntities = None
class SettingsCmdCreateParcelROW(SettingsParcel):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
CleanupAtAlignmentIntersections = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: CleanupAtAlignmentIntersections(self: SettingsCmdCreateParcelROW) -> SettingsCmdCleanupAtAlignmentIntersections
"""
CleanupAtParcelBoundaries = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: CleanupAtParcelBoundaries(self: SettingsCmdCreateParcelROW) -> SettingsCmdCleanupAtParcelBoundaries
"""
CreateParcelRightOfWay = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: CreateParcelRightOfWay(self: SettingsCmdCreateParcelROW) -> SettingsCmdCreateParcelRightOfWay
"""
SettingsCmdCleanupAtAlignmentIntersections = None
SettingsCmdCleanupAtParcelBoundaries = None
SettingsCmdCreateParcelRightOfWay = None
class SettingsCmdCreatePointCloud(SettingsPointCloud):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
DefaultLayer = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: DefaultLayer(self: SettingsCmdCreatePointCloud) -> SettingsCmdDefaultLayer
"""
FileFormat = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: FileFormat(self: SettingsCmdCreatePointCloud) -> PropertyEnum[PointCloudDefaultFileExtensionType]
"""
SettingsCmdDefaultLayer = None
class SettingsCmdCreatePointGroup(SettingsPoint):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdCreatePoints(SettingsPoint):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
Layer = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Layer(self: SettingsCmdCreatePoints) -> SettingsCmdLayer
"""
PointIdentity = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: PointIdentity(self: SettingsCmdCreatePoints) -> SettingsCmdPointIdentity
"""
PointsCreation = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: PointsCreation(self: SettingsCmdCreatePoints) -> SettingsCmdPointsCreation
"""
SettingsCmdLayer = None
SettingsCmdPointIdentity = None
SettingsCmdPointsCreation = None
class SettingsCmdCreatePointsFromCorridor(SettingsCorridor):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdCreatePolylineFromCorridor(SettingsCorridor):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsSuperelevationView(SettingsAmbient):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
NameFormat = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: NameFormat(self: SettingsSuperelevationView) -> SettingsNameFormat
"""
Styles = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Styles(self: SettingsSuperelevationView) -> SettingsStyles
"""
SettingsNameFormat = None
SettingsStyles = None
class SettingsCmdCreatePolylineFromSuper(SettingsSuperelevationView):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdCreatePressureFromIndModel(SettingsPressureNetwork):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdCreatePressureNetwork(SettingsPressureNetwork):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
DepthOfCover = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: DepthOfCover(self: SettingsCmdCreatePressureNetwork) -> SettingsCmdDepthOfCover
"""
LabelNewParts = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: LabelNewParts(self: SettingsCmdCreatePressureNetwork) -> SettingsCmdLabelNewParts
"""
SettingsCmdDepthOfCover = None
SettingsCmdLabelNewParts = None
class SettingsCmdCreatePressurePartList(SettingsPressureNetwork):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdCreatePressurePartListFull(SettingsPressureNetwork):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdCreateProfileFromCorridor(SettingsCorridor):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
CriteriaBasedDesignOptions = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: CriteriaBasedDesignOptions(self: SettingsCmdCreateProfileFromCorridor) -> SettingsCmdCriteriaBasedDesignOptions
"""
SettingsCmdCriteriaBasedDesignOptions = None
class SettingsProfile(SettingsAmbient):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
CriteriaBasedDesignOptions = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: CriteriaBasedDesignOptions(self: SettingsProfile) -> SettingsCriteriaBasedDesignOptions
"""
DefaultNameFormat = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: DefaultNameFormat(self: SettingsProfile) -> SettingsDefaultNameFormat
"""
ProfilesCreation = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: ProfilesCreation(self: SettingsProfile) -> SettingsProfileCreation
"""
StyleSettings = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: StyleSettings(self: SettingsProfile) -> SettingsStyles
"""
SettingsCriteriaBasedDesignOptions = None
SettingsDefaultNameFormat = None
SettingsProfileCreation = None
SettingsStyles = None
class SettingsCmdCreateProfileFromFile(SettingsProfile):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdCreateProfileFromSurface(SettingsProfile):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
Geometry = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Geometry(self: SettingsCmdCreateProfileFromSurface) -> SettingsCmdGeometry
"""
SettingsCmdGeometry = None
class SettingsCmdCreateProfileLayout(SettingsProfile):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
CurveTessellationOption = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: CurveTessellationOption(self: SettingsCmdCreateProfileLayout) -> SettingsCmdCurveTessellationOption
"""
RegressionGraphOption = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: RegressionGraphOption(self: SettingsCmdCreateProfileLayout) -> SettingsCmdRegressionGraphOption
"""
SettingsCmdCurveTessellationOption = None
SettingsCmdRegressionGraphOption = None
class SettingsCmdCreateProfileReference(SettingsProfile):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdCreateProfileView(SettingsProfileView):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdCreateQuickProfile(SettingsProfile):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
QuickProfile = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: QuickProfile(self: SettingsCmdCreateQuickProfile) -> SettingsCmdQuickProfile
"""
SettingsCmdQuickProfile = None
class SettingsSampleLine(SettingsAmbient):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
NameFormat = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: NameFormat(self: SettingsSampleLine) -> SettingsNameFormat
"""
Styles = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Styles(self: SettingsSampleLine) -> SettingsStyles
"""
SettingsNameFormat = None
SettingsStyles = None
class SettingsCmdCreateSampleLines(SettingsSampleLine):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
AdditionalSampleControls = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: AdditionalSampleControls(self: SettingsCmdCreateSampleLines) -> SettingsCmdAdditionalSampleControls
"""
Miscellaneous = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Miscellaneous(self: SettingsCmdCreateSampleLines) -> SettingsCmdMiscellaneous
"""
SamplingIncrements = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: SamplingIncrements(self: SettingsCmdCreateSampleLines) -> SettingsCmdSamplingIncrements
"""
SwathWidths = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: SwathWidths(self: SettingsCmdCreateSampleLines) -> SettingsCmdSwathWidths
"""
SettingsCmdAdditionalSampleControls = None
SettingsCmdMiscellaneous = None
SettingsCmdSamplingIncrements = None
SettingsCmdSwathWidths = None
class SettingsCmdCreateSectionSheets(SettingsSectionView):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
SheetCreation = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: SheetCreation(self: SettingsCmdCreateSectionSheets) -> SettingsCmdSheetCreation
"""
SettingsCmdSheetCreation = None
class SettingsCmdCreateSectionView(SettingsSectionView):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
TableCreation = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: TableCreation(self: SettingsCmdCreateSectionView) -> SettingsCmdTableCreation
"""
SettingsCmdTableCreation = None
class SettingsViewFrameGroup(SettingsAmbient):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
Information = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Information(self: SettingsViewFrameGroup) -> SettingsInformation
"""
NameFormat = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: NameFormat(self: SettingsViewFrameGroup) -> SettingsNameFormat
"""
Styles = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Styles(self: SettingsViewFrameGroup) -> SettingsStyles
"""
SettingsInformation = None
SettingsNameFormat = None
SettingsStyles = None
class SettingsCmdCreateSheets(SettingsViewFrameGroup):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
SheetCreation = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: SheetCreation(self: SettingsCmdCreateSheets) -> SettingsCmdSheetCreation
"""
SettingsCmdSheetCreation = None
class SettingsCmdCreateSimpleCorridor(SettingsCorridor):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
AssemblyInsertion = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: AssemblyInsertion(self: SettingsCmdCreateSimpleCorridor) -> SettingsCmdAssemblyInsertion
"""
SettingsCmdAssemblyInsertion = None
class SettingsCmdCreateSite(SettingsParcel):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
Alignment = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Alignment(self: SettingsCmdCreateSite) -> SettingsCmdAlignment
"""
FeatureLine = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: FeatureLine(self: SettingsCmdCreateSite) -> SettingsCmdFeatureLine
"""
Parcel = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Parcel(self: SettingsCmdCreateSite) -> SettingsCmdParcel
"""
SettingsCmdAlignment = None
SettingsCmdFeatureLine = None
SettingsCmdParcel = None
class SettingsSubassembly(SettingsAmbient):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
DefaultStyles = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: DefaultStyles(self: SettingsSubassembly) -> SettingsDefaultStyles
"""
NameFormat = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: NameFormat(self: SettingsSubassembly) -> SettingsNameFormat
"""
SettingsDefaultStyles = None
SettingsNameFormat = None
class SettingsCmdCreateSubassemblyTool(SettingsSubassembly):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
SubassemblyOptions = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: SubassemblyOptions(self: SettingsCmdCreateSubassemblyTool) -> SettingsCmdSubassemblyOptions
"""
SettingsCmdSubassemblyOptions = None
class SettingsCmdCreateSubFromPline(SettingsSubassembly):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
CreateFromEntities = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: CreateFromEntities(self: SettingsCmdCreateSubFromPline) -> SettingsCmdCreateFromEntities
"""
SettingsCmdCreateFromEntities = None
class SettingsCmdCreateSuperelevationView(SettingsSuperelevationView):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdCreateSurface(SettingsSurface):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
BuildOptions = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: BuildOptions(self: SettingsCmdCreateSurface) -> SettingsCmdBuildOptions
"""
NameFormat = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: NameFormat(self: SettingsCmdCreateSurface) -> SettingsNameFormat
"""
SurfaceCreation = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: SurfaceCreation(self: SettingsCmdCreateSurface) -> SettingsCmdSurfaceCreation
"""
SettingsCmdBuildOptions = None
SettingsCmdSurfaceCreation = None
SettingsNameFormat = None
class SettingsCmdCreateSurfaceFromTIN(SettingsSurface):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdCreateSurfaceGridFromDEM(SettingsSurface):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
BuildOptions = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: BuildOptions(self: SettingsCmdCreateSurfaceGridFromDEM) -> SettingsCmdBuildOptions
"""
ImportOptions = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: ImportOptions(self: SettingsCmdCreateSurfaceGridFromDEM) -> SettingsCmdImportOptions
"""
SettingsCmdBuildOptions = None
SettingsCmdImportOptions = None
class SettingsCmdCreateSurfaceReference(SettingsSurface):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
NameFormat = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: NameFormat(self: SettingsCmdCreateSurfaceReference) -> SettingsNameFormat
"""
SettingsNameFormat = None
class SettingsCmdCreateSurfaceWaterdrop(SettingsSurface):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
WaterdropMarker = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: WaterdropMarker(self: SettingsCmdCreateSurfaceWaterdrop) -> SettingsCmdWaterdropMarker
"""
WaterdropPath = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: WaterdropPath(self: SettingsCmdCreateSurfaceWaterdrop) -> SettingsCmdWaterdropPath
"""
SettingsCmdWaterdropMarker = None
SettingsCmdWaterdropPath = None
class SettingsCmdCreateViewFrames(SettingsViewFrameGroup):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
ViewFrameCreation = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: ViewFrameCreation(self: SettingsCmdCreateViewFrames) -> SettingsCmdViewFrameCreation
"""
SettingsCmdViewFrameCreation = None
class SettingsCmdDrawFeatureLine(SettingsGrading):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
FeatureLineCreation = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: FeatureLineCreation(self: SettingsCmdDrawFeatureLine) -> SettingsCmdFeatureLineCreation
"""
SettingsCmdFeatureLineCreation = None
class SettingsCmdEditFlowSegments(SettingsCatchment):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
ChannelFlow = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: ChannelFlow(self: SettingsCmdEditFlowSegments) -> SettingsCmdChannelFlow
"""
ShallowConcentratedFlow = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: ShallowConcentratedFlow(self: SettingsCmdEditFlowSegments) -> SettingsCmdShallowConcentratedFlow
"""
SheetFlow = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: SheetFlow(self: SettingsCmdEditFlowSegments) -> SettingsCmdSheetFlow
"""
SettingsCmdChannelFlow = None
SettingsCmdShallowConcentratedFlow = None
SettingsCmdSheetFlow = None
class SettingsCmdEditInStormSewers(SettingsPipeNetwork):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdEditSVGroupStyle(SettingsSectionView):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdExportParcelAnalysis(SettingsParcel):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
ParcelAnalysis = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: ParcelAnalysis(self: SettingsCmdExportParcelAnalysis) -> SettingsCmdParcelAnalysis
"""
SettingsCmdParcelAnalysis = None
class SettingsCmdExportStormSewerData(SettingsPipeNetwork):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdFeatureLinesFromCorridor(SettingsCorridor):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
FeatureLineCreation = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: FeatureLineCreation(self: SettingsCmdFeatureLinesFromCorridor) -> SettingsCmdFeatureLineCreation
"""
SettingsCmdFeatureLineCreation = None
class SettingsCmdFitCurveFeature(SettingsGrading):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
FeatureLineFitCurve = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: FeatureLineFitCurve(self: SettingsCmdFitCurveFeature) -> SettingsCmdFeatureLineFitCurve
"""
SettingsCmdFeatureLineFitCurve = None
class SettingsCmdGenerateQuantitiesReport(SettingsQuantityTakeoff):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
DisplayXmlReport = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: DisplayXmlReport(self: SettingsCmdGenerateQuantitiesReport) -> PropertyBoolean
"""
class SettingsCmdGradingElevEditor(SettingsGrading):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
GradingElevationEditor = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: GradingElevationEditor(self: SettingsCmdGradingElevEditor) -> SettingsCmdGradingElevationEditor
"""
SettingsCmdGradingElevationEditor = None
class SettingsCmdGradingTools(SettingsGrading):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
GradingLayoutTools = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: GradingLayoutTools(self: SettingsCmdGradingTools) -> SettingsCmdGradingLayoutTools
"""
SettingsCmdGradingLayoutTools = None
class SettingsCmdGradingVolumeTools(SettingsGrading):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
LimitFeatureSelectionToCurrentGroup = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: LimitFeatureSelectionToCurrentGroup(self: SettingsCmdGradingVolumeTools) -> PropertyBoolean
"""
RaiseLowerElevationIncrement = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: RaiseLowerElevationIncrement(self: SettingsCmdGradingVolumeTools) -> PropertyDouble
"""
class SettingsCmdImportBuildingSite(SettingsBuildingSite):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdImportGISData(SettingsGeneral):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
PipeNetwork = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: PipeNetwork(self: SettingsCmdImportGISData) -> SettingsCmdPipeNetwork
"""
SettingsCmdPipeNetwork = None
class SettingsCmdImportStormSewerData(SettingsPipeNetwork):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdJoinFeatures(SettingsGrading):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
FeatureLineJoin = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: FeatureLineJoin(self: SettingsCmdJoinFeatures) -> SettingsCmdFeatureLineJoin
"""
SettingsCmdFeatureLineJoin = None
class SettingsCmdLayoutSectionViewGroup(SettingsSectionView):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdMapCheck(SettingsGeneral):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
Mapcheck = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Mapcheck(self: SettingsCmdMapCheck) -> SettingsCmdMapcheck
"""
SettingsCmdMapcheck = None
class SettingsCmdMinimizeSurfaceFlatAreas(SettingsSurface):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
AddPointsToFlatEdges = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: AddPointsToFlatEdges(self: SettingsCmdMinimizeSurfaceFlatAreas) -> PropertyBoolean
"""
AddPointsToFlatTriangles = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: AddPointsToFlatTriangles(self: SettingsCmdMinimizeSurfaceFlatAreas) -> PropertyBoolean
"""
FillGapsInContour = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: FillGapsInContour(self: SettingsCmdMinimizeSurfaceFlatAreas) -> PropertyBoolean
"""
SwapEdges = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: SwapEdges(self: SettingsCmdMinimizeSurfaceFlatAreas) -> PropertyBoolean
"""
class SettingsCmdMoveBlockstoAttribElev(SettingsSurface):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdMoveBlocksToSurface(SettingsSurface):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdMoveTextToElevation(SettingsSurface):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdProjectObjectsToMultiSect(SettingsSectionView):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
ObjectSelectionOptions = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: ObjectSelectionOptions(self: SettingsCmdProjectObjectsToMultiSect) -> SettingsCmdObjectSelectionOptions
"""
SettingsCmdObjectSelectionOptions = None
class SettingsCmdProjectObjectsToProf(SettingsProfileView):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdProjectObjectsToSect(SettingsSectionView):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdReAddParcelAreaLabel(SettingsParcel):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdReAddParcelSegmentLabels(SettingsParcel):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdRenamePipeNetworkParts(SettingsPipeNetwork):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdResetAnchorPipe(SettingsPipeNetwork):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdReverseAlignmentDirection(SettingsAlignment):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdRunDepthCheck(SettingsPressureNetwork):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
DepthCheckOption = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: DepthCheckOption(self: SettingsCmdRunDepthCheck) -> SettingsCmdDepthCheckOption
"""
SettingsCmdDepthCheckOption = None
class SettingsCmdRunDesignCheck(SettingsPressureNetwork):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
DesignCheckOption = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: DesignCheckOption(self: SettingsCmdRunDesignCheck) -> SettingsCmdDesignCheckOption
"""
SettingsCmdDesignCheckOption = None
class SettingsCmdShowGeodeticCalculator(SettingsPoint):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdShowPointGroupProperties(SettingsPoint):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdShowSpanningPipes(SettingsPipeNetwork):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdSimplifySurface(SettingsSurface):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
MaximumChangeInElevation = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: MaximumChangeInElevation(self: SettingsCmdSimplifySurface) -> PropertyDouble
"""
PercentageOfPointsToRemove = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: PercentageOfPointsToRemove(self: SettingsCmdSimplifySurface) -> PropertyDouble
"""
RegionOptions = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: RegionOptions(self: SettingsCmdSimplifySurface) -> PropertyEnum[SurfaceRegionOptionsType]
"""
SimplifyMethod = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: SimplifyMethod(self: SettingsCmdSimplifySurface) -> PropertyEnum[SurfaceSimplifyType]
"""
UseMaximumChangeInElevation = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: UseMaximumChangeInElevation(self: SettingsCmdSimplifySurface) -> PropertyBoolean
"""
UsePercentageOfPointsToRemove = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: UsePercentageOfPointsToRemove(self: SettingsCmdSimplifySurface) -> PropertyBoolean
"""
class SettingsCmdSuperimposeProfile(SettingsProfile):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
SuperimposeProfile = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: SuperimposeProfile(self: SettingsCmdSuperimposeProfile) -> SettingsCmdSuperimposeProfileOption
"""
SettingsCmdSuperimposeProfileOption = None
class SettingsCmdSurfaceExportToDem(SettingsSurface):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
ExportOptions = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: ExportOptions(self: SettingsCmdSurfaceExportToDem) -> SettingsCmdExportOptions
"""
SettingsCmdExportOptions = None
class SettingsCmdSurfaceExtractObjects(SettingsSurface):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsCmdTakeOff(SettingsQuantityTakeoff):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
ComputeTakeOffOption = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: ComputeTakeOffOption(self: SettingsCmdTakeOff) -> SettingsCmdComputeTakeOff
"""
SettingsCmdComputeTakeOff = None
class SettingsCmdViewEditCorridorSection(SettingsCorridor):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
GridSettings = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: GridSettings(self: SettingsCmdViewEditCorridorSection) -> SettingsCmdGridSettings
"""
GridTextSettings = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: GridTextSettings(self: SettingsCmdViewEditCorridorSection) -> SettingsCmdGridTextSettings
"""
SectionSliderInMultipleViewports = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: SectionSliderInMultipleViewports(self: SettingsCmdViewEditCorridorSection) -> SettingsCmdSectionSliderInMultipleViewports
"""
ViewEditOptions = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: ViewEditOptions(self: SettingsCmdViewEditCorridorSection) -> SettingsCmdViewEditOptions
"""
SettingsCmdGridSettings = None
SettingsCmdGridTextSettings = None
SettingsCmdSectionSliderInMultipleViewports = None
SettingsCmdViewEditOptions = None
class SettingsCmdVolumesDashboard(SettingsSurface):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
BoundedVolumeCreation = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: BoundedVolumeCreation(self: SettingsCmdVolumesDashboard) -> SettingsCmdBoundedVolumeCreation
"""
BuildOptions = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: BuildOptions(self: SettingsCmdVolumesDashboard) -> SettingsCmdBuildOptions
"""
DynamicHighlightOptions = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: DynamicHighlightOptions(self: SettingsCmdVolumesDashboard) -> SettingsCmdDynamicHighlightOptions
"""
VolumeSurfaceCreation = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: VolumeSurfaceCreation(self: SettingsCmdVolumesDashboard) -> SettingsCmdVolumeSurfaceCreation
"""
SettingsCmdBoundedVolumeCreation = None
SettingsCmdBuildOptions = None
SettingsCmdDynamicHighlightOptions = None
SettingsCmdVolumeSurfaceCreation = None
class SettingsCmdWeedFeatures(SettingsGrading):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
FeatureLineWeed = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: FeatureLineWeed(self: SettingsCmdWeedFeatures) -> SettingsCmdFeatureLineWeed
"""
SettingsCmdFeatureLineWeed = None
class SettingsCoordinateSystem(object):
Category = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Category(self: SettingsCoordinateSystem) -> str
"""
Code = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Code(self: SettingsCoordinateSystem) -> str
"""
Datum = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Datum(self: SettingsCoordinateSystem) -> str
"""
Description = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Description(self: SettingsCoordinateSystem) -> str
"""
Projection = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Projection(self: SettingsCoordinateSystem) -> str
"""
Unit = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Unit(self: SettingsCoordinateSystem) -> str
"""
class SettingsDrawing(TreeOidWrapper):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
AbbreviationsSettings = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: AbbreviationsSettings(self: SettingsDrawing) -> SettingsAbbreviation
"""
AmbientSettings = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: AmbientSettings(self: SettingsDrawing) -> SettingsAmbient
"""
ApplyTransformSettings = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: ApplyTransformSettings(self: SettingsDrawing) -> bool
Set: ApplyTransformSettings(self: SettingsDrawing) = value
"""
ObjectLayerSettings = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: ObjectLayerSettings(self: SettingsDrawing) -> SettingsObjectLayers
"""
TransformationSettings = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: TransformationSettings(self: SettingsDrawing) -> SettingsTransformation
"""
UnitZoneSettings = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: UnitZoneSettings(self: SettingsDrawing) -> SettingsUnitZone
"""
class SettingsLandXML(TreeOidWrapper):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
Export = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Export(self: SettingsLandXML) -> SettingsLandXMLExport
"""
Import = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Import(self: SettingsLandXML) -> SettingsLandXMLImport
"""
class SettingsLandXMLExport(TreeOidWrapper):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
AlignmentExport = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: AlignmentExport(self: SettingsLandXMLExport) -> SettingsAlignmentExport
"""
Data = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Data(self: SettingsLandXMLExport) -> SettingsData
"""
FeatureLineExport = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: FeatureLineExport(self: SettingsLandXMLExport) -> SettingsFeatureLineExport
"""
Identification = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Identification(self: SettingsLandXMLExport) -> SettingsIdentification
"""
ParcelExport = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: ParcelExport(self: SettingsLandXMLExport) -> SettingsParcelExport
"""
PointExport = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: PointExport(self: SettingsLandXMLExport) -> SettingsPointExport
"""
SurfaceExport = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: SurfaceExport(self: SettingsLandXMLExport) -> SettingsSurfaceExport
"""
SettingsAlignmentExport = None
SettingsData = None
SettingsFeatureLineExport = None
SettingsIdentification = None
SettingsParcelExport = None
SettingsPointExport = None
SettingsSurfaceExport = None
class SettingsLandXMLImport(TreeOidWrapper):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
AlignmentImport = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: AlignmentImport(self: SettingsLandXMLImport) -> SettingsAlignmentImport
"""
ConflictResolution = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: ConflictResolution(self: SettingsLandXMLImport) -> SettingsConflictResolution
"""
DiameterUnits = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: DiameterUnits(self: SettingsLandXMLImport) -> SettingsDiameterUnits
"""
FeatureLineImport = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: FeatureLineImport(self: SettingsLandXMLImport) -> SettingsFeatureLineImport
"""
PipeNetwork = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: PipeNetwork(self: SettingsLandXMLImport) -> SettingsPipeNetwork
"""
PointImport = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: PointImport(self: SettingsLandXMLImport) -> SettingsPointImport
"""
PropertySetData = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: PropertySetData(self: SettingsLandXMLImport) -> SettingsPropertySetData
"""
Rotation = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Rotation(self: SettingsLandXMLImport) -> SettingsRotation
"""
SurfaceImport = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: SurfaceImport(self: SettingsLandXMLImport) -> SettingsSurfaceImport
"""
Translation = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Translation(self: SettingsLandXMLImport) -> SettingsTranslation
"""
SettingsAlignmentImport = None
SettingsConflictResolution = None
SettingsDiameterUnits = None
SettingsFeatureLineImport = None
SettingsPipeNetwork = None
SettingsPointImport = None
SettingsPropertySetData = None
SettingsRotation = None
SettingsSurfaceImport = None
SettingsTranslation = None
class SettingsMassHaulLine(SettingsAmbient):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsMatchLine(SettingsAmbient):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsObjectLayer(TreeOidWrapper):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
LayerId = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: LayerId(self: SettingsObjectLayer) -> ObjectId
Set: LayerId(self: SettingsObjectLayer) = value
"""
LayerName = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: LayerName(self: SettingsObjectLayer) -> str
Set: LayerName(self: SettingsObjectLayer) = value
"""
Locked = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Locked(self: SettingsObjectLayer) -> bool
Set: Locked(self: SettingsObjectLayer) = value
"""
Modifier = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Modifier(self: SettingsObjectLayer) -> ObjectLayerModifierType
Set: Modifier(self: SettingsObjectLayer) = value
"""
ModifierValue = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: ModifierValue(self: SettingsObjectLayer) -> str
Set: ModifierValue(self: SettingsObjectLayer) = value
"""
ObjectType = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: ObjectType(self: SettingsObjectLayer) -> SettingsObjectLayerType
"""
class SettingsObjectLayers(TreeOidWrapper):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
def GetObjectLayerSetting(self, settingsType):
""" GetObjectLayerSetting(self: SettingsObjectLayers, settingsType: SettingsObjectLayerType) -> SettingsObjectLayer """
pass
ObjectControlledByLayer = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: ObjectControlledByLayer(self: SettingsObjectLayers) -> bool
Set: ObjectControlledByLayer(self: SettingsObjectLayers) = value
"""
class SettingsObjectLayerType(Enum):
""" enum SettingsObjectLayerType, values: Alignment (0), AlignmentLabeling (1), AlignmentTable (2), Appurtenance (56), AppurtenanceLabeling (57), Assembly (3), BuildingSite (53), CantView (58), Catchment (59), CatchmentLabeling (60), Corridor (4), CorridorSection (5), FeatureLine (6), Fitting (61), FittingLabeling (62), GeneralNoteLabel (7), GeneralSegmentLabel (8), Grading (9), GradingLabeling (10), GridSurface (11), GridSurfaceLabeling (12), Interference (13), Intersection (54), IntersectionLabeling (55), MassHaulLine (14), MassHaulView (15), MatchLine (16), MatchLineLabeling (17), MaterialSection (18), MaterialTable (19), Parcel (20), ParcelLabeling (21), ParcelSegment (22), ParcelSegmentLabeling (23), ParcelTable (24), Pipe (25), PipeAndStructureTable (27), PipeLabeling (26), PipeNetworkSection (28), PipeOrStructureProfile (29), PointTable (30), PressureNetworkSection (63), PressurePartProfile (64), PressurePartTable (65), PressurePipe (66), PressurePipeLabeling (67), Profile (31), ProfileLabeling (32), ProfileView (33), ProfileViewLabeling (34), SampleLine (35), SampleLineLabeling (36), Section (37), SectionLabeling (38), SectionView (39), SectionViewLabeling (40), SectionViewQuantityTakeoffTable (41), Sheet (42), Structure (43), StructureLabeling (44), Subassembly (45), SuperelevationView (68), SurfaceLegendTable (46), SurveyFigure (47), SurveyFigureLabeling (69), SurveyFigureSegmentLable (70), SurveyNetwork (48), TinSurface (49), TinSurfaceLabeling (50), ViewFrame (51), ViewFrameLabeling (52) """
Alignment = None
AlignmentLabeling = None
AlignmentTable = None
Appurtenance = None
AppurtenanceLabeling = None
Assembly = None
BuildingSite = None
CantView = None
Catchment = None
CatchmentLabeling = None
Corridor = None
CorridorSection = None
FeatureLine = None
Fitting = None
FittingLabeling = None
GeneralNoteLabel = None
GeneralSegmentLabel = None
Grading = None
GradingLabeling = None
GridSurface = None
GridSurfaceLabeling = None
Interference = None
Intersection = None
IntersectionLabeling = None
MassHaulLine = None
MassHaulView = None
MatchLine = None
MatchLineLabeling = None
MaterialSection = None
MaterialTable = None
Parcel = None
ParcelLabeling = None
ParcelSegment = None
ParcelSegmentLabeling = None
ParcelTable = None
Pipe = None
PipeAndStructureTable = None
PipeLabeling = None
PipeNetworkSection = None
PipeOrStructureProfile = None
PointTable = None
PressureNetworkSection = None
PressurePartProfile = None
PressurePartTable = None
PressurePipe = None
PressurePipeLabeling = None
Profile = None
ProfileLabeling = None
ProfileView = None
ProfileViewLabeling = None
SampleLine = None
SampleLineLabeling = None
Section = None
SectionLabeling = None
SectionView = None
SectionViewLabeling = None
SectionViewQuantityTakeoffTable = None
Sheet = None
Structure = None
StructureLabeling = None
Subassembly = None
SuperelevationView = None
SurfaceLegendTable = None
SurveyFigure = None
SurveyFigureLabeling = None
SurveyFigureSegmentLable = None
SurveyNetwork = None
TinSurface = None
TinSurfaceLabeling = None
value__ = None
ViewFrame = None
ViewFrameLabeling = None
class SettingsPipe(SettingsAmbient):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsPressureAppurtenance(SettingsAmbient):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsPressureFitting(SettingsAmbient):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsPressurePipe(SettingsAmbient):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsRoot(TreeOidWrapper):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
def GetSettings(self):
AssociateShortcutProjectId = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: AssociateShortcutProjectId(self: SettingsRoot) -> str
Set: AssociateShortcutProjectId(self: SettingsRoot) = value
"""
DrawingSettings = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: DrawingSettings(self: SettingsRoot) -> SettingsDrawing
"""
LandXMLSettings = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: LandXMLSettings(self: SettingsRoot) -> SettingsLandXML
"""
TagSettings = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: TagSettings(self: SettingsRoot) -> SettingsTag
"""
class SettingsSection(SettingsAmbient):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
NameFormat = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: NameFormat(self: SettingsSection) -> SettingsNameFormat
"""
Styles = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Styles(self: SettingsSection) -> SettingsStyles
"""
SettingsNameFormat = None
SettingsStyles = None
class SettingsStructure(SettingsAmbient):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SettingsTag(TreeOidWrapper):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
Creation = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Creation(self: SettingsTag) -> SettingsCreation
"""
Renumbering = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: Renumbering(self: SettingsTag) -> SettingsRenumbering
"""
SettingsCreation = None
SettingsRenumbering = None
class SettingsTransformation(TreeOidWrapper):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
ApplySeaLevelScaleFactor = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: ApplySeaLevelScaleFactor(self: SettingsTransformation) -> bool
Set: ApplySeaLevelScaleFactor(self: SettingsTransformation) = value
"""
GridReferencePoint = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: GridReferencePoint(self: SettingsTransformation) -> Point2d
Set: GridReferencePoint(self: SettingsTransformation) = value
"""
GridRotationPoint = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: GridRotationPoint(self: SettingsTransformation) -> Point2d
Set: GridRotationPoint(self: SettingsTransformation) = value
"""
GridScaleFactor = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: GridScaleFactor(self: SettingsTransformation) -> float
Set: GridScaleFactor(self: SettingsTransformation) = value
"""
GridScaleFactorComputation = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: GridScaleFactorComputation(self: SettingsTransformation) -> GridScaleFactorType
Set: GridScaleFactorComputation(self: SettingsTransformation) = value
"""
LocalReferencePoint = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: LocalReferencePoint(self: SettingsTransformation) -> Point2d
Set: LocalReferencePoint(self: SettingsTransformation) = value
"""
LocalRotationPoint = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: LocalRotationPoint(self: SettingsTransformation) -> Point2d
Set: LocalRotationPoint(self: SettingsTransformation) = value
"""
RotationToGridAzimuth = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: RotationToGridAzimuth(self: SettingsTransformation) -> float
Set: RotationToGridAzimuth(self: SettingsTransformation) = value
"""
RotationToGridNorth = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: RotationToGridNorth(self: SettingsTransformation) -> float
Set: RotationToGridNorth(self: SettingsTransformation) = value
"""
SeaLevelScaleElevation = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: SeaLevelScaleElevation(self: SettingsTransformation) -> float
Set: SeaLevelScaleElevation(self: SettingsTransformation) = value
"""
SpecifyRotationType = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: SpecifyRotationType(self: SettingsTransformation) -> SpecifyRotationType
Set: SpecifyRotationType(self: SettingsTransformation) = value
"""
SpheroidRadius = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: SpheroidRadius(self: SettingsTransformation) -> float
"""
class SettingsUnitZone(TreeOidWrapper):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
@staticmethod
def GetAllCodes():
""" GetAllCodes() -> Array[str] """
pass
@staticmethod
def GetCoordinateSystemByCode(code):
""" GetCoordinateSystemByCode(code: str) -> SettingsCoordinateSystem """
pass
AngularUnits = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: AngularUnits(self: SettingsUnitZone) -> AngleUnitType
Set: AngularUnits(self: SettingsUnitZone) = value
"""
CoordinateSystemCode = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: CoordinateSystemCode(self: SettingsUnitZone) -> str
Set: CoordinateSystemCode(self: SettingsUnitZone) = value
"""
DrawingScale = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: DrawingScale(self: SettingsUnitZone) -> float
Set: DrawingScale(self: SettingsUnitZone) = value
"""
DrawingUnits = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: DrawingUnits(self: SettingsUnitZone) -> DrawingUnitType
Set: DrawingUnits(self: SettingsUnitZone) = value
"""
ImperialToMetricConversion = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: ImperialToMetricConversion(self: SettingsUnitZone) -> ImperialToMetricConversionType
Set: ImperialToMetricConversion(self: SettingsUnitZone) = value
"""
MatchAutoCADVariables = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: MatchAutoCADVariables(self: SettingsUnitZone) -> bool
Set: MatchAutoCADVariables(self: SettingsUnitZone) = value
"""
ScaleObjectsFromOtherDrawings = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: ScaleObjectsFromOtherDrawings(self: SettingsUnitZone) -> bool
Set: ScaleObjectsFromOtherDrawings(self: SettingsUnitZone) = value
"""
class SettingsViewFrame(SettingsAmbient):
def Dispose(self):
""" Dispose(self: DisposableWrapper, A_0: bool) """
pass
class SpecifyRotationType(Enum):
""" enum SpecifyRotationType, values: GridRotationAngle (1), RotationPoint (0) """
GridRotationAngle = None
RotationPoint = None
value__ = None
class TableAnchorType(Enum):
""" enum TableAnchorType, values: BottomCenter (7), BottomLeft (6), BottomRight (8), MiddleCenter (4), MiddleLeft (3), MiddleRight (5), TopCenter (1), TopLeft (0), TopRight (2) """
BottomCenter = None
BottomLeft = None
BottomRight = None
MiddleCenter = None
MiddleLeft = None
MiddleRight = None
TopCenter = None
TopLeft = None
TopRight = None
value__ = None
class TableLayoutType(Enum):
""" enum TableLayoutType, values: Horizontal (0), Vertical (1) """
Horizontal = None
value__ = None
Vertical = None
class TileDirectionType(Enum):
""" enum TileDirectionType, values: Across (0), Down (1) """
Across = None
Down = None
value__ = None
| false | true |
790bf59a165f1925a9da1f25fa5a2e9a0d530556 | 25,330 | py | Python | coupled_channel/cutils.py | AleksiNummelin/coupled_channel | 0e96e54400bb853b8c42cfc55b968a476114dcef | [
"MIT"
] | 2 | 2020-11-16T10:46:33.000Z | 2020-11-16T10:46:35.000Z | coupled_channel/cutils.py | AleksiNummelin/coupled_channel | 0e96e54400bb853b8c42cfc55b968a476114dcef | [
"MIT"
] | null | null | null | coupled_channel/cutils.py | AleksiNummelin/coupled_channel | 0e96e54400bb853b8c42cfc55b968a476114dcef | [
"MIT"
] | null | null | null | #from numba import jit
import numpy as np
#from joblib import Parallel, delayed, parallel_backend
#from joblib import load, dump
#import tempfile
#import shutil
#import os
#
#import sys
#sys.path.append('pyunicorn_timeseries')
#from pyunicorn_timeseries.surrogates import Surrogates
def set_model_constants(xx=50.E3,nx=100,va=10.,tmax=60*360*24*3600.,avep=24*3600.,dt=3600.,period=3600*24*360*1,B=2.,T0=273.15+6,dT=2.,Cs=1.E-3,Cp=1030.,ra=1.5,ro=1030.,ri=900.,Cpo=4.E3,Cpi=2.9E3,H=200.,vo=0.2,Hb=1.E3,Li=3.3E6,Tf=273.15-1.8,SW0=50.,SW_anom=100.,emissivity=0.99,Da=1.E6,Do=5.E2,tau_entrainment=30*24*3600.,**args):
'''Setup model constants. All of the constants have fixed values, but one can pass in own values or even some arbitrary values via **args.'''
#
C={}
C['xx'] = xx #grid size in [m]
C['nx'] = nx #number of grid cell - the total width of the domain is xx*nx long
C['va'] = va #wind in m/s
#
C['tmax'] = tmax #tmax seconds
C['dt'] = dt #timestep
#
C['avep'] = avep #averaging period in seconds
#
C['period'] = period #period of boundary restoring
C['Cs'] = Cs #exchange coefficient for bulk formula
C['Cp'] = Cp #air heat capacity
C['ra'] = ra #density of air [kg/m3]
C['ro'] = ro #density of sea water [kg/m3]
C['ri'] = ri #density of sea ice [kg/m3]
C['Cpo'] = Cpo #sea water heat capacity
C['T0'] = T0 #initial temp in degC
C['dT'] = dT #initial temp perturbationHb=2E3
C['H'] = H #mixed layer depth in ocean [m]
C['vo'] = vo #ocean current speed [m/s]
C['Hb'] = Hb #boundary layer height in the atmosphere [m]
C['Cpi'] = Cpi #sea ice heat capacity [J/ Kg K]
C['Li'] = Li #Latent heat of fusion of sea water [J / kg K]
C['Tf'] = Tf #Freezing point of sea water [C]
C['B'] = B # long-wave radiation constant [W/m2]
C['emissivity'] = emissivity #surface emissivity
C['SW0'] = SW0 # background net downwelling SW radiation
C['SW_anom']= SW_anom # amplitude of annual cycle in SW radiation
C['Da'] = Da # atmospheric diffusion [m2/s]
C['Do'] = Do # ocean diffusion [m2/s]
C['tau_entrainment'] = tau_entrainment # ocean entrainment/damping timescale
for var in args.keys():
C[var]=args[var]
#
return C
def CoupledChannel(C,forcing, T_boundary=None, dt_f=30*24*3600, restoring=False,ice_model=True,atm_adv=True,spatial_pattern=None,atm_DA_tendencies=None,ocn_DA_tendencies=None, return_coupled_fluxes=False,random_amp=0.1):
'''
This is the main function for the coupled ocean--atm channel model.
## INPUT VARIABLES ##
tmax: running time in seconds
avep: averaging period for the ouput
T0: initial temperature
forcing: dimensionless scaling for the heat flux forcing - default strength is 5 W/m2
dt_f: timestep of the forcing
atm_adv: boolean, advective atmosphere
atm_ocn: boolean, advective ocean
'''
#
# number of simulation timesteps and output timesteps
nt = int(C['tmax']/C['dt']) #simulation
nt1 = int(C['tmax']/C['avep']) #output
# rtas = np.random.rand(C['nx'])
# intitialize the model variables, first dimension is due to 2 timesteps deep scheme
sst = C['T0']*np.ones((2,C['nx']))
tas = C['T0']*np.ones((2,C['nx'])) #+rtas
hice = np.zeros((2,C['nx']))
# INCOMING SHORTWAVE RADIATION
SW0 = np.tile(C['SW0'][:,np.newaxis],(1,nt))
naxis = np.tile(np.arange(nt)[np.newaxis,],(C['nx'],1))
SW_warming = np.max(np.concatenate([(SW0-C['SW_anom']*np.cos(2*np.pi*(naxis*C['dt'])/(360*24*3600)))[np.newaxis,],np.zeros((C['nx'],nt))[np.newaxis,]],axis=0),0)
# If boundary conditions are not defined, then set initially to T0
if np.all(T_boundary==None):
T_boundary=C['T0']*np.ones(nt)
#
sst_boundary=T_boundary[0]*np.ones((2)) #nt+1
# evolve_boundary=True
#else:
# sst_boundary=np.concatenate((sst_boundary[np.newaxis,],sst_boundary[np.newaxis,]),axis=0)
# evolve_boundary=False
#
# interpolate forcing to the new timescale
if np.all(forcing!=None):
forcing = np.interp(np.arange(0,len(forcing)*dt_f,C['dt']),np.arange(0,len(forcing)*dt_f,dt_f),forcing)
else:
forcing = np.zeros(nt+1)
#
# initialize outputs
sst_out = np.zeros((nt1,C['nx']))
tas_out = np.zeros((nt1,C['nx']))
hice_out = np.zeros((nt1,C['nx']))
sflx_f_out = np.zeros((nt1,C['nx'])) #forcing
sflx_out = np.zeros((nt1,C['nx']))
# spatial pattern of the forcing - assume a sine wave
if np.all(spatial_pattern==None):
spatial_pattern=np.ones(C['nx'])
#
if np.all(atm_DA_tendencies!=None):
use_atm_tendencies=True
else:
use_atm_tendencies=False
if np.all(ocn_DA_tendencies!=None):
use_ocn_tendencies=True
else:
use_ocn_tendencies=False
#
if return_coupled_fluxes:
atm_DA_tendencies = np.zeros((nt,C['nx']))
ocn_DA_tendencies = np.zeros((nt,C['nx']))
# initialize counters
c=0; c2=0; c3=0; n=1
#####################
# --- TIME LOOP ---
#####################
for nn in range(nt):
#
# FORCING - WILL BE ZERO IF NOT SPECIFIED, no spatial pattern if not specified
sflx=forcing[nn]*spatial_pattern #+ forcing[nn]*random_amp*np.random.rand(C['nx'])
#
# save the forcing component
#
sflx_f_out[c,:]=sflx_f_out[c,:]+sflx
#
# SURFACE HEAT FLUXES
# Add sensible heat flux to the total surface flux in W/m**-2
sflx=sflx+C['ra']*C['Cp']*C['va']*C['Cs']*(sst[n-1,:]-tas[n-1,:])
# RADIATIVE FLUXES - LW will cool the atmosphere, SW will warm the ocean
LW_cooling = C['emissivity']*5.67E-8*(tas[n-1,:]**4)
#
# OCEAN BOUNDARY CONDITION
#if evolve_boundary:
sst_boundary_tendency=SW_warming[0,nn]*C['dt']/(C['H']*C['Cpo']*C['ro'])-C['emissivity']*5.67E-8*(sst_boundary[n-1]**4)*C['dt']/(C['H']*C['Cpo']*C['ro'])+(T_boundary[nn]-sst_boundary[n-1])*C['dt']/C['period']
############################################
#
# ATMOSPHERE
#
############################################
#
# ADVECTION
#
# set atm_adv=False is no atmospheric advection - note that we still need to know the wind speed to resolve heat fluxes
if atm_adv:
a_adv = np.concatenate([sst_boundary[n-1]-tas[n-1,:1],tas[n-1,:-1]-tas[n-1,1:]],axis=0)*(C['va']*C['dt']/C['xx'])
else:
a_adv = 0
#
# DIFFUSION
#
a_diff = (tas[n-1,2:]+tas[n-1,:-2]-2*tas[n-1,1:-1])*(C['Da']*C['dt']/(C['xx']**2))
a_diff0 = (tas[n-1,1]+sst_boundary[n-1]-2*tas[n-1,0])*(C['Da']*C['dt']/(C['xx']**2))
a_diff = np.concatenate([np.array([a_diff0]),a_diff,a_diff[-1:]],axis=0)
#
# SURFACE FLUXES
#
a_netsflx = (sflx*C['dt'])/(C['Hb']*C['Cp']*C['ra']) - LW_cooling*C['dt']/(C['Hb']*C['Cp']*C['ra'])
#
#
if return_coupled_fluxes:
atm_DA_tendencies[nn,:] = a_adv + a_diff
#
# ATM UPDATE
#
if use_atm_tendencies:
tas[n,:] = tas[n-1,:] + a_netsflx + atm_DA_tendencies[c3,:]
else:
tas[n,:] = tas[n-1,:] + a_netsflx + a_adv + a_diff
#
################################################
#
# OCEAN
#
################################################
# AND DIFFUSION + ENTRAINMENT
# ocean advection
#
# ADVECTION set vo=0 for stagnant ocean (slab)
#
o_adv = np.concatenate([sst_boundary[n-1]-sst[n-1,:1],sst[n-1,:-1]-sst[n-1,1:]],axis=0)*(C['vo']*C['dt']/C['xx'])
#
# DIFFUSION
#
o_diff = (sst[n-1,2:]+sst[n-1,:-2]-2*sst[n-1,1:-1])*(C['Do']*C['dt']/(C['xx']**2))
o_diff0 = (sst[n-1,1]+sst_boundary[n-1]-2*sst[n-1,0])*(C['Do']*C['dt']/(C['xx']**2))
o_diff = np.concatenate([np.array([o_diff0]),o_diff,o_diff[-1:]],axis=0)
#
# ENTRAINMENT - RESTORING TO AN AMBIENT WATER MASS (CAN BE SEEN AS LATERAL OR VERTICAL MIXING)
# set tau_entrainment=0 for no entrainment
if C['tau_entrainment']>0:
o_entrain = (C['T0']-sst[n-1,:])*C['dt']/C['tau_entrainment']
else:
o_entrain = 0
#
# SURFACE FLUXES
#
o_netsflx = -sflx*C['dt']/(C['H']*C['Cpo']*C['ro'])+SW_warming[:,nn]*C['dt']/(C['H']*C['Cpo']*C['ro'])
#
if return_coupled_fluxes:
ocn_DA_tendencies[nn,:] = o_adv + o_diff + o_entrain
#
# OCN update
if use_ocn_tendencies:
sst[n,:] = sst[n-1,:] + o_netsflx + ocn_DA_tendencies[c3,:]
else:
sst[n,:] = sst[n-1,:] + o_netsflx + o_adv + o_diff + o_entrain
#
if ice_model:
# THIS IS A DIAGNOSTIC SEA ICE MODEL
#
# SST is first allowed to cool below freezing and then we form sea ice from the excess_freeze
# i.e the amount that heat that is used to cool SST below freezing is converted to ice instead.
# Similarly, SST is allowed to warm above Tf even if there is ice, and then excess_melt,
# i.e. the amount of heat that is used to warm the water is first used to melt ice,
# and then the rest can warm the water.
#
# This scheme conserves energy - it simply switches it between ocean and ice storages
#
# advection
#hice[n-1,1:]=hice[n-1,1:]-(hice[n-1,:-1]-hice[n-1,1:])*(C['vo']*C['dt']/C['xx'])
#dhice = (hice[n-1,:-1]-hice[n-1,1:])*(C['vo']*C['dt']/C['xx'])
#hice[n-1,:-1] = hice[n-1,:-1] -dhice
#hice[n-1,-1] = hice[n-1,-1] + dhice[-1]
#
ice_mask = (hice[n-1,:]>0).astype(np.float) #cells where there is ice to melt
freezing_mask = (sst[n,:]<C['Tf']).astype(np.float) #cells where freezing will happen
# change in energy
dEdt = C['H']*C['ro']*C['Cpo']*(sst[n,:]-sst[n-1,:])/C['dt']
# negative change in energy will produce ice whenver the water would otherwise cool below freezing
excess_freeze = freezing_mask*np.max([-dEdt,np.zeros(C['nx'])],axis=0)
# positive change will melt ice where there is ice
excess_melt = ice_mask*np.max([dEdt,np.zeros(C['nx'])],axis=0)
# note that freezing and melting will never happen at the same time in the same cell
# freezing
dhice_freeze = C['dt']*excess_freeze/(C['Li']*C['ri'])
# melting
dhice_melt= C['dt']*excess_melt/(C['Li']*C['ri'])
# update
hice[n,:] = hice[n-1,:] + dhice_freeze - dhice_melt
# check how much energy was used for melting sea ice - remove this energy from ocean
hice_melt = (dhice_melt>0).astype(np.float)*np.min([dhice_melt,hice[n-1,:]],axis=0)
# Do not allow ice to be negative - that energy is kept in the ocean all the time.
# The line above ensures that not more energy than is needed to melt the whole ice cover
# is removed from the ocean at any given time
hice[n,:] = np.max([hice[n,:],np.zeros(C['nx'])],axis=0)
#
# Update SST
# Give back the energy that was used for freezing (will keep the water temperature above freezing)
sst[n,:] = sst[n,:] + C['dt']*excess_freeze/(C['H']*C['Cpo']*C['ro'])
# take out the heat that was used to melt ice
# (need to cap to hice, the extra heat is never used and will stay in the ocean)
sst[n,:] = sst[n,:] - hice_melt*(C['Li']*C['ri'])/(C['ro']*C['Cpo']*C['H'])
#
#############################
# --- PREPARE OUTPUT ----
#############################
# accumulate output
tas_out[c,:] = tas_out[c,:]+tas[n,:]
sst_out[c,:] = sst_out[c,:]+sst[n,:]
hice_out[c,:] = hice_out[c,:]+hice[n,:]
sflx_out[c,:] = sflx_out[c,:]+sflx
# accumulate averaging counter
c2=c2+1
c3=c3+1
if ((nn+1)*C['dt'])%(360*24*3600)==0:
#print(nn)
c3=0
#calculate the average for the output
if (((nn+1)*C['dt'])%C['avep']==0 and nn>0):
tas_out[c,:] = tas_out[c,:]/c2
sst_out[c,:] = sst_out[c,:]/c2
sflx_out[c,:] = sflx_out[c,:]/c2
sflx_f_out[c,:] = sflx_f_out[c,:]/c2
hice_out[c,:] = hice_out[c,:]/c2
# update counters
c = c+1
c2 = 0
if ((nn+1)*C['dt'])%(360*24*3600)==0:
print('Year ', (nn+1)*C['dt']/(360*24*3600), sst[1,int(C['nx']/4)], sst[1,int(3*C['nx']/4)])
#update the variables
tas[0,:] = tas[1,:].copy()
sst[0,:] = sst[1,:].copy()
hice[0,:] = hice[1,:].copy()
# SST at the boundary
sst_boundary[n-1]=sst_boundary[n-1]+sst_boundary_tendency
#
#
# if there is no ice, set to nan
hice_out[np.where(hice_out==0)]=np.nan
#
if return_coupled_fluxes:
return tas_out, sst_out, hice_out, sflx_out, sflx_f_out, nt1, nt, atm_DA_tendencies, ocn_DA_tendencies
else:
return tas_out, sst_out, hice_out, sflx_out, sflx_f_out, nt1, nt
#@jit(nopython=True)
def CoupledChannel_time(nt,nx,xx,dt,avep,sst,tas,hice,sst_boundary,sst_out,tas_out,hice_out,sflx_f_out,sflx_out,forcing,spatial_pattern,ra,Cp,va,vo,Da,Do,Cs,T0,Tf,emissivity,SW0,SW_anom,H,Hb,Cpo,ro,tau_entrainment,Li,ri,use_ocn_tendencies,use_atm_tendencies, atm_DA_tendencies, ocn_DA_tendencies,ice_model,atm_adv,return_coupled_fluxes):
'''
Separate time loop to enable numba
'''
#initialize counters
c=0; c2=0; c3=0; n=1
#####################
# --- TIME LOOP ---
#####################
for nn in range(nt):
#
# FORCING - WILL BE ZERO IF NOT SPECIFIED, no spatial pattern if not specified
sflx=forcing[nn]*spatial_pattern #+ forcing[nn]*random_amp*np.random.rand(C['nx'])
#
# save the forcing component
#
sflx_f_out[c,:]=sflx_f_out[c,:]+sflx
#
# SURFACE HEAT FLUXES
# Add sensible heat flux to the total surface flux in W/m**-2
sflx=sflx+ra*Cp*va*Cs*(sst[n-1,:]-tas[n-1,:])
# RADIATIVE FLUXES - LW will cool the atmosphere, SW will warm the ocean
LW_cooling = emissivity*5.67E-8*(tas[n-1,:]**4)
SW_warming = SW0+max(SW_anom*np.sin(2*float(nn)*dt*np.pi/(360*24*3600)),0.0)
#net_radiation = SW_warming-LW_cooling
net_radiation = -LW_cooling
#
# OCEAN BOUNDARY CONDITION - SET dT to zero to suppress the sin
sst_boundary[n]=sst_boundary[n-1]+SW_warming[0]*dt/(H*Cpo*ro)-emissivity*5.67E-8*(sst_boundary[n-1]**4)*dt/(H*Cpo*ro)+(T0-sst_boundary[n-1])*dt/(360*24*3600) #C['T0']+C['dT']*np.sin(nn*C['dt']*np.pi/C['period']) +
#
# ATMOSPHERE - ADVECTION AND DIFFUSION
# set atm_adv=False is no atmospheric advection - note that we need to know the wind speed to resolve heat fluxes
if atm_adv:
a_adv = np.concatenate((sst_boundary[n-1]-tas[n-1,:1],tas[n-1,:-1]-tas[n-1,1:]),axis=0)*(va*dt/xx)
#tas[n,0]=tas[n-1,0]+(C['T0']-tas[n-1,0])*(C['va']*C['dt']/C['xx']) #always constant temperature blowing over the ocean from land
#tas[n,0]=tas[n-1,0]+(sst[n,0]-tas[n-1,0])*(C['va']*C['dt']/C['xx']) #atmospheric temperature at the boundary is in equilibrium with the ocean
#tas[n,1:]=tas[n-1,1:]+(tas[n-1,:-1]-tas[n-1,1:])*(C['va']*C['dt']/C['xx'])
else:
#tas[n,:] = tas[n-1,0]
a_adv = np.zeros(nx)
#
# DIFFUSION
#
#tas[n,1:-1] = tas[n,1:-1] + (tas[n-1,2:]+tas[n-1,:-2]-2*tas[n-1,1:-1])*(C['Da']*C['dt']/(C['xx']**2))
a_diff = (tas[n-1,2:]+tas[n-1,:-2]-2*tas[n-1,1:-1])*(Da*dt/(xx**2))
a_diff0 = (tas[n-1,1]+sst_boundary[n-1]-2*tas[n-1,0])*(Da*dt/(xx**2))
a_diff = np.concatenate((np.array([a_diff0]),a_diff,a_diff[-1:]),axis=0)
#
# ATMOSPHERE - SURFACE FLUXES
#
a_netsflx = (sflx*dt)/(Hb*Cp*ra) + net_radiation*dt/(Hb*Cp*ra)
#
# full update
#
#
if return_coupled_fluxes:
atm_DA_tendencies[nn,:]=np.sum((a_adv,a_diff),axis=0)
#
if use_atm_tendencies:
tas[n,:] = tas[n-1,:] + a_netsflx + atm_DA_tendencies[c3,:]
else:
tas[n,:] = tas[n-1,:] + a_netsflx + a_adv + a_diff
#
# OCEAN - ADVECTION AND DIFFUSION + ENTRAINMENT
# ocean advection
# set vo=0 for stagnant ocean (slab)
#
#sst[n,1:] = sst[n-1,1:]+(sst[n-1,:-1]-sst[n-1,1:])*(1-ocn_mixing_ratio)*(C['vo']*C['dt']/C['xx'])+(C['T0']-sst[n-1,1:])*ocn_mixing_ratio*(C['vo']*C['dt']/C['xx'])
o_adv = np.concatenate((sst_boundary[n-1]-sst[n-1,:1],sst[n-1,:-1]-sst[n-1,1:]),axis=0)*(vo*dt/xx)
# DIFFUSION
#sst[n,1:-1] = sst[n,1:-1] + (sst[n-1,2:]+sst[n-1,:-2]-2*sst[n-1,1:-1])*(C['Do']*C['dt']/(C['xx']**2))
o_diff = (sst[n-1,2:]+sst[n-1,:-2]-2*sst[n-1,1:-1])*(Do*dt/(xx**2))
o_diff0 = (sst[n-1,1]+sst_boundary[n-1]-2*sst[n-1,0])*(Do*dt/(xx**2))
o_diff = np.concatenate((np.array([o_diff0]),o_diff,o_diff[-1:]),axis=0)
# ENTRAINMENT (damping by a lower layer)
o_entrain = (T0-sst[n-1,:])*dt/tau_entrainment
#sst[n,1:]=sst[n,1:]+(C['T0']-sst[n-1,1:])*C['dt']/C['tau_entrainment']
#
# OCEAN - SURFACE FLUXES
#
o_netsflx = -sflx*dt/(H*Cpo*ro)+SW_warming*dt/(H*Cpo*ro)
#sst[n,:]=sst[n,:]-(sflx*C['dt'])/(C['H']*C['Cpo']*C['ro'])
if return_coupled_fluxes:
ocn_DA_tendencies[nn,:] = o_adv + o_diff + o_entrain
# OCN update
if use_ocn_tendencies:
sst[n,:] = sst[n-1,:] + o_netsflx + ocn_DA_tendencies[c3,:]
else:
sst[n,:] = sst[n-1,:] + o_netsflx + o_adv + o_diff + o_entrain
#
if ice_model:
# THIS IS A DIAGNOSTIC SEA ICE MODEL
#
# sst is first allowed to cool below freezing and then we forM sea ice from the excess_freeze
# i.e the amount that heat that is used to cool sst below freezing is converted to ice instead
# similarly sst is allowed to warm above Tf even if there is ice, and then excess_melt,
# i.e. the amount of heat that is used to warm the water is first used to melt ice,
# and then the rest can warm water. This scheme conserves energy - it simply switches it between ocean and ice
#
ice_mask = (hice[n-1,:]>0).astype(np.float) #cells where there is ice to melt
freezing_mask = (sst[n,:]<Tf).astype(np.float) #cells where freezing will happen
# change in energy
dEdt = H*ro*Cpo*(sst[n,:]-sst[n-1,:])/dt
# negative change in energy will produce ice whenver the water would otherwise cool below freezing
excess_freeze = freezing_mask*np.max([-dEdt,np.zeros(nx)],axis=0)
# positive change will melt ice where there is ice
excess_melt = ice_mask*np.max([dEdt,np.zeros(nx)],axis=0)
# note that freezing and melting will never happen at the same time in the same cell
# freezing
dhice_freeze = dt*excess_freeze/(Li*ri)
# melting
dhice_melt= dt*excess_melt/(Li*ri)
# update
hice[n,:] = hice[n-1,:] + dhice_freeze - dhice_melt
# check how much energy was used for melting sea ice - remove this energy from ocean
hice_melt = (dhice_melt>0).astype(np.float)*np.min([dhice_melt,hice[n-1,:]],axis=0)
# Do not allow ice to be negative - that energy is kept in the ocean all the time.
# The line above ensures that not more energy than is needed to melt the whole ice cover
# is removed from the ocean at any given time
hice[n,:] = np.max([hice[n,:],np.zeros(nx)],axis=0)
#
# Update SST
# Give back the energy that was used for freezing (will keep the water temperature above freezing)
sst[n,:] = sst[n,:] + dt*excess_freeze/(H*Cpo*ro)
# take out the heat that was used to melt ice
# (need to cap to hice, the extra heat is never used and will stay in the ocean)
sst[n,:] = sst[n,:] - hice_melt*(Li*ri)/(ro*Cpo*H)
#
#############################
# --- PREPARE OUTPUT ----
#############################
#accumulate
tas_out[c,:] = tas_out[c,:]+tas[n,:]
sst_out[c,:] = sst_out[c,:]+sst[n,:]
hice_out[c,:] = hice_out[c,:]+hice[n,:]
sflx_out[c,:] = sflx_out[c,:]+sflx
# accumulate averaging counter
c2=c2+1
c3=c3+1
if ((nn+1)*dt)%(360*24*3600)==0:
#print(nn)
c3=0
#calculate the average for the output
if (((nn+1)*dt)%avep==0 and nn>0):
tas_out[c,:] = tas_out[c,:]/c2
sst_out[c,:] = sst_out[c,:]/c2
sflx_out[c,:] = sflx_out[c,:]/c2
sflx_f_out[c,:] = sflx_f_out[c,:]/c2
hice_out[c,:] = hice_out[c,:]/c2
# update counters
c = c+1
c2 = 0
#if ((nn+1)*C['dt'])%(360*24*3600)==0:
# print('Year ', (nn+1)*C['dt']/(360*24*3600), sst[1,int(C['nx']/4)], sst[1,int(3*C['nx']/4)])
#update the variables
tas[0,:] = tas[1,:].copy()
sst[0,:] = sst[1,:].copy()
hice[0,:] = hice[1,:].copy()
sst_boundary[0]=sst_boundary[1].copy()
#
hice_out[np.where(hice_out==0)]=np.nan
#
return tas_out, sst_out, hice_out, sflx_out, sflx_f_out, atm_DA_tendencies, ocn_DA_tendencies
def CoupledChannel2(C,forcing, dt_f=30*24*3600, ocn_mixing_ratio=0, restoring=False,ice_model=True,atm_adv=True,spatial_pattern=None,atm_DA_tendencies=None,ocn_DA_tendencies=None, return_coupled_fluxes=False,random_amp=0.1):
'''
This is the main function for the coupled ocean--atm channel model.
## INPUT VARIABLES ##
tmax: running time in seconds
avep: averaging period for the ouput
T0: initial temperature
forcing: dimensionless scaling for the heat flux forcing - default strength is 5 W/m2
dt_f: timestep of the forcing
atm_adv: boolean, advective atmosphere
atm_ocn: boolean, advective ocean
ocn_mixing: add non-local mixing to ocean
ocn_mixing_ratio: 0-1 ratio between advection and mixing (0 only advection; 1 only mixing)
'''
#
#print(C)
#print(C['T0'],C['SW0'],C['Da'],C['xx'])
#
nt=int(C['tmax']/C['dt']) #steps
nt1=int(C['tmax']/C['avep'])
tau=float(C['period'])/float(C['dt']) #this is period/dt, previously nt/8
rtas=np.random.rand(C['nx'])
#print(rtas.max())
#intitialize the model variables, only 2 timesteps deep scheme
sst=C['T0']*np.ones((2,C['nx']))
tas=C['T0']*np.ones((2,C['nx']))+rtas
hice=np.zeros((2,C['nx']))
sst_boundary=C['T0']*np.ones((2))
#
#print(sst.max(),tas.max())
#interpolate forcing to the new timescale
if np.all(forcing!=None):
forcing = np.interp(np.arange(0,len(forcing)*dt_f,C['dt']),np.arange(0,len(forcing)*dt_f,dt_f),forcing)
else:
forcing = np.zeros(nt+1)
#
#initialize outputs
sst_out = np.zeros((nt1,C['nx']))
tas_out = np.zeros((nt1,C['nx']))
hice_out = np.zeros((nt1,C['nx']))
sflx_f_out = np.zeros((nt1,C['nx'])) #forcing
sflx_out = np.zeros((nt1,C['nx']))
#spatial pattern of the forcing - assume a sine wave
if np.all(spatial_pattern==None):
spatial_pattern=np.ones(C['nx'])
#
if np.all(atm_DA_tendencies!=None):
use_atm_tendencies=True
else:
use_atm_tendencies=False
if np.all(ocn_DA_tendencies!=None):
use_ocn_tendencies=True
else:
use_ocn_tendencies=False
#
atm_DA_tendencies = np.zeros((nt,C['nx']))
ocn_DA_tendencies = np.zeros((nt,C['nx']))
#
tas_out, sst_out, hice_out, sflx_out, sflx_f_out, atm_DA_tendencies, ocn_DA_tendencies=CoupledChannel_time(nt,C['nx'],C['xx'],C['dt'],C['avep'],sst,tas,hice,sst_boundary,sst_out,tas_out,hice_out,sflx_f_out,sflx_out,forcing,spatial_pattern,C['ra'],C['Cp'],C['va'],C['vo'],C['Da'],C['Do'],C['Cs'],C['T0'],C['Tf'],C['emissivity'],C['SW0'],C['SW_anom'],C['H'],C['Hb'],C['Cpo'],C['ro'],C['tau_entrainment'],C['Li'],C['ri'],use_ocn_tendencies,use_atm_tendencies, atm_DA_tendencies, ocn_DA_tendencies,ice_model,atm_adv,return_coupled_fluxes)
#
if return_coupled_fluxes:
return tas_out, sst_out, hice_out, sflx_out, sflx_f_out, nt1, nt, atm_DA_tendencies, ocn_DA_tendencies
else:
return tas_out, sst_out, hice_out, sflx_out, sflx_f_out, nt1, nt
| 46.994434 | 538 | 0.557521 |
import numpy as np
def set_model_constants(xx=50.E3,nx=100,va=10.,tmax=60*360*24*3600.,avep=24*3600.,dt=3600.,period=3600*24*360*1,B=2.,T0=273.15+6,dT=2.,Cs=1.E-3,Cp=1030.,ra=1.5,ro=1030.,ri=900.,Cpo=4.E3,Cpi=2.9E3,H=200.,vo=0.2,Hb=1.E3,Li=3.3E6,Tf=273.15-1.8,SW0=50.,SW_anom=100.,emissivity=0.99,Da=1.E6,Do=5.E2,tau_entrainment=30*24*3600.,**args):
C={}
C['xx'] = xx
C['nx'] = nx
C['va'] = va
C['tmax'] = tmax
C['dt'] = dt
C['avep'] = avep
C['period'] = period
C['Cs'] = Cs
C['Cp'] = Cp
C['ra'] = ra
C['ro'] = ro
C['ri'] = ri
C['Cpo'] = Cpo
C['T0'] = T0
C['dT'] = dT
C['H'] = H
C['vo'] = vo
C['Hb'] = Hb
C['Cpi'] = Cpi
C['Li'] = Li
C['Tf'] = Tf
C['B'] = B
C['emissivity'] = emissivity
C['SW0'] = SW0
C['SW_anom']= SW_anom
C['Da'] = Da
C['Do'] = Do
C['tau_entrainment'] = tau_entrainment
for var in args.keys():
C[var]=args[var]
return C
def CoupledChannel(C,forcing, T_boundary=None, dt_f=30*24*3600, restoring=False,ice_model=True,atm_adv=True,spatial_pattern=None,atm_DA_tendencies=None,ocn_DA_tendencies=None, return_coupled_fluxes=False,random_amp=0.1):
nt = int(C['tmax']/C['dt'])
nt1 = int(C['tmax']/C['avep'])
sst = C['T0']*np.ones((2,C['nx']))
tas = C['T0']*np.ones((2,C['nx']))
hice = np.zeros((2,C['nx']))
SW0 = np.tile(C['SW0'][:,np.newaxis],(1,nt))
naxis = np.tile(np.arange(nt)[np.newaxis,],(C['nx'],1))
SW_warming = np.max(np.concatenate([(SW0-C['SW_anom']*np.cos(2*np.pi*(naxis*C['dt'])/(360*24*3600)))[np.newaxis,],np.zeros((C['nx'],nt))[np.newaxis,]],axis=0),0)
if np.all(T_boundary==None):
T_boundary=C['T0']*np.ones(nt)
sst_boundary=T_boundary[0]*np.ones((2))
if np.all(forcing!=None):
forcing = np.interp(np.arange(0,len(forcing)*dt_f,C['dt']),np.arange(0,len(forcing)*dt_f,dt_f),forcing)
else:
forcing = np.zeros(nt+1)
sst_out = np.zeros((nt1,C['nx']))
tas_out = np.zeros((nt1,C['nx']))
hice_out = np.zeros((nt1,C['nx']))
sflx_f_out = np.zeros((nt1,C['nx']))
sflx_out = np.zeros((nt1,C['nx']))
if np.all(spatial_pattern==None):
spatial_pattern=np.ones(C['nx'])
if np.all(atm_DA_tendencies!=None):
use_atm_tendencies=True
else:
use_atm_tendencies=False
if np.all(ocn_DA_tendencies!=None):
use_ocn_tendencies=True
else:
use_ocn_tendencies=False
if return_coupled_fluxes:
atm_DA_tendencies = np.zeros((nt,C['nx']))
ocn_DA_tendencies = np.zeros((nt,C['nx']))
c=0; c2=0; c3=0; n=1
/(C['H']*C['Cpo']*C['ro'])-C['emissivity']*5.67E-8*(sst_boundary[n-1]**4)*C['dt']/(C['H']*C['Cpo']*C['ro'])+(T_boundary[nn]-sst_boundary[n-1])*C['dt']/C['period']
a,Cp,va,vo,Da,Do,Cs,T0,Tf,emissivity,SW0,SW_anom,H,Hb,Cpo,ro,tau_entrainment,Li,ri,use_ocn_tendencies,use_atm_tendencies, atm_DA_tendencies, ocn_DA_tendencies,ice_model,atm_adv,return_coupled_fluxes):
c=0; c2=0; c3=0; n=1
radiation = -LW_cooling
sst_boundary[n]=sst_boundary[n-1]+SW_warming[0]*dt/(H*Cpo*ro)-emissivity*5.67E-8*(sst_boundary[n-1]**4)*dt/(H*Cpo*ro)+(T0-sst_boundary[n-1])*dt/(360*24*3600)
if atm_adv:
a_adv = np.concatenate((sst_boundary[n-1]-tas[n-1,:1],tas[n-1,:-1]-tas[n-1,1:]),axis=0)*(va*dt/xx)
iff = (tas[n-1,2:]+tas[n-1,:-2]-2*tas[n-1,1:-1])*(Da*dt/(xx**2))
a_diff0 = (tas[n-1,1]+sst_boundary[n-1]-2*tas[n-1,0])*(Da*dt/(xx**2))
a_diff = np.concatenate((np.array([a_diff0]),a_diff,a_diff[-1:]),axis=0)
a_netsflx = (sflx*dt)/(Hb*Cp*ra) + net_radiation*dt/(Hb*Cp*ra)
if return_coupled_fluxes:
atm_DA_tendencies[nn,:]=np.sum((a_adv,a_diff),axis=0)
if use_atm_tendencies:
tas[n,:] = tas[n-1,:] + a_netsflx + atm_DA_tendencies[c3,:]
else:
tas[n,:] = tas[n-1,:] + a_netsflx + a_adv + a_diff
o_adv = np.concatenate((sst_boundary[n-1]-sst[n-1,:1],sst[n-1,:-1]-sst[n-1,1:]),axis=0)*(vo*dt/xx)
o_diff = (sst[n-1,2:]+sst[n-1,:-2]-2*sst[n-1,1:-1])*(Do*dt/(xx**2))
o_diff0 = (sst[n-1,1]+sst_boundary[n-1]-2*sst[n-1,0])*(Do*dt/(xx**2))
o_diff = np.concatenate((np.array([o_diff0]),o_diff,o_diff[-1:]),axis=0)
o_entrain = (T0-sst[n-1,:])*dt/tau_entrainment
o_netsflx = -sflx*dt/(H*Cpo*ro)+SW_warming*dt/(H*Cpo*ro)
if return_coupled_fluxes:
ocn_DA_tendencies[nn,:] = o_adv + o_diff + o_entrain
if use_ocn_tendencies:
sst[n,:] = sst[n-1,:] + o_netsflx + ocn_DA_tendencies[c3,:]
else:
sst[n,:] = sst[n-1,:] + o_netsflx + o_adv + o_diff + o_entrain
if ice_model:
ice_mask = (hice[n-1,:]>0).astype(np.float)
freezing_mask = (sst[n,:]<Tf).astype(np.float)
dEdt = H*ro*Cpo*(sst[n,:]-sst[n-1,:])/dt
excess_freeze = freezing_mask*np.max([-dEdt,np.zeros(nx)],axis=0)
excess_melt = ice_mask*np.max([dEdt,np.zeros(nx)],axis=0)
dhice_freeze = dt*excess_freeze/(Li*ri)
dhice_melt= dt*excess_melt/(Li*ri)
hice[n,:] = hice[n-1,:] + dhice_freeze - dhice_melt
hice_melt = (dhice_melt>0).astype(np.float)*np.min([dhice_melt,hice[n-1,:]],axis=0)
hice[n,:] = np.max([hice[n,:],np.zeros(nx)],axis=0)
sst[n,:] = sst[n,:] + dt*excess_freeze/(H*Cpo*ro)
sst[n,:] = sst[n,:] - hice_melt*(Li*ri)/(ro*Cpo*H)
sst_boundary[0]=sst_boundary[1].copy()
hice_out[np.where(hice_out==0)]=np.nan
return tas_out, sst_out, hice_out, sflx_out, sflx_f_out, atm_DA_tendencies, ocn_DA_tendencies
def CoupledChannel2(C,forcing, dt_f=30*24*3600, ocn_mixing_ratio=0, restoring=False,ice_model=True,atm_adv=True,spatial_pattern=None,atm_DA_tendencies=None,ocn_DA_tendencies=None, return_coupled_fluxes=False,random_amp=0.1):
nt=int(C['tmax']/C['dt'])
nt1=int(C['tmax']/C['avep'])
tau=float(C['period'])/float(C['dt'])
rtas=np.random.rand(C['nx'])
sst=C['T0']*np.ones((2,C['nx']))
tas=C['T0']*np.ones((2,C['nx']))+rtas
hice=np.zeros((2,C['nx']))
sst_boundary=C['T0']*np.ones((2))
if np.all(forcing!=None):
forcing = np.interp(np.arange(0,len(forcing)*dt_f,C['dt']),np.arange(0,len(forcing)*dt_f,dt_f),forcing)
else:
forcing = np.zeros(nt+1)
sst_out = np.zeros((nt1,C['nx']))
tas_out = np.zeros((nt1,C['nx']))
hice_out = np.zeros((nt1,C['nx']))
sflx_f_out = np.zeros((nt1,C['nx']))
sflx_out = np.zeros((nt1,C['nx']))
if np.all(spatial_pattern==None):
spatial_pattern=np.ones(C['nx'])
if np.all(atm_DA_tendencies!=None):
use_atm_tendencies=True
else:
use_atm_tendencies=False
if np.all(ocn_DA_tendencies!=None):
use_ocn_tendencies=True
else:
use_ocn_tendencies=False
atm_DA_tendencies = np.zeros((nt,C['nx']))
ocn_DA_tendencies = np.zeros((nt,C['nx']))
tas_out, sst_out, hice_out, sflx_out, sflx_f_out, atm_DA_tendencies, ocn_DA_tendencies=CoupledChannel_time(nt,C['nx'],C['xx'],C['dt'],C['avep'],sst,tas,hice,sst_boundary,sst_out,tas_out,hice_out,sflx_f_out,sflx_out,forcing,spatial_pattern,C['ra'],C['Cp'],C['va'],C['vo'],C['Da'],C['Do'],C['Cs'],C['T0'],C['Tf'],C['emissivity'],C['SW0'],C['SW_anom'],C['H'],C['Hb'],C['Cpo'],C['ro'],C['tau_entrainment'],C['Li'],C['ri'],use_ocn_tendencies,use_atm_tendencies, atm_DA_tendencies, ocn_DA_tendencies,ice_model,atm_adv,return_coupled_fluxes)
if return_coupled_fluxes:
return tas_out, sst_out, hice_out, sflx_out, sflx_f_out, nt1, nt, atm_DA_tendencies, ocn_DA_tendencies
else:
return tas_out, sst_out, hice_out, sflx_out, sflx_f_out, nt1, nt
| true | true |
790bf5f84234ec065a5d0d52c9aaa59b1d07ab77 | 2,728 | py | Python | Module_02_Building_Your_Own_Custom_Object_Detector/2.10_Re-Training_and_Running_your_Classifier/hard_negative_mine.py | CactusJackFX/PyImageSearch_Guru | 01f5bce644b58848db029f72656002e21545bb10 | [
"Apache-2.0"
] | 2 | 2020-02-12T12:17:01.000Z | 2021-01-07T02:31:18.000Z | Module_02_Building_Your_Own_Custom_Object_Detector/2.10_Re-Training_and_Running_your_Classifier/hard_negative_mine.py | CactusJackFX/PyImageSearch_Guru | 01f5bce644b58848db029f72656002e21545bb10 | [
"Apache-2.0"
] | 1 | 2020-03-22T06:33:10.000Z | 2020-03-22T06:33:10.000Z | Module_02_Building_Your_Own_Custom_Object_Detector/2.9_Hard-Negative_Mining/hard_negative_mine.py | CactusJackFX/PyImageSearch_Guru | 01f5bce644b58848db029f72656002e21545bb10 | [
"Apache-2.0"
] | 3 | 2020-02-18T05:24:13.000Z | 2020-09-21T06:58:58.000Z | # USAGE
# python hard_negative_mine.py --conf conf/cars.json
# import the necessary packages
from __future__ import print_function
from pyimagesearch.object_detection import ObjectDetector
from pyimagesearch.descriptors import HOG
from pyimagesearch.utils import dataset
from pyimagesearch.utils import Conf
from imutils import paths
import numpy as np
import progressbar
import argparse
import pickle
import random
import cv2
# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-c", "--conf", required=True, help="path to the configuration file")
args = vars(ap.parse_args())
# load the configuration file and initialize the data list
conf = Conf(args["conf"])
data = []
# load the classifier, then initialize the Histogram of Oriented Gradients descriptor
# and the object detector
model = pickle.loads(open(conf["classifier_path"], "rb").read())
hog = HOG(orientations=conf["orientations"], pixelsPerCell=tuple(conf["pixels_per_cell"]),
cellsPerBlock=tuple(conf["cells_per_block"]), normalize=conf["normalize"], block_norm="L1")
od = ObjectDetector(model, hog)
# grab the set of distraction paths and randomly sample them
dstPaths = list(paths.list_images(conf["image_distractions"]))
dstPaths = random.sample(dstPaths, conf["hn_num_distraction_images"])
# setup the progress bar
widgets = ["Mining: ", progressbar.Percentage(), " ", progressbar.Bar(), " ", progressbar.ETA()]
pbar = progressbar.ProgressBar(maxval=len(dstPaths), widgets=widgets).start()
# loop over the distraction paths
for (i, imagePath) in enumerate(dstPaths):
# load the image and convert it to grayscale
image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# detect objects in the image
(boxes, probs) = od.detect(gray, conf["window_dim"], winStep=conf["hn_window_step"],
pyramidScale=conf["hn_pyramid_scale"], minProb=conf["hn_min_probability"])
# loop over the bounding boxes
for (prob, (startX, startY, endX, endY)) in zip(probs, boxes):
# extract the ROI from the image, resize it to a known, canonical size, extract
# HOG features from teh ROI, and finally update the data
roi = cv2.resize(gray[startY:endY, startX:endX], tuple(conf["window_dim"]),
interpolation=cv2.INTER_AREA)
features = hog.describe(roi)
data.append(np.hstack([[prob], features]))
# update the progress bar
pbar.update(i)
# sort the data points by confidence
pbar.finish()
print("[INFO] sorting by probability...")
data = np.array(data)
data = data[data[:, 0].argsort()[::-1]]
# dump the dataset to file
print("[INFO] dumping hard negatives to file...")
dataset.dump_dataset(data[:, 1:], [-1] * len(data), conf["features_path"], "hard_negatives",
writeMethod="a") | 37.369863 | 96 | 0.752933 |
from __future__ import print_function
from pyimagesearch.object_detection import ObjectDetector
from pyimagesearch.descriptors import HOG
from pyimagesearch.utils import dataset
from pyimagesearch.utils import Conf
from imutils import paths
import numpy as np
import progressbar
import argparse
import pickle
import random
import cv2
ap = argparse.ArgumentParser()
ap.add_argument("-c", "--conf", required=True, help="path to the configuration file")
args = vars(ap.parse_args())
conf = Conf(args["conf"])
data = []
model = pickle.loads(open(conf["classifier_path"], "rb").read())
hog = HOG(orientations=conf["orientations"], pixelsPerCell=tuple(conf["pixels_per_cell"]),
cellsPerBlock=tuple(conf["cells_per_block"]), normalize=conf["normalize"], block_norm="L1")
od = ObjectDetector(model, hog)
dstPaths = list(paths.list_images(conf["image_distractions"]))
dstPaths = random.sample(dstPaths, conf["hn_num_distraction_images"])
widgets = ["Mining: ", progressbar.Percentage(), " ", progressbar.Bar(), " ", progressbar.ETA()]
pbar = progressbar.ProgressBar(maxval=len(dstPaths), widgets=widgets).start()
for (i, imagePath) in enumerate(dstPaths):
image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
(boxes, probs) = od.detect(gray, conf["window_dim"], winStep=conf["hn_window_step"],
pyramidScale=conf["hn_pyramid_scale"], minProb=conf["hn_min_probability"])
for (prob, (startX, startY, endX, endY)) in zip(probs, boxes):
roi = cv2.resize(gray[startY:endY, startX:endX], tuple(conf["window_dim"]),
interpolation=cv2.INTER_AREA)
features = hog.describe(roi)
data.append(np.hstack([[prob], features]))
pbar.update(i)
pbar.finish()
print("[INFO] sorting by probability...")
data = np.array(data)
data = data[data[:, 0].argsort()[::-1]]
print("[INFO] dumping hard negatives to file...")
dataset.dump_dataset(data[:, 1:], [-1] * len(data), conf["features_path"], "hard_negatives",
writeMethod="a") | true | true |
790bf6088d55d4f16f4c829e953b087d0a1c8eb4 | 1,422 | py | Python | macaw/macaw.py | dcchambers/macaw | d16ea2d8021323d3be65d5449e06e61e7f527355 | [
"MIT"
] | null | null | null | macaw/macaw.py | dcchambers/macaw | d16ea2d8021323d3be65d5449e06e61e7f527355 | [
"MIT"
] | 1 | 2021-04-16T18:37:46.000Z | 2021-04-16T18:37:46.000Z | macaw/macaw.py | dcchambers/macaw | d16ea2d8021323d3be65d5449e06e61e7f527355 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
# Macaw
#
# Testing file open and string concatenation.
import random
import pkgutil
def main():
# This dictionary of words is for testing only and should *not* be considered secure.
# Courtesy of https://gist.github.com/deekayen/4148741
#f = open('dictionary.txt')
f = pkgutil.get_data("macaw","dictionary.txt").decode("utf8")
wordList = f.split()
password = generatePassword(wordList)
speakPassword(password)
def speakPassword(str):
print(r"""
,,,___
,' _ \__ ___________________________________________
/ { O / `\ / \
,\ } /---./ .-' """+str+"""
/\ `-.__- `--' `-. |
/ `._ : | \___________________________________________/
/\_; -' : ;
/ \_; / /
/| \ \_/..-'
________|_\___/_\\\_\\\________
----------------;;-;;--------
\/ `-'/
|\_|_/|
\/ \/
\_/
""")
def generatePassword(wordList):
tempPass = ''
for i in range(0, 5):
word = wordList[random.randint(0,999)] # grab a random word from the dictionary file.
tempPass = tempPass + word #concat that word to the end of the password.
return tempPass
| 30.913043 | 93 | 0.466245 |
import random
import pkgutil
def main():
f = pkgutil.get_data("macaw","dictionary.txt").decode("utf8")
wordList = f.split()
password = generatePassword(wordList)
speakPassword(password)
def speakPassword(str):
print(r"""
,,,___
,' _ \__ ___________________________________________
/ { O / `\ / \
,\ } /---./ .-' """+str+"""
/\ `-.__- `--' `-. |
/ `._ : | \___________________________________________/
/\_; -' : ;
/ \_; / /
/| \ \_/..-'
________|_\___/_\\\_\\\________
----------------;;-;;--------
\/ `-'/
|\_|_/|
\/ \/
\_/
""")
def generatePassword(wordList):
tempPass = ''
for i in range(0, 5):
word = wordList[random.randint(0,999)]
tempPass = tempPass + word
return tempPass
| true | true |
790bf61367d85b79bae4b153328b229b10721b38 | 1,495 | py | Python | tensorflow/contrib/losses/__init__.py | xincao79/tensorflow | 7fa0cf39f854d5fdaaa19ad6425dfed02f5fea64 | [
"Apache-2.0"
] | 384 | 2017-02-21T18:38:04.000Z | 2022-02-22T07:30:25.000Z | tensorflow/contrib/losses/__init__.py | xincao79/tensorflow | 7fa0cf39f854d5fdaaa19ad6425dfed02f5fea64 | [
"Apache-2.0"
] | 15 | 2017-03-01T20:18:43.000Z | 2020-05-07T10:33:51.000Z | tensorflow/contrib/losses/__init__.py | xincao79/tensorflow | 7fa0cf39f854d5fdaaa19ad6425dfed02f5fea64 | [
"Apache-2.0"
] | 81 | 2017-02-21T19:31:19.000Z | 2022-02-22T07:30:24.000Z | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Ops for building neural network losses.
See @{$python/contrib.losses}.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# pylint: disable=wildcard-import
from tensorflow.contrib.losses.python.losses import *
# pylint: enable=wildcard-import
from tensorflow.python.util.all_util import remove_undocumented
_allowed_symbols = [
'absolute_difference',
'add_loss',
'hinge_loss',
'compute_weighted_loss',
'cosine_distance',
'get_losses',
'get_regularization_losses',
'get_total_loss',
'log_loss',
'mean_pairwise_squared_error',
'mean_squared_error',
'sigmoid_cross_entropy',
'softmax_cross_entropy',
'sparse_softmax_cross_entropy',
]
remove_undocumented(__name__, _allowed_symbols)
| 31.145833 | 80 | 0.720401 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.losses.python.losses import *
from tensorflow.python.util.all_util import remove_undocumented
_allowed_symbols = [
'absolute_difference',
'add_loss',
'hinge_loss',
'compute_weighted_loss',
'cosine_distance',
'get_losses',
'get_regularization_losses',
'get_total_loss',
'log_loss',
'mean_pairwise_squared_error',
'mean_squared_error',
'sigmoid_cross_entropy',
'softmax_cross_entropy',
'sparse_softmax_cross_entropy',
]
remove_undocumented(__name__, _allowed_symbols)
| true | true |
790bf63ebd6b665702445bddb88c8a1278a17112 | 172 | py | Python | bookr/reviews/utils.py | rodrigobmedeiros/Bookr | bc8313226b020755c16f5ea2574f8716bd3774fd | [
"MIT"
] | null | null | null | bookr/reviews/utils.py | rodrigobmedeiros/Bookr | bc8313226b020755c16f5ea2574f8716bd3774fd | [
"MIT"
] | null | null | null | bookr/reviews/utils.py | rodrigobmedeiros/Bookr | bc8313226b020755c16f5ea2574f8716bd3774fd | [
"MIT"
] | null | null | null | def average_rating(rating_list):
if not rating_list:
# if rating_list is empty return 0
return 0
return round(sum(rating_list) / len(rating_list)) | 24.571429 | 53 | 0.680233 | def average_rating(rating_list):
if not rating_list:
return 0
return round(sum(rating_list) / len(rating_list)) | true | true |
790bf65c4b6713bbef82dca5b557e23041d8c9ce | 3,408 | py | Python | python/benchmark/function/test_cumprod.py | isabella232/nnabla | 82a3c6fed382f889d1a4a429c696bb8cedf6ce79 | [
"Apache-2.0"
] | 1 | 2019-05-31T14:00:58.000Z | 2019-05-31T14:00:58.000Z | python/benchmark/function/test_cumprod.py | Pandinosaurus/nnabla | 62a21db4afc15c52ce43f3f5b87e5fa4181b2deb | [
"Apache-2.0"
] | null | null | null | python/benchmark/function/test_cumprod.py | Pandinosaurus/nnabla | 62a21db4afc15c52ce43f3f5b87e5fa4181b2deb | [
"Apache-2.0"
] | null | null | null | # Copyright 2021 Sony Group Corporation.
#
# 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 pytest
import numpy as np
import nnabla.functions as F
from function_benchmark import FunctionBenchmark, Inspec
class Case:
def __init__(self, shape, axis, rtol=1e-6):
# rtol (relative tolerance) 1e-6 is default for assert_allclose
self.shape = shape
self.axis = axis
self.rtol = rtol
# Print this message by pytest when a test fails.
def __repr__(self):
return 'Case(shape=' + str(self.shape) + \
' axes=' + str(self.axis) + \
', rtol=' + str(self.rtol) + ')'
test_cases = [
# --------------------------------
# Common use case
# --------------------------------
# Axis 0
Case((512, 512), 0),
Case((512, 1024), 0),
Case((512, 2048), 0),
Case((1024, 512), 0),
Case((1024, 1024), 0),
Case((1024, 2048), 0),
Case((2048, 512), 0),
Case((2048, 1024), 0),
Case((2048, 2048), 0),
# Axis 1
Case((512, 512), 1),
Case((512, 1024), 1),
Case((512, 2048), 1),
Case((1024, 512), 1),
Case((1024, 1024), 1),
Case((1024, 2048), 1),
Case((2048, 512), 1),
Case((2048, 1024), 1),
Case((2048, 2048), 1),
# --------------------------------
# Large cases
# --------------------------------
Case((1024*1024, 32), 1),
Case((32, 1024*1024), 0),
Case((2048, 2048), 1),
Case((2048, 2048), 0),
Case((2024*2024, 2), 0),
Case((2, 2024*2024), 1),
# Weak cases
# PyTorch uses Cub library in these cases.
Case((2024*2024, 1), 0),
Case((1, 2024*2024), 1),
]
def create_cumprod_input(rng, shape, axis, with_mask):
x = (rng.randn(*shape)).astype(np.float32)
if with_mask:
# Make zero elements with the probability of `1 / x_shape[axis]`.
# It is the probability of existence of one zero element in each scan axis.
mask = rng.rand(*shape) > (1.0 / shape[axis])
x = x * mask
return x
@pytest.mark.parametrize("seed", [123])
@pytest.mark.parametrize("test_case", test_cases)
@pytest.mark.parametrize('exclusive', [False, True])
@pytest.mark.parametrize('reverse', [False, True])
@pytest.mark.parametrize("with_mask", [True, False])
def test_cumprod(seed, test_case, exclusive, reverse, with_mask, nnabla_opts):
x_shape = test_case.shape
axis = test_case.axis
def init(shape):
rng = np.random.RandomState(seed)
return create_cumprod_input(rng, shape, axis, with_mask)
need_grad = True
inputs = [Inspec(x_shape, init, need_grad)]
func_kwargs = dict(
axis=axis,
exclusive=exclusive,
reverse=reverse,
)
fb = FunctionBenchmark(
F.cumprod, inputs, [], func_kwargs,
nnabla_opts.ext, nnabla_opts.ext_kwargs)
fb.benchmark()
fb.write(writer=nnabla_opts.function_benchmark_writer)
| 29.634783 | 83 | 0.601232 |
import pytest
import numpy as np
import nnabla.functions as F
from function_benchmark import FunctionBenchmark, Inspec
class Case:
def __init__(self, shape, axis, rtol=1e-6):
self.shape = shape
self.axis = axis
self.rtol = rtol
def __repr__(self):
return 'Case(shape=' + str(self.shape) + \
' axes=' + str(self.axis) + \
', rtol=' + str(self.rtol) + ')'
test_cases = [
Case((512, 512), 0),
Case((512, 1024), 0),
Case((512, 2048), 0),
Case((1024, 512), 0),
Case((1024, 1024), 0),
Case((1024, 2048), 0),
Case((2048, 512), 0),
Case((2048, 1024), 0),
Case((2048, 2048), 0),
Case((512, 512), 1),
Case((512, 1024), 1),
Case((512, 2048), 1),
Case((1024, 512), 1),
Case((1024, 1024), 1),
Case((1024, 2048), 1),
Case((2048, 512), 1),
Case((2048, 1024), 1),
Case((2048, 2048), 1),
Case((1024*1024, 32), 1),
Case((32, 1024*1024), 0),
Case((2048, 2048), 1),
Case((2048, 2048), 0),
Case((2024*2024, 2), 0),
Case((2, 2024*2024), 1),
Case((2024*2024, 1), 0),
Case((1, 2024*2024), 1),
]
def create_cumprod_input(rng, shape, axis, with_mask):
x = (rng.randn(*shape)).astype(np.float32)
if with_mask:
mask = rng.rand(*shape) > (1.0 / shape[axis])
x = x * mask
return x
@pytest.mark.parametrize("seed", [123])
@pytest.mark.parametrize("test_case", test_cases)
@pytest.mark.parametrize('exclusive', [False, True])
@pytest.mark.parametrize('reverse', [False, True])
@pytest.mark.parametrize("with_mask", [True, False])
def test_cumprod(seed, test_case, exclusive, reverse, with_mask, nnabla_opts):
x_shape = test_case.shape
axis = test_case.axis
def init(shape):
rng = np.random.RandomState(seed)
return create_cumprod_input(rng, shape, axis, with_mask)
need_grad = True
inputs = [Inspec(x_shape, init, need_grad)]
func_kwargs = dict(
axis=axis,
exclusive=exclusive,
reverse=reverse,
)
fb = FunctionBenchmark(
F.cumprod, inputs, [], func_kwargs,
nnabla_opts.ext, nnabla_opts.ext_kwargs)
fb.benchmark()
fb.write(writer=nnabla_opts.function_benchmark_writer)
| true | true |
790bf68e6bb4b60e25c139472fb6878dd263f693 | 5,938 | py | Python | test_autofit/mapper/test_take_attributes.py | rhayes777/PyAutoF | 87f56419348833b285b00da1a524e329588e0b01 | [
"MIT"
] | null | null | null | test_autofit/mapper/test_take_attributes.py | rhayes777/PyAutoF | 87f56419348833b285b00da1a524e329588e0b01 | [
"MIT"
] | null | null | null | test_autofit/mapper/test_take_attributes.py | rhayes777/PyAutoF | 87f56419348833b285b00da1a524e329588e0b01 | [
"MIT"
] | null | null | null | import pytest
import autofit as af
from autofit.mock import mock as m
@pytest.fixture(
name="target_gaussian"
)
def make_target_gaussian():
return af.PriorModel(
m.Gaussian
)
@pytest.fixture(
name="prior"
)
def make_prior():
return af.UniformPrior()
@pytest.fixture(
name="source_gaussian"
)
def make_source_gaussian(prior):
return af.PriorModel(
m.Gaussian,
centre=prior
)
def test_simple(
source_gaussian,
target_gaussian,
prior
):
target_gaussian.take_attributes(
source_gaussian
)
assert target_gaussian.centre == prior
def test_assertions(
source_gaussian,
target_gaussian
):
target_gaussian.add_assertion(
target_gaussian.centre <= target_gaussian.intensity
)
with pytest.raises(AssertionError):
target_gaussian.take_attributes(
source_gaussian
)
def test_assertions_collection(
source_gaussian,
target_gaussian
):
target_gaussian.add_assertion(
target_gaussian.centre <= target_gaussian.intensity
)
target_collection = af.Collection(
gaussian=target_gaussian
)
source_collection = af.Collection(
gaussian=source_gaussian
)
with pytest.raises(AssertionError):
target_collection.take_attributes(
source_collection
)
def test_in_collection(
source_gaussian,
target_gaussian,
prior
):
target = af.CollectionPriorModel(
gaussian=target_gaussian
)
source = af.CollectionPriorModel(
gaussian=source_gaussian
)
target.take_attributes(
source
)
assert target.gaussian.centre == prior
def test_tuple(
source_gaussian,
target_gaussian,
prior
):
source_gaussian.centre = (prior, 1.0)
target_gaussian.take_attributes(
source_gaussian
)
assert target_gaussian.centre == (prior, 1.0)
def test_tuple_prior(
source_gaussian,
target_gaussian,
prior
):
source_gaussian.centre = (prior, 1.0)
target_gaussian.centre = af.TuplePrior()
target_gaussian.take_attributes(
source_gaussian
)
assert target_gaussian.centre == (prior, 1.0)
def test_tuple_in_instance(
target_gaussian,
prior
):
# noinspection PyTypeChecker
source_gaussian = m.Gaussian(
centre=(prior, 1.0)
)
target_gaussian.take_attributes(
source_gaussian
)
assert target_gaussian.centre == (prior, 1.0)
def test_tuple_in_collection(
source_gaussian,
target_gaussian,
prior
):
source_gaussian.centre = (prior, 1.0)
source = af.CollectionPriorModel(
gaussian=source_gaussian
)
target = af.CollectionPriorModel(
gaussian=target_gaussian
)
target.take_attributes(source)
assert target.gaussian.centre == (prior, 1.0)
def test_tuple_in_instance_in_collection(
target_gaussian,
prior
):
# noinspection PyTypeChecker
source_gaussian = m.Gaussian(
centre=(prior, 1.0)
)
source = af.CollectionPriorModel(
gaussian=source_gaussian
)
target = af.CollectionPriorModel(
gaussian=target_gaussian
)
target.take_attributes(source)
assert target.gaussian.centre == (prior, 1.0)
def test_source_is_dict(
source_gaussian,
target_gaussian,
prior
):
source = dict(
gaussian=source_gaussian
)
target = af.CollectionPriorModel(
gaussian=target_gaussian
)
target.take_attributes(source)
assert target.gaussian.centre == prior
def test_target_is_dict(
source_gaussian,
target_gaussian,
prior
):
source = af.CollectionPriorModel(
collection=af.CollectionPriorModel(
gaussian=source_gaussian
)
)
target = af.CollectionPriorModel(
collection=dict(
gaussian=target_gaussian
)
)
target.take_attributes(source)
assert target.collection.gaussian.centre == prior
def test_missing_from_source(
target_gaussian,
prior
):
target_gaussian.centre = prior
target_gaussian.take_attributes(
af.CollectionPriorModel()
)
assert target_gaussian.centre == prior
def test_unlabelled_in_collection(
source_gaussian,
target_gaussian,
prior
):
target = af.CollectionPriorModel(
[target_gaussian]
)
source = af.CollectionPriorModel(
[source_gaussian]
)
target.take_attributes(
source
)
assert target[0].centre == prior
def test_passing_float(
source_gaussian,
target_gaussian
):
source_gaussian.centre = 2.0
target_gaussian.take_attributes(
source_gaussian
)
assert target_gaussian.centre == 2.0
def test_missing_from_origin(
target_gaussian
):
target_gaussian.take_attributes(
af.CollectionPriorModel()
)
def test_limits(
source_gaussian,
target_gaussian
):
source_gaussian.centre = af.GaussianPrior(
mean=0,
sigma=1,
lower_limit=-1,
upper_limit=1
)
target_gaussian.take_attributes(
source_gaussian
)
assert target_gaussian.centre.lower_limit == -1
assert target_gaussian.centre.upper_limit == 1
def test_tuples():
centre = (0.0, 1.0)
source = af.Model(
m.Gaussian,
centre=centre
)
target = af.Model(
m.Gaussian
)
target.take_attributes(source)
assert target.centre == centre
| 20.335616 | 60 | 0.616201 | import pytest
import autofit as af
from autofit.mock import mock as m
@pytest.fixture(
name="target_gaussian"
)
def make_target_gaussian():
return af.PriorModel(
m.Gaussian
)
@pytest.fixture(
name="prior"
)
def make_prior():
return af.UniformPrior()
@pytest.fixture(
name="source_gaussian"
)
def make_source_gaussian(prior):
return af.PriorModel(
m.Gaussian,
centre=prior
)
def test_simple(
source_gaussian,
target_gaussian,
prior
):
target_gaussian.take_attributes(
source_gaussian
)
assert target_gaussian.centre == prior
def test_assertions(
source_gaussian,
target_gaussian
):
target_gaussian.add_assertion(
target_gaussian.centre <= target_gaussian.intensity
)
with pytest.raises(AssertionError):
target_gaussian.take_attributes(
source_gaussian
)
def test_assertions_collection(
source_gaussian,
target_gaussian
):
target_gaussian.add_assertion(
target_gaussian.centre <= target_gaussian.intensity
)
target_collection = af.Collection(
gaussian=target_gaussian
)
source_collection = af.Collection(
gaussian=source_gaussian
)
with pytest.raises(AssertionError):
target_collection.take_attributes(
source_collection
)
def test_in_collection(
source_gaussian,
target_gaussian,
prior
):
target = af.CollectionPriorModel(
gaussian=target_gaussian
)
source = af.CollectionPriorModel(
gaussian=source_gaussian
)
target.take_attributes(
source
)
assert target.gaussian.centre == prior
def test_tuple(
source_gaussian,
target_gaussian,
prior
):
source_gaussian.centre = (prior, 1.0)
target_gaussian.take_attributes(
source_gaussian
)
assert target_gaussian.centre == (prior, 1.0)
def test_tuple_prior(
source_gaussian,
target_gaussian,
prior
):
source_gaussian.centre = (prior, 1.0)
target_gaussian.centre = af.TuplePrior()
target_gaussian.take_attributes(
source_gaussian
)
assert target_gaussian.centre == (prior, 1.0)
def test_tuple_in_instance(
target_gaussian,
prior
):
source_gaussian = m.Gaussian(
centre=(prior, 1.0)
)
target_gaussian.take_attributes(
source_gaussian
)
assert target_gaussian.centre == (prior, 1.0)
def test_tuple_in_collection(
source_gaussian,
target_gaussian,
prior
):
source_gaussian.centre = (prior, 1.0)
source = af.CollectionPriorModel(
gaussian=source_gaussian
)
target = af.CollectionPriorModel(
gaussian=target_gaussian
)
target.take_attributes(source)
assert target.gaussian.centre == (prior, 1.0)
def test_tuple_in_instance_in_collection(
target_gaussian,
prior
):
source_gaussian = m.Gaussian(
centre=(prior, 1.0)
)
source = af.CollectionPriorModel(
gaussian=source_gaussian
)
target = af.CollectionPriorModel(
gaussian=target_gaussian
)
target.take_attributes(source)
assert target.gaussian.centre == (prior, 1.0)
def test_source_is_dict(
source_gaussian,
target_gaussian,
prior
):
source = dict(
gaussian=source_gaussian
)
target = af.CollectionPriorModel(
gaussian=target_gaussian
)
target.take_attributes(source)
assert target.gaussian.centre == prior
def test_target_is_dict(
source_gaussian,
target_gaussian,
prior
):
source = af.CollectionPriorModel(
collection=af.CollectionPriorModel(
gaussian=source_gaussian
)
)
target = af.CollectionPriorModel(
collection=dict(
gaussian=target_gaussian
)
)
target.take_attributes(source)
assert target.collection.gaussian.centre == prior
def test_missing_from_source(
target_gaussian,
prior
):
target_gaussian.centre = prior
target_gaussian.take_attributes(
af.CollectionPriorModel()
)
assert target_gaussian.centre == prior
def test_unlabelled_in_collection(
source_gaussian,
target_gaussian,
prior
):
target = af.CollectionPriorModel(
[target_gaussian]
)
source = af.CollectionPriorModel(
[source_gaussian]
)
target.take_attributes(
source
)
assert target[0].centre == prior
def test_passing_float(
source_gaussian,
target_gaussian
):
source_gaussian.centre = 2.0
target_gaussian.take_attributes(
source_gaussian
)
assert target_gaussian.centre == 2.0
def test_missing_from_origin(
target_gaussian
):
target_gaussian.take_attributes(
af.CollectionPriorModel()
)
def test_limits(
source_gaussian,
target_gaussian
):
source_gaussian.centre = af.GaussianPrior(
mean=0,
sigma=1,
lower_limit=-1,
upper_limit=1
)
target_gaussian.take_attributes(
source_gaussian
)
assert target_gaussian.centre.lower_limit == -1
assert target_gaussian.centre.upper_limit == 1
def test_tuples():
centre = (0.0, 1.0)
source = af.Model(
m.Gaussian,
centre=centre
)
target = af.Model(
m.Gaussian
)
target.take_attributes(source)
assert target.centre == centre
| true | true |
790bf6bb1e0f9e05694d9b6a3d0724b15d046a61 | 890 | py | Python | sfm2latex/dictionary/Image.py | redmer/sfm2latex | 6d57eadf7af10058ade3999efec6c590295027b2 | [
"MIT"
] | null | null | null | sfm2latex/dictionary/Image.py | redmer/sfm2latex | 6d57eadf7af10058ade3999efec6c590295027b2 | [
"MIT"
] | null | null | null | sfm2latex/dictionary/Image.py | redmer/sfm2latex | 6d57eadf7af10058ade3999efec6c590295027b2 | [
"MIT"
] | null | null | null | from ..utils import sortkey, capitalize_first
FIGURE_TEX_TEMPLATE = r'\hwgraphic{{{path}}}{{{headword}}}{{{attribution}}}'
# change to {filename} if you want to specify full paths.
FIGURE_PATH_TEMPLATE = r'figures/ill-{filename}'
class Image(object):
type = 'img'
def sk(self):
return sortkey(self.hw)
def __init__(self, hw='', img_src='', img_attrib=''):
super().__init__()
self.hw = hw
self.img_src = img_src
self.img_attrib = img_attrib
def __repr__(self):
return "(Image of '{headword}')".format(
headword=self.hw
)
def render(self, settings={}):
figure_path = FIGURE_PATH_TEMPLATE.format(filename=self.img_src)
return FIGURE_TEX_TEMPLATE.format(
headword=capitalize_first(self.hw),
path=figure_path,
attribution=self.img_attrib
)
| 27.8125 | 76 | 0.622472 | from ..utils import sortkey, capitalize_first
FIGURE_TEX_TEMPLATE = r'\hwgraphic{{{path}}}{{{headword}}}{{{attribution}}}'
FIGURE_PATH_TEMPLATE = r'figures/ill-{filename}'
class Image(object):
type = 'img'
def sk(self):
return sortkey(self.hw)
def __init__(self, hw='', img_src='', img_attrib=''):
super().__init__()
self.hw = hw
self.img_src = img_src
self.img_attrib = img_attrib
def __repr__(self):
return "(Image of '{headword}')".format(
headword=self.hw
)
def render(self, settings={}):
figure_path = FIGURE_PATH_TEMPLATE.format(filename=self.img_src)
return FIGURE_TEX_TEMPLATE.format(
headword=capitalize_first(self.hw),
path=figure_path,
attribution=self.img_attrib
)
| true | true |
790bf764810a2b414f0c97895b25464e4c42d581 | 12,706 | py | Python | sympy/vector/tests/test_coordsysrect.py | ovolve/sympy | 0a15782f20505673466b940454b33b8014a25c13 | [
"BSD-3-Clause"
] | 4 | 2018-07-04T17:20:12.000Z | 2019-07-14T18:07:25.000Z | sympy/vector/tests/test_coordsysrect.py | ovolve/sympy | 0a15782f20505673466b940454b33b8014a25c13 | [
"BSD-3-Clause"
] | 7 | 2017-05-01T14:15:32.000Z | 2017-09-06T20:44:24.000Z | sympy/vector/tests/test_coordsysrect.py | ovolve/sympy | 0a15782f20505673466b940454b33b8014a25c13 | [
"BSD-3-Clause"
] | 1 | 2020-10-02T04:21:11.000Z | 2020-10-02T04:21:11.000Z | from sympy.vector.coordsysrect import CoordSysCartesian
from sympy.vector.scalar import BaseScalar
from sympy import sin, cos, pi, ImmutableMatrix as Matrix, \
symbols, simplify, zeros, expand
from sympy.vector.functions import express
from sympy.vector.point import Point
from sympy.vector.vector import Vector
from sympy.vector.orienters import (AxisOrienter, BodyOrienter,
SpaceOrienter, QuaternionOrienter)
a, b, c, q = symbols('a b c q')
q1, q2, q3, q4 = symbols('q1 q2 q3 q4')
def test_func_args():
A = CoordSysCartesian('A')
assert A.x.func(*A.x.args) == A.x
expr = 3*A.x + 4*A.y
assert expr.func(*expr.args) == expr
assert A.i.func(*A.i.args) == A.i
v = A.x*A.i + A.y*A.j + A.z*A.k
assert v.func(*v.args) == v
assert A.origin.func(*A.origin.args) == A.origin
def test_coordsyscartesian_equivalence():
A = CoordSysCartesian('A')
A1 = CoordSysCartesian('A')
assert A1 == A
B = CoordSysCartesian('B')
assert A != B
def test_orienters():
A = CoordSysCartesian('A')
axis_orienter = AxisOrienter(a, A.k)
body_orienter = BodyOrienter(a, b, c, '123')
space_orienter = SpaceOrienter(a, b, c, '123')
q_orienter = QuaternionOrienter(q1, q2, q3, q4)
assert axis_orienter.rotation_matrix(A) == Matrix([
[ cos(a), sin(a), 0],
[-sin(a), cos(a), 0],
[ 0, 0, 1]])
assert body_orienter.rotation_matrix() == Matrix([
[ cos(b)*cos(c), sin(a)*sin(b)*cos(c) + sin(c)*cos(a),
sin(a)*sin(c) - sin(b)*cos(a)*cos(c)],
[-sin(c)*cos(b), -sin(a)*sin(b)*sin(c) + cos(a)*cos(c),
sin(a)*cos(c) + sin(b)*sin(c)*cos(a)],
[ sin(b), -sin(a)*cos(b),
cos(a)*cos(b)]])
assert space_orienter.rotation_matrix() == Matrix([
[cos(b)*cos(c), sin(c)*cos(b), -sin(b)],
[sin(a)*sin(b)*cos(c) - sin(c)*cos(a),
sin(a)*sin(b)*sin(c) + cos(a)*cos(c), sin(a)*cos(b)],
[sin(a)*sin(c) + sin(b)*cos(a)*cos(c), -sin(a)*cos(c) +
sin(b)*sin(c)*cos(a), cos(a)*cos(b)]])
assert q_orienter.rotation_matrix() == Matrix([
[q1**2 + q2**2 - q3**2 - q4**2, 2*q1*q4 + 2*q2*q3,
-2*q1*q3 + 2*q2*q4],
[-2*q1*q4 + 2*q2*q3, q1**2 - q2**2 + q3**2 - q4**2,
2*q1*q2 + 2*q3*q4],
[2*q1*q3 + 2*q2*q4,
-2*q1*q2 + 2*q3*q4, q1**2 - q2**2 - q3**2 + q4**2]])
def test_coordinate_vars():
"""
Tests the coordinate variables functionality with respect to
reorientation of coordinate systems.
"""
A = CoordSysCartesian('A')
# Note that the name given on the lhs is different from A.x._name
assert BaseScalar('A.x', 0, A, 'A_x', r'\mathbf{{x}_{A}}') == A.x
assert BaseScalar('A.y', 1, A, 'A_y', r'\mathbf{{y}_{A}}') == A.y
assert BaseScalar('A.z', 2, A, 'A_z', r'\mathbf{{z}_{A}}') == A.z
assert BaseScalar('A.x', 0, A, 'A_x', r'\mathbf{{x}_{A}}').__hash__() == A.x.__hash__()
assert isinstance(A.x, BaseScalar) and \
isinstance(A.y, BaseScalar) and \
isinstance(A.z, BaseScalar)
assert A.x*A.y == A.y*A.x
assert A.scalar_map(A) == {A.x: A.x, A.y: A.y, A.z: A.z}
assert A.x.system == A
assert A.x.diff(A.x) == 1
B = A.orient_new_axis('B', q, A.k)
assert B.scalar_map(A) == {B.z: A.z, B.y: -A.x*sin(q) + A.y*cos(q),
B.x: A.x*cos(q) + A.y*sin(q)}
assert A.scalar_map(B) == {A.x: B.x*cos(q) - B.y*sin(q),
A.y: B.x*sin(q) + B.y*cos(q), A.z: B.z}
assert express(B.x, A, variables=True) == A.x*cos(q) + A.y*sin(q)
assert express(B.y, A, variables=True) == -A.x*sin(q) + A.y*cos(q)
assert express(B.z, A, variables=True) == A.z
assert expand(express(B.x*B.y*B.z, A, variables=True)) == \
expand(A.z*(-A.x*sin(q) + A.y*cos(q))*(A.x*cos(q) + A.y*sin(q)))
assert express(B.x*B.i + B.y*B.j + B.z*B.k, A) == \
(B.x*cos(q) - B.y*sin(q))*A.i + (B.x*sin(q) + \
B.y*cos(q))*A.j + B.z*A.k
assert simplify(express(B.x*B.i + B.y*B.j + B.z*B.k, A, \
variables=True)) == \
A.x*A.i + A.y*A.j + A.z*A.k
assert express(A.x*A.i + A.y*A.j + A.z*A.k, B) == \
(A.x*cos(q) + A.y*sin(q))*B.i + \
(-A.x*sin(q) + A.y*cos(q))*B.j + A.z*B.k
assert simplify(express(A.x*A.i + A.y*A.j + A.z*A.k, B, \
variables=True)) == \
B.x*B.i + B.y*B.j + B.z*B.k
N = B.orient_new_axis('N', -q, B.k)
assert N.scalar_map(A) == \
{N.x: A.x, N.z: A.z, N.y: A.y}
C = A.orient_new_axis('C', q, A.i + A.j + A.k)
mapping = A.scalar_map(C)
assert mapping[A.x] == (C.x*(2*cos(q) + 1)/3 +
C.y*(-2*sin(q + pi/6) + 1)/3 +
C.z*(-2*cos(q + pi/3) + 1)/3)
assert mapping[A.y] == (C.x*(-2*cos(q + pi/3) + 1)/3 +
C.y*(2*cos(q) + 1)/3 +
C.z*(-2*sin(q + pi/6) + 1)/3)
assert mapping[A.z] == (C.x*(-2*sin(q + pi/6) + 1)/3 +
C.y*(-2*cos(q + pi/3) + 1)/3 +
C.z*(2*cos(q) + 1)/3)
D = A.locate_new('D', a*A.i + b*A.j + c*A.k)
assert D.scalar_map(A) == {D.z: A.z - c, D.x: A.x - a, D.y: A.y - b}
E = A.orient_new_axis('E', a, A.k, a*A.i + b*A.j + c*A.k)
assert A.scalar_map(E) == {A.z: E.z + c,
A.x: E.x*cos(a) - E.y*sin(a) + a,
A.y: E.x*sin(a) + E.y*cos(a) + b}
assert E.scalar_map(A) == {E.x: (A.x - a)*cos(a) + (A.y - b)*sin(a),
E.y: (-A.x + a)*sin(a) + (A.y - b)*cos(a),
E.z: A.z - c}
F = A.locate_new('F', Vector.zero)
assert A.scalar_map(F) == {A.z: F.z, A.x: F.x, A.y: F.y}
def test_rotation_matrix():
N = CoordSysCartesian('N')
A = N.orient_new_axis('A', q1, N.k)
B = A.orient_new_axis('B', q2, A.i)
C = B.orient_new_axis('C', q3, B.j)
D = N.orient_new_axis('D', q4, N.j)
E = N.orient_new_space('E', q1, q2, q3, '123')
F = N.orient_new_quaternion('F', q1, q2, q3, q4)
G = N.orient_new_body('G', q1, q2, q3, '123')
assert N.rotation_matrix(C) == Matrix([
[- sin(q1) * sin(q2) * sin(q3) + cos(q1) * cos(q3), - sin(q1) *
cos(q2), sin(q1) * sin(q2) * cos(q3) + sin(q3) * cos(q1)], \
[sin(q1) * cos(q3) + sin(q2) * sin(q3) * cos(q1), \
cos(q1) * cos(q2), sin(q1) * sin(q3) - sin(q2) * cos(q1) * \
cos(q3)], [- sin(q3) * cos(q2), sin(q2), cos(q2) * cos(q3)]])
test_mat = D.rotation_matrix(C) - Matrix(
[[cos(q1) * cos(q3) * cos(q4) - sin(q3) * (- sin(q4) * cos(q2) +
sin(q1) * sin(q2) * cos(q4)), - sin(q2) * sin(q4) - sin(q1) *
cos(q2) * cos(q4), sin(q3) * cos(q1) * cos(q4) + cos(q3) * \
(- sin(q4) * cos(q2) + sin(q1) * sin(q2) * cos(q4))], \
[sin(q1) * cos(q3) + sin(q2) * sin(q3) * cos(q1), cos(q1) * \
cos(q2), sin(q1) * sin(q3) - sin(q2) * cos(q1) * cos(q3)], \
[sin(q4) * cos(q1) * cos(q3) - sin(q3) * (cos(q2) * cos(q4) + \
sin(q1) * sin(q2) * \
sin(q4)), sin(q2) *
cos(q4) - sin(q1) * sin(q4) * cos(q2), sin(q3) * \
sin(q4) * cos(q1) + cos(q3) * (cos(q2) * cos(q4) + \
sin(q1) * sin(q2) * sin(q4))]])
assert test_mat.expand() == zeros(3, 3)
assert E.rotation_matrix(N) == Matrix(
[[cos(q2)*cos(q3), sin(q3)*cos(q2), -sin(q2)],
[sin(q1)*sin(q2)*cos(q3) - sin(q3)*cos(q1), \
sin(q1)*sin(q2)*sin(q3) + cos(q1)*cos(q3), sin(q1)*cos(q2)], \
[sin(q1)*sin(q3) + sin(q2)*cos(q1)*cos(q3), - \
sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1), cos(q1)*cos(q2)]])
assert F.rotation_matrix(N) == Matrix([[
q1**2 + q2**2 - q3**2 - q4**2,
2*q1*q4 + 2*q2*q3, -2*q1*q3 + 2*q2*q4],[ -2*q1*q4 + 2*q2*q3,
q1**2 - q2**2 + q3**2 - q4**2, 2*q1*q2 + 2*q3*q4],
[2*q1*q3 + 2*q2*q4,
-2*q1*q2 + 2*q3*q4,
q1**2 - q2**2 - q3**2 + q4**2]])
assert G.rotation_matrix(N) == Matrix([[
cos(q2)*cos(q3), sin(q1)*sin(q2)*cos(q3) + sin(q3)*cos(q1),
sin(q1)*sin(q3) - sin(q2)*cos(q1)*cos(q3)], [
-sin(q3)*cos(q2), -sin(q1)*sin(q2)*sin(q3) + cos(q1)*cos(q3),
sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1)],[
sin(q2), -sin(q1)*cos(q2), cos(q1)*cos(q2)]])
def test_vector():
"""
Tests the effects of orientation of coordinate systems on
basic vector operations.
"""
N = CoordSysCartesian('N')
A = N.orient_new_axis('A', q1, N.k)
B = A.orient_new_axis('B', q2, A.i)
C = B.orient_new_axis('C', q3, B.j)
#Test to_matrix
v1 = a*N.i + b*N.j + c*N.k
assert v1.to_matrix(A) == Matrix([[ a*cos(q1) + b*sin(q1)],
[-a*sin(q1) + b*cos(q1)],
[ c]])
#Test dot
assert N.i.dot(A.i) == cos(q1)
assert N.i.dot(A.j) == -sin(q1)
assert N.i.dot(A.k) == 0
assert N.j.dot(A.i) == sin(q1)
assert N.j.dot(A.j) == cos(q1)
assert N.j.dot(A.k) == 0
assert N.k.dot(A.i) == 0
assert N.k.dot(A.j) == 0
assert N.k.dot(A.k) == 1
assert N.i.dot(A.i + A.j) == -sin(q1) + cos(q1) == \
(A.i + A.j).dot(N.i)
assert A.i.dot(C.i) == cos(q3)
assert A.i.dot(C.j) == 0
assert A.i.dot(C.k) == sin(q3)
assert A.j.dot(C.i) == sin(q2)*sin(q3)
assert A.j.dot(C.j) == cos(q2)
assert A.j.dot(C.k) == -sin(q2)*cos(q3)
assert A.k.dot(C.i) == -cos(q2)*sin(q3)
assert A.k.dot(C.j) == sin(q2)
assert A.k.dot(C.k) == cos(q2)*cos(q3)
#Test cross
assert N.i.cross(A.i) == sin(q1)*A.k
assert N.i.cross(A.j) == cos(q1)*A.k
assert N.i.cross(A.k) == -sin(q1)*A.i - cos(q1)*A.j
assert N.j.cross(A.i) == -cos(q1)*A.k
assert N.j.cross(A.j) == sin(q1)*A.k
assert N.j.cross(A.k) == cos(q1)*A.i - sin(q1)*A.j
assert N.k.cross(A.i) == A.j
assert N.k.cross(A.j) == -A.i
assert N.k.cross(A.k) == Vector.zero
assert N.i.cross(A.i) == sin(q1)*A.k
assert N.i.cross(A.j) == cos(q1)*A.k
assert N.i.cross(A.i + A.j) == sin(q1)*A.k + cos(q1)*A.k
assert (A.i + A.j).cross(N.i) == (-sin(q1) - cos(q1))*N.k
assert A.i.cross(C.i) == sin(q3)*C.j
assert A.i.cross(C.j) == -sin(q3)*C.i + cos(q3)*C.k
assert A.i.cross(C.k) == -cos(q3)*C.j
assert C.i.cross(A.i) == (-sin(q3)*cos(q2))*A.j + \
(-sin(q2)*sin(q3))*A.k
assert C.j.cross(A.i) == (sin(q2))*A.j + (-cos(q2))*A.k
assert express(C.k.cross(A.i), C).trigsimp() == cos(q3)*C.j
def test_orient_new_methods():
N = CoordSysCartesian('N')
orienter1 = AxisOrienter(q4, N.j)
orienter2 = SpaceOrienter(q1, q2, q3, '123')
orienter3 = QuaternionOrienter(q1, q2, q3, q4)
orienter4 = BodyOrienter(q1, q2, q3, '123')
D = N.orient_new('D', (orienter1, ))
E = N.orient_new('E', (orienter2, ))
F = N.orient_new('F', (orienter3, ))
G = N.orient_new('G', (orienter4, ))
assert D == N.orient_new_axis('D', q4, N.j)
assert E == N.orient_new_space('E', q1, q2, q3, '123')
assert F == N.orient_new_quaternion('F', q1, q2, q3, q4)
assert G == N.orient_new_body('G', q1, q2, q3, '123')
def test_locatenew_point():
"""
Tests Point class, and locate_new method in CoordSysCartesian.
"""
A = CoordSysCartesian('A')
assert isinstance(A.origin, Point)
v = a*A.i + b*A.j + c*A.k
C = A.locate_new('C', v)
assert C.origin.position_wrt(A) == \
C.position_wrt(A) == \
C.origin.position_wrt(A.origin) == v
assert A.origin.position_wrt(C) == \
A.position_wrt(C) == \
A.origin.position_wrt(C.origin) == -v
assert A.origin.express_coordinates(C) == (-a, -b, -c)
p = A.origin.locate_new('p', -v)
assert p.express_coordinates(A) == (-a, -b, -c)
assert p.position_wrt(C.origin) == p.position_wrt(C) == \
-2 * v
p1 = p.locate_new('p1', 2*v)
assert p1.position_wrt(C.origin) == Vector.zero
assert p1.express_coordinates(C) == (0, 0, 0)
p2 = p.locate_new('p2', A.i)
assert p1.position_wrt(p2) == 2*v - A.i
assert p2.express_coordinates(C) == (-2*a + 1, -2*b, -2*c)
def test_evalf():
A = CoordSysCartesian('A')
v = 3*A.i + 4*A.j + a*A.k
assert v.n() == v.evalf()
assert v.evalf(subs={a:1}) == v.subs(a, 1).evalf()
| 43.071186 | 91 | 0.488745 | from sympy.vector.coordsysrect import CoordSysCartesian
from sympy.vector.scalar import BaseScalar
from sympy import sin, cos, pi, ImmutableMatrix as Matrix, \
symbols, simplify, zeros, expand
from sympy.vector.functions import express
from sympy.vector.point import Point
from sympy.vector.vector import Vector
from sympy.vector.orienters import (AxisOrienter, BodyOrienter,
SpaceOrienter, QuaternionOrienter)
a, b, c, q = symbols('a b c q')
q1, q2, q3, q4 = symbols('q1 q2 q3 q4')
def test_func_args():
A = CoordSysCartesian('A')
assert A.x.func(*A.x.args) == A.x
expr = 3*A.x + 4*A.y
assert expr.func(*expr.args) == expr
assert A.i.func(*A.i.args) == A.i
v = A.x*A.i + A.y*A.j + A.z*A.k
assert v.func(*v.args) == v
assert A.origin.func(*A.origin.args) == A.origin
def test_coordsyscartesian_equivalence():
A = CoordSysCartesian('A')
A1 = CoordSysCartesian('A')
assert A1 == A
B = CoordSysCartesian('B')
assert A != B
def test_orienters():
A = CoordSysCartesian('A')
axis_orienter = AxisOrienter(a, A.k)
body_orienter = BodyOrienter(a, b, c, '123')
space_orienter = SpaceOrienter(a, b, c, '123')
q_orienter = QuaternionOrienter(q1, q2, q3, q4)
assert axis_orienter.rotation_matrix(A) == Matrix([
[ cos(a), sin(a), 0],
[-sin(a), cos(a), 0],
[ 0, 0, 1]])
assert body_orienter.rotation_matrix() == Matrix([
[ cos(b)*cos(c), sin(a)*sin(b)*cos(c) + sin(c)*cos(a),
sin(a)*sin(c) - sin(b)*cos(a)*cos(c)],
[-sin(c)*cos(b), -sin(a)*sin(b)*sin(c) + cos(a)*cos(c),
sin(a)*cos(c) + sin(b)*sin(c)*cos(a)],
[ sin(b), -sin(a)*cos(b),
cos(a)*cos(b)]])
assert space_orienter.rotation_matrix() == Matrix([
[cos(b)*cos(c), sin(c)*cos(b), -sin(b)],
[sin(a)*sin(b)*cos(c) - sin(c)*cos(a),
sin(a)*sin(b)*sin(c) + cos(a)*cos(c), sin(a)*cos(b)],
[sin(a)*sin(c) + sin(b)*cos(a)*cos(c), -sin(a)*cos(c) +
sin(b)*sin(c)*cos(a), cos(a)*cos(b)]])
assert q_orienter.rotation_matrix() == Matrix([
[q1**2 + q2**2 - q3**2 - q4**2, 2*q1*q4 + 2*q2*q3,
-2*q1*q3 + 2*q2*q4],
[-2*q1*q4 + 2*q2*q3, q1**2 - q2**2 + q3**2 - q4**2,
2*q1*q2 + 2*q3*q4],
[2*q1*q3 + 2*q2*q4,
-2*q1*q2 + 2*q3*q4, q1**2 - q2**2 - q3**2 + q4**2]])
def test_coordinate_vars():
A = CoordSysCartesian('A')
assert BaseScalar('A.x', 0, A, 'A_x', r'\mathbf{{x}_{A}}') == A.x
assert BaseScalar('A.y', 1, A, 'A_y', r'\mathbf{{y}_{A}}') == A.y
assert BaseScalar('A.z', 2, A, 'A_z', r'\mathbf{{z}_{A}}') == A.z
assert BaseScalar('A.x', 0, A, 'A_x', r'\mathbf{{x}_{A}}').__hash__() == A.x.__hash__()
assert isinstance(A.x, BaseScalar) and \
isinstance(A.y, BaseScalar) and \
isinstance(A.z, BaseScalar)
assert A.x*A.y == A.y*A.x
assert A.scalar_map(A) == {A.x: A.x, A.y: A.y, A.z: A.z}
assert A.x.system == A
assert A.x.diff(A.x) == 1
B = A.orient_new_axis('B', q, A.k)
assert B.scalar_map(A) == {B.z: A.z, B.y: -A.x*sin(q) + A.y*cos(q),
B.x: A.x*cos(q) + A.y*sin(q)}
assert A.scalar_map(B) == {A.x: B.x*cos(q) - B.y*sin(q),
A.y: B.x*sin(q) + B.y*cos(q), A.z: B.z}
assert express(B.x, A, variables=True) == A.x*cos(q) + A.y*sin(q)
assert express(B.y, A, variables=True) == -A.x*sin(q) + A.y*cos(q)
assert express(B.z, A, variables=True) == A.z
assert expand(express(B.x*B.y*B.z, A, variables=True)) == \
expand(A.z*(-A.x*sin(q) + A.y*cos(q))*(A.x*cos(q) + A.y*sin(q)))
assert express(B.x*B.i + B.y*B.j + B.z*B.k, A) == \
(B.x*cos(q) - B.y*sin(q))*A.i + (B.x*sin(q) + \
B.y*cos(q))*A.j + B.z*A.k
assert simplify(express(B.x*B.i + B.y*B.j + B.z*B.k, A, \
variables=True)) == \
A.x*A.i + A.y*A.j + A.z*A.k
assert express(A.x*A.i + A.y*A.j + A.z*A.k, B) == \
(A.x*cos(q) + A.y*sin(q))*B.i + \
(-A.x*sin(q) + A.y*cos(q))*B.j + A.z*B.k
assert simplify(express(A.x*A.i + A.y*A.j + A.z*A.k, B, \
variables=True)) == \
B.x*B.i + B.y*B.j + B.z*B.k
N = B.orient_new_axis('N', -q, B.k)
assert N.scalar_map(A) == \
{N.x: A.x, N.z: A.z, N.y: A.y}
C = A.orient_new_axis('C', q, A.i + A.j + A.k)
mapping = A.scalar_map(C)
assert mapping[A.x] == (C.x*(2*cos(q) + 1)/3 +
C.y*(-2*sin(q + pi/6) + 1)/3 +
C.z*(-2*cos(q + pi/3) + 1)/3)
assert mapping[A.y] == (C.x*(-2*cos(q + pi/3) + 1)/3 +
C.y*(2*cos(q) + 1)/3 +
C.z*(-2*sin(q + pi/6) + 1)/3)
assert mapping[A.z] == (C.x*(-2*sin(q + pi/6) + 1)/3 +
C.y*(-2*cos(q + pi/3) + 1)/3 +
C.z*(2*cos(q) + 1)/3)
D = A.locate_new('D', a*A.i + b*A.j + c*A.k)
assert D.scalar_map(A) == {D.z: A.z - c, D.x: A.x - a, D.y: A.y - b}
E = A.orient_new_axis('E', a, A.k, a*A.i + b*A.j + c*A.k)
assert A.scalar_map(E) == {A.z: E.z + c,
A.x: E.x*cos(a) - E.y*sin(a) + a,
A.y: E.x*sin(a) + E.y*cos(a) + b}
assert E.scalar_map(A) == {E.x: (A.x - a)*cos(a) + (A.y - b)*sin(a),
E.y: (-A.x + a)*sin(a) + (A.y - b)*cos(a),
E.z: A.z - c}
F = A.locate_new('F', Vector.zero)
assert A.scalar_map(F) == {A.z: F.z, A.x: F.x, A.y: F.y}
def test_rotation_matrix():
N = CoordSysCartesian('N')
A = N.orient_new_axis('A', q1, N.k)
B = A.orient_new_axis('B', q2, A.i)
C = B.orient_new_axis('C', q3, B.j)
D = N.orient_new_axis('D', q4, N.j)
E = N.orient_new_space('E', q1, q2, q3, '123')
F = N.orient_new_quaternion('F', q1, q2, q3, q4)
G = N.orient_new_body('G', q1, q2, q3, '123')
assert N.rotation_matrix(C) == Matrix([
[- sin(q1) * sin(q2) * sin(q3) + cos(q1) * cos(q3), - sin(q1) *
cos(q2), sin(q1) * sin(q2) * cos(q3) + sin(q3) * cos(q1)], \
[sin(q1) * cos(q3) + sin(q2) * sin(q3) * cos(q1), \
cos(q1) * cos(q2), sin(q1) * sin(q3) - sin(q2) * cos(q1) * \
cos(q3)], [- sin(q3) * cos(q2), sin(q2), cos(q2) * cos(q3)]])
test_mat = D.rotation_matrix(C) - Matrix(
[[cos(q1) * cos(q3) * cos(q4) - sin(q3) * (- sin(q4) * cos(q2) +
sin(q1) * sin(q2) * cos(q4)), - sin(q2) * sin(q4) - sin(q1) *
cos(q2) * cos(q4), sin(q3) * cos(q1) * cos(q4) + cos(q3) * \
(- sin(q4) * cos(q2) + sin(q1) * sin(q2) * cos(q4))], \
[sin(q1) * cos(q3) + sin(q2) * sin(q3) * cos(q1), cos(q1) * \
cos(q2), sin(q1) * sin(q3) - sin(q2) * cos(q1) * cos(q3)], \
[sin(q4) * cos(q1) * cos(q3) - sin(q3) * (cos(q2) * cos(q4) + \
sin(q1) * sin(q2) * \
sin(q4)), sin(q2) *
cos(q4) - sin(q1) * sin(q4) * cos(q2), sin(q3) * \
sin(q4) * cos(q1) + cos(q3) * (cos(q2) * cos(q4) + \
sin(q1) * sin(q2) * sin(q4))]])
assert test_mat.expand() == zeros(3, 3)
assert E.rotation_matrix(N) == Matrix(
[[cos(q2)*cos(q3), sin(q3)*cos(q2), -sin(q2)],
[sin(q1)*sin(q2)*cos(q3) - sin(q3)*cos(q1), \
sin(q1)*sin(q2)*sin(q3) + cos(q1)*cos(q3), sin(q1)*cos(q2)], \
[sin(q1)*sin(q3) + sin(q2)*cos(q1)*cos(q3), - \
sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1), cos(q1)*cos(q2)]])
assert F.rotation_matrix(N) == Matrix([[
q1**2 + q2**2 - q3**2 - q4**2,
2*q1*q4 + 2*q2*q3, -2*q1*q3 + 2*q2*q4],[ -2*q1*q4 + 2*q2*q3,
q1**2 - q2**2 + q3**2 - q4**2, 2*q1*q2 + 2*q3*q4],
[2*q1*q3 + 2*q2*q4,
-2*q1*q2 + 2*q3*q4,
q1**2 - q2**2 - q3**2 + q4**2]])
assert G.rotation_matrix(N) == Matrix([[
cos(q2)*cos(q3), sin(q1)*sin(q2)*cos(q3) + sin(q3)*cos(q1),
sin(q1)*sin(q3) - sin(q2)*cos(q1)*cos(q3)], [
-sin(q3)*cos(q2), -sin(q1)*sin(q2)*sin(q3) + cos(q1)*cos(q3),
sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1)],[
sin(q2), -sin(q1)*cos(q2), cos(q1)*cos(q2)]])
def test_vector():
N = CoordSysCartesian('N')
A = N.orient_new_axis('A', q1, N.k)
B = A.orient_new_axis('B', q2, A.i)
C = B.orient_new_axis('C', q3, B.j)
v1 = a*N.i + b*N.j + c*N.k
assert v1.to_matrix(A) == Matrix([[ a*cos(q1) + b*sin(q1)],
[-a*sin(q1) + b*cos(q1)],
[ c]])
assert N.i.dot(A.i) == cos(q1)
assert N.i.dot(A.j) == -sin(q1)
assert N.i.dot(A.k) == 0
assert N.j.dot(A.i) == sin(q1)
assert N.j.dot(A.j) == cos(q1)
assert N.j.dot(A.k) == 0
assert N.k.dot(A.i) == 0
assert N.k.dot(A.j) == 0
assert N.k.dot(A.k) == 1
assert N.i.dot(A.i + A.j) == -sin(q1) + cos(q1) == \
(A.i + A.j).dot(N.i)
assert A.i.dot(C.i) == cos(q3)
assert A.i.dot(C.j) == 0
assert A.i.dot(C.k) == sin(q3)
assert A.j.dot(C.i) == sin(q2)*sin(q3)
assert A.j.dot(C.j) == cos(q2)
assert A.j.dot(C.k) == -sin(q2)*cos(q3)
assert A.k.dot(C.i) == -cos(q2)*sin(q3)
assert A.k.dot(C.j) == sin(q2)
assert A.k.dot(C.k) == cos(q2)*cos(q3)
assert N.i.cross(A.i) == sin(q1)*A.k
assert N.i.cross(A.j) == cos(q1)*A.k
assert N.i.cross(A.k) == -sin(q1)*A.i - cos(q1)*A.j
assert N.j.cross(A.i) == -cos(q1)*A.k
assert N.j.cross(A.j) == sin(q1)*A.k
assert N.j.cross(A.k) == cos(q1)*A.i - sin(q1)*A.j
assert N.k.cross(A.i) == A.j
assert N.k.cross(A.j) == -A.i
assert N.k.cross(A.k) == Vector.zero
assert N.i.cross(A.i) == sin(q1)*A.k
assert N.i.cross(A.j) == cos(q1)*A.k
assert N.i.cross(A.i + A.j) == sin(q1)*A.k + cos(q1)*A.k
assert (A.i + A.j).cross(N.i) == (-sin(q1) - cos(q1))*N.k
assert A.i.cross(C.i) == sin(q3)*C.j
assert A.i.cross(C.j) == -sin(q3)*C.i + cos(q3)*C.k
assert A.i.cross(C.k) == -cos(q3)*C.j
assert C.i.cross(A.i) == (-sin(q3)*cos(q2))*A.j + \
(-sin(q2)*sin(q3))*A.k
assert C.j.cross(A.i) == (sin(q2))*A.j + (-cos(q2))*A.k
assert express(C.k.cross(A.i), C).trigsimp() == cos(q3)*C.j
def test_orient_new_methods():
N = CoordSysCartesian('N')
orienter1 = AxisOrienter(q4, N.j)
orienter2 = SpaceOrienter(q1, q2, q3, '123')
orienter3 = QuaternionOrienter(q1, q2, q3, q4)
orienter4 = BodyOrienter(q1, q2, q3, '123')
D = N.orient_new('D', (orienter1, ))
E = N.orient_new('E', (orienter2, ))
F = N.orient_new('F', (orienter3, ))
G = N.orient_new('G', (orienter4, ))
assert D == N.orient_new_axis('D', q4, N.j)
assert E == N.orient_new_space('E', q1, q2, q3, '123')
assert F == N.orient_new_quaternion('F', q1, q2, q3, q4)
assert G == N.orient_new_body('G', q1, q2, q3, '123')
def test_locatenew_point():
A = CoordSysCartesian('A')
assert isinstance(A.origin, Point)
v = a*A.i + b*A.j + c*A.k
C = A.locate_new('C', v)
assert C.origin.position_wrt(A) == \
C.position_wrt(A) == \
C.origin.position_wrt(A.origin) == v
assert A.origin.position_wrt(C) == \
A.position_wrt(C) == \
A.origin.position_wrt(C.origin) == -v
assert A.origin.express_coordinates(C) == (-a, -b, -c)
p = A.origin.locate_new('p', -v)
assert p.express_coordinates(A) == (-a, -b, -c)
assert p.position_wrt(C.origin) == p.position_wrt(C) == \
-2 * v
p1 = p.locate_new('p1', 2*v)
assert p1.position_wrt(C.origin) == Vector.zero
assert p1.express_coordinates(C) == (0, 0, 0)
p2 = p.locate_new('p2', A.i)
assert p1.position_wrt(p2) == 2*v - A.i
assert p2.express_coordinates(C) == (-2*a + 1, -2*b, -2*c)
def test_evalf():
A = CoordSysCartesian('A')
v = 3*A.i + 4*A.j + a*A.k
assert v.n() == v.evalf()
assert v.evalf(subs={a:1}) == v.subs(a, 1).evalf()
| true | true |
790bf88266f11d454e343bd766de7cb931a386ae | 132,204 | py | Python | tb_rest_client/api/api_pe/entity_group_controller_api.py | samson0v/python_tb_rest_client | 08ff7898740f7cec2170e85d5c3c89e222e967f7 | [
"Apache-2.0"
] | 30 | 2020-06-19T06:42:50.000Z | 2021-08-23T21:16:36.000Z | tb_rest_client/api/api_pe/entity_group_controller_api.py | samson0v/python_tb_rest_client | 08ff7898740f7cec2170e85d5c3c89e222e967f7 | [
"Apache-2.0"
] | 25 | 2021-08-30T01:17:27.000Z | 2022-03-16T14:10:14.000Z | tb_rest_client/api/api_pe/entity_group_controller_api.py | samson0v/python_tb_rest_client | 08ff7898740f7cec2170e85d5c3c89e222e967f7 | [
"Apache-2.0"
] | 23 | 2020-07-06T13:41:54.000Z | 2021-08-23T21:04:50.000Z | # coding: utf-8
"""
ThingsBoard REST API
ThingsBoard Professional Edition IoT platform REST API documentation. # noqa: E501
OpenAPI spec version: 3.3.3PAAS-RC1
Contact: info@thingsboard.io
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import re # noqa: F401
# python 2 and python 3 compatibility library
import six
from tb_rest_client.api_client import ApiClient
class EntityGroupControllerApi(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
def add_entities_to_entity_group_using_post(self, entity_group_id, **kwargs): # noqa: E501
"""Add entities to the group (addEntitiesToEntityGroup) # noqa: E501
Add entities to the specified entity group. Entity group allows you to group multiple entities of the same entity type (Device, Asset, Customer, User, Dashboard, etc). Entity Group always have an owner - particular Tenant or Customer. Each entity may belong to multiple groups simultaneously. Available for users with 'TENANT_ADMIN' or 'CUSTOMER_USER' authority. Security check is performed to verify that the user has 'ADD_TO_GROUP' permission for specified group. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.add_entities_to_entity_group_using_post(entity_group_id, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str entity_group_id: A string value representing the Entity Group Id. For example, '784f394c-42b6-435a-983c-b7beff2784f9' (required)
:param list[str] body:
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.add_entities_to_entity_group_using_post_with_http_info(entity_group_id, **kwargs) # noqa: E501
else:
(data) = self.add_entities_to_entity_group_using_post_with_http_info(entity_group_id, **kwargs) # noqa: E501
return data
def add_entities_to_entity_group_using_post_with_http_info(self, entity_group_id, **kwargs): # noqa: E501
"""Add entities to the group (addEntitiesToEntityGroup) # noqa: E501
Add entities to the specified entity group. Entity group allows you to group multiple entities of the same entity type (Device, Asset, Customer, User, Dashboard, etc). Entity Group always have an owner - particular Tenant or Customer. Each entity may belong to multiple groups simultaneously. Available for users with 'TENANT_ADMIN' or 'CUSTOMER_USER' authority. Security check is performed to verify that the user has 'ADD_TO_GROUP' permission for specified group. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.add_entities_to_entity_group_using_post_with_http_info(entity_group_id, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str entity_group_id: A string value representing the Entity Group Id. For example, '784f394c-42b6-435a-983c-b7beff2784f9' (required)
:param list[str] body:
:return: None
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['entity_group_id', 'body'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method add_entities_to_entity_group_using_post" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'entity_group_id' is set
if ('entity_group_id' not in params or
params['entity_group_id'] is None):
raise ValueError("Missing the required parameter `entity_group_id` when calling `add_entities_to_entity_group_using_post`") # noqa: E501
collection_formats = {}
path_params = {}
if 'entity_group_id' in params:
path_params['entityGroupId'] = params['entity_group_id'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['X-Authorization'] # noqa: E501
return self.api_client.call_api(
'/api/entityGroup/{entityGroupId}/addEntities', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def assign_entity_group_to_edge_using_post(self, edge_id, group_type, entity_group_id, **kwargs): # noqa: E501
"""Assign entity group to edge (assignEntityGroupToEdge) # noqa: E501
Creates assignment of an existing entity group to an instance of The Edge. Assignment works in async way - first, notification event pushed to edge service queue on platform. Second, remote edge service will receive a copy of assignment entity group (Edge will receive this instantly, if it's currently connected, or once it's going to be connected to platform). Third, once entity group will be delivered to edge service, edge will request entities of this group to be send to edge. Once entities will be delivered to edge service, they are going to be available for usage on remote edge instance. Available for users with 'TENANT_ADMIN' or 'CUSTOMER_USER' authority. Security check is performed to verify that the user has 'WRITE' permission for the entity (entities). # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.assign_entity_group_to_edge_using_post(edge_id, group_type, entity_group_id, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str edge_id: A string value representing the edge id. For example, '784f394c-42b6-435a-983c-b7beff2784f9' (required)
:param str group_type: EntityGroup type (required)
:param str entity_group_id: A string value representing the Entity Group Id. For example, '784f394c-42b6-435a-983c-b7beff2784f9' (required)
:return: EntityGroup
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.assign_entity_group_to_edge_using_post_with_http_info(edge_id, group_type, entity_group_id, **kwargs) # noqa: E501
else:
(data) = self.assign_entity_group_to_edge_using_post_with_http_info(edge_id, group_type, entity_group_id, **kwargs) # noqa: E501
return data
def assign_entity_group_to_edge_using_post_with_http_info(self, edge_id, group_type, entity_group_id, **kwargs): # noqa: E501
"""Assign entity group to edge (assignEntityGroupToEdge) # noqa: E501
Creates assignment of an existing entity group to an instance of The Edge. Assignment works in async way - first, notification event pushed to edge service queue on platform. Second, remote edge service will receive a copy of assignment entity group (Edge will receive this instantly, if it's currently connected, or once it's going to be connected to platform). Third, once entity group will be delivered to edge service, edge will request entities of this group to be send to edge. Once entities will be delivered to edge service, they are going to be available for usage on remote edge instance. Available for users with 'TENANT_ADMIN' or 'CUSTOMER_USER' authority. Security check is performed to verify that the user has 'WRITE' permission for the entity (entities). # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.assign_entity_group_to_edge_using_post_with_http_info(edge_id, group_type, entity_group_id, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str edge_id: A string value representing the edge id. For example, '784f394c-42b6-435a-983c-b7beff2784f9' (required)
:param str group_type: EntityGroup type (required)
:param str entity_group_id: A string value representing the Entity Group Id. For example, '784f394c-42b6-435a-983c-b7beff2784f9' (required)
:return: EntityGroup
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['edge_id', 'group_type', 'entity_group_id'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method assign_entity_group_to_edge_using_post" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'edge_id' is set
if ('edge_id' not in params or
params['edge_id'] is None):
raise ValueError("Missing the required parameter `edge_id` when calling `assign_entity_group_to_edge_using_post`") # noqa: E501
# verify the required parameter 'group_type' is set
if ('group_type' not in params or
params['group_type'] is None):
raise ValueError("Missing the required parameter `group_type` when calling `assign_entity_group_to_edge_using_post`") # noqa: E501
# verify the required parameter 'entity_group_id' is set
if ('entity_group_id' not in params or
params['entity_group_id'] is None):
raise ValueError("Missing the required parameter `entity_group_id` when calling `assign_entity_group_to_edge_using_post`") # noqa: E501
collection_formats = {}
path_params = {}
if 'edge_id' in params:
path_params['edgeId'] = params['edge_id'] # noqa: E501
if 'group_type' in params:
path_params['groupType'] = params['group_type'] # noqa: E501
if 'entity_group_id' in params:
path_params['entityGroupId'] = params['entity_group_id'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['X-Authorization'] # noqa: E501
return self.api_client.call_api(
'/api/edge/{edgeId}/entityGroup/{entityGroupId}/{groupType}', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='EntityGroup', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_entity_group_using_delete(self, entity_group_id, **kwargs): # noqa: E501
"""Delete Entity Group (deleteEntityGroup) # noqa: E501
Deletes the entity group but does not delete the entities in the group, since they are also present in reserved group 'All'. Referencing non-existing Entity Group Id will cause an error. Available for users with 'TENANT_ADMIN' or 'CUSTOMER_USER' authority. Security check is performed to verify that the user has 'DELETE' permission for specified group. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_entity_group_using_delete(entity_group_id, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str entity_group_id: A string value representing the Entity Group Id. For example, '784f394c-42b6-435a-983c-b7beff2784f9' (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.delete_entity_group_using_delete_with_http_info(entity_group_id, **kwargs) # noqa: E501
else:
(data) = self.delete_entity_group_using_delete_with_http_info(entity_group_id, **kwargs) # noqa: E501
return data
def delete_entity_group_using_delete_with_http_info(self, entity_group_id, **kwargs): # noqa: E501
"""Delete Entity Group (deleteEntityGroup) # noqa: E501
Deletes the entity group but does not delete the entities in the group, since they are also present in reserved group 'All'. Referencing non-existing Entity Group Id will cause an error. Available for users with 'TENANT_ADMIN' or 'CUSTOMER_USER' authority. Security check is performed to verify that the user has 'DELETE' permission for specified group. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_entity_group_using_delete_with_http_info(entity_group_id, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str entity_group_id: A string value representing the Entity Group Id. For example, '784f394c-42b6-435a-983c-b7beff2784f9' (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['entity_group_id'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_entity_group_using_delete" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'entity_group_id' is set
if ('entity_group_id' not in params or
params['entity_group_id'] is None):
raise ValueError("Missing the required parameter `entity_group_id` when calling `delete_entity_group_using_delete`") # noqa: E501
collection_formats = {}
path_params = {}
if 'entity_group_id' in params:
path_params['entityGroupId'] = params['entity_group_id'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['X-Authorization'] # noqa: E501
return self.api_client.call_api(
'/api/entityGroup/{entityGroupId}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_all_edge_entity_groups_using_get(self, edge_id, group_type, **kwargs): # noqa: E501
"""Get All Edge Entity Groups by entity type (getAllEdgeEntityGroups) # noqa: E501
Fetch the list of Entity Group Info objects based on the provided Entity Type and assigned to the provided Edge entity. Entity group allows you to group multiple entities of the same entity type (Device, Asset, Customer, User, Dashboard, etc). Entity Group always have an owner - particular Tenant or Customer. Each entity may belong to multiple groups simultaneously.Entity Group Info extends Entity Group object and adds 'ownerIds' - a list of owner ids. Available for users with 'TENANT_ADMIN' or 'CUSTOMER_USER' authority. Security check is performed to verify that the user has 'READ' permission for the entity (entities). # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_all_edge_entity_groups_using_get(edge_id, group_type, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str edge_id: A string value representing the edge id. For example, '784f394c-42b6-435a-983c-b7beff2784f9' (required)
:param str group_type: EntityGroup type (required)
:return: list[EntityGroupInfo]
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.get_all_edge_entity_groups_using_get_with_http_info(edge_id, group_type, **kwargs) # noqa: E501
else:
(data) = self.get_all_edge_entity_groups_using_get_with_http_info(edge_id, group_type, **kwargs) # noqa: E501
return data
def get_all_edge_entity_groups_using_get_with_http_info(self, edge_id, group_type, **kwargs): # noqa: E501
"""Get All Edge Entity Groups by entity type (getAllEdgeEntityGroups) # noqa: E501
Fetch the list of Entity Group Info objects based on the provided Entity Type and assigned to the provided Edge entity. Entity group allows you to group multiple entities of the same entity type (Device, Asset, Customer, User, Dashboard, etc). Entity Group always have an owner - particular Tenant or Customer. Each entity may belong to multiple groups simultaneously.Entity Group Info extends Entity Group object and adds 'ownerIds' - a list of owner ids. Available for users with 'TENANT_ADMIN' or 'CUSTOMER_USER' authority. Security check is performed to verify that the user has 'READ' permission for the entity (entities). # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_all_edge_entity_groups_using_get_with_http_info(edge_id, group_type, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str edge_id: A string value representing the edge id. For example, '784f394c-42b6-435a-983c-b7beff2784f9' (required)
:param str group_type: EntityGroup type (required)
:return: list[EntityGroupInfo]
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['edge_id', 'group_type'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_all_edge_entity_groups_using_get" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'edge_id' is set
if ('edge_id' not in params or
params['edge_id'] is None):
raise ValueError("Missing the required parameter `edge_id` when calling `get_all_edge_entity_groups_using_get`") # noqa: E501
# verify the required parameter 'group_type' is set
if ('group_type' not in params or
params['group_type'] is None):
raise ValueError("Missing the required parameter `group_type` when calling `get_all_edge_entity_groups_using_get`") # noqa: E501
collection_formats = {}
path_params = {}
if 'edge_id' in params:
path_params['edgeId'] = params['edge_id'] # noqa: E501
if 'group_type' in params:
path_params['groupType'] = params['group_type'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['X-Authorization'] # noqa: E501
return self.api_client.call_api(
'/api/allEntityGroups/edge/{edgeId}/{groupType}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='list[EntityGroupInfo]', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_edge_entity_groups_using_get(self, edge_id, group_type, page_size, page, **kwargs): # noqa: E501
"""Get Edge Entity Groups by entity type (getEdgeEntityGroups) # noqa: E501
Returns a page of Entity Group Info objects based on the provided Entity Type and assigned to the provided Edge entity. Entity group allows you to group multiple entities of the same entity type (Device, Asset, Customer, User, Dashboard, etc). Entity Group always have an owner - particular Tenant or Customer. Each entity may belong to multiple groups simultaneously.Entity Group Info extends Entity Group object and adds 'ownerIds' - a list of owner ids.You can specify parameters to filter the results. The result is wrapped with PageData object that allows you to iterate over result set using pagination. See the 'Model' tab of the Response Class for more details. Available for users with 'TENANT_ADMIN' or 'CUSTOMER_USER' authority. Security check is performed to verify that the user has 'READ' permission for the entity (entities). # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_edge_entity_groups_using_get(edge_id, group_type, page_size, page, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str edge_id: A string value representing the edge id. For example, '784f394c-42b6-435a-983c-b7beff2784f9' (required)
:param str group_type: EntityGroup type (required)
:param int page_size: Maximum amount of entities in a one page (required)
:param int page: Sequence number of page starting from 0 (required)
:param str sort_property: Property of entity to sort by
:param str sort_order: Sort order. ASC (ASCENDING) or DESC (DESCENDING)
:return: PageDataEntityGroupInfo
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.get_edge_entity_groups_using_get_with_http_info(edge_id, group_type, page_size, page, **kwargs) # noqa: E501
else:
(data) = self.get_edge_entity_groups_using_get_with_http_info(edge_id, group_type, page_size, page, **kwargs) # noqa: E501
return data
def get_edge_entity_groups_using_get_with_http_info(self, edge_id, group_type, page_size, page, **kwargs): # noqa: E501
"""Get Edge Entity Groups by entity type (getEdgeEntityGroups) # noqa: E501
Returns a page of Entity Group Info objects based on the provided Entity Type and assigned to the provided Edge entity. Entity group allows you to group multiple entities of the same entity type (Device, Asset, Customer, User, Dashboard, etc). Entity Group always have an owner - particular Tenant or Customer. Each entity may belong to multiple groups simultaneously.Entity Group Info extends Entity Group object and adds 'ownerIds' - a list of owner ids.You can specify parameters to filter the results. The result is wrapped with PageData object that allows you to iterate over result set using pagination. See the 'Model' tab of the Response Class for more details. Available for users with 'TENANT_ADMIN' or 'CUSTOMER_USER' authority. Security check is performed to verify that the user has 'READ' permission for the entity (entities). # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_edge_entity_groups_using_get_with_http_info(edge_id, group_type, page_size, page, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str edge_id: A string value representing the edge id. For example, '784f394c-42b6-435a-983c-b7beff2784f9' (required)
:param str group_type: EntityGroup type (required)
:param int page_size: Maximum amount of entities in a one page (required)
:param int page: Sequence number of page starting from 0 (required)
:param str sort_property: Property of entity to sort by
:param str sort_order: Sort order. ASC (ASCENDING) or DESC (DESCENDING)
:return: PageDataEntityGroupInfo
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['edge_id', 'group_type', 'page_size', 'page', 'sort_property', 'sort_order'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_edge_entity_groups_using_get" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'edge_id' is set
if ('edge_id' not in params or
params['edge_id'] is None):
raise ValueError("Missing the required parameter `edge_id` when calling `get_edge_entity_groups_using_get`") # noqa: E501
# verify the required parameter 'group_type' is set
if ('group_type' not in params or
params['group_type'] is None):
raise ValueError("Missing the required parameter `group_type` when calling `get_edge_entity_groups_using_get`") # noqa: E501
# verify the required parameter 'page_size' is set
if ('page_size' not in params or
params['page_size'] is None):
raise ValueError("Missing the required parameter `page_size` when calling `get_edge_entity_groups_using_get`") # noqa: E501
# verify the required parameter 'page' is set
if ('page' not in params or
params['page'] is None):
raise ValueError("Missing the required parameter `page` when calling `get_edge_entity_groups_using_get`") # noqa: E501
collection_formats = {}
path_params = {}
if 'edge_id' in params:
path_params['edgeId'] = params['edge_id'] # noqa: E501
if 'group_type' in params:
path_params['groupType'] = params['group_type'] # noqa: E501
query_params = []
if 'page_size' in params:
query_params.append(('pageSize', params['page_size'])) # noqa: E501
if 'page' in params:
query_params.append(('page', params['page'])) # noqa: E501
if 'sort_property' in params:
query_params.append(('sortProperty', params['sort_property'])) # noqa: E501
if 'sort_order' in params:
query_params.append(('sortOrder', params['sort_order'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['X-Authorization'] # noqa: E501
return self.api_client.call_api(
'/api/entityGroups/edge/{edgeId}/{groupType}{?page,pageSize,sortOrder,sortProperty}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='PageDataEntityGroupInfo', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_entities_using_get(self, entity_group_id, page_size, page, **kwargs): # noqa: E501
"""Get Group Entities (getEntities) # noqa: E501
Returns a page of Short Entity View objects that belongs to specified Entity Group Id. Short Entity View object contains the entity id and number of fields (attributes, telemetry, etc). List of those fields is configurable and defined in the group configuration.You can specify parameters to filter the results. The result is wrapped with PageData object that allows you to iterate over result set using pagination. See the 'Model' tab of the Response Class for more details. Available for users with 'TENANT_ADMIN' or 'CUSTOMER_USER' authority. Security check is performed to verify that the user has 'READ' permission for specified group. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_entities_using_get(entity_group_id, page_size, page, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str entity_group_id: A string value representing the Entity Group Id. For example, '784f394c-42b6-435a-983c-b7beff2784f9' (required)
:param int page_size: Maximum amount of entities in a one page (required)
:param int page: Sequence number of page starting from 0 (required)
:param str text_search: The case insensitive 'startsWith' filter based on the entity group name.
:param str sort_property: Property of entity to sort by
:param str sort_order: Sort order. ASC (ASCENDING) or DESC (DESCENDING)
:return: PageDataShortEntityView
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.get_entities_using_get_with_http_info(entity_group_id, page_size, page, **kwargs) # noqa: E501
else:
(data) = self.get_entities_using_get_with_http_info(entity_group_id, page_size, page, **kwargs) # noqa: E501
return data
def get_entities_using_get_with_http_info(self, entity_group_id, page_size, page, **kwargs): # noqa: E501
"""Get Group Entities (getEntities) # noqa: E501
Returns a page of Short Entity View objects that belongs to specified Entity Group Id. Short Entity View object contains the entity id and number of fields (attributes, telemetry, etc). List of those fields is configurable and defined in the group configuration.You can specify parameters to filter the results. The result is wrapped with PageData object that allows you to iterate over result set using pagination. See the 'Model' tab of the Response Class for more details. Available for users with 'TENANT_ADMIN' or 'CUSTOMER_USER' authority. Security check is performed to verify that the user has 'READ' permission for specified group. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_entities_using_get_with_http_info(entity_group_id, page_size, page, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str entity_group_id: A string value representing the Entity Group Id. For example, '784f394c-42b6-435a-983c-b7beff2784f9' (required)
:param int page_size: Maximum amount of entities in a one page (required)
:param int page: Sequence number of page starting from 0 (required)
:param str text_search: The case insensitive 'startsWith' filter based on the entity group name.
:param str sort_property: Property of entity to sort by
:param str sort_order: Sort order. ASC (ASCENDING) or DESC (DESCENDING)
:return: PageDataShortEntityView
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['entity_group_id', 'page_size', 'page', 'text_search', 'sort_property', 'sort_order'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_entities_using_get" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'entity_group_id' is set
if ('entity_group_id' not in params or
params['entity_group_id'] is None):
raise ValueError("Missing the required parameter `entity_group_id` when calling `get_entities_using_get`") # noqa: E501
# verify the required parameter 'page_size' is set
if ('page_size' not in params or
params['page_size'] is None):
raise ValueError("Missing the required parameter `page_size` when calling `get_entities_using_get`") # noqa: E501
# verify the required parameter 'page' is set
if ('page' not in params or
params['page'] is None):
raise ValueError("Missing the required parameter `page` when calling `get_entities_using_get`") # noqa: E501
collection_formats = {}
path_params = {}
if 'entity_group_id' in params:
path_params['entityGroupId'] = params['entity_group_id'] # noqa: E501
query_params = []
if 'page_size' in params:
query_params.append(('pageSize', params['page_size'])) # noqa: E501
if 'page' in params:
query_params.append(('page', params['page'])) # noqa: E501
if 'text_search' in params:
query_params.append(('textSearch', params['text_search'])) # noqa: E501
if 'sort_property' in params:
query_params.append(('sortProperty', params['sort_property'])) # noqa: E501
if 'sort_order' in params:
query_params.append(('sortOrder', params['sort_order'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['X-Authorization'] # noqa: E501
return self.api_client.call_api(
'/api/entityGroup/{entityGroupId}/entities{?page,pageSize,sortOrder,sortProperty,textSearch}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='PageDataShortEntityView', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_entity_group_all_by_owner_and_type_using_get(self, owner_type, owner_id, group_type, **kwargs): # noqa: E501
"""Get special group All by owner and entity type (getEntityGroupsByOwnerAndType) # noqa: E501
Fetch reserved group 'All' based on the provided Owner Id and Entity Type. Entity group allows you to group multiple entities of the same entity type (Device, Asset, Customer, User, Dashboard, etc). Entity Group always have an owner - particular Tenant or Customer. Each entity may belong to multiple groups simultaneously.Entity Group Info extends Entity Group object and adds 'ownerIds' - a list of owner ids. Available for users with 'TENANT_ADMIN' or 'CUSTOMER_USER' authority. Security check is performed to verify that the user has 'READ' permission for specified group. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_entity_group_all_by_owner_and_type_using_get(owner_type, owner_id, group_type, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str owner_type: Tenant or Customer (required)
:param str owner_id: A string value representing the Tenant or Customer id (required)
:param str group_type: Entity Group type (required)
:return: EntityGroupInfo
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.get_entity_group_all_by_owner_and_type_using_get_with_http_info(owner_type, owner_id, group_type, **kwargs) # noqa: E501
else:
(data) = self.get_entity_group_all_by_owner_and_type_using_get_with_http_info(owner_type, owner_id, group_type, **kwargs) # noqa: E501
return data
def get_entity_group_all_by_owner_and_type_using_get_with_http_info(self, owner_type, owner_id, group_type, **kwargs): # noqa: E501
"""Get special group All by owner and entity type (getEntityGroupsByOwnerAndType) # noqa: E501
Fetch reserved group 'All' based on the provided Owner Id and Entity Type. Entity group allows you to group multiple entities of the same entity type (Device, Asset, Customer, User, Dashboard, etc). Entity Group always have an owner - particular Tenant or Customer. Each entity may belong to multiple groups simultaneously.Entity Group Info extends Entity Group object and adds 'ownerIds' - a list of owner ids. Available for users with 'TENANT_ADMIN' or 'CUSTOMER_USER' authority. Security check is performed to verify that the user has 'READ' permission for specified group. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_entity_group_all_by_owner_and_type_using_get_with_http_info(owner_type, owner_id, group_type, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str owner_type: Tenant or Customer (required)
:param str owner_id: A string value representing the Tenant or Customer id (required)
:param str group_type: Entity Group type (required)
:return: EntityGroupInfo
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['owner_type', 'owner_id', 'group_type'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_entity_group_all_by_owner_and_type_using_get" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'owner_type' is set
if ('owner_type' not in params or
params['owner_type'] is None):
raise ValueError("Missing the required parameter `owner_type` when calling `get_entity_group_all_by_owner_and_type_using_get`") # noqa: E501
# verify the required parameter 'owner_id' is set
if ('owner_id' not in params or
params['owner_id'] is None):
raise ValueError("Missing the required parameter `owner_id` when calling `get_entity_group_all_by_owner_and_type_using_get`") # noqa: E501
# verify the required parameter 'group_type' is set
if ('group_type' not in params or
params['group_type'] is None):
raise ValueError("Missing the required parameter `group_type` when calling `get_entity_group_all_by_owner_and_type_using_get`") # noqa: E501
collection_formats = {}
path_params = {}
if 'owner_type' in params:
path_params['ownerType'] = params['owner_type'] # noqa: E501
if 'owner_id' in params:
path_params['ownerId'] = params['owner_id'] # noqa: E501
if 'group_type' in params:
path_params['groupType'] = params['group_type'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['X-Authorization'] # noqa: E501
return self.api_client.call_api(
'/api/entityGroup/all/{ownerType}/{ownerId}/{groupType}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='EntityGroupInfo', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_entity_group_by_id_using_get(self, entity_group_id, **kwargs): # noqa: E501
"""Get Entity Group Info (getEntityGroupById) # noqa: E501
Fetch the Entity Group object based on the provided Entity Group Id. Entity group allows you to group multiple entities of the same entity type (Device, Asset, Customer, User, Dashboard, etc). Entity Group always have an owner - particular Tenant or Customer. Each entity may belong to multiple groups simultaneously.Entity Group Info extends Entity Group object and adds 'ownerIds' - a list of owner ids. Entity group name is unique in the scope of owner and entity type. For example, you can't create two tenant device groups called 'Water meters'. However, you may create device and asset group with the same name. And also you may create groups with the same name for two different customers of the same tenant. Available for users with 'TENANT_ADMIN' or 'CUSTOMER_USER' authority. Security check is performed to verify that the user has 'READ' permission for specified group. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_entity_group_by_id_using_get(entity_group_id, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str entity_group_id: A string value representing the Entity Group Id. For example, '784f394c-42b6-435a-983c-b7beff2784f9' (required)
:return: EntityGroupInfo
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.get_entity_group_by_id_using_get_with_http_info(entity_group_id, **kwargs) # noqa: E501
else:
(data) = self.get_entity_group_by_id_using_get_with_http_info(entity_group_id, **kwargs) # noqa: E501
return data
def get_entity_group_by_id_using_get_with_http_info(self, entity_group_id, **kwargs): # noqa: E501
"""Get Entity Group Info (getEntityGroupById) # noqa: E501
Fetch the Entity Group object based on the provided Entity Group Id. Entity group allows you to group multiple entities of the same entity type (Device, Asset, Customer, User, Dashboard, etc). Entity Group always have an owner - particular Tenant or Customer. Each entity may belong to multiple groups simultaneously.Entity Group Info extends Entity Group object and adds 'ownerIds' - a list of owner ids. Entity group name is unique in the scope of owner and entity type. For example, you can't create two tenant device groups called 'Water meters'. However, you may create device and asset group with the same name. And also you may create groups with the same name for two different customers of the same tenant. Available for users with 'TENANT_ADMIN' or 'CUSTOMER_USER' authority. Security check is performed to verify that the user has 'READ' permission for specified group. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_entity_group_by_id_using_get_with_http_info(entity_group_id, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str entity_group_id: A string value representing the Entity Group Id. For example, '784f394c-42b6-435a-983c-b7beff2784f9' (required)
:return: EntityGroupInfo
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['entity_group_id'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_entity_group_by_id_using_get" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'entity_group_id' is set
if ('entity_group_id' not in params or
params['entity_group_id'] is None):
raise ValueError("Missing the required parameter `entity_group_id` when calling `get_entity_group_by_id_using_get`") # noqa: E501
collection_formats = {}
path_params = {}
if 'entity_group_id' in params:
path_params['entityGroupId'] = params['entity_group_id'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['X-Authorization'] # noqa: E501
return self.api_client.call_api(
'/api/entityGroup/{entityGroupId}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='EntityGroupInfo', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_entity_group_by_owner_and_name_and_type_using_get(self, owner_type, owner_id, group_type, group_name, **kwargs): # noqa: E501
"""Get Entity Group by owner, type and name (getEntityGroupByOwnerAndNameAndType) # noqa: E501
Fetch the Entity Group object based on the provided Entity Group Id. Entity group allows you to group multiple entities of the same entity type (Device, Asset, Customer, User, Dashboard, etc). Entity Group always have an owner - particular Tenant or Customer. Each entity may belong to multiple groups simultaneously.Entity Group Info extends Entity Group object and adds 'ownerIds' - a list of owner ids. Entity group name is unique in the scope of owner and entity type. For example, you can't create two tenant device groups called 'Water meters'. However, you may create device and asset group with the same name. And also you may create groups with the same name for two different customers of the same tenant. Available for users with 'TENANT_ADMIN' or 'CUSTOMER_USER' authority. Security check is performed to verify that the user has 'READ' permission for specified group. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_entity_group_by_owner_and_name_and_type_using_get(owner_type, owner_id, group_type, group_name, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str owner_type: Tenant or Customer (required)
:param str owner_id: A string value representing the Tenant or Customer id (required)
:param str group_type: Entity Group type (required)
:param str group_name: Entity Group name (required)
:return: EntityGroupInfo
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.get_entity_group_by_owner_and_name_and_type_using_get_with_http_info(owner_type, owner_id, group_type, group_name, **kwargs) # noqa: E501
else:
(data) = self.get_entity_group_by_owner_and_name_and_type_using_get_with_http_info(owner_type, owner_id, group_type, group_name, **kwargs) # noqa: E501
return data
def get_entity_group_by_owner_and_name_and_type_using_get_with_http_info(self, owner_type, owner_id, group_type, group_name, **kwargs): # noqa: E501
"""Get Entity Group by owner, type and name (getEntityGroupByOwnerAndNameAndType) # noqa: E501
Fetch the Entity Group object based on the provided Entity Group Id. Entity group allows you to group multiple entities of the same entity type (Device, Asset, Customer, User, Dashboard, etc). Entity Group always have an owner - particular Tenant or Customer. Each entity may belong to multiple groups simultaneously.Entity Group Info extends Entity Group object and adds 'ownerIds' - a list of owner ids. Entity group name is unique in the scope of owner and entity type. For example, you can't create two tenant device groups called 'Water meters'. However, you may create device and asset group with the same name. And also you may create groups with the same name for two different customers of the same tenant. Available for users with 'TENANT_ADMIN' or 'CUSTOMER_USER' authority. Security check is performed to verify that the user has 'READ' permission for specified group. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_entity_group_by_owner_and_name_and_type_using_get_with_http_info(owner_type, owner_id, group_type, group_name, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str owner_type: Tenant or Customer (required)
:param str owner_id: A string value representing the Tenant or Customer id (required)
:param str group_type: Entity Group type (required)
:param str group_name: Entity Group name (required)
:return: EntityGroupInfo
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['owner_type', 'owner_id', 'group_type', 'group_name'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_entity_group_by_owner_and_name_and_type_using_get" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'owner_type' is set
if ('owner_type' not in params or
params['owner_type'] is None):
raise ValueError("Missing the required parameter `owner_type` when calling `get_entity_group_by_owner_and_name_and_type_using_get`") # noqa: E501
# verify the required parameter 'owner_id' is set
if ('owner_id' not in params or
params['owner_id'] is None):
raise ValueError("Missing the required parameter `owner_id` when calling `get_entity_group_by_owner_and_name_and_type_using_get`") # noqa: E501
# verify the required parameter 'group_type' is set
if ('group_type' not in params or
params['group_type'] is None):
raise ValueError("Missing the required parameter `group_type` when calling `get_entity_group_by_owner_and_name_and_type_using_get`") # noqa: E501
# verify the required parameter 'group_name' is set
if ('group_name' not in params or
params['group_name'] is None):
raise ValueError("Missing the required parameter `group_name` when calling `get_entity_group_by_owner_and_name_and_type_using_get`") # noqa: E501
collection_formats = {}
path_params = {}
if 'owner_type' in params:
path_params['ownerType'] = params['owner_type'] # noqa: E501
if 'owner_id' in params:
path_params['ownerId'] = params['owner_id'] # noqa: E501
if 'group_type' in params:
path_params['groupType'] = params['group_type'] # noqa: E501
if 'group_name' in params:
path_params['groupName'] = params['group_name'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['X-Authorization'] # noqa: E501
return self.api_client.call_api(
'/api/entityGroup/{ownerType}/{ownerId}/{groupType}/{groupName}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='EntityGroupInfo', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_entity_groups_by_ids_using_get(self, entity_group_ids, **kwargs): # noqa: E501
"""Get Entity Groups by Ids (getDevicesByIds) # noqa: E501
Requested devices must be owned by tenant or assigned to customer which user is performing the request. Available for users with 'TENANT_ADMIN' or 'CUSTOMER_USER' authority. Security check is performed to verify that the user has 'READ' permission for the entity (entities). # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_entity_groups_by_ids_using_get(entity_group_ids, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str entity_group_ids: A list of group ids, separated by comma ',' (required)
:return: list[EntityGroup]
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.get_entity_groups_by_ids_using_get_with_http_info(entity_group_ids, **kwargs) # noqa: E501
else:
(data) = self.get_entity_groups_by_ids_using_get_with_http_info(entity_group_ids, **kwargs) # noqa: E501
return data
def get_entity_groups_by_ids_using_get_with_http_info(self, entity_group_ids, **kwargs): # noqa: E501
"""Get Entity Groups by Ids (getDevicesByIds) # noqa: E501
Requested devices must be owned by tenant or assigned to customer which user is performing the request. Available for users with 'TENANT_ADMIN' or 'CUSTOMER_USER' authority. Security check is performed to verify that the user has 'READ' permission for the entity (entities). # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_entity_groups_by_ids_using_get_with_http_info(entity_group_ids, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str entity_group_ids: A list of group ids, separated by comma ',' (required)
:return: list[EntityGroup]
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['entity_group_ids'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_entity_groups_by_ids_using_get" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'entity_group_ids' is set
if ('entity_group_ids' not in params or
params['entity_group_ids'] is None):
raise ValueError("Missing the required parameter `entity_group_ids` when calling `get_entity_groups_by_ids_using_get`") # noqa: E501
collection_formats = {}
path_params = {}
query_params = []
if 'entity_group_ids' in params:
query_params.append(('entityGroupIds', params['entity_group_ids'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['X-Authorization'] # noqa: E501
return self.api_client.call_api(
'/api/entityGroups{?entityGroupIds}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='list[EntityGroup]', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_entity_groups_by_owner_and_type_using_get(self, owner_type, owner_id, group_type, **kwargs): # noqa: E501
"""Get Entity Groups by owner and entity type (getEntityGroupsByOwnerAndType) # noqa: E501
Fetch the list of Entity Group Info objects based on the provided Owner Id and Entity Type. Entity group allows you to group multiple entities of the same entity type (Device, Asset, Customer, User, Dashboard, etc). Entity Group always have an owner - particular Tenant or Customer. Each entity may belong to multiple groups simultaneously.Entity Group Info extends Entity Group object and adds 'ownerIds' - a list of owner ids. Available for users with 'TENANT_ADMIN' or 'CUSTOMER_USER' authority. Security check is performed to verify that the user has 'READ' permission for specified group. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_entity_groups_by_owner_and_type_using_get(owner_type, owner_id, group_type, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str owner_type: Tenant or Customer (required)
:param str owner_id: A string value representing the Tenant or Customer id (required)
:param str group_type: Entity Group type (required)
:return: list[EntityGroupInfo]
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.get_entity_groups_by_owner_and_type_using_get_with_http_info(owner_type, owner_id, group_type, **kwargs) # noqa: E501
else:
(data) = self.get_entity_groups_by_owner_and_type_using_get_with_http_info(owner_type, owner_id, group_type, **kwargs) # noqa: E501
return data
def get_entity_groups_by_owner_and_type_using_get_with_http_info(self, owner_type, owner_id, group_type, **kwargs): # noqa: E501
"""Get Entity Groups by owner and entity type (getEntityGroupsByOwnerAndType) # noqa: E501
Fetch the list of Entity Group Info objects based on the provided Owner Id and Entity Type. Entity group allows you to group multiple entities of the same entity type (Device, Asset, Customer, User, Dashboard, etc). Entity Group always have an owner - particular Tenant or Customer. Each entity may belong to multiple groups simultaneously.Entity Group Info extends Entity Group object and adds 'ownerIds' - a list of owner ids. Available for users with 'TENANT_ADMIN' or 'CUSTOMER_USER' authority. Security check is performed to verify that the user has 'READ' permission for specified group. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_entity_groups_by_owner_and_type_using_get_with_http_info(owner_type, owner_id, group_type, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str owner_type: Tenant or Customer (required)
:param str owner_id: A string value representing the Tenant or Customer id (required)
:param str group_type: Entity Group type (required)
:return: list[EntityGroupInfo]
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['owner_type', 'owner_id', 'group_type'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_entity_groups_by_owner_and_type_using_get" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'owner_type' is set
if ('owner_type' not in params or
params['owner_type'] is None):
raise ValueError("Missing the required parameter `owner_type` when calling `get_entity_groups_by_owner_and_type_using_get`") # noqa: E501
# verify the required parameter 'owner_id' is set
if ('owner_id' not in params or
params['owner_id'] is None):
raise ValueError("Missing the required parameter `owner_id` when calling `get_entity_groups_by_owner_and_type_using_get`") # noqa: E501
# verify the required parameter 'group_type' is set
if ('group_type' not in params or
params['group_type'] is None):
raise ValueError("Missing the required parameter `group_type` when calling `get_entity_groups_by_owner_and_type_using_get`") # noqa: E501
collection_formats = {}
path_params = {}
if 'owner_type' in params:
path_params['ownerType'] = params['owner_type'] # noqa: E501
if 'owner_id' in params:
path_params['ownerId'] = params['owner_id'] # noqa: E501
if 'group_type' in params:
path_params['groupType'] = params['group_type'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['X-Authorization'] # noqa: E501
return self.api_client.call_api(
'/api/entityGroups/{ownerType}/{ownerId}/{groupType}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='list[EntityGroupInfo]', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_entity_groups_by_type_using_get(self, group_type, **kwargs): # noqa: E501
"""Get Entity Groups by entity type (getEntityGroupsByType) # noqa: E501
Fetch the list of Entity Group Info objects based on the provided Entity Type. Entity group allows you to group multiple entities of the same entity type (Device, Asset, Customer, User, Dashboard, etc). Entity Group always have an owner - particular Tenant or Customer. Each entity may belong to multiple groups simultaneously.Entity Group Info extends Entity Group object and adds 'ownerIds' - a list of owner ids. Available for users with 'TENANT_ADMIN' or 'CUSTOMER_USER' authority. Security check is performed to verify that the user has 'READ' permission for specified group. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_entity_groups_by_type_using_get(group_type, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str group_type: Entity Group type (required)
:return: list[EntityGroupInfo]
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.get_entity_groups_by_type_using_get_with_http_info(group_type, **kwargs) # noqa: E501
else:
(data) = self.get_entity_groups_by_type_using_get_with_http_info(group_type, **kwargs) # noqa: E501
return data
def get_entity_groups_by_type_using_get_with_http_info(self, group_type, **kwargs): # noqa: E501
"""Get Entity Groups by entity type (getEntityGroupsByType) # noqa: E501
Fetch the list of Entity Group Info objects based on the provided Entity Type. Entity group allows you to group multiple entities of the same entity type (Device, Asset, Customer, User, Dashboard, etc). Entity Group always have an owner - particular Tenant or Customer. Each entity may belong to multiple groups simultaneously.Entity Group Info extends Entity Group object and adds 'ownerIds' - a list of owner ids. Available for users with 'TENANT_ADMIN' or 'CUSTOMER_USER' authority. Security check is performed to verify that the user has 'READ' permission for specified group. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_entity_groups_by_type_using_get_with_http_info(group_type, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str group_type: Entity Group type (required)
:return: list[EntityGroupInfo]
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['group_type'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_entity_groups_by_type_using_get" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'group_type' is set
if ('group_type' not in params or
params['group_type'] is None):
raise ValueError("Missing the required parameter `group_type` when calling `get_entity_groups_by_type_using_get`") # noqa: E501
collection_formats = {}
path_params = {}
if 'group_type' in params:
path_params['groupType'] = params['group_type'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['X-Authorization'] # noqa: E501
return self.api_client.call_api(
'/api/entityGroups/{groupType}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='list[EntityGroupInfo]', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_entity_groups_for_entity_using_get(self, entity_type, entity_id, **kwargs): # noqa: E501
"""Get Entity Groups by Entity Id (getEntityGroupsForEntity) # noqa: E501
Returns a list of groups that contain the specified Entity Id. For example, all device groups that contain specific device. The list always contain at least one element - special group 'All'.You can specify parameters to filter the results. The result is wrapped with PageData object that allows you to iterate over result set using pagination. See the 'Model' tab of the Response Class for more details. Available for users with 'TENANT_ADMIN' or 'CUSTOMER_USER' authority. Security check is performed to verify that the user has 'READ' permission for the entity (entities). # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_entity_groups_for_entity_using_get(entity_type, entity_id, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str entity_type: Entity Group type (required)
:param str entity_id: A string value representing the entity id. For example, '784f394c-42b6-435a-983c-b7beff2784f9' (required)
:return: list[EntityGroupId]
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.get_entity_groups_for_entity_using_get_with_http_info(entity_type, entity_id, **kwargs) # noqa: E501
else:
(data) = self.get_entity_groups_for_entity_using_get_with_http_info(entity_type, entity_id, **kwargs) # noqa: E501
return data
def get_entity_groups_for_entity_using_get_with_http_info(self, entity_type, entity_id, **kwargs): # noqa: E501
"""Get Entity Groups by Entity Id (getEntityGroupsForEntity) # noqa: E501
Returns a list of groups that contain the specified Entity Id. For example, all device groups that contain specific device. The list always contain at least one element - special group 'All'.You can specify parameters to filter the results. The result is wrapped with PageData object that allows you to iterate over result set using pagination. See the 'Model' tab of the Response Class for more details. Available for users with 'TENANT_ADMIN' or 'CUSTOMER_USER' authority. Security check is performed to verify that the user has 'READ' permission for the entity (entities). # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_entity_groups_for_entity_using_get_with_http_info(entity_type, entity_id, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str entity_type: Entity Group type (required)
:param str entity_id: A string value representing the entity id. For example, '784f394c-42b6-435a-983c-b7beff2784f9' (required)
:return: list[EntityGroupId]
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['entity_type', 'entity_id'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_entity_groups_for_entity_using_get" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'entity_type' is set
if ('entity_type' not in params or
params['entity_type'] is None):
raise ValueError("Missing the required parameter `entity_type` when calling `get_entity_groups_for_entity_using_get`") # noqa: E501
# verify the required parameter 'entity_id' is set
if ('entity_id' not in params or
params['entity_id'] is None):
raise ValueError("Missing the required parameter `entity_id` when calling `get_entity_groups_for_entity_using_get`") # noqa: E501
collection_formats = {}
path_params = {}
if 'entity_type' in params:
path_params['entityType'] = params['entity_type'] # noqa: E501
if 'entity_id' in params:
path_params['entityId'] = params['entity_id'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['X-Authorization'] # noqa: E501
return self.api_client.call_api(
'/api/entityGroups/{entityType}/{entityId}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='list[EntityGroupId]', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_group_entity_using_get(self, entity_group_id, entity_id, **kwargs): # noqa: E501
"""Get Group Entity (getGroupEntity) # noqa: E501
Fetch the Short Entity View object based on the group and entity id. Short Entity View object contains the entity id and number of fields (attributes, telemetry, etc). List of those fields is configurable and defined in the group configuration. Available for users with 'TENANT_ADMIN' or 'CUSTOMER_USER' authority. Security check is performed to verify that the user has 'READ' permission for specified group. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_group_entity_using_get(entity_group_id, entity_id, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str entity_group_id: A string value representing the Entity Group Id. For example, '784f394c-42b6-435a-983c-b7beff2784f9' (required)
:param str entity_id: A string value representing the entity id. For example, '784f394c-42b6-435a-983c-b7beff2784f9' (required)
:return: ShortEntityView
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.get_group_entity_using_get_with_http_info(entity_group_id, entity_id, **kwargs) # noqa: E501
else:
(data) = self.get_group_entity_using_get_with_http_info(entity_group_id, entity_id, **kwargs) # noqa: E501
return data
def get_group_entity_using_get_with_http_info(self, entity_group_id, entity_id, **kwargs): # noqa: E501
"""Get Group Entity (getGroupEntity) # noqa: E501
Fetch the Short Entity View object based on the group and entity id. Short Entity View object contains the entity id and number of fields (attributes, telemetry, etc). List of those fields is configurable and defined in the group configuration. Available for users with 'TENANT_ADMIN' or 'CUSTOMER_USER' authority. Security check is performed to verify that the user has 'READ' permission for specified group. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_group_entity_using_get_with_http_info(entity_group_id, entity_id, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str entity_group_id: A string value representing the Entity Group Id. For example, '784f394c-42b6-435a-983c-b7beff2784f9' (required)
:param str entity_id: A string value representing the entity id. For example, '784f394c-42b6-435a-983c-b7beff2784f9' (required)
:return: ShortEntityView
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['entity_group_id', 'entity_id'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_group_entity_using_get" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'entity_group_id' is set
if ('entity_group_id' not in params or
params['entity_group_id'] is None):
raise ValueError("Missing the required parameter `entity_group_id` when calling `get_group_entity_using_get`") # noqa: E501
# verify the required parameter 'entity_id' is set
if ('entity_id' not in params or
params['entity_id'] is None):
raise ValueError("Missing the required parameter `entity_id` when calling `get_group_entity_using_get`") # noqa: E501
collection_formats = {}
path_params = {}
if 'entity_group_id' in params:
path_params['entityGroupId'] = params['entity_group_id'] # noqa: E501
if 'entity_id' in params:
path_params['entityId'] = params['entity_id'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['X-Authorization'] # noqa: E501
return self.api_client.call_api(
'/api/entityGroup/{entityGroupId}/{entityId}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='ShortEntityView', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_owners_using_get(self, page_size, page, **kwargs): # noqa: E501
"""Get Owners (getOwners) # noqa: E501
Provides a rage view of Customers that the current user has READ access to. If the current user is Tenant administrator, the result set also contains the tenant. The call is designed for the UI auto-complete component to show tenant and all possible Customers that the user may select to change the owner of the particular entity or entity group. Available for users with 'TENANT_ADMIN' or 'CUSTOMER_USER' authority. Security check is performed to verify that the user has 'READ' permission for the entity (entities). # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_owners_using_get(page_size, page, async_req=True)
>>> result = thread.get()
:param async_req bool
:param int page_size: Maximum amount of entities in a one page (required)
:param int page: Sequence number of page starting from 0 (required)
:param str text_search: The case insensitive 'startsWith' filter based on the entity group name.
:param str sort_property: Property of entity to sort by
:param str sort_order: Sort order. ASC (ASCENDING) or DESC (DESCENDING)
:return: PageDataContactBasedobject
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.get_owners_using_get_with_http_info(page_size, page, **kwargs) # noqa: E501
else:
(data) = self.get_owners_using_get_with_http_info(page_size, page, **kwargs) # noqa: E501
return data
def get_owners_using_get_with_http_info(self, page_size, page, **kwargs): # noqa: E501
"""Get Owners (getOwners) # noqa: E501
Provides a rage view of Customers that the current user has READ access to. If the current user is Tenant administrator, the result set also contains the tenant. The call is designed for the UI auto-complete component to show tenant and all possible Customers that the user may select to change the owner of the particular entity or entity group. Available for users with 'TENANT_ADMIN' or 'CUSTOMER_USER' authority. Security check is performed to verify that the user has 'READ' permission for the entity (entities). # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_owners_using_get_with_http_info(page_size, page, async_req=True)
>>> result = thread.get()
:param async_req bool
:param int page_size: Maximum amount of entities in a one page (required)
:param int page: Sequence number of page starting from 0 (required)
:param str text_search: The case insensitive 'startsWith' filter based on the entity group name.
:param str sort_property: Property of entity to sort by
:param str sort_order: Sort order. ASC (ASCENDING) or DESC (DESCENDING)
:return: PageDataContactBasedobject
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['page_size', 'page', 'text_search', 'sort_property', 'sort_order'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_owners_using_get" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'page_size' is set
if ('page_size' not in params or
params['page_size'] is None):
raise ValueError("Missing the required parameter `page_size` when calling `get_owners_using_get`") # noqa: E501
# verify the required parameter 'page' is set
if ('page' not in params or
params['page'] is None):
raise ValueError("Missing the required parameter `page` when calling `get_owners_using_get`") # noqa: E501
collection_formats = {}
path_params = {}
query_params = []
if 'page_size' in params:
query_params.append(('pageSize', params['page_size'])) # noqa: E501
if 'page' in params:
query_params.append(('page', params['page'])) # noqa: E501
if 'text_search' in params:
query_params.append(('textSearch', params['text_search'])) # noqa: E501
if 'sort_property' in params:
query_params.append(('sortProperty', params['sort_property'])) # noqa: E501
if 'sort_order' in params:
query_params.append(('sortOrder', params['sort_order'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['X-Authorization'] # noqa: E501
return self.api_client.call_api(
'/api/owners{?page,pageSize,sortOrder,sortProperty,textSearch}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='PageDataContactBasedobject', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def make_entity_group_private_using_post(self, entity_group_id, **kwargs): # noqa: E501
"""Make Entity Group Private (makeEntityGroupPrivate) # noqa: E501
Make the entity group not available for non authorized users. Every group is private by default. This call is useful to hide the group that was previously made public. Available for users with 'TENANT_ADMIN' or 'CUSTOMER_USER' authority. Security check is performed to verify that the user has 'WRITE' permission for specified group. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.make_entity_group_private_using_post(entity_group_id, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str entity_group_id: A string value representing the Entity Group Id. For example, '784f394c-42b6-435a-983c-b7beff2784f9' (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.make_entity_group_private_using_post_with_http_info(entity_group_id, **kwargs) # noqa: E501
else:
(data) = self.make_entity_group_private_using_post_with_http_info(entity_group_id, **kwargs) # noqa: E501
return data
def make_entity_group_private_using_post_with_http_info(self, entity_group_id, **kwargs): # noqa: E501
"""Make Entity Group Private (makeEntityGroupPrivate) # noqa: E501
Make the entity group not available for non authorized users. Every group is private by default. This call is useful to hide the group that was previously made public. Available for users with 'TENANT_ADMIN' or 'CUSTOMER_USER' authority. Security check is performed to verify that the user has 'WRITE' permission for specified group. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.make_entity_group_private_using_post_with_http_info(entity_group_id, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str entity_group_id: A string value representing the Entity Group Id. For example, '784f394c-42b6-435a-983c-b7beff2784f9' (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['entity_group_id'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method make_entity_group_private_using_post" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'entity_group_id' is set
if ('entity_group_id' not in params or
params['entity_group_id'] is None):
raise ValueError("Missing the required parameter `entity_group_id` when calling `make_entity_group_private_using_post`") # noqa: E501
collection_formats = {}
path_params = {}
if 'entity_group_id' in params:
path_params['entityGroupId'] = params['entity_group_id'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['X-Authorization'] # noqa: E501
return self.api_client.call_api(
'/api/entityGroup/{entityGroupId}/makePrivate', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def make_entity_group_public_using_post(self, entity_group_id, **kwargs): # noqa: E501
"""Make Entity Group Publicly available (makeEntityGroupPublic) # noqa: E501
Make the entity group available for non authorized users. Useful for public dashboards that will be embedded into the public websites. Available for users with 'TENANT_ADMIN' or 'CUSTOMER_USER' authority. Security check is performed to verify that the user has 'WRITE' permission for specified group. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.make_entity_group_public_using_post(entity_group_id, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str entity_group_id: A string value representing the Entity Group Id. For example, '784f394c-42b6-435a-983c-b7beff2784f9' (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.make_entity_group_public_using_post_with_http_info(entity_group_id, **kwargs) # noqa: E501
else:
(data) = self.make_entity_group_public_using_post_with_http_info(entity_group_id, **kwargs) # noqa: E501
return data
def make_entity_group_public_using_post_with_http_info(self, entity_group_id, **kwargs): # noqa: E501
"""Make Entity Group Publicly available (makeEntityGroupPublic) # noqa: E501
Make the entity group available for non authorized users. Useful for public dashboards that will be embedded into the public websites. Available for users with 'TENANT_ADMIN' or 'CUSTOMER_USER' authority. Security check is performed to verify that the user has 'WRITE' permission for specified group. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.make_entity_group_public_using_post_with_http_info(entity_group_id, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str entity_group_id: A string value representing the Entity Group Id. For example, '784f394c-42b6-435a-983c-b7beff2784f9' (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['entity_group_id'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method make_entity_group_public_using_post" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'entity_group_id' is set
if ('entity_group_id' not in params or
params['entity_group_id'] is None):
raise ValueError("Missing the required parameter `entity_group_id` when calling `make_entity_group_public_using_post`") # noqa: E501
collection_formats = {}
path_params = {}
if 'entity_group_id' in params:
path_params['entityGroupId'] = params['entity_group_id'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['X-Authorization'] # noqa: E501
return self.api_client.call_api(
'/api/entityGroup/{entityGroupId}/makePublic', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def remove_entities_from_entity_group_using_post(self, entity_group_id, **kwargs): # noqa: E501
"""Remove entities from the group (removeEntitiesFromEntityGroup) # noqa: E501
Removes entities from the specified entity group. Entity group allows you to group multiple entities of the same entity type (Device, Asset, Customer, User, Dashboard, etc). Entity Group always have an owner - particular Tenant or Customer. Each entity may belong to multiple groups simultaneously. Available for users with 'TENANT_ADMIN' or 'CUSTOMER_USER' authority. Security check is performed to verify that the user has 'REMOVE_FROM_GROUP' permission for specified group. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.remove_entities_from_entity_group_using_post(entity_group_id, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str entity_group_id: A string value representing the Entity Group Id. For example, '784f394c-42b6-435a-983c-b7beff2784f9' (required)
:param list[str] body:
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.remove_entities_from_entity_group_using_post_with_http_info(entity_group_id, **kwargs) # noqa: E501
else:
(data) = self.remove_entities_from_entity_group_using_post_with_http_info(entity_group_id, **kwargs) # noqa: E501
return data
def remove_entities_from_entity_group_using_post_with_http_info(self, entity_group_id, **kwargs): # noqa: E501
"""Remove entities from the group (removeEntitiesFromEntityGroup) # noqa: E501
Removes entities from the specified entity group. Entity group allows you to group multiple entities of the same entity type (Device, Asset, Customer, User, Dashboard, etc). Entity Group always have an owner - particular Tenant or Customer. Each entity may belong to multiple groups simultaneously. Available for users with 'TENANT_ADMIN' or 'CUSTOMER_USER' authority. Security check is performed to verify that the user has 'REMOVE_FROM_GROUP' permission for specified group. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.remove_entities_from_entity_group_using_post_with_http_info(entity_group_id, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str entity_group_id: A string value representing the Entity Group Id. For example, '784f394c-42b6-435a-983c-b7beff2784f9' (required)
:param list[str] body:
:return: None
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['entity_group_id', 'body'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method remove_entities_from_entity_group_using_post" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'entity_group_id' is set
if ('entity_group_id' not in params or
params['entity_group_id'] is None):
raise ValueError("Missing the required parameter `entity_group_id` when calling `remove_entities_from_entity_group_using_post`") # noqa: E501
collection_formats = {}
path_params = {}
if 'entity_group_id' in params:
path_params['entityGroupId'] = params['entity_group_id'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['X-Authorization'] # noqa: E501
return self.api_client.call_api(
'/api/entityGroup/{entityGroupId}/deleteEntities', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def save_entity_group_using_post(self, **kwargs): # noqa: E501
"""Create Or Update Entity Group (saveEntityGroup) # noqa: E501
Create or update the Entity Group. When creating Entity Group, platform generates Entity Group Id as [time-based UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_1_(date-time_and_MAC_address)). The newly created Entity Group Id will be present in the response. Specify existing Entity Group Id to update the group. Referencing non-existing Entity Group Id will cause 'Not Found' error. Entity group name is unique in the scope of owner and entity type. For example, you can't create two tenant device groups called 'Water meters'. However, you may create device and asset group with the same name. And also you may create groups with the same name for two different customers of the same tenant. Available for users with 'TENANT_ADMIN' or 'CUSTOMER_USER' authority. Security check is performed to verify that the user has 'WRITE' permission for specified group. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.save_entity_group_using_post(async_req=True)
>>> result = thread.get()
:param async_req bool
:param EntityGroup body:
:return: EntityGroupInfo
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.save_entity_group_using_post_with_http_info(**kwargs) # noqa: E501
else:
(data) = self.save_entity_group_using_post_with_http_info(**kwargs) # noqa: E501
return data
def save_entity_group_using_post_with_http_info(self, **kwargs): # noqa: E501
"""Create Or Update Entity Group (saveEntityGroup) # noqa: E501
Create or update the Entity Group. When creating Entity Group, platform generates Entity Group Id as [time-based UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_1_(date-time_and_MAC_address)). The newly created Entity Group Id will be present in the response. Specify existing Entity Group Id to update the group. Referencing non-existing Entity Group Id will cause 'Not Found' error. Entity group name is unique in the scope of owner and entity type. For example, you can't create two tenant device groups called 'Water meters'. However, you may create device and asset group with the same name. And also you may create groups with the same name for two different customers of the same tenant. Available for users with 'TENANT_ADMIN' or 'CUSTOMER_USER' authority. Security check is performed to verify that the user has 'WRITE' permission for specified group. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.save_entity_group_using_post_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool
:param EntityGroup body:
:return: EntityGroupInfo
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method save_entity_group_using_post" % key
)
params[key] = val
del params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['X-Authorization'] # noqa: E501
return self.api_client.call_api(
'/api/entityGroup', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='EntityGroupInfo', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def share_entity_group_to_child_owner_user_group_using_post(self, entity_group_id, user_group_id, role_id, **kwargs): # noqa: E501
"""Share the Entity Group with User group (shareEntityGroupToChildOwnerUserGroup) # noqa: E501
Share the entity group with specified user group using specified role. Available for users with 'TENANT_ADMIN' or 'CUSTOMER_USER' authority. Security check is performed to verify that the user has 'WRITE' permission for specified group. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.share_entity_group_to_child_owner_user_group_using_post(entity_group_id, user_group_id, role_id, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str entity_group_id: A string value representing the Entity Group Id that you would like to share. For example, '784f394c-42b6-435a-983c-b7beff2784f9' (required)
:param str user_group_id: A string value representing the Entity(User) Group Id that you would like to share with. For example, '784f394c-42b6-435a-983c-b7beff2784f9' (required)
:param str role_id: A string value representing the Role Id that describes set of permissions you would like to share (read, write, etc). For example, '784f394c-42b6-435a-983c-b7beff2784f9' (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.share_entity_group_to_child_owner_user_group_using_post_with_http_info(entity_group_id, user_group_id, role_id, **kwargs) # noqa: E501
else:
(data) = self.share_entity_group_to_child_owner_user_group_using_post_with_http_info(entity_group_id, user_group_id, role_id, **kwargs) # noqa: E501
return data
def share_entity_group_to_child_owner_user_group_using_post_with_http_info(self, entity_group_id, user_group_id, role_id, **kwargs): # noqa: E501
"""Share the Entity Group with User group (shareEntityGroupToChildOwnerUserGroup) # noqa: E501
Share the entity group with specified user group using specified role. Available for users with 'TENANT_ADMIN' or 'CUSTOMER_USER' authority. Security check is performed to verify that the user has 'WRITE' permission for specified group. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.share_entity_group_to_child_owner_user_group_using_post_with_http_info(entity_group_id, user_group_id, role_id, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str entity_group_id: A string value representing the Entity Group Id that you would like to share. For example, '784f394c-42b6-435a-983c-b7beff2784f9' (required)
:param str user_group_id: A string value representing the Entity(User) Group Id that you would like to share with. For example, '784f394c-42b6-435a-983c-b7beff2784f9' (required)
:param str role_id: A string value representing the Role Id that describes set of permissions you would like to share (read, write, etc). For example, '784f394c-42b6-435a-983c-b7beff2784f9' (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['entity_group_id', 'user_group_id', 'role_id'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method share_entity_group_to_child_owner_user_group_using_post" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'entity_group_id' is set
if ('entity_group_id' not in params or
params['entity_group_id'] is None):
raise ValueError("Missing the required parameter `entity_group_id` when calling `share_entity_group_to_child_owner_user_group_using_post`") # noqa: E501
# verify the required parameter 'user_group_id' is set
if ('user_group_id' not in params or
params['user_group_id'] is None):
raise ValueError("Missing the required parameter `user_group_id` when calling `share_entity_group_to_child_owner_user_group_using_post`") # noqa: E501
# verify the required parameter 'role_id' is set
if ('role_id' not in params or
params['role_id'] is None):
raise ValueError("Missing the required parameter `role_id` when calling `share_entity_group_to_child_owner_user_group_using_post`") # noqa: E501
collection_formats = {}
path_params = {}
if 'entity_group_id' in params:
path_params['entityGroupId'] = params['entity_group_id'] # noqa: E501
if 'user_group_id' in params:
path_params['userGroupId'] = params['user_group_id'] # noqa: E501
if 'role_id' in params:
path_params['roleId'] = params['role_id'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['X-Authorization'] # noqa: E501
return self.api_client.call_api(
'/api/entityGroup/{entityGroupId}/{userGroupId}/{roleId}/share', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def share_entity_group_using_post(self, entity_group_id, **kwargs): # noqa: E501
"""Share the Entity Group (shareEntityGroup) # noqa: E501
Share the entity group with certain user group based on the provided Share Group Request. The request is quite flexible and processing of the request involves multiple security checks using platform RBAC feature. Available for users with 'TENANT_ADMIN' or 'CUSTOMER_USER' authority. Security check is performed to verify that the user has 'WRITE' permission for specified group. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.share_entity_group_using_post(entity_group_id, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str entity_group_id: A string value representing the Entity Group Id. For example, '784f394c-42b6-435a-983c-b7beff2784f9' (required)
:param ShareGroupRequest body:
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.share_entity_group_using_post_with_http_info(entity_group_id, **kwargs) # noqa: E501
else:
(data) = self.share_entity_group_using_post_with_http_info(entity_group_id, **kwargs) # noqa: E501
return data
def share_entity_group_using_post_with_http_info(self, entity_group_id, **kwargs): # noqa: E501
"""Share the Entity Group (shareEntityGroup) # noqa: E501
Share the entity group with certain user group based on the provided Share Group Request. The request is quite flexible and processing of the request involves multiple security checks using platform RBAC feature. Available for users with 'TENANT_ADMIN' or 'CUSTOMER_USER' authority. Security check is performed to verify that the user has 'WRITE' permission for specified group. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.share_entity_group_using_post_with_http_info(entity_group_id, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str entity_group_id: A string value representing the Entity Group Id. For example, '784f394c-42b6-435a-983c-b7beff2784f9' (required)
:param ShareGroupRequest body:
:return: None
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['entity_group_id', 'body'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method share_entity_group_using_post" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'entity_group_id' is set
if ('entity_group_id' not in params or
params['entity_group_id'] is None):
raise ValueError("Missing the required parameter `entity_group_id` when calling `share_entity_group_using_post`") # noqa: E501
collection_formats = {}
path_params = {}
if 'entity_group_id' in params:
path_params['entityGroupId'] = params['entity_group_id'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['X-Authorization'] # noqa: E501
return self.api_client.call_api(
'/api/entityGroup/{entityGroupId}/share', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def unassign_entity_group_from_edge_using_delete(self, edge_id, group_type, entity_group_id, **kwargs): # noqa: E501
"""Unassign entity group from edge (unassignEntityGroupFromEdge) # noqa: E501
Clears assignment of the entity group to the edge. Unassignment works in async way - first, 'unassign' notification event pushed to edge queue on platform. Second, remote edge service will receive an 'unassign' command to remove entity group (Edge will receive this instantly, if it's currently connected, or once it's going to be connected to platform). Third, once 'unassign' command will be delivered to edge service, it's going to remove entity group and entities inside this group locally. Available for users with 'TENANT_ADMIN' or 'CUSTOMER_USER' authority. Security check is performed to verify that the user has 'WRITE' permission for the entity (entities). # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.unassign_entity_group_from_edge_using_delete(edge_id, group_type, entity_group_id, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str edge_id: A string value representing the edge id. For example, '784f394c-42b6-435a-983c-b7beff2784f9' (required)
:param str group_type: EntityGroup type (required)
:param str entity_group_id: A string value representing the Entity Group Id. For example, '784f394c-42b6-435a-983c-b7beff2784f9' (required)
:return: EntityGroup
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.unassign_entity_group_from_edge_using_delete_with_http_info(edge_id, group_type, entity_group_id, **kwargs) # noqa: E501
else:
(data) = self.unassign_entity_group_from_edge_using_delete_with_http_info(edge_id, group_type, entity_group_id, **kwargs) # noqa: E501
return data
def unassign_entity_group_from_edge_using_delete_with_http_info(self, edge_id, group_type, entity_group_id, **kwargs): # noqa: E501
"""Unassign entity group from edge (unassignEntityGroupFromEdge) # noqa: E501
Clears assignment of the entity group to the edge. Unassignment works in async way - first, 'unassign' notification event pushed to edge queue on platform. Second, remote edge service will receive an 'unassign' command to remove entity group (Edge will receive this instantly, if it's currently connected, or once it's going to be connected to platform). Third, once 'unassign' command will be delivered to edge service, it's going to remove entity group and entities inside this group locally. Available for users with 'TENANT_ADMIN' or 'CUSTOMER_USER' authority. Security check is performed to verify that the user has 'WRITE' permission for the entity (entities). # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.unassign_entity_group_from_edge_using_delete_with_http_info(edge_id, group_type, entity_group_id, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str edge_id: A string value representing the edge id. For example, '784f394c-42b6-435a-983c-b7beff2784f9' (required)
:param str group_type: EntityGroup type (required)
:param str entity_group_id: A string value representing the Entity Group Id. For example, '784f394c-42b6-435a-983c-b7beff2784f9' (required)
:return: EntityGroup
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['edge_id', 'group_type', 'entity_group_id'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method unassign_entity_group_from_edge_using_delete" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'edge_id' is set
if ('edge_id' not in params or
params['edge_id'] is None):
raise ValueError("Missing the required parameter `edge_id` when calling `unassign_entity_group_from_edge_using_delete`") # noqa: E501
# verify the required parameter 'group_type' is set
if ('group_type' not in params or
params['group_type'] is None):
raise ValueError("Missing the required parameter `group_type` when calling `unassign_entity_group_from_edge_using_delete`") # noqa: E501
# verify the required parameter 'entity_group_id' is set
if ('entity_group_id' not in params or
params['entity_group_id'] is None):
raise ValueError("Missing the required parameter `entity_group_id` when calling `unassign_entity_group_from_edge_using_delete`") # noqa: E501
collection_formats = {}
path_params = {}
if 'edge_id' in params:
path_params['edgeId'] = params['edge_id'] # noqa: E501
if 'group_type' in params:
path_params['groupType'] = params['group_type'] # noqa: E501
if 'entity_group_id' in params:
path_params['entityGroupId'] = params['entity_group_id'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['X-Authorization'] # noqa: E501
return self.api_client.call_api(
'/api/edge/{edgeId}/entityGroup/{entityGroupId}/{groupType}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='EntityGroup', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
| 56.113752 | 911 | 0.670978 |
from __future__ import absolute_import
import re
import six
from tb_rest_client.api_client import ApiClient
class EntityGroupControllerApi(object):
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
def add_entities_to_entity_group_using_post(self, entity_group_id, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.add_entities_to_entity_group_using_post_with_http_info(entity_group_id, **kwargs)
else:
(data) = self.add_entities_to_entity_group_using_post_with_http_info(entity_group_id, **kwargs)
return data
def add_entities_to_entity_group_using_post_with_http_info(self, entity_group_id, **kwargs):
all_params = ['entity_group_id', 'body']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method add_entities_to_entity_group_using_post" % key
)
params[key] = val
del params['kwargs']
if ('entity_group_id' not in params or
params['entity_group_id'] is None):
raise ValueError("Missing the required parameter `entity_group_id` when calling `add_entities_to_entity_group_using_post`")
collection_formats = {}
path_params = {}
if 'entity_group_id' in params:
path_params['entityGroupId'] = params['entity_group_id']
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
header_params['Accept'] = self.api_client.select_header_accept(
['application/json'])
header_params['Content-Type'] = self.api_client.select_header_content_type(
['application/json'])
auth_settings = ['X-Authorization']
return self.api_client.call_api(
'/api/entityGroup/{entityGroupId}/addEntities', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None,
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def assign_entity_group_to_edge_using_post(self, edge_id, group_type, entity_group_id, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.assign_entity_group_to_edge_using_post_with_http_info(edge_id, group_type, entity_group_id, **kwargs)
else:
(data) = self.assign_entity_group_to_edge_using_post_with_http_info(edge_id, group_type, entity_group_id, **kwargs)
return data
def assign_entity_group_to_edge_using_post_with_http_info(self, edge_id, group_type, entity_group_id, **kwargs):
all_params = ['edge_id', 'group_type', 'entity_group_id']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method assign_entity_group_to_edge_using_post" % key
)
params[key] = val
del params['kwargs']
if ('edge_id' not in params or
params['edge_id'] is None):
raise ValueError("Missing the required parameter `edge_id` when calling `assign_entity_group_to_edge_using_post`")
if ('group_type' not in params or
params['group_type'] is None):
raise ValueError("Missing the required parameter `group_type` when calling `assign_entity_group_to_edge_using_post`")
if ('entity_group_id' not in params or
params['entity_group_id'] is None):
raise ValueError("Missing the required parameter `entity_group_id` when calling `assign_entity_group_to_edge_using_post`")
collection_formats = {}
path_params = {}
if 'edge_id' in params:
path_params['edgeId'] = params['edge_id']
if 'group_type' in params:
path_params['groupType'] = params['group_type']
if 'entity_group_id' in params:
path_params['entityGroupId'] = params['entity_group_id']
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.select_header_accept(
['application/json'])
auth_settings = ['X-Authorization']
return self.api_client.call_api(
'/api/edge/{edgeId}/entityGroup/{entityGroupId}/{groupType}', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='EntityGroup',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_entity_group_using_delete(self, entity_group_id, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.delete_entity_group_using_delete_with_http_info(entity_group_id, **kwargs)
else:
(data) = self.delete_entity_group_using_delete_with_http_info(entity_group_id, **kwargs)
return data
def delete_entity_group_using_delete_with_http_info(self, entity_group_id, **kwargs):
all_params = ['entity_group_id']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_entity_group_using_delete" % key
)
params[key] = val
del params['kwargs']
if ('entity_group_id' not in params or
params['entity_group_id'] is None):
raise ValueError("Missing the required parameter `entity_group_id` when calling `delete_entity_group_using_delete`")
collection_formats = {}
path_params = {}
if 'entity_group_id' in params:
path_params['entityGroupId'] = params['entity_group_id']
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.select_header_accept(
['application/json'])
auth_settings = ['X-Authorization']
return self.api_client.call_api(
'/api/entityGroup/{entityGroupId}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None,
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_all_edge_entity_groups_using_get(self, edge_id, group_type, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.get_all_edge_entity_groups_using_get_with_http_info(edge_id, group_type, **kwargs)
else:
(data) = self.get_all_edge_entity_groups_using_get_with_http_info(edge_id, group_type, **kwargs)
return data
def get_all_edge_entity_groups_using_get_with_http_info(self, edge_id, group_type, **kwargs):
all_params = ['edge_id', 'group_type']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_all_edge_entity_groups_using_get" % key
)
params[key] = val
del params['kwargs']
if ('edge_id' not in params or
params['edge_id'] is None):
raise ValueError("Missing the required parameter `edge_id` when calling `get_all_edge_entity_groups_using_get`")
if ('group_type' not in params or
params['group_type'] is None):
raise ValueError("Missing the required parameter `group_type` when calling `get_all_edge_entity_groups_using_get`")
collection_formats = {}
path_params = {}
if 'edge_id' in params:
path_params['edgeId'] = params['edge_id']
if 'group_type' in params:
path_params['groupType'] = params['group_type']
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.select_header_accept(
['application/json'])
auth_settings = ['X-Authorization']
return self.api_client.call_api(
'/api/allEntityGroups/edge/{edgeId}/{groupType}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='list[EntityGroupInfo]',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_edge_entity_groups_using_get(self, edge_id, group_type, page_size, page, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.get_edge_entity_groups_using_get_with_http_info(edge_id, group_type, page_size, page, **kwargs)
else:
(data) = self.get_edge_entity_groups_using_get_with_http_info(edge_id, group_type, page_size, page, **kwargs)
return data
def get_edge_entity_groups_using_get_with_http_info(self, edge_id, group_type, page_size, page, **kwargs):
all_params = ['edge_id', 'group_type', 'page_size', 'page', 'sort_property', 'sort_order']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_edge_entity_groups_using_get" % key
)
params[key] = val
del params['kwargs']
if ('edge_id' not in params or
params['edge_id'] is None):
raise ValueError("Missing the required parameter `edge_id` when calling `get_edge_entity_groups_using_get`")
if ('group_type' not in params or
params['group_type'] is None):
raise ValueError("Missing the required parameter `group_type` when calling `get_edge_entity_groups_using_get`")
if ('page_size' not in params or
params['page_size'] is None):
raise ValueError("Missing the required parameter `page_size` when calling `get_edge_entity_groups_using_get`")
if ('page' not in params or
params['page'] is None):
raise ValueError("Missing the required parameter `page` when calling `get_edge_entity_groups_using_get`")
collection_formats = {}
path_params = {}
if 'edge_id' in params:
path_params['edgeId'] = params['edge_id']
if 'group_type' in params:
path_params['groupType'] = params['group_type']
query_params = []
if 'page_size' in params:
query_params.append(('pageSize', params['page_size']))
if 'page' in params:
query_params.append(('page', params['page']))
if 'sort_property' in params:
query_params.append(('sortProperty', params['sort_property']))
if 'sort_order' in params:
query_params.append(('sortOrder', params['sort_order']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.select_header_accept(
['application/json'])
auth_settings = ['X-Authorization']
return self.api_client.call_api(
'/api/entityGroups/edge/{edgeId}/{groupType}{?page,pageSize,sortOrder,sortProperty}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='PageDataEntityGroupInfo',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_entities_using_get(self, entity_group_id, page_size, page, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.get_entities_using_get_with_http_info(entity_group_id, page_size, page, **kwargs)
else:
(data) = self.get_entities_using_get_with_http_info(entity_group_id, page_size, page, **kwargs)
return data
def get_entities_using_get_with_http_info(self, entity_group_id, page_size, page, **kwargs):
all_params = ['entity_group_id', 'page_size', 'page', 'text_search', 'sort_property', 'sort_order']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_entities_using_get" % key
)
params[key] = val
del params['kwargs']
if ('entity_group_id' not in params or
params['entity_group_id'] is None):
raise ValueError("Missing the required parameter `entity_group_id` when calling `get_entities_using_get`")
if ('page_size' not in params or
params['page_size'] is None):
raise ValueError("Missing the required parameter `page_size` when calling `get_entities_using_get`")
if ('page' not in params or
params['page'] is None):
raise ValueError("Missing the required parameter `page` when calling `get_entities_using_get`")
collection_formats = {}
path_params = {}
if 'entity_group_id' in params:
path_params['entityGroupId'] = params['entity_group_id']
query_params = []
if 'page_size' in params:
query_params.append(('pageSize', params['page_size']))
if 'page' in params:
query_params.append(('page', params['page']))
if 'text_search' in params:
query_params.append(('textSearch', params['text_search']))
if 'sort_property' in params:
query_params.append(('sortProperty', params['sort_property']))
if 'sort_order' in params:
query_params.append(('sortOrder', params['sort_order']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.select_header_accept(
['application/json'])
auth_settings = ['X-Authorization']
return self.api_client.call_api(
'/api/entityGroup/{entityGroupId}/entities{?page,pageSize,sortOrder,sortProperty,textSearch}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='PageDataShortEntityView',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_entity_group_all_by_owner_and_type_using_get(self, owner_type, owner_id, group_type, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.get_entity_group_all_by_owner_and_type_using_get_with_http_info(owner_type, owner_id, group_type, **kwargs)
else:
(data) = self.get_entity_group_all_by_owner_and_type_using_get_with_http_info(owner_type, owner_id, group_type, **kwargs)
return data
def get_entity_group_all_by_owner_and_type_using_get_with_http_info(self, owner_type, owner_id, group_type, **kwargs):
all_params = ['owner_type', 'owner_id', 'group_type']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_entity_group_all_by_owner_and_type_using_get" % key
)
params[key] = val
del params['kwargs']
if ('owner_type' not in params or
params['owner_type'] is None):
raise ValueError("Missing the required parameter `owner_type` when calling `get_entity_group_all_by_owner_and_type_using_get`")
if ('owner_id' not in params or
params['owner_id'] is None):
raise ValueError("Missing the required parameter `owner_id` when calling `get_entity_group_all_by_owner_and_type_using_get`")
if ('group_type' not in params or
params['group_type'] is None):
raise ValueError("Missing the required parameter `group_type` when calling `get_entity_group_all_by_owner_and_type_using_get`")
collection_formats = {}
path_params = {}
if 'owner_type' in params:
path_params['ownerType'] = params['owner_type']
if 'owner_id' in params:
path_params['ownerId'] = params['owner_id']
if 'group_type' in params:
path_params['groupType'] = params['group_type']
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.select_header_accept(
['application/json'])
auth_settings = ['X-Authorization']
return self.api_client.call_api(
'/api/entityGroup/all/{ownerType}/{ownerId}/{groupType}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='EntityGroupInfo',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_entity_group_by_id_using_get(self, entity_group_id, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.get_entity_group_by_id_using_get_with_http_info(entity_group_id, **kwargs)
else:
(data) = self.get_entity_group_by_id_using_get_with_http_info(entity_group_id, **kwargs)
return data
def get_entity_group_by_id_using_get_with_http_info(self, entity_group_id, **kwargs):
all_params = ['entity_group_id']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_entity_group_by_id_using_get" % key
)
params[key] = val
del params['kwargs']
if ('entity_group_id' not in params or
params['entity_group_id'] is None):
raise ValueError("Missing the required parameter `entity_group_id` when calling `get_entity_group_by_id_using_get`")
collection_formats = {}
path_params = {}
if 'entity_group_id' in params:
path_params['entityGroupId'] = params['entity_group_id']
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.select_header_accept(
['application/json'])
auth_settings = ['X-Authorization']
return self.api_client.call_api(
'/api/entityGroup/{entityGroupId}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='EntityGroupInfo',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_entity_group_by_owner_and_name_and_type_using_get(self, owner_type, owner_id, group_type, group_name, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.get_entity_group_by_owner_and_name_and_type_using_get_with_http_info(owner_type, owner_id, group_type, group_name, **kwargs)
else:
(data) = self.get_entity_group_by_owner_and_name_and_type_using_get_with_http_info(owner_type, owner_id, group_type, group_name, **kwargs)
return data
def get_entity_group_by_owner_and_name_and_type_using_get_with_http_info(self, owner_type, owner_id, group_type, group_name, **kwargs):
all_params = ['owner_type', 'owner_id', 'group_type', 'group_name']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_entity_group_by_owner_and_name_and_type_using_get" % key
)
params[key] = val
del params['kwargs']
if ('owner_type' not in params or
params['owner_type'] is None):
raise ValueError("Missing the required parameter `owner_type` when calling `get_entity_group_by_owner_and_name_and_type_using_get`")
if ('owner_id' not in params or
params['owner_id'] is None):
raise ValueError("Missing the required parameter `owner_id` when calling `get_entity_group_by_owner_and_name_and_type_using_get`")
if ('group_type' not in params or
params['group_type'] is None):
raise ValueError("Missing the required parameter `group_type` when calling `get_entity_group_by_owner_and_name_and_type_using_get`")
if ('group_name' not in params or
params['group_name'] is None):
raise ValueError("Missing the required parameter `group_name` when calling `get_entity_group_by_owner_and_name_and_type_using_get`")
collection_formats = {}
path_params = {}
if 'owner_type' in params:
path_params['ownerType'] = params['owner_type']
if 'owner_id' in params:
path_params['ownerId'] = params['owner_id']
if 'group_type' in params:
path_params['groupType'] = params['group_type']
if 'group_name' in params:
path_params['groupName'] = params['group_name']
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.select_header_accept(
['application/json'])
auth_settings = ['X-Authorization']
return self.api_client.call_api(
'/api/entityGroup/{ownerType}/{ownerId}/{groupType}/{groupName}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='EntityGroupInfo',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_entity_groups_by_ids_using_get(self, entity_group_ids, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.get_entity_groups_by_ids_using_get_with_http_info(entity_group_ids, **kwargs)
else:
(data) = self.get_entity_groups_by_ids_using_get_with_http_info(entity_group_ids, **kwargs)
return data
def get_entity_groups_by_ids_using_get_with_http_info(self, entity_group_ids, **kwargs):
all_params = ['entity_group_ids']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_entity_groups_by_ids_using_get" % key
)
params[key] = val
del params['kwargs']
if ('entity_group_ids' not in params or
params['entity_group_ids'] is None):
raise ValueError("Missing the required parameter `entity_group_ids` when calling `get_entity_groups_by_ids_using_get`")
collection_formats = {}
path_params = {}
query_params = []
if 'entity_group_ids' in params:
query_params.append(('entityGroupIds', params['entity_group_ids']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.select_header_accept(
['application/json'])
auth_settings = ['X-Authorization']
return self.api_client.call_api(
'/api/entityGroups{?entityGroupIds}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='list[EntityGroup]',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_entity_groups_by_owner_and_type_using_get(self, owner_type, owner_id, group_type, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.get_entity_groups_by_owner_and_type_using_get_with_http_info(owner_type, owner_id, group_type, **kwargs)
else:
(data) = self.get_entity_groups_by_owner_and_type_using_get_with_http_info(owner_type, owner_id, group_type, **kwargs)
return data
def get_entity_groups_by_owner_and_type_using_get_with_http_info(self, owner_type, owner_id, group_type, **kwargs):
all_params = ['owner_type', 'owner_id', 'group_type']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_entity_groups_by_owner_and_type_using_get" % key
)
params[key] = val
del params['kwargs']
if ('owner_type' not in params or
params['owner_type'] is None):
raise ValueError("Missing the required parameter `owner_type` when calling `get_entity_groups_by_owner_and_type_using_get`")
if ('owner_id' not in params or
params['owner_id'] is None):
raise ValueError("Missing the required parameter `owner_id` when calling `get_entity_groups_by_owner_and_type_using_get`")
if ('group_type' not in params or
params['group_type'] is None):
raise ValueError("Missing the required parameter `group_type` when calling `get_entity_groups_by_owner_and_type_using_get`")
collection_formats = {}
path_params = {}
if 'owner_type' in params:
path_params['ownerType'] = params['owner_type']
if 'owner_id' in params:
path_params['ownerId'] = params['owner_id']
if 'group_type' in params:
path_params['groupType'] = params['group_type']
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.select_header_accept(
['application/json'])
auth_settings = ['X-Authorization']
return self.api_client.call_api(
'/api/entityGroups/{ownerType}/{ownerId}/{groupType}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='list[EntityGroupInfo]',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_entity_groups_by_type_using_get(self, group_type, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.get_entity_groups_by_type_using_get_with_http_info(group_type, **kwargs)
else:
(data) = self.get_entity_groups_by_type_using_get_with_http_info(group_type, **kwargs)
return data
def get_entity_groups_by_type_using_get_with_http_info(self, group_type, **kwargs):
all_params = ['group_type']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_entity_groups_by_type_using_get" % key
)
params[key] = val
del params['kwargs']
if ('group_type' not in params or
params['group_type'] is None):
raise ValueError("Missing the required parameter `group_type` when calling `get_entity_groups_by_type_using_get`")
collection_formats = {}
path_params = {}
if 'group_type' in params:
path_params['groupType'] = params['group_type']
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.select_header_accept(
['application/json'])
auth_settings = ['X-Authorization']
return self.api_client.call_api(
'/api/entityGroups/{groupType}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='list[EntityGroupInfo]',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_entity_groups_for_entity_using_get(self, entity_type, entity_id, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.get_entity_groups_for_entity_using_get_with_http_info(entity_type, entity_id, **kwargs)
else:
(data) = self.get_entity_groups_for_entity_using_get_with_http_info(entity_type, entity_id, **kwargs)
return data
def get_entity_groups_for_entity_using_get_with_http_info(self, entity_type, entity_id, **kwargs):
all_params = ['entity_type', 'entity_id']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_entity_groups_for_entity_using_get" % key
)
params[key] = val
del params['kwargs']
if ('entity_type' not in params or
params['entity_type'] is None):
raise ValueError("Missing the required parameter `entity_type` when calling `get_entity_groups_for_entity_using_get`")
if ('entity_id' not in params or
params['entity_id'] is None):
raise ValueError("Missing the required parameter `entity_id` when calling `get_entity_groups_for_entity_using_get`")
collection_formats = {}
path_params = {}
if 'entity_type' in params:
path_params['entityType'] = params['entity_type']
if 'entity_id' in params:
path_params['entityId'] = params['entity_id']
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.select_header_accept(
['application/json'])
auth_settings = ['X-Authorization']
return self.api_client.call_api(
'/api/entityGroups/{entityType}/{entityId}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='list[EntityGroupId]',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_group_entity_using_get(self, entity_group_id, entity_id, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.get_group_entity_using_get_with_http_info(entity_group_id, entity_id, **kwargs)
else:
(data) = self.get_group_entity_using_get_with_http_info(entity_group_id, entity_id, **kwargs)
return data
def get_group_entity_using_get_with_http_info(self, entity_group_id, entity_id, **kwargs):
all_params = ['entity_group_id', 'entity_id']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_group_entity_using_get" % key
)
params[key] = val
del params['kwargs']
if ('entity_group_id' not in params or
params['entity_group_id'] is None):
raise ValueError("Missing the required parameter `entity_group_id` when calling `get_group_entity_using_get`")
if ('entity_id' not in params or
params['entity_id'] is None):
raise ValueError("Missing the required parameter `entity_id` when calling `get_group_entity_using_get`")
collection_formats = {}
path_params = {}
if 'entity_group_id' in params:
path_params['entityGroupId'] = params['entity_group_id']
if 'entity_id' in params:
path_params['entityId'] = params['entity_id']
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.select_header_accept(
['application/json'])
auth_settings = ['X-Authorization']
return self.api_client.call_api(
'/api/entityGroup/{entityGroupId}/{entityId}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='ShortEntityView',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_owners_using_get(self, page_size, page, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.get_owners_using_get_with_http_info(page_size, page, **kwargs)
else:
(data) = self.get_owners_using_get_with_http_info(page_size, page, **kwargs)
return data
def get_owners_using_get_with_http_info(self, page_size, page, **kwargs):
all_params = ['page_size', 'page', 'text_search', 'sort_property', 'sort_order']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_owners_using_get" % key
)
params[key] = val
del params['kwargs']
if ('page_size' not in params or
params['page_size'] is None):
raise ValueError("Missing the required parameter `page_size` when calling `get_owners_using_get`")
if ('page' not in params or
params['page'] is None):
raise ValueError("Missing the required parameter `page` when calling `get_owners_using_get`")
collection_formats = {}
path_params = {}
query_params = []
if 'page_size' in params:
query_params.append(('pageSize', params['page_size']))
if 'page' in params:
query_params.append(('page', params['page']))
if 'text_search' in params:
query_params.append(('textSearch', params['text_search']))
if 'sort_property' in params:
query_params.append(('sortProperty', params['sort_property']))
if 'sort_order' in params:
query_params.append(('sortOrder', params['sort_order']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.select_header_accept(
['application/json'])
auth_settings = ['X-Authorization']
return self.api_client.call_api(
'/api/owners{?page,pageSize,sortOrder,sortProperty,textSearch}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='PageDataContactBasedobject',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def make_entity_group_private_using_post(self, entity_group_id, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.make_entity_group_private_using_post_with_http_info(entity_group_id, **kwargs)
else:
(data) = self.make_entity_group_private_using_post_with_http_info(entity_group_id, **kwargs)
return data
def make_entity_group_private_using_post_with_http_info(self, entity_group_id, **kwargs):
all_params = ['entity_group_id']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method make_entity_group_private_using_post" % key
)
params[key] = val
del params['kwargs']
if ('entity_group_id' not in params or
params['entity_group_id'] is None):
raise ValueError("Missing the required parameter `entity_group_id` when calling `make_entity_group_private_using_post`")
collection_formats = {}
path_params = {}
if 'entity_group_id' in params:
path_params['entityGroupId'] = params['entity_group_id']
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.select_header_accept(
['application/json'])
auth_settings = ['X-Authorization']
return self.api_client.call_api(
'/api/entityGroup/{entityGroupId}/makePrivate', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None,
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def make_entity_group_public_using_post(self, entity_group_id, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.make_entity_group_public_using_post_with_http_info(entity_group_id, **kwargs)
else:
(data) = self.make_entity_group_public_using_post_with_http_info(entity_group_id, **kwargs)
return data
def make_entity_group_public_using_post_with_http_info(self, entity_group_id, **kwargs):
all_params = ['entity_group_id']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method make_entity_group_public_using_post" % key
)
params[key] = val
del params['kwargs']
if ('entity_group_id' not in params or
params['entity_group_id'] is None):
raise ValueError("Missing the required parameter `entity_group_id` when calling `make_entity_group_public_using_post`")
collection_formats = {}
path_params = {}
if 'entity_group_id' in params:
path_params['entityGroupId'] = params['entity_group_id']
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.select_header_accept(
['application/json'])
auth_settings = ['X-Authorization']
return self.api_client.call_api(
'/api/entityGroup/{entityGroupId}/makePublic', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None,
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def remove_entities_from_entity_group_using_post(self, entity_group_id, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.remove_entities_from_entity_group_using_post_with_http_info(entity_group_id, **kwargs)
else:
(data) = self.remove_entities_from_entity_group_using_post_with_http_info(entity_group_id, **kwargs)
return data
def remove_entities_from_entity_group_using_post_with_http_info(self, entity_group_id, **kwargs):
all_params = ['entity_group_id', 'body']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method remove_entities_from_entity_group_using_post" % key
)
params[key] = val
del params['kwargs']
if ('entity_group_id' not in params or
params['entity_group_id'] is None):
raise ValueError("Missing the required parameter `entity_group_id` when calling `remove_entities_from_entity_group_using_post`")
collection_formats = {}
path_params = {}
if 'entity_group_id' in params:
path_params['entityGroupId'] = params['entity_group_id']
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
header_params['Accept'] = self.api_client.select_header_accept(
['application/json'])
header_params['Content-Type'] = self.api_client.select_header_content_type(
['application/json'])
auth_settings = ['X-Authorization']
return self.api_client.call_api(
'/api/entityGroup/{entityGroupId}/deleteEntities', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None,
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def save_entity_group_using_post(self, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.save_entity_group_using_post_with_http_info(**kwargs)
else:
(data) = self.save_entity_group_using_post_with_http_info(**kwargs)
return data
def save_entity_group_using_post_with_http_info(self, **kwargs):
all_params = ['body']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method save_entity_group_using_post" % key
)
params[key] = val
del params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
header_params['Accept'] = self.api_client.select_header_accept(
['application/json'])
header_params['Content-Type'] = self.api_client.select_header_content_type(
['application/json'])
auth_settings = ['X-Authorization']
return self.api_client.call_api(
'/api/entityGroup', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='EntityGroupInfo',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def share_entity_group_to_child_owner_user_group_using_post(self, entity_group_id, user_group_id, role_id, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.share_entity_group_to_child_owner_user_group_using_post_with_http_info(entity_group_id, user_group_id, role_id, **kwargs)
else:
(data) = self.share_entity_group_to_child_owner_user_group_using_post_with_http_info(entity_group_id, user_group_id, role_id, **kwargs)
return data
def share_entity_group_to_child_owner_user_group_using_post_with_http_info(self, entity_group_id, user_group_id, role_id, **kwargs):
all_params = ['entity_group_id', 'user_group_id', 'role_id']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method share_entity_group_to_child_owner_user_group_using_post" % key
)
params[key] = val
del params['kwargs']
if ('entity_group_id' not in params or
params['entity_group_id'] is None):
raise ValueError("Missing the required parameter `entity_group_id` when calling `share_entity_group_to_child_owner_user_group_using_post`")
if ('user_group_id' not in params or
params['user_group_id'] is None):
raise ValueError("Missing the required parameter `user_group_id` when calling `share_entity_group_to_child_owner_user_group_using_post`")
if ('role_id' not in params or
params['role_id'] is None):
raise ValueError("Missing the required parameter `role_id` when calling `share_entity_group_to_child_owner_user_group_using_post`")
collection_formats = {}
path_params = {}
if 'entity_group_id' in params:
path_params['entityGroupId'] = params['entity_group_id']
if 'user_group_id' in params:
path_params['userGroupId'] = params['user_group_id']
if 'role_id' in params:
path_params['roleId'] = params['role_id']
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.select_header_accept(
['application/json'])
auth_settings = ['X-Authorization']
return self.api_client.call_api(
'/api/entityGroup/{entityGroupId}/{userGroupId}/{roleId}/share', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None,
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def share_entity_group_using_post(self, entity_group_id, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.share_entity_group_using_post_with_http_info(entity_group_id, **kwargs)
else:
(data) = self.share_entity_group_using_post_with_http_info(entity_group_id, **kwargs)
return data
def share_entity_group_using_post_with_http_info(self, entity_group_id, **kwargs):
all_params = ['entity_group_id', 'body']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method share_entity_group_using_post" % key
)
params[key] = val
del params['kwargs']
if ('entity_group_id' not in params or
params['entity_group_id'] is None):
raise ValueError("Missing the required parameter `entity_group_id` when calling `share_entity_group_using_post`")
collection_formats = {}
path_params = {}
if 'entity_group_id' in params:
path_params['entityGroupId'] = params['entity_group_id']
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
header_params['Accept'] = self.api_client.select_header_accept(
['application/json'])
header_params['Content-Type'] = self.api_client.select_header_content_type(
['application/json'])
auth_settings = ['X-Authorization']
return self.api_client.call_api(
'/api/entityGroup/{entityGroupId}/share', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None,
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def unassign_entity_group_from_edge_using_delete(self, edge_id, group_type, entity_group_id, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.unassign_entity_group_from_edge_using_delete_with_http_info(edge_id, group_type, entity_group_id, **kwargs)
else:
(data) = self.unassign_entity_group_from_edge_using_delete_with_http_info(edge_id, group_type, entity_group_id, **kwargs)
return data
def unassign_entity_group_from_edge_using_delete_with_http_info(self, edge_id, group_type, entity_group_id, **kwargs):
all_params = ['edge_id', 'group_type', 'entity_group_id']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method unassign_entity_group_from_edge_using_delete" % key
)
params[key] = val
del params['kwargs']
if ('edge_id' not in params or
params['edge_id'] is None):
raise ValueError("Missing the required parameter `edge_id` when calling `unassign_entity_group_from_edge_using_delete`")
if ('group_type' not in params or
params['group_type'] is None):
raise ValueError("Missing the required parameter `group_type` when calling `unassign_entity_group_from_edge_using_delete`")
if ('entity_group_id' not in params or
params['entity_group_id'] is None):
raise ValueError("Missing the required parameter `entity_group_id` when calling `unassign_entity_group_from_edge_using_delete`")
collection_formats = {}
path_params = {}
if 'edge_id' in params:
path_params['edgeId'] = params['edge_id']
if 'group_type' in params:
path_params['groupType'] = params['group_type']
if 'entity_group_id' in params:
path_params['entityGroupId'] = params['entity_group_id']
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.select_header_accept(
['application/json'])
auth_settings = ['X-Authorization']
return self.api_client.call_api(
'/api/edge/{edgeId}/entityGroup/{entityGroupId}/{groupType}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='EntityGroup',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
| true | true |
790bf8ceade6039bbd651fce1960c04f9c51c63e | 28,394 | py | Python | tensorflow/python/keras/_impl/keras/applications/mobilenet.py | qinchangping/tensorflow | f7f7036d1cdc5716aff976fae0ea4d1b9a931b56 | [
"Apache-2.0"
] | 24 | 2018-02-01T15:49:22.000Z | 2021-01-11T16:31:18.000Z | tensorflow/python/keras/_impl/keras/applications/mobilenet.py | qinchangping/tensorflow | f7f7036d1cdc5716aff976fae0ea4d1b9a931b56 | [
"Apache-2.0"
] | 2 | 2018-09-09T07:29:07.000Z | 2019-03-11T07:14:45.000Z | tensorflow/python/keras/_impl/keras/applications/mobilenet.py | qinchangping/tensorflow | f7f7036d1cdc5716aff976fae0ea4d1b9a931b56 | [
"Apache-2.0"
] | 4 | 2018-10-29T18:43:22.000Z | 2020-09-28T07:19:52.000Z | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
# pylint: disable=invalid-name
# pylint: disable=unused-import
"""MobileNet v1 models for Keras.
MobileNet is a general architecture and can be used for multiple use cases.
Depending on the use case, it can use different input layer size and
different width factors. This allows different width models to reduce
the number of multiply-adds and thereby
reduce inference cost on mobile devices.
MobileNets support any input size greater than 32 x 32, with larger image sizes
offering better performance.
The number of parameters and number of multiply-adds
can be modified by using the `alpha` parameter,
which increases/decreases the number of filters in each layer.
By altering the image size and `alpha` parameter,
all 16 models from the paper can be built, with ImageNet weights provided.
The paper demonstrates the performance of MobileNets using `alpha` values of
1.0 (also called 100 % MobileNet), 0.75, 0.5 and 0.25.
For each of these `alpha` values, weights for 4 different input image sizes
are provided (224, 192, 160, 128).
The following table describes the size and accuracy of the 100% MobileNet
on size 224 x 224:
----------------------------------------------------------------------------
Width Multiplier (alpha) | ImageNet Acc | Multiply-Adds (M) | Params (M)
----------------------------------------------------------------------------
| 1.0 MobileNet-224 | 70.6 % | 529 | 4.2 |
| 0.75 MobileNet-224 | 68.4 % | 325 | 2.6 |
| 0.50 MobileNet-224 | 63.7 % | 149 | 1.3 |
| 0.25 MobileNet-224 | 50.6 % | 41 | 0.5 |
----------------------------------------------------------------------------
The following table describes the performance of
the 100 % MobileNet on various input sizes:
------------------------------------------------------------------------
Resolution | ImageNet Acc | Multiply-Adds (M) | Params (M)
------------------------------------------------------------------------
| 1.0 MobileNet-224 | 70.6 % | 529 | 4.2 |
| 1.0 MobileNet-192 | 69.1 % | 529 | 4.2 |
| 1.0 MobileNet-160 | 67.2 % | 529 | 4.2 |
| 1.0 MobileNet-128 | 64.4 % | 529 | 4.2 |
------------------------------------------------------------------------
The weights for all 16 models are obtained and translated
from TensorFlow checkpoints found at
https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet_v1.md
# Reference
- [MobileNets: Efficient Convolutional Neural Networks for
Mobile Vision Applications](https://arxiv.org/pdf/1704.04861.pdf))
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from tensorflow.python.keras._impl.keras import backend as K
from tensorflow.python.keras._impl.keras import constraints
from tensorflow.python.keras._impl.keras import initializers
from tensorflow.python.keras._impl.keras import regularizers
from tensorflow.python.keras._impl.keras.applications import imagenet_utils
from tensorflow.python.keras._impl.keras.applications.imagenet_utils import _obtain_input_shape
from tensorflow.python.keras._impl.keras.applications.imagenet_utils import decode_predictions
from tensorflow.python.keras._impl.keras.engine import InputSpec
from tensorflow.python.keras._impl.keras.engine.topology import get_source_inputs
from tensorflow.python.keras._impl.keras.engine.topology import shape_type_conversion
from tensorflow.python.keras._impl.keras.layers import Activation
from tensorflow.python.keras._impl.keras.layers import BatchNormalization
from tensorflow.python.keras._impl.keras.layers import Conv2D
from tensorflow.python.keras._impl.keras.layers import Dropout
from tensorflow.python.keras._impl.keras.layers import GlobalAveragePooling2D
from tensorflow.python.keras._impl.keras.layers import GlobalMaxPooling2D
from tensorflow.python.keras._impl.keras.layers import Input
from tensorflow.python.keras._impl.keras.layers import Reshape
from tensorflow.python.keras._impl.keras.models import Model
from tensorflow.python.keras._impl.keras.utils import conv_utils
from tensorflow.python.keras._impl.keras.utils.data_utils import get_file
from tensorflow.python.platform import tf_logging as logging
BASE_WEIGHT_PATH = 'https://github.com/fchollet/deep-learning-models/releases/download/v0.6/'
def relu6(x):
return K.relu(x, max_value=6)
def preprocess_input(x):
"""Preprocesses a numpy array encoding a batch of images.
Arguments:
x: a 4D numpy array consists of RGB values within [0, 255].
Returns:
Preprocessed array.
"""
return imagenet_utils.preprocess_input(x, mode='tf')
class DepthwiseConv2D(Conv2D):
"""Depthwise separable 2D convolution.
Depthwise Separable convolutions consists in performing
just the first step in a depthwise spatial convolution
(which acts on each input channel separately).
The `depth_multiplier` argument controls how many
output channels are generated per input channel in the depthwise step.
Arguments:
kernel_size: An integer or tuple/list of 2 integers, specifying the
width and height of the 2D convolution window.
Can be a single integer to specify the same value for
all spatial dimensions.
strides: An integer or tuple/list of 2 integers,
specifying the strides of the convolution along the width and height.
Can be a single integer to specify the same value for
all spatial dimensions.
Specifying any stride value != 1 is incompatible with specifying
any `dilation_rate` value != 1.
padding: one of `'valid'` or `'same'` (case-insensitive).
depth_multiplier: The number of depthwise convolution output channels
for each input channel.
The total number of depthwise convolution output
channels will be equal to `filters_in * depth_multiplier`.
data_format: A string,
one of `channels_last` (default) or `channels_first`.
The ordering of the dimensions in the inputs.
`channels_last` corresponds to inputs with shape
`(batch, height, width, channels)` while `channels_first`
corresponds to inputs with shape
`(batch, channels, height, width)`.
It defaults to the `image_data_format` value found in your
Keras config file at `~/.keras/keras.json`.
If you never set it, then it will be 'channels_last'.
activation: Activation function to use.
If you don't specify anything, no activation is applied
(ie. 'linear' activation: `a(x) = x`).
use_bias: Boolean, whether the layer uses a bias vector.
depthwise_initializer: Initializer for the depthwise kernel matrix.
bias_initializer: Initializer for the bias vector.
depthwise_regularizer: Regularizer function applied to
the depthwise kernel matrix.
bias_regularizer: Regularizer function applied to the bias vector.
activity_regularizer: Regularizer function applied to
the output of the layer (its 'activation')..
depthwise_constraint: Constraint function applied to
the depthwise kernel matrix.
bias_constraint: Constraint function applied to the bias vector.
Input shape:
4D tensor with shape:
`[batch, channels, rows, cols]` if data_format='channels_first'
or 4D tensor with shape:
`[batch, rows, cols, channels]` if data_format='channels_last'.
Output shape:
4D tensor with shape:
`[batch, filters, new_rows, new_cols]` if data_format='channels_first'
or 4D tensor with shape:
`[batch, new_rows, new_cols, filters]` if data_format='channels_last'.
`rows` and `cols` values might have changed due to padding.
"""
def __init__(self,
kernel_size,
strides=(1, 1),
padding='valid',
depth_multiplier=1,
data_format=None,
activation=None,
use_bias=True,
depthwise_initializer='glorot_uniform',
bias_initializer='zeros',
depthwise_regularizer=None,
bias_regularizer=None,
activity_regularizer=None,
depthwise_constraint=None,
bias_constraint=None,
**kwargs):
super(DepthwiseConv2D, self).__init__(
filters=None,
kernel_size=kernel_size,
strides=strides,
padding=padding,
data_format=data_format,
activation=activation,
use_bias=use_bias,
bias_regularizer=bias_regularizer,
activity_regularizer=activity_regularizer,
bias_constraint=bias_constraint,
**kwargs)
self.depth_multiplier = depth_multiplier
self.depthwise_initializer = initializers.get(depthwise_initializer)
self.depthwise_regularizer = regularizers.get(depthwise_regularizer)
self.depthwise_constraint = constraints.get(depthwise_constraint)
self.bias_initializer = initializers.get(bias_initializer)
@shape_type_conversion
def build(self, input_shape):
if len(input_shape) < 4:
raise ValueError('Inputs to `DepthwiseConv2D` should have rank 4. '
'Received input shape:', str(input_shape))
if self.data_format == 'channels_first':
channel_axis = 1
else:
channel_axis = 3
if input_shape[channel_axis] is None:
raise ValueError('The channel dimension of the inputs to '
'`DepthwiseConv2D` '
'should be defined. Found `None`.')
input_dim = int(input_shape[channel_axis])
depthwise_kernel_shape = (self.kernel_size[0], self.kernel_size[1],
input_dim, self.depth_multiplier)
self.depthwise_kernel = self.add_weight(
shape=depthwise_kernel_shape,
initializer=self.depthwise_initializer,
name='depthwise_kernel',
regularizer=self.depthwise_regularizer,
constraint=self.depthwise_constraint)
if self.use_bias:
self.bias = self.add_weight(
shape=(input_dim * self.depth_multiplier,),
initializer=self.bias_initializer,
name='bias',
regularizer=self.bias_regularizer,
constraint=self.bias_constraint)
else:
self.bias = None
# Set input spec.
self.input_spec = InputSpec(ndim=4, axes={channel_axis: input_dim})
self.built = True
def call(self, inputs, training=None):
outputs = K.depthwise_conv2d(
inputs,
self.depthwise_kernel,
strides=self.strides,
padding=self.padding,
dilation_rate=self.dilation_rate,
data_format=self.data_format)
if self.bias:
outputs = K.bias_add(outputs, self.bias, data_format=self.data_format)
if self.activation is not None:
return self.activation(outputs)
return outputs
@shape_type_conversion
def compute_output_shape(self, input_shape):
if self.data_format == 'channels_first':
rows = input_shape[2]
cols = input_shape[3]
out_filters = input_shape[1] * self.depth_multiplier
elif self.data_format == 'channels_last':
rows = input_shape[1]
cols = input_shape[2]
out_filters = input_shape[3] * self.depth_multiplier
rows = conv_utils.conv_output_length(rows, self.kernel_size[0],
self.padding, self.strides[0])
cols = conv_utils.conv_output_length(cols, self.kernel_size[1],
self.padding, self.strides[1])
if self.data_format == 'channels_first':
return (input_shape[0], out_filters, rows, cols)
elif self.data_format == 'channels_last':
return (input_shape[0], rows, cols, out_filters)
def get_config(self):
config = super(DepthwiseConv2D, self).get_config()
config.pop('filters')
config.pop('kernel_initializer')
config.pop('kernel_regularizer')
config.pop('kernel_constraint')
config['depth_multiplier'] = self.depth_multiplier
config['depthwise_initializer'] = initializers.serialize(
self.depthwise_initializer)
config['depthwise_regularizer'] = regularizers.serialize(
self.depthwise_regularizer)
config['depthwise_constraint'] = constraints.serialize(
self.depthwise_constraint)
return config
def MobileNet(input_shape=None,
alpha=1.0,
depth_multiplier=1,
dropout=1e-3,
include_top=True,
weights='imagenet',
input_tensor=None,
pooling=None,
classes=1000):
"""Instantiates the MobileNet architecture.
Note that only TensorFlow is supported for now,
therefore it only works with the data format
`image_data_format='channels_last'` in your Keras config
at `~/.keras/keras.json`.
To load a MobileNet model via `load_model`, import the custom
objects `relu6` and `DepthwiseConv2D` and pass them to the
`custom_objects` parameter.
E.g.
model = load_model('mobilenet.h5', custom_objects={
'relu6': mobilenet.relu6,
'DepthwiseConv2D': mobilenet.DepthwiseConv2D})
Arguments:
input_shape: optional shape tuple, only to be specified
if `include_top` is False (otherwise the input shape
has to be `(224, 224, 3)` (with `channels_last` data format)
or (3, 224, 224) (with `channels_first` data format).
It should have exactly 3 inputs channels,
and width and height should be no smaller than 32.
E.g. `(200, 200, 3)` would be one valid value.
alpha: controls the width of the network.
- If `alpha` < 1.0, proportionally decreases the number
of filters in each layer.
- If `alpha` > 1.0, proportionally increases the number
of filters in each layer.
- If `alpha` = 1, default number of filters from the paper
are used at each layer.
depth_multiplier: depth multiplier for depthwise convolution
(also called the resolution multiplier)
dropout: dropout rate
include_top: whether to include the fully-connected
layer at the top of the network.
weights: one of `None` (random initialization),
'imagenet' (pre-training on ImageNet),
or the path to the weights file to be loaded.
input_tensor: optional Keras tensor (i.e. output of
`layers.Input()`)
to use as image input for the model.
pooling: Optional pooling mode for feature extraction
when `include_top` is `False`.
- `None` means that the output of the model
will be the 4D tensor output of the
last convolutional layer.
- `avg` means that global average pooling
will be applied to the output of the
last convolutional layer, and thus
the output of the model will be a
2D tensor.
- `max` means that global max pooling will
be applied.
classes: optional number of classes to classify images
into, only to be specified if `include_top` is True, and
if no `weights` argument is specified.
Returns:
A Keras model instance.
Raises:
ValueError: in case of invalid argument for `weights`,
or invalid input shape.
RuntimeError: If attempting to run this model with a
backend that does not support separable convolutions.
"""
if K.backend() != 'tensorflow':
raise RuntimeError('Only TensorFlow backend is currently supported, '
'as other backends do not support '
'depthwise convolution.')
if not (weights in {'imagenet', None} or os.path.exists(weights)):
raise ValueError('The `weights` argument should be either '
'`None` (random initialization), `imagenet` '
'(pre-training on ImageNet), '
'or the path to the weights file to be loaded.')
if weights == 'imagenet' and include_top and classes != 1000:
raise ValueError('If using `weights` as ImageNet with `include_top` '
'as true, `classes` should be 1000')
# Determine proper input shape and default size.
if input_shape is None:
default_size = 224
else:
if K.image_data_format() == 'channels_first':
rows = input_shape[1]
cols = input_shape[2]
else:
rows = input_shape[0]
cols = input_shape[1]
if rows == cols and rows in [128, 160, 192, 224]:
default_size = rows
else:
default_size = 224
input_shape = _obtain_input_shape(
input_shape,
default_size=default_size,
min_size=32,
data_format=K.image_data_format(),
require_flatten=include_top,
weights=weights)
if K.image_data_format() == 'channels_last':
row_axis, col_axis = (0, 1)
else:
row_axis, col_axis = (1, 2)
rows = input_shape[row_axis]
cols = input_shape[col_axis]
if weights == 'imagenet':
if depth_multiplier != 1:
raise ValueError('If imagenet weights are being loaded, '
'depth multiplier must be 1')
if alpha not in [0.25, 0.50, 0.75, 1.0]:
raise ValueError('If imagenet weights are being loaded, '
'alpha can be one of'
'`0.25`, `0.50`, `0.75` or `1.0` only.')
if rows != cols or rows not in [128, 160, 192, 224]:
raise ValueError('If imagenet weights are being loaded, '
'input must have a static square shape (one of '
'(128,128), (160,160), (192,192), or (224, 224)).'
' Input shape provided = %s' % (input_shape,))
if K.image_data_format() != 'channels_last':
logging.warning('The MobileNet family of models is only available '
'for the input data format "channels_last" '
'(width, height, channels). '
'However your settings specify the default '
'data format "channels_first" (channels, width, height).'
' You should set `image_data_format="channels_last"` '
'in your Keras config located at ~/.keras/keras.json. '
'The model being returned right now will expect inputs '
'to follow the "channels_last" data format.')
K.set_image_data_format('channels_last')
old_data_format = 'channels_first'
else:
old_data_format = None
if input_tensor is None:
img_input = Input(shape=input_shape)
else:
if not K.is_keras_tensor(input_tensor):
img_input = Input(tensor=input_tensor, shape=input_shape)
else:
img_input = input_tensor
x = _conv_block(img_input, 32, alpha, strides=(2, 2))
x = _depthwise_conv_block(x, 64, alpha, depth_multiplier, block_id=1)
x = _depthwise_conv_block(
x, 128, alpha, depth_multiplier, strides=(2, 2), block_id=2)
x = _depthwise_conv_block(x, 128, alpha, depth_multiplier, block_id=3)
x = _depthwise_conv_block(
x, 256, alpha, depth_multiplier, strides=(2, 2), block_id=4)
x = _depthwise_conv_block(x, 256, alpha, depth_multiplier, block_id=5)
x = _depthwise_conv_block(
x, 512, alpha, depth_multiplier, strides=(2, 2), block_id=6)
x = _depthwise_conv_block(x, 512, alpha, depth_multiplier, block_id=7)
x = _depthwise_conv_block(x, 512, alpha, depth_multiplier, block_id=8)
x = _depthwise_conv_block(x, 512, alpha, depth_multiplier, block_id=9)
x = _depthwise_conv_block(x, 512, alpha, depth_multiplier, block_id=10)
x = _depthwise_conv_block(x, 512, alpha, depth_multiplier, block_id=11)
x = _depthwise_conv_block(
x, 1024, alpha, depth_multiplier, strides=(2, 2), block_id=12)
x = _depthwise_conv_block(x, 1024, alpha, depth_multiplier, block_id=13)
if include_top:
if K.image_data_format() == 'channels_first':
shape = (int(1024 * alpha), 1, 1)
else:
shape = (1, 1, int(1024 * alpha))
x = GlobalAveragePooling2D()(x)
x = Reshape(shape, name='reshape_1')(x)
x = Dropout(dropout, name='dropout')(x)
x = Conv2D(classes, (1, 1), padding='same', name='conv_preds')(x)
x = Activation('softmax', name='act_softmax')(x)
x = Reshape((classes,), name='reshape_2')(x)
else:
if pooling == 'avg':
x = GlobalAveragePooling2D()(x)
elif pooling == 'max':
x = GlobalMaxPooling2D()(x)
# Ensure that the model takes into account
# any potential predecessors of `input_tensor`.
if input_tensor is not None:
inputs = get_source_inputs(input_tensor)
else:
inputs = img_input
# Create model.
model = Model(inputs, x, name='mobilenet_%0.2f_%s' % (alpha, rows))
# load weights
if weights == 'imagenet':
if K.image_data_format() == 'channels_first':
raise ValueError('Weights for "channels_last" format '
'are not available.')
if alpha == 1.0:
alpha_text = '1_0'
elif alpha == 0.75:
alpha_text = '7_5'
elif alpha == 0.50:
alpha_text = '5_0'
else:
alpha_text = '2_5'
if include_top:
model_name = 'mobilenet_%s_%d_tf.h5' % (alpha_text, rows)
weigh_path = BASE_WEIGHT_PATH + model_name
weights_path = get_file(model_name, weigh_path, cache_subdir='models')
else:
model_name = 'mobilenet_%s_%d_tf_no_top.h5' % (alpha_text, rows)
weigh_path = BASE_WEIGHT_PATH + model_name
weights_path = get_file(model_name, weigh_path, cache_subdir='models')
model.load_weights(weights_path)
elif weights is not None:
model.load_weights(weights)
if old_data_format:
K.set_image_data_format(old_data_format)
return model
def _conv_block(inputs, filters, alpha, kernel=(3, 3), strides=(1, 1)):
"""Adds an initial convolution layer (with batch normalization and relu6).
Arguments:
inputs: Input tensor of shape `(rows, cols, 3)`
(with `channels_last` data format) or
(3, rows, cols) (with `channels_first` data format).
It should have exactly 3 inputs channels,
and width and height should be no smaller than 32.
E.g. `(224, 224, 3)` would be one valid value.
filters: Integer, the dimensionality of the output space
(i.e. the number output of filters in the convolution).
alpha: controls the width of the network.
- If `alpha` < 1.0, proportionally decreases the number
of filters in each layer.
- If `alpha` > 1.0, proportionally increases the number
of filters in each layer.
- If `alpha` = 1, default number of filters from the paper
are used at each layer.
kernel: An integer or tuple/list of 2 integers, specifying the
width and height of the 2D convolution window.
Can be a single integer to specify the same value for
all spatial dimensions.
strides: An integer or tuple/list of 2 integers,
specifying the strides of the convolution along the width and height.
Can be a single integer to specify the same value for
all spatial dimensions.
Specifying any stride value != 1 is incompatible with specifying
any `dilation_rate` value != 1.
Input shape:
4D tensor with shape:
`(samples, channels, rows, cols)` if data_format='channels_first'
or 4D tensor with shape:
`(samples, rows, cols, channels)` if data_format='channels_last'.
Output shape:
4D tensor with shape:
`(samples, filters, new_rows, new_cols)` if data_format='channels_first'
or 4D tensor with shape:
`(samples, new_rows, new_cols, filters)` if data_format='channels_last'.
`rows` and `cols` values might have changed due to stride.
Returns:
Output tensor of block.
"""
channel_axis = 1 if K.image_data_format() == 'channels_first' else -1
filters = int(filters * alpha)
x = Conv2D(
filters,
kernel,
padding='same',
use_bias=False,
strides=strides,
name='conv1')(
inputs)
x = BatchNormalization(axis=channel_axis, name='conv1_bn')(x)
return Activation(relu6, name='conv1_relu')(x)
def _depthwise_conv_block(inputs,
pointwise_conv_filters,
alpha,
depth_multiplier=1,
strides=(1, 1),
block_id=1):
"""Adds a depthwise convolution block.
A depthwise convolution block consists of a depthwise conv,
batch normalization, relu6, pointwise convolution,
batch normalization and relu6 activation.
Arguments:
inputs: Input tensor of shape `(rows, cols, channels)`
(with `channels_last` data format) or
(channels, rows, cols) (with `channels_first` data format).
pointwise_conv_filters: Integer, the dimensionality of the output space
(i.e. the number output of filters in the pointwise convolution).
alpha: controls the width of the network.
- If `alpha` < 1.0, proportionally decreases the number
of filters in each layer.
- If `alpha` > 1.0, proportionally increases the number
of filters in each layer.
- If `alpha` = 1, default number of filters from the paper
are used at each layer.
depth_multiplier: The number of depthwise convolution output channels
for each input channel.
The total number of depthwise convolution output
channels will be equal to `filters_in * depth_multiplier`.
strides: An integer or tuple/list of 2 integers,
specifying the strides of the convolution along the width and height.
Can be a single integer to specify the same value for
all spatial dimensions.
Specifying any stride value != 1 is incompatible with specifying
any `dilation_rate` value != 1.
block_id: Integer, a unique identification designating the block number.
Input shape:
4D tensor with shape:
`(batch, channels, rows, cols)` if data_format='channels_first'
or 4D tensor with shape:
`(batch, rows, cols, channels)` if data_format='channels_last'.
Output shape:
4D tensor with shape:
`(batch, filters, new_rows, new_cols)` if data_format='channels_first'
or 4D tensor with shape:
`(batch, new_rows, new_cols, filters)` if data_format='channels_last'.
`rows` and `cols` values might have changed due to stride.
Returns:
Output tensor of block.
"""
channel_axis = 1 if K.image_data_format() == 'channels_first' else -1
pointwise_conv_filters = int(pointwise_conv_filters * alpha)
x = DepthwiseConv2D( # pylint: disable=not-callable
(3, 3),
padding='same',
depth_multiplier=depth_multiplier,
strides=strides,
use_bias=False,
name='conv_dw_%d' % block_id)(
inputs)
x = BatchNormalization(axis=channel_axis, name='conv_dw_%d_bn' % block_id)(x)
x = Activation(relu6, name='conv_dw_%d_relu' % block_id)(x)
x = Conv2D(
pointwise_conv_filters, (1, 1),
padding='same',
use_bias=False,
strides=(1, 1),
name='conv_pw_%d' % block_id)(
x)
x = BatchNormalization(axis=channel_axis, name='conv_pw_%d_bn' % block_id)(x)
return Activation(relu6, name='conv_pw_%d_relu' % block_id)(x)
| 41.451095 | 95 | 0.650736 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from tensorflow.python.keras._impl.keras import backend as K
from tensorflow.python.keras._impl.keras import constraints
from tensorflow.python.keras._impl.keras import initializers
from tensorflow.python.keras._impl.keras import regularizers
from tensorflow.python.keras._impl.keras.applications import imagenet_utils
from tensorflow.python.keras._impl.keras.applications.imagenet_utils import _obtain_input_shape
from tensorflow.python.keras._impl.keras.applications.imagenet_utils import decode_predictions
from tensorflow.python.keras._impl.keras.engine import InputSpec
from tensorflow.python.keras._impl.keras.engine.topology import get_source_inputs
from tensorflow.python.keras._impl.keras.engine.topology import shape_type_conversion
from tensorflow.python.keras._impl.keras.layers import Activation
from tensorflow.python.keras._impl.keras.layers import BatchNormalization
from tensorflow.python.keras._impl.keras.layers import Conv2D
from tensorflow.python.keras._impl.keras.layers import Dropout
from tensorflow.python.keras._impl.keras.layers import GlobalAveragePooling2D
from tensorflow.python.keras._impl.keras.layers import GlobalMaxPooling2D
from tensorflow.python.keras._impl.keras.layers import Input
from tensorflow.python.keras._impl.keras.layers import Reshape
from tensorflow.python.keras._impl.keras.models import Model
from tensorflow.python.keras._impl.keras.utils import conv_utils
from tensorflow.python.keras._impl.keras.utils.data_utils import get_file
from tensorflow.python.platform import tf_logging as logging
BASE_WEIGHT_PATH = 'https://github.com/fchollet/deep-learning-models/releases/download/v0.6/'
def relu6(x):
return K.relu(x, max_value=6)
def preprocess_input(x):
return imagenet_utils.preprocess_input(x, mode='tf')
class DepthwiseConv2D(Conv2D):
def __init__(self,
kernel_size,
strides=(1, 1),
padding='valid',
depth_multiplier=1,
data_format=None,
activation=None,
use_bias=True,
depthwise_initializer='glorot_uniform',
bias_initializer='zeros',
depthwise_regularizer=None,
bias_regularizer=None,
activity_regularizer=None,
depthwise_constraint=None,
bias_constraint=None,
**kwargs):
super(DepthwiseConv2D, self).__init__(
filters=None,
kernel_size=kernel_size,
strides=strides,
padding=padding,
data_format=data_format,
activation=activation,
use_bias=use_bias,
bias_regularizer=bias_regularizer,
activity_regularizer=activity_regularizer,
bias_constraint=bias_constraint,
**kwargs)
self.depth_multiplier = depth_multiplier
self.depthwise_initializer = initializers.get(depthwise_initializer)
self.depthwise_regularizer = regularizers.get(depthwise_regularizer)
self.depthwise_constraint = constraints.get(depthwise_constraint)
self.bias_initializer = initializers.get(bias_initializer)
@shape_type_conversion
def build(self, input_shape):
if len(input_shape) < 4:
raise ValueError('Inputs to `DepthwiseConv2D` should have rank 4. '
'Received input shape:', str(input_shape))
if self.data_format == 'channels_first':
channel_axis = 1
else:
channel_axis = 3
if input_shape[channel_axis] is None:
raise ValueError('The channel dimension of the inputs to '
'`DepthwiseConv2D` '
'should be defined. Found `None`.')
input_dim = int(input_shape[channel_axis])
depthwise_kernel_shape = (self.kernel_size[0], self.kernel_size[1],
input_dim, self.depth_multiplier)
self.depthwise_kernel = self.add_weight(
shape=depthwise_kernel_shape,
initializer=self.depthwise_initializer,
name='depthwise_kernel',
regularizer=self.depthwise_regularizer,
constraint=self.depthwise_constraint)
if self.use_bias:
self.bias = self.add_weight(
shape=(input_dim * self.depth_multiplier,),
initializer=self.bias_initializer,
name='bias',
regularizer=self.bias_regularizer,
constraint=self.bias_constraint)
else:
self.bias = None
self.input_spec = InputSpec(ndim=4, axes={channel_axis: input_dim})
self.built = True
def call(self, inputs, training=None):
outputs = K.depthwise_conv2d(
inputs,
self.depthwise_kernel,
strides=self.strides,
padding=self.padding,
dilation_rate=self.dilation_rate,
data_format=self.data_format)
if self.bias:
outputs = K.bias_add(outputs, self.bias, data_format=self.data_format)
if self.activation is not None:
return self.activation(outputs)
return outputs
@shape_type_conversion
def compute_output_shape(self, input_shape):
if self.data_format == 'channels_first':
rows = input_shape[2]
cols = input_shape[3]
out_filters = input_shape[1] * self.depth_multiplier
elif self.data_format == 'channels_last':
rows = input_shape[1]
cols = input_shape[2]
out_filters = input_shape[3] * self.depth_multiplier
rows = conv_utils.conv_output_length(rows, self.kernel_size[0],
self.padding, self.strides[0])
cols = conv_utils.conv_output_length(cols, self.kernel_size[1],
self.padding, self.strides[1])
if self.data_format == 'channels_first':
return (input_shape[0], out_filters, rows, cols)
elif self.data_format == 'channels_last':
return (input_shape[0], rows, cols, out_filters)
def get_config(self):
config = super(DepthwiseConv2D, self).get_config()
config.pop('filters')
config.pop('kernel_initializer')
config.pop('kernel_regularizer')
config.pop('kernel_constraint')
config['depth_multiplier'] = self.depth_multiplier
config['depthwise_initializer'] = initializers.serialize(
self.depthwise_initializer)
config['depthwise_regularizer'] = regularizers.serialize(
self.depthwise_regularizer)
config['depthwise_constraint'] = constraints.serialize(
self.depthwise_constraint)
return config
def MobileNet(input_shape=None,
alpha=1.0,
depth_multiplier=1,
dropout=1e-3,
include_top=True,
weights='imagenet',
input_tensor=None,
pooling=None,
classes=1000):
if K.backend() != 'tensorflow':
raise RuntimeError('Only TensorFlow backend is currently supported, '
'as other backends do not support '
'depthwise convolution.')
if not (weights in {'imagenet', None} or os.path.exists(weights)):
raise ValueError('The `weights` argument should be either '
'`None` (random initialization), `imagenet` '
'(pre-training on ImageNet), '
'or the path to the weights file to be loaded.')
if weights == 'imagenet' and include_top and classes != 1000:
raise ValueError('If using `weights` as ImageNet with `include_top` '
'as true, `classes` should be 1000')
if input_shape is None:
default_size = 224
else:
if K.image_data_format() == 'channels_first':
rows = input_shape[1]
cols = input_shape[2]
else:
rows = input_shape[0]
cols = input_shape[1]
if rows == cols and rows in [128, 160, 192, 224]:
default_size = rows
else:
default_size = 224
input_shape = _obtain_input_shape(
input_shape,
default_size=default_size,
min_size=32,
data_format=K.image_data_format(),
require_flatten=include_top,
weights=weights)
if K.image_data_format() == 'channels_last':
row_axis, col_axis = (0, 1)
else:
row_axis, col_axis = (1, 2)
rows = input_shape[row_axis]
cols = input_shape[col_axis]
if weights == 'imagenet':
if depth_multiplier != 1:
raise ValueError('If imagenet weights are being loaded, '
'depth multiplier must be 1')
if alpha not in [0.25, 0.50, 0.75, 1.0]:
raise ValueError('If imagenet weights are being loaded, '
'alpha can be one of'
'`0.25`, `0.50`, `0.75` or `1.0` only.')
if rows != cols or rows not in [128, 160, 192, 224]:
raise ValueError('If imagenet weights are being loaded, '
'input must have a static square shape (one of '
'(128,128), (160,160), (192,192), or (224, 224)).'
' Input shape provided = %s' % (input_shape,))
if K.image_data_format() != 'channels_last':
logging.warning('The MobileNet family of models is only available '
'for the input data format "channels_last" '
'(width, height, channels). '
'However your settings specify the default '
'data format "channels_first" (channels, width, height).'
' You should set `image_data_format="channels_last"` '
'in your Keras config located at ~/.keras/keras.json. '
'The model being returned right now will expect inputs '
'to follow the "channels_last" data format.')
K.set_image_data_format('channels_last')
old_data_format = 'channels_first'
else:
old_data_format = None
if input_tensor is None:
img_input = Input(shape=input_shape)
else:
if not K.is_keras_tensor(input_tensor):
img_input = Input(tensor=input_tensor, shape=input_shape)
else:
img_input = input_tensor
x = _conv_block(img_input, 32, alpha, strides=(2, 2))
x = _depthwise_conv_block(x, 64, alpha, depth_multiplier, block_id=1)
x = _depthwise_conv_block(
x, 128, alpha, depth_multiplier, strides=(2, 2), block_id=2)
x = _depthwise_conv_block(x, 128, alpha, depth_multiplier, block_id=3)
x = _depthwise_conv_block(
x, 256, alpha, depth_multiplier, strides=(2, 2), block_id=4)
x = _depthwise_conv_block(x, 256, alpha, depth_multiplier, block_id=5)
x = _depthwise_conv_block(
x, 512, alpha, depth_multiplier, strides=(2, 2), block_id=6)
x = _depthwise_conv_block(x, 512, alpha, depth_multiplier, block_id=7)
x = _depthwise_conv_block(x, 512, alpha, depth_multiplier, block_id=8)
x = _depthwise_conv_block(x, 512, alpha, depth_multiplier, block_id=9)
x = _depthwise_conv_block(x, 512, alpha, depth_multiplier, block_id=10)
x = _depthwise_conv_block(x, 512, alpha, depth_multiplier, block_id=11)
x = _depthwise_conv_block(
x, 1024, alpha, depth_multiplier, strides=(2, 2), block_id=12)
x = _depthwise_conv_block(x, 1024, alpha, depth_multiplier, block_id=13)
if include_top:
if K.image_data_format() == 'channels_first':
shape = (int(1024 * alpha), 1, 1)
else:
shape = (1, 1, int(1024 * alpha))
x = GlobalAveragePooling2D()(x)
x = Reshape(shape, name='reshape_1')(x)
x = Dropout(dropout, name='dropout')(x)
x = Conv2D(classes, (1, 1), padding='same', name='conv_preds')(x)
x = Activation('softmax', name='act_softmax')(x)
x = Reshape((classes,), name='reshape_2')(x)
else:
if pooling == 'avg':
x = GlobalAveragePooling2D()(x)
elif pooling == 'max':
x = GlobalMaxPooling2D()(x)
if input_tensor is not None:
inputs = get_source_inputs(input_tensor)
else:
inputs = img_input
model = Model(inputs, x, name='mobilenet_%0.2f_%s' % (alpha, rows))
if weights == 'imagenet':
if K.image_data_format() == 'channels_first':
raise ValueError('Weights for "channels_last" format '
'are not available.')
if alpha == 1.0:
alpha_text = '1_0'
elif alpha == 0.75:
alpha_text = '7_5'
elif alpha == 0.50:
alpha_text = '5_0'
else:
alpha_text = '2_5'
if include_top:
model_name = 'mobilenet_%s_%d_tf.h5' % (alpha_text, rows)
weigh_path = BASE_WEIGHT_PATH + model_name
weights_path = get_file(model_name, weigh_path, cache_subdir='models')
else:
model_name = 'mobilenet_%s_%d_tf_no_top.h5' % (alpha_text, rows)
weigh_path = BASE_WEIGHT_PATH + model_name
weights_path = get_file(model_name, weigh_path, cache_subdir='models')
model.load_weights(weights_path)
elif weights is not None:
model.load_weights(weights)
if old_data_format:
K.set_image_data_format(old_data_format)
return model
def _conv_block(inputs, filters, alpha, kernel=(3, 3), strides=(1, 1)):
channel_axis = 1 if K.image_data_format() == 'channels_first' else -1
filters = int(filters * alpha)
x = Conv2D(
filters,
kernel,
padding='same',
use_bias=False,
strides=strides,
name='conv1')(
inputs)
x = BatchNormalization(axis=channel_axis, name='conv1_bn')(x)
return Activation(relu6, name='conv1_relu')(x)
def _depthwise_conv_block(inputs,
pointwise_conv_filters,
alpha,
depth_multiplier=1,
strides=(1, 1),
block_id=1):
channel_axis = 1 if K.image_data_format() == 'channels_first' else -1
pointwise_conv_filters = int(pointwise_conv_filters * alpha)
x = DepthwiseConv2D(
(3, 3),
padding='same',
depth_multiplier=depth_multiplier,
strides=strides,
use_bias=False,
name='conv_dw_%d' % block_id)(
inputs)
x = BatchNormalization(axis=channel_axis, name='conv_dw_%d_bn' % block_id)(x)
x = Activation(relu6, name='conv_dw_%d_relu' % block_id)(x)
x = Conv2D(
pointwise_conv_filters, (1, 1),
padding='same',
use_bias=False,
strides=(1, 1),
name='conv_pw_%d' % block_id)(
x)
x = BatchNormalization(axis=channel_axis, name='conv_pw_%d_bn' % block_id)(x)
return Activation(relu6, name='conv_pw_%d_relu' % block_id)(x)
| true | true |
790bf9fe8a42b67994f7345b2484de5970a9982c | 615 | py | Python | exercise_brokencounts_solution.py | annezola/gdi-python | a806f0eca2eb17e5a975cce8d0b1d90490dd455e | [
"MIT"
] | null | null | null | exercise_brokencounts_solution.py | annezola/gdi-python | a806f0eca2eb17e5a975cce8d0b1d90490dd455e | [
"MIT"
] | null | null | null | exercise_brokencounts_solution.py | annezola/gdi-python | a806f0eca2eb17e5a975cce8d0b1d90490dd455e | [
"MIT"
] | 1 | 2022-01-04T15:26:40.000Z | 2022-01-04T15:26:40.000Z | # Fix the code so that there's no error!
def count_evens(start, end):
"""Returns the number of even numbers between start and end."""
counter = start
num_evens = 0
while counter <= end:
if counter % 2 == 0:
num_evens += 1
counter += 1
return num_evens
def count_multiples(start, end, divisor):
"""Returns the number of multiples of divisor between start and end."""
counter = start
num_multiples = 0
while counter <= end:
if counter % divisor == 0:
num_multiples += 1
counter += 1
return num_multiples
count_both = count_evens(10, 20) + count_multiples(10, 20, 3)
| 25.625 | 73 | 0.666667 |
def count_evens(start, end):
counter = start
num_evens = 0
while counter <= end:
if counter % 2 == 0:
num_evens += 1
counter += 1
return num_evens
def count_multiples(start, end, divisor):
counter = start
num_multiples = 0
while counter <= end:
if counter % divisor == 0:
num_multiples += 1
counter += 1
return num_multiples
count_both = count_evens(10, 20) + count_multiples(10, 20, 3)
| true | true |
790bf9ff34ff4483a6201d656573973b10b16f63 | 56,109 | py | Python | seqio/dataset_providers_test.py | shism2/seqio | a2de55ee4fc17b02324d0bdae18295cd4d0df4be | [
"Apache-2.0"
] | 1 | 2022-03-11T20:05:56.000Z | 2022-03-11T20:05:56.000Z | seqio/dataset_providers_test.py | 00mjk/seqio | 63f96f1d29f7721af67d79c0265d7f937170ee20 | [
"Apache-2.0"
] | null | null | null | seqio/dataset_providers_test.py | 00mjk/seqio | 63f96f1d29f7721af67d79c0265d7f937170ee20 | [
"Apache-2.0"
] | null | null | null | # Copyright 2022 The SeqIO Authors.
#
# 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.
# Lint as: python3
"""Tests for seqio.dataset_providers."""
import copy
import functools
import os
import shutil
from typing import Any, Callable, Mapping, Optional, Sequence
from absl.testing import absltest
from absl.testing import parameterized
from seqio import dataset_providers
from seqio import feature_converters
from seqio import metrics as metrics_lib
from seqio import preprocessors
from seqio import test_utils
from seqio import utils
from seqio import vocabularies
import tensorflow.compat.v2 as tf
import tensorflow_datasets as tfds
tf.compat.v1.enable_eager_execution()
TaskRegistry = dataset_providers.TaskRegistry
MixtureRegistry = dataset_providers.MixtureRegistry
mock = absltest.mock
assert_dataset = test_utils.assert_dataset
create_default_dataset = test_utils.create_default_dataset
class TasksTest(test_utils.FakeTaskTest):
def test_invalid_name(self):
with self.assertRaisesRegex(
ValueError,
"Task name 'invalid/name' contains invalid characters. "
"Must match regex: .*"):
self.add_task("invalid/name", self.function_source)
def test_repeat_name(self):
with self.assertRaisesWithLiteralMatch(
ValueError,
"Attempting to register duplicate provider: text_line_task"):
self.add_task("text_line_task", self.text_line_source)
def test_function_source_signature(self):
# Good signatures.
def good_fn(split, shuffle_files):
del split
del shuffle_files
dataset_providers.FunctionDataSource(good_fn, splits=("train",))
def default_good_fn(split, shuffle_files=False):
del split
del shuffle_files
dataset_providers.FunctionDataSource(default_good_fn, splits=("train",))
def seed_fn(split, shuffle_files=True, seed=0):
del split
del shuffle_files
del seed
dataset_providers.FunctionDataSource(seed_fn, splits=("train",))
def extra_kwarg_good_fn(split, shuffle_files, unused_kwarg=True):
del split
del shuffle_files
dataset_providers.FunctionDataSource(extra_kwarg_good_fn, splits=("train",))
# Bad signatures.
with self.assertRaisesWithLiteralMatch(
ValueError,
"'missing_shuff' must have positional args ('split', 'shuffle_files'), "
"got: ('split',)"):
def missing_shuff(split):
del split
dataset_providers.FunctionDataSource(missing_shuff, splits=("train",))
with self.assertRaisesWithLiteralMatch(
ValueError,
"'missing_split' must have positional args ('split', 'shuffle_files'), "
"got: ('shuffle_files',)"):
def missing_split(shuffle_files):
del shuffle_files
dataset_providers.FunctionDataSource(missing_split, splits=("train",))
with self.assertRaisesWithLiteralMatch(
ValueError,
"'extra_pos_arg' may only have positional args ('split', "
"'shuffle_files'), got: ('split', 'shuffle_files', 'unused_arg')"):
def extra_pos_arg(split, shuffle_files, unused_arg):
del split
del shuffle_files
dataset_providers.FunctionDataSource(extra_pos_arg, splits=("train",))
def test_metric_fn_signature(self):
# pylint:disable=unused-argument
add_task = functools.partial(self.add_task, source=self.function_source)
def score_metric_fn(targets, scores):
return {}
def predict_metric_fn(targets, predictions):
return {}
valid_task = add_task(
"valid_metrics", metric_fns=[score_metric_fn, predict_metric_fn])
self.assertSameElements(
[score_metric_fn, predict_metric_fn], valid_task.metric_fns)
self.assertSameElements(
[score_metric_fn], valid_task.score_metric_fns)
self.assertSameElements(
[predict_metric_fn], valid_task.predict_metric_fns)
def extra_arg_metric_fn(targets, predictions, extra_param):
return {}
expected_error_message_prefix = (
"Metric functions must have positional arguments matching either "
"('targets', 'predictions') or ('targets', 'scores'). Got: ")
with self.assertRaisesWithLiteralMatch(
ValueError,
expected_error_message_prefix +
"('targets', 'predictions', 'extra_param')"):
valid_task = add_task(
"extra_arg_metric", metric_fns=[extra_arg_metric_fn])
def bad_order_metric_fn(predictions, targets):
return {}
with self.assertRaisesWithLiteralMatch(
ValueError,
expected_error_message_prefix + "('predictions', 'targets')"):
valid_task = add_task(
"bad_order_metric", metric_fns=[bad_order_metric_fn])
def bad_default_metric_fn(targets, predictions=(0)):
return {}
with self.assertRaisesWithLiteralMatch(
ValueError,
expected_error_message_prefix + "('targets',)"):
valid_task = add_task(
"bad_default_metric", metric_fns=[bad_default_metric_fn])
def ok_default_metric_fn(targets, predictions, extra_param=3):
return {}
valid_task_2 = add_task(
"valid_metrics_2", metric_fns=[ok_default_metric_fn])
self.assertSameElements([ok_default_metric_fn], valid_task_2.metric_fns)
self.assertEmpty(valid_task_2.score_metric_fns)
self.assertSameElements(
[ok_default_metric_fn], valid_task_2.predict_metric_fns)
def predict_metric_fn_with_types(
targets: Sequence[Mapping[str,
Any]], predictions: Sequence[Mapping[str,
Any]]
) -> Mapping[str, metrics_lib.MetricValue]:
return {}
valid_task_with_types = TaskRegistry.add(
"valid_metrics_with_types",
source=self.function_source,
output_features={
"inputs":
dataset_providers.Feature(test_utils.sentencepiece_vocab()),
"targets":
dataset_providers.Feature(test_utils.sentencepiece_vocab())
},
metric_fns=[predict_metric_fn_with_types])
self.assertSameElements([predict_metric_fn_with_types],
valid_task_with_types.metric_fns)
# pylint:enable=unused-argument
def test_no_tfds_version(self):
with self.assertRaisesWithLiteralMatch(
ValueError, "TFDS name must contain a version number, got: fake"):
dataset_providers.TfdsDataSource(tfds_name="fake")
def test_tfds_splits(self):
self.assertSameElements(
["train", "validation"],
dataset_providers.TfdsDataSource(tfds_name="fake:0.0.0").splits)
self.assertSameElements(
["validation"],
dataset_providers.TfdsDataSource(
tfds_name="fake:0.0.0", splits=["validation"]).splits)
self.assertSameElements(
["validation"],
dataset_providers.TfdsDataSource(
tfds_name="fake:0.0.0", splits={"validation": "train"}).splits)
def test_tfds_task(self):
self.verify_task_matches_fake_datasets(
"tfds_task", use_cached=False)
def test_function_task(self):
self.verify_task_matches_fake_datasets(
"function_task", use_cached=False)
def test_text_line_task(self):
self.verify_task_matches_fake_datasets(
"text_line_task", use_cached=False, splits=["train"])
def test_tf_example_task(self):
self.verify_task_matches_fake_datasets(
"tf_example_task", use_cached=False, splits=["train"])
@mock.patch.object(tf.io.gfile, "glob")
def test_file_data_source_shuffle_buffer_low(self, mock_glob):
mock_glob.return_value = [f"{i}" for i in range(20)]
fds = dataset_providers.FileDataSource(
read_file_fn=lambda x: tf.data.Dataset.from_tensor_slices([x]),
split_to_filepattern={"train": "filepattern"},
file_shuffle_buffer_size=2)
for _ in range(10):
ds = [
d.decode() for d in tfds.as_numpy(
fds.get_dataset("train", shuffle=True, seed=23))
]
self.assertListEqual(
ds,
[ # Not a great shuffle.
"0", "2", "1", "4", "5", "3", "7", "6", "9", "10", "11", "8",
"13", "14", "12", "16", "15", "18", "17", "19"
])
@mock.patch.object(tf.io.gfile, "glob")
def test_file_data_source_shuffle_buffer_full(self, mock_glob):
mock_glob.return_value = [f"{i}" for i in range(20)]
fds = dataset_providers.FileDataSource(
read_file_fn=lambda x: tf.data.Dataset.from_tensor_slices([x]),
split_to_filepattern={"train": "filepattern"},
file_shuffle_buffer_size=None)
for _ in range(10):
ds = [
d.decode() for d in tfds.as_numpy(
fds.get_dataset("train", shuffle=True, seed=23))
]
self.assertListEqual(
ds,
[ # Good shuffle.
"2", "13", "12", "19", "15", "5", "9", "1", "6", "8", "3", "0",
"10", "4", "14", "7", "16", "17", "18", "11"
])
def _get_preps_with_cache_placeholder_buffer_size(self, buffer_size):
preps = list(self.DEFAULT_PREPROCESSORS)
for i, p in enumerate(preps):
if isinstance(p, dataset_providers.CacheDatasetPlaceholder):
preps[i] = dataset_providers.CacheDatasetPlaceholder(
file_shuffle_buffer_size=buffer_size)
return preps
def _mock_and_assert_cached_source(self, task_name, buffer_size):
cached_task = dataset_providers.get_mixture_or_task(task_name)
cached_task._get_cached_source = mock.MagicMock(
side_effect=cached_task._get_cached_source)
_ = cached_task.get_dataset(None, "train", use_cached=True)
cached_task._get_cached_source.assert_called_once_with(
"train", buffer_size)
def test_cached_data_source_shuffle_buffer_default(self):
self._mock_and_assert_cached_source("cached_task", None)
def test_cached_data_source_shuffle_buffer_set(self):
self.add_task("cached_task_buf_2", self.tfds_source,
self._get_preps_with_cache_placeholder_buffer_size(2))
shutil.copytree(self.cached_task_dir,
os.path.join(self.test_data_dir, "cached_task_buf_2"))
self._mock_and_assert_cached_source("cached_task_buf_2", 2)
def test_cached_data_source_shuffle_buffer_None(self):
self.add_task("cached_task_buf_None", self.tfds_source,
self._get_preps_with_cache_placeholder_buffer_size(None))
shutil.copytree(self.cached_task_dir,
os.path.join(self.test_data_dir, "cached_task_buf_None"))
self._mock_and_assert_cached_source("cached_task_buf_None", None)
def test_proto_task(self):
self.verify_task_matches_fake_datasets(
"proto_task", use_cached=False, splits=["train"])
def test_num_input_examples(self):
self.assertEqual(30, self.cached_task.num_input_examples("train"))
self.assertEqual(10, self.cached_task.num_input_examples("validation"))
def test_disallow_shuffle(self):
task = dataset_providers.Task(
"no_shuffle",
source=self.function_source,
output_features=self.DEFAULT_OUTPUT_FEATURES,
preprocessors=self.DEFAULT_PREPROCESSORS,
shuffle_buffer_size=None)
with self.assertRaisesWithLiteralMatch(
ValueError, "Shuffling is disallowed for Task 'no_shuffle' since its "
"`shuffle_buffer_size` was set to `None` on construction."):
task.get_dataset(None, shuffle=True)
with self.assertRaisesWithLiteralMatch(
ValueError, "Shuffling is disallowed for Task 'no_shuffle' since its "
"`shuffle_buffer_size` was set to `None` on construction."):
task.get_dataset(None, shuffle=True, shuffle_buffer_size=100)
task.get_dataset(None, shuffle=False)
def test_supports_caching(self):
self.assertFalse(
dataset_providers.Task(
"nosupports_cache",
source=self.function_source,
output_features=self.DEFAULT_OUTPUT_FEATURES,
preprocessors=[]).supports_caching)
self.assertFalse(
dataset_providers.Task(
"nosupports_cache",
source=self.function_source,
output_features=self.DEFAULT_OUTPUT_FEATURES,
preprocessors=[preprocessors.tokenize]).supports_caching)
self.assertTrue(
dataset_providers.Task(
"supports_cache",
source=self.function_source,
output_features=self.DEFAULT_OUTPUT_FEATURES,
preprocessors=[
preprocessors.tokenize,
dataset_providers.CacheDatasetPlaceholder()
]).supports_caching)
self.assertTrue(
dataset_providers.Task(
"supports_cache",
source=self.function_source,
output_features=self.DEFAULT_OUTPUT_FEATURES,
preprocessors=[
dataset_providers.CacheDatasetPlaceholder(required=True),
preprocessors.tokenize,
]).supports_caching)
self.assertTrue(
dataset_providers.Task(
"supports_cache",
source=self.function_source,
output_features=self.DEFAULT_OUTPUT_FEATURES,
preprocessors=[
dataset_providers.CacheDatasetPlaceholder(),
]).supports_caching)
def test_requires_caching(self):
self.assertFalse(
dataset_providers.Task(
"nosupports_cache",
output_features=self.DEFAULT_OUTPUT_FEATURES,
source=self.function_source,
preprocessors=[preprocessors.tokenize]).requires_caching)
self.assertFalse(
dataset_providers.Task(
"supports_cache",
output_features=self.DEFAULT_OUTPUT_FEATURES,
source=self.function_source,
preprocessors=[
preprocessors.tokenize,
dataset_providers.CacheDatasetPlaceholder()
]).requires_caching)
task = dataset_providers.Task(
"requires_cache",
output_features=self.DEFAULT_OUTPUT_FEATURES,
source=self.function_source,
preprocessors=[
dataset_providers.CacheDatasetPlaceholder(required=True),
preprocessors.tokenize,
])
self.assertTrue(task.requires_caching)
with self.assertRaisesWithLiteralMatch(
ValueError,
"Task 'requires_cache' requires caching, but was called with "
"`use_cached=False`."):
task.get_dataset({"inputs": 512, "targets": 512}, use_cached=False)
# We haven't actually cached the task, so it still fails but with a
# different error.
with self.assertRaisesWithLiteralMatch(
AssertionError,
"'requires_cache' does not exist in any of the task cache "
"directories."):
task.get_dataset({"inputs": 512, "targets": 512}, use_cached=True)
def test_datasource_prohibits_caching(self):
function_source_no_cache = dataset_providers.FunctionDataSource(
dataset_fn=test_utils.get_fake_dataset,
splits=["train", "validation"],
caching_permitted=False)
with self.assertRaisesWithLiteralMatch(
ValueError,
"Caching was requested for 'prohibits_cache', but the underlying data "
"source prohibits caching. Please remove `CacheDatasetPlaceholder` and "
"try again."
):
dataset_providers.Task(
"prohibits_cache",
output_features=self.DEFAULT_OUTPUT_FEATURES,
source=function_source_no_cache,
preprocessors=[
dataset_providers.CacheDatasetPlaceholder(required=True),
preprocessors.tokenize,
])
def test_cache_exists(self):
self.assertTrue(self.cached_task.cache_dir)
self.cached_task.assert_cached()
self.assertEqual(
os.path.join(self.test_data_dir, "cached_task"),
self.cached_task.cache_dir)
self.assertFalse(self.uncached_task.cache_dir)
with self.assertRaisesWithLiteralMatch(
AssertionError,
"'tfds_task' does not exist in any of the task cache directories."):
TaskRegistry.get("tfds_task").assert_cached()
def test_get_cached_stats(self):
expected_train_stats = {
"examples": 3,
"inputs_tokens": 36, "inputs_max_tokens": 13,
"targets_tokens": 18, "targets_max_tokens": 6}
self.assertEqual(
expected_train_stats,
self.cached_task.get_cached_stats("train"))
# Check repeated call.
self.assertEqual(
expected_train_stats,
self.cached_task.get_cached_stats("train"))
expected_validation_stats = {
"examples": 2,
"inputs_tokens": 23, "inputs_max_tokens": 12,
"targets_tokens": 36, "targets_max_tokens": 21}
self.assertEqual(
expected_validation_stats,
self.cached_task.get_cached_stats("validation"))
with self.assertRaisesWithLiteralMatch(
ValueError, "Stats do not exist for 'cached_task' split: fake"):
self.cached_task.get_cached_stats("fake")
with self.assertRaisesWithLiteralMatch(
AssertionError,
"'uncached_task' does not exist in any of the task cache directories."):
self.uncached_task.get_cached_stats("train")
def test_set_global_cache_dirs(self):
utils.set_global_cache_dirs([])
self.assertFalse(self.cached_task.cache_dir)
utils.set_global_cache_dirs([self.test_data_dir])
self.assertTrue(self.cached_task.cache_dir)
def test_get_dataset_cached(self):
self.verify_task_matches_fake_datasets(
"cached_task", use_cached=True, token_preprocessed=False)
# Test with token preprocessor.
self.cached_task._preprocessors = self.DEFAULT_PREPROCESSORS + (
test_utils.test_token_preprocessor,)
self.verify_task_matches_fake_datasets(
"cached_task", use_cached=True, token_preprocessed=True)
def test_get_dataset_onthefly(self):
self.verify_task_matches_fake_datasets(
"uncached_task", use_cached=False)
# Test with token preprocessor.
self.cached_task._preprocessors = self.DEFAULT_PREPROCESSORS + (
test_utils.test_token_preprocessor,)
self.verify_task_matches_fake_datasets(
"cached_task", use_cached=False, token_preprocessed=True)
def test_get_dataset_no_truncation(self):
self.verify_task_matches_fake_datasets(
"uncached_task", use_cached=False, sequence_length=None)
def test_sharding(self):
for i in range(3):
self.verify_task_matches_fake_datasets(
"cached_task", use_cached=False, num_shards=i,
token_preprocessed=False)
self.verify_task_matches_fake_datasets(
"cached_task", use_cached=True, num_shards=i,
token_preprocessed=False)
def test_feature_validation(self):
default_vocab = test_utils.sentencepiece_vocab()
features = {
"inputs":
dataset_providers.Feature(vocabulary=default_vocab, required=False),
"targets":
dataset_providers.Feature(vocabulary=default_vocab, required=True),
"inputs_rank2":
dataset_providers.Feature(
vocabulary=vocabularies.PassThroughVocabulary(5),
required=False,
rank=2),
"continuous_features":
dataset_providers.ContinuousFeature(
required=False,
rank=2)
}
def _materialize(output):
task = dataset_providers.Task(
"feature_validation_task",
self.function_source,
output_features=features,
preprocessors=(lambda _: tf.data.Dataset.from_tensors(output),),
metric_fns=[],
)
list(
task.get_dataset(
{"inputs": 13, "targets": 13, "inputs_rank2": 13}, "train",
use_cached=False
).as_numpy_iterator()
)
# Missing optional feature: OK
_materialize({"targets": [0]})
# Missing required feature.
with self.assertRaisesWithLiteralMatch(
ValueError,
"Task dataset is missing expected output feature after preprocessing: "
"targets"):
_materialize({"inputs": [0]})
# Wrong type.
with self.assertRaisesWithLiteralMatch(
ValueError,
"Task dataset has incorrect type for feature 'targets' after "
"preprocessing: Got string, expected int32"):
_materialize({"targets": ["wrong type"]})
# Wrong rank.
with self.assertRaisesWithLiteralMatch(
ValueError,
"Task dataset has incorrect rank for feature 'targets' after "
"preprocessing: Got 0, expected 1"):
_materialize({"targets": 0})
# Verify rank > 1 works.
_materialize({"targets": [0], "inputs_rank2": [[0, 0, 0], [0, 0, 0]]})
# Wrong rank (1 when 2 is expected).
with self.assertRaisesWithLiteralMatch(
ValueError,
"Task dataset has incorrect rank for feature 'inputs_rank2' after "
"preprocessing: Got 1, expected 2"):
_materialize({"targets": [0], "inputs_rank2": [0]})
# Test ContinuousFeature
_materialize({
"targets": [0],
"continuous_features": [[1, 1], [0, 1]]
})
def test_value_errors(self):
dataset_fn = (
lambda split, shuffle_files: tf.data.Dataset.from_tensors(["test"]))
output_features = {
"inputs": dataset_providers.Feature(test_utils.sentencepiece_vocab())
}
with self.assertRaisesWithLiteralMatch(
ValueError, "`CacheDatasetPlaceholder` can appear at most once in the "
"preprocessing pipeline. Found 2 in 'multiple_cache_placeholders'."):
dataset_providers.Task(
"multiple_cache_placeholders",
source=dataset_providers.FunctionDataSource(
dataset_fn=dataset_fn,
splits=["train", "validation"]
),
preprocessors=[
test_utils.test_text_preprocessor,
preprocessors.tokenize,
dataset_providers.CacheDatasetPlaceholder(),
test_utils.test_token_preprocessor,
dataset_providers.CacheDatasetPlaceholder()
],
output_features=output_features,
metric_fns=[])
with self.assertRaisesWithLiteralMatch(
ValueError,
"'test_token_preprocessor' has a `sequence_length` argument but occurs "
"before `CacheDatasetPlaceholder` in 'sequence_length_pre_cache'. This "
"is not allowed since the sequence length is specified at run time."):
dataset_providers.Task(
"sequence_length_pre_cache",
dataset_providers.FunctionDataSource(
dataset_fn=dataset_fn,
splits=["train"],
),
preprocessors=[
test_utils.test_text_preprocessor,
preprocessors.tokenize,
test_utils.test_token_preprocessor,
dataset_providers.CacheDatasetPlaceholder()
],
output_features=output_features,
metric_fns=[])
def test_tfds_source_splits(self):
default_splits_src = dataset_providers.TfdsDataSource("fake:0.0.0")
self.assertSameElements(["train", "validation"], default_splits_src.splits)
validation_split_src = dataset_providers.TfdsDataSource(
"fake:0.0.0", splits=["validation"])
self.assertSameElements(["validation"], validation_split_src.splits)
sliced_split_src = dataset_providers.TfdsDataSource(
"fake:0.0.0", splits={"validation": "train[0:1%]"})
self.assertSameElements(["validation"], sliced_split_src.splits)
def test_no_eos(self):
default_vocab = test_utils.sentencepiece_vocab()
features = {
"inputs":
dataset_providers.Feature(add_eos=True, vocabulary=default_vocab),
"targets":
dataset_providers.Feature(add_eos=False, vocabulary=default_vocab),
}
self.add_task("task_no_eos", self.function_source, output_features=features)
self.verify_task_matches_fake_datasets("task_no_eos", use_cached=False)
def test_dtype(self):
default_vocab = test_utils.sentencepiece_vocab()
features = {
"inputs":
# defaults to int32
dataset_providers.Feature(vocabulary=default_vocab),
"targets":
dataset_providers.Feature(dtype=tf.int64, vocabulary=default_vocab),
}
self.add_task(
"task_dtypes",
self.function_source,
preprocessors=self.DEFAULT_PREPROCESSORS + (
utils.map_over_dataset(
lambda x: {k: tf.cast(v, tf.int64) if k == "targets" else v # pylint:disable=g-long-lambda
for k, v in x.items()}
),
),
output_features=features
)
self.verify_task_matches_fake_datasets("task_dtypes", use_cached=False)
def test_num_epochs(self):
# Try repeating after preprocessing the dataset to verify the outputs are
# the same.
epoch1_ds = self.random_task.get_dataset(
{"inputs": 13, "targets": 13},
split="train", use_cached=False, shuffle=True, seed=0)
# `random_task` has 3 examples per epoch.
epoch2_ds = self.random_task.get_dataset(
{"inputs": 13, "targets": 13},
split="train", use_cached=False, shuffle=True, seed=0
).repeat(2).skip(3)
test_utils.assert_datasets_eq(epoch1_ds, epoch2_ds)
# Try repeating before preprocessing the dataset to verify the outputs are
# different.
epoch1_ds = self.random_task.get_dataset(
{"inputs": 13, "targets": 13},
split="train", use_cached=False, shuffle=True, seed=0)
# `random_task` has 3 examples per epoch.
epoch2_ds = self.random_task.get_dataset(
{"inputs": 13, "targets": 13},
split="train", use_cached=False, shuffle=True, seed=0, num_epochs=2
).skip(3)
test_utils.assert_datasets_neq(epoch1_ds, epoch2_ds)
def test_same_seeds_cached_match(self):
dataset1 = self.cached_task.get_dataset(
{"inputs": 13, "targets": 13},
split="train", use_cached=True, shuffle=True, seed=0)
dataset2 = self.cached_task.get_dataset(
{"inputs": 13, "targets": 13},
split="train", use_cached=True, shuffle=True, seed=0)
test_utils.assert_datasets_eq(dataset1, dataset2)
def test_different_seeds_cached_mismatch(self):
dataset1 = self.cached_task.get_dataset(
{"inputs": 13, "targets": 13},
split="train", use_cached=True, shuffle=True, seed=0)
dataset2 = self.cached_task.get_dataset(
{"inputs": 13, "targets": 13},
split="train", use_cached=True, shuffle=True, seed=42)
test_utils.assert_datasets_neq(dataset1, dataset2)
def test_same_seeds_uncached_match(self):
dataset1 = self.uncached_task.get_dataset(
{"inputs": 13, "targets": 13},
split="train", use_cached=False, shuffle=True, seed=0)
dataset2 = self.uncached_task.get_dataset(
{"inputs": 13, "targets": 13},
split="train", use_cached=False, shuffle=True, seed=0)
test_utils.assert_datasets_eq(dataset1, dataset2)
def test_different_seeds_uncached_mismatch(self):
dataset1 = self.uncached_task.get_dataset(
{"inputs": 13, "targets": 13},
split="train", use_cached=False, shuffle=True, seed=0)
dataset2 = self.uncached_task.get_dataset(
{"inputs": 13, "targets": 13},
split="train", use_cached=False, shuffle=True, seed=42)
test_utils.assert_datasets_neq(dataset1, dataset2)
def test_same_seeds_random_tp_uncached_match(self):
dataset1 = self.random_task.get_dataset(
{"inputs": 13, "targets": 13},
split="train", use_cached=False, shuffle=True, seed=0).repeat(4)
dataset2 = self.random_task.get_dataset(
{"inputs": 13, "targets": 13},
split="train", use_cached=False, shuffle=True, seed=0).repeat(4)
test_utils.assert_datasets_eq(dataset1, dataset2)
def test_different_seeds_random_tp_uncached_mismatch(self):
dataset1 = self.random_task.get_dataset(
{"inputs": 13, "targets": 13},
split="train", use_cached=False, shuffle=True, seed=0)
dataset2 = self.random_task.get_dataset(
{"inputs": 13, "targets": 13},
split="train", use_cached=False, shuffle=True, seed=42)
test_utils.assert_datasets_neq(dataset1, dataset2)
def test_no_shuffle_with_seed_cached_match(self):
dataset1 = self.cached_task.get_dataset(
{"inputs": 13, "targets": 13},
split="train", use_cached=True, shuffle=False, seed=0)
dataset2 = self.cached_task.get_dataset(
{"inputs": 13, "targets": 13},
split="train", use_cached=True, shuffle=False, seed=42)
test_utils.assert_datasets_eq(dataset1, dataset2)
def test_no_shuffle_with_seed_uncached_match(self):
dataset1 = self.uncached_task.get_dataset(
{"inputs": 13, "targets": 13},
split="train", use_cached=False, shuffle=False, seed=0)
dataset2 = self.uncached_task.get_dataset(
{"inputs": 13, "targets": 13},
split="train", use_cached=False, shuffle=False, seed=42)
test_utils.assert_datasets_eq(dataset1, dataset2)
def test_no_shuffle_different_seeds_random_tp_uncached_mismatch(self):
dataset1 = self.random_task.get_dataset(
{"inputs": 13, "targets": 13},
split="train", use_cached=False, shuffle=False, seed=0)
dataset2 = self.random_task.get_dataset(
{"inputs": 13, "targets": 13},
split="train", use_cached=False, shuffle=False, seed=42)
test_utils.assert_datasets_neq(dataset1, dataset2)
def test_plaintext_to_pretokenized_rename(self):
ds = self.cached_plaintext_task.get_dataset(
{"inputs": 13, "targets": 13},
split="train", use_cached=True, shuffle=False)
keys = next(ds.as_numpy_iterator()).keys()
self.assertSetEqual(
set(keys),
set(["inputs", "inputs_pretokenized",
"targets", "targets_pretokenized"]))
def test_list_shards(self):
def _get_formatted_shards_list(task_name, split):
shards = dataset_providers.get_mixture_or_task(
task_name).source.list_shards(split)
shards = [s.split("/")[-1] for s in shards]
return sorted(shards)
self.assertListEqual(
_get_formatted_shards_list("tfds_task", "train"),
["train.tfrecord-00000-of-00002", "train.tfrecord-00001-of-00002"])
self.assertListEqual(
_get_formatted_shards_list("text_line_task", "train"),
["train.tsv-00000-of-00002", "train.tsv-00001-of-00002"])
self.assertListEqual(
_get_formatted_shards_list("tf_example_task", "train"),
["train.tfrecord-00000-of-00002", "train.tfrecord-00001-of-00002"])
self.assertListEqual(
_get_formatted_shards_list("proto_task", "train"),
["train.tfrecord-00000-of-00002", "train.tfrecord-00001-of-00002"])
self.assertListEqual(
_get_formatted_shards_list("function_task", "train"), ["train"])
self.assertListEqual(
_get_formatted_shards_list("fully_processed_precache", "train"),
["train"])
self.assertListEqual(
_get_formatted_shards_list("tokenized_postcache", "train"), ["train"])
self.assertListEqual(
_get_formatted_shards_list("random_task", "train"), ["train"])
self.assertListEqual(
_get_formatted_shards_list("uncached_task", "train"),
["train.tfrecord-00000-of-00002", "train.tfrecord-00001-of-00002"])
self.assertListEqual(
_get_formatted_shards_list("cached_task", "train"),
["train.tfrecord-00000-of-00002", "train.tfrecord-00001-of-00002"])
self.assertListEqual(
_get_formatted_shards_list("cached_plaintext_task", "train"),
["train.tfrecord-00000-of-00002", "train.tfrecord-00001-of-00002"])
class MixturesTest(test_utils.FakeTaskTest):
def test_tasks(self):
self.add_task("task1", self.function_source)
self.add_task("task2", self.function_source)
MixtureRegistry.add("test_mix1", [("task1", 1), ("task2", 1)])
mix = MixtureRegistry.get("test_mix1")
self.assertEqual(len(mix.tasks), 2)
for task in mix.tasks:
self.verify_task_matches_fake_datasets(task.name, use_cached=False)
self.assertEqual(mix.get_rate(task), 1)
def test_num_examples(self):
MixtureRegistry.add("test_mix2", [(self.cached_task.name, 1)])
mix = MixtureRegistry.get("test_mix2")
self.assertEqual(mix.num_input_examples(split="train"), 30)
def test_splits(self):
MixtureRegistry.add(
"test_mix",
[(self.cached_task.name, 1), (self.uncached_task.name, 1)]
)
mix = MixtureRegistry.get("test_mix")
self.assertSameElements(["train", "validation"], mix.splits, 30)
def test_get_dataset(self):
MixtureRegistry.add("test_mix3", [(self.cached_task.name, 1)])
task_ds = TaskRegistry.get_dataset(
self.cached_task.name, {
"inputs": 13,
"targets": 13
},
"validation",
use_cached=False,
shuffle=False)
mix_ds = MixtureRegistry.get("test_mix3").get_dataset(
{
"inputs": 13,
"targets": 13
}, "validation", use_cached=False, shuffle=False)
# mix.get_dataset strips non-output features
task_ds = task_ds.map(lambda x: {k: x[k] for k in ["inputs", "targets"]})
# limit size since get_dataset repeats the dataset
test_utils.assert_datasets_eq(task_ds.repeat(2), mix_ds.take(4))
def test_get_dataset_mix(self):
@utils.map_over_dataset
def _constant_preprocessor(unused_x, val):
return {
"targets": tf.constant([val], tf.int32),
"inputs": tf.constant([val], tf.int32),
}
self.add_task(
"two_task",
self.function_source,
preprocessors=(functools.partial(_constant_preprocessor, val=2),)
)
self.add_task(
"three_task",
self.function_source,
preprocessors=(functools.partial(_constant_preprocessor, val=3),)
)
MixtureRegistry.add("test_mix", [("two_task", 1), ("three_task", 1)])
sequence_length = {"inputs": 2, "targets": 2}
mix_ds = MixtureRegistry.get("test_mix").get_dataset(
sequence_length, "train", seed=13).take(1000)
res = sum(int(item["inputs"][0]) for item in mix_ds.as_numpy_iterator())
self.assertEqual(res, 2481)
def test_get_dataset_passthrough_features(self):
@utils.map_over_dataset
def _constant_feature_preprocessor(unused_x, val):
return {
"targets": tf.constant([val], tf.int32),
"inputs": tf.constant([val], tf.int32),
"feature": tf.constant([val], tf.int32),
}
self.add_task(
"two_task",
self.function_source,
preprocessors=(functools.partial(_constant_feature_preprocessor,
val=2),))
self.add_task(
"three_task",
self.function_source,
preprocessors=(functools.partial(_constant_feature_preprocessor,
val=3),))
MixtureRegistry.add("test_mix", [("two_task", 1), ("three_task", 1)])
sequence_length = {"inputs": 2, "targets": 2}
passthrough_features = ["feature"]
mix_ds = MixtureRegistry.get("test_mix").get_dataset(
sequence_length,
"train",
seed=13,
passthrough_features=passthrough_features).take(1000)
# output features are defined as "inputs" and "targets" by default.
res = sum(int(item["feature"][0]) for item in mix_ds.as_numpy_iterator())
self.assertEqual(res, 2481)
def test_copy_pretokenized(self):
@utils.map_over_dataset
def _constant_preprocessor(unused_x, val):
return {
"targets": tf.constant([val], tf.int32),
"targets_pretokenized": tf.constant(f"targets_{val}"),
"inputs": tf.constant([val], tf.int32),
"inputs_pretokenized": tf.constant(f"inputs_{val}")
}
self.add_task(
"two_task",
self.function_source,
preprocessors=(functools.partial(_constant_preprocessor, val=2),)
)
self.add_task(
"three_task",
self.function_source,
preprocessors=(functools.partial(_constant_preprocessor, val=3),)
)
MixtureRegistry.add("test_mix", [("two_task", 1), ("three_task", 1)])
sequence_length = {"inputs": 2, "targets": 2}
mix_ds = MixtureRegistry.get("test_mix").get_dataset(
sequence_length, "train", seed=13, copy_pretokenized=True).take(1000)
inputs_pretokenized = set(
ex["inputs_pretokenized"] for ex in mix_ds.as_numpy_iterator())
targets_pretokenized = set(
ex["targets_pretokenized"] for ex in mix_ds.as_numpy_iterator())
self.assertCountEqual([b"inputs_2", b"inputs_3"], inputs_pretokenized)
self.assertCountEqual([b"targets_2", b"targets_3"], targets_pretokenized)
mix_ds = MixtureRegistry.get("test_mix").get_dataset(
sequence_length, "train", seed=13, copy_pretokenized=False).take(1000)
for ex in mix_ds.as_numpy_iterator():
self.assertNoCommonElements(
["inputs_pretokenized", "targets_pretokenized"], ex.keys())
def test_get_rate_with_callable(self):
def fn(t):
self.assertEqual(t.name, "task4")
return 42
self.add_task("task4", self.function_source)
task = TaskRegistry.get("task4")
MixtureRegistry.add("test_mix5", [("task4", fn)])
mix = MixtureRegistry.get("test_mix5")
self.assertEqual(mix.get_rate(task), 42)
def test_mixture_of_mixtures(self):
self.add_task("task_a", self.function_source)
self.add_task("task_b", self.function_source)
self.add_task("task_c", self.function_source)
MixtureRegistry.add("another_mix", [("task_a", 1), ("task_b", 1)])
MixtureRegistry.add("supermix", [("another_mix", 1), ("task_c", 1)])
supermix = MixtureRegistry.get("supermix")
names = [task.name for task in supermix.tasks]
self.assertEqual(names, ["task_a", "task_b", "task_c"])
self.assertEqual([supermix.get_rate(t) for t in supermix.tasks],
[0.5, 0.5, 1])
def test_mixture_of_mixtures_dupe(self):
self.add_task("task2_a", self.function_source)
self.add_task("task2_b", self.function_source)
self.add_task("task2_c", self.function_source)
MixtureRegistry.add("yet_another_mix", [("task2_a", 1), ("task2_b", 1)])
MixtureRegistry.add("supermix_with_dupe", [("yet_another_mix", 1),
("task2_a", 1), ("task2_c", 1)])
supermix = MixtureRegistry.get("supermix_with_dupe")
names = [task.name for task in supermix.tasks]
self.assertEqual(names, ["task2_a", "task2_b", "task2_c"])
self.assertEqual([supermix.get_rate(t) for t in supermix.tasks],
[1.5, 0.5, 1])
def test_mixture_with_sample_fn(self):
def sequential_intereave(datasets: Sequence[tf.data.Dataset],
rates: Sequence[float],
sample_seed: Optional[int]) -> tf.data.Dataset:
"""Sample function that simply concatenates two datasets."""
del rates, sample_seed
return datasets[0].concatenate(datasets[1])
def gen_dataset(split,
shuffle_files=False,
seed=None,
val: str = "") -> tf.data.Dataset:
del split, shuffle_files, seed # Need this to pass arg validation.
return tf.data.Dataset.from_tensor_slices({
"inputs": [[val]] * 3,
})
# Register two very simple tasks, each with 3 repeated string values.
vocab = vocabularies.PassThroughVocabulary(0)
tasks = []
for task_name in ["first", "second"]:
tasks.append(self.add_task(
task_name,
dataset_providers.FunctionDataSource(
dataset_fn=functools.partial(gen_dataset, val=task_name),
splits=["train"]),
preprocessors=[],
output_features={
"inputs": dataset_providers.Feature(vocab, dtype=tf.string)
}))
# Verify that by default, interleaving of datasets is random.
MixtureRegistry.add("default_mix", [("first", 1), ("second", 1)])
default_ds = MixtureRegistry.get("default_mix").get_dataset(
None, "train", shuffle=False, seed=2, num_epochs=1)
expected = [b"second", b"first", b"second", b"first", b"second", b"first"]
actual = [x["inputs"] for x in default_ds.as_numpy_iterator()]
self.assertEqual(expected, actual)
# Verify that we can modify sampling function correctly.
MixtureRegistry.add(
"sequential_mix", [("first", 1), ("second", 1)],
sample_fn=sequential_intereave)
sequential_ds = MixtureRegistry.get("sequential_mix").get_dataset(
None, "train", shuffle=False, seed=2, num_epochs=1)
expected = [b"first"] * 3 + [b"second"] * 3
actual = [x["inputs"] for x in sequential_ds.as_numpy_iterator()]
self.assertEqual(expected, actual)
class GetDatasetTest(parameterized.TestCase, tf.test.TestCase):
def test_get_dataset_enc_dec_unpacked(self):
mixture_or_task_name = "enc_dec_unpacked"
x = [{"inputs": [7, 8, 5, 6, 9, 4, 3], "targets": [3, 9]},
{"inputs": [8, 4], "targets": [4]},
{"inputs": [5, 6, 7], "targets": [6, 5]}]
ds = create_default_dataset(x)
dataset_fn = lambda split, shuffle_files: ds
register_dummy_task(mixture_or_task_name, dataset_fn=dataset_fn)
task_feature_lengths = {"inputs": 7, "targets": 5}
converter = feature_converters.EncDecFeatureConverter(pack=False)
output_ds = dataset_providers.get_dataset(
mixture_or_task_name=mixture_or_task_name,
task_feature_lengths=task_feature_lengths,
dataset_split="train",
shuffle=False,
feature_converter=converter)
expected = [{
"encoder_input_tokens": [7, 8, 5, 6, 9, 4, 1],
"decoder_target_tokens": [3, 9, 1, 0, 0],
"decoder_input_tokens": [0, 3, 9, 1, 0],
"decoder_loss_weights": [1, 1, 1, 0, 0],
}, {
"encoder_input_tokens": [8, 4, 1, 0, 0, 0, 0],
"decoder_target_tokens": [4, 1, 0, 0, 0],
"decoder_input_tokens": [0, 4, 1, 0, 0],
"decoder_loss_weights": [1, 1, 0, 0, 0],
}, {
"encoder_input_tokens": [5, 6, 7, 1, 0, 0, 0],
"decoder_target_tokens": [6, 5, 1, 0, 0],
"decoder_input_tokens": [0, 6, 5, 1, 0],
"decoder_loss_weights": [1, 1, 1, 0, 0],
}]
expected_dtypes = {feat: tf.int32 for feat in expected[0].keys()}
assert_dataset(output_ds, expected, expected_dtypes=expected_dtypes)
@parameterized.parameters(
dict(
task_name="enc_dec_partial_trim_both",
task_feature_lengths={
"inputs": 7,
"targets": 2
},
expect_trim_inputs=True,
expect_trim_targets=True),
dict(
task_name="enc_dec_partial_trim_targets",
task_feature_lengths={
"inputs": None,
"targets": 2
},
expect_trim_inputs=False,
expect_trim_targets=True),
dict(
task_name="enc_dec_partial_trim_inputs",
task_feature_lengths={
"inputs": 7,
"targets": None
},
expect_trim_inputs=True,
expect_trim_targets=False),
dict(
task_name="enc_dec_partial_trim_neither",
task_feature_lengths={
"inputs": None,
"targets": None
},
expect_trim_inputs=False,
expect_trim_targets=False),
dict(
task_name="enc_dec_partial_trim_nothing",
task_feature_lengths=None,
expect_trim_inputs=False,
expect_trim_targets=False))
def test_partial_sequence_length(self, task_name, task_feature_lengths,
expect_trim_inputs, expect_trim_targets):
x = [{"inputs": [7, 8, 5, 6, 9, 4, 3], "targets": [3, 9]},
{"inputs": [8, 4], "targets": [4]},
{"inputs": [5, 6, 7], "targets": [6, 5]}]
ds = create_default_dataset(x)
dataset_fn = lambda split, shuffle_files: ds
register_dummy_task(task_name, dataset_fn=dataset_fn)
# Unlike the other tests, don't use a feature converter. Instead, test the
# task.get_dataset method directly, which is similar to how evaluation.py
# infers feature lengths w/trimming.
task = dataset_providers.get_mixture_or_task(task_name)
output_ds = task.get_dataset(
sequence_length=task_feature_lengths,
shuffle=False)
expected = [{
"inputs": [7, 8, 5, 6, 9, 4, 3, 1],
"targets": [3, 9, 1],
}, {
"inputs": [8, 4, 1],
"targets": [4, 1],
}, {
"inputs": [5, 6, 7, 1],
"targets": [6, 5, 1],
}]
if expect_trim_inputs:
expected[0]["inputs"] = [7, 8, 5, 6, 9, 4, 1]
if expect_trim_targets:
expected[0]["targets"] = [3, 1]
expected[2]["targets"] = [6, 1]
expected_dtypes = {feat: tf.int32 for feat in expected[0].keys()}
assert_dataset(output_ds, expected, expected_dtypes=expected_dtypes)
@parameterized.parameters(
dict(
task_name="enc_dec_multidim_trim_both",
task_feature_lengths={
"inputs": (2, 5),
"targets": 2
},
expect_trim_inputs=True,
expect_trim_targets=True,
),
dict(
task_name="enc_dec_multidim_trim_inputs",
task_feature_lengths={
"inputs": (2, 5),
"targets": None
},
expect_trim_inputs=True,
expect_trim_targets=False,
),
dict(
task_name="enc_dec_multidim_trim_targets",
task_feature_lengths={
"inputs": None,
"targets": 2
},
expect_trim_inputs=False,
expect_trim_targets=True,
),
dict(
task_name="enc_dec_no_multidim_trim",
task_feature_lengths={
"inputs": None,
"targets": None
},
expect_trim_inputs=False,
expect_trim_targets=False
)
)
def test_multidimension_sequence_length(self,
task_name,
task_feature_lengths,
expect_trim_inputs,
expect_trim_targets):
x = [{"inputs": [[7, 8, 5, 6, 9, 4, 3],
[2, 3, 4, 5, 0, 0, 0],
[6, 7, 1, 0, 0, 0, 0]],
"targets": [3, 9]},
{"inputs": [[8, 4],
[1, 0],
[2, 3]],
"targets": [4]},
{"inputs": [[5, 6, 7]],
"targets": [6, 5, 1]},
{"inputs": [[7, 8, 9, 1, 2, 3, 4, 5, 6]],
"targets": [10, 11, 1]}]
ds = tf.data.Dataset.from_generator(
lambda: x,
output_types={"inputs": tf.int32, "targets": tf.int32},
output_shapes={"inputs": (None, None), "targets": (None,)})
dataset_fn = lambda split, shuffle_files: ds
dataset_providers.TaskRegistry.add(
task_name,
source=dataset_providers.FunctionDataSource(
dataset_fn=dataset_fn, splits=["train", "validation"]),
preprocessors=[
dataset_providers.CacheDatasetPlaceholder(),
],
output_features={
"inputs": dataset_providers.Feature(
test_utils.sentencepiece_vocab(), rank=2),
"targets": dataset_providers.Feature(
test_utils.sentencepiece_vocab())
},
metric_fns=[])
# Unlike the other tests, don't use a feature converter. Instead, test the
# task.get_dataset method directly, which is similar to how evaluation.py
# infers feature lengths w/trimming.
task = dataset_providers.get_mixture_or_task(task_name)
output_ds = task.get_dataset(
sequence_length=task_feature_lengths,
shuffle=False)
expected = copy.deepcopy(x)
if expect_trim_inputs:
expected[0]["inputs"] = [[7, 8, 5, 6, 9],
[2, 3, 4, 5, 0]]
expected[1]["inputs"] = [[8, 4],
[1, 0]]
expected[3]["inputs"] = [[7, 8, 9, 1, 2]]
if expect_trim_targets:
expected[2]["targets"] = [6, 5]
expected[3]["targets"] = [10, 11]
expected_dtypes = {feat: tf.int32 for feat in expected[0].keys()}
assert_dataset(output_ds, expected, expected_dtypes=expected_dtypes)
def test_get_dataset_enc_dec_packed(self):
mixture_or_task_name = "enc_dec_packed"
x = [{"inputs": [7, 8, 5, 6, 9, 4, 3], "targets": [3, 9]},
{"inputs": [8, 4], "targets": [4]},
{"inputs": [5, 6, 7], "targets": [6, 5]}]
ds = create_default_dataset(x)
dataset_fn = lambda split, shuffle_files: ds
register_dummy_task(mixture_or_task_name, dataset_fn=dataset_fn)
task_feature_lengths = {"inputs": 7, "targets": 5}
converter = feature_converters.EncDecFeatureConverter(pack=True)
output_ds = dataset_providers.get_dataset(
mixture_or_task_name=mixture_or_task_name,
task_feature_lengths=task_feature_lengths,
dataset_split="train",
shuffle=False,
feature_converter=converter)
expected = [{
# Example 1 is trimmed
"encoder_input_tokens": [7, 8, 5, 6, 9, 4, 1],
"encoder_segment_ids": [1, 1, 1, 1, 1, 1, 1],
"encoder_positions": [0, 1, 2, 3, 4, 5, 6],
"decoder_target_tokens": [3, 9, 1, 0, 0],
"decoder_input_tokens": [0, 3, 9, 0, 0],
"decoder_loss_weights": [1, 1, 1, 0, 0],
"decoder_segment_ids": [1, 1, 1, 0, 0],
"decoder_positions": [0, 1, 2, 0, 0],
}, {
# Example 2 and 3 are packed together
"encoder_input_tokens": [8, 4, 1, 5, 6, 7, 1],
"encoder_segment_ids": [1, 1, 1, 2, 2, 2, 2],
"encoder_positions": [0, 1, 2, 0, 1, 2, 3],
"decoder_target_tokens": [4, 1, 6, 5, 1],
"decoder_input_tokens": [0, 4, 0, 6, 5],
"decoder_loss_weights": [1, 1, 1, 1, 1],
"decoder_segment_ids": [1, 1, 2, 2, 2],
"decoder_positions": [0, 1, 0, 1, 2],
}]
expected_dtypes = {feat: tf.int32 for feat in expected[0].keys()}
assert_dataset(output_ds, expected, expected_dtypes=expected_dtypes)
def test_get_dataset_both_train_and_validation_splits(self):
mixture_or_task_name = "both_train_and_validation_splits"
x_train = [{"inputs": [7, 8, 5, 6, 9, 4, 3], "targets": [3, 9]}]
x_val = [{"inputs": [8, 4], "targets": [4]}]
datasets = {
"train": create_default_dataset(x_train),
"validation": create_default_dataset(x_val)
}
dataset_fn = lambda split, shuffle_files: datasets[split]
register_dummy_task(mixture_or_task_name, dataset_fn=dataset_fn)
task_feature_lengths = {"inputs": 7, "targets": 5}
output_ds = {}
for split in ["train", "validation"]:
converter = feature_converters.EncDecFeatureConverter(pack=False)
output_ds[split] = dataset_providers.get_dataset(
mixture_or_task_name=mixture_or_task_name,
task_feature_lengths=task_feature_lengths,
dataset_split=split,
shuffle=False,
feature_converter=converter)
expected_train = {
"encoder_input_tokens": [7, 8, 5, 6, 9, 4, 1],
"decoder_target_tokens": [3, 9, 1, 0, 0],
"decoder_input_tokens": [0, 3, 9, 1, 0],
"decoder_loss_weights": [1, 1, 1, 0, 0],
}
expected_val = {
"encoder_input_tokens": [8, 4, 1, 0, 0, 0, 0],
"decoder_target_tokens": [4, 1, 0, 0, 0],
"decoder_input_tokens": [0, 4, 1, 0, 0],
"decoder_loss_weights": [1, 1, 0, 0, 0],
}
expected_dtypes = {feat: tf.int32 for feat in expected_train.keys()}
assert_dataset(
output_ds["train"], expected_train, expected_dtypes=expected_dtypes)
assert_dataset(
output_ds["validation"], expected_val, expected_dtypes=expected_dtypes)
def test_get_dataset_enc_dec_sharded(self):
mixture_or_task_name = "enc_dec_sharded"
x = [{"inputs": [7, 8, 5, 6, 9, 4, 3], "targets": [3, 9]},
{"inputs": [8, 4], "targets": [4]},
{"inputs": [5, 6, 7], "targets": [6, 5]}]
ds = create_default_dataset(x)
dataset_fn = lambda split, shuffle_files: ds
register_dummy_task(mixture_or_task_name, dataset_fn=dataset_fn)
task_feature_lengths = {"inputs": 7, "targets": 5}
converter = feature_converters.EncDecFeatureConverter(pack=False)
shard_info = dataset_providers.ShardInfo(index=0, num_shards=2)
output_ds = dataset_providers.get_dataset(
mixture_or_task_name=mixture_or_task_name,
task_feature_lengths=task_feature_lengths,
dataset_split="train",
shuffle=False,
feature_converter=converter,
shard_info=shard_info)
# Example index 1 should not be present in the sharded dataset.
expected = [{
"encoder_input_tokens": [7, 8, 5, 6, 9, 4, 1],
"decoder_target_tokens": [3, 9, 1, 0, 0],
"decoder_input_tokens": [0, 3, 9, 1, 0],
"decoder_loss_weights": [1, 1, 1, 0, 0],
}, {
"encoder_input_tokens": [5, 6, 7, 1, 0, 0, 0],
"decoder_target_tokens": [6, 5, 1, 0, 0],
"decoder_input_tokens": [0, 6, 5, 1, 0],
"decoder_loss_weights": [1, 1, 1, 0, 0],
}]
expected_dtypes = {feat: tf.int32 for feat in expected[0].keys()}
assert_dataset(output_ds, expected, expected_dtypes=expected_dtypes)
def test_get_dataset_enc_dec_sharded_and_packed(self):
mixture_or_task_name = "enc_dec_sharded_and_packed"
x = [{"inputs": [7, 8], "targets": [3, 9]},
{"inputs": [8, 4], "targets": [4]},
{"inputs": [5, 6, 7], "targets": [6]}]
ds = create_default_dataset(x)
dataset_fn = lambda split, shuffle_files: ds
register_dummy_task(mixture_or_task_name, dataset_fn=dataset_fn)
task_feature_lengths = {"inputs": 7, "targets": 5}
converter = feature_converters.EncDecFeatureConverter(pack=True)
shard_info = dataset_providers.ShardInfo(index=0, num_shards=2)
output_ds = dataset_providers.get_dataset(
mixture_or_task_name=mixture_or_task_name,
task_feature_lengths=task_feature_lengths,
dataset_split="train",
shuffle=False,
feature_converter=converter,
shard_info=shard_info)
# Packing should be done after the sharding.
expected = {
"encoder_input_tokens": [7, 8, 1, 5, 6, 7, 1],
"encoder_segment_ids": [1, 1, 1, 2, 2, 2, 2],
"encoder_positions": [0, 1, 2, 0, 1, 2, 3],
"decoder_target_tokens": [3, 9, 1, 6, 1],
"decoder_input_tokens": [0, 3, 9, 0, 6],
"decoder_loss_weights": [1, 1, 1, 1, 1],
"decoder_segment_ids": [1, 1, 1, 2, 2],
"decoder_positions": [0, 1, 2, 0, 1],
}
expected_dtypes = {feat: tf.int32 for feat in expected.keys()}
assert_dataset(output_ds, expected, expected_dtypes=expected_dtypes)
def register_dummy_task(
task_name: str,
dataset_fn: Callable[[str, str], tf.data.Dataset],
output_feature_names: Sequence[str] = ("inputs", "targets")) -> None:
"""Register a dummy task for GetDatasetTest."""
dataset_providers.TaskRegistry.add(
task_name,
source=dataset_providers.FunctionDataSource(
dataset_fn=dataset_fn, splits=["train", "validation"]),
preprocessors=[
dataset_providers.CacheDatasetPlaceholder(),
preprocessors.append_eos_after_trim,
],
output_features={
feat: dataset_providers.Feature(test_utils.sentencepiece_vocab())
for feat in output_feature_names
},
metric_fns=[])
if __name__ == "__main__":
absltest.main()
| 38.483539 | 107 | 0.647989 |
import copy
import functools
import os
import shutil
from typing import Any, Callable, Mapping, Optional, Sequence
from absl.testing import absltest
from absl.testing import parameterized
from seqio import dataset_providers
from seqio import feature_converters
from seqio import metrics as metrics_lib
from seqio import preprocessors
from seqio import test_utils
from seqio import utils
from seqio import vocabularies
import tensorflow.compat.v2 as tf
import tensorflow_datasets as tfds
tf.compat.v1.enable_eager_execution()
TaskRegistry = dataset_providers.TaskRegistry
MixtureRegistry = dataset_providers.MixtureRegistry
mock = absltest.mock
assert_dataset = test_utils.assert_dataset
create_default_dataset = test_utils.create_default_dataset
class TasksTest(test_utils.FakeTaskTest):
def test_invalid_name(self):
with self.assertRaisesRegex(
ValueError,
"Task name 'invalid/name' contains invalid characters. "
"Must match regex: .*"):
self.add_task("invalid/name", self.function_source)
def test_repeat_name(self):
with self.assertRaisesWithLiteralMatch(
ValueError,
"Attempting to register duplicate provider: text_line_task"):
self.add_task("text_line_task", self.text_line_source)
def test_function_source_signature(self):
def good_fn(split, shuffle_files):
del split
del shuffle_files
dataset_providers.FunctionDataSource(good_fn, splits=("train",))
def default_good_fn(split, shuffle_files=False):
del split
del shuffle_files
dataset_providers.FunctionDataSource(default_good_fn, splits=("train",))
def seed_fn(split, shuffle_files=True, seed=0):
del split
del shuffle_files
del seed
dataset_providers.FunctionDataSource(seed_fn, splits=("train",))
def extra_kwarg_good_fn(split, shuffle_files, unused_kwarg=True):
del split
del shuffle_files
dataset_providers.FunctionDataSource(extra_kwarg_good_fn, splits=("train",))
with self.assertRaisesWithLiteralMatch(
ValueError,
"'missing_shuff' must have positional args ('split', 'shuffle_files'), "
"got: ('split',)"):
def missing_shuff(split):
del split
dataset_providers.FunctionDataSource(missing_shuff, splits=("train",))
with self.assertRaisesWithLiteralMatch(
ValueError,
"'missing_split' must have positional args ('split', 'shuffle_files'), "
"got: ('shuffle_files',)"):
def missing_split(shuffle_files):
del shuffle_files
dataset_providers.FunctionDataSource(missing_split, splits=("train",))
with self.assertRaisesWithLiteralMatch(
ValueError,
"'extra_pos_arg' may only have positional args ('split', "
"'shuffle_files'), got: ('split', 'shuffle_files', 'unused_arg')"):
def extra_pos_arg(split, shuffle_files, unused_arg):
del split
del shuffle_files
dataset_providers.FunctionDataSource(extra_pos_arg, splits=("train",))
def test_metric_fn_signature(self):
add_task = functools.partial(self.add_task, source=self.function_source)
def score_metric_fn(targets, scores):
return {}
def predict_metric_fn(targets, predictions):
return {}
valid_task = add_task(
"valid_metrics", metric_fns=[score_metric_fn, predict_metric_fn])
self.assertSameElements(
[score_metric_fn, predict_metric_fn], valid_task.metric_fns)
self.assertSameElements(
[score_metric_fn], valid_task.score_metric_fns)
self.assertSameElements(
[predict_metric_fn], valid_task.predict_metric_fns)
def extra_arg_metric_fn(targets, predictions, extra_param):
return {}
expected_error_message_prefix = (
"Metric functions must have positional arguments matching either "
"('targets', 'predictions') or ('targets', 'scores'). Got: ")
with self.assertRaisesWithLiteralMatch(
ValueError,
expected_error_message_prefix +
"('targets', 'predictions', 'extra_param')"):
valid_task = add_task(
"extra_arg_metric", metric_fns=[extra_arg_metric_fn])
def bad_order_metric_fn(predictions, targets):
return {}
with self.assertRaisesWithLiteralMatch(
ValueError,
expected_error_message_prefix + "('predictions', 'targets')"):
valid_task = add_task(
"bad_order_metric", metric_fns=[bad_order_metric_fn])
def bad_default_metric_fn(targets, predictions=(0)):
return {}
with self.assertRaisesWithLiteralMatch(
ValueError,
expected_error_message_prefix + "('targets',)"):
valid_task = add_task(
"bad_default_metric", metric_fns=[bad_default_metric_fn])
def ok_default_metric_fn(targets, predictions, extra_param=3):
return {}
valid_task_2 = add_task(
"valid_metrics_2", metric_fns=[ok_default_metric_fn])
self.assertSameElements([ok_default_metric_fn], valid_task_2.metric_fns)
self.assertEmpty(valid_task_2.score_metric_fns)
self.assertSameElements(
[ok_default_metric_fn], valid_task_2.predict_metric_fns)
def predict_metric_fn_with_types(
targets: Sequence[Mapping[str,
Any]], predictions: Sequence[Mapping[str,
Any]]
) -> Mapping[str, metrics_lib.MetricValue]:
return {}
valid_task_with_types = TaskRegistry.add(
"valid_metrics_with_types",
source=self.function_source,
output_features={
"inputs":
dataset_providers.Feature(test_utils.sentencepiece_vocab()),
"targets":
dataset_providers.Feature(test_utils.sentencepiece_vocab())
},
metric_fns=[predict_metric_fn_with_types])
self.assertSameElements([predict_metric_fn_with_types],
valid_task_with_types.metric_fns)
def test_no_tfds_version(self):
with self.assertRaisesWithLiteralMatch(
ValueError, "TFDS name must contain a version number, got: fake"):
dataset_providers.TfdsDataSource(tfds_name="fake")
def test_tfds_splits(self):
self.assertSameElements(
["train", "validation"],
dataset_providers.TfdsDataSource(tfds_name="fake:0.0.0").splits)
self.assertSameElements(
["validation"],
dataset_providers.TfdsDataSource(
tfds_name="fake:0.0.0", splits=["validation"]).splits)
self.assertSameElements(
["validation"],
dataset_providers.TfdsDataSource(
tfds_name="fake:0.0.0", splits={"validation": "train"}).splits)
def test_tfds_task(self):
self.verify_task_matches_fake_datasets(
"tfds_task", use_cached=False)
def test_function_task(self):
self.verify_task_matches_fake_datasets(
"function_task", use_cached=False)
def test_text_line_task(self):
self.verify_task_matches_fake_datasets(
"text_line_task", use_cached=False, splits=["train"])
def test_tf_example_task(self):
self.verify_task_matches_fake_datasets(
"tf_example_task", use_cached=False, splits=["train"])
@mock.patch.object(tf.io.gfile, "glob")
def test_file_data_source_shuffle_buffer_low(self, mock_glob):
mock_glob.return_value = [f"{i}" for i in range(20)]
fds = dataset_providers.FileDataSource(
read_file_fn=lambda x: tf.data.Dataset.from_tensor_slices([x]),
split_to_filepattern={"train": "filepattern"},
file_shuffle_buffer_size=2)
for _ in range(10):
ds = [
d.decode() for d in tfds.as_numpy(
fds.get_dataset("train", shuffle=True, seed=23))
]
self.assertListEqual(
ds,
[
"0", "2", "1", "4", "5", "3", "7", "6", "9", "10", "11", "8",
"13", "14", "12", "16", "15", "18", "17", "19"
])
@mock.patch.object(tf.io.gfile, "glob")
def test_file_data_source_shuffle_buffer_full(self, mock_glob):
mock_glob.return_value = [f"{i}" for i in range(20)]
fds = dataset_providers.FileDataSource(
read_file_fn=lambda x: tf.data.Dataset.from_tensor_slices([x]),
split_to_filepattern={"train": "filepattern"},
file_shuffle_buffer_size=None)
for _ in range(10):
ds = [
d.decode() for d in tfds.as_numpy(
fds.get_dataset("train", shuffle=True, seed=23))
]
self.assertListEqual(
ds,
[
"2", "13", "12", "19", "15", "5", "9", "1", "6", "8", "3", "0",
"10", "4", "14", "7", "16", "17", "18", "11"
])
def _get_preps_with_cache_placeholder_buffer_size(self, buffer_size):
preps = list(self.DEFAULT_PREPROCESSORS)
for i, p in enumerate(preps):
if isinstance(p, dataset_providers.CacheDatasetPlaceholder):
preps[i] = dataset_providers.CacheDatasetPlaceholder(
file_shuffle_buffer_size=buffer_size)
return preps
def _mock_and_assert_cached_source(self, task_name, buffer_size):
cached_task = dataset_providers.get_mixture_or_task(task_name)
cached_task._get_cached_source = mock.MagicMock(
side_effect=cached_task._get_cached_source)
_ = cached_task.get_dataset(None, "train", use_cached=True)
cached_task._get_cached_source.assert_called_once_with(
"train", buffer_size)
def test_cached_data_source_shuffle_buffer_default(self):
self._mock_and_assert_cached_source("cached_task", None)
def test_cached_data_source_shuffle_buffer_set(self):
self.add_task("cached_task_buf_2", self.tfds_source,
self._get_preps_with_cache_placeholder_buffer_size(2))
shutil.copytree(self.cached_task_dir,
os.path.join(self.test_data_dir, "cached_task_buf_2"))
self._mock_and_assert_cached_source("cached_task_buf_2", 2)
def test_cached_data_source_shuffle_buffer_None(self):
self.add_task("cached_task_buf_None", self.tfds_source,
self._get_preps_with_cache_placeholder_buffer_size(None))
shutil.copytree(self.cached_task_dir,
os.path.join(self.test_data_dir, "cached_task_buf_None"))
self._mock_and_assert_cached_source("cached_task_buf_None", None)
def test_proto_task(self):
self.verify_task_matches_fake_datasets(
"proto_task", use_cached=False, splits=["train"])
def test_num_input_examples(self):
self.assertEqual(30, self.cached_task.num_input_examples("train"))
self.assertEqual(10, self.cached_task.num_input_examples("validation"))
def test_disallow_shuffle(self):
task = dataset_providers.Task(
"no_shuffle",
source=self.function_source,
output_features=self.DEFAULT_OUTPUT_FEATURES,
preprocessors=self.DEFAULT_PREPROCESSORS,
shuffle_buffer_size=None)
with self.assertRaisesWithLiteralMatch(
ValueError, "Shuffling is disallowed for Task 'no_shuffle' since its "
"`shuffle_buffer_size` was set to `None` on construction."):
task.get_dataset(None, shuffle=True)
with self.assertRaisesWithLiteralMatch(
ValueError, "Shuffling is disallowed for Task 'no_shuffle' since its "
"`shuffle_buffer_size` was set to `None` on construction."):
task.get_dataset(None, shuffle=True, shuffle_buffer_size=100)
task.get_dataset(None, shuffle=False)
def test_supports_caching(self):
self.assertFalse(
dataset_providers.Task(
"nosupports_cache",
source=self.function_source,
output_features=self.DEFAULT_OUTPUT_FEATURES,
preprocessors=[]).supports_caching)
self.assertFalse(
dataset_providers.Task(
"nosupports_cache",
source=self.function_source,
output_features=self.DEFAULT_OUTPUT_FEATURES,
preprocessors=[preprocessors.tokenize]).supports_caching)
self.assertTrue(
dataset_providers.Task(
"supports_cache",
source=self.function_source,
output_features=self.DEFAULT_OUTPUT_FEATURES,
preprocessors=[
preprocessors.tokenize,
dataset_providers.CacheDatasetPlaceholder()
]).supports_caching)
self.assertTrue(
dataset_providers.Task(
"supports_cache",
source=self.function_source,
output_features=self.DEFAULT_OUTPUT_FEATURES,
preprocessors=[
dataset_providers.CacheDatasetPlaceholder(required=True),
preprocessors.tokenize,
]).supports_caching)
self.assertTrue(
dataset_providers.Task(
"supports_cache",
source=self.function_source,
output_features=self.DEFAULT_OUTPUT_FEATURES,
preprocessors=[
dataset_providers.CacheDatasetPlaceholder(),
]).supports_caching)
def test_requires_caching(self):
self.assertFalse(
dataset_providers.Task(
"nosupports_cache",
output_features=self.DEFAULT_OUTPUT_FEATURES,
source=self.function_source,
preprocessors=[preprocessors.tokenize]).requires_caching)
self.assertFalse(
dataset_providers.Task(
"supports_cache",
output_features=self.DEFAULT_OUTPUT_FEATURES,
source=self.function_source,
preprocessors=[
preprocessors.tokenize,
dataset_providers.CacheDatasetPlaceholder()
]).requires_caching)
task = dataset_providers.Task(
"requires_cache",
output_features=self.DEFAULT_OUTPUT_FEATURES,
source=self.function_source,
preprocessors=[
dataset_providers.CacheDatasetPlaceholder(required=True),
preprocessors.tokenize,
])
self.assertTrue(task.requires_caching)
with self.assertRaisesWithLiteralMatch(
ValueError,
"Task 'requires_cache' requires caching, but was called with "
"`use_cached=False`."):
task.get_dataset({"inputs": 512, "targets": 512}, use_cached=False)
# different error.
with self.assertRaisesWithLiteralMatch(
AssertionError,
"'requires_cache' does not exist in any of the task cache "
"directories."):
task.get_dataset({"inputs": 512, "targets": 512}, use_cached=True)
def test_datasource_prohibits_caching(self):
function_source_no_cache = dataset_providers.FunctionDataSource(
dataset_fn=test_utils.get_fake_dataset,
splits=["train", "validation"],
caching_permitted=False)
with self.assertRaisesWithLiteralMatch(
ValueError,
"Caching was requested for 'prohibits_cache', but the underlying data "
"source prohibits caching. Please remove `CacheDatasetPlaceholder` and "
"try again."
):
dataset_providers.Task(
"prohibits_cache",
output_features=self.DEFAULT_OUTPUT_FEATURES,
source=function_source_no_cache,
preprocessors=[
dataset_providers.CacheDatasetPlaceholder(required=True),
preprocessors.tokenize,
])
def test_cache_exists(self):
self.assertTrue(self.cached_task.cache_dir)
self.cached_task.assert_cached()
self.assertEqual(
os.path.join(self.test_data_dir, "cached_task"),
self.cached_task.cache_dir)
self.assertFalse(self.uncached_task.cache_dir)
with self.assertRaisesWithLiteralMatch(
AssertionError,
"'tfds_task' does not exist in any of the task cache directories."):
TaskRegistry.get("tfds_task").assert_cached()
def test_get_cached_stats(self):
expected_train_stats = {
"examples": 3,
"inputs_tokens": 36, "inputs_max_tokens": 13,
"targets_tokens": 18, "targets_max_tokens": 6}
self.assertEqual(
expected_train_stats,
self.cached_task.get_cached_stats("train"))
# Check repeated call.
self.assertEqual(
expected_train_stats,
self.cached_task.get_cached_stats("train"))
expected_validation_stats = {
"examples": 2,
"inputs_tokens": 23, "inputs_max_tokens": 12,
"targets_tokens": 36, "targets_max_tokens": 21}
self.assertEqual(
expected_validation_stats,
self.cached_task.get_cached_stats("validation"))
with self.assertRaisesWithLiteralMatch(
ValueError, "Stats do not exist for 'cached_task' split: fake"):
self.cached_task.get_cached_stats("fake")
with self.assertRaisesWithLiteralMatch(
AssertionError,
"'uncached_task' does not exist in any of the task cache directories."):
self.uncached_task.get_cached_stats("train")
def test_set_global_cache_dirs(self):
utils.set_global_cache_dirs([])
self.assertFalse(self.cached_task.cache_dir)
utils.set_global_cache_dirs([self.test_data_dir])
self.assertTrue(self.cached_task.cache_dir)
def test_get_dataset_cached(self):
self.verify_task_matches_fake_datasets(
"cached_task", use_cached=True, token_preprocessed=False)
# Test with token preprocessor.
self.cached_task._preprocessors = self.DEFAULT_PREPROCESSORS + (
test_utils.test_token_preprocessor,)
self.verify_task_matches_fake_datasets(
"cached_task", use_cached=True, token_preprocessed=True)
def test_get_dataset_onthefly(self):
self.verify_task_matches_fake_datasets(
"uncached_task", use_cached=False)
# Test with token preprocessor.
self.cached_task._preprocessors = self.DEFAULT_PREPROCESSORS + (
test_utils.test_token_preprocessor,)
self.verify_task_matches_fake_datasets(
"cached_task", use_cached=False, token_preprocessed=True)
def test_get_dataset_no_truncation(self):
self.verify_task_matches_fake_datasets(
"uncached_task", use_cached=False, sequence_length=None)
def test_sharding(self):
for i in range(3):
self.verify_task_matches_fake_datasets(
"cached_task", use_cached=False, num_shards=i,
token_preprocessed=False)
self.verify_task_matches_fake_datasets(
"cached_task", use_cached=True, num_shards=i,
token_preprocessed=False)
def test_feature_validation(self):
default_vocab = test_utils.sentencepiece_vocab()
features = {
"inputs":
dataset_providers.Feature(vocabulary=default_vocab, required=False),
"targets":
dataset_providers.Feature(vocabulary=default_vocab, required=True),
"inputs_rank2":
dataset_providers.Feature(
vocabulary=vocabularies.PassThroughVocabulary(5),
required=False,
rank=2),
"continuous_features":
dataset_providers.ContinuousFeature(
required=False,
rank=2)
}
def _materialize(output):
task = dataset_providers.Task(
"feature_validation_task",
self.function_source,
output_features=features,
preprocessors=(lambda _: tf.data.Dataset.from_tensors(output),),
metric_fns=[],
)
list(
task.get_dataset(
{"inputs": 13, "targets": 13, "inputs_rank2": 13}, "train",
use_cached=False
).as_numpy_iterator()
)
# Missing optional feature: OK
_materialize({"targets": [0]})
# Missing required feature.
with self.assertRaisesWithLiteralMatch(
ValueError,
"Task dataset is missing expected output feature after preprocessing: "
"targets"):
_materialize({"inputs": [0]})
# Wrong type.
with self.assertRaisesWithLiteralMatch(
ValueError,
"Task dataset has incorrect type for feature 'targets' after "
"preprocessing: Got string, expected int32"):
_materialize({"targets": ["wrong type"]})
# Wrong rank.
with self.assertRaisesWithLiteralMatch(
ValueError,
"Task dataset has incorrect rank for feature 'targets' after "
"preprocessing: Got 0, expected 1"):
_materialize({"targets": 0})
# Verify rank > 1 works.
_materialize({"targets": [0], "inputs_rank2": [[0, 0, 0], [0, 0, 0]]})
# Wrong rank (1 when 2 is expected).
with self.assertRaisesWithLiteralMatch(
ValueError,
"Task dataset has incorrect rank for feature 'inputs_rank2' after "
"preprocessing: Got 1, expected 2"):
_materialize({"targets": [0], "inputs_rank2": [0]})
# Test ContinuousFeature
_materialize({
"targets": [0],
"continuous_features": [[1, 1], [0, 1]]
})
def test_value_errors(self):
dataset_fn = (
lambda split, shuffle_files: tf.data.Dataset.from_tensors(["test"]))
output_features = {
"inputs": dataset_providers.Feature(test_utils.sentencepiece_vocab())
}
with self.assertRaisesWithLiteralMatch(
ValueError, "`CacheDatasetPlaceholder` can appear at most once in the "
"preprocessing pipeline. Found 2 in 'multiple_cache_placeholders'."):
dataset_providers.Task(
"multiple_cache_placeholders",
source=dataset_providers.FunctionDataSource(
dataset_fn=dataset_fn,
splits=["train", "validation"]
),
preprocessors=[
test_utils.test_text_preprocessor,
preprocessors.tokenize,
dataset_providers.CacheDatasetPlaceholder(),
test_utils.test_token_preprocessor,
dataset_providers.CacheDatasetPlaceholder()
],
output_features=output_features,
metric_fns=[])
with self.assertRaisesWithLiteralMatch(
ValueError,
"'test_token_preprocessor' has a `sequence_length` argument but occurs "
"before `CacheDatasetPlaceholder` in 'sequence_length_pre_cache'. This "
"is not allowed since the sequence length is specified at run time."):
dataset_providers.Task(
"sequence_length_pre_cache",
dataset_providers.FunctionDataSource(
dataset_fn=dataset_fn,
splits=["train"],
),
preprocessors=[
test_utils.test_text_preprocessor,
preprocessors.tokenize,
test_utils.test_token_preprocessor,
dataset_providers.CacheDatasetPlaceholder()
],
output_features=output_features,
metric_fns=[])
def test_tfds_source_splits(self):
default_splits_src = dataset_providers.TfdsDataSource("fake:0.0.0")
self.assertSameElements(["train", "validation"], default_splits_src.splits)
validation_split_src = dataset_providers.TfdsDataSource(
"fake:0.0.0", splits=["validation"])
self.assertSameElements(["validation"], validation_split_src.splits)
sliced_split_src = dataset_providers.TfdsDataSource(
"fake:0.0.0", splits={"validation": "train[0:1%]"})
self.assertSameElements(["validation"], sliced_split_src.splits)
def test_no_eos(self):
default_vocab = test_utils.sentencepiece_vocab()
features = {
"inputs":
dataset_providers.Feature(add_eos=True, vocabulary=default_vocab),
"targets":
dataset_providers.Feature(add_eos=False, vocabulary=default_vocab),
}
self.add_task("task_no_eos", self.function_source, output_features=features)
self.verify_task_matches_fake_datasets("task_no_eos", use_cached=False)
def test_dtype(self):
default_vocab = test_utils.sentencepiece_vocab()
features = {
"inputs":
# defaults to int32
dataset_providers.Feature(vocabulary=default_vocab),
"targets":
dataset_providers.Feature(dtype=tf.int64, vocabulary=default_vocab),
}
self.add_task(
"task_dtypes",
self.function_source,
preprocessors=self.DEFAULT_PREPROCESSORS + (
utils.map_over_dataset(
lambda x: {k: tf.cast(v, tf.int64) if k == "targets" else v # pylint:disable=g-long-lambda
for k, v in x.items()}
),
),
output_features=features
)
self.verify_task_matches_fake_datasets("task_dtypes", use_cached=False)
def test_num_epochs(self):
# Try repeating after preprocessing the dataset to verify the outputs are
# the same.
epoch1_ds = self.random_task.get_dataset(
{"inputs": 13, "targets": 13},
split="train", use_cached=False, shuffle=True, seed=0)
# `random_task` has 3 examples per epoch.
epoch2_ds = self.random_task.get_dataset(
{"inputs": 13, "targets": 13},
split="train", use_cached=False, shuffle=True, seed=0
).repeat(2).skip(3)
test_utils.assert_datasets_eq(epoch1_ds, epoch2_ds)
# Try repeating before preprocessing the dataset to verify the outputs are
# different.
epoch1_ds = self.random_task.get_dataset(
{"inputs": 13, "targets": 13},
split="train", use_cached=False, shuffle=True, seed=0)
# `random_task` has 3 examples per epoch.
epoch2_ds = self.random_task.get_dataset(
{"inputs": 13, "targets": 13},
split="train", use_cached=False, shuffle=True, seed=0, num_epochs=2
).skip(3)
test_utils.assert_datasets_neq(epoch1_ds, epoch2_ds)
def test_same_seeds_cached_match(self):
dataset1 = self.cached_task.get_dataset(
{"inputs": 13, "targets": 13},
split="train", use_cached=True, shuffle=True, seed=0)
dataset2 = self.cached_task.get_dataset(
{"inputs": 13, "targets": 13},
split="train", use_cached=True, shuffle=True, seed=0)
test_utils.assert_datasets_eq(dataset1, dataset2)
def test_different_seeds_cached_mismatch(self):
dataset1 = self.cached_task.get_dataset(
{"inputs": 13, "targets": 13},
split="train", use_cached=True, shuffle=True, seed=0)
dataset2 = self.cached_task.get_dataset(
{"inputs": 13, "targets": 13},
split="train", use_cached=True, shuffle=True, seed=42)
test_utils.assert_datasets_neq(dataset1, dataset2)
def test_same_seeds_uncached_match(self):
dataset1 = self.uncached_task.get_dataset(
{"inputs": 13, "targets": 13},
split="train", use_cached=False, shuffle=True, seed=0)
dataset2 = self.uncached_task.get_dataset(
{"inputs": 13, "targets": 13},
split="train", use_cached=False, shuffle=True, seed=0)
test_utils.assert_datasets_eq(dataset1, dataset2)
def test_different_seeds_uncached_mismatch(self):
dataset1 = self.uncached_task.get_dataset(
{"inputs": 13, "targets": 13},
split="train", use_cached=False, shuffle=True, seed=0)
dataset2 = self.uncached_task.get_dataset(
{"inputs": 13, "targets": 13},
split="train", use_cached=False, shuffle=True, seed=42)
test_utils.assert_datasets_neq(dataset1, dataset2)
def test_same_seeds_random_tp_uncached_match(self):
dataset1 = self.random_task.get_dataset(
{"inputs": 13, "targets": 13},
split="train", use_cached=False, shuffle=True, seed=0).repeat(4)
dataset2 = self.random_task.get_dataset(
{"inputs": 13, "targets": 13},
split="train", use_cached=False, shuffle=True, seed=0).repeat(4)
test_utils.assert_datasets_eq(dataset1, dataset2)
def test_different_seeds_random_tp_uncached_mismatch(self):
dataset1 = self.random_task.get_dataset(
{"inputs": 13, "targets": 13},
split="train", use_cached=False, shuffle=True, seed=0)
dataset2 = self.random_task.get_dataset(
{"inputs": 13, "targets": 13},
split="train", use_cached=False, shuffle=True, seed=42)
test_utils.assert_datasets_neq(dataset1, dataset2)
def test_no_shuffle_with_seed_cached_match(self):
dataset1 = self.cached_task.get_dataset(
{"inputs": 13, "targets": 13},
split="train", use_cached=True, shuffle=False, seed=0)
dataset2 = self.cached_task.get_dataset(
{"inputs": 13, "targets": 13},
split="train", use_cached=True, shuffle=False, seed=42)
test_utils.assert_datasets_eq(dataset1, dataset2)
def test_no_shuffle_with_seed_uncached_match(self):
dataset1 = self.uncached_task.get_dataset(
{"inputs": 13, "targets": 13},
split="train", use_cached=False, shuffle=False, seed=0)
dataset2 = self.uncached_task.get_dataset(
{"inputs": 13, "targets": 13},
split="train", use_cached=False, shuffle=False, seed=42)
test_utils.assert_datasets_eq(dataset1, dataset2)
def test_no_shuffle_different_seeds_random_tp_uncached_mismatch(self):
dataset1 = self.random_task.get_dataset(
{"inputs": 13, "targets": 13},
split="train", use_cached=False, shuffle=False, seed=0)
dataset2 = self.random_task.get_dataset(
{"inputs": 13, "targets": 13},
split="train", use_cached=False, shuffle=False, seed=42)
test_utils.assert_datasets_neq(dataset1, dataset2)
def test_plaintext_to_pretokenized_rename(self):
ds = self.cached_plaintext_task.get_dataset(
{"inputs": 13, "targets": 13},
split="train", use_cached=True, shuffle=False)
keys = next(ds.as_numpy_iterator()).keys()
self.assertSetEqual(
set(keys),
set(["inputs", "inputs_pretokenized",
"targets", "targets_pretokenized"]))
def test_list_shards(self):
def _get_formatted_shards_list(task_name, split):
shards = dataset_providers.get_mixture_or_task(
task_name).source.list_shards(split)
shards = [s.split("/")[-1] for s in shards]
return sorted(shards)
self.assertListEqual(
_get_formatted_shards_list("tfds_task", "train"),
["train.tfrecord-00000-of-00002", "train.tfrecord-00001-of-00002"])
self.assertListEqual(
_get_formatted_shards_list("text_line_task", "train"),
["train.tsv-00000-of-00002", "train.tsv-00001-of-00002"])
self.assertListEqual(
_get_formatted_shards_list("tf_example_task", "train"),
["train.tfrecord-00000-of-00002", "train.tfrecord-00001-of-00002"])
self.assertListEqual(
_get_formatted_shards_list("proto_task", "train"),
["train.tfrecord-00000-of-00002", "train.tfrecord-00001-of-00002"])
self.assertListEqual(
_get_formatted_shards_list("function_task", "train"), ["train"])
self.assertListEqual(
_get_formatted_shards_list("fully_processed_precache", "train"),
["train"])
self.assertListEqual(
_get_formatted_shards_list("tokenized_postcache", "train"), ["train"])
self.assertListEqual(
_get_formatted_shards_list("random_task", "train"), ["train"])
self.assertListEqual(
_get_formatted_shards_list("uncached_task", "train"),
["train.tfrecord-00000-of-00002", "train.tfrecord-00001-of-00002"])
self.assertListEqual(
_get_formatted_shards_list("cached_task", "train"),
["train.tfrecord-00000-of-00002", "train.tfrecord-00001-of-00002"])
self.assertListEqual(
_get_formatted_shards_list("cached_plaintext_task", "train"),
["train.tfrecord-00000-of-00002", "train.tfrecord-00001-of-00002"])
class MixturesTest(test_utils.FakeTaskTest):
def test_tasks(self):
self.add_task("task1", self.function_source)
self.add_task("task2", self.function_source)
MixtureRegistry.add("test_mix1", [("task1", 1), ("task2", 1)])
mix = MixtureRegistry.get("test_mix1")
self.assertEqual(len(mix.tasks), 2)
for task in mix.tasks:
self.verify_task_matches_fake_datasets(task.name, use_cached=False)
self.assertEqual(mix.get_rate(task), 1)
def test_num_examples(self):
MixtureRegistry.add("test_mix2", [(self.cached_task.name, 1)])
mix = MixtureRegistry.get("test_mix2")
self.assertEqual(mix.num_input_examples(split="train"), 30)
def test_splits(self):
MixtureRegistry.add(
"test_mix",
[(self.cached_task.name, 1), (self.uncached_task.name, 1)]
)
mix = MixtureRegistry.get("test_mix")
self.assertSameElements(["train", "validation"], mix.splits, 30)
def test_get_dataset(self):
MixtureRegistry.add("test_mix3", [(self.cached_task.name, 1)])
task_ds = TaskRegistry.get_dataset(
self.cached_task.name, {
"inputs": 13,
"targets": 13
},
"validation",
use_cached=False,
shuffle=False)
mix_ds = MixtureRegistry.get("test_mix3").get_dataset(
{
"inputs": 13,
"targets": 13
}, "validation", use_cached=False, shuffle=False)
# mix.get_dataset strips non-output features
task_ds = task_ds.map(lambda x: {k: x[k] for k in ["inputs", "targets"]})
# limit size since get_dataset repeats the dataset
test_utils.assert_datasets_eq(task_ds.repeat(2), mix_ds.take(4))
def test_get_dataset_mix(self):
@utils.map_over_dataset
def _constant_preprocessor(unused_x, val):
return {
"targets": tf.constant([val], tf.int32),
"inputs": tf.constant([val], tf.int32),
}
self.add_task(
"two_task",
self.function_source,
preprocessors=(functools.partial(_constant_preprocessor, val=2),)
)
self.add_task(
"three_task",
self.function_source,
preprocessors=(functools.partial(_constant_preprocessor, val=3),)
)
MixtureRegistry.add("test_mix", [("two_task", 1), ("three_task", 1)])
sequence_length = {"inputs": 2, "targets": 2}
mix_ds = MixtureRegistry.get("test_mix").get_dataset(
sequence_length, "train", seed=13).take(1000)
res = sum(int(item["inputs"][0]) for item in mix_ds.as_numpy_iterator())
self.assertEqual(res, 2481)
def test_get_dataset_passthrough_features(self):
@utils.map_over_dataset
def _constant_feature_preprocessor(unused_x, val):
return {
"targets": tf.constant([val], tf.int32),
"inputs": tf.constant([val], tf.int32),
"feature": tf.constant([val], tf.int32),
}
self.add_task(
"two_task",
self.function_source,
preprocessors=(functools.partial(_constant_feature_preprocessor,
val=2),))
self.add_task(
"three_task",
self.function_source,
preprocessors=(functools.partial(_constant_feature_preprocessor,
val=3),))
MixtureRegistry.add("test_mix", [("two_task", 1), ("three_task", 1)])
sequence_length = {"inputs": 2, "targets": 2}
passthrough_features = ["feature"]
mix_ds = MixtureRegistry.get("test_mix").get_dataset(
sequence_length,
"train",
seed=13,
passthrough_features=passthrough_features).take(1000)
# output features are defined as "inputs" and "targets" by default.
res = sum(int(item["feature"][0]) for item in mix_ds.as_numpy_iterator())
self.assertEqual(res, 2481)
def test_copy_pretokenized(self):
@utils.map_over_dataset
def _constant_preprocessor(unused_x, val):
return {
"targets": tf.constant([val], tf.int32),
"targets_pretokenized": tf.constant(f"targets_{val}"),
"inputs": tf.constant([val], tf.int32),
"inputs_pretokenized": tf.constant(f"inputs_{val}")
}
self.add_task(
"two_task",
self.function_source,
preprocessors=(functools.partial(_constant_preprocessor, val=2),)
)
self.add_task(
"three_task",
self.function_source,
preprocessors=(functools.partial(_constant_preprocessor, val=3),)
)
MixtureRegistry.add("test_mix", [("two_task", 1), ("three_task", 1)])
sequence_length = {"inputs": 2, "targets": 2}
mix_ds = MixtureRegistry.get("test_mix").get_dataset(
sequence_length, "train", seed=13, copy_pretokenized=True).take(1000)
inputs_pretokenized = set(
ex["inputs_pretokenized"] for ex in mix_ds.as_numpy_iterator())
targets_pretokenized = set(
ex["targets_pretokenized"] for ex in mix_ds.as_numpy_iterator())
self.assertCountEqual([b"inputs_2", b"inputs_3"], inputs_pretokenized)
self.assertCountEqual([b"targets_2", b"targets_3"], targets_pretokenized)
mix_ds = MixtureRegistry.get("test_mix").get_dataset(
sequence_length, "train", seed=13, copy_pretokenized=False).take(1000)
for ex in mix_ds.as_numpy_iterator():
self.assertNoCommonElements(
["inputs_pretokenized", "targets_pretokenized"], ex.keys())
def test_get_rate_with_callable(self):
def fn(t):
self.assertEqual(t.name, "task4")
return 42
self.add_task("task4", self.function_source)
task = TaskRegistry.get("task4")
MixtureRegistry.add("test_mix5", [("task4", fn)])
mix = MixtureRegistry.get("test_mix5")
self.assertEqual(mix.get_rate(task), 42)
def test_mixture_of_mixtures(self):
self.add_task("task_a", self.function_source)
self.add_task("task_b", self.function_source)
self.add_task("task_c", self.function_source)
MixtureRegistry.add("another_mix", [("task_a", 1), ("task_b", 1)])
MixtureRegistry.add("supermix", [("another_mix", 1), ("task_c", 1)])
supermix = MixtureRegistry.get("supermix")
names = [task.name for task in supermix.tasks]
self.assertEqual(names, ["task_a", "task_b", "task_c"])
self.assertEqual([supermix.get_rate(t) for t in supermix.tasks],
[0.5, 0.5, 1])
def test_mixture_of_mixtures_dupe(self):
self.add_task("task2_a", self.function_source)
self.add_task("task2_b", self.function_source)
self.add_task("task2_c", self.function_source)
MixtureRegistry.add("yet_another_mix", [("task2_a", 1), ("task2_b", 1)])
MixtureRegistry.add("supermix_with_dupe", [("yet_another_mix", 1),
("task2_a", 1), ("task2_c", 1)])
supermix = MixtureRegistry.get("supermix_with_dupe")
names = [task.name for task in supermix.tasks]
self.assertEqual(names, ["task2_a", "task2_b", "task2_c"])
self.assertEqual([supermix.get_rate(t) for t in supermix.tasks],
[1.5, 0.5, 1])
def test_mixture_with_sample_fn(self):
def sequential_intereave(datasets: Sequence[tf.data.Dataset],
rates: Sequence[float],
sample_seed: Optional[int]) -> tf.data.Dataset:
del rates, sample_seed
return datasets[0].concatenate(datasets[1])
def gen_dataset(split,
shuffle_files=False,
seed=None,
val: str = "") -> tf.data.Dataset:
del split, shuffle_files, seed # Need this to pass arg validation.
return tf.data.Dataset.from_tensor_slices({
"inputs": [[val]] * 3,
})
# Register two very simple tasks, each with 3 repeated string values.
vocab = vocabularies.PassThroughVocabulary(0)
tasks = []
for task_name in ["first", "second"]:
tasks.append(self.add_task(
task_name,
dataset_providers.FunctionDataSource(
dataset_fn=functools.partial(gen_dataset, val=task_name),
splits=["train"]),
preprocessors=[],
output_features={
"inputs": dataset_providers.Feature(vocab, dtype=tf.string)
}))
# Verify that by default, interleaving of datasets is random.
MixtureRegistry.add("default_mix", [("first", 1), ("second", 1)])
default_ds = MixtureRegistry.get("default_mix").get_dataset(
None, "train", shuffle=False, seed=2, num_epochs=1)
expected = [b"second", b"first", b"second", b"first", b"second", b"first"]
actual = [x["inputs"] for x in default_ds.as_numpy_iterator()]
self.assertEqual(expected, actual)
# Verify that we can modify sampling function correctly.
MixtureRegistry.add(
"sequential_mix", [("first", 1), ("second", 1)],
sample_fn=sequential_intereave)
sequential_ds = MixtureRegistry.get("sequential_mix").get_dataset(
None, "train", shuffle=False, seed=2, num_epochs=1)
expected = [b"first"] * 3 + [b"second"] * 3
actual = [x["inputs"] for x in sequential_ds.as_numpy_iterator()]
self.assertEqual(expected, actual)
class GetDatasetTest(parameterized.TestCase, tf.test.TestCase):
def test_get_dataset_enc_dec_unpacked(self):
mixture_or_task_name = "enc_dec_unpacked"
x = [{"inputs": [7, 8, 5, 6, 9, 4, 3], "targets": [3, 9]},
{"inputs": [8, 4], "targets": [4]},
{"inputs": [5, 6, 7], "targets": [6, 5]}]
ds = create_default_dataset(x)
dataset_fn = lambda split, shuffle_files: ds
register_dummy_task(mixture_or_task_name, dataset_fn=dataset_fn)
task_feature_lengths = {"inputs": 7, "targets": 5}
converter = feature_converters.EncDecFeatureConverter(pack=False)
output_ds = dataset_providers.get_dataset(
mixture_or_task_name=mixture_or_task_name,
task_feature_lengths=task_feature_lengths,
dataset_split="train",
shuffle=False,
feature_converter=converter)
expected = [{
"encoder_input_tokens": [7, 8, 5, 6, 9, 4, 1],
"decoder_target_tokens": [3, 9, 1, 0, 0],
"decoder_input_tokens": [0, 3, 9, 1, 0],
"decoder_loss_weights": [1, 1, 1, 0, 0],
}, {
"encoder_input_tokens": [8, 4, 1, 0, 0, 0, 0],
"decoder_target_tokens": [4, 1, 0, 0, 0],
"decoder_input_tokens": [0, 4, 1, 0, 0],
"decoder_loss_weights": [1, 1, 0, 0, 0],
}, {
"encoder_input_tokens": [5, 6, 7, 1, 0, 0, 0],
"decoder_target_tokens": [6, 5, 1, 0, 0],
"decoder_input_tokens": [0, 6, 5, 1, 0],
"decoder_loss_weights": [1, 1, 1, 0, 0],
}]
expected_dtypes = {feat: tf.int32 for feat in expected[0].keys()}
assert_dataset(output_ds, expected, expected_dtypes=expected_dtypes)
@parameterized.parameters(
dict(
task_name="enc_dec_partial_trim_both",
task_feature_lengths={
"inputs": 7,
"targets": 2
},
expect_trim_inputs=True,
expect_trim_targets=True),
dict(
task_name="enc_dec_partial_trim_targets",
task_feature_lengths={
"inputs": None,
"targets": 2
},
expect_trim_inputs=False,
expect_trim_targets=True),
dict(
task_name="enc_dec_partial_trim_inputs",
task_feature_lengths={
"inputs": 7,
"targets": None
},
expect_trim_inputs=True,
expect_trim_targets=False),
dict(
task_name="enc_dec_partial_trim_neither",
task_feature_lengths={
"inputs": None,
"targets": None
},
expect_trim_inputs=False,
expect_trim_targets=False),
dict(
task_name="enc_dec_partial_trim_nothing",
task_feature_lengths=None,
expect_trim_inputs=False,
expect_trim_targets=False))
def test_partial_sequence_length(self, task_name, task_feature_lengths,
expect_trim_inputs, expect_trim_targets):
x = [{"inputs": [7, 8, 5, 6, 9, 4, 3], "targets": [3, 9]},
{"inputs": [8, 4], "targets": [4]},
{"inputs": [5, 6, 7], "targets": [6, 5]}]
ds = create_default_dataset(x)
dataset_fn = lambda split, shuffle_files: ds
register_dummy_task(task_name, dataset_fn=dataset_fn)
# Unlike the other tests, don't use a feature converter. Instead, test the
task = dataset_providers.get_mixture_or_task(task_name)
output_ds = task.get_dataset(
sequence_length=task_feature_lengths,
shuffle=False)
expected = [{
"inputs": [7, 8, 5, 6, 9, 4, 3, 1],
"targets": [3, 9, 1],
}, {
"inputs": [8, 4, 1],
"targets": [4, 1],
}, {
"inputs": [5, 6, 7, 1],
"targets": [6, 5, 1],
}]
if expect_trim_inputs:
expected[0]["inputs"] = [7, 8, 5, 6, 9, 4, 1]
if expect_trim_targets:
expected[0]["targets"] = [3, 1]
expected[2]["targets"] = [6, 1]
expected_dtypes = {feat: tf.int32 for feat in expected[0].keys()}
assert_dataset(output_ds, expected, expected_dtypes=expected_dtypes)
@parameterized.parameters(
dict(
task_name="enc_dec_multidim_trim_both",
task_feature_lengths={
"inputs": (2, 5),
"targets": 2
},
expect_trim_inputs=True,
expect_trim_targets=True,
),
dict(
task_name="enc_dec_multidim_trim_inputs",
task_feature_lengths={
"inputs": (2, 5),
"targets": None
},
expect_trim_inputs=True,
expect_trim_targets=False,
),
dict(
task_name="enc_dec_multidim_trim_targets",
task_feature_lengths={
"inputs": None,
"targets": 2
},
expect_trim_inputs=False,
expect_trim_targets=True,
),
dict(
task_name="enc_dec_no_multidim_trim",
task_feature_lengths={
"inputs": None,
"targets": None
},
expect_trim_inputs=False,
expect_trim_targets=False
)
)
def test_multidimension_sequence_length(self,
task_name,
task_feature_lengths,
expect_trim_inputs,
expect_trim_targets):
x = [{"inputs": [[7, 8, 5, 6, 9, 4, 3],
[2, 3, 4, 5, 0, 0, 0],
[6, 7, 1, 0, 0, 0, 0]],
"targets": [3, 9]},
{"inputs": [[8, 4],
[1, 0],
[2, 3]],
"targets": [4]},
{"inputs": [[5, 6, 7]],
"targets": [6, 5, 1]},
{"inputs": [[7, 8, 9, 1, 2, 3, 4, 5, 6]],
"targets": [10, 11, 1]}]
ds = tf.data.Dataset.from_generator(
lambda: x,
output_types={"inputs": tf.int32, "targets": tf.int32},
output_shapes={"inputs": (None, None), "targets": (None,)})
dataset_fn = lambda split, shuffle_files: ds
dataset_providers.TaskRegistry.add(
task_name,
source=dataset_providers.FunctionDataSource(
dataset_fn=dataset_fn, splits=["train", "validation"]),
preprocessors=[
dataset_providers.CacheDatasetPlaceholder(),
],
output_features={
"inputs": dataset_providers.Feature(
test_utils.sentencepiece_vocab(), rank=2),
"targets": dataset_providers.Feature(
test_utils.sentencepiece_vocab())
},
metric_fns=[])
# task.get_dataset method directly, which is similar to how evaluation.py
# infers feature lengths w/trimming.
task = dataset_providers.get_mixture_or_task(task_name)
output_ds = task.get_dataset(
sequence_length=task_feature_lengths,
shuffle=False)
expected = copy.deepcopy(x)
if expect_trim_inputs:
expected[0]["inputs"] = [[7, 8, 5, 6, 9],
[2, 3, 4, 5, 0]]
expected[1]["inputs"] = [[8, 4],
[1, 0]]
expected[3]["inputs"] = [[7, 8, 9, 1, 2]]
if expect_trim_targets:
expected[2]["targets"] = [6, 5]
expected[3]["targets"] = [10, 11]
expected_dtypes = {feat: tf.int32 for feat in expected[0].keys()}
assert_dataset(output_ds, expected, expected_dtypes=expected_dtypes)
def test_get_dataset_enc_dec_packed(self):
mixture_or_task_name = "enc_dec_packed"
x = [{"inputs": [7, 8, 5, 6, 9, 4, 3], "targets": [3, 9]},
{"inputs": [8, 4], "targets": [4]},
{"inputs": [5, 6, 7], "targets": [6, 5]}]
ds = create_default_dataset(x)
dataset_fn = lambda split, shuffle_files: ds
register_dummy_task(mixture_or_task_name, dataset_fn=dataset_fn)
task_feature_lengths = {"inputs": 7, "targets": 5}
converter = feature_converters.EncDecFeatureConverter(pack=True)
output_ds = dataset_providers.get_dataset(
mixture_or_task_name=mixture_or_task_name,
task_feature_lengths=task_feature_lengths,
dataset_split="train",
shuffle=False,
feature_converter=converter)
expected = [{
# Example 1 is trimmed
"encoder_input_tokens": [7, 8, 5, 6, 9, 4, 1],
"encoder_segment_ids": [1, 1, 1, 1, 1, 1, 1],
"encoder_positions": [0, 1, 2, 3, 4, 5, 6],
"decoder_target_tokens": [3, 9, 1, 0, 0],
"decoder_input_tokens": [0, 3, 9, 0, 0],
"decoder_loss_weights": [1, 1, 1, 0, 0],
"decoder_segment_ids": [1, 1, 1, 0, 0],
"decoder_positions": [0, 1, 2, 0, 0],
}, {
# Example 2 and 3 are packed together
"encoder_input_tokens": [8, 4, 1, 5, 6, 7, 1],
"encoder_segment_ids": [1, 1, 1, 2, 2, 2, 2],
"encoder_positions": [0, 1, 2, 0, 1, 2, 3],
"decoder_target_tokens": [4, 1, 6, 5, 1],
"decoder_input_tokens": [0, 4, 0, 6, 5],
"decoder_loss_weights": [1, 1, 1, 1, 1],
"decoder_segment_ids": [1, 1, 2, 2, 2],
"decoder_positions": [0, 1, 0, 1, 2],
}]
expected_dtypes = {feat: tf.int32 for feat in expected[0].keys()}
assert_dataset(output_ds, expected, expected_dtypes=expected_dtypes)
def test_get_dataset_both_train_and_validation_splits(self):
mixture_or_task_name = "both_train_and_validation_splits"
x_train = [{"inputs": [7, 8, 5, 6, 9, 4, 3], "targets": [3, 9]}]
x_val = [{"inputs": [8, 4], "targets": [4]}]
datasets = {
"train": create_default_dataset(x_train),
"validation": create_default_dataset(x_val)
}
dataset_fn = lambda split, shuffle_files: datasets[split]
register_dummy_task(mixture_or_task_name, dataset_fn=dataset_fn)
task_feature_lengths = {"inputs": 7, "targets": 5}
output_ds = {}
for split in ["train", "validation"]:
converter = feature_converters.EncDecFeatureConverter(pack=False)
output_ds[split] = dataset_providers.get_dataset(
mixture_or_task_name=mixture_or_task_name,
task_feature_lengths=task_feature_lengths,
dataset_split=split,
shuffle=False,
feature_converter=converter)
expected_train = {
"encoder_input_tokens": [7, 8, 5, 6, 9, 4, 1],
"decoder_target_tokens": [3, 9, 1, 0, 0],
"decoder_input_tokens": [0, 3, 9, 1, 0],
"decoder_loss_weights": [1, 1, 1, 0, 0],
}
expected_val = {
"encoder_input_tokens": [8, 4, 1, 0, 0, 0, 0],
"decoder_target_tokens": [4, 1, 0, 0, 0],
"decoder_input_tokens": [0, 4, 1, 0, 0],
"decoder_loss_weights": [1, 1, 0, 0, 0],
}
expected_dtypes = {feat: tf.int32 for feat in expected_train.keys()}
assert_dataset(
output_ds["train"], expected_train, expected_dtypes=expected_dtypes)
assert_dataset(
output_ds["validation"], expected_val, expected_dtypes=expected_dtypes)
def test_get_dataset_enc_dec_sharded(self):
mixture_or_task_name = "enc_dec_sharded"
x = [{"inputs": [7, 8, 5, 6, 9, 4, 3], "targets": [3, 9]},
{"inputs": [8, 4], "targets": [4]},
{"inputs": [5, 6, 7], "targets": [6, 5]}]
ds = create_default_dataset(x)
dataset_fn = lambda split, shuffle_files: ds
register_dummy_task(mixture_or_task_name, dataset_fn=dataset_fn)
task_feature_lengths = {"inputs": 7, "targets": 5}
converter = feature_converters.EncDecFeatureConverter(pack=False)
shard_info = dataset_providers.ShardInfo(index=0, num_shards=2)
output_ds = dataset_providers.get_dataset(
mixture_or_task_name=mixture_or_task_name,
task_feature_lengths=task_feature_lengths,
dataset_split="train",
shuffle=False,
feature_converter=converter,
shard_info=shard_info)
# Example index 1 should not be present in the sharded dataset.
expected = [{
"encoder_input_tokens": [7, 8, 5, 6, 9, 4, 1],
"decoder_target_tokens": [3, 9, 1, 0, 0],
"decoder_input_tokens": [0, 3, 9, 1, 0],
"decoder_loss_weights": [1, 1, 1, 0, 0],
}, {
"encoder_input_tokens": [5, 6, 7, 1, 0, 0, 0],
"decoder_target_tokens": [6, 5, 1, 0, 0],
"decoder_input_tokens": [0, 6, 5, 1, 0],
"decoder_loss_weights": [1, 1, 1, 0, 0],
}]
expected_dtypes = {feat: tf.int32 for feat in expected[0].keys()}
assert_dataset(output_ds, expected, expected_dtypes=expected_dtypes)
def test_get_dataset_enc_dec_sharded_and_packed(self):
mixture_or_task_name = "enc_dec_sharded_and_packed"
x = [{"inputs": [7, 8], "targets": [3, 9]},
{"inputs": [8, 4], "targets": [4]},
{"inputs": [5, 6, 7], "targets": [6]}]
ds = create_default_dataset(x)
dataset_fn = lambda split, shuffle_files: ds
register_dummy_task(mixture_or_task_name, dataset_fn=dataset_fn)
task_feature_lengths = {"inputs": 7, "targets": 5}
converter = feature_converters.EncDecFeatureConverter(pack=True)
shard_info = dataset_providers.ShardInfo(index=0, num_shards=2)
output_ds = dataset_providers.get_dataset(
mixture_or_task_name=mixture_or_task_name,
task_feature_lengths=task_feature_lengths,
dataset_split="train",
shuffle=False,
feature_converter=converter,
shard_info=shard_info)
# Packing should be done after the sharding.
expected = {
"encoder_input_tokens": [7, 8, 1, 5, 6, 7, 1],
"encoder_segment_ids": [1, 1, 1, 2, 2, 2, 2],
"encoder_positions": [0, 1, 2, 0, 1, 2, 3],
"decoder_target_tokens": [3, 9, 1, 6, 1],
"decoder_input_tokens": [0, 3, 9, 0, 6],
"decoder_loss_weights": [1, 1, 1, 1, 1],
"decoder_segment_ids": [1, 1, 1, 2, 2],
"decoder_positions": [0, 1, 2, 0, 1],
}
expected_dtypes = {feat: tf.int32 for feat in expected.keys()}
assert_dataset(output_ds, expected, expected_dtypes=expected_dtypes)
def register_dummy_task(
task_name: str,
dataset_fn: Callable[[str, str], tf.data.Dataset],
output_feature_names: Sequence[str] = ("inputs", "targets")) -> None:
dataset_providers.TaskRegistry.add(
task_name,
source=dataset_providers.FunctionDataSource(
dataset_fn=dataset_fn, splits=["train", "validation"]),
preprocessors=[
dataset_providers.CacheDatasetPlaceholder(),
preprocessors.append_eos_after_trim,
],
output_features={
feat: dataset_providers.Feature(test_utils.sentencepiece_vocab())
for feat in output_feature_names
},
metric_fns=[])
if __name__ == "__main__":
absltest.main()
| true | true |
790bfa5dcb72761c01a9ba47699f9d2ad6b32755 | 5,875 | py | Python | 2018/10_TheStarsAlign/aoc_10.py | deanearlwright/AdventOfCode | ca4cf6315c0efa38bd7748fb6f4bc99e7934871d | [
"MIT"
] | 1 | 2021-01-03T23:09:28.000Z | 2021-01-03T23:09:28.000Z | 2018/10_TheStarsAlign/aoc_10.py | deanearlwright/AdventOfCode | ca4cf6315c0efa38bd7748fb6f4bc99e7934871d | [
"MIT"
] | 6 | 2020-12-26T21:02:42.000Z | 2020-12-26T21:02:52.000Z | 2018/10_TheStarsAlign/aoc_10.py | deanearlwright/AdventOfCode | ca4cf6315c0efa38bd7748fb6f4bc99e7934871d | [
"MIT"
] | null | null | null | # ======================================================================
# The Stars Align
# Advent of Code 2018 Day 10 -- Eric Wastl -- https://adventofcode.com
#
# Python implementation by Dr. Dean Earl Wright III
# ======================================================================
# ======================================================================
# a o c _ 1 0 . p y
# ======================================================================
"Solve the puzzles for Advent of Code 2018 day 10"
# ----------------------------------------------------------------------
# import
# ----------------------------------------------------------------------
import argparse
import sys
import lights
# ----------------------------------------------------------------------
# constants
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
# parse_commnd_line
# ----------------------------------------------------------------------
def parse_command_line():
"Parse the command line options"
# 1. Create the command line parser
desc = 'The Stars Align - Day 10 of Advent of Code 2018'
sample = 'sample: python aoc_10.py input.txt'
parser = argparse.ArgumentParser(description=desc,
epilog=sample)
parser.add_argument('-v', '--verbose', action='store_true', default=False,
dest='verbose', help='Print status messages to stdout')
parser.add_argument('-p', '--part', action='store', default=1, type=int,
dest='part', help='Puzzle Part (1 or 2)')
parser.add_argument('-l', '--limit', action='store', default=0, type=int,
dest='limit',
help='Maximum limit (e.g., time, size, recursion) before stopping')
parser.add_argument('filepath', metavar='FILENAME', action='store', type=str,
help="Location of puzzle input")
# 2. Get the options and arguments
return parser.parse_args()
# ----------------------------------------------------------------------
# part_one
# ----------------------------------------------------------------------
def part_one(args, input_lines):
"Process part one of the puzzle"
# 1. Create the puzzle solver
solver = lights.Lights(part2=False, text=input_lines)
# 2. Determine the solution for part one
solution = solver.part_one(verbose=args.verbose, limit=args.limit)
if solution is None:
print("There is no solution")
else:
print("The solution for part one is %s" % (solution))
# 3. Return result
return solution is not None
# ----------------------------------------------------------------------
# part_two
# ----------------------------------------------------------------------
def part_two(args, input_lines):
"Process part two of the puzzle"
# 1. Create the puzzle solver
solver = lights.Lights(part2=True, text=input_lines)
# 2. Determine the solution for part two
solution = solver.part_two(verbose=args.verbose, limit=args.limit)
if solution is None:
print("There is no solution")
else:
print("The solution for part two is %s" % (solution))
# 3. Return result
return solution is not None
# ----------------------------------------------------------------------
# from_file
# ----------------------------------------------------------------------
def from_file(filepath):
"Read the file"
return from_text(open(filepath).read())
# ----------------------------------------------------------------------
# from_text
# ----------------------------------------------------------------------
def from_text(text):
"Break the text into trimed, non-comment lines"
# 1. We start with no lines
lines = []
# 2. Loop for lines in the text
for line in text.split('\n'):
# 3. But ignore blank and non-claim lines
line = line.rstrip(' \r')
if not line:
continue
if line.startswith('!'):
continue
# 4. Add the line
lines.append(line)
# 5. Return a list of clean lines
return lines
# ----------------------------------------------------------------------
# main
# ----------------------------------------------------------------------
def main():
"Read the Advent of Code problem and solve it"
# 1. Get the command line options
args = parse_command_line()
# 2. Read the puzzle file
input_text = from_file(args.filepath)
# 3. Process the appropiate part of the puzzle
if args.part == 1:
result = part_one(args, input_text)
else:
result = part_two(args, input_text)
# 5. Set return code (0 if solution found, 2 if not)
if result:
sys.exit(0)
sys.exit(2)
# ----------------------------------------------------------------------
# module initialization
# ----------------------------------------------------------------------
if __name__ == '__main__':
main()
# ======================================================================
# end a o c _ 1 0 . p y end
# ======================================================================
| 35.179641 | 91 | 0.372936 |
import argparse
import sys
import lights
def parse_command_line():
desc = 'The Stars Align - Day 10 of Advent of Code 2018'
sample = 'sample: python aoc_10.py input.txt'
parser = argparse.ArgumentParser(description=desc,
epilog=sample)
parser.add_argument('-v', '--verbose', action='store_true', default=False,
dest='verbose', help='Print status messages to stdout')
parser.add_argument('-p', '--part', action='store', default=1, type=int,
dest='part', help='Puzzle Part (1 or 2)')
parser.add_argument('-l', '--limit', action='store', default=0, type=int,
dest='limit',
help='Maximum limit (e.g., time, size, recursion) before stopping')
parser.add_argument('filepath', metavar='FILENAME', action='store', type=str,
help="Location of puzzle input")
return parser.parse_args()
def part_one(args, input_lines):
solver = lights.Lights(part2=False, text=input_lines)
solution = solver.part_one(verbose=args.verbose, limit=args.limit)
if solution is None:
print("There is no solution")
else:
print("The solution for part one is %s" % (solution))
return solution is not None
def part_two(args, input_lines):
solver = lights.Lights(part2=True, text=input_lines)
solution = solver.part_two(verbose=args.verbose, limit=args.limit)
if solution is None:
print("There is no solution")
else:
print("The solution for part two is %s" % (solution))
return solution is not None
def from_file(filepath):
return from_text(open(filepath).read())
def from_text(text):
lines = []
for line in text.split('\n'):
line = line.rstrip(' \r')
if not line:
continue
if line.startswith('!'):
continue
lines.append(line)
return lines
def main():
args = parse_command_line()
input_text = from_file(args.filepath)
if args.part == 1:
result = part_one(args, input_text)
else:
result = part_two(args, input_text)
if result:
sys.exit(0)
sys.exit(2)
if __name__ == '__main__':
main()
| true | true |
790bfb3c72491d430ec86eaa31bd44bfeec55858 | 12,525 | py | Python | homeassistant/components/media_player/kodi.py | sbidoul/home-assistant | 75adb7ff46e64e510c206d2b1f141253bbc4997a | [
"MIT"
] | null | null | null | homeassistant/components/media_player/kodi.py | sbidoul/home-assistant | 75adb7ff46e64e510c206d2b1f141253bbc4997a | [
"MIT"
] | null | null | null | homeassistant/components/media_player/kodi.py | sbidoul/home-assistant | 75adb7ff46e64e510c206d2b1f141253bbc4997a | [
"MIT"
] | 2 | 2018-10-22T17:05:47.000Z | 2021-09-22T10:52:31.000Z | """
Support for interfacing with the XBMC/Kodi JSON-RPC API.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.kodi/
"""
import asyncio
import logging
import urllib
import aiohttp
import voluptuous as vol
from homeassistant.components.media_player import (
SUPPORT_NEXT_TRACK, SUPPORT_PAUSE, SUPPORT_PREVIOUS_TRACK, SUPPORT_SEEK,
SUPPORT_PLAY_MEDIA, SUPPORT_VOLUME_MUTE, SUPPORT_VOLUME_SET, SUPPORT_STOP,
SUPPORT_TURN_OFF, SUPPORT_PLAY, SUPPORT_VOLUME_STEP, MediaPlayerDevice,
PLATFORM_SCHEMA)
from homeassistant.const import (
STATE_IDLE, STATE_OFF, STATE_PAUSED, STATE_PLAYING, CONF_HOST, CONF_NAME,
CONF_PORT, CONF_USERNAME, CONF_PASSWORD)
from homeassistant.helpers.aiohttp_client import async_get_clientsession
import homeassistant.helpers.config_validation as cv
REQUIREMENTS = ['jsonrpc-async==0.2']
_LOGGER = logging.getLogger(__name__)
CONF_TURN_OFF_ACTION = 'turn_off_action'
DEFAULT_NAME = 'Kodi'
DEFAULT_PORT = 8080
DEFAULT_TIMEOUT = 5
TURN_OFF_ACTION = [None, 'quit', 'hibernate', 'suspend', 'reboot', 'shutdown']
SUPPORT_KODI = SUPPORT_PAUSE | SUPPORT_VOLUME_SET | SUPPORT_VOLUME_MUTE | \
SUPPORT_PREVIOUS_TRACK | SUPPORT_NEXT_TRACK | SUPPORT_SEEK | \
SUPPORT_PLAY_MEDIA | SUPPORT_STOP | SUPPORT_PLAY | SUPPORT_VOLUME_STEP
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_HOST): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port,
vol.Optional(CONF_TURN_OFF_ACTION, default=None): vol.In(TURN_OFF_ACTION),
vol.Inclusive(CONF_USERNAME, 'auth'): cv.string,
vol.Inclusive(CONF_PASSWORD, 'auth'): cv.string,
})
@asyncio.coroutine
def async_setup_platform(hass, config, async_add_entities,
discovery_info=None):
"""Setup the Kodi platform."""
host = config.get(CONF_HOST)
port = config.get(CONF_PORT)
if host.startswith('http://') or host.startswith('https://'):
host = host.lstrip('http://').lstrip('https://')
_LOGGER.warning(
"Kodi host name should no longer conatin http:// See updated "
"definitions here: "
"https://home-assistant.io/components/media_player.kodi/")
entity = KodiDevice(
hass,
name=config.get(CONF_NAME),
host=host, port=port,
username=config.get(CONF_USERNAME),
password=config.get(CONF_PASSWORD),
turn_off_action=config.get(CONF_TURN_OFF_ACTION))
yield from async_add_entities([entity], update_before_add=True)
class KodiDevice(MediaPlayerDevice):
"""Representation of a XBMC/Kodi device."""
def __init__(self, hass, name, host, port, username=None, password=None,
turn_off_action=None):
"""Initialize the Kodi device."""
import jsonrpc_async
self.hass = hass
self._name = name
kwargs = {
'timeout': DEFAULT_TIMEOUT,
'session': async_get_clientsession(hass),
}
if username is not None:
kwargs['auth'] = aiohttp.BasicAuth(username, password)
image_auth_string = "{}:{}@".format(username, password)
else:
image_auth_string = ""
self._http_url = 'http://{}:{}/jsonrpc'.format(host, port)
self._image_url = 'http://{}{}:{}/image'.format(
image_auth_string, host, port)
self._server = jsonrpc_async.Server(self._http_url, **kwargs)
self._turn_off_action = turn_off_action
self._players = list()
self._properties = None
self._item = None
self._app_properties = None
@property
def name(self):
"""Return the name of the device."""
return self._name
@asyncio.coroutine
def _get_players(self):
"""Return the active player objects or None."""
import jsonrpc_async
try:
return (yield from self._server.Player.GetActivePlayers())
except jsonrpc_async.jsonrpc.TransportError:
if self._players is not None:
_LOGGER.info('Unable to fetch kodi data')
_LOGGER.debug('Unable to fetch kodi data', exc_info=True)
return None
@property
def state(self):
"""Return the state of the device."""
if self._players is None:
return STATE_OFF
if len(self._players) == 0:
return STATE_IDLE
if self._properties['speed'] == 0 and not self._properties['live']:
return STATE_PAUSED
else:
return STATE_PLAYING
@asyncio.coroutine
def async_update(self):
"""Retrieve latest state."""
self._players = yield from self._get_players()
if self._players is not None and len(self._players) > 0:
player_id = self._players[0]['playerid']
assert isinstance(player_id, int)
self._properties = yield from self._server.Player.GetProperties(
player_id,
['time', 'totaltime', 'speed', 'live']
)
self._item = (yield from self._server.Player.GetItem(
player_id,
['title', 'file', 'uniqueid', 'thumbnail', 'artist']
))['item']
self._app_properties = \
yield from self._server.Application.GetProperties(
['volume', 'muted']
)
else:
self._properties = None
self._item = None
self._app_properties = None
@property
def volume_level(self):
"""Volume level of the media player (0..1)."""
if self._app_properties is not None:
return self._app_properties['volume'] / 100.0
@property
def is_volume_muted(self):
"""Boolean if volume is currently muted."""
if self._app_properties is not None:
return self._app_properties['muted']
@property
def media_content_id(self):
"""Content ID of current playing media."""
if self._item is not None:
return self._item.get('uniqueid', None)
@property
def media_content_type(self):
"""Content type of current playing media."""
if self._players is not None and len(self._players) > 0:
return self._players[0]['type']
@property
def media_duration(self):
"""Duration of current playing media in seconds."""
if self._properties is not None and not self._properties['live']:
total_time = self._properties['totaltime']
return (
total_time['hours'] * 3600 +
total_time['minutes'] * 60 +
total_time['seconds'])
@property
def media_image_url(self):
"""Image url of current playing media."""
if self._item is None:
return None
url_components = urllib.parse.urlparse(self._item['thumbnail'])
if url_components.scheme == 'image':
return '{}/{}'.format(
self._image_url,
urllib.parse.quote_plus(self._item['thumbnail']))
@property
def media_title(self):
"""Title of current playing media."""
# find a string we can use as a title
if self._item is not None:
return self._item.get(
'title',
self._item.get('label', self._item.get('file', 'unknown')))
@property
def supported_media_commands(self):
"""Flag of media commands that are supported."""
supported_media_commands = SUPPORT_KODI
if self._turn_off_action in TURN_OFF_ACTION:
supported_media_commands |= SUPPORT_TURN_OFF
return supported_media_commands
@asyncio.coroutine
def async_turn_off(self):
"""Execute turn_off_action to turn off media player."""
if self._turn_off_action == 'quit':
yield from self._server.Application.Quit()
elif self._turn_off_action == 'hibernate':
yield from self._server.System.Hibernate()
elif self._turn_off_action == 'suspend':
yield from self._server.System.Suspend()
elif self._turn_off_action == 'reboot':
yield from self._server.System.Reboot()
elif self._turn_off_action == 'shutdown':
yield from self._server.System.Shutdown()
else:
_LOGGER.warning('turn_off requested but turn_off_action is none')
@asyncio.coroutine
def async_volume_up(self):
"""Volume up the media player."""
assert (
yield from self._server.Input.ExecuteAction('volumeup')) == 'OK'
@asyncio.coroutine
def async_volume_down(self):
"""Volume down the media player."""
assert (
yield from self._server.Input.ExecuteAction('volumedown')) == 'OK'
def async_set_volume_level(self, volume):
"""Set volume level, range 0..1.
This method must be run in the event loop and returns a coroutine.
"""
return self._server.Application.SetVolume(int(volume * 100))
def async_mute_volume(self, mute):
"""Mute (true) or unmute (false) media player.
This method must be run in the event loop and returns a coroutine.
"""
return self._server.Application.SetMute(mute)
@asyncio.coroutine
def async_set_play_state(self, state):
"""Helper method for play/pause/toggle."""
players = yield from self._get_players()
if len(players) != 0:
yield from self._server.Player.PlayPause(
players[0]['playerid'], state)
def async_media_play_pause(self):
"""Pause media on media player.
This method must be run in the event loop and returns a coroutine.
"""
return self.async_set_play_state('toggle')
def async_media_play(self):
"""Play media.
This method must be run in the event loop and returns a coroutine.
"""
return self.async_set_play_state(True)
def async_media_pause(self):
"""Pause the media player.
This method must be run in the event loop and returns a coroutine.
"""
return self.async_set_play_state(False)
@asyncio.coroutine
def async_media_stop(self):
"""Stop the media player."""
players = yield from self._get_players()
if len(players) != 0:
yield from self._server.Player.Stop(players[0]['playerid'])
@asyncio.coroutine
def _goto(self, direction):
"""Helper method used for previous/next track."""
players = yield from self._get_players()
if len(players) != 0:
if direction == 'previous':
# first seek to position 0. Kodi goes to the beginning of the
# current track if the current track is not at the beginning.
yield from self._server.Player.Seek(players[0]['playerid'], 0)
yield from self._server.Player.GoTo(
players[0]['playerid'], direction)
def async_media_next_track(self):
"""Send next track command.
This method must be run in the event loop and returns a coroutine.
"""
return self._goto('next')
def async_media_previous_track(self):
"""Send next track command.
This method must be run in the event loop and returns a coroutine.
"""
return self._goto('previous')
@asyncio.coroutine
def async_media_seek(self, position):
"""Send seek command."""
players = yield from self._get_players()
time = {}
time['milliseconds'] = int((position % 1) * 1000)
position = int(position)
time['seconds'] = int(position % 60)
position /= 60
time['minutes'] = int(position % 60)
position /= 60
time['hours'] = int(position)
if len(players) != 0:
yield from self._server.Player.Seek(players[0]['playerid'], time)
def async_play_media(self, media_type, media_id, **kwargs):
"""Send the play_media command to the media player.
This method must be run in the event loop and returns a coroutine.
"""
if media_type == "CHANNEL":
return self._server.Player.Open(
{"item": {"channelid": int(media_id)}})
else:
return self._server.Player.Open(
{"item": {"file": str(media_id)}})
| 33.4 | 78 | 0.621876 | import asyncio
import logging
import urllib
import aiohttp
import voluptuous as vol
from homeassistant.components.media_player import (
SUPPORT_NEXT_TRACK, SUPPORT_PAUSE, SUPPORT_PREVIOUS_TRACK, SUPPORT_SEEK,
SUPPORT_PLAY_MEDIA, SUPPORT_VOLUME_MUTE, SUPPORT_VOLUME_SET, SUPPORT_STOP,
SUPPORT_TURN_OFF, SUPPORT_PLAY, SUPPORT_VOLUME_STEP, MediaPlayerDevice,
PLATFORM_SCHEMA)
from homeassistant.const import (
STATE_IDLE, STATE_OFF, STATE_PAUSED, STATE_PLAYING, CONF_HOST, CONF_NAME,
CONF_PORT, CONF_USERNAME, CONF_PASSWORD)
from homeassistant.helpers.aiohttp_client import async_get_clientsession
import homeassistant.helpers.config_validation as cv
REQUIREMENTS = ['jsonrpc-async==0.2']
_LOGGER = logging.getLogger(__name__)
CONF_TURN_OFF_ACTION = 'turn_off_action'
DEFAULT_NAME = 'Kodi'
DEFAULT_PORT = 8080
DEFAULT_TIMEOUT = 5
TURN_OFF_ACTION = [None, 'quit', 'hibernate', 'suspend', 'reboot', 'shutdown']
SUPPORT_KODI = SUPPORT_PAUSE | SUPPORT_VOLUME_SET | SUPPORT_VOLUME_MUTE | \
SUPPORT_PREVIOUS_TRACK | SUPPORT_NEXT_TRACK | SUPPORT_SEEK | \
SUPPORT_PLAY_MEDIA | SUPPORT_STOP | SUPPORT_PLAY | SUPPORT_VOLUME_STEP
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_HOST): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port,
vol.Optional(CONF_TURN_OFF_ACTION, default=None): vol.In(TURN_OFF_ACTION),
vol.Inclusive(CONF_USERNAME, 'auth'): cv.string,
vol.Inclusive(CONF_PASSWORD, 'auth'): cv.string,
})
@asyncio.coroutine
def async_setup_platform(hass, config, async_add_entities,
discovery_info=None):
host = config.get(CONF_HOST)
port = config.get(CONF_PORT)
if host.startswith('http://') or host.startswith('https://'):
host = host.lstrip('http://').lstrip('https://')
_LOGGER.warning(
"Kodi host name should no longer conatin http:// See updated "
"definitions here: "
"https://home-assistant.io/components/media_player.kodi/")
entity = KodiDevice(
hass,
name=config.get(CONF_NAME),
host=host, port=port,
username=config.get(CONF_USERNAME),
password=config.get(CONF_PASSWORD),
turn_off_action=config.get(CONF_TURN_OFF_ACTION))
yield from async_add_entities([entity], update_before_add=True)
class KodiDevice(MediaPlayerDevice):
def __init__(self, hass, name, host, port, username=None, password=None,
turn_off_action=None):
import jsonrpc_async
self.hass = hass
self._name = name
kwargs = {
'timeout': DEFAULT_TIMEOUT,
'session': async_get_clientsession(hass),
}
if username is not None:
kwargs['auth'] = aiohttp.BasicAuth(username, password)
image_auth_string = "{}:{}@".format(username, password)
else:
image_auth_string = ""
self._http_url = 'http://{}:{}/jsonrpc'.format(host, port)
self._image_url = 'http://{}{}:{}/image'.format(
image_auth_string, host, port)
self._server = jsonrpc_async.Server(self._http_url, **kwargs)
self._turn_off_action = turn_off_action
self._players = list()
self._properties = None
self._item = None
self._app_properties = None
@property
def name(self):
return self._name
@asyncio.coroutine
def _get_players(self):
import jsonrpc_async
try:
return (yield from self._server.Player.GetActivePlayers())
except jsonrpc_async.jsonrpc.TransportError:
if self._players is not None:
_LOGGER.info('Unable to fetch kodi data')
_LOGGER.debug('Unable to fetch kodi data', exc_info=True)
return None
@property
def state(self):
if self._players is None:
return STATE_OFF
if len(self._players) == 0:
return STATE_IDLE
if self._properties['speed'] == 0 and not self._properties['live']:
return STATE_PAUSED
else:
return STATE_PLAYING
@asyncio.coroutine
def async_update(self):
self._players = yield from self._get_players()
if self._players is not None and len(self._players) > 0:
player_id = self._players[0]['playerid']
assert isinstance(player_id, int)
self._properties = yield from self._server.Player.GetProperties(
player_id,
['time', 'totaltime', 'speed', 'live']
)
self._item = (yield from self._server.Player.GetItem(
player_id,
['title', 'file', 'uniqueid', 'thumbnail', 'artist']
))['item']
self._app_properties = \
yield from self._server.Application.GetProperties(
['volume', 'muted']
)
else:
self._properties = None
self._item = None
self._app_properties = None
@property
def volume_level(self):
if self._app_properties is not None:
return self._app_properties['volume'] / 100.0
@property
def is_volume_muted(self):
if self._app_properties is not None:
return self._app_properties['muted']
@property
def media_content_id(self):
if self._item is not None:
return self._item.get('uniqueid', None)
@property
def media_content_type(self):
if self._players is not None and len(self._players) > 0:
return self._players[0]['type']
@property
def media_duration(self):
if self._properties is not None and not self._properties['live']:
total_time = self._properties['totaltime']
return (
total_time['hours'] * 3600 +
total_time['minutes'] * 60 +
total_time['seconds'])
@property
def media_image_url(self):
if self._item is None:
return None
url_components = urllib.parse.urlparse(self._item['thumbnail'])
if url_components.scheme == 'image':
return '{}/{}'.format(
self._image_url,
urllib.parse.quote_plus(self._item['thumbnail']))
@property
def media_title(self):
if self._item is not None:
return self._item.get(
'title',
self._item.get('label', self._item.get('file', 'unknown')))
@property
def supported_media_commands(self):
supported_media_commands = SUPPORT_KODI
if self._turn_off_action in TURN_OFF_ACTION:
supported_media_commands |= SUPPORT_TURN_OFF
return supported_media_commands
@asyncio.coroutine
def async_turn_off(self):
if self._turn_off_action == 'quit':
yield from self._server.Application.Quit()
elif self._turn_off_action == 'hibernate':
yield from self._server.System.Hibernate()
elif self._turn_off_action == 'suspend':
yield from self._server.System.Suspend()
elif self._turn_off_action == 'reboot':
yield from self._server.System.Reboot()
elif self._turn_off_action == 'shutdown':
yield from self._server.System.Shutdown()
else:
_LOGGER.warning('turn_off requested but turn_off_action is none')
@asyncio.coroutine
def async_volume_up(self):
assert (
yield from self._server.Input.ExecuteAction('volumeup')) == 'OK'
@asyncio.coroutine
def async_volume_down(self):
assert (
yield from self._server.Input.ExecuteAction('volumedown')) == 'OK'
def async_set_volume_level(self, volume):
return self._server.Application.SetVolume(int(volume * 100))
def async_mute_volume(self, mute):
return self._server.Application.SetMute(mute)
@asyncio.coroutine
def async_set_play_state(self, state):
players = yield from self._get_players()
if len(players) != 0:
yield from self._server.Player.PlayPause(
players[0]['playerid'], state)
def async_media_play_pause(self):
return self.async_set_play_state('toggle')
def async_media_play(self):
return self.async_set_play_state(True)
def async_media_pause(self):
return self.async_set_play_state(False)
@asyncio.coroutine
def async_media_stop(self):
players = yield from self._get_players()
if len(players) != 0:
yield from self._server.Player.Stop(players[0]['playerid'])
@asyncio.coroutine
def _goto(self, direction):
players = yield from self._get_players()
if len(players) != 0:
if direction == 'previous':
yield from self._server.Player.Seek(players[0]['playerid'], 0)
yield from self._server.Player.GoTo(
players[0]['playerid'], direction)
def async_media_next_track(self):
return self._goto('next')
def async_media_previous_track(self):
return self._goto('previous')
@asyncio.coroutine
def async_media_seek(self, position):
players = yield from self._get_players()
time = {}
time['milliseconds'] = int((position % 1) * 1000)
position = int(position)
time['seconds'] = int(position % 60)
position /= 60
time['minutes'] = int(position % 60)
position /= 60
time['hours'] = int(position)
if len(players) != 0:
yield from self._server.Player.Seek(players[0]['playerid'], time)
def async_play_media(self, media_type, media_id, **kwargs):
if media_type == "CHANNEL":
return self._server.Player.Open(
{"item": {"channelid": int(media_id)}})
else:
return self._server.Player.Open(
{"item": {"file": str(media_id)}})
| true | true |
790bfb8d190d1cf2f4627a5bc380f5f90b282636 | 4,526 | py | Python | sepc/exp/freeanchor/sepc_freeanchor.py | jshilong/SEPC | 26624fdb66968f87500313fd99b7a1aa8ed61a8f | [
"Apache-2.0"
] | 337 | 2020-04-23T16:13:56.000Z | 2022-03-29T02:20:27.000Z | sepc/exp/freeanchor/sepc_freeanchor.py | jshilong/SEPC | 26624fdb66968f87500313fd99b7a1aa8ed61a8f | [
"Apache-2.0"
] | 24 | 2020-04-25T13:29:47.000Z | 2021-04-23T08:04:19.000Z | sepc/exp/freeanchor/sepc_freeanchor.py | jshilong/SEPC | 26624fdb66968f87500313fd99b7a1aa8ed61a8f | [
"Apache-2.0"
] | 58 | 2020-04-25T11:52:09.000Z | 2021-09-01T15:30:48.000Z | # model settings
model = dict(
type='RetinaNet',
pretrained='torchvision://resnet50',
backbone=dict(type='ResNet',
depth=50,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=1,
norm_cfg=dict(type='BN', requires_grad=True),
style='pytorch'),
neck=[
dict(type='FPN',
in_channels=[256, 512, 1024, 2048],
out_channels=256,
start_level=1,
add_extra_convs=True,
num_outs=5),
dict(
type='SEPC',
out_channels=256,
Pconv_num=4,
pconv_deform=True,
lcconv_deform=True,
iBN=True, # when open, please set imgs/gpu >= 4
)
],
bbox_head=dict(type='SepcFreeAnchorRetinaHead',
num_classes=81,
in_channels=256,
stacked_convs=0,
feat_channels=256,
octave_base_scale=4,
scales_per_octave=3,
anchor_ratios=[0.5, 1.0, 2.0],
anchor_strides=[8, 16, 32, 64, 128],
target_means=[.0, .0, .0, .0],
target_stds=[0.1, 0.1, 0.2, 0.2],
loss_bbox=dict(type='SmoothL1Loss',
beta=0.11,
loss_weight=0.75)))
# training and testing settings
train_cfg = dict(assigner=dict(type='MaxIoUAssigner',
pos_iou_thr=0.5,
neg_iou_thr=0.4,
min_pos_iou=0,
ignore_iof_thr=-1),
allowed_border=-1,
pos_weight=-1,
debug=False)
test_cfg = dict(nms_pre=1000,
min_bbox_size=0,
score_thr=0.05,
nms=dict(type='nms', iou_thr=0.5),
max_per_img=100)
# dataset settings
dataset_type = 'CocoDataset'
data_root = 'data/coco/'
img_norm_cfg = dict(mean=[123.675, 116.28, 103.53],
std=[58.395, 57.12, 57.375],
to_rgb=True)
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='LoadAnnotations', with_bbox=True),
dict(type='Resize', img_scale=(1333, 800), keep_ratio=True),
dict(type='RandomFlip', flip_ratio=0.5),
dict(type='Normalize', **img_norm_cfg),
dict(type='Pad', size_divisor=32),
dict(type='DefaultFormatBundle'),
dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']),
]
test_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='MultiScaleFlipAug',
img_scale=(1333, 800),
flip=False,
transforms=[
dict(type='Resize', keep_ratio=True),
dict(type='RandomFlip'),
dict(type='Normalize', **img_norm_cfg),
dict(type='Pad', size_divisor=32),
dict(type='ImageToTensor', keys=['img']),
dict(type='Collect', keys=['img']),
])
]
data = dict(
imgs_per_gpu=4,
workers_per_gpu=2,
train=dict(type=dataset_type,
ann_file=data_root + 'annotations/instances_train2017.json',
img_prefix=data_root + 'train2017/',
pipeline=train_pipeline),
val=dict(type=dataset_type,
ann_file=data_root + 'annotations/instances_val2017.json',
img_prefix=data_root + 'val2017/',
pipeline=test_pipeline),
test=dict(type=dataset_type,
ann_file=data_root + 'annotations/instances_val2017.json',
img_prefix=data_root + 'val2017/',
pipeline=test_pipeline))
evaluation = dict(interval=1, metric='bbox')
# optimizer
optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001)
optimizer_config = dict(grad_clip=dict(max_norm=35, norm_type=2))
# learning policy
lr_config = dict(policy='step',
warmup='linear',
warmup_iters=500,
warmup_ratio=1.0 / 3,
step=[8, 11])
checkpoint_config = dict(interval=1)
# yapf:disable
log_config = dict(
interval=1,
hooks=[
dict(type='TextLoggerHook'),
# dict(type='TensorboardLoggerHook')
])
# yapf:enable
# runtime settings
total_epochs = 12
dist_params = dict(backend='nccl')
log_level = 'INFO'
work_dir = './work_dirs/retinanet_free_anchor_r50_fpn_1x'
load_from = None
resume_from = None
workflow = [('train', 1)]
| 35.359375 | 75 | 0.53977 |
model = dict(
type='RetinaNet',
pretrained='torchvision://resnet50',
backbone=dict(type='ResNet',
depth=50,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=1,
norm_cfg=dict(type='BN', requires_grad=True),
style='pytorch'),
neck=[
dict(type='FPN',
in_channels=[256, 512, 1024, 2048],
out_channels=256,
start_level=1,
add_extra_convs=True,
num_outs=5),
dict(
type='SEPC',
out_channels=256,
Pconv_num=4,
pconv_deform=True,
lcconv_deform=True,
iBN=True,
)
],
bbox_head=dict(type='SepcFreeAnchorRetinaHead',
num_classes=81,
in_channels=256,
stacked_convs=0,
feat_channels=256,
octave_base_scale=4,
scales_per_octave=3,
anchor_ratios=[0.5, 1.0, 2.0],
anchor_strides=[8, 16, 32, 64, 128],
target_means=[.0, .0, .0, .0],
target_stds=[0.1, 0.1, 0.2, 0.2],
loss_bbox=dict(type='SmoothL1Loss',
beta=0.11,
loss_weight=0.75)))
train_cfg = dict(assigner=dict(type='MaxIoUAssigner',
pos_iou_thr=0.5,
neg_iou_thr=0.4,
min_pos_iou=0,
ignore_iof_thr=-1),
allowed_border=-1,
pos_weight=-1,
debug=False)
test_cfg = dict(nms_pre=1000,
min_bbox_size=0,
score_thr=0.05,
nms=dict(type='nms', iou_thr=0.5),
max_per_img=100)
dataset_type = 'CocoDataset'
data_root = 'data/coco/'
img_norm_cfg = dict(mean=[123.675, 116.28, 103.53],
std=[58.395, 57.12, 57.375],
to_rgb=True)
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='LoadAnnotations', with_bbox=True),
dict(type='Resize', img_scale=(1333, 800), keep_ratio=True),
dict(type='RandomFlip', flip_ratio=0.5),
dict(type='Normalize', **img_norm_cfg),
dict(type='Pad', size_divisor=32),
dict(type='DefaultFormatBundle'),
dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']),
]
test_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='MultiScaleFlipAug',
img_scale=(1333, 800),
flip=False,
transforms=[
dict(type='Resize', keep_ratio=True),
dict(type='RandomFlip'),
dict(type='Normalize', **img_norm_cfg),
dict(type='Pad', size_divisor=32),
dict(type='ImageToTensor', keys=['img']),
dict(type='Collect', keys=['img']),
])
]
data = dict(
imgs_per_gpu=4,
workers_per_gpu=2,
train=dict(type=dataset_type,
ann_file=data_root + 'annotations/instances_train2017.json',
img_prefix=data_root + 'train2017/',
pipeline=train_pipeline),
val=dict(type=dataset_type,
ann_file=data_root + 'annotations/instances_val2017.json',
img_prefix=data_root + 'val2017/',
pipeline=test_pipeline),
test=dict(type=dataset_type,
ann_file=data_root + 'annotations/instances_val2017.json',
img_prefix=data_root + 'val2017/',
pipeline=test_pipeline))
evaluation = dict(interval=1, metric='bbox')
optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001)
optimizer_config = dict(grad_clip=dict(max_norm=35, norm_type=2))
lr_config = dict(policy='step',
warmup='linear',
warmup_iters=500,
warmup_ratio=1.0 / 3,
step=[8, 11])
checkpoint_config = dict(interval=1)
log_config = dict(
interval=1,
hooks=[
dict(type='TextLoggerHook'),
])
total_epochs = 12
dist_params = dict(backend='nccl')
log_level = 'INFO'
work_dir = './work_dirs/retinanet_free_anchor_r50_fpn_1x'
load_from = None
resume_from = None
workflow = [('train', 1)]
| true | true |
790bfb9d722715703a84bf5209777fd1bbae58ba | 1,301 | py | Python | Apis/App/api.py | andrew962/Python | 4398da94e0f465c92bd560989ea61c324423782b | [
"MIT"
] | 1 | 2019-04-27T19:11:11.000Z | 2019-04-27T19:11:11.000Z | Apis/App/api.py | andrew962/Python | 4398da94e0f465c92bd560989ea61c324423782b | [
"MIT"
] | null | null | null | Apis/App/api.py | andrew962/Python | 4398da94e0f465c92bd560989ea61c324423782b | [
"MIT"
] | null | null | null | import pyowm
owm = pyowm.OWM('ce688b67bbf90c2a0236d4eb23d8c7bd') # You MUST provide a valid API key
# Will it be sunny tomorrow at this time in Milan (Italy) ?
#forecast = owm.daily_forecast('panama')
tomorrow = pyowm.timeutils.tomorrow()
#forecast.will_be_sunny_at(tomorrow) # Always True in Italy, right? ;-)
# Search for current weather in London (UK)
observation = owm.weather_at_place('ayangue')
w = observation.get_weather()
rete=w.get_reference_time(timeformat='date')
refe=w.get_reference_time('iso')
estatus=w.get_status()
time=w.get_sunset_time('iso')
wind=(w.get_wind()['speed'])
wind1=w.get_wind()
tempe=w.get_temperature('celsius')
tempe1=w.get_temperature('celsius')['temp_max']
l = observation.get_location()
lugar = l.get_country()
# status=Clouds>
# Weather details
#print(forecast)
print(lugar)
print(w) # <Weather - reference time=2013-12-18 09:20,
#print(rete)
#print(time)
print(estatus)# status=Clouds>
print(refe)
#print(tomorrow)#Dia de mañana
print(wind)#velocidad de viento
print(wind1)
print(w.get_humidity())#humedad
print(tempe)#temperatura
print(tempe1)
#w.get_wind() # {'speed': 4.6, 'deg': 330}
#w.get_humidity() # 87
#w.get_temperature('celsius') # {'temp_max': 10.5, 'temp': 9.7, 'temp_min': 9.0} | 29.568182 | 87 | 0.703305 | import pyowm
owm = pyowm.OWM('ce688b67bbf90c2a0236d4eb23d8c7bd')
tomorrow = pyowm.timeutils.tomorrow()
ace('ayangue')
w = observation.get_weather()
rete=w.get_reference_time(timeformat='date')
refe=w.get_reference_time('iso')
estatus=w.get_status()
time=w.get_sunset_time('iso')
wind=(w.get_wind()['speed'])
wind1=w.get_wind()
tempe=w.get_temperature('celsius')
tempe1=w.get_temperature('celsius')['temp_max']
l = observation.get_location()
lugar = l.get_country()
print(lugar)
print(w)
print(estatus)
print(refe)
rint(wind1)
print(w.get_humidity())
print(tempe)
print(tempe1)
| true | true |
790bfbd44f16d901a0167e10b3b6d1ce6c96d9dd | 239 | py | Python | behaviors/youbot_behavior_simple_test/setup.py | FlexBE/youbot_behaviors | 6f7a0330d6a9e883fc0a3dff22f44422e2379274 | [
"BSD-3-Clause"
] | 6 | 2015-11-17T15:59:38.000Z | 2019-12-04T02:24:30.000Z | behaviors/youbot_behavior_simple_test/setup.py | FlexBE/youbot_behaviors | 6f7a0330d6a9e883fc0a3dff22f44422e2379274 | [
"BSD-3-Clause"
] | null | null | null | behaviors/youbot_behavior_simple_test/setup.py | FlexBE/youbot_behaviors | 6f7a0330d6a9e883fc0a3dff22f44422e2379274 | [
"BSD-3-Clause"
] | 2 | 2018-05-09T13:01:30.000Z | 2022-03-30T10:16:15.000Z | #!/usr/bin/env python
from distutils.core import setup
from catkin_pkg.python_setup import generate_distutils_setup
d = generate_distutils_setup(
packages = ['youbot_behavior_simple_test'],
package_dir = {'': 'src'}
)
setup(**d) | 21.727273 | 60 | 0.748954 |
from distutils.core import setup
from catkin_pkg.python_setup import generate_distutils_setup
d = generate_distutils_setup(
packages = ['youbot_behavior_simple_test'],
package_dir = {'': 'src'}
)
setup(**d) | true | true |
790bfbf2fb99fe349874ed1aa55887a5ca95e7c6 | 357 | py | Python | uw_sdbmyuw/dao.py | uw-it-aca/uw-restclients-sdbmyuw | 70932a09b47530100e104b1921b72bff822c03c1 | [
"Apache-2.0"
] | null | null | null | uw_sdbmyuw/dao.py | uw-it-aca/uw-restclients-sdbmyuw | 70932a09b47530100e104b1921b72bff822c03c1 | [
"Apache-2.0"
] | 8 | 2017-11-08T00:18:44.000Z | 2021-06-01T17:14:30.000Z | uw_sdbmyuw/dao.py | uw-it-aca/uw-restclients-sdbmyuw | 70932a09b47530100e104b1921b72bff822c03c1 | [
"Apache-2.0"
] | null | null | null | # Copyright 2021 UW-IT, University of Washington
# SPDX-License-Identifier: Apache-2.0
import os
from os.path import abspath, dirname
from restclients_core.dao import DAO
class Sdbmyuw_DAO(DAO):
def service_name(self):
return 'sdbmyuw'
def service_mock_paths(self):
return [abspath(os.path.join(dirname(__file__), "resources"))]
| 23.8 | 70 | 0.731092 |
import os
from os.path import abspath, dirname
from restclients_core.dao import DAO
class Sdbmyuw_DAO(DAO):
def service_name(self):
return 'sdbmyuw'
def service_mock_paths(self):
return [abspath(os.path.join(dirname(__file__), "resources"))]
| true | true |
790bfcf51a7b404e975bf5b7d7f7e1f8ac744c16 | 2,104 | py | Python | mewarpx/examples/thermionic_diode.py | ModernElectron/WarpX | 563813bc125a01a1a54267a3d4bb3ba77bcc68a3 | [
"BSD-3-Clause-LBNL"
] | 1 | 2021-06-23T23:38:50.000Z | 2021-06-23T23:38:50.000Z | mewarpx/examples/thermionic_diode.py | ModernElectron/WarpX | 563813bc125a01a1a54267a3d4bb3ba77bcc68a3 | [
"BSD-3-Clause-LBNL"
] | 106 | 2021-06-08T23:57:54.000Z | 2022-03-08T00:36:46.000Z | mewarpx/examples/thermionic_diode.py | ModernElectron/WarpX | 563813bc125a01a1a54267a3d4bb3ba77bcc68a3 | [
"BSD-3-Clause-LBNL"
] | 1 | 2021-06-21T18:50:43.000Z | 2021-06-21T18:50:43.000Z | import argparse
import sys
import numpy as np
from mewarpx.utils_store import util as mwxutil
mwxutil.init_libwarpx(ndim=2, rz=False)
from mewarpx.mwxrun import mwxrun
from mewarpx.setups_store import diode_setup
def run_simulation(V_bias, steps, save_current):
####################################
# Diode setup
####################################
run = diode_setup.DiodeRun_V1(
CATHODE_TEMP = 1100.0 + 273.15, # K
CATHODE_A = 6e5, # A/m^2/K^2
CATHODE_PHI = 2.11, # eV
USE_SCHOTTKY = True,
ANODE_TEMP = 200, # K
ANODE_PHI = 1.4, # eV
V_ANODE_CATHODE = V_bias, # V
D_CA = 50e-6, # m
DT = 0.5e-12, # s
NX = 8,
NZ = 128,
DIRECT_SOLVER = True,
NPPC = 100,
TOTAL_TIMESTEPS = steps,
DIAG_STEPS = ((steps // 5) if steps > 10 else steps),
)
# Only the functions we change from defaults are listed here
run.setup_run(
init_runinfo=True,
init_fluxdiag=True,
init_simcontrol=True,
init_warpx=True
)
#################################
# Simulation run
#################################
mwxrun.simulation.step(steps)
#################################
# Save IV results
#################################
if save_current and mwxrun.me == 0:
key = ('scrape', 'anode', 'electrons')
J_diode = run.fluxdiag.ts_dict[key].get_averagevalue_by_key('J')
print(f'{V_bias} {J_diode}')
with open(f'results_d_{int(run.D_CA*1e6)}.dat', 'a') as f:
f.write(f'{V_bias} {J_diode}\n')
parser = argparse.ArgumentParser()
parser.add_argument('--V', help='bias voltage in Volt', type=float, default=0)
parser.add_argument('--steps', help='set the number of simulation steps',
type=int, default=3000)
parser.add_argument('--save', help='save voltage and current pairs',
default=False, action='store_true')
args, left = parser.parse_known_args()
sys.argv = sys.argv[:1]+left
run_simulation(args.V, args.steps, args.save)
| 28.821918 | 78 | 0.551806 | import argparse
import sys
import numpy as np
from mewarpx.utils_store import util as mwxutil
mwxutil.init_libwarpx(ndim=2, rz=False)
from mewarpx.mwxrun import mwxrun
from mewarpx.setups_store import diode_setup
def run_simulation(V_bias, steps, save_current):
| true | true |
790bfda2727dc109030b122bbd79807846d3f166 | 7,817 | py | Python | tests/validation/tests.py | pavanv/django-tastypie | b4ffc642aa56d25d3c577ccae0a03c820b71c4bc | [
"BSD-3-Clause"
] | 1,570 | 2015-02-03T10:19:33.000Z | 2022-03-29T10:34:18.000Z | tests/validation/tests.py | pavanv/django-tastypie | b4ffc642aa56d25d3c577ccae0a03c820b71c4bc | [
"BSD-3-Clause"
] | 587 | 2015-02-06T13:59:23.000Z | 2022-03-09T22:56:30.000Z | tests/validation/tests.py | pavanv/django-tastypie | b4ffc642aa56d25d3c577ccae0a03c820b71c4bc | [
"BSD-3-Clause"
] | 492 | 2015-02-07T06:18:36.000Z | 2022-03-29T19:06:44.000Z | import json
from django.test.utils import override_settings
from tastypie.exceptions import NotFound
from basic.models import Note
from testcases import TestCaseWithFixture
from django.test.testcases import SimpleTestCase
@override_settings(ROOT_URLCONF='validation.api.urls')
class FilteringErrorsTestCase(TestCaseWithFixture):
def test_valid_date(self):
resp = self.client.get('/api/v1/notes/', data={
'format': 'json',
'created__gte': '2010-03-31 00:00:00Z'
})
self.assertEqual(resp.status_code, 200)
deserialized = json.loads(resp.content.decode('utf-8'))
self.assertEqual(len(deserialized['objects']), Note.objects.filter(created__gte='2010-03-31 00:00:00Z').count())
def test_invalid_date(self):
resp = self.client.get('/api/v1/notes/', data={
'format': 'json',
'created__gte': 'foo-baz-bar'
})
self.assertEqual(resp.status_code, 400)
@override_settings(ROOT_URLCONF='validation.api.urls')
class PostRelatedUrlValidationTestCase(TestCaseWithFixture):
def test_valid_url(self):
data_with_pk = json.dumps({
'title': 'Test title related pk',
'slug': 'test-slug-related-pk',
'content': 'This is the content',
'user': {'pk': 1},
})
data_with_url = json.dumps({
'title': 'Test title related url',
'slug': 'test-slug-related-url',
'content': 'This is the content',
'user': '/api/v1/users/1/',
})
resp_with_pk = self.client.post('/api/v1/notes/', data=data_with_pk, content_type='application/json')
self.assertEqual(resp_with_pk.status_code, 201)
note_posted_with_pk = json.loads(self.client.get(resp_with_pk['location']).content.decode('utf-8'))
resp_with_url = self.client.post('/api/v1/notes/', data=data_with_url, content_type='application/json')
self.assertEqual(resp_with_url.status_code, 201)
note_posted_with_url = json.loads(self.client.get(resp_with_url['location']).content.decode('utf-8'))
self.assertEqual(note_posted_with_pk['user'], note_posted_with_url['user'])
def test_invalid_url(self):
data = json.dumps({
'title': 'Test title related url',
'slug': 'test-slug-related-url',
'content': 'This is the content',
'user': 'invalid-url',
})
with self.assertRaises(NotFound):
self.client.post('/api/v1/notes/', data=data, content_type='application/json')
@override_settings(ROOT_URLCONF='validation.api.urls')
class PostNestResouceValidationTestCase(TestCaseWithFixture):
def test_valid_data(self):
data = json.dumps({
'title': 'Test Title',
'slug': 'test-title',
'content': 'This is the content',
'user': {'pk': 1}, # loaded from fixtures
'annotated': {'annotations': 'This is an annotations'},
})
resp = self.client.post('/api/v1/notes/', data=data, content_type='application/json')
self.assertEqual(resp.status_code, 201)
note = json.loads(self.client.get(resp['location']).content.decode('utf-8'))
self.assertTrue(note['annotated'])
def test_invalid_data(self):
data = json.dumps({
'title': '',
'slug': 'test-title',
'content': 'This is the content',
'user': {'pk': 1}, # loaded from fixtures
'annotated': {'annotations': ''},
})
resp = self.client.post('/api/v1/notes/', data=data, content_type='application/json')
self.assertEqual(resp.status_code, 400)
self.assertEqual(json.loads(resp.content.decode('utf-8')), {
'notes': {
'title': ['This field is required.']
},
'annotated': {
'annotations': ['This field is required.']
}
})
@override_settings(ROOT_URLCONF='validation.api.urls')
class PutDetailNestResouceValidationTestCase(TestCaseWithFixture):
def test_valid_data(self):
data = json.dumps({
'title': 'Test Title',
'slug': 'test-title',
'content': 'This is the content',
'annotated': {'annotations': 'This is another annotations'},
})
resp = self.client.put('/api/v1/notes/1/', data=data, content_type='application/json')
self.assertEqual(resp.status_code, 204)
note = json.loads(self.client.get('/api/v1/notes/1/', content_type='application/json').content.decode('utf-8'))
self.assertTrue(note['annotated'])
self.assertEqual('test-title', note['slug'])
def test_invalid_data(self):
data = json.dumps({
'title': '',
'slug': '',
'content': 'This is the content',
'annotated': {'annotations': None},
})
resp = self.client.put('/api/v1/notes/1/', data=data, content_type='application/json')
self.assertEqual(resp.status_code, 400)
self.assertEqual(json.loads(resp.content.decode('utf-8')), {
'notes': {
'slug': ['This field is required.'],
'title': ['This field is required.']
},
'annotated': {
'annotations': ['This field is required.']
}
})
@override_settings(ROOT_URLCONF='validation.api.urls')
class PutListNestResouceValidationTestCase(TestCaseWithFixture):
def test_valid_data(self):
data = json.dumps({'objects': [
{
'id': 1,
'title': 'Test Title',
'slug': 'test-title',
'content': 'This is the content',
'annotated': {'annotations': 'This is another annotations'},
'user': {'id': 1}
},
{
'id': 2,
'title': 'Test Title',
'slug': 'test-title',
'content': 'This is the content',
'annotated': {'annotations': 'This is the third annotations'},
'user': {'id': 1}
}
]})
resp = self.client.put('/api/v1/notes/', data=data, content_type='application/json')
self.assertEqual(resp.status_code, 204)
note = json.loads(self.client.get('/api/v1/notes/1/', content_type='application/json').content.decode('utf-8'))
self.assertTrue(note['annotated'])
note = json.loads(self.client.get('/api/v1/notes/2/', content_type='application/json').content.decode('utf-8'))
self.assertTrue(note['annotated'])
def test_invalid_data(self):
data = json.dumps({'objects': [
{
'id': 1,
'title': 'Test Title',
'slug': 'test-title',
'annotated': {'annotations': None},
'user': {'id': 1}
},
{
'id': 2,
'title': 'Test Title',
'annotated': {'annotations': None},
'user': {'id': 1}
}
]})
resp = self.client.put('/api/v1/notes/', data=data, content_type='application/json')
self.assertEqual(resp.status_code, 400)
self.assertEqual(json.loads(resp.content.decode('utf-8')), {
'notes': {
'content': ['This field is required.']
},
'annotated': {
'annotations': ['This field is required.']
}
})
class TestJSONPValidation(SimpleTestCase):
"""
Explicitly run the doctests for tastypie.utils.validate_jsonp
"""
def test_jsonp(self):
import tastypie.utils.validate_jsonp
import doctest
doctest.testmod(tastypie.utils.validate_jsonp)
| 38.131707 | 120 | 0.567609 | import json
from django.test.utils import override_settings
from tastypie.exceptions import NotFound
from basic.models import Note
from testcases import TestCaseWithFixture
from django.test.testcases import SimpleTestCase
@override_settings(ROOT_URLCONF='validation.api.urls')
class FilteringErrorsTestCase(TestCaseWithFixture):
def test_valid_date(self):
resp = self.client.get('/api/v1/notes/', data={
'format': 'json',
'created__gte': '2010-03-31 00:00:00Z'
})
self.assertEqual(resp.status_code, 200)
deserialized = json.loads(resp.content.decode('utf-8'))
self.assertEqual(len(deserialized['objects']), Note.objects.filter(created__gte='2010-03-31 00:00:00Z').count())
def test_invalid_date(self):
resp = self.client.get('/api/v1/notes/', data={
'format': 'json',
'created__gte': 'foo-baz-bar'
})
self.assertEqual(resp.status_code, 400)
@override_settings(ROOT_URLCONF='validation.api.urls')
class PostRelatedUrlValidationTestCase(TestCaseWithFixture):
def test_valid_url(self):
data_with_pk = json.dumps({
'title': 'Test title related pk',
'slug': 'test-slug-related-pk',
'content': 'This is the content',
'user': {'pk': 1},
})
data_with_url = json.dumps({
'title': 'Test title related url',
'slug': 'test-slug-related-url',
'content': 'This is the content',
'user': '/api/v1/users/1/',
})
resp_with_pk = self.client.post('/api/v1/notes/', data=data_with_pk, content_type='application/json')
self.assertEqual(resp_with_pk.status_code, 201)
note_posted_with_pk = json.loads(self.client.get(resp_with_pk['location']).content.decode('utf-8'))
resp_with_url = self.client.post('/api/v1/notes/', data=data_with_url, content_type='application/json')
self.assertEqual(resp_with_url.status_code, 201)
note_posted_with_url = json.loads(self.client.get(resp_with_url['location']).content.decode('utf-8'))
self.assertEqual(note_posted_with_pk['user'], note_posted_with_url['user'])
def test_invalid_url(self):
data = json.dumps({
'title': 'Test title related url',
'slug': 'test-slug-related-url',
'content': 'This is the content',
'user': 'invalid-url',
})
with self.assertRaises(NotFound):
self.client.post('/api/v1/notes/', data=data, content_type='application/json')
@override_settings(ROOT_URLCONF='validation.api.urls')
class PostNestResouceValidationTestCase(TestCaseWithFixture):
def test_valid_data(self):
data = json.dumps({
'title': 'Test Title',
'slug': 'test-title',
'content': 'This is the content',
'user': {'pk': 1},
'annotated': {'annotations': 'This is an annotations'},
})
resp = self.client.post('/api/v1/notes/', data=data, content_type='application/json')
self.assertEqual(resp.status_code, 201)
note = json.loads(self.client.get(resp['location']).content.decode('utf-8'))
self.assertTrue(note['annotated'])
def test_invalid_data(self):
data = json.dumps({
'title': '',
'slug': 'test-title',
'content': 'This is the content',
'user': {'pk': 1},
'annotated': {'annotations': ''},
})
resp = self.client.post('/api/v1/notes/', data=data, content_type='application/json')
self.assertEqual(resp.status_code, 400)
self.assertEqual(json.loads(resp.content.decode('utf-8')), {
'notes': {
'title': ['This field is required.']
},
'annotated': {
'annotations': ['This field is required.']
}
})
@override_settings(ROOT_URLCONF='validation.api.urls')
class PutDetailNestResouceValidationTestCase(TestCaseWithFixture):
def test_valid_data(self):
data = json.dumps({
'title': 'Test Title',
'slug': 'test-title',
'content': 'This is the content',
'annotated': {'annotations': 'This is another annotations'},
})
resp = self.client.put('/api/v1/notes/1/', data=data, content_type='application/json')
self.assertEqual(resp.status_code, 204)
note = json.loads(self.client.get('/api/v1/notes/1/', content_type='application/json').content.decode('utf-8'))
self.assertTrue(note['annotated'])
self.assertEqual('test-title', note['slug'])
def test_invalid_data(self):
data = json.dumps({
'title': '',
'slug': '',
'content': 'This is the content',
'annotated': {'annotations': None},
})
resp = self.client.put('/api/v1/notes/1/', data=data, content_type='application/json')
self.assertEqual(resp.status_code, 400)
self.assertEqual(json.loads(resp.content.decode('utf-8')), {
'notes': {
'slug': ['This field is required.'],
'title': ['This field is required.']
},
'annotated': {
'annotations': ['This field is required.']
}
})
@override_settings(ROOT_URLCONF='validation.api.urls')
class PutListNestResouceValidationTestCase(TestCaseWithFixture):
def test_valid_data(self):
data = json.dumps({'objects': [
{
'id': 1,
'title': 'Test Title',
'slug': 'test-title',
'content': 'This is the content',
'annotated': {'annotations': 'This is another annotations'},
'user': {'id': 1}
},
{
'id': 2,
'title': 'Test Title',
'slug': 'test-title',
'content': 'This is the content',
'annotated': {'annotations': 'This is the third annotations'},
'user': {'id': 1}
}
]})
resp = self.client.put('/api/v1/notes/', data=data, content_type='application/json')
self.assertEqual(resp.status_code, 204)
note = json.loads(self.client.get('/api/v1/notes/1/', content_type='application/json').content.decode('utf-8'))
self.assertTrue(note['annotated'])
note = json.loads(self.client.get('/api/v1/notes/2/', content_type='application/json').content.decode('utf-8'))
self.assertTrue(note['annotated'])
def test_invalid_data(self):
data = json.dumps({'objects': [
{
'id': 1,
'title': 'Test Title',
'slug': 'test-title',
'annotated': {'annotations': None},
'user': {'id': 1}
},
{
'id': 2,
'title': 'Test Title',
'annotated': {'annotations': None},
'user': {'id': 1}
}
]})
resp = self.client.put('/api/v1/notes/', data=data, content_type='application/json')
self.assertEqual(resp.status_code, 400)
self.assertEqual(json.loads(resp.content.decode('utf-8')), {
'notes': {
'content': ['This field is required.']
},
'annotated': {
'annotations': ['This field is required.']
}
})
class TestJSONPValidation(SimpleTestCase):
def test_jsonp(self):
import tastypie.utils.validate_jsonp
import doctest
doctest.testmod(tastypie.utils.validate_jsonp)
| true | true |
790bfdd125a54aeb226d078c352496de6419c71c | 9,413 | py | Python | managesf/tests/test_resources_storyboard.py | enovance/managesf | 5f6bc6857ebbffb929a063ccc3ab94317fa3784a | [
"Apache-2.0"
] | null | null | null | managesf/tests/test_resources_storyboard.py | enovance/managesf | 5f6bc6857ebbffb929a063ccc3ab94317fa3784a | [
"Apache-2.0"
] | null | null | null | managesf/tests/test_resources_storyboard.py | enovance/managesf | 5f6bc6857ebbffb929a063ccc3ab94317fa3784a | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
#
# Copyright (c) 2017 Red Hat, Inc.
#
# 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.
from unittest import TestCase
from mock import patch, call, Mock
from contextlib import nested
from managesf.tests import dummy_conf
from managesf.model.yamlbkd.resources.storyboard import StoryboardOps
class StoryboardOpsTest(TestCase):
def test_is_activated(self):
conf = dummy_conf()
s = StoryboardOps(conf, None)
project = {'issue-tracker': 'SFStoryboard'}
self.assertTrue(s.is_activated(**project))
project = {'issue-tracker': ''}
self.assertFalse(s.is_activated(**project))
conf.services.remove('SFStoryboard')
project = {'issue-tracker': 'SFStoryboard'}
self.assertFalse(s.is_activated(**project))
def test_extra_validation(self):
conf = dummy_conf()
s = StoryboardOps(conf, None)
project = {
'name': 'project1',
'source-repositories': ['repo1', 'repo2']
}
logs = s.extra_validations(**project)
self.assertTrue(len(logs) == 0)
project = {
'name': 'project2',
'source-repositories': ['repo', '-hjook']
}
logs = s.extra_validations(**project)
self.assertTrue('Minimal len is 5' in logs[0])
self.assertTrue('should match the RE' in logs[1])
def test_update_project(self):
class FakeItem(object):
def __init__(self, name, id):
self.name = name
self.id = id
conf = dummy_conf()
s = StoryboardOps(conf, None)
patches = [
patch('storyboardclient.v1.projects.ProjectsManager.get_all'),
patch('storyboardclient.v1.projects.ProjectsManager.update'),
patch('storyboardclient.v1.projects.ProjectsManager.create')]
with nested(*patches) as (get_all, update, create):
get_all.return_value = [FakeItem('project1', 1)]
s.update_project('project1', 'A desc')
self.assertTrue(get_all.called)
self.assertTrue(update.called)
self.assertFalse(create.called)
with nested(*patches) as (get_all, update, create):
get_all.return_value = [FakeItem('project1', 1)]
s.update_project('project2', 'A desc')
self.assertTrue(get_all.called)
self.assertFalse(update.called)
self.assertTrue(create.called)
def test_update_project_group(self):
class FakeItem(object):
def __init__(self, name, id):
self.name = name
self.id = id
conf = dummy_conf()
patches = [
patch('storyboardclient.v1.project_groups.'
'ProjectGroupsManager.get_all'),
patch('storyboardclient.v1.project_groups.'
'ProjectGroupsManager.create'),
patch.object(StoryboardOps, 'update_project'),
patch('storyboardclient.v1.project_groups.'
'ProjectGroupsManager.get'),
patch('storyboardclient.v1.project_groups.'
'ProjectGroupsManager.update'),
patch('storyboardclient.v1.projects.'
'ProjectsManager.get_all')]
with nested(*patches) as (get_all, create, update_project,
get, update, p_get_all):
new = {
'resources': {
'repos': {
'project1': {'description': 'A desc'},
'project2': {'description': 'A desc'}
}
}
}
s = StoryboardOps(conf, new)
get_all.return_value = [FakeItem('pg1', 1)]
fake_subprojects = [
FakeItem('project1', 1),
FakeItem('project2', 2)]
mput = Mock()
mdelete = Mock()
class fprojects():
def get_all(self):
return fake_subprojects
def put(self, id):
mput(id)
def delete(self, id):
mdelete(id)
class NestedProjects():
def __init__(self):
self.projects = fprojects()
get.return_value = NestedProjects()
update.return_value = NestedProjects()
p_get_all.return_value = fake_subprojects
# Here projects are already included in the project
# group so nothing will be added/removed in the project
# group. Just projects will be updated.
s.update_project_groups(
**{'name': 'pg1',
'source-repositories': ['project1', 'project2']})
self.assertFalse(mput.called)
self.assertFalse(mdelete.called)
self.assertTrue(len(update_project.mock_calls), 2)
# Here project1 and project2 are already included but
# the resources project decription only defines the
# project2 to be included. So we make sure the delete
# is called with id 1.
mput.reset_mock()
mdelete.reset_mock()
update_project.reset_mock()
s.update_project_groups(
**{'name': 'pg1',
'source-repositories': ['project2']})
self.assertFalse(mput.called)
self.assertTrue(mdelete.called)
self.assertListEqual(mdelete.call_args_list, [call(1)])
self.assertTrue(len(update_project.mock_calls), 1)
# Here only project1 is already included but
# the resources project decription defines the
# project1 and project2 to be included. So we make sure
# the put is called with id 2.
mput.reset_mock()
mdelete.reset_mock()
update_project.reset_mock()
fake_subprojects = [
FakeItem('project1', 1)]
s.update_project_groups(
**{'name': 'pg1',
'source-repositories': ['project1', 'project2']})
self.assertTrue(mput.called)
self.assertListEqual(mput.call_args_list, [call(2)])
self.assertFalse(mdelete.called)
self.assertTrue(len(update_project.mock_calls), 1)
# Here the project group does not exist. So we verify
# it is created and provisionned with two projects
# included.
get_all.return_value = []
p_get_all.return_value = [
FakeItem('project1', 1),
FakeItem('project2', 2)]
fake_subprojects = []
get.return_value = NestedProjects()
update.return_value = NestedProjects()
mput.reset_mock()
mdelete.reset_mock()
update_project.reset_mock()
s.update_project_groups(
**{'name': 'pg1',
'source-repositories': ['project1', 'project2']})
self.assertTrue(create.called)
self.assertTrue(len(update_project.mock_calls), 2)
self.assertTrue(len(mput.mock_calls), 2)
self.assertFalse(mdelete.called)
def test_delete_project_group(self):
class FakeItem(object):
def __init__(self, name, id):
self.name = name
self.id = id
conf = dummy_conf()
patches = [
patch('storyboardclient.v1.project_groups.'
'ProjectGroupsManager.get_all'),
patch('storyboardclient.v1.project_groups.'
'ProjectGroupsManager.get'),
patch('storyboardclient.v1.project_groups.'
'ProjectGroupsManager.update'),
patch('storyboardclient.v1.project_groups.'
'ProjectGroupsManager.delete')]
with nested(*patches) as (get_all, get, update, delete):
s = StoryboardOps(conf, None)
get_all.return_value = [FakeItem('pg1', 3)]
mdelete = Mock()
fake_subprojects = [
FakeItem('project1', 1),
FakeItem('project2', 2)]
class fprojects():
def get_all(self):
return fake_subprojects
def delete(self, id):
mdelete(id)
class NestedProjects():
def __init__(self):
self.projects = fprojects()
get.return_value = NestedProjects()
update.return_value = NestedProjects()
s.delete_project_groups(**{'name': 'pg1'})
self.assertEqual(len(mdelete.call_args_list), 2)
self.assertIn(call(1), mdelete.call_args_list)
self.assertIn(call(2), mdelete.call_args_list)
self.assertListEqual(delete.call_args_list, [call(id=3)])
| 39.220833 | 75 | 0.564432 |
from unittest import TestCase
from mock import patch, call, Mock
from contextlib import nested
from managesf.tests import dummy_conf
from managesf.model.yamlbkd.resources.storyboard import StoryboardOps
class StoryboardOpsTest(TestCase):
def test_is_activated(self):
conf = dummy_conf()
s = StoryboardOps(conf, None)
project = {'issue-tracker': 'SFStoryboard'}
self.assertTrue(s.is_activated(**project))
project = {'issue-tracker': ''}
self.assertFalse(s.is_activated(**project))
conf.services.remove('SFStoryboard')
project = {'issue-tracker': 'SFStoryboard'}
self.assertFalse(s.is_activated(**project))
def test_extra_validation(self):
conf = dummy_conf()
s = StoryboardOps(conf, None)
project = {
'name': 'project1',
'source-repositories': ['repo1', 'repo2']
}
logs = s.extra_validations(**project)
self.assertTrue(len(logs) == 0)
project = {
'name': 'project2',
'source-repositories': ['repo', '-hjook']
}
logs = s.extra_validations(**project)
self.assertTrue('Minimal len is 5' in logs[0])
self.assertTrue('should match the RE' in logs[1])
def test_update_project(self):
class FakeItem(object):
def __init__(self, name, id):
self.name = name
self.id = id
conf = dummy_conf()
s = StoryboardOps(conf, None)
patches = [
patch('storyboardclient.v1.projects.ProjectsManager.get_all'),
patch('storyboardclient.v1.projects.ProjectsManager.update'),
patch('storyboardclient.v1.projects.ProjectsManager.create')]
with nested(*patches) as (get_all, update, create):
get_all.return_value = [FakeItem('project1', 1)]
s.update_project('project1', 'A desc')
self.assertTrue(get_all.called)
self.assertTrue(update.called)
self.assertFalse(create.called)
with nested(*patches) as (get_all, update, create):
get_all.return_value = [FakeItem('project1', 1)]
s.update_project('project2', 'A desc')
self.assertTrue(get_all.called)
self.assertFalse(update.called)
self.assertTrue(create.called)
def test_update_project_group(self):
class FakeItem(object):
def __init__(self, name, id):
self.name = name
self.id = id
conf = dummy_conf()
patches = [
patch('storyboardclient.v1.project_groups.'
'ProjectGroupsManager.get_all'),
patch('storyboardclient.v1.project_groups.'
'ProjectGroupsManager.create'),
patch.object(StoryboardOps, 'update_project'),
patch('storyboardclient.v1.project_groups.'
'ProjectGroupsManager.get'),
patch('storyboardclient.v1.project_groups.'
'ProjectGroupsManager.update'),
patch('storyboardclient.v1.projects.'
'ProjectsManager.get_all')]
with nested(*patches) as (get_all, create, update_project,
get, update, p_get_all):
new = {
'resources': {
'repos': {
'project1': {'description': 'A desc'},
'project2': {'description': 'A desc'}
}
}
}
s = StoryboardOps(conf, new)
get_all.return_value = [FakeItem('pg1', 1)]
fake_subprojects = [
FakeItem('project1', 1),
FakeItem('project2', 2)]
mput = Mock()
mdelete = Mock()
class fprojects():
def get_all(self):
return fake_subprojects
def put(self, id):
mput(id)
def delete(self, id):
mdelete(id)
class NestedProjects():
def __init__(self):
self.projects = fprojects()
get.return_value = NestedProjects()
update.return_value = NestedProjects()
p_get_all.return_value = fake_subprojects
s.update_project_groups(
**{'name': 'pg1',
'source-repositories': ['project1', 'project2']})
self.assertFalse(mput.called)
self.assertFalse(mdelete.called)
self.assertTrue(len(update_project.mock_calls), 2)
mput.reset_mock()
mdelete.reset_mock()
update_project.reset_mock()
s.update_project_groups(
**{'name': 'pg1',
'source-repositories': ['project2']})
self.assertFalse(mput.called)
self.assertTrue(mdelete.called)
self.assertListEqual(mdelete.call_args_list, [call(1)])
self.assertTrue(len(update_project.mock_calls), 1)
mput.reset_mock()
mdelete.reset_mock()
update_project.reset_mock()
fake_subprojects = [
FakeItem('project1', 1)]
s.update_project_groups(
**{'name': 'pg1',
'source-repositories': ['project1', 'project2']})
self.assertTrue(mput.called)
self.assertListEqual(mput.call_args_list, [call(2)])
self.assertFalse(mdelete.called)
self.assertTrue(len(update_project.mock_calls), 1)
get_all.return_value = []
p_get_all.return_value = [
FakeItem('project1', 1),
FakeItem('project2', 2)]
fake_subprojects = []
get.return_value = NestedProjects()
update.return_value = NestedProjects()
mput.reset_mock()
mdelete.reset_mock()
update_project.reset_mock()
s.update_project_groups(
**{'name': 'pg1',
'source-repositories': ['project1', 'project2']})
self.assertTrue(create.called)
self.assertTrue(len(update_project.mock_calls), 2)
self.assertTrue(len(mput.mock_calls), 2)
self.assertFalse(mdelete.called)
def test_delete_project_group(self):
class FakeItem(object):
def __init__(self, name, id):
self.name = name
self.id = id
conf = dummy_conf()
patches = [
patch('storyboardclient.v1.project_groups.'
'ProjectGroupsManager.get_all'),
patch('storyboardclient.v1.project_groups.'
'ProjectGroupsManager.get'),
patch('storyboardclient.v1.project_groups.'
'ProjectGroupsManager.update'),
patch('storyboardclient.v1.project_groups.'
'ProjectGroupsManager.delete')]
with nested(*patches) as (get_all, get, update, delete):
s = StoryboardOps(conf, None)
get_all.return_value = [FakeItem('pg1', 3)]
mdelete = Mock()
fake_subprojects = [
FakeItem('project1', 1),
FakeItem('project2', 2)]
class fprojects():
def get_all(self):
return fake_subprojects
def delete(self, id):
mdelete(id)
class NestedProjects():
def __init__(self):
self.projects = fprojects()
get.return_value = NestedProjects()
update.return_value = NestedProjects()
s.delete_project_groups(**{'name': 'pg1'})
self.assertEqual(len(mdelete.call_args_list), 2)
self.assertIn(call(1), mdelete.call_args_list)
self.assertIn(call(2), mdelete.call_args_list)
self.assertListEqual(delete.call_args_list, [call(id=3)])
| true | true |
790bfde1ab6b6b3d18bbab24e581e7b4bc432cbb | 2,652 | py | Python | plugins/QuoteGrabs/__init__.py | jlu5/Limnoria | 0e1e37a5a2bd5b717e11320b20773644b44502dd | [
"BSD-3-Clause"
] | 1 | 2021-11-11T04:48:33.000Z | 2021-11-11T04:48:33.000Z | plugins/QuoteGrabs/__init__.py | jlu5/Limnoria | 0e1e37a5a2bd5b717e11320b20773644b44502dd | [
"BSD-3-Clause"
] | 4 | 2017-10-23T15:16:40.000Z | 2018-05-27T10:19:52.000Z | plugins/QuoteGrabs/__init__.py | jlu5/Limnoria | 0e1e37a5a2bd5b717e11320b20773644b44502dd | [
"BSD-3-Clause"
] | 1 | 2021-11-11T04:48:23.000Z | 2021-11-11T04:48:23.000Z | ###
# Copyright (c) 2004, Daniel DiPaolo
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions, and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions, and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the author of this software nor the name of
# contributors to this software may be used to endorse or promote products
# derived from this software without specific prior written consent.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
###
"""
Quotegrabs are like IRC sound bites. When someone says something funny,
incriminating, stupid, outrageous, ... anything that might be worth
remembering, you can grab that quote for that person. With this plugin, you
can store many quotes per person and display their most recent quote, as well
as see who "grabbed" the quote in the first place.
"""
import supybot
import supybot.world as world
# Use this for the version of this plugin. You may wish to put a CVS keyword
# in here if you're keeping the plugin in CVS or some similar system.
__version__ = "%%VERSION%%"
# XXX Replace this with an appropriate author or supybot.Author instance.
__author__ = supybot.authors.strike
# This is a dictionary mapping supybot.Author instances to lists of
# contributions.
__contributors__ = {}
from . import config
from . import plugin
from imp import reload
reload(plugin) # In case we're being reloaded.
if world.testing:
from . import test
Class = plugin.Class
configure = config.configure
# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:
| 40.8 | 79 | 0.768854 |
import supybot
import supybot.world as world
__version__ = "%%VERSION%%"
# XXX Replace this with an appropriate author or supybot.Author instance.
__author__ = supybot.authors.strike
# This is a dictionary mapping supybot.Author instances to lists of
# contributions.
__contributors__ = {}
from . import config
from . import plugin
from imp import reload
reload(plugin) # In case we're being reloaded.
if world.testing:
from . import test
Class = plugin.Class
configure = config.configure
| true | true |
790bfe23c955a12e0756d09e044c0180b61ef9ba | 20,785 | py | Python | ckan/lib/dictization/model_save.py | NP-compete/ckan | 3bbbe028e43a25ea2179c35e50ed4b67c404b135 | [
"Apache-2.0"
] | 1 | 2019-11-03T11:35:38.000Z | 2019-11-03T11:35:38.000Z | ckan/lib/dictization/model_save.py | NP-compete/ckan | 3bbbe028e43a25ea2179c35e50ed4b67c404b135 | [
"Apache-2.0"
] | null | null | null | ckan/lib/dictization/model_save.py | NP-compete/ckan | 3bbbe028e43a25ea2179c35e50ed4b67c404b135 | [
"Apache-2.0"
] | null | null | null | # encoding: utf-8
import datetime
import uuid
import logging
from sqlalchemy.orm import class_mapper
from six import string_types
import ckan.lib.dictization as d
import ckan.lib.helpers as h
import ckan.authz as authz
log = logging.getLogger(__name__)
def resource_dict_save(res_dict, context):
model = context["model"]
session = context["session"]
id = res_dict.get("id")
obj = None
if id:
obj = session.query(model.Resource).get(id)
if not obj:
new = True
obj = model.Resource()
else:
new = False
table = class_mapper(model.Resource).mapped_table
fields = [field.name for field in table.c]
# Resource extras not submitted will be removed from the existing extras
# dict
new_extras = {}
for key, value in res_dict.iteritems():
if isinstance(value, list):
continue
if key in ('extras', 'revision_timestamp', 'tracking_summary'):
continue
if key in fields:
if isinstance(getattr(obj, key), datetime.datetime):
if getattr(obj, key).isoformat() == value:
continue
if key == 'last_modified' and not new:
obj.url_changed = True
if key == 'url' and not new and obj.url != value:
obj.url_changed = True
setattr(obj, key, value)
else:
# resources save extras directly onto the object, instead
# of in a separate extras field like packages and groups
new_extras[key] = value
obj.state = u'active'
obj.extras = new_extras
session.add(obj)
return obj
def package_resource_list_save(res_dicts, package, context):
allow_partial_update = context.get("allow_partial_update", False)
if res_dicts is None and allow_partial_update:
return
resource_list = package.resources_all
old_list = package.resources_all[:]
obj_list = []
for res_dict in res_dicts or []:
if not u'package_id' in res_dict or not res_dict[u'package_id']:
res_dict[u'package_id'] = package.id
obj = resource_dict_save(res_dict, context)
obj_list.append(obj)
# Set the package's resources. resource_list is an ORM relation - the
# package's resources. If we didn't have the slice operator "[:]" then it
# would reassign the variable "resource_list" to be the obj_list. But with
# the slice operator it changes the contents of the relation, setting the
# package's resources.
# At the table level, for each resource in the obj_list, its
# resource.package_id is changed to this package (which is needed for new
# resources), and every resource.position is set to ascending integers,
# according to their ordering in the obj_list.
resource_list[:] = obj_list
# Mark any left-over resources as deleted
for resource in set(old_list) - set(obj_list):
resource.state = 'deleted'
resource_list.append(resource)
def package_extras_save(extra_dicts, obj, context):
allow_partial_update = context.get("allow_partial_update", False)
if extra_dicts is None and allow_partial_update:
return
model = context["model"]
session = context["session"]
extras_list = obj.extras_list
old_extras = dict((extra.key, extra) for extra in extras_list)
new_extras = {}
for extra_dict in extra_dicts or []:
if extra_dict.get("deleted"):
continue
if extra_dict['value'] is None:
pass
else:
new_extras[extra_dict["key"]] = extra_dict["value"]
#new
for key in set(new_extras.keys()) - set(old_extras.keys()):
state = 'active'
extra = model.PackageExtra(state=state, key=key, value=new_extras[key])
session.add(extra)
extras_list.append(extra)
#changed
for key in set(new_extras.keys()) & set(old_extras.keys()):
extra = old_extras[key]
if new_extras[key] == extra.value and extra.state != 'deleted':
continue
state = 'active'
extra.value = new_extras[key]
extra.state = state
session.add(extra)
#deleted
for key in set(old_extras.keys()) - set(new_extras.keys()):
extra = old_extras[key]
if extra.state == 'deleted':
continue
state = 'deleted'
extra.state = state
def group_extras_save(extras_dicts, context):
model = context["model"]
session = context["session"]
result_dict = {}
for extra_dict in extras_dicts:
if extra_dict.get("deleted"):
continue
result_dict[extra_dict["key"]] = extra_dict["value"]
return result_dict
def package_tag_list_save(tag_dicts, package, context):
allow_partial_update = context.get("allow_partial_update", False)
if tag_dicts is None and allow_partial_update:
return
model = context["model"]
session = context["session"]
tag_package_tag = dict((package_tag.tag, package_tag)
for package_tag in
package.package_tag_all)
tag_package_tag_inactive = {tag: pt for tag,pt in tag_package_tag.items() if
pt.state in ['deleted']}
tag_name_vocab = set()
tags = set()
for tag_dict in tag_dicts or []:
if (tag_dict.get('name'), tag_dict.get('vocabulary_id')) not in tag_name_vocab:
tag_obj = d.table_dict_save(tag_dict, model.Tag, context)
tags.add(tag_obj)
tag_name_vocab.add((tag_obj.name, tag_obj.vocabulary_id))
# 3 cases
# case 1: currently active but not in new list
for tag in set(tag_package_tag.keys()) - tags:
package_tag = tag_package_tag[tag]
package_tag.state = 'deleted'
# case 2: in new list but never used before
for tag in tags - set(tag_package_tag.keys()):
state = 'active'
package_tag_obj = model.PackageTag(package, tag, state)
session.add(package_tag_obj)
tag_package_tag[tag] = package_tag_obj
# case 3: in new list and already used but in deleted state
for tag in tags.intersection(set(tag_package_tag_inactive.keys())):
state = 'active'
package_tag = tag_package_tag[tag]
package_tag.state = state
package.package_tag_all[:] = tag_package_tag.values()
def package_membership_list_save(group_dicts, package, context):
allow_partial_update = context.get("allow_partial_update", False)
if group_dicts is None and allow_partial_update:
return
capacity = 'public'
model = context["model"]
session = context["session"]
user = context.get('user')
members = session.query(model.Member) \
.filter(model.Member.table_id == package.id) \
.filter(model.Member.capacity != 'organization')
group_member = dict((member.group, member)
for member in
members)
groups = set()
for group_dict in group_dicts or []:
id = group_dict.get("id")
name = group_dict.get("name")
capacity = group_dict.get("capacity", "public")
if capacity == 'organization':
continue
if id:
group = session.query(model.Group).get(id)
else:
group = session.query(model.Group).filter_by(name=name).first()
if group:
groups.add(group)
## need to flush so we can get out the package id
model.Session.flush()
# Remove any groups we are no longer in
for group in set(group_member.keys()) - groups:
member_obj = group_member[group]
if member_obj and member_obj.state == 'deleted':
continue
if authz.has_user_permission_for_group_or_org(
member_obj.group_id, user, 'read'):
member_obj.capacity = capacity
member_obj.state = 'deleted'
session.add(member_obj)
# Add any new groups
for group in groups:
member_obj = group_member.get(group)
if member_obj and member_obj.state == 'active':
continue
if authz.has_user_permission_for_group_or_org(
group.id, user, 'read'):
member_obj = group_member.get(group)
if member_obj:
member_obj.capacity = capacity
member_obj.state = 'active'
else:
member_obj = model.Member(table_id=package.id,
table_name='package',
group=group,
capacity=capacity,
group_id=group.id,
state = 'active')
session.add(member_obj)
def relationship_list_save(relationship_dicts, package, attr, context):
allow_partial_update = context.get("allow_partial_update", False)
if relationship_dicts is None and allow_partial_update:
return
model = context["model"]
session = context["session"]
relationship_list = getattr(package, attr)
old_list = relationship_list[:]
relationships = []
for relationship_dict in relationship_dicts or []:
obj = d.table_dict_save(relationship_dict,
model.PackageRelationship, context)
relationships.append(obj)
relationship_list[:] = relationships
for relationship in set(old_list) - set(relationship_list):
relationship.state = 'deleted'
relationship_list.append(relationship)
def package_dict_save(pkg_dict, context):
model = context["model"]
package = context.get("package")
allow_partial_update = context.get("allow_partial_update", False)
if package:
pkg_dict["id"] = package.id
Package = model.Package
if 'metadata_created' in pkg_dict:
del pkg_dict['metadata_created']
if 'metadata_modified' in pkg_dict:
del pkg_dict['metadata_modified']
pkg = d.table_dict_save(pkg_dict, Package, context)
if not pkg.id:
pkg.id = str(uuid.uuid4())
package_resource_list_save(pkg_dict.get("resources"), pkg, context)
package_tag_list_save(pkg_dict.get("tags"), pkg, context)
package_membership_list_save(pkg_dict.get("groups"), pkg, context)
# relationships are not considered 'part' of the package, so only
# process this if the key is provided
if 'relationships_as_subject' in pkg_dict:
subjects = pkg_dict.get('relationships_as_subject')
relationship_list_save(subjects, pkg, 'relationships_as_subject', context)
if 'relationships_as_object' in pkg_dict:
objects = pkg_dict.get('relationships_as_object')
relationship_list_save(objects, pkg, 'relationships_as_object', context)
extras = package_extras_save(pkg_dict.get("extras"), pkg, context)
return pkg
def group_member_save(context, group_dict, member_table_name):
model = context["model"]
session = context["session"]
group = context['group']
entity_list = group_dict.get(member_table_name, None)
if entity_list is None:
if context.get('allow_partial_update', False):
return {'added': [], 'removed': []}
else:
entity_list = []
entities = {}
Member = model.Member
classname = member_table_name[:-1].capitalize()
if classname == 'Organization':
# Organizations use the model.Group class
classname = 'Group'
ModelClass = getattr(model, classname)
for entity_dict in entity_list:
name_or_id = entity_dict.get('id') or entity_dict.get('name')
obj = ModelClass.get(name_or_id)
if obj and obj not in entities.values():
entities[(obj.id, entity_dict.get('capacity', 'public'))] = obj
members = session.query(Member).filter_by(
table_name=member_table_name[:-1],
group_id=group.id,
).all()
processed = {
'added': [],
'removed': []
}
entity_member = dict(((member.table_id, member.capacity), member) for member in members)
for entity_id in set(entity_member.keys()) - set(entities.keys()):
if entity_member[entity_id].state != 'deleted':
processed['removed'].append(entity_id[0])
entity_member[entity_id].state = 'deleted'
session.add(entity_member[entity_id])
for entity_id in set(entity_member.keys()) & set(entities.keys()):
if entity_member[entity_id].state != 'active':
processed['added'].append(entity_id[0])
entity_member[entity_id].state = 'active'
session.add(entity_member[entity_id])
for entity_id in set(entities.keys()) - set(entity_member.keys()):
member = Member(group=group, group_id=group.id, table_id=entity_id[0],
table_name=member_table_name[:-1],
capacity=entity_id[1])
processed['added'].append(entity_id[0])
session.add(member)
return processed
def group_dict_save(group_dict, context, prevent_packages_update=False):
from ckan.lib.search import rebuild
model = context["model"]
session = context["session"]
group = context.get("group")
allow_partial_update = context.get("allow_partial_update", False)
Group = model.Group
if group:
group_dict["id"] = group.id
group = d.table_dict_save(group_dict, Group, context)
if not group.id:
group.id = str(uuid.uuid4())
context['group'] = group
# Under the new org rules we do not want to be able to update datasets
# via group edit so we need a way to prevent this. It may be more
# sensible in future to send a list of allowed/disallowed updates for
# groups, users, tabs etc.
if not prevent_packages_update:
pkgs_edited = group_member_save(context, group_dict, 'packages')
else:
pkgs_edited = {
'added': [],
'removed': []
}
group_users_changed = group_member_save(context, group_dict, 'users')
group_groups_changed = group_member_save(context, group_dict, 'groups')
group_tags_changed = group_member_save(context, group_dict, 'tags')
log.debug('Group save membership changes - Packages: %r Users: %r '
'Groups: %r Tags: %r', pkgs_edited, group_users_changed,
group_groups_changed, group_tags_changed)
extras = group_extras_save(group_dict.get("extras", {}), context)
if extras or not allow_partial_update:
old_extras = set(group.extras.keys())
new_extras = set(extras.keys())
for key in old_extras - new_extras:
del group.extras[key]
for key in new_extras:
group.extras[key] = extras[key]
# We will get a list of packages that we have either added or
# removed from the group, and trigger a re-index.
package_ids = pkgs_edited['removed']
package_ids.extend( pkgs_edited['added'] )
if package_ids:
session.commit()
map( rebuild, package_ids )
return group
def user_dict_save(user_dict, context):
model = context['model']
session = context['session']
user = context.get('user_obj')
User = model.User
if user:
user_dict['id'] = user.id
if 'password' in user_dict and not len(user_dict['password']):
del user_dict['password']
user = d.table_dict_save(user_dict, User, context)
return user
def package_api_to_dict(api1_dict, context):
package = context.get("package")
api_version = context.get('api_version')
assert api_version, 'No api_version supplied in context'
dictized = {}
for key, value in api1_dict.iteritems():
new_value = value
if key == 'tags':
if isinstance(value, string_types):
new_value = [{"name": item} for item in value.split()]
else:
new_value = [{"name": item} for item in value]
if key == 'extras':
updated_extras = {}
if package:
updated_extras.update(package.extras)
updated_extras.update(value)
new_value = []
for extras_key, extras_value in updated_extras.iteritems():
new_value.append({"key": extras_key,
"value": extras_value})
if key == 'groups' and len(value):
if api_version == 1:
new_value = [{'name': item} for item in value]
else:
new_value = [{'id': item} for item in value]
dictized[key] = new_value
download_url = dictized.pop('download_url', None)
if download_url and not dictized.get('resources'):
dictized["resources"] = [{'url': download_url}]
download_url = dictized.pop('download_url', None)
return dictized
def group_api_to_dict(api1_dict, context):
dictized = {}
for key, value in api1_dict.iteritems():
new_value = value
if key == 'packages':
new_value = [{"id": item} for item in value]
if key == 'extras':
new_value = [{"key": extra_key, "value": value[extra_key]}
for extra_key in value]
dictized[key] = new_value
return dictized
def task_status_dict_save(task_status_dict, context):
model = context["model"]
task_status = context.get("task_status")
allow_partial_update = context.get("allow_partial_update", False)
if task_status:
task_status_dict["id"] = task_status.id
task_status = d.table_dict_save(task_status_dict, model.TaskStatus, context)
return task_status
def activity_dict_save(activity_dict, context):
model = context['model']
session = context['session']
user_id = activity_dict['user_id']
object_id = activity_dict['object_id']
revision_id = activity_dict['revision_id']
activity_type = activity_dict['activity_type']
if activity_dict.has_key('data'):
data = activity_dict['data']
else:
data = None
activity_obj = model.Activity(user_id, object_id, revision_id,
activity_type, data)
session.add(activity_obj)
# TODO: Handle activity details.
return activity_obj
def vocabulary_tag_list_save(new_tag_dicts, vocabulary_obj, context):
model = context['model']
session = context['session']
# First delete any tags not in new_tag_dicts.
for tag in vocabulary_obj.tags:
if tag.name not in [t['name'] for t in new_tag_dicts]:
tag.delete()
# Now add any new tags.
for tag_dict in new_tag_dicts:
current_tag_names = [tag.name for tag in vocabulary_obj.tags]
if tag_dict['name'] not in current_tag_names:
# Make sure the tag belongs to this vocab..
tag_dict['vocabulary_id'] = vocabulary_obj.id
# then add it.
tag_dict_save(tag_dict, {'model': model, 'session': session})
def vocabulary_dict_save(vocabulary_dict, context):
model = context['model']
session = context['session']
vocabulary_name = vocabulary_dict['name']
vocabulary_obj = model.Vocabulary(vocabulary_name)
session.add(vocabulary_obj)
if vocabulary_dict.has_key('tags'):
vocabulary_tag_list_save(vocabulary_dict['tags'], vocabulary_obj,
context)
return vocabulary_obj
def vocabulary_dict_update(vocabulary_dict, context):
model = context['model']
session = context['session']
vocabulary_obj = model.vocabulary.Vocabulary.get(vocabulary_dict['id'])
if vocabulary_dict.has_key('name'):
vocabulary_obj.name = vocabulary_dict['name']
if vocabulary_dict.has_key('tags'):
vocabulary_tag_list_save(vocabulary_dict['tags'], vocabulary_obj,
context)
return vocabulary_obj
def tag_dict_save(tag_dict, context):
model = context['model']
tag = context.get('tag')
if tag:
tag_dict['id'] = tag.id
tag = d.table_dict_save(tag_dict, model.Tag, context)
return tag
def follower_dict_save(data_dict, context, FollowerClass):
model = context['model']
session = context['session']
follower_obj = FollowerClass(
follower_id=model.User.get(context['user']).id,
object_id=data_dict['id'])
session.add(follower_obj)
return follower_obj
def resource_view_dict_save(data_dict, context):
model = context['model']
resource_view = context.get('resource_view')
if resource_view:
data_dict['id'] = resource_view.id
config = {}
for key, value in data_dict.iteritems():
if key not in model.ResourceView.get_columns():
config[key] = value
data_dict['config'] = config
return d.table_dict_save(data_dict, model.ResourceView, context)
| 33.578352 | 92 | 0.637864 |
import datetime
import uuid
import logging
from sqlalchemy.orm import class_mapper
from six import string_types
import ckan.lib.dictization as d
import ckan.lib.helpers as h
import ckan.authz as authz
log = logging.getLogger(__name__)
def resource_dict_save(res_dict, context):
model = context["model"]
session = context["session"]
id = res_dict.get("id")
obj = None
if id:
obj = session.query(model.Resource).get(id)
if not obj:
new = True
obj = model.Resource()
else:
new = False
table = class_mapper(model.Resource).mapped_table
fields = [field.name for field in table.c]
new_extras = {}
for key, value in res_dict.iteritems():
if isinstance(value, list):
continue
if key in ('extras', 'revision_timestamp', 'tracking_summary'):
continue
if key in fields:
if isinstance(getattr(obj, key), datetime.datetime):
if getattr(obj, key).isoformat() == value:
continue
if key == 'last_modified' and not new:
obj.url_changed = True
if key == 'url' and not new and obj.url != value:
obj.url_changed = True
setattr(obj, key, value)
else:
new_extras[key] = value
obj.state = u'active'
obj.extras = new_extras
session.add(obj)
return obj
def package_resource_list_save(res_dicts, package, context):
allow_partial_update = context.get("allow_partial_update", False)
if res_dicts is None and allow_partial_update:
return
resource_list = package.resources_all
old_list = package.resources_all[:]
obj_list = []
for res_dict in res_dicts or []:
if not u'package_id' in res_dict or not res_dict[u'package_id']:
res_dict[u'package_id'] = package.id
obj = resource_dict_save(res_dict, context)
obj_list.append(obj)
# package's resources. If we didn't have the slice operator "[:]" then it
# would reassign the variable "resource_list" to be the obj_list. But with
# the slice operator it changes the contents of the relation, setting the
# package's resources.
resource_list[:] = obj_list
for resource in set(old_list) - set(obj_list):
resource.state = 'deleted'
resource_list.append(resource)
def package_extras_save(extra_dicts, obj, context):
allow_partial_update = context.get("allow_partial_update", False)
if extra_dicts is None and allow_partial_update:
return
model = context["model"]
session = context["session"]
extras_list = obj.extras_list
old_extras = dict((extra.key, extra) for extra in extras_list)
new_extras = {}
for extra_dict in extra_dicts or []:
if extra_dict.get("deleted"):
continue
if extra_dict['value'] is None:
pass
else:
new_extras[extra_dict["key"]] = extra_dict["value"]
for key in set(new_extras.keys()) - set(old_extras.keys()):
state = 'active'
extra = model.PackageExtra(state=state, key=key, value=new_extras[key])
session.add(extra)
extras_list.append(extra)
for key in set(new_extras.keys()) & set(old_extras.keys()):
extra = old_extras[key]
if new_extras[key] == extra.value and extra.state != 'deleted':
continue
state = 'active'
extra.value = new_extras[key]
extra.state = state
session.add(extra)
for key in set(old_extras.keys()) - set(new_extras.keys()):
extra = old_extras[key]
if extra.state == 'deleted':
continue
state = 'deleted'
extra.state = state
def group_extras_save(extras_dicts, context):
model = context["model"]
session = context["session"]
result_dict = {}
for extra_dict in extras_dicts:
if extra_dict.get("deleted"):
continue
result_dict[extra_dict["key"]] = extra_dict["value"]
return result_dict
def package_tag_list_save(tag_dicts, package, context):
allow_partial_update = context.get("allow_partial_update", False)
if tag_dicts is None and allow_partial_update:
return
model = context["model"]
session = context["session"]
tag_package_tag = dict((package_tag.tag, package_tag)
for package_tag in
package.package_tag_all)
tag_package_tag_inactive = {tag: pt for tag,pt in tag_package_tag.items() if
pt.state in ['deleted']}
tag_name_vocab = set()
tags = set()
for tag_dict in tag_dicts or []:
if (tag_dict.get('name'), tag_dict.get('vocabulary_id')) not in tag_name_vocab:
tag_obj = d.table_dict_save(tag_dict, model.Tag, context)
tags.add(tag_obj)
tag_name_vocab.add((tag_obj.name, tag_obj.vocabulary_id))
for tag in set(tag_package_tag.keys()) - tags:
package_tag = tag_package_tag[tag]
package_tag.state = 'deleted'
for tag in tags - set(tag_package_tag.keys()):
state = 'active'
package_tag_obj = model.PackageTag(package, tag, state)
session.add(package_tag_obj)
tag_package_tag[tag] = package_tag_obj
for tag in tags.intersection(set(tag_package_tag_inactive.keys())):
state = 'active'
package_tag = tag_package_tag[tag]
package_tag.state = state
package.package_tag_all[:] = tag_package_tag.values()
def package_membership_list_save(group_dicts, package, context):
allow_partial_update = context.get("allow_partial_update", False)
if group_dicts is None and allow_partial_update:
return
capacity = 'public'
model = context["model"]
session = context["session"]
user = context.get('user')
members = session.query(model.Member) \
.filter(model.Member.table_id == package.id) \
.filter(model.Member.capacity != 'organization')
group_member = dict((member.group, member)
for member in
members)
groups = set()
for group_dict in group_dicts or []:
id = group_dict.get("id")
name = group_dict.get("name")
capacity = group_dict.get("capacity", "public")
if capacity == 'organization':
continue
if id:
group = session.query(model.Group).get(id)
else:
group = session.query(model.Group).filter_by(name=name).first()
if group:
groups.add(group)
n set(group_member.keys()) - groups:
member_obj = group_member[group]
if member_obj and member_obj.state == 'deleted':
continue
if authz.has_user_permission_for_group_or_org(
member_obj.group_id, user, 'read'):
member_obj.capacity = capacity
member_obj.state = 'deleted'
session.add(member_obj)
for group in groups:
member_obj = group_member.get(group)
if member_obj and member_obj.state == 'active':
continue
if authz.has_user_permission_for_group_or_org(
group.id, user, 'read'):
member_obj = group_member.get(group)
if member_obj:
member_obj.capacity = capacity
member_obj.state = 'active'
else:
member_obj = model.Member(table_id=package.id,
table_name='package',
group=group,
capacity=capacity,
group_id=group.id,
state = 'active')
session.add(member_obj)
def relationship_list_save(relationship_dicts, package, attr, context):
allow_partial_update = context.get("allow_partial_update", False)
if relationship_dicts is None and allow_partial_update:
return
model = context["model"]
session = context["session"]
relationship_list = getattr(package, attr)
old_list = relationship_list[:]
relationships = []
for relationship_dict in relationship_dicts or []:
obj = d.table_dict_save(relationship_dict,
model.PackageRelationship, context)
relationships.append(obj)
relationship_list[:] = relationships
for relationship in set(old_list) - set(relationship_list):
relationship.state = 'deleted'
relationship_list.append(relationship)
def package_dict_save(pkg_dict, context):
model = context["model"]
package = context.get("package")
allow_partial_update = context.get("allow_partial_update", False)
if package:
pkg_dict["id"] = package.id
Package = model.Package
if 'metadata_created' in pkg_dict:
del pkg_dict['metadata_created']
if 'metadata_modified' in pkg_dict:
del pkg_dict['metadata_modified']
pkg = d.table_dict_save(pkg_dict, Package, context)
if not pkg.id:
pkg.id = str(uuid.uuid4())
package_resource_list_save(pkg_dict.get("resources"), pkg, context)
package_tag_list_save(pkg_dict.get("tags"), pkg, context)
package_membership_list_save(pkg_dict.get("groups"), pkg, context)
if 'relationships_as_subject' in pkg_dict:
subjects = pkg_dict.get('relationships_as_subject')
relationship_list_save(subjects, pkg, 'relationships_as_subject', context)
if 'relationships_as_object' in pkg_dict:
objects = pkg_dict.get('relationships_as_object')
relationship_list_save(objects, pkg, 'relationships_as_object', context)
extras = package_extras_save(pkg_dict.get("extras"), pkg, context)
return pkg
def group_member_save(context, group_dict, member_table_name):
model = context["model"]
session = context["session"]
group = context['group']
entity_list = group_dict.get(member_table_name, None)
if entity_list is None:
if context.get('allow_partial_update', False):
return {'added': [], 'removed': []}
else:
entity_list = []
entities = {}
Member = model.Member
classname = member_table_name[:-1].capitalize()
if classname == 'Organization':
classname = 'Group'
ModelClass = getattr(model, classname)
for entity_dict in entity_list:
name_or_id = entity_dict.get('id') or entity_dict.get('name')
obj = ModelClass.get(name_or_id)
if obj and obj not in entities.values():
entities[(obj.id, entity_dict.get('capacity', 'public'))] = obj
members = session.query(Member).filter_by(
table_name=member_table_name[:-1],
group_id=group.id,
).all()
processed = {
'added': [],
'removed': []
}
entity_member = dict(((member.table_id, member.capacity), member) for member in members)
for entity_id in set(entity_member.keys()) - set(entities.keys()):
if entity_member[entity_id].state != 'deleted':
processed['removed'].append(entity_id[0])
entity_member[entity_id].state = 'deleted'
session.add(entity_member[entity_id])
for entity_id in set(entity_member.keys()) & set(entities.keys()):
if entity_member[entity_id].state != 'active':
processed['added'].append(entity_id[0])
entity_member[entity_id].state = 'active'
session.add(entity_member[entity_id])
for entity_id in set(entities.keys()) - set(entity_member.keys()):
member = Member(group=group, group_id=group.id, table_id=entity_id[0],
table_name=member_table_name[:-1],
capacity=entity_id[1])
processed['added'].append(entity_id[0])
session.add(member)
return processed
def group_dict_save(group_dict, context, prevent_packages_update=False):
from ckan.lib.search import rebuild
model = context["model"]
session = context["session"]
group = context.get("group")
allow_partial_update = context.get("allow_partial_update", False)
Group = model.Group
if group:
group_dict["id"] = group.id
group = d.table_dict_save(group_dict, Group, context)
if not group.id:
group.id = str(uuid.uuid4())
context['group'] = group
if not prevent_packages_update:
pkgs_edited = group_member_save(context, group_dict, 'packages')
else:
pkgs_edited = {
'added': [],
'removed': []
}
group_users_changed = group_member_save(context, group_dict, 'users')
group_groups_changed = group_member_save(context, group_dict, 'groups')
group_tags_changed = group_member_save(context, group_dict, 'tags')
log.debug('Group save membership changes - Packages: %r Users: %r '
'Groups: %r Tags: %r', pkgs_edited, group_users_changed,
group_groups_changed, group_tags_changed)
extras = group_extras_save(group_dict.get("extras", {}), context)
if extras or not allow_partial_update:
old_extras = set(group.extras.keys())
new_extras = set(extras.keys())
for key in old_extras - new_extras:
del group.extras[key]
for key in new_extras:
group.extras[key] = extras[key]
package_ids = pkgs_edited['removed']
package_ids.extend( pkgs_edited['added'] )
if package_ids:
session.commit()
map( rebuild, package_ids )
return group
def user_dict_save(user_dict, context):
model = context['model']
session = context['session']
user = context.get('user_obj')
User = model.User
if user:
user_dict['id'] = user.id
if 'password' in user_dict and not len(user_dict['password']):
del user_dict['password']
user = d.table_dict_save(user_dict, User, context)
return user
def package_api_to_dict(api1_dict, context):
package = context.get("package")
api_version = context.get('api_version')
assert api_version, 'No api_version supplied in context'
dictized = {}
for key, value in api1_dict.iteritems():
new_value = value
if key == 'tags':
if isinstance(value, string_types):
new_value = [{"name": item} for item in value.split()]
else:
new_value = [{"name": item} for item in value]
if key == 'extras':
updated_extras = {}
if package:
updated_extras.update(package.extras)
updated_extras.update(value)
new_value = []
for extras_key, extras_value in updated_extras.iteritems():
new_value.append({"key": extras_key,
"value": extras_value})
if key == 'groups' and len(value):
if api_version == 1:
new_value = [{'name': item} for item in value]
else:
new_value = [{'id': item} for item in value]
dictized[key] = new_value
download_url = dictized.pop('download_url', None)
if download_url and not dictized.get('resources'):
dictized["resources"] = [{'url': download_url}]
download_url = dictized.pop('download_url', None)
return dictized
def group_api_to_dict(api1_dict, context):
dictized = {}
for key, value in api1_dict.iteritems():
new_value = value
if key == 'packages':
new_value = [{"id": item} for item in value]
if key == 'extras':
new_value = [{"key": extra_key, "value": value[extra_key]}
for extra_key in value]
dictized[key] = new_value
return dictized
def task_status_dict_save(task_status_dict, context):
model = context["model"]
task_status = context.get("task_status")
allow_partial_update = context.get("allow_partial_update", False)
if task_status:
task_status_dict["id"] = task_status.id
task_status = d.table_dict_save(task_status_dict, model.TaskStatus, context)
return task_status
def activity_dict_save(activity_dict, context):
model = context['model']
session = context['session']
user_id = activity_dict['user_id']
object_id = activity_dict['object_id']
revision_id = activity_dict['revision_id']
activity_type = activity_dict['activity_type']
if activity_dict.has_key('data'):
data = activity_dict['data']
else:
data = None
activity_obj = model.Activity(user_id, object_id, revision_id,
activity_type, data)
session.add(activity_obj)
return activity_obj
def vocabulary_tag_list_save(new_tag_dicts, vocabulary_obj, context):
model = context['model']
session = context['session']
for tag in vocabulary_obj.tags:
if tag.name not in [t['name'] for t in new_tag_dicts]:
tag.delete()
for tag_dict in new_tag_dicts:
current_tag_names = [tag.name for tag in vocabulary_obj.tags]
if tag_dict['name'] not in current_tag_names:
tag_dict['vocabulary_id'] = vocabulary_obj.id
tag_dict_save(tag_dict, {'model': model, 'session': session})
def vocabulary_dict_save(vocabulary_dict, context):
model = context['model']
session = context['session']
vocabulary_name = vocabulary_dict['name']
vocabulary_obj = model.Vocabulary(vocabulary_name)
session.add(vocabulary_obj)
if vocabulary_dict.has_key('tags'):
vocabulary_tag_list_save(vocabulary_dict['tags'], vocabulary_obj,
context)
return vocabulary_obj
def vocabulary_dict_update(vocabulary_dict, context):
model = context['model']
session = context['session']
vocabulary_obj = model.vocabulary.Vocabulary.get(vocabulary_dict['id'])
if vocabulary_dict.has_key('name'):
vocabulary_obj.name = vocabulary_dict['name']
if vocabulary_dict.has_key('tags'):
vocabulary_tag_list_save(vocabulary_dict['tags'], vocabulary_obj,
context)
return vocabulary_obj
def tag_dict_save(tag_dict, context):
model = context['model']
tag = context.get('tag')
if tag:
tag_dict['id'] = tag.id
tag = d.table_dict_save(tag_dict, model.Tag, context)
return tag
def follower_dict_save(data_dict, context, FollowerClass):
model = context['model']
session = context['session']
follower_obj = FollowerClass(
follower_id=model.User.get(context['user']).id,
object_id=data_dict['id'])
session.add(follower_obj)
return follower_obj
def resource_view_dict_save(data_dict, context):
model = context['model']
resource_view = context.get('resource_view')
if resource_view:
data_dict['id'] = resource_view.id
config = {}
for key, value in data_dict.iteritems():
if key not in model.ResourceView.get_columns():
config[key] = value
data_dict['config'] = config
return d.table_dict_save(data_dict, model.ResourceView, context)
| true | true |
790bfe7b6701239a7a166a21c31872ee524d7bd3 | 910 | py | Python | api/admin.py | emeth-/the-foot-globalhack5 | c2d999a75e53aaf7a20c0b34d7057bf2ea64f69e | [
"MIT"
] | null | null | null | api/admin.py | emeth-/the-foot-globalhack5 | c2d999a75e53aaf7a20c0b34d7057bf2ea64f69e | [
"MIT"
] | null | null | null | api/admin.py | emeth-/the-foot-globalhack5 | c2d999a75e53aaf7a20c0b34d7057bf2ea64f69e | [
"MIT"
] | null | null | null | from django.contrib import admin
from api.models import Citation
class CitationAdmin(admin.ModelAdmin):
list_display = ('id', 'citation_number', 'citation_date', 'first_name', 'last_name', 'date_of_birth', 'defendant_address', 'defendant_city', 'defendant_state', 'drivers_license_number', 'court_date', 'court_location', 'court_address')
search_fields = ('id', 'first_name', 'last_name', 'court_location', 'drivers_license_number')
admin.site.register(Citation, CitationAdmin)
from api.models import Violation
class ViolationAdmin(admin.ModelAdmin):
list_display = ('id', 'citation_number', 'violation_number', 'violation_description', 'warrant_status', 'warrant_number', 'status', 'status_date', 'fine_amount', 'court_cost')
list_filter = ('warrant_status',)
search_fields = ('id', 'citation_number', 'violation_number', 'warrant_number')
admin.site.register(Violation, ViolationAdmin) | 60.666667 | 238 | 0.762637 | from django.contrib import admin
from api.models import Citation
class CitationAdmin(admin.ModelAdmin):
list_display = ('id', 'citation_number', 'citation_date', 'first_name', 'last_name', 'date_of_birth', 'defendant_address', 'defendant_city', 'defendant_state', 'drivers_license_number', 'court_date', 'court_location', 'court_address')
search_fields = ('id', 'first_name', 'last_name', 'court_location', 'drivers_license_number')
admin.site.register(Citation, CitationAdmin)
from api.models import Violation
class ViolationAdmin(admin.ModelAdmin):
list_display = ('id', 'citation_number', 'violation_number', 'violation_description', 'warrant_status', 'warrant_number', 'status', 'status_date', 'fine_amount', 'court_cost')
list_filter = ('warrant_status',)
search_fields = ('id', 'citation_number', 'violation_number', 'warrant_number')
admin.site.register(Violation, ViolationAdmin) | true | true |
790bfe9e637a97c25700c02b7d5832d6e5fb589f | 131 | py | Python | src/pythonFEA/templates/__init__.py | honzatomek/pythonFEA | c851c20800a06cc2084ef53dfd2ab67e7dfbc3b7 | [
"MIT"
] | null | null | null | src/pythonFEA/templates/__init__.py | honzatomek/pythonFEA | c851c20800a06cc2084ef53dfd2ab67e7dfbc3b7 | [
"MIT"
] | null | null | null | src/pythonFEA/templates/__init__.py | honzatomek/pythonFEA | c851c20800a06cc2084ef53dfd2ab67e7dfbc3b7 | [
"MIT"
] | null | null | null | # print('Reading templates/__init__.py')
from .errors import *
import logging
logging.debug('Reading src/templates/__init__.py')
| 18.714286 | 50 | 0.770992 |
from .errors import *
import logging
logging.debug('Reading src/templates/__init__.py')
| true | true |
790bfebe2eb785aaa8b60e4994304b971a0f8eaa | 2,846 | py | Python | train.py | blufzzz/MeshCNN | 54221ddaef20c2886dca17d4edaf76f8cf040af0 | [
"MIT"
] | null | null | null | train.py | blufzzz/MeshCNN | 54221ddaef20c2886dca17d4edaf76f8cf040af0 | [
"MIT"
] | null | null | null | train.py | blufzzz/MeshCNN | 54221ddaef20c2886dca17d4edaf76f8cf040af0 | [
"MIT"
] | null | null | null | import time
from options.train_options import TrainOptions
from data import DataLoader
from models import create_model
from util.writer import Writer
from test import run_test
if __name__ == '__main__':
opt = TrainOptions().parse()
# opt.serial_batches = True # no shuffle
print('Creating DataLoader...')
dataset = DataLoader(opt)
print('DataLoader created!')
print('#training meshes = %d' % dataset_size)
model = create_model(opt)
writer = Writer(opt)
total_steps = 0
for epoch in range(opt.epoch_count,
opt.niter + opt.niter_decay + 1):
epoch_start_time = time.time()
iter_data_time = time.time()
epoch_iter = 0
o_ncorrect = 0
o_nexamples = 0
o_pr = 0
o_re = 0
model.save_network(0)
for i, data in enumerate(dataset):
print(i)
iter_start_time = time.time()
if total_steps % opt.print_freq == 0:
t_data = iter_start_time - iter_data_time
total_steps += opt.batch_size
epoch_iter += opt.batch_size
model.set_input(data)
ncorrect, nexamples, pr, re = model.optimize_parameters()
o_ncorrect += ncorrect
o_nexamples += nexamples
o_pr += pr
o_re += re
if total_steps % opt.print_freq == 0:
loss = model.loss
t = (time.time() - iter_start_time) / opt.batch_size
writer.print_current_losses(epoch, epoch_iter, loss, t, t_data)
writer.plot_loss(loss, epoch, epoch_iter, dataset_size)
if i % opt.save_latest_freq == 0:
print('saving the latest model (epoch %d, total_steps %d)' %
(epoch, total_steps))
model.save_network('latest')
iter_data_time = time.time()
if epoch % opt.save_epoch_freq == 0:
print('saving the model at the end of epoch %d, iters %d' %
(epoch, total_steps))
model.save_network('latest')
model.save_network(epoch)
print('End of epoch %d / %d \t Time Taken: %d sec' %
(epoch, opt.niter + opt.niter_decay, time.time() - epoch_start_time))
model.update_learning_rate()
if opt.verbose_plot:
writer.plot_model_wts(model, epoch)
if epoch % opt.run_test_freq == 0:
acc, pr, re = run_test(epoch)
writer.plot_acc(acc, epoch)
writer.plot_pr(pr, epoch)
writer.plot_re(re, epoch)
writer.plot_train_acc(float(o_ncorrect)/o_nexamples, epoch)
writer.plot_train_pr(float(o_pr)/o_nexamples, epoch)
writer.plot_train_re(float(o_re)/o_nexamples, epoch)
writer.close()
| 34.289157 | 83 | 0.576599 | import time
from options.train_options import TrainOptions
from data import DataLoader
from models import create_model
from util.writer import Writer
from test import run_test
if __name__ == '__main__':
opt = TrainOptions().parse()
Creating DataLoader...')
dataset = DataLoader(opt)
print('DataLoader created!')
print('#training meshes = %d' % dataset_size)
model = create_model(opt)
writer = Writer(opt)
total_steps = 0
for epoch in range(opt.epoch_count,
opt.niter + opt.niter_decay + 1):
epoch_start_time = time.time()
iter_data_time = time.time()
epoch_iter = 0
o_ncorrect = 0
o_nexamples = 0
o_pr = 0
o_re = 0
model.save_network(0)
for i, data in enumerate(dataset):
print(i)
iter_start_time = time.time()
if total_steps % opt.print_freq == 0:
t_data = iter_start_time - iter_data_time
total_steps += opt.batch_size
epoch_iter += opt.batch_size
model.set_input(data)
ncorrect, nexamples, pr, re = model.optimize_parameters()
o_ncorrect += ncorrect
o_nexamples += nexamples
o_pr += pr
o_re += re
if total_steps % opt.print_freq == 0:
loss = model.loss
t = (time.time() - iter_start_time) / opt.batch_size
writer.print_current_losses(epoch, epoch_iter, loss, t, t_data)
writer.plot_loss(loss, epoch, epoch_iter, dataset_size)
if i % opt.save_latest_freq == 0:
print('saving the latest model (epoch %d, total_steps %d)' %
(epoch, total_steps))
model.save_network('latest')
iter_data_time = time.time()
if epoch % opt.save_epoch_freq == 0:
print('saving the model at the end of epoch %d, iters %d' %
(epoch, total_steps))
model.save_network('latest')
model.save_network(epoch)
print('End of epoch %d / %d \t Time Taken: %d sec' %
(epoch, opt.niter + opt.niter_decay, time.time() - epoch_start_time))
model.update_learning_rate()
if opt.verbose_plot:
writer.plot_model_wts(model, epoch)
if epoch % opt.run_test_freq == 0:
acc, pr, re = run_test(epoch)
writer.plot_acc(acc, epoch)
writer.plot_pr(pr, epoch)
writer.plot_re(re, epoch)
writer.plot_train_acc(float(o_ncorrect)/o_nexamples, epoch)
writer.plot_train_pr(float(o_pr)/o_nexamples, epoch)
writer.plot_train_re(float(o_re)/o_nexamples, epoch)
writer.close()
| true | true |
790bff7a824582a5bd81e5ba50fd57cd8d353b74 | 803 | py | Python | app/__init__.py | hazzillrodriguez/flask-user-management | 1c9e9707f9302a908b8cc5cb324abe89f4db7bc9 | [
"MIT"
] | 1 | 2021-11-30T05:33:19.000Z | 2021-11-30T05:33:19.000Z | app/__init__.py | hazzillrodriguez/flask-user-management | 1c9e9707f9302a908b8cc5cb324abe89f4db7bc9 | [
"MIT"
] | null | null | null | app/__init__.py | hazzillrodriguez/flask-user-management | 1c9e9707f9302a908b8cc5cb324abe89f4db7bc9 | [
"MIT"
] | 1 | 2021-09-27T11:24:52.000Z | 2021-09-27T11:24:52.000Z | from flask import Flask, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_migrate import Migrate
from flask_bcrypt import Bcrypt
from flask_mail import Mail
app = Flask(__name__)
# Configuration
app.config.from_object('config.DevelopmentConfig')
db = SQLAlchemy(app)
login_manager = LoginManager(app)
migrate = Migrate(app, db)
bcrypt = Bcrypt(app)
mail = Mail(app)
from app.auth.views import auth_blueprint
from app.admin.views import admin_blueprint
from app.user.views import user_blueprint
app.register_blueprint(auth_blueprint, url_prefix='/auth')
app.register_blueprint(admin_blueprint, url_prefix='/admin')
app.register_blueprint(user_blueprint, url_prefix='/user')
@app.route('/')
def root():
return(redirect(url_for('auth.login'))) | 28.678571 | 60 | 0.809465 | from flask import Flask, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_migrate import Migrate
from flask_bcrypt import Bcrypt
from flask_mail import Mail
app = Flask(__name__)
app.config.from_object('config.DevelopmentConfig')
db = SQLAlchemy(app)
login_manager = LoginManager(app)
migrate = Migrate(app, db)
bcrypt = Bcrypt(app)
mail = Mail(app)
from app.auth.views import auth_blueprint
from app.admin.views import admin_blueprint
from app.user.views import user_blueprint
app.register_blueprint(auth_blueprint, url_prefix='/auth')
app.register_blueprint(admin_blueprint, url_prefix='/admin')
app.register_blueprint(user_blueprint, url_prefix='/user')
@app.route('/')
def root():
return(redirect(url_for('auth.login'))) | true | true |
790bfff162b54b4b284aab426678a810628d87f2 | 14,194 | py | Python | solaris/tile/vector_tile.py | motokimura/solaris | e3a18522ee41aad3da37ae88ba159efabf76a180 | [
"Apache-2.0"
] | 60 | 2020-07-29T23:31:18.000Z | 2022-03-20T02:02:47.000Z | 3-SatShipAI/solaris/tile/vector_tile.py | Z-Zheng/SpaceNet_SAR_Buildings_Solutions | 6a9c3962d987d985384d0d41a187f5fbfadac82c | [
"Apache-2.0"
] | 9 | 2021-01-15T08:57:15.000Z | 2021-11-04T04:27:41.000Z | 3-SatShipAI/solaris/tile/vector_tile.py | Z-Zheng/SpaceNet_SAR_Buildings_Solutions | 6a9c3962d987d985384d0d41a187f5fbfadac82c | [
"Apache-2.0"
] | 16 | 2020-07-30T12:56:03.000Z | 2021-08-13T16:55:05.000Z | import os
import numpy as np
from shapely.geometry import box, Polygon
import geopandas as gpd
from ..utils.core import _check_gdf_load, _check_crs
from ..utils.tile import save_empty_geojson
from ..utils.geo import gdf_get_projection_unit, split_multi_geometries
from ..utils.geo import reproject_geometry
from tqdm import tqdm
class VectorTiler(object):
"""An object to tile geospatial vector data into smaller pieces.
Arguments
---------
Attributes
----------
"""
def __init__(self, dest_dir=None, dest_crs=None, output_format='GeoJSON',
verbose=False, super_verbose=False):
if verbose or super_verbose:
print('Preparing the tiler...')
self.dest_dir = dest_dir
if not os.path.isdir(self.dest_dir):
os.makedirs(self.dest_dir)
if dest_crs is not None:
self.dest_crs = _check_crs(dest_crs)
self.output_format = output_format
self.verbose = verbose
self.super_verbose = super_verbose
self.tile_paths = [] # retains the paths of the last call to .tile()
if self.verbose or self.super_verbose:
print('Initialization done.')
def tile(self, src, tile_bounds, tile_bounds_crs=None, geom_type='Polygon',
split_multi_geoms=True, min_partial_perc=0.0,
dest_fname_base='geoms', obj_id_col=None,
output_ext='.geojson'):
"""Tile `src` into vector data tiles bounded by `tile_bounds`.
Arguments
---------
src : `str` or :class:`geopandas.GeoDataFrame`
The source vector data to tile. Must either be a path to a GeoJSON
or a :class:`geopandas.GeoDataFrame`.
tile_bounds : list
A :class:`list` made up of ``[left, top, right, bottom] `` sublists
(this can be extracted from
:class:`solaris.tile.raster_tile.RasterTiler` after tiling imagery)
tile_bounds_crs : int, optional
The EPSG code or rasterio.crs.CRS object for the CRS that the tile
bounds are in. RasterTiler.tile returns the CRS of the raster tiles
and can be used here. If not provided, it's assumed that the CRS is the
same as in `src`. This argument must be provided if the bound
coordinates and `src` are not in the same CRS, otherwise tiling will
not occur correctly.
geom_type : str, optional (default: "Polygon")
The type of geometries contained within `src`. Defaults to
``"Polygon"``, can also be ``"LineString"``.
split_multi_geoms : bool, optional (default: True)
Should multi-polygons or multi-linestrings generated by clipping
a geometry into discontinuous pieces be separated? Defaults to yes
(``True``).
min_partial_perc : float, optional (default: 0.0)
The minimum percentage of a :class:`shapely.geometry.Polygon` 's
area or :class:`shapely.geometry.LineString` 's length that must
be retained within a tile's bounds to be included in the output.
Defaults to ``0.0``, meaning that the contained portion of a
clipped geometry will be included, no matter how small.
dest_fname_base : str, optional (default: 'geoms')
The base filename to use when creating outputs. The lower left
corner coordinates of the tile's bounding box will be appended
when saving.
obj_id_col : str, optional (default: None)
If ``split_multi_geoms=True``, the name of a column that specifies
a unique identifier for each geometry (e.g. the ``"BuildingId"``
column in many SpaceNet datasets.) See
:func:`solaris.utils.geo.split_multi_geometries` for more.
output_ext : str, optional, (default: geojson)
Extension of output files, can be 'geojson' or 'json'.
"""
tile_gen = self.tile_generator(src, tile_bounds, tile_bounds_crs,
geom_type, split_multi_geoms,
min_partial_perc,
obj_id_col=obj_id_col)
self.tile_paths = []
for tile_gdf, tb in tqdm(tile_gen):
if self.proj_unit not in ['meter', 'metre']:
dest_path = os.path.join(
self.dest_dir, '{}_{}_{}{}'.format(dest_fname_base,
np.round(tb[0], 3),
np.round(tb[3], 3),
output_ext))
else:
dest_path = os.path.join(
self.dest_dir, '{}_{}_{}{}'.format(dest_fname_base,
int(tb[0]),
int(tb[3]),
output_ext))
self.tile_paths.append(dest_path)
if len(tile_gdf) > 0:
tile_gdf.to_file(dest_path, driver='GeoJSON')
else:
save_empty_geojson(dest_path, self.dest_crs)
def tile_generator(self, src, tile_bounds, tile_bounds_crs=None,
geom_type='Polygon', split_multi_geoms=True,
min_partial_perc=0.0, obj_id_col=None):
"""Generate `src` vector data tiles bounded by `tile_bounds`.
Arguments
---------
src : `str` or :class:`geopandas.GeoDataFrame`
The source vector data to tile. Must either be a path to a GeoJSON
or a :class:`geopandas.GeoDataFrame`.
tile_bounds : list
A :class:`list` made up of ``[left, top, right, bottom] `` sublists
(this can be extracted from
:class:`solaris.tile.raster_tile.RasterTiler` after tiling imagery)
tile_bounds_crs : int, optional
The EPSG code for the CRS that the tile bounds are in. If not
provided, it's assumed that the CRS is the same as in `src`. This
argument must be provided if the bound coordinates and `src` are
not in the same CRS, otherwise tiling will not occur correctly.
geom_type : str, optional (default: "Polygon")
The type of geometries contained within `src`. Defaults to
``"Polygon"``, can also be ``"LineString"``.
split_multi_geoms : bool, optional (default: True)
Should multi-polygons or multi-linestrings generated by clipping
a geometry into discontinuous pieces be separated? Defaults to yes
(``True``).
min_partial_perc : float, optional (default: 0.0)
The minimum percentage of a :class:`shapely.geometry.Polygon` 's
area or :class:`shapely.geometry.LineString` 's length that must
be retained within a tile's bounds to be included in the output.
Defaults to ``0.0``, meaning that the contained portion of a
clipped geometry will be included, no matter how small.
obj_id_col : str, optional (default: None)
If ``split_multi_geoms=True``, the name of a column that specifies
a unique identifier for each geometry (e.g. the ``"BuildingId"``
column in many SpaceNet datasets.) See
:func:`solaris.utils.geo.split_multi_geometries` for more.
Yields
------
tile_gdf : :class:`geopandas.GeoDataFrame`
A tile geodataframe.
tb : list
A list with ``[left, top, right, bottom] `` coordinates for the
boundaries contained by `tile_gdf`.
"""
self.src = _check_gdf_load(src)
if self.verbose:
print("Num tiles:", len(tile_bounds))
self.src_crs = _check_crs(self.src.crs)
# check if the tile bounds and vector are in the same crs
if tile_bounds_crs is not None:
tile_bounds_crs = _check_crs(tile_bounds_crs)
else:
tile_bounds_crs = self.src_crs
if self.src_crs != tile_bounds_crs:
reproject_bounds = True # used to transform tb for clip_gdf()
else:
reproject_bounds = False
self.proj_unit = self.src_crs.linear_units
if getattr(self, 'dest_crs', None) is None:
self.dest_crs = self.src_crs
for i, tb in enumerate(tile_bounds):
if self.super_verbose:
print("\n", i, "/", len(tile_bounds))
if reproject_bounds:
tile_gdf = clip_gdf(self.src,
reproject_geometry(box(*tb),
tile_bounds_crs,
self.src_crs),
min_partial_perc,
geom_type, verbose=self.super_verbose)
else:
tile_gdf = clip_gdf(self.src, tb, min_partial_perc, geom_type,
verbose=self.super_verbose)
if self.src_crs != self.dest_crs:
tile_gdf = tile_gdf.to_crs(crs=self.dest_crs.to_wkt())
if split_multi_geoms:
split_multi_geometries(tile_gdf, obj_id_col=obj_id_col)
yield tile_gdf, tb
def search_gdf_polygon(gdf, tile_polygon):
"""Find polygons in a GeoDataFrame that overlap with `tile_polygon` .
Arguments
---------
gdf : :py:class:`geopandas.GeoDataFrame`
A :py:class:`geopandas.GeoDataFrame` of polygons to search.
tile_polygon : :py:class:`shapely.geometry.Polygon`
A :py:class:`shapely.geometry.Polygon` denoting a tile's bounds.
Returns
-------
precise_matches : :py:class:`geopandas.GeoDataFrame`
The subset of `gdf` that overlaps with `tile_polygon` . If
there are no overlaps, this will return an empty
:py:class:`geopandas.GeoDataFrame`.
"""
sindex = gdf.sindex
possible_matches_index = list(sindex.intersection(tile_polygon.bounds))
possible_matches = gdf.iloc[possible_matches_index]
precise_matches = possible_matches[
possible_matches.intersects(tile_polygon)
]
if precise_matches.empty:
precise_matches = gpd.GeoDataFrame(geometry=[])
return precise_matches
def clip_gdf(gdf, tile_bounds, min_partial_perc=0.0, geom_type="Polygon",
use_sindex=True, verbose=False):
"""Clip GDF to a provided polygon.
Clips objects within `gdf` to the region defined by
`poly_to_cut`. Also adds several columns to the output::
`origarea`
The original area of the polygons (only used if `geom_type` ==
``"Polygon"``).
`origlen`
The original length of the objects (only used if `geom_type` ==
``"LineString"``).
`partialDec`
The fraction of the object that remains after clipping
(fraction of area for Polygons, fraction of length for
LineStrings.) Can filter based on this by using `min_partial_perc`.
`truncated`
Boolean indicator of whether or not an object was clipped.
Arguments
---------
gdf : :py:class:`geopandas.GeoDataFrame`
A :py:class:`geopandas.GeoDataFrame` of polygons to clip.
tile_bounds : `list` or :class:`shapely.geometry.Polygon`
The geometry to clip objects in `gdf` to. This can either be a
``[left, top, right, bottom] `` bounds list or a
:class:`shapely.geometry.Polygon` object defining the area to keep.
min_partial_perc : float, optional
The minimum fraction of an object in `gdf` that must be
preserved. Defaults to 0.0 (include any object if any part remains
following clipping).
geom_type : str, optional
Type of objects in `gdf`. Can be one of
``["Polygon", "LineString"]`` . Defaults to ``"Polygon"`` .
use_sindex : bool, optional
Use the `gdf` sindex be used for searching. Improves efficiency
but requires `libspatialindex <http://libspatialindex.github.io/>`__ .
verbose : bool, optional
Switch to print relevant values.
Returns
-------
cut_gdf : :py:class:`geopandas.GeoDataFrame`
`gdf` with all contained objects clipped to `poly_to_cut` .
See notes above for details on additional clipping columns added.
"""
if isinstance(tile_bounds, tuple):
tb = box(*tile_bounds)
elif isinstance(tile_bounds, list):
tb = box(*tile_bounds)
elif isinstance(tile_bounds, Polygon):
tb = tile_bounds
if use_sindex and (geom_type == "Polygon"):
gdf = search_gdf_polygon(gdf, tb)
# if geom_type == "LineString":
if 'origarea' in gdf.columns:
pass
else:
if "geom_type" == "LineString":
gdf['origarea'] = 0
else:
gdf['origarea'] = gdf.area
if 'origlen' in gdf.columns:
pass
else:
if "geom_type" == "LineString":
gdf['origlen'] = gdf.length
else:
gdf['origlen'] = 0
# TODO must implement different case for lines and for spatialIndex
# (Assume RTree is already performed)
cut_gdf = gdf.copy()
cut_gdf.geometry = gdf.intersection(tb)
if geom_type == 'Polygon':
cut_gdf['partialDec'] = cut_gdf.area / cut_gdf['origarea']
cut_gdf = cut_gdf.loc[cut_gdf['partialDec'] > min_partial_perc, :]
cut_gdf['truncated'] = (cut_gdf['partialDec'] != 1.0).astype(int)
else:
# assume linestrings
# remove null
cut_gdf = cut_gdf[cut_gdf['geometry'].notnull()]
cut_gdf['partialDec'] = 1
cut_gdf['truncated'] = 0
# cut_gdf = cut_gdf[cut_gdf.geom_type != "GeometryCollection"]
if len(cut_gdf) > 0 and verbose:
print("clip_gdf() - gdf.iloc[0]:", gdf.iloc[0])
print("clip_gdf() - tb:", tb)
print("clip_gdf() - gdf_cut:", cut_gdf)
# TODO: IMPLEMENT TRUNCATION MEASUREMENT FOR LINESTRINGS
return cut_gdf
| 44.080745 | 83 | 0.594688 | import os
import numpy as np
from shapely.geometry import box, Polygon
import geopandas as gpd
from ..utils.core import _check_gdf_load, _check_crs
from ..utils.tile import save_empty_geojson
from ..utils.geo import gdf_get_projection_unit, split_multi_geometries
from ..utils.geo import reproject_geometry
from tqdm import tqdm
class VectorTiler(object):
def __init__(self, dest_dir=None, dest_crs=None, output_format='GeoJSON',
verbose=False, super_verbose=False):
if verbose or super_verbose:
print('Preparing the tiler...')
self.dest_dir = dest_dir
if not os.path.isdir(self.dest_dir):
os.makedirs(self.dest_dir)
if dest_crs is not None:
self.dest_crs = _check_crs(dest_crs)
self.output_format = output_format
self.verbose = verbose
self.super_verbose = super_verbose
self.tile_paths = []
if self.verbose or self.super_verbose:
print('Initialization done.')
def tile(self, src, tile_bounds, tile_bounds_crs=None, geom_type='Polygon',
split_multi_geoms=True, min_partial_perc=0.0,
dest_fname_base='geoms', obj_id_col=None,
output_ext='.geojson'):
tile_gen = self.tile_generator(src, tile_bounds, tile_bounds_crs,
geom_type, split_multi_geoms,
min_partial_perc,
obj_id_col=obj_id_col)
self.tile_paths = []
for tile_gdf, tb in tqdm(tile_gen):
if self.proj_unit not in ['meter', 'metre']:
dest_path = os.path.join(
self.dest_dir, '{}_{}_{}{}'.format(dest_fname_base,
np.round(tb[0], 3),
np.round(tb[3], 3),
output_ext))
else:
dest_path = os.path.join(
self.dest_dir, '{}_{}_{}{}'.format(dest_fname_base,
int(tb[0]),
int(tb[3]),
output_ext))
self.tile_paths.append(dest_path)
if len(tile_gdf) > 0:
tile_gdf.to_file(dest_path, driver='GeoJSON')
else:
save_empty_geojson(dest_path, self.dest_crs)
def tile_generator(self, src, tile_bounds, tile_bounds_crs=None,
geom_type='Polygon', split_multi_geoms=True,
min_partial_perc=0.0, obj_id_col=None):
self.src = _check_gdf_load(src)
if self.verbose:
print("Num tiles:", len(tile_bounds))
self.src_crs = _check_crs(self.src.crs)
if tile_bounds_crs is not None:
tile_bounds_crs = _check_crs(tile_bounds_crs)
else:
tile_bounds_crs = self.src_crs
if self.src_crs != tile_bounds_crs:
reproject_bounds = True
else:
reproject_bounds = False
self.proj_unit = self.src_crs.linear_units
if getattr(self, 'dest_crs', None) is None:
self.dest_crs = self.src_crs
for i, tb in enumerate(tile_bounds):
if self.super_verbose:
print("\n", i, "/", len(tile_bounds))
if reproject_bounds:
tile_gdf = clip_gdf(self.src,
reproject_geometry(box(*tb),
tile_bounds_crs,
self.src_crs),
min_partial_perc,
geom_type, verbose=self.super_verbose)
else:
tile_gdf = clip_gdf(self.src, tb, min_partial_perc, geom_type,
verbose=self.super_verbose)
if self.src_crs != self.dest_crs:
tile_gdf = tile_gdf.to_crs(crs=self.dest_crs.to_wkt())
if split_multi_geoms:
split_multi_geometries(tile_gdf, obj_id_col=obj_id_col)
yield tile_gdf, tb
def search_gdf_polygon(gdf, tile_polygon):
sindex = gdf.sindex
possible_matches_index = list(sindex.intersection(tile_polygon.bounds))
possible_matches = gdf.iloc[possible_matches_index]
precise_matches = possible_matches[
possible_matches.intersects(tile_polygon)
]
if precise_matches.empty:
precise_matches = gpd.GeoDataFrame(geometry=[])
return precise_matches
def clip_gdf(gdf, tile_bounds, min_partial_perc=0.0, geom_type="Polygon",
use_sindex=True, verbose=False):
if isinstance(tile_bounds, tuple):
tb = box(*tile_bounds)
elif isinstance(tile_bounds, list):
tb = box(*tile_bounds)
elif isinstance(tile_bounds, Polygon):
tb = tile_bounds
if use_sindex and (geom_type == "Polygon"):
gdf = search_gdf_polygon(gdf, tb)
if 'origarea' in gdf.columns:
pass
else:
if "geom_type" == "LineString":
gdf['origarea'] = 0
else:
gdf['origarea'] = gdf.area
if 'origlen' in gdf.columns:
pass
else:
if "geom_type" == "LineString":
gdf['origlen'] = gdf.length
else:
gdf['origlen'] = 0
cut_gdf = gdf.copy()
cut_gdf.geometry = gdf.intersection(tb)
if geom_type == 'Polygon':
cut_gdf['partialDec'] = cut_gdf.area / cut_gdf['origarea']
cut_gdf = cut_gdf.loc[cut_gdf['partialDec'] > min_partial_perc, :]
cut_gdf['truncated'] = (cut_gdf['partialDec'] != 1.0).astype(int)
else:
cut_gdf = cut_gdf[cut_gdf['geometry'].notnull()]
cut_gdf['partialDec'] = 1
cut_gdf['truncated'] = 0
if len(cut_gdf) > 0 and verbose:
print("clip_gdf() - gdf.iloc[0]:", gdf.iloc[0])
print("clip_gdf() - tb:", tb)
print("clip_gdf() - gdf_cut:", cut_gdf)
return cut_gdf
| true | true |
790c00350f25bef8955e5ddf884e6c7a046a9a32 | 1,171 | py | Python | display/plugins/Shutdown.py | rGunti/Yuki-Chan-Music-Player | d83ecc6d7fe2250725797386c670797847363f6e | [
"MIT"
] | null | null | null | display/plugins/Shutdown.py | rGunti/Yuki-Chan-Music-Player | d83ecc6d7fe2250725797386c670797847363f6e | [
"MIT"
] | null | null | null | display/plugins/Shutdown.py | rGunti/Yuki-Chan-Music-Player | d83ecc6d7fe2250725797386c670797847363f6e | [
"MIT"
] | null | null | null | #!/usr/bin/env python
"""
SHUTDOWN.PY
Shutdown Plugin
(C) 2015, rGunti
"""
import dot3k.lcd as lcd
import dot3k.backlight as backlight
import time, datetime, copy, math, psutil
import sys
import os
from dot3k.menu import Menu, MenuOption
class Shutdown(MenuOption):
def __init__(self):
self.last = self.millis()
MenuOption.__init__(self)
def redraw(self, menu):
lcd.clear()
lcd.set_cursor_position(3,1)
lcd.write("Bye (^_^)/")
for x in reversed(range(127)):
backlight.rgb(0, x * 2, 0)
lcd.clear()
os.system("halt")
sys.exit(0)
class Reboot(MenuOption):
def __init__(self):
self.last = self.millis()
MenuOption.__init__(self)
def redraw(self, menu):
lcd.clear()
lcd.set_cursor_position(3,1)
lcd.write("Bye (^_^)/")
for x in reversed(range(127)):
backlight.rgb(0, x * 2, 0)
lcd.clear()
os.system("reboot")
sys.exit(0)
class QuitScript(MenuOption):
def __init__(self):
self.last = self.millis()
MenuOption.__init__(self)
def redraw(self, menu):
lcd.clear()
lcd.set_cursor_position(3,1)
lcd.write("Bye (^_^)/")
for x in reversed(range(127)):
backlight.rgb(0, x * 2, 0)
lcd.clear()
sys.exit(0) | 20.189655 | 41 | 0.672075 |
import dot3k.lcd as lcd
import dot3k.backlight as backlight
import time, datetime, copy, math, psutil
import sys
import os
from dot3k.menu import Menu, MenuOption
class Shutdown(MenuOption):
def __init__(self):
self.last = self.millis()
MenuOption.__init__(self)
def redraw(self, menu):
lcd.clear()
lcd.set_cursor_position(3,1)
lcd.write("Bye (^_^)/")
for x in reversed(range(127)):
backlight.rgb(0, x * 2, 0)
lcd.clear()
os.system("halt")
sys.exit(0)
class Reboot(MenuOption):
def __init__(self):
self.last = self.millis()
MenuOption.__init__(self)
def redraw(self, menu):
lcd.clear()
lcd.set_cursor_position(3,1)
lcd.write("Bye (^_^)/")
for x in reversed(range(127)):
backlight.rgb(0, x * 2, 0)
lcd.clear()
os.system("reboot")
sys.exit(0)
class QuitScript(MenuOption):
def __init__(self):
self.last = self.millis()
MenuOption.__init__(self)
def redraw(self, menu):
lcd.clear()
lcd.set_cursor_position(3,1)
lcd.write("Bye (^_^)/")
for x in reversed(range(127)):
backlight.rgb(0, x * 2, 0)
lcd.clear()
sys.exit(0) | true | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.