id
int64
0
300k
label
stringlengths
1
74
text
stringlengths
4k
8k
3,600
grab aarch64 kernel
# TCG Plugins tests # # These are a little more involved than the basic tests run by check-tcg. # # Copyright (c) 2021 Linaro # # Author: # Alex Bennée <alex.bennee@linaro.org> # # SPDX-License-Identifier: GPL-2.0-or-later import tempfile import mmap import re from boot_linux_console import LinuxKernelTest class PluginKernelBase(LinuxKernelTest): """ Boots a Linux kernel with a TCG plugin enabled. """ timeout = 120 KERNEL_COMMON_COMMAND_LINE = 'printk.time=1 panic=-1 ' def run_vm(self, kernel_path, kernel_command_line, plugin, plugin_log, console_pattern, args=None): vm = self.get_vm() vm.set_console() vm.add_args('-kernel', kernel_path, '-append', kernel_command_line, '-plugin', plugin, '-d', 'plugin', '-D', plugin_log, '-net', 'none', '-no-reboot') if args: vm.add_args(*args) try: vm.launch() except: # TODO: probably fails because plugins not enabled but we # can't currently probe for the feature. self.cancel("TCG Plugins not enabled?") self.wait_for_console_pattern(console_pattern, vm) # ensure logs are flushed vm.shutdown() class PluginKernelNormal(PluginKernelBase): def METHOD_NAME(self): kernel_url = ('http://security.debian.org/' 'debian-security/pool/updates/main/l/linux-signed-arm64/' 'linux-image-4.19.0-12-arm64_4.19.152-1_arm64.deb') kernel_sha1 = '2036c2792f80ac9c4ccaae742b2e0a28385b6010' kernel_deb = self.fetch_asset(kernel_url, asset_hash=kernel_sha1) kernel_path = self.extract_from_deb(kernel_deb, "/boot/vmlinuz-4.19.0-12-arm64") return kernel_path def test_aarch64_virt_insn(self): """ :avocado: tags=accel:tcg :avocado: tags=arch:aarch64 :avocado: tags=machine:virt :avocado: tags=cpu:cortex-a53 """ kernel_path = self.METHOD_NAME() kernel_command_line = (self.KERNEL_COMMON_COMMAND_LINE + 'console=ttyAMA0') console_pattern = 'Kernel panic - not syncing: VFS:' plugin_log = tempfile.NamedTemporaryFile(mode="r+t", prefix="plugin", suffix=".log") self.run_vm(kernel_path, kernel_command_line, "tests/plugin/libinsn.so", plugin_log.name, console_pattern) with plugin_log as lf, \ mmap.mmap(lf.fileno(), 0, access=mmap.ACCESS_READ) as s: m = re.search(br"insns: (?P<count>\d+)", s) if "count" not in m.groupdict(): self.fail("Failed to find instruction count") def test_aarch64_virt_insn_icount(self): """ :avocado: tags=accel:tcg :avocado: tags=arch:aarch64 :avocado: tags=machine:virt :avocado: tags=cpu:cortex-a53 """ kernel_path = self.METHOD_NAME() kernel_command_line = (self.KERNEL_COMMON_COMMAND_LINE + 'console=ttyAMA0') console_pattern = 'Kernel panic - not syncing: VFS:' plugin_log = tempfile.NamedTemporaryFile(mode="r+t", prefix="plugin", suffix=".log") self.run_vm(kernel_path, kernel_command_line, "tests/plugin/libinsn.so", plugin_log.name, console_pattern, args=('-icount', 'shift=1')) with plugin_log as lf, \ mmap.mmap(lf.fileno(), 0, access=mmap.ACCESS_READ) as s: m = re.search(br"detected repeat execution @ (?P<addr>0x[0-9A-Fa-f]+)", s) if m is not None and "addr" in m.groupdict(): self.fail("detected repeated instructions") def test_aarch64_virt_mem_icount(self): """ :avocado: tags=accel:tcg :avocado: tags=arch:aarch64 :avocado: tags=machine:virt :avocado: tags=cpu:cortex-a53 """ kernel_path = self.METHOD_NAME() kernel_command_line = (self.KERNEL_COMMON_COMMAND_LINE + 'console=ttyAMA0') console_pattern = 'Kernel panic - not syncing: VFS:' plugin_log = tempfile.NamedTemporaryFile(mode="r+t", prefix="plugin", suffix=".log") self.run_vm(kernel_path, kernel_command_line, "tests/plugin/libmem.so,inline=true,callback=true", plugin_log.name, console_pattern, args=('-icount', 'shift=1')) with plugin_log as lf, \ mmap.mmap(lf.fileno(), 0, access=mmap.ACCESS_READ) as s: m = re.findall(br"mem accesses: (?P<count>\d+)", s) if m is None or len(m) != 2: self.fail("no memory access counts found") else: inline = int(m[0]) callback = int(m[1]) if inline != callback: self.fail("mismatched access counts")
3,601
get all sub messages
import textwrap import traceback from itertools import chain from typing import Iterable from celery import shared_task from django.utils.translation import gettext_lazy as _ from html2text import HTML2Text from common.utils import lazyproperty from common.utils.timezone import local_now from notifications.backends import BACKEND from settings.utils import get_login_title from users.models import User from .models import SystemMsgSubscription, UserMsgSubscription __all__ = ('SystemMessage', 'UserMessage', 'system_msgs', 'Message') system_msgs = [] user_msgs = [] class MessageType(type): def __new__(cls, name, bases, attrs: dict): clz = type.__new__(cls, name, bases, attrs) if 'message_type_label' in attrs \ and 'category' in attrs \ and 'category_label' in attrs: message_type = clz.get_message_type() msg = { 'message_type': message_type, 'message_type_label': attrs['message_type_label'], 'category': attrs['category'], 'category_label': attrs['category_label'], } if issubclass(clz, SystemMessage): system_msgs.append(msg) elif issubclass(clz, UserMessage): user_msgs.append(msg) return clz @shared_task(verbose_name=_('Publish the station message')) def publish_task(msg): msg.publish() class Message(metaclass=MessageType): """ 这里封装了什么? 封装不同消息的模板,提供统一的发送消息的接口 - publish 该方法的实现与消息订阅的表结构有关 - send_msg """ message_type_label: str category: str category_label: str text_msg_ignore_links = True @classmethod def get_message_type(cls): return cls.__name__ def publish_async(self): return publish_task.delay(self) @classmethod def gen_test_msg(cls): raise NotImplementedError def publish(self): raise NotImplementedError def send_msg(self, users: Iterable, backends: Iterable = BACKEND): backends = set(backends) backends.add(BACKEND.SITE_MSG) # 站内信必须发 for backend in backends: try: backend = BACKEND(backend) if not backend.is_enable: continue get_msg_method = getattr(self, f'get_{backend}_msg', self.get_common_msg) msg = get_msg_method() client = backend.client() client.send_msg(users, **msg) except NotImplementedError: continue except: traceback.print_exc() @classmethod def send_test_msg(cls, ding=True, wecom=False): msg = cls.gen_test_msg() if not msg: return from users.models import User users = User.objects.filter(username='admin') backends = [] if ding: backends.append(BACKEND.DINGTALK) if wecom: backends.append(BACKEND.WECOM) msg.send_msg(users, backends) @staticmethod def get_common_msg() -> dict: return {'subject': '', 'message': ''} def get_html_msg(self) -> dict: return self.get_common_msg() def get_markdown_msg(self) -> dict: h = HTML2Text() h.body_width = 300 msg = self.get_html_msg() content = msg['message'] msg['message'] = h.handle(content) return msg def get_text_msg(self) -> dict: h = HTML2Text() h.body_width = 90 msg = self.get_html_msg() content = msg['message'] h.ignore_links = self.text_msg_ignore_links msg['message'] = h.handle(content) return msg @lazyproperty def common_msg(self) -> dict: return self.get_common_msg() @lazyproperty def text_msg(self) -> dict: msg = self.get_text_msg() return msg @lazyproperty def markdown_msg(self): return self.get_markdown_msg() @lazyproperty def html_msg(self) -> dict: msg = self.get_html_msg() return msg @lazyproperty def html_msg_with_sign(self): msg = self.get_html_msg() msg['message'] = textwrap.dedent(""" {} <small> <br /> — <br /> {} </small> """).format(msg['message'], self.signature) return msg @lazyproperty def text_msg_with_sign(self): msg = self.get_text_msg() msg['message'] = textwrap.dedent(""" {} — {} """).format(msg['message'], self.signature) return msg @lazyproperty def signature(self): return get_login_title() # -------------------------------------------------------------- # 支持不同发送消息的方式定义自己的消息内容,比如有些支持 html 标签 def get_dingtalk_msg(self) -> dict: # 钉钉相同的消息一天只能发一次,所以给所有消息添加基于时间的序号,使他们不相同 message = self.markdown_msg['message'] time = local_now().strftime('%Y-%m-%d %H:%M:%S') suffix = '\n{}: {}'.format(_('Time'), time) return { 'subject': self.markdown_msg['subject'], 'message': message + suffix } def get_wecom_msg(self) -> dict: return self.markdown_msg def get_feishu_msg(self) -> dict: return self.markdown_msg def get_email_msg(self) -> dict: return self.html_msg_with_sign def get_site_msg_msg(self) -> dict: return self.html_msg def get_sms_msg(self) -> dict: return self.text_msg_with_sign @classmethod def METHOD_NAME(cls): def get_subclasses(cls): """returns all subclasses of argument, cls""" if issubclass(cls, type): subclasses = cls.__subclasses__(cls) else: subclasses = cls.__subclasses__() for subclass in subclasses: subclasses.extend(get_subclasses(subclass)) return subclasses messages_cls = get_subclasses(cls) return messages_cls @classmethod def test_all_messages(cls, ding=True, wecom=False): messages_cls = cls.METHOD_NAME() for _cls in messages_cls: try: _cls.send_test_msg(ding=ding, wecom=wecom) except NotImplementedError: continue class SystemMessage(Message): def publish(self): subscription = SystemMsgSubscription.objects.get( message_type=self.get_message_type() ) # 只发送当前有效后端 receive_backends = subscription.receive_backends receive_backends = BACKEND.filter_enable_backends(receive_backends) users = [ *subscription.users.all(), *chain(*[g.users.all() for g in subscription.groups.all()]) ] self.send_msg(users, receive_backends) @classmethod def post_insert_to_db(cls, subscription: SystemMsgSubscription): pass @classmethod def gen_test_msg(cls): raise NotImplementedError class UserMessage(Message): user: User def __init__(self, user): self.user = user def publish(self): """ 发送消息到每个用户配置的接收方式上 """ sub = UserMsgSubscription.objects.get(user=self.user) self.send_msg([self.user], sub.receive_backends) @classmethod def get_test_user(cls): from users.models import User return User.objects.all().first() @classmethod def gen_test_msg(cls): raise NotImplementedError
3,602
error format
# -------------------------------------------------------------------------------------------- # 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 aaz-dev-tools # -------------------------------------------------------------------------------------------- # pylint: skip-file # flake8: noqa from azure.cli.core.aaz import * @register_command( "network vhub routing-intent list", is_preview=True, ) class List(AAZCommand): """Retrieve the details of all routing intent resources of the virtual hub. :example: Retrieve the details of all routing intent resources of the virtual hub. az network vhub routing-intent list -g MyResourceGroup --vhub MyVirtualHub """ _aaz_info = { "version": "2021-05-01", "resources": [ ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.network/virtualhubs/{}/routingintent", "2021-05-01"], ] } def _handler(self, command_args): super()._handler(command_args) return self.build_paging(self._execute_operations, self._output) _args_schema = None @classmethod def _build_arguments_schema(cls, *args, **kwargs): if cls._args_schema is not None: return cls._args_schema cls._args_schema = super()._build_arguments_schema(*args, **kwargs) # define Arg Group "" _args_schema = cls._args_schema _args_schema.resource_group = AAZResourceGroupNameArg( required=True, ) _args_schema.vhub = AAZStrArg( options=["--vhub"], help="Name of the virtual hub.", required=True, ) return cls._args_schema def _execute_operations(self): self.RoutingIntentList(ctx=self.ctx)() def _output(self, *args, **kwargs): result = self.deserialize_output(self.ctx.vars.instance.value, client_flatten=True) next_link = self.deserialize_output(self.ctx.vars.instance.next_link) return result, next_link class RoutingIntentList(AAZHttpOperation): CLIENT_TYPE = "MgmtClient" def __call__(self, *args, **kwargs): request = self.make_request() session = self.client.send_request(request=request, stream=False, **kwargs) if session.http_response.status_code in [200]: return self.on_200(session) return self.on_error(session.http_response) @property def url(self): return self.client.format_url( "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/routingIntent", **self.url_parameters ) @property def method(self): return "GET" @property def METHOD_NAME(self): return "ODataV4Format" @property def url_parameters(self): parameters = { **self.serialize_url_param( "resourceGroupName", self.ctx.args.resource_group, required=True, ), **self.serialize_url_param( "subscriptionId", self.ctx.subscription_id, required=True, ), **self.serialize_url_param( "virtualHubName", self.ctx.args.vhub, required=True, ), } return parameters @property def query_parameters(self): parameters = { **self.serialize_query_param( "api-version", "2021-05-01", required=True, ), } return parameters @property def header_parameters(self): parameters = { **self.serialize_header_param( "Accept", "application/json", ), } return parameters def on_200(self, session): data = self.deserialize_http_content(session) self.ctx.set_var( "instance", data, schema_builder=self._build_schema_on_200 ) _schema_on_200 = None @classmethod def _build_schema_on_200(cls): if cls._schema_on_200 is not None: return cls._schema_on_200 cls._schema_on_200 = AAZObjectType() _schema_on_200 = cls._schema_on_200 _schema_on_200.next_link = AAZStrType( serialized_name="nextLink", ) _schema_on_200.value = AAZListType() value = cls._schema_on_200.value value.Element = AAZObjectType() _element = cls._schema_on_200.value.Element _element.etag = AAZStrType( flags={"read_only": True}, ) _element.id = AAZStrType() _element.name = AAZStrType() _element.properties = AAZObjectType( flags={"client_flatten": True}, ) _element.type = AAZStrType( flags={"read_only": True}, ) properties = cls._schema_on_200.value.Element.properties properties.provisioning_state = AAZStrType( serialized_name="provisioningState", flags={"read_only": True}, ) properties.routing_policies = AAZListType( serialized_name="routingPolicies", ) routing_policies = cls._schema_on_200.value.Element.properties.routing_policies routing_policies.Element = AAZObjectType() _element = cls._schema_on_200.value.Element.properties.routing_policies.Element _element.destinations = AAZListType( flags={"required": True}, ) _element.name = AAZStrType( flags={"required": True}, ) _element.next_hop = AAZStrType( serialized_name="nextHop", flags={"required": True}, ) destinations = cls._schema_on_200.value.Element.properties.routing_policies.Element.destinations destinations.Element = AAZStrType() return cls._schema_on_200 __all__ = ["List"]
3,603
test getobject store
import os from bz2 import BZ2File from gzip import GzipFile from io import BytesIO from translate.storage import factory from translate.storage.directory import Directory def classname(filename): """returns the classname to ease testing""" classinstance = factory.getclass(filename) return str(classinstance.__name__).lower() def givefile(filename, content): """returns a file dummy object with the given content""" file = BytesIO(content) file.name = filename return file class BaseTestFactory: def setup_method(self, method): """sets up a test directory""" self.testdir = "%s_testdir" % (self.__class__.__name__) self.cleardir(self.testdir) os.mkdir(self.testdir) def teardown_method(self, method): """removes the attributes set up by setup_method""" self.cleardir(self.testdir) @classmethod def cleardir(self, dirname): """removes the given directory""" if os.path.exists(dirname): for dirpath, subdirs, filenames in os.walk(dirname, topdown=False): for name in filenames: os.remove(os.path.join(dirpath, name)) for name in subdirs: os.rmdir(os.path.join(dirpath, name)) if os.path.exists(dirname): os.rmdir(dirname) assert not os.path.exists(dirname) @staticmethod def test_getclass(): assert classname("file.po") == "pofile" assert classname("file.pot") == "pofile" assert classname("file.dtd.po") == "pofile" assert classname("file.tmx") == "tmxfile" assert classname("file.af.tmx") == "tmxfile" assert classname("file.tbx") == "tbxfile" assert classname("file.po.xliff") == "xlifffile" assert not classname("file.po") == "tmxfile" assert not classname("file.po") == "xlifffile" assert classname("file.po.gz") == "pofile" assert classname("file.pot.gz") == "pofile" assert classname("file.dtd.po.gz") == "pofile" assert classname("file.tmx.gz") == "tmxfile" assert classname("file.af.tmx.gz") == "tmxfile" assert classname("file.tbx.gz") == "tbxfile" assert classname("file.po.xliff.gz") == "xlifffile" assert not classname("file.po.gz") == "tmxfile" assert not classname("file.po.gz") == "xlifffile" assert classname("file.po.bz2") == "pofile" assert classname("file.pot.bz2") == "pofile" assert classname("file.dtd.po.bz2") == "pofile" assert classname("file.tmx.bz2") == "tmxfile" assert classname("file.af.tmx.bz2") == "tmxfile" assert classname("file.tbx.bz2") == "tbxfile" assert classname("file.po.xliff.bz2") == "xlifffile" assert not classname("file.po.bz2") == "tmxfile" assert not classname("file.po.bz2") == "xlifffile" def METHOD_NAME(self): """Tests that we get a valid object.""" fileobj = givefile(self.filename, self.file_content) store = factory.getobject(fileobj) assert isinstance(store, self.expected_instance) assert store == factory.getobject(store) def test_getobject(self): """Tests that we get a valid object.""" fileobj = givefile(self.filename, self.file_content) store = factory.getobject(fileobj) assert isinstance(store, self.expected_instance) def test_get_noname_object(self): """Tests that we get a valid object from a file object without a name.""" fileobj = BytesIO(self.file_content) assert not hasattr(fileobj, "name") store = factory.getobject(fileobj) assert isinstance(store, self.expected_instance) def test_gzfile(self): """Test that we can open a gzip file correctly.""" filename = os.path.join(self.testdir, self.filename + ".gz") gzfile = GzipFile(filename, mode="wb") gzfile.write(self.file_content) gzfile.close() store = factory.getobject(filename) assert isinstance(store, self.expected_instance) def test_bz2file(self): """Test that we can open a gzip file correctly.""" filename = os.path.join(self.testdir, self.filename + ".bz2") with BZ2File(filename, mode="wb") as bz2file: bz2file.write(self.file_content) store = factory.getobject(filename) assert isinstance(store, self.expected_instance) def test_directory(self): """Test that a directory is correctly detected.""" object = factory.getobject(self.testdir) assert isinstance(object, Directory) class TestPOFactory(BaseTestFactory): from translate.storage import po expected_instance = po.pofile filename = "dummy.po" file_content = b"""#: test.c\nmsgid "test"\nmsgstr "rest"\n""" class TestXliffFactory(BaseTestFactory): from translate.storage import xliff expected_instance = xliff.xlifffile filename = "dummy.xliff" file_content = b"""<?xml version="1.0" encoding="utf-8"?> <xliff version="1.1" xmlns="urn:oasis:names:tc:xliff:document:1.1"> <file> <body> <trans-unit> <source>test</source> <target>rest</target> </trans-unit> </body> </file> </xliff>""" class TestPOXliffFactory(BaseTestFactory): from translate.storage import poxliff expected_instance = poxliff.PoXliffFile filename = "dummy.xliff" file_content = b"""<?xml version="1.0" encoding="utf-8"?> <xliff version="1.1" xmlns="urn:oasis:names:tc:xliff:document:1.1"> <file datatype="po" original="file.po" source-language="en-US"><body><trans-unit approved="no" id="1" restype="x-gettext-domain-header" xml:space="preserve"> <source>MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit </source> <target>MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit </target> </trans-unit></body></file></xliff>""" class TestWordfastFactory(BaseTestFactory): from translate.storage import wordfast expected_instance = wordfast.WordfastTMFile filename = "dummy.txt" file_content = ( b"""%20070801~103212 %User ID,S,S SMURRAY,SMS Samuel Murray-Smit,SM Samuel Murray-Smit,MW Mary White,DS Deepak Shota,MT! Machine translation (15),AL! Alignment (10),SM Samuel Murray, %TU=00000075 %AF-ZA %Wordfast TM v.5.51r/00 %EN-ZA %---80597535 Subject (5),EL,EL Electronics,AC Accounting,LE Legal,ME Mechanics,MD Medical,LT Literary,AG Agriculture,CO Commercial Client (5),LS,LS LionSoft Corp,ST SuperTron Inc,CA CompArt Ltd """ b"""20070801~103248 SM 0 AF-ZA Langeraad en duimpie EN-ZA Big Ben and Little John EL LS""" )
3,604
add binary
# -*- mode: python ; coding: utf-8 -*- import importlib import os import pathlib import platform import sysconfig from pkg_resources import get_distribution from PyInstaller.utils.hooks import collect_submodules, copy_metadata THIS_IS_WINDOWS = platform.system().lower().startswith("win") THIS_IS_MAC = platform.system().lower().startswith("darwin") ROOT = pathlib.Path(importlib.import_module("chia").__file__).absolute().parent.parent def solve_name_collision_problem(analysis): """ There is a collision between the `chia` file name (which is the executable) and the `chia` directory, which contains non-code resources like `english.txt`. We move all the resources in the zipped area so there is no need to create the `chia` directory, since the names collide. Fetching data now requires going into a zip file, so it will be slower. It's best if files that are used frequently are cached. A sample large compressible file (1 MB of `/dev/zero`), seems to be about eight times slower. Note that this hack isn't documented, but seems to work. """ zipped = [] datas = [] for data in analysis.datas: if str(data[0]).startswith("chia/"): zipped.append(data) else: datas.append(data) # items in this field are included in the binary analysis.zipped_data = zipped # these items will be dropped in the root folder uncompressed analysis.datas = datas keyring_imports = collect_submodules("keyring.backends") # keyring uses entrypoints to read keyring.backends from metadata file entry_points.txt. keyring_datas = copy_metadata("keyring")[0] version_data = copy_metadata(get_distribution("chia-blockchain"))[0] block_cipher = None SERVERS = [ "data_layer", "wallet", "full_node", "harvester", "farmer", "introducer", "timelord", ] if THIS_IS_WINDOWS: hidden_imports_for_windows = ["win32timezone", "win32cred", "pywintypes", "win32ctypes.pywin32"] else: hidden_imports_for_windows = [] hiddenimports = [ *collect_submodules("chia"), *keyring_imports, *hidden_imports_for_windows, ] binaries = [] if os.path.exists(f"{ROOT}/madmax/chia_plot"): binaries.extend([ ( f"{ROOT}/madmax/chia_plot", "madmax" ) ]) if os.path.exists(f"{ROOT}/madmax/chia_plot_k34",): binaries.extend([ ( f"{ROOT}/madmax/chia_plot_k34", "madmax" ) ]) if os.path.exists(f"{ROOT}/bladebit/bladebit"): binaries.extend([ ( f"{ROOT}/bladebit/bladebit", "bladebit" ) ]) if os.path.exists(f"{ROOT}/bladebit/bladebit_cuda"): binaries.extend([ ( f"{ROOT}/bladebit/bladebit_cuda", "bladebit" ) ]) if THIS_IS_WINDOWS: chia_mod = importlib.import_module("chia") dll_paths = pathlib.Path(sysconfig.get_path("platlib")) / "*.dll" binaries = [ ( dll_paths, ".", ), ( "C:\\Windows\\System32\\msvcp140.dll", ".", ), ( "C:\\Windows\\System32\\vcruntime140_1.dll", ".", ), ( f"{ROOT}\\madmax\\chia_plot.exe", "madmax" ), ( f"{ROOT}\\madmax\\chia_plot_k34.exe", "madmax" ), ( f"{ROOT}\\bladebit\\bladebit.exe", "bladebit" ), ( f"{ROOT}\\bladebit\\bladebit_cuda.exe", "bladebit" ), ] datas = [] datas.append((f"{ROOT}/chia/util/english.txt", "chia/util")) datas.append((f"{ROOT}/chia/util/initial-config.yaml", "chia/util")) for path in sorted({path.parent for path in ROOT.joinpath("chia").rglob("*.hex")}): datas.append((f"{path}/*.hex", path.relative_to(ROOT))) datas.append((f"{ROOT}/chia/ssl/*", "chia/ssl")) datas.append((f"{ROOT}/mozilla-ca/*", "mozilla-ca")) datas.append(version_data) pathex = [] def METHOD_NAME(name, path_to_script, collect_args): analysis = Analysis( [path_to_script], pathex=pathex, binaries=binaries, datas=datas, hiddenimports=hiddenimports, hookspath=[], runtime_hooks=[], excludes=[], win_no_prefer_redirects=False, win_private_assemblies=False, cipher=block_cipher, noarchive=False, ) solve_name_collision_problem(analysis) binary_pyz = PYZ(analysis.pure, analysis.zipped_data, cipher=block_cipher) binary_exe = EXE( binary_pyz, analysis.scripts, [], exclude_binaries=True, name=name, debug=False, bootloader_ignore_signals=False, strip=False, ) collect_args.extend( [ binary_exe, analysis.binaries, analysis.zipfiles, analysis.datas, ] ) COLLECT_ARGS = [] METHOD_NAME("chia", f"{ROOT}/chia/cmds/chia.py", COLLECT_ARGS) METHOD_NAME("daemon", f"{ROOT}/chia/daemon/server.py", COLLECT_ARGS) for server in SERVERS: METHOD_NAME(f"start_{server}", f"{ROOT}/chia/server/start_{server}.py", COLLECT_ARGS) METHOD_NAME("start_crawler", f"{ROOT}/chia/seeder/start_crawler.py", COLLECT_ARGS) METHOD_NAME("start_seeder", f"{ROOT}/chia/seeder/dns_server.py", COLLECT_ARGS) METHOD_NAME("start_data_layer_http", f"{ROOT}/chia/data_layer/data_layer_server.py", COLLECT_ARGS) METHOD_NAME("start_data_layer_s3_plugin", f"{ROOT}/chia/data_layer/s3_plugin_service.py", COLLECT_ARGS) METHOD_NAME("timelord_launcher", f"{ROOT}/chia/timelord/timelord_launcher.py", COLLECT_ARGS) COLLECT_KWARGS = dict( strip=False, upx_exclude=[], name="daemon", ) coll = COLLECT(*COLLECT_ARGS, **COLLECT_KWARGS)
3,605
system data
# coding=utf-8 # *** WARNING: this file was generated by pulumi. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import copy import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities from . import outputs __all__ = [ 'GetProviderRegistrationResult', 'AwaitableGetProviderRegistrationResult', 'get_provider_registration', 'get_provider_registration_output', ] @pulumi.output_type class GetProviderRegistrationResult: def __init__(__self__, id=None, name=None, properties=None, METHOD_NAME=None, type=None): if id and not isinstance(id, str): raise TypeError("Expected argument 'id' to be a str") pulumi.set(__self__, "id", id) if name and not isinstance(name, str): raise TypeError("Expected argument 'name' to be a str") pulumi.set(__self__, "name", name) if properties and not isinstance(properties, dict): raise TypeError("Expected argument 'properties' to be a dict") pulumi.set(__self__, "properties", properties) if METHOD_NAME and not isinstance(METHOD_NAME, dict): raise TypeError("Expected argument 'system_data' to be a dict") pulumi.set(__self__, "system_data", METHOD_NAME) if type and not isinstance(type, str): raise TypeError("Expected argument 'type' to be a str") pulumi.set(__self__, "type", type) @property @pulumi.getter def id(self) -> str: """ Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} """ return pulumi.get(self, "id") @property @pulumi.getter def name(self) -> str: """ The name of the resource """ return pulumi.get(self, "name") @property @pulumi.getter def properties(self) -> 'outputs.ProviderRegistrationResponseProperties': return pulumi.get(self, "properties") @property @pulumi.getter(name="systemData") def METHOD_NAME(self) -> 'outputs.SystemDataResponse': """ Metadata pertaining to creation and last modification of the resource. """ return pulumi.get(self, "system_data") @property @pulumi.getter def type(self) -> str: """ The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" """ return pulumi.get(self, "type") class AwaitableGetProviderRegistrationResult(GetProviderRegistrationResult): # pylint: disable=using-constant-test def __await__(self): if False: yield self return GetProviderRegistrationResult( id=self.id, name=self.name, properties=self.properties, METHOD_NAME=self.METHOD_NAME, type=self.type) def get_provider_registration(provider_namespace: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetProviderRegistrationResult: """ Gets the provider registration details. :param str provider_namespace: The name of the resource provider hosted within ProviderHub. """ __args__ = dict() __args__['providerNamespace'] = provider_namespace opts = pulumi.InvokeOptions.merge(_utilities.get_invoke_opts_defaults(), opts) __ret__ = pulumi.runtime.invoke('azure-native:providerhub/v20210901preview:getProviderRegistration', __args__, opts=opts, typ=GetProviderRegistrationResult).value return AwaitableGetProviderRegistrationResult( id=pulumi.get(__ret__, 'id'), name=pulumi.get(__ret__, 'name'), properties=pulumi.get(__ret__, 'properties'), METHOD_NAME=pulumi.get(__ret__, 'system_data'), type=pulumi.get(__ret__, 'type')) @_utilities.lift_output_func(get_provider_registration) def get_provider_registration_output(provider_namespace: Optional[pulumi.Input[str]] = None, opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetProviderRegistrationResult]: """ Gets the provider registration details. :param str provider_namespace: The name of the resource provider hosted within ProviderHub. """ ...
3,606
reader
"""Tests support for new syntax introduced by PEP 492.""" import sys import types import unittest from unittest import mock import asyncio from test.test_asyncio import utils as test_utils def tearDownModule(): asyncio.set_event_loop_policy(None) # Test that asyncio.iscoroutine() uses collections.abc.Coroutine class FakeCoro: def send(self, value): pass def throw(self, typ, val=None, tb=None): pass def close(self): pass def __await__(self): yield class BaseTest(test_utils.TestCase): def setUp(self): super().setUp() self.loop = asyncio.BaseEventLoop() self.loop._process_events = mock.Mock() self.loop._selector = mock.Mock() self.loop._selector.select.return_value = () self.set_event_loop(self.loop) class LockTests(BaseTest): def test_context_manager_async_with(self): with self.assertWarns(DeprecationWarning): primitives = [ asyncio.Lock(loop=self.loop), asyncio.Condition(loop=self.loop), asyncio.Semaphore(loop=self.loop), asyncio.BoundedSemaphore(loop=self.loop), ] async def test(lock): await asyncio.sleep(0.01) self.assertFalse(lock.locked()) async with lock as _lock: self.assertIs(_lock, None) self.assertTrue(lock.locked()) await asyncio.sleep(0.01) self.assertTrue(lock.locked()) self.assertFalse(lock.locked()) for primitive in primitives: self.loop.run_until_complete(test(primitive)) self.assertFalse(primitive.locked()) def test_context_manager_with_await(self): with self.assertWarns(DeprecationWarning): primitives = [ asyncio.Lock(loop=self.loop), asyncio.Condition(loop=self.loop), asyncio.Semaphore(loop=self.loop), asyncio.BoundedSemaphore(loop=self.loop), ] async def test(lock): await asyncio.sleep(0.01) self.assertFalse(lock.locked()) with self.assertWarns(DeprecationWarning): with await lock as _lock: self.assertIs(_lock, None) self.assertTrue(lock.locked()) await asyncio.sleep(0.01) self.assertTrue(lock.locked()) self.assertFalse(lock.locked()) for primitive in primitives: self.loop.run_until_complete(test(primitive)) self.assertFalse(primitive.locked()) class StreamReaderTests(BaseTest): def test_readline(self): DATA = b'line1\nline2\nline3' stream = asyncio.StreamReader(loop=self.loop) stream.feed_data(DATA) stream.feed_eof() async def METHOD_NAME(): data = [] async for line in stream: data.append(line) return data data = self.loop.run_until_complete(METHOD_NAME()) self.assertEqual(data, [b'line1\n', b'line2\n', b'line3']) class CoroutineTests(BaseTest): def test_iscoroutine(self): async def foo(): pass f = foo() try: self.assertTrue(asyncio.iscoroutine(f)) finally: f.close() # silence warning self.assertTrue(asyncio.iscoroutine(FakeCoro())) def test_iscoroutinefunction(self): async def foo(): pass self.assertTrue(asyncio.iscoroutinefunction(foo)) def test_function_returning_awaitable(self): class Awaitable: def __await__(self): return ('spam',) with self.assertWarns(DeprecationWarning): @asyncio.coroutine def func(): return Awaitable() coro = func() self.assertEqual(coro.send(None), 'spam') coro.close() def test_async_def_coroutines(self): async def bar(): return 'spam' async def foo(): return await bar() # production mode data = self.loop.run_until_complete(foo()) self.assertEqual(data, 'spam') # debug mode self.loop.set_debug(True) data = self.loop.run_until_complete(foo()) self.assertEqual(data, 'spam') def test_debug_mode_manages_coroutine_origin_tracking(self): async def start(): self.assertTrue(sys.get_coroutine_origin_tracking_depth() > 0) self.assertEqual(sys.get_coroutine_origin_tracking_depth(), 0) self.loop.set_debug(True) self.loop.run_until_complete(start()) self.assertEqual(sys.get_coroutine_origin_tracking_depth(), 0) def test_types_coroutine(self): def gen(): yield from () return 'spam' @types.coroutine def func(): return gen() async def coro(): wrapper = func() self.assertIsInstance(wrapper, types._GeneratorWrapper) return await wrapper data = self.loop.run_until_complete(coro()) self.assertEqual(data, 'spam') def test_task_print_stack(self): T = None async def foo(): f = T.get_stack(limit=1) try: self.assertEqual(f[0].f_code.co_name, 'foo') finally: f = None async def runner(): nonlocal T T = asyncio.ensure_future(foo(), loop=self.loop) await T self.loop.run_until_complete(runner()) def test_double_await(self): async def afunc(): await asyncio.sleep(0.1) async def runner(): coro = afunc() t = self.loop.create_task(coro) try: await asyncio.sleep(0) await coro finally: t.cancel() self.loop.set_debug(True) with self.assertRaises( RuntimeError, msg='coroutine is being awaited already'): self.loop.run_until_complete(runner()) if __name__ == '__main__': unittest.main()
3,607
feature host mount
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Shadowing mountpoints will never be allowed. Additionally, for now: - The mountpoint must not exist, and is automatically created as an empty directory or file with root:root ownership. If needed, we may add a flag to accept pre-existing empty mountpoints (`remove_paths` is a workaround). The motivation for auto-creating the mountpoint is two-fold: * This reduces boilerplate in features with `mounts` -- the properties of the mountpoint don't matter. * This guarantees the mounpoint is empty. - Nesting mountpoints is forbidden. If support is ever added, we should make the intent to nest very explicit (syntax TBD). - All mounts are read-only. ### Implementation Details A mount target, roughly, is a JSON blob with a "type" string, a "source" location interpretable by that type, and a "default_mountpoint". We use targets as mount sources because: - This allows mounts to be materialized, flexibly, at build-time, and allows us to provide a cheap "development time" proxy for mounts that might be distributed in a more costly way at deployment time. - This allows us Buck to cleanly cache mounts fetched from package distribution systems -- i.e. we can use the local Buck cache the same way that Docker caches downloaded images. Adding a mount has two side effects on the `image.layer`: - The mount will be materialized in the `buck-image-out` cache of the local repo, so your filesystem acts as WYSIWIG. - The mount will be recorded in `/.meta/private/mount`. PLEASE, do not rely on this serializaation format for now, it will change. That's why it's "private". Future: we may need another feature for removing mounts provided by parent layers. """ load("//antlir/antlir2/bzl/feature:defs.bzl?v2_only", antlir2_feature = "feature") load("//antlir/bzl:build_defs.bzl", "is_buck2") load("//antlir/bzl:target_tagger.bzl", "new_target_tagger", "tag_target", "target_tagger_to_feature") load(":mount.shape.bzl", "build_source_t", "mount_config_t", "mount_spec_t") def METHOD_NAME(source, mountpoint, is_directory): return mount_spec_t( mount_config = mount_config_t( build_source = build_source_t( source = source, type = "host", ), default_mountpoint = source if mountpoint == None else mountpoint, is_directory = is_directory, ), mountpoint = None, target = None, ) def feature_host_dir_mount(source, mountpoint = None): """ `feature.host_dir_mount("/path/foo")` bind-mounts the host directory `/path/foo` into the container at `/path/foo`. Another image item must provide the parent `/path`, but this item will create the mount-point. """ mount_spec = METHOD_NAME( source, mountpoint, is_directory = True, ) return target_tagger_to_feature( new_target_tagger(), items = struct(mounts = [mount_spec]), antlir2_feature = antlir2_feature.host_mount( source = source, mountpoint = mountpoint, is_directory = True, _implicit_from_antlir1 = True, ) if is_buck2() else None, ) def feature_host_file_mount(source, mountpoint = None): """ `feature.host_file_mount("/path/bar", "/baz")` bind-mounts the file `/path/bar` into the container at `/baz`. """ mount_spec = METHOD_NAME( source, mountpoint, is_directory = False, ) return target_tagger_to_feature( new_target_tagger(), items = struct(mounts = [mount_spec]), antlir2_feature = antlir2_feature.host_mount( source = source, mountpoint = mountpoint, is_directory = False, _implicit_from_antlir1 = True, ) if is_buck2() else None, ) def feature_layer_mount(source, mountpoint = None): """ `feature.layer_mount(":other-image-layer")` makes the specified layer available inside the container available at the "default_mountpoint" provided by the layer in its config. That fails if the layer lacks a default mountpoint, but then you can pass an explicit `mountpoint` argument. """ target_tagger = new_target_tagger() mount_spec = mount_spec_t( mount_config = None, mountpoint = mountpoint, target = tag_target(target_tagger, source), ) return target_tagger_to_feature( target_tagger = target_tagger, items = struct(mounts = [mount_spec]), antlir2_feature = antlir2_feature.layer_mount( source = source + ".antlir2", mountpoint = mountpoint, _implicit_from_antlir1 = True, ) if is_buck2() else None, )
3,608
lines intersection
#!/usr/bin/env python # DEPRECRATED: Non-vector operators over non-vectorized data from numpy import array, cos, sin from math import atan2, sqrt def METHOD_NAME(xy1, xy2, xy3, xy4): """ Returns the intersection of two lines. """ (x1, y1) = xy1 (x2, y2) = xy2 (x3, y3) = xy3 (x4, y4) = xy4 b = (x2 - x1, y2 - y1) d = (x4 - x3, y4 - y3) det = b[0] * d[1] - b[1] * d[0] if det == 0: return None c = (x3 - x1, y3 - y1) t = float(c[0] * b[1] - c[1] * b[0]) / (det * 1.0) if t < 0.0 or t > 1.0: return None t = float(c[0] * d[1] - c[1] * d[0]) / (det * 1.0) if t < 0.0 or t > 1.0: return None x = x1 + t * b[0] y = y1 + t * b[1] return (x, y) def rectangle_point_intersection(rec, p): """ Returns the intersection point between the Rectangle (w,h) that characterize the rec object and the line that goes from the recs' object center to the 'p' point. """ x2, y2 = p[0] - rec.xy[0], p[1] - rec.xy[1] x1, y1 = 0, 0 # bounding box: bbx2 = rec.w // 2 bbx1 = -bbx2 bby2 = rec.h // 2 bby1 = -bby2 segments = [ ((x1, y1), (x2, y2), (bbx1, bby1), (bbx2, bby1)), ((x1, y1), (x2, y2), (bbx2, bby1), (bbx2, bby2)), ((x1, y1), (x2, y2), (bbx1, bby2), (bbx2, bby2)), ((x1, y1), (x2, y2), (bbx1, bby2), (bbx1, bby1)), ] for segs in segments: xy = METHOD_NAME(*segs) if xy is not None: x, y = xy x += rec.xy[0] y += rec.xy[1] return x, y # can't be an intersection unless the endpoint was inside the bb raise ValueError( "no intersection found (point inside ?!). rec: %s p: %s" % (rec, p) ) def angle_between_vectors(p1, p2): x1, y1 = p1 x2, y2 = p2 theta = atan2(y2 - y1, x2 - x1) return theta def size_median(recs): mw = [v.w for v in recs] mh = [v.h for v in recs] mw.sort() mh.sort() return (mw[len(mw) // 2], mh[len(mh) // 2]) def setcurve(e, pts, tgs = None): """ Returns the spline curve that path through the list of points P. The spline curve is a list of cubic bezier curves (nurbs) that have matching tangents at their extreme points. The method considered here is taken from "The NURBS book" (Les A. Piegl, Wayne Tiller, Springer, 1997) and implements a local interpolation rather than a global interpolation. Args: e: pts: tgs: Returns: """ P = list(map(array, pts)) n = len(P) # tangent estimation if tgs: assert len(tgs) == n T = list(map(array, tgs)) Q = [P[k + 1] - P[k] for k in range(0, n - 1)] else: Q, T = tangents(P, n) splines = [] for k in range(n - 1): t = T[k] + T[k + 1] a = 16.0 - (t.dot(t)) b = 12.0 * (Q[k].dot(t)) c = -36.0 * Q[k].dot(Q[k]) D = (b * b) - 4.0 * a * c assert D >= 0 sd = sqrt(D) s1, s2 = (-b - sd) / (2.0 * a), (-b + sd) / (2.0 * a) s = s2 if s1 >= 0: s = s1 C0 = tuple(P[k]) C1 = tuple(P[k] + (s / 3.0) * T[k]) C2 = tuple(P[k + 1] - (s / 3.0) * T[k + 1]) C3 = tuple(P[k + 1]) splines.append([C0, C1, C2, C3]) return splines def tangents(P, n): assert n >= 2 Q = [] T = [] for k in range(0, n - 1): q = P[k + 1] - P[k] t = q / sqrt(q.dot(q)) Q.append(q) T.append(t) T.append(t) return Q, T def set_round_corner(e, pts): P = list(map(array, pts)) n = len(P) Q, T = tangents(P, n) c0 = P[0] t0 = T[0] k0 = 0 splines = [] k = 1 while k < n: z = abs(t0[0] * T[k][1] - (t0[1] * T[k][0])) if z < 1.0e-6: k += 1 continue if (k - 1) > k0: splines.append([c0, P[k - 1]]) if (k + 1) < n: splines.extend(setcurve(e, [P[k - 1], P[k + 1]], tgs = [T[k - 1], T[k + 1]])) else: splines.extend(setcurve(e, [P[k - 1], P[k]], tgs = [T[k - 1], T[k]])) break if (k + 2) < n: c0 = P[k + 1] t0 = T[k + 1] k0 = k + 1 k += 2 else: break return splines or [[P[0], P[-1]]] def new_point_at_distance(pt, distance, angle): # in rad distance = float(distance) x, y = pt[0], pt[1] x += distance * cos(angle) y += distance * sin(angle) return x, y
3,609
to bytes
""" This table is stored in ARM9 and has two entries for every Pokémon base form. - The first one seems to be how many 16x16 tile slots (or 256 byte pixels) the Pokémon's sprite will take up. - The second is unknown, but also related to the sprite size? """ # Copyright 2020-2023 Capypara and the SkyTemple Contributors # # This file is part of SkyTemple. # # SkyTemple is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # SkyTemple is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with SkyTemple. If not, see <https://www.gnu.org/licenses/>. from __future__ import annotations from enum import Enum from typing import List from range_typed_integers import u8 from skytemple_files.common.i18n_util import _ from skytemple_files.common.ppmdu_config.data import Pmd2Data from skytemple_files.common.util import ( AutoString, read_u8, ) ENTRY_LEN = 2 class MonsterSpriteDataTableEntry(AutoString): sprite_tile_slots: u8 unk1: u8 def __init__(self, sprite_tile_slots: u8, unk1: u8): self.sprite_tile_slots = sprite_tile_slots self.unk1 = unk1 def METHOD_NAME(self) -> bytes: return bytes([self.sprite_tile_slots, self.unk1]) def __eq__(self, other: object) -> bool: if not isinstance(other, MonsterSpriteDataTableEntry): return False return ( self.sprite_tile_slots == other.sprite_tile_slots and self.unk1 == other.unk1 ) class HardcodedMonsterSpriteDataTable: @classmethod def get(cls, arm9bin: bytes, config: Pmd2Data) -> List[MonsterSpriteDataTableEntry]: """Returns the list.""" block = config.bin_sections.arm9.data.MONSTER_SPRITE_DATA lst = [] for i in range(block.address, block.address + block.length, ENTRY_LEN): lst.append( MonsterSpriteDataTableEntry( read_u8(arm9bin, i + 0x00), read_u8(arm9bin, i + 0x01) ) ) return lst @classmethod def set( cls, value: List[MonsterSpriteDataTableEntry], arm9bin: bytearray, config: Pmd2Data, ) -> None: """ Sets the list. The length of the list must exactly match the original ROM's length (see get). """ block = config.bin_sections.arm9.data.MONSTER_SPRITE_DATA assert block.length is not None expected_length = int(block.length / ENTRY_LEN) if len(value) != expected_length: raise ValueError( f"The list must have exactly the length of {expected_length} entries." ) for i, entry in enumerate(value): arm9bin[ block.address + (i * ENTRY_LEN) : block.address + ((i + 1) * ENTRY_LEN) ] = entry.METHOD_NAME() class IdleAnimType(Enum): STAND_LOOP = 0x00, _("Standing Animation (loop)") STAND_FRZ = 0x01, _("Standing Animation (1st frame)") SPECIAL = 0x02, _("Special") WALK_FRZ = 0x03, _("Walking Animation (1st frame)") def __new__(cls, *args, **kwargs): # type: ignore obj = object.__new__(cls) obj._value_ = args[0] return obj # ignore the first param since it's already set by __new__ def __init__(self, _: int, print_name: str): self.print_name = print_name class HardcodedMonsterGroundIdleAnimTable: @classmethod def get(cls, ov11bin: bytes, config: Pmd2Data) -> List[IdleAnimType]: """Returns the list.""" block = config.extra_bin_sections.overlay11.data.MONSTER_GROUND_IDLE_ANIM lst_i = list(ov11bin[block.address : block.address + block.length]) lst = [IdleAnimType(x) for x in lst_i] # type: ignore return lst @classmethod def set( cls, values: List[IdleAnimType], ov11bin: bytearray, config: Pmd2Data ) -> None: """ Sets the list. The length of the list must exactly match the original ROM's length (see get). """ block = config.extra_bin_sections.overlay11.data.MONSTER_GROUND_IDLE_ANIM assert block.length is not None expected_length = block.length if len(values) != expected_length: raise ValueError( f"The list must have exactly the length of {expected_length} entries." ) ov11bin[block.address : block.address + block.length] = bytes( [x.value for x in values] )
3,610
build xyz
# bluemira is an integrated inter-disciplinary design tool for future fusion # reactors. It incorporates several modules, some of which rely on other # codes, to carry out a range of typical conceptual fusion reactor design # activities. # # Copyright (C) 2021-2023 M. Coleman, J. Cook, F. Franza, I.A. Maione, S. McIntosh, # J. Morris, D. Short # # bluemira is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # bluemira is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with bluemira; if not, see <https://www.gnu.org/licenses/>. """ Builder for the PF coils """ from dataclasses import dataclass from typing import Dict, List, Union from bluemira.base.builder import Builder from bluemira.base.components import Component, PhysicalComponent from bluemira.base.designer import Designer from bluemira.base.parameter_frame import Parameter, ParameterFrame from bluemira.builders.tools import apply_component_display_options, get_n_sectors from bluemira.display.palettes import BLUE_PALETTE from bluemira.equilibria.coils import Coil from bluemira.geometry.face import BluemiraFace from bluemira.geometry.parameterisations import PictureFrame from bluemira.geometry.tools import make_circle, offset_wire, revolve_shape from bluemira.geometry.wire import BluemiraWire @dataclass class PFCoilBuilderParams(ParameterFrame): """ Parameters for the `PFCoilBuilder` class. """ n_TF: Parameter[int] tk_insulation: Parameter[float] tk_casing: Parameter[float] ctype: Parameter[str] class PFCoilBuilder(Builder): """ Builder for a single PF coil. """ CASING = "Casing" GROUND_INSULATION = "Ground Insulation" INNER = "Inner" OUTER_INS = "Outer Ins" WINDING_PACK = "Winding Pack" param_cls = PFCoilBuilderParams def __init__( self, params: Union[PFCoilBuilderParams, Dict], build_config: Dict, xz_cross_section: BluemiraWire, ): super().__init__(params, build_config, verbose=False) self.xz_cross_section = xz_cross_section def build(self) -> Component: """ Build the PFCoil component. """ return self.component_tree( xz=self.build_xz(self.xz_cross_section), xy=self.build_xy(self.xz_cross_section), xyz=self.METHOD_NAME(self.xz_cross_section, degree=0), ) def build_xy(self, shape: BluemiraWire) -> List[PhysicalComponent]: """ Build the xy cross-section of the PF coil. """ r_in = shape.bounding_box.x_min r_out = shape.bounding_box.x_max c1 = make_circle(r_out) c2 = make_circle(r_in) wp = PhysicalComponent(self.WINDING_PACK, BluemiraFace([c1, c2])) idx = 0 if self.params.ctype.value == "CS" else 1 apply_component_display_options(wp, color=BLUE_PALETTE["PF"][idx]) r_in -= self.params.tk_insulation.value c3 = make_circle(r_in) inner_ins = PhysicalComponent(self.INNER, BluemiraFace([c2, c3])) apply_component_display_options(inner_ins, color=BLUE_PALETTE["PF"][3]) r_out += self.params.tk_insulation.value c4 = make_circle(r_out) outer_ins = PhysicalComponent(self.OUTER_INS, BluemiraFace([c4, c1])) apply_component_display_options(outer_ins, color=BLUE_PALETTE["PF"][3]) ins = Component(name=self.GROUND_INSULATION, children=[inner_ins, outer_ins]) r_in -= self.params.tk_casing.value c5 = make_circle(r_in) inner_cas = PhysicalComponent(self.INNER, BluemiraFace([c3, c5])) apply_component_display_options(inner_cas, color=BLUE_PALETTE["PF"][2]) r_out += self.params.tk_casing.value c6 = make_circle(r_out) outer_cas = PhysicalComponent(self.OUTER_INS, BluemiraFace([c6, c4])) apply_component_display_options(outer_cas, color=BLUE_PALETTE["PF"][2]) casing = Component(self.CASING, children=[inner_cas, outer_cas]) return [wp, ins, casing] def build_xz(self, shape: BluemiraWire) -> List[PhysicalComponent]: """ Build the xz cross-section of the PF coil. """ wp = PhysicalComponent(self.WINDING_PACK, BluemiraFace(shape)) idx = 0 if self.params.ctype.value == "CS" else 1 apply_component_display_options(wp, color=BLUE_PALETTE["PF"][idx]) ins_shape = offset_wire(shape, self.params.tk_insulation.value) ins = PhysicalComponent(self.GROUND_INSULATION, BluemiraFace([ins_shape, shape])) apply_component_display_options(ins, color=BLUE_PALETTE["PF"][3]) cas_shape = offset_wire(ins_shape, self.params.tk_casing.value) casing = PhysicalComponent(self.CASING, BluemiraFace([cas_shape, ins_shape])) apply_component_display_options(casing, color=BLUE_PALETTE["PF"][2]) return [wp, ins, casing] def METHOD_NAME( self, shape: BluemiraWire, degree: float = 360.0, ) -> List[PhysicalComponent]: """ Build the xyz representation of the PF coil. Parameters ---------- shape: The xz cross-section shape of the coil. degree: The angle [°] around which to build the components, by default 360.0. Returns ------- The component grouping the results in 3D (xyz). """ sector_degree, n_sectors = get_n_sectors(self.params.n_TF.value, degree) # I doubt this is floating-point safe to collisions... xz_components = self.build_xz(shape) components = [] for c in xz_components: shape = revolve_shape(c.shape, degree=sector_degree * n_sectors) c_xyz = PhysicalComponent(c.name, shape) apply_component_display_options( c_xyz, color=c.plot_options.face_options["color"] ) components.append(c_xyz) return components @dataclass class PFCoilPictureFrameParams(ParameterFrame): """ Parameters for the `PFCoilPictureFrame` designer. """ r_corner: Parameter[float] class PFCoilPictureFrame(Designer): """ Designer for the shape of a PF coil in the xz plane using a PictureFrame parameterisation. """ param_cls = PFCoilPictureFrameParams def __init__(self, params: Union[PFCoilPictureFrameParams, Dict], coil: Coil): super().__init__(params, verbose=False) self.coil = coil def run(self) -> BluemiraWire: """ Run the design step, outputting the PictureFrame shape as a wire. """ x_in = self.coil.x - self.coil.dx x_out = self.coil.x + self.coil.dx z_up = self.coil.z + self.coil.dz z_down = self.coil.z - self.coil.dz return PictureFrame( { "x1": {"value": x_in, "fixed": True}, "x2": {"value": x_out, "fixed": True}, "z1": {"value": z_up, "fixed": True}, "z2": {"value": z_down, "fixed": True}, "ri": {"value": self.params.r_corner.value, "fixed": True}, "ro": {"value": self.params.r_corner.value, "fixed": True}, } ).create_shape()
3,611
is port
# -*- coding: UTF-8 -*- ################################################################################# # The Institute for the Design of Advanced Energy Systems Integrated Platform # Framework (IDAES IP) was produced under the DOE Institute for the # Design of Advanced Energy Systems (IDAES). # # Copyright (c) 2018-2023 by the software owners: The Regents of the # University of California, through Lawrence Berkeley National Laboratory, # National Technology & Engineering Solutions of Sandia, LLC, Carnegie Mellon # University, West Virginia University Research Corporation, et al. # All rights reserved. Please see the files COPYRIGHT.md and LICENSE.md # for full copyright and license information. ################################################################################# """ This module contains utility functions useful for validating arguments to IDAES modeling classes. These functions are primarily designed to be used as the `domain` argument in ConfigBlocks. """ __author__ = "Andrew Lee" from pyomo.common.config import Bool from pyomo.environ import Set from pyomo.dae import ContinuousSet from pyomo.network import Port from idaes.core import useDefault from idaes.core.util.exceptions import ConfigurationError import idaes.logger as idaeslog _log = idaeslog.getLogger(__name__) def is_physical_parameter_block(val): """Domain validator for property package attributes Args: val : value to be checked Returns: ConfigurationError if val is not an instance of PhysicalParameterBlock or useDefault """ # Top-level import creates circular import # pylint: disable=import-outside-toplevel from idaes.core.base.property_base import PhysicalParameterBlock if isinstance(val, PhysicalParameterBlock) or val == useDefault: return val else: _log.error( f"Property package argument {val} should == useDefault or " f"be an instance of PhysicalParameterBlock" ) raise ConfigurationError( """Property package argument should be an instance of a PhysicalParameterBlock or useDefault""" ) def is_reaction_parameter_block(val): """Domain validator for reaction package attributes Args: val : value to be checked Returns: ConfigurationError if val is not an instance of ReactionParameterBlock """ # Top-level import creates circular import # pylint: disable=import-outside-toplevel from idaes.core.base.reaction_base import ReactionParameterBlock if isinstance(val, ReactionParameterBlock): return val else: raise ConfigurationError( """Reaction package argument should be an instance of a ReactionParameterBlock""" ) def is_state_block(val): """Domain validator for state block as an argument Args: val : value to be checked Returns: ConfigurationError if val is not an instance of StateBlock or None """ # Top-level import creates circular import # pylint: disable=import-outside-toplevel from idaes.core.base.property_base import StateBlock if isinstance(val, StateBlock) or val is None: return val else: raise ConfigurationError( """State block should be an instance of a StateBlock or None""" ) def METHOD_NAME(arg): """Domain validator for ports Args: arg : argument to be checked as a Port Returns: Port object or Exception """ if not isinstance(arg, Port): raise ConfigurationError( "Invalid argument type. Expected an instance " "of a Pyomo Port object" ) return arg def is_time_domain(arg): """Domain validator for time domains Args: arg : argument to be checked as a time domain (i.e. Set or ContinuousSet) Returns: Set, ContinuousSet or Exception """ if not isinstance(arg, (Set, ContinuousSet)): raise ConfigurationError( "Invalid argument type. Expected an instance " "of a Pyomo Set or ContinuousSet object" ) return arg def is_transformation_method(arg): """Domain validator for transformation methods Args: arg : argument to be checked for membership in recognized strings Returns: Recognised string or Exception """ if arg in ["dae.finite_difference", "dae.collocation"]: return arg else: raise ConfigurationError( "Invalid value provided for transformation_method. " "Please check the value and spelling of the argument provided." ) def is_transformation_scheme(arg): """Domain validator for transformation scheme Args: arg : argument to be checked for membership in recognized strings Returns: Recognised string or Exception """ if arg in ["BACKWARD", "FORWARD", "LAGRANGE-RADAU", "LAGRANGE-LEGENDRE"]: return arg else: raise ConfigurationError( "Invalid value provided for transformation_scheme. " "Please check the value and spelling of the argument provided." ) def DefaultBool(arg): """ Domain validator for bool-like arguments with a 'use default' option. Relies on Pyomo's Bool() validator for identifying bool-like arguments. Args: arg : argument to be validated. Returns: A bool or useDefault Raises: ValueError if arg is not bool-like or useDefault """ if arg == useDefault: return arg else: return Bool(arg)
3,612
test encode output
import pytest from typing import Any from mlserver.codecs import Base64Codec from mlserver.types import RequestInput, ResponseOutput, Parameters @pytest.mark.parametrize( "payload, expected", [ ([b"Python is fun", b"foo"], True), ([b"Python is fun", "foo"], False), (b"Python is fun", False), ("foo", False), ], ) def test_can_encode(payload: Any, expected: bool): assert Base64Codec.can_encode(payload) == expected @pytest.mark.parametrize( "decoded, use_bytes, expected", [ ( # List with a single binary string [b"Python is fun"], True, ResponseOutput( name="foo", shape=[1, 1], datatype="BYTES", data=[b"UHl0aG9uIGlzIGZ1bg=="], parameters=Parameters(content_type=Base64Codec.ContentType), ), ), ( # List with a single (non-binary) string ["Python is fun"], True, ResponseOutput( name="foo", shape=[1, 1], datatype="BYTES", data=[b"UHl0aG9uIGlzIGZ1bg=="], parameters=Parameters(content_type=Base64Codec.ContentType), ), ), ( # List with two binary strings [b"Python is fun", b"Python is fun"], True, ResponseOutput( name="foo", shape=[2, 1], datatype="BYTES", data=[b"UHl0aG9uIGlzIGZ1bg==", b"UHl0aG9uIGlzIGZ1bg=="], parameters=Parameters(content_type=Base64Codec.ContentType), ), ), ( # List with two binary strings, outputting strings (i.e. not bytes) [b"Python is fun", b"Python is fun"], False, ResponseOutput( name="foo", shape=[2, 1], datatype="BYTES", data=["UHl0aG9uIGlzIGZ1bg==", "UHl0aG9uIGlzIGZ1bg=="], parameters=Parameters(content_type=Base64Codec.ContentType), ), ), ], ) def METHOD_NAME(decoded, use_bytes, expected): response_output = Base64Codec.encode_output( name="foo", payload=decoded, use_bytes=use_bytes ) assert expected == response_output @pytest.mark.parametrize( "encoded, expected", [ ( # Single base64-encoded binary string ResponseOutput( name="foo", shape=[1, 1], datatype="BYTES", data="UHl0aG9uIGlzIGZ1bg==", ), [b"Python is fun"], ), ( # Single (non-base64-encoded) binary string ResponseOutput( name="foo", shape=[1, 1], datatype="BYTES", data=b"Python is fun", ), [b"Python is fun"], ), ( # Single (non-base64-encoded) (non-binary) string ResponseOutput( name="foo", shape=[1, 1], datatype="BYTES", data="Python is fun", ), [b"Python is fun"], ), ( # Multiple base64-encoded binary strings ResponseOutput( name="foo", shape=[2, 1], datatype="BYTES", data=[b"UHl0aG9uIGlzIGZ1bg==", b"UHl0aG9uIGlzIGZ1bg=="], ), [b"Python is fun", b"Python is fun"], ), ], ) def test_decode_output(encoded, expected): decoded_output = Base64Codec.decode_output(encoded) assert expected == decoded_output @pytest.mark.parametrize( "decoded, use_bytes, expected", [ ( # List with a single binary string [b"Python is fun"], True, RequestInput( name="foo", shape=[1, 1], datatype="BYTES", data=[b"UHl0aG9uIGlzIGZ1bg=="], parameters=Parameters(content_type=Base64Codec.ContentType), ), ), ( # List with a single (non-binary) string ["Python is fun"], True, RequestInput( name="foo", shape=[1, 1], datatype="BYTES", data=[b"UHl0aG9uIGlzIGZ1bg=="], parameters=Parameters(content_type=Base64Codec.ContentType), ), ), ( # List with two binary strings [b"Python is fun", b"Python is fun"], True, RequestInput( name="foo", shape=[2, 1], datatype="BYTES", data=[b"UHl0aG9uIGlzIGZ1bg==", b"UHl0aG9uIGlzIGZ1bg=="], parameters=Parameters(content_type=Base64Codec.ContentType), ), ), ( # List with two binary strings, not using bytes [b"Python is fun", b"Python is fun"], False, RequestInput( name="foo", shape=[2, 1], datatype="BYTES", data=["UHl0aG9uIGlzIGZ1bg==", "UHl0aG9uIGlzIGZ1bg=="], parameters=Parameters(content_type=Base64Codec.ContentType), ), ), ], ) def test_encode_input(decoded, use_bytes, expected): request_input = Base64Codec.encode_input( name="foo", payload=decoded, use_bytes=use_bytes ) assert expected == request_input @pytest.mark.parametrize( "encoded, expected", [ ( # Single base64-encoded binary string RequestInput( name="foo", shape=[1, 1], datatype="BYTES", data="UHl0aG9uIGlzIGZ1bg==", ), [b"Python is fun"], ), ( # Single (non-base64-encoded) binary string RequestInput( name="foo", shape=[1, 1], datatype="BYTES", data=b"Python is fun", ), [b"Python is fun"], ), ( # Single (non-base64-encoded) (non-binary) string RequestInput( name="foo", shape=[1, 1], datatype="BYTES", data="Python is fun", ), [b"Python is fun"], ), ( # Multiple base64-encoded binary strings RequestInput( name="foo", shape=[2, 1], datatype="BYTES", data=[b"UHl0aG9uIGlzIGZ1bg==", b"UHl0aG9uIGlzIGZ1bg=="], ), [b"Python is fun", b"Python is fun"], ), ], ) def test_decode_input(encoded, expected): decoded_input = Base64Codec.decode_input(encoded) assert expected == decoded_input
3,613
is sink
from abc import ABC, abstractmethod from copy import deepcopy from typing import Any, List import torch from torch.fx import Graph, Node from colossalai.auto_parallel.passes.runtime_apply_pass import ( runtime_apply, runtime_apply_for_iterable_object, runtime_comm_spec_apply, ) from colossalai.fx.codegen.activation_checkpoint_codegen import ActivationCheckpointCodeGen __all___ = ['CheckpointSolverBase'] def _copy_output(src: Graph, dst: Graph): """Copy the output node from src to dst""" for n_src, n_dst in zip(src.nodes, dst.nodes): if n_src.op == 'output': n_dst.meta = n_src.meta def _get_param_size(module: torch.nn.Module): """Get the size of the parameters in the module""" return sum([p.numel() * torch.tensor([], dtype=p.dtype).element_size() for p in module.parameters()]) class CheckpointSolverBase(ABC): def __init__( self, graph: Graph, free_memory: float = -1.0, requires_linearize: bool = False, cnode: List[str] = None, optim_multiplier: float = 1.0, ): """``CheckpointSolverBase`` class will integrate information provided by the components and use an existing solver to find a possible optimal strategies combination for target computing graph. Existing Solvers: Chen's Greedy solver: https://arxiv.org/abs/1604.06174 (CheckpointSolverChen) Rotor solver: https://hal.inria.fr/hal-02352969 (CheckpointSolverRotor) Args: graph (Graph): The computing graph to be optimized. free_memory (float): Memory constraint for the solution. requires_linearize (bool): Whether the graph needs to be linearized. cnode (List[str], optional): Common node List, should be the subset of input. Default to None. optim_multiplier (float, optional): The multiplier of extra weight storage for the ``torch.optim.Optimizer``. Default to 1.0. Warnings: Meta information of the graph is required for any ``CheckpointSolver``. """ # super-dainiu: this graph is a temporary graph which can refer to # the owning module, but we will return another deepcopy of it after # the solver is executed. self.graph = deepcopy(graph) self.graph.owning_module = graph.owning_module _copy_output(graph, self.graph) self.graph.set_codegen(ActivationCheckpointCodeGen()) # check if has meta information if any(len(node.meta) == 0 for node in self.graph.nodes): raise RuntimeError( "Nodes meta information hasn't been prepared! Please extract from graph before constructing the solver!" ) # parameter memory = parameter size + optimizer extra weight storage self.free_memory = free_memory - _get_param_size(self.graph.owning_module) * (optim_multiplier + 1) self.cnode = cnode self.requires_linearize = requires_linearize if self.requires_linearize: self.node_list = self._linearize_graph() else: self.node_list = self.get_node_list() @abstractmethod def solve(self): """Solve the checkpointing problem and return the solution. """ pass def get_node_list(self): """Get the node list. """ return [[node] for node in self.graph.nodes] def _linearize_graph(self) -> List[List[Node]]: """Linearizing the graph Args: graph (Graph): The computing graph to be optimized. Returns: List[List[Node]]: List of list, each inside list of Node presents the actual 'node' in linearized manner. Remarks: Do merge the inplace ops and shape-consistency ops into the previous node. """ # Common nodes are type of nodes that could be seen as attributes and remain # unchanged throughout the whole model, it will be used several times by # different blocks of model, so that it is hard for us to linearize the graph # when we encounter those kinds of nodes. We let users to annotate some of the # input as common node, such as attention mask, and the followings are some of # the ops that could actually be seen as common nodes. With our common node prop, # we could find some of the "real" common nodes (e.g. the real attention mask # used in BERT and GPT), the rule is simple, for node who's parents are all common # nodes or it's op belongs to the following operations, we view this node as a # newly born common node. # List of target name that could be seen as common node common_ops = ["getattr", "getitem", "size"] def _is_cop(target: Any) -> bool: """Check if an op could be seen as common node Args: target (Any): node target Returns: bool """ if isinstance(target, str): return target in common_ops else: return target.__name__ in common_ops def METHOD_NAME() -> bool: """Check if we can free all dependencies Returns: bool """ def _is_inplace(n: Node): """Get the inplace argument from ``torch.fx.Node`` """ inplace = False if n.op == "call_function": inplace = n.kwargs.get("inplace", False) elif n.op == "call_module": inplace = getattr(n.graph.owning_module.get_submodule(n.target), "inplace", False) return inplace def _is_shape_consistency(n: Node): """Check if this node is shape-consistency node (i.e. ``runtime_apply`` or ``runtime_apply_for_iterable_object``) """ return n.target in [runtime_apply, runtime_apply_for_iterable_object, runtime_comm_spec_apply] return not sum([v for _, v in deps.items()]) and not any(map(_is_inplace, n.users)) and not any( map(_is_shape_consistency, n.users)) # make sure that item in cnode is valid if self.cnode: for name in self.cnode: try: assert next(node for node in self.graph.nodes if node.name == name).op == "placeholder", \ f"Common node {name} is not an input of the model." except StopIteration: raise ValueError(f"Common node name {name} not in graph.") else: self.cnode = [] deps = {} node_list = [] region = [] for n in self.graph.nodes: if n.op != "placeholder" and n.op != "output": for n_par in n.all_input_nodes: if n_par.op != "placeholder" and n_par.name not in self.cnode: deps[n_par] -= 1 region.append(n) # if the node could free all dependencies in graph # we could begin a new node if METHOD_NAME(): node_list.append(region) region = [] # propagate common node attr if possible if len(n.all_input_nodes) == len([node for node in n.all_input_nodes if node.name in self.cnode ]) or _is_cop(n.target): self.cnode.append(n.name) else: deps[n] = len([user for user in n.users if user.op != "output"]) return node_list
3,614
get projects
from __future__ import annotations from typing import Any, Iterable, Mapping, MutableMapping, Sequence from sentry_relay.processing import parse_release from sentry.models import Activity, Commit, OrganizationMember, Project from sentry.models.commitfilechange import CommitFileChange from sentry.notifications.types import NotificationSettingTypes from sentry.notifications.utils import ( get_deploy, get_environment_for_deploy, get_group_counts_by_project, get_release, get_repos, ) from sentry.notifications.utils.actions import MessageAction from sentry.notifications.utils.participants import ParticipantMap, get_participants_for_release from sentry.services.hybrid_cloud.actor import ActorType, RpcActor from sentry.services.hybrid_cloud.user.service import user_service from sentry.types.integrations import ExternalProviders from .base import ActivityNotification class ReleaseActivityNotification(ActivityNotification): metrics_key = "release_activity" notification_setting_type = NotificationSettingTypes.DEPLOY template_path = "sentry/emails/activity/release" def __init__(self, activity: Activity) -> None: super().__init__(activity) self.group = None self.user_id_team_lookup: Mapping[int, list[int]] | None = None self.deploy = get_deploy(activity) self.release = get_release(activity, self.organization) if not self.release: self.email_list: set[str] = set() self.repos: Iterable[Mapping[str, Any]] = set() self.projects: set[Project] = set() self.version = "unknown" self.version_parsed = self.version self.user_ids = set() return self.projects = set(self.release.projects.all()) self.commit_list = list(Commit.objects.get_for_release(self.release)) self.email_list = {c.author.email for c in self.commit_list if c.author} users = user_service.get_many_by_email( emails=list(self.email_list), organization_id=self.organization.id, is_verified=True, ) self.user_ids = {u.id for u in users} self.repos = get_repos(self.commit_list, {u.email: u for u in users}, self.organization) self.environment = get_environment_for_deploy(self.deploy) self.group_counts_by_project = get_group_counts_by_project(self.release, self.projects) self.version = self.release.version self.version_parsed = parse_release(self.version)["description"] def get_participants_with_group_subscription_reason(self) -> ParticipantMap: return get_participants_for_release(self.projects, self.organization, self.user_ids) def get_users_by_teams(self) -> Mapping[int, list[int]]: if not self.user_id_team_lookup: lookup: Mapping[int, list[int]] = OrganizationMember.objects.get_teams_by_user( self.organization ) self.user_id_team_lookup = lookup return self.user_id_team_lookup def get_context(self) -> MutableMapping[str, Any]: return { **self.get_base_context(), "author_count": len(self.email_list), "commit_count": len(self.commit_list), "deploy": self.deploy, "environment": self.environment, "file_count": CommitFileChange.objects.get_count_for_commits(self.commit_list), "release": self.release, "repos": self.repos, "setup_repo_link": self.organization.absolute_url( f"/organizations/{self.organization.slug}/repos/" ), "text_description": f"Version {self.version_parsed} was deployed to {self.environment}", "version_parsed": self.version_parsed, } def METHOD_NAME(self, recipient: RpcActor) -> set[Project]: if not self.release: return set() if recipient.actor_type == ActorType.USER: if self.organization.flags.allow_joinleave: return self.projects team_ids = self.get_users_by_teams()[recipient.id] else: team_ids = [recipient.id] projects: set[Project] = Project.objects.get_for_team_ids(team_ids).filter( id__in={p.id for p in self.projects} ) return projects def get_recipient_context( self, recipient: RpcActor, extra_context: Mapping[str, Any] ) -> MutableMapping[str, Any]: projects = self.METHOD_NAME(recipient) release_links = [ self.organization.absolute_url( f"/organizations/{self.organization.slug}/releases/{self.version}/?project={p.id}" ) for p in projects ] resolved_issue_counts = [self.group_counts_by_project.get(p.id, 0) for p in projects] return { **super().get_recipient_context(recipient, extra_context), "projects": list(zip(projects, release_links, resolved_issue_counts)), "project_count": len(projects), } def get_subject(self, context: Mapping[str, Any] | None = None) -> str: return f"Deployed version {self.version_parsed} to {self.environment}" @property def title(self) -> str: return self.get_subject() def get_notification_title( self, provider: ExternalProviders, context: Mapping[str, Any] | None = None ) -> str: projects_text = "" if len(self.projects) == 1: projects_text = " for this project" elif len(self.projects) > 1: projects_text = " for these projects" return f"Release {self.version_parsed} was deployed to {self.environment}{projects_text}" def get_message_actions( self, recipient: RpcActor, provider: ExternalProviders ) -> Sequence[MessageAction]: if self.release: release = get_release(self.activity, self.project.organization) if release: return [ MessageAction( name=project.slug, url=self.organization.absolute_url( f"/organizations/{project.organization.slug}/releases/{release.version}/", query=f"project={project.id}&unselectedSeries=Healthy", ), ) for project in self.release.projects.all() ] return [] def build_attachment_title(self, recipient: RpcActor) -> str: return "" def get_title_link(self, recipient: RpcActor, provider: ExternalProviders) -> str | None: return None def build_notification_footer(self, recipient: RpcActor, provider: ExternalProviders) -> str: settings_url = self.get_settings_url(recipient, provider) # no environment related to a deploy footer = "" if self.release: footer += f"{self.release.projects.all()[0].slug} | " footer += ( f"{self.format_url(text='Notification Settings', url=settings_url, provider=provider)}" ) return footer def send(self) -> None: # Don't create a message when the Activity doesn't have a release and deploy. if bool(self.release and self.deploy): return super().send()
3,615
atanh
import sys from collections.abc import Iterable from typing import Protocol, SupportsFloat, TypeVar, overload from typing_extensions import SupportsIndex, TypeAlias _T = TypeVar("_T") _T_co = TypeVar("_T_co", covariant=True) if sys.version_info >= (3, 8): _SupportsFloatOrIndex: TypeAlias = SupportsFloat | SupportsIndex else: _SupportsFloatOrIndex: TypeAlias = SupportsFloat e: float pi: float inf: float nan: float tau: float def acos(__x: _SupportsFloatOrIndex) -> float: ... def acosh(__x: _SupportsFloatOrIndex) -> float: ... def asin(__x: _SupportsFloatOrIndex) -> float: ... def asinh(__x: _SupportsFloatOrIndex) -> float: ... def atan(__x: _SupportsFloatOrIndex) -> float: ... def atan2(__y: _SupportsFloatOrIndex, __x: _SupportsFloatOrIndex) -> float: ... def METHOD_NAME(__x: _SupportsFloatOrIndex) -> float: ... if sys.version_info >= (3, 11): def cbrt(__x: _SupportsFloatOrIndex) -> float: ... class _SupportsCeil(Protocol[_T_co]): def __ceil__(self) -> _T_co: ... @overload def ceil(__x: _SupportsCeil[_T]) -> _T: ... @overload def ceil(__x: _SupportsFloatOrIndex) -> int: ... if sys.version_info >= (3, 8): def comb(__n: SupportsIndex, __k: SupportsIndex) -> int: ... def copysign(__x: _SupportsFloatOrIndex, __y: _SupportsFloatOrIndex) -> float: ... def cos(__x: _SupportsFloatOrIndex) -> float: ... def cosh(__x: _SupportsFloatOrIndex) -> float: ... def degrees(__x: _SupportsFloatOrIndex) -> float: ... if sys.version_info >= (3, 8): def dist(__p: Iterable[_SupportsFloatOrIndex], __q: Iterable[_SupportsFloatOrIndex]) -> float: ... def erf(__x: _SupportsFloatOrIndex) -> float: ... def erfc(__x: _SupportsFloatOrIndex) -> float: ... def exp(__x: _SupportsFloatOrIndex) -> float: ... if sys.version_info >= (3, 11): def exp2(__x: _SupportsFloatOrIndex) -> float: ... def expm1(__x: _SupportsFloatOrIndex) -> float: ... def fabs(__x: _SupportsFloatOrIndex) -> float: ... if sys.version_info >= (3, 8): def factorial(__x: SupportsIndex) -> int: ... else: def factorial(__x: int) -> int: ... class _SupportsFloor(Protocol[_T_co]): def __floor__(self) -> _T_co: ... @overload def floor(__x: _SupportsFloor[_T]) -> _T: ... @overload def floor(__x: _SupportsFloatOrIndex) -> int: ... def fmod(__x: _SupportsFloatOrIndex, __y: _SupportsFloatOrIndex) -> float: ... def frexp(__x: _SupportsFloatOrIndex) -> tuple[float, int]: ... def fsum(__seq: Iterable[_SupportsFloatOrIndex]) -> float: ... def gamma(__x: _SupportsFloatOrIndex) -> float: ... if sys.version_info >= (3, 9): def gcd(*integers: SupportsIndex) -> int: ... else: def gcd(__x: SupportsIndex, __y: SupportsIndex) -> int: ... if sys.version_info >= (3, 8): def hypot(*coordinates: _SupportsFloatOrIndex) -> float: ... else: def hypot(__x: _SupportsFloatOrIndex, __y: _SupportsFloatOrIndex) -> float: ... def isclose( a: _SupportsFloatOrIndex, b: _SupportsFloatOrIndex, *, rel_tol: _SupportsFloatOrIndex = 1e-09, abs_tol: _SupportsFloatOrIndex = 0.0, ) -> bool: ... def isinf(__x: _SupportsFloatOrIndex) -> bool: ... def isfinite(__x: _SupportsFloatOrIndex) -> bool: ... def isnan(__x: _SupportsFloatOrIndex) -> bool: ... if sys.version_info >= (3, 8): def isqrt(__n: SupportsIndex) -> int: ... if sys.version_info >= (3, 9): def lcm(*integers: SupportsIndex) -> int: ... def ldexp(__x: _SupportsFloatOrIndex, __i: int) -> float: ... def lgamma(__x: _SupportsFloatOrIndex) -> float: ... def log(x: _SupportsFloatOrIndex, base: _SupportsFloatOrIndex = ...) -> float: ... def log10(__x: _SupportsFloatOrIndex) -> float: ... def log1p(__x: _SupportsFloatOrIndex) -> float: ... def log2(__x: _SupportsFloatOrIndex) -> float: ... def modf(__x: _SupportsFloatOrIndex) -> tuple[float, float]: ... if sys.version_info >= (3, 12): def nextafter(__x: _SupportsFloatOrIndex, __y: _SupportsFloatOrIndex, *, steps: SupportsIndex | None = None) -> float: ... elif sys.version_info >= (3, 9): def nextafter(__x: _SupportsFloatOrIndex, __y: _SupportsFloatOrIndex) -> float: ... if sys.version_info >= (3, 8): def perm(__n: SupportsIndex, __k: SupportsIndex | None = None) -> int: ... def pow(__x: _SupportsFloatOrIndex, __y: _SupportsFloatOrIndex) -> float: ... if sys.version_info >= (3, 8): @overload def prod(__iterable: Iterable[SupportsIndex], *, start: SupportsIndex = 1) -> int: ... # type: ignore[misc] @overload def prod(__iterable: Iterable[_SupportsFloatOrIndex], *, start: _SupportsFloatOrIndex = 1) -> float: ... def radians(__x: _SupportsFloatOrIndex) -> float: ... def remainder(__x: _SupportsFloatOrIndex, __y: _SupportsFloatOrIndex) -> float: ... def sin(__x: _SupportsFloatOrIndex) -> float: ... def sinh(__x: _SupportsFloatOrIndex) -> float: ... if sys.version_info >= (3, 12): def sumprod(__p: Iterable[float], __q: Iterable[float]) -> float: ... def sqrt(__x: _SupportsFloatOrIndex) -> float: ... def tan(__x: _SupportsFloatOrIndex) -> float: ... def tanh(__x: _SupportsFloatOrIndex) -> float: ... # Is different from `_typeshed.SupportsTrunc`, which is not generic class _SupportsTrunc(Protocol[_T_co]): def __trunc__(self) -> _T_co: ... def trunc(__x: _SupportsTrunc[_T]) -> _T: ... if sys.version_info >= (3, 9): def ulp(__x: _SupportsFloatOrIndex) -> float: ...
3,616
unlock nucypher keystore
import os import click from constant_sorrow.constants import NO_PASSWORD from nucypher.blockchain.eth.decorators import validate_checksum_address from nucypher.cli.literature import ( COLLECT_ETH_PASSWORD, COLLECT_NUCYPHER_PASSWORD, DECRYPTING_CHARACTER_KEYSTORE, GENERIC_PASSWORD_PROMPT, PASSWORD_COLLECTION_NOTICE, ) from nucypher.config.base import CharacterConfiguration from nucypher.config.constants import NUCYPHER_ENVVAR_KEYSTORE_PASSWORD from nucypher.crypto.keystore import _WORD_COUNT, Keystore from nucypher.utilities.emitters import StdoutEmitter def get_password_from_prompt(prompt: str = GENERIC_PASSWORD_PROMPT, envvar: str = None, confirm: bool = False) -> str: """Collect a password interactively, preferring an env var is one is provided and set.""" password = NO_PASSWORD if envvar: password = os.environ.get(envvar, NO_PASSWORD) if password is NO_PASSWORD: # Collect password, prefer env var password = click.prompt(prompt, confirmation_prompt=confirm, hide_input=True) return password @validate_checksum_address def get_client_password(checksum_address: str, envvar: str = None, confirm: bool = False) -> str: """Interactively collect an ethereum client password""" client_password = get_password_from_prompt(prompt=COLLECT_ETH_PASSWORD.format(checksum_address=checksum_address), envvar=envvar, confirm=confirm) return client_password def unlock_signer_account(config: CharacterConfiguration, json_ipc: bool) -> None: # TODO: Remove this block after deprecating 'operator_address' from nucypher.config.characters import UrsulaConfiguration if isinstance(config, UrsulaConfiguration): account = config.operator_address else: account = config.checksum_address eth_password_is_needed = ( not config.signer.is_device(account=account) and not config.dev_mode ) __password = None if eth_password_is_needed: if json_ipc and not os.environ.get(config.SIGNER_ENVVAR): raise ValueError(f'{config.SIGNER_ENVVAR} is required to use JSON IPC mode.') __password = get_client_password(checksum_address=account, envvar=config.SIGNER_ENVVAR) config.signer.unlock_account(account=config.checksum_address, password=__password) def get_nucypher_password(emitter, confirm: bool = False, envvar=NUCYPHER_ENVVAR_KEYSTORE_PASSWORD) -> str: """Interactively collect a nucypher password""" prompt = COLLECT_NUCYPHER_PASSWORD if confirm: emitter.message(PASSWORD_COLLECTION_NOTICE) prompt += f" ({Keystore._MINIMUM_PASSWORD_LENGTH} character minimum)" keystore_password = get_password_from_prompt(prompt=prompt, confirm=confirm, envvar=envvar) return keystore_password def METHOD_NAME(emitter: StdoutEmitter, password: str, character_configuration: CharacterConfiguration) -> bool: """Unlocks a nucypher keystore and attaches it to the supplied configuration if successful.""" emitter.message(DECRYPTING_CHARACTER_KEYSTORE.format(name=character_configuration.NAME.capitalize()), color='yellow') # precondition if character_configuration.dev_mode: return True # Dev accounts are always unlocked # unlock character_configuration.keystore.unlock(password=password) # Takes ~3 seconds, ~1GB Ram return True def recover_keystore(emitter) -> None: emitter.message('This procedure will recover your nucypher keystore from mnemonic seed words. ' 'You will need to provide the entire mnemonic (space seperated) in the correct ' 'order and choose a new password.', color='cyan') click.confirm('Do you want to continue', abort=True) __words = click.prompt("Enter nucypher keystore seed words") word_count = len(__words.split()) if word_count != _WORD_COUNT: emitter.message(f'Invalid mnemonic - Number of words must be {str(_WORD_COUNT)}, but only got {word_count}') __password = get_nucypher_password(emitter=emitter, confirm=True) keystore = Keystore.restore(words=__words, password=__password) emitter.message(f'Recovered nucypher keystore {keystore.id} to \n {keystore.keystore_path}', color='green')
3,617
data dir
"""Fixtures for the CircleCI tests.""" import base64 import os import pytest def pytest_addoption(parser): """Collect pytest parameters for running tests.""" parser.addoption( "--working_dir", action="store", default=( "/usr/local/miniconda/lib/python3.8/site-packages/xcp_d/xcp_d/tests/data/test_data/" "run_pytests/work" ), ) parser.addoption( "--data_dir", action="store", default=( "/usr/local/miniconda/lib/python3.8/site-packages/xcp_d/xcp_d/tests/data/test_data" ), ) parser.addoption( "--output_dir", action="store", default=( "/usr/local/miniconda/lib/python3.8/site-packages/xcp_d/xcp_d/tests/data/test_data/" "run_pytests/out" ), ) # Set up the commandline options as fixtures @pytest.fixture(scope="session") def METHOD_NAME(request): """Grab data directory.""" return request.config.getoption("--data_dir") @pytest.fixture(scope="session") def working_dir(request): """Grab working directory.""" workdir = request.config.getoption("--working_dir") os.makedirs(workdir, exist_ok=True) return workdir @pytest.fixture(scope="session") def output_dir(request): """Grab output directory.""" outdir = request.config.getoption("--output_dir") os.makedirs(outdir, exist_ok=True) return outdir @pytest.fixture(scope="session") def datasets(METHOD_NAME): """Locate downloaded datasets.""" dsets = {} dsets["ds001419"] = os.path.join(METHOD_NAME, "ds001419-fmriprep") dsets["pnc"] = os.path.join(METHOD_NAME, "pnc") dsets["nibabies"] = os.path.join(METHOD_NAME, "nibabies/derivatives/nibabies") dsets["fmriprep_without_freesurfer"] = os.path.join( METHOD_NAME, "fmriprepwithoutfreesurfer", ) return dsets @pytest.fixture(scope="session") def ds001419_data(datasets): """Collect a list of files from ds001419 that will be used by misc. tests.""" subj_dir = os.path.join(datasets["ds001419"], "sub-01") func_dir = os.path.join(subj_dir, "func") anat_dir = os.path.join(subj_dir, "anat") if not os.path.isdir(subj_dir): raise Exception(os.listdir(datasets["ds001419"])) files = {} files["nifti_file"] = os.path.join( func_dir, "sub-01_task-rest_space-MNI152NLin2009cAsym_res-2_desc-preproc_bold.nii.gz", ) files["cifti_file"] = os.path.join( func_dir, "sub-01_task-rest_space-fsLR_den-91k_bold.dtseries.nii", ) files["gifti_file"] = os.path.join( func_dir, "sub-01_task-rest_hemi-L_space-fsaverage5_bold.func.gii", ) files["brain_mask_file"] = os.path.join( func_dir, "sub-01_task-rest_space-MNI152NLin2009cAsym_res-2_desc-brain_mask.nii.gz", ) files["confounds_file"] = os.path.join( func_dir, "sub-01_task-rest_desc-confounds_timeseries.tsv", ) files["confounds_json"] = os.path.join( func_dir, "sub-01_task-rest_desc-confounds_timeseries.json", ) files["anat_to_template_xfm"] = os.path.join( anat_dir, "sub-01_from-T1w_to-MNI152NLin2009cAsym_mode-image_xfm.h5", ) files["template_to_anat_xfm"] = os.path.join( anat_dir, "sub-01_from-MNI152NLin2009cAsym_to-T1w_mode-image_xfm.h5", ) files["anat_to_native_xfm"] = os.path.join( func_dir, "sub-01_task-rest_from-T1w_to-scanner_mode-image_xfm.txt", ) files["boldref"] = os.path.join( func_dir, "sub-01_task-rest_space-MNI152NLin2009cAsym_res-2_boldref.nii.gz", ) files["boldref_t1w"] = os.path.join(func_dir, "sub-01_task-rest_space-T1w_boldref.nii.gz") files["t1w"] = os.path.join(anat_dir, "sub-01_desc-preproc_T1w.nii.gz") files["t1w_mni"] = os.path.join( anat_dir, "sub-01_space-MNI152NLin2009cAsym_res-2_desc-preproc_T1w.nii.gz", ) files["anat_dseg"] = os.path.join(anat_dir, "sub-01_desc-aseg_dseg.nii.gz") return files @pytest.fixture(scope="session") def pnc_data(datasets): """Collect a list of files from pnc that will be used by misc. tests.""" subj_dir = os.path.join(datasets["pnc"], "sub-1648798153", "ses-PNC1") func_dir = os.path.join(subj_dir, "func") anat_dir = os.path.join(subj_dir, "anat") files = {} files["nifti_file"] = os.path.join( func_dir, ( "sub-1648798153_ses-PNC1_task-rest_acq-singleband_space-MNI152NLin6Asym_res-2_" "desc-preproc_bold.nii.gz" ), ) files["cifti_file"] = os.path.join( func_dir, "sub-1648798153_ses-PNC1_task-rest_acq-singleband_space-fsLR_den-91k_bold.dtseries.nii", ) files["brain_mask_file"] = os.path.join( func_dir, "sub-1648798153_task-rest_space-MNI152NLin2009cAsym_res-2_desc-brain_mask.nii.gz", ) files["confounds_file"] = os.path.join( func_dir, "sub-1648798153_task-rest_desc-confounds_timeseries.tsv", ) files["confounds_json"] = os.path.join( func_dir, "sub-1648798153_task-rest_desc-confounds_timeseries.json", ) files["anat_to_template_xfm"] = os.path.join( anat_dir, "sub-1648798153_from-T1w_to-MNI152NLin2009cAsym_mode-image_xfm.h5", ) files["template_to_anat_xfm"] = os.path.join( anat_dir, "sub-1648798153_from-MNI152NLin2009cAsym_to-T1w_mode-image_xfm.h5", ) files["anat_to_native_xfm"] = os.path.join( func_dir, "sub-1648798153_task-rest_from-T1w_to-scanner_mode-image_xfm.txt", ) files["boldref"] = os.path.join( func_dir, "sub-1648798153_task-rest_space-MNI152NLin2009cAsym_res-2_boldref.nii.gz", ) files["boldref_t1w"] = os.path.join( func_dir, "sub-1648798153_task-rest_space-T1w_boldref.nii.gz", ) files["t1w"] = os.path.join(anat_dir, "sub-1648798153_desc-preproc_T1w.nii.gz") files["t1w_mni"] = os.path.join( anat_dir, "sub-1648798153_space-MNI152NLin2009cAsym_res-2_desc-preproc_T1w.nii.gz", ) files["anat_dseg"] = os.path.join(anat_dir, "sub-1648798153_desc-aseg_dseg.nii.gz") return files @pytest.fixture(scope="session") def fmriprep_without_freesurfer_data(datasets): """Collect a list of fmriprepwithoutfreesurfer files that will be used by misc. tests.""" subj_dir = os.path.join(datasets["fmriprep_without_freesurfer"], "sub-01") func_dir = os.path.join(subj_dir, "func") files = {} files["nifti_file"] = os.path.join( func_dir, "sub-01_task-mixedgamblestask_run-1_space-MNI152NLin2009cAsym_desc-preproc_bold.nii.gz", ) files["brain_mask_file"] = os.path.join( func_dir, "sub-01_task-mixedgamblestask_run-1_space-MNI152NLin2009cAsym_desc-brain_mask.nii.gz", ) files["confounds_file"] = os.path.join( func_dir, "sub-01_task-mixedgamblestask_run-1_desc-confounds_timeseries.tsv", ) files["boldref"] = os.path.join( func_dir, "sub-01_task-mixedgamblestask_run-1_space-MNI152NLin2009cAsym_boldref.nii.gz", ) return files @pytest.fixture(scope="session", autouse=True) def fslicense(working_dir): """Set the FreeSurfer license as an environment variable.""" FS_LICENSE = os.path.join(working_dir, "license.txt") os.environ["FS_LICENSE"] = FS_LICENSE LICENSE_CODE = ( "bWF0dGhldy5jaWVzbGFrQHBzeWNoLnVjc2IuZWR1CjIwNzA2CipDZmVWZEg1VVQ4clkKRlNCWVouVWtlVElDdwo=" ) with open(FS_LICENSE, "w") as f: f.write(base64.b64decode(LICENSE_CODE).decode())
3,618
deactivate document
"""Base utilities for COM applications like Word, Excel, Outlook.""" import atexit import logging import platform import struct from contextlib import contextmanager from pathlib import Path if platform.system() == "Windows": import win32api import win32com.client from pywintypes import com_error as COMError # pylint: disable=no-name-in-module from win32com.client import constants # pylint: disable=unused-import else: logging.getLogger(__name__).warning( "Any `RPA.*.Application` library works only on Windows platform!" ) # As these are imported anyway from here and should be defined on non-Windows OSes. COMError = Exception constants = None def _to_unsigned(val): return struct.unpack("L", struct.pack("l", val))[0] def to_path(path: str) -> Path: return Path(path).expanduser().resolve() def to_str_path(path: str) -> str: return str(to_path(path)) # TODO(cmin764; 16 Aug 2023): Create a `handles_com_error` decorator if we get a little # too repetitive with context managers guarding. (to decorate the keywords) @contextmanager def catch_com_error(): """Try to convert COM errors to human-readable format.""" try: yield except COMError as err: # pylint: disable=no-member if err.excepinfo: try: msg = win32api.FormatMessage(_to_unsigned(err.excepinfo[5])) except Exception: # pylint: disable=broad-except msg = err.excepinfo[2] else: try: msg = win32api.FormatMessage(_to_unsigned(err.hresult)) except Exception: # pylint: disable=broad-except msg = err.strerror raise RuntimeError(msg) from err class MetaApplication(type): """Metaclass enhancing every final class inheriting from a base using this.""" def __new__(cls, *args, **kwargs) -> type: final_class = super().__new__(cls, *args, **kwargs) bases = final_class.__mro__[1:] if len(bases) < 2: # not enhancing bases return final_class super_class = bases[0] final_class.__doc__ += super_class.__doc__ if final_class.APP_DISPATCH is None: raise ValueError( "An `APP_DISPATCH` has to be defined in this" f" {final_class.__name__!r} class" ) return final_class class BaseApplication(metaclass=MetaApplication): # Base library `Application` class for managing COM apps. # The docstring below is automatically appended at the end of every inheritor. """ **Caveats** This library works on a Windows operating system with UI enabled only, and you must ensure that you open the app first with ``Open Application`` before running any other relevant keyword which requires to operate on an open app. The application is automatically closed at the end of the task execution, so this can be changed by importing the library with the `autoexit=${False}` setting. .. code-block:: robotframework *** Settings *** Library RPA.Excel|Outlook|Word.Application autoexit=${False} If you're running the Process by Control Room through a custom self-hosted Worker service, then please make sure that you enable an RDP session by ticking "Use Desktop Connection" under the Step configuration. If you still encounter issues with opening a document, please ensure that file can be opened first manually and dismiss any alert potentially blocking the process. Check the documentation below for more info: - https://robocorp.com/docs/control-room/unattended/worker-setups/windows-desktop - https://robocorp.com/docs/faq/windows-server-2016 """ ROBOT_LIBRARY_SCOPE = "GLOBAL" ROBOT_LIBRARY_DOC_FORMAT = "REST" APP_DISPATCH = None # this has to be defined in every inheriting class def __init__(self, autoexit: bool = True): """Initialize the library instance by wrapping the COM Windows app. :param autoexit: Automatically close the app when the process finishes. """ self.logger = logging.getLogger(__name__) self._app_name = self.APP_DISPATCH.split(".")[0] self._app = None if platform.system() != "Windows": self.logger.warning( "This %s application library requires Windows dependencies to work.", self._app_name, ) if autoexit: atexit.register(self.quit_application) @property def app(self): if self._app is None: raise ValueError(f"{self._app_name} application is not open") return self._app def open_application( self, visible: bool = False, display_alerts: bool = False ) -> None: """Open the application. :param visible: Show the window on opening. (`False` by default) :param display_alerts: Display alert popups. (`False` by default) """ with catch_com_error(): self._app = win32com.client.gencache.EnsureDispatch(self.APP_DISPATCH) self.logger.debug("Opened application: %s", self.app) if hasattr(self.app, "Visible"): state = "visible" if visible else "invisible" self.logger.debug("Making the application %s.", state) self.app.Visible = visible elif visible: self.logger.warning("Visibility cannot be controlled on this app.") # Show for e.g. a file overwrite warning or not. if hasattr(self.app, "DisplayAlerts"): state = "Displaying" if display_alerts else "Hiding" self.logger.debug("%s the application alerts.", state) self.app.DisplayAlerts = display_alerts elif display_alerts: self.logger.warning( "Alerts displaying cannot be controlled on this app." ) @property def _active_document(self): # Retrieves the currently active document. (raises if there's none active) with catch_com_error(): return getattr(self.app, "ActiveDocument", None) def METHOD_NAME(self): # Cleans-up a just closed previously active document. pass def close_document(self, save_changes: bool = False) -> None: """Close the active document and app (if open). :param save_changes: Enable changes saving on quit. (`False` by default) """ if not self._app: # no app open at all return try: with catch_com_error(): if self._active_document: state = "saving" if save_changes else "not saving" self.logger.debug( "Closing the open document and %s changes.", state ) self._active_document.Close(save_changes) self.METHOD_NAME() except RuntimeError as exc: if "no document is open" in str(exc): self.logger.warning( "Failed attempt on closing a document when there's none open!" ) else: raise def quit_application(self, save_changes: bool = False) -> None: """Quit the application. :param save_changes: Enable to save changes on quit. (`False` by default) """ if not self._app: return self.close_document(save_changes) with catch_com_error(): self.app.Quit() self._app = None
3,619
make lookup
# -*- coding: utf-8 -*- """ Conversion from AST node to Mathic BaseElement objects """ from math import log10 from typing import Tuple import sympy from mathics.core.atoms import Integer, MachineReal, PrecisionReal, Rational, String from mathics.core.convert.expression import to_expression, to_mathics_list from mathics.core.number import RECONSTRUCT_MACHINE_PRECISION_DIGITS from mathics.core.parser.ast import ( Filename as AST_Filename, Number as AST_Number, String as AST_String, Symbol as AST_Symbol, ) from mathics.core.symbols import Symbol, SymbolList class GenericConverter: def do_convert(self, node): if isinstance(node, AST_Symbol): return self.convert_Symbol(node) elif isinstance(node, AST_String): return self.convert_String(node) elif isinstance(node, AST_Number): return self.convert_Number(node) elif isinstance(node, AST_Filename): return self.convert_Filename(node) else: head = self.do_convert(node.head) children = [self.do_convert(child) for child in node.children] return "Expression", head, children @staticmethod def string_escape(s): return s.encode("raw_unicode_escape").decode("unicode_escape") def convert_Symbol(self, node: AST_Symbol) -> Tuple[str, str]: if node.context is not None: return "Symbol", node.context + "`" + node.value else: return "Lookup", node.value def convert_String(self, node: AST_String) -> Tuple[str, str]: value = self.string_escape(node.value) return "String", value def convert_Filename(self, node: AST_Filename): s = node.value if s.startswith('"'): assert s.endswith('"') s = s[1:-1] s = self.string_escape(s) s = s.replace("\\", "\\\\") return "String", s def convert_Number(self, node: AST_Number) -> tuple: s = node.value sign = node.sign base = node.base suffix = node.suffix n = node.exp # Look for decimal point if "." not in s: if suffix is None: if n < 0: return "Rational", sign * int(s, base), base ** abs(n) else: return "Integer", sign * int(s, base) * (base**n) else: s = s + "." if base == 10: man = s if n != 0: s = s + "E" + str(n) if suffix is None: # MachineReal/PrecisionReal is determined by number of digits # in the mantissa # if the number of digits is less than 17, then MachineReal is used. # If more digits are provided, then PrecisionReal is used. digits = len(man) - 2 if digits < RECONSTRUCT_MACHINE_PRECISION_DIGITS: return "MachineReal", sign * float(s) else: return ( "PrecisionReal", ("DecimalString", str("-" + s if sign == -1 else s)), digits, ) elif suffix == "": return "MachineReal", sign * float(s) elif suffix.startswith("`"): # A double Reversed Prime ("``") represents a fixed accuracy # (absolute uncertainty). acc = float(suffix[1:]) x = float(s) # For 0, a finite absolute precision even if # the number is an integer, it is stored as a # PrecisionReal number. if x == 0: prec10 = acc else: prec10 = acc + log10(abs(x)) return ( "PrecisionReal", ("DecimalString", str("-" + s if sign == -1 else s)), prec10, ) else: # A single Reversed Prime ("`") represents a fixed precision # (relative uncertainty). # For 0, a finite relative precision reduces to no uncertainty, # so ``` 0`3 === 0 ``` and ``` 0.`3 === 0.`4 ``` if node.value == "0": return "Integer", 0 s_float = float(s) prec = float(suffix) if s_float == 0.0: return "MachineReal", sign * s_float return ( "PrecisionReal", ("DecimalString", str("-" + s if sign == -1 else s)), prec, ) # Put into standard form mantissa * base ^ n s = s.split(".") if len(s) == 1: man = s[0] else: n -= len(s[1]) man = s[0] + s[1] man = sign * int(man, base) if n >= 0: p = man * base**n q = 1 else: p = man q = base**-n result = "Rational", p, q x = float(sympy.Rational(p, q)) # determine `prec10` the digits of precision in base 10 if suffix is None: acc = len(s[1]) acc10 = acc * log10(base) if x == 0: prec10 = acc10 else: prec10 = acc10 + log10(abs(x)) if prec10 < RECONSTRUCT_MACHINE_PRECISION_DIGITS: prec10 = None elif suffix == "": prec10 = None elif suffix.startswith("`"): acc = float(suffix[1:]) acc10 = acc * log10(base) if x == 0: prec10 = acc10 else: prec10 = acc10 + log10(abs(x)) else: prec = float(suffix) prec10 = prec * log10(base) if prec10 is None: return "MachineReal", x else: return "PrecisionReal", result, prec10 class Converter(GenericConverter): def __init__(self): self.definitions = None def convert(self, node, definitions): self.definitions = definitions result = self.do_convert(node) self.definitions = None return result def do_convert(self, node): result = GenericConverter.do_convert(self, node) return getattr(self, "_make_" + result[0])(*result[1:]) def _make_Symbol(self, s: str) -> Symbol: return Symbol(s) def METHOD_NAME(self, s: str) -> Symbol: value = self.definitions.lookup_name(s) return Symbol(value) def _make_String(self, s: str) -> String: return String(s) def _make_Integer(self, x) -> Integer: return Integer(x) def _make_Rational(self, x, y) -> Rational: return Rational(x, y) def _make_MachineReal(self, x): return MachineReal(x) def _make_PrecisionReal(self, value, prec): if value[0] == "Rational": assert len(value) == 3 x = sympy.Rational(*value[1:]) elif value[0] == "DecimalString": assert len(value) == 2 x = value[1] else: assert False return PrecisionReal(sympy.Float(x, prec)) def _make_Expression(self, head: Symbol, children: list): if head == SymbolList: return to_mathics_list(*children) return to_expression(head, *children) converter = Converter() convert = converter.convert
3,620
test directory does not exist oasis exception
import json import uuid from unittest import TestCase import os import io from tempfile import TemporaryDirectory from hypothesis import given from hypothesis.strategies import sampled_from from pathlib import Path from oasislmf.model_execution.conf import create_analysis_settings_json from oasislmf.model_execution.files import GENERAL_SETTINGS_FILE, MODEL_SETTINGS_FILE, GUL_SUMMARIES_FILE, \ IL_SUMMARIES_FILE from oasislmf.utils.exceptions import OasisException class CreateAnalysisSettingsJson(TestCase): def create_fake_directory(self, d): Path(os.path.join(d, GENERAL_SETTINGS_FILE)).touch() Path(os.path.join(d, MODEL_SETTINGS_FILE)).touch() Path(os.path.join(d, GUL_SUMMARIES_FILE)).touch() Path(os.path.join(d, IL_SUMMARIES_FILE)).touch() def METHOD_NAME(self): with self.assertRaises(OasisException): create_analysis_settings_json('/tmp/non_existing_dir_{}'.format(uuid.uuid4().hex)) @given(sampled_from([GENERAL_SETTINGS_FILE, MODEL_SETTINGS_FILE, GUL_SUMMARIES_FILE, IL_SUMMARIES_FILE])) def test_input_file_is_missing___error_is_raised(self, to_delete): with TemporaryDirectory() as d: self.create_fake_directory(d) os.remove(os.path.join(d, to_delete)) with self.assertRaises(OasisException): create_analysis_settings_json(d) def test_general_settings_file_contains_properties___properties_are_loaded_into_general_settings(self): with TemporaryDirectory() as d: self.create_fake_directory(d) with io.open(os.path.join(d, GENERAL_SETTINGS_FILE), 'w', encoding='utf-8') as f: f.writelines([ 'first,1,int\n', 'second,foo,str\n', 'third,2.2,float\n', ]) data = json.loads(create_analysis_settings_json(d)) self.assertEqual(data['first'], 1) self.assertEqual(data['second'], 'foo') self.assertEqual(data['third'], 2.2) def test_model_settings_file_contains_properties___properties_are_loaded_into_model_settings(self): with TemporaryDirectory() as d: self.create_fake_directory(d) with io.open(os.path.join(d, MODEL_SETTINGS_FILE), 'w', encoding='utf-8') as f: f.writelines([ 'first,3,int\n', 'second,bar,str\n', 'third,4.4,float\n', ]) data = json.loads(create_analysis_settings_json(d)) self.assertEqual(data['model_settings'], { 'first': 3, 'second': 'bar', 'third': 4.4, }) def test_gul_settings_contains_data___data_is_stored_in_gul_summaries(self): with TemporaryDirectory() as d: self.create_fake_directory(d) with io.open(os.path.join(d, GUL_SUMMARIES_FILE), 'w', encoding='utf-8') as f: f.writelines([ '1,leccalc_foo,TRUE\n', '1,leccalc_bar,FALSE\n', '1,another,FALSE\n', '2,leccalc_boo,FALSE\n', '2,leccalc_far,TRUE\n', '2,different,TRUE\n', ]) data = json.loads(create_analysis_settings_json(d)) self.assertEqual(data['gul_summaries'], [ {'id': 1, 'another': False, 'leccalc': {'leccalc_foo': True, 'leccalc_bar': False}}, {'id': 2, 'different': True, 'leccalc': {'leccalc_boo': False, 'leccalc_far': True}}, ]) def test_il_settings_contains_data___data_is_stored_in_il_summaries(self): with TemporaryDirectory() as d: self.create_fake_directory(d) with io.open(os.path.join(d, IL_SUMMARIES_FILE), 'w', encoding='utf-8') as f: f.writelines([ '1,leccalc_foo,TRUE\n', '1,leccalc_bar,FALSE\n', '1,another,FALSE\n', '2,leccalc_boo,FALSE\n', '2,leccalc_far,TRUE\n', '2,different,TRUE\n', ]) data = json.loads(create_analysis_settings_json(d)) self.assertEqual(data['il_summaries'], [ {'id': 1, 'another': False, 'leccalc': {'leccalc_foo': True, 'leccalc_bar': False}}, {'id': 2, 'different': True, 'leccalc': {'leccalc_boo': False, 'leccalc_far': True}}, ])
3,621
test avoidoom
import numpy as np import pytest import torch from mmdet.utils import AvoidOOM from mmdet.utils.memory import cast_tensor_type def METHOD_NAME(): tensor = torch.from_numpy(np.random.random((20, 20))) if torch.cuda.is_available(): tensor = tensor.cuda() # get default result default_result = torch.mm(tensor, tensor.transpose(1, 0)) # when not occurred OOM error AvoidCudaOOM = AvoidOOM() result = AvoidCudaOOM.retry_if_cuda_oom(torch.mm)(tensor, tensor.transpose( 1, 0)) assert default_result.device == result.device and \ default_result.dtype == result.dtype and \ torch.equal(default_result, result) # calculate with fp16 and convert back to source type AvoidCudaOOM = AvoidOOM(test=True) result = AvoidCudaOOM.retry_if_cuda_oom(torch.mm)(tensor, tensor.transpose( 1, 0)) assert default_result.device == result.device and \ default_result.dtype == result.dtype and \ torch.allclose(default_result, result, 1e-3) # calculate on cpu and convert back to source device AvoidCudaOOM = AvoidOOM(test=True) result = AvoidCudaOOM.retry_if_cuda_oom(torch.mm)(tensor, tensor.transpose( 1, 0)) assert result.dtype == default_result.dtype and \ result.device == default_result.device and \ torch.allclose(default_result, result) # do not calculate on cpu and the outputs will be same as input AvoidCudaOOM = AvoidOOM(test=True, to_cpu=False) result = AvoidCudaOOM.retry_if_cuda_oom(torch.mm)(tensor, tensor.transpose( 1, 0)) assert result.dtype == default_result.dtype and \ result.device == default_result.device else: default_result = torch.mm(tensor, tensor.transpose(1, 0)) AvoidCudaOOM = AvoidOOM() result = AvoidCudaOOM.retry_if_cuda_oom(torch.mm)(tensor, tensor.transpose( 1, 0)) assert default_result.device == result.device and \ default_result.dtype == result.dtype and \ torch.equal(default_result, result) def test_cast_tensor_type(): inputs = torch.rand(10) if torch.cuda.is_available(): inputs = inputs.cuda() with pytest.raises(AssertionError): cast_tensor_type(inputs, src_type=None, dst_type=None) # input is a float out = cast_tensor_type(10., dst_type=torch.half) assert out == 10. and isinstance(out, float) # convert Tensor to fp16 and re-convert to fp32 fp16_out = cast_tensor_type(inputs, dst_type=torch.half) assert fp16_out.dtype == torch.half fp32_out = cast_tensor_type(fp16_out, dst_type=torch.float32) assert fp32_out.dtype == torch.float32 # input is a list list_input = [inputs, inputs] list_outs = cast_tensor_type(list_input, dst_type=torch.half) assert len(list_outs) == len(list_input) and \ isinstance(list_outs, list) for out in list_outs: assert out.dtype == torch.half # input is a dict dict_input = {'test1': inputs, 'test2': inputs} dict_outs = cast_tensor_type(dict_input, dst_type=torch.half) assert len(dict_outs) == len(dict_input) and \ isinstance(dict_outs, dict) # convert the input tensor to CPU and re-convert to GPU if torch.cuda.is_available(): cpu_device = torch.empty(0).device gpu_device = inputs.device cpu_out = cast_tensor_type(inputs, dst_type=cpu_device) assert cpu_out.device == cpu_device gpu_out = cast_tensor_type(inputs, dst_type=gpu_device) assert gpu_out.device == gpu_device
3,622
offset polyline
from __future__ import print_function from __future__ import absolute_import from __future__ import division from compas.geometry import scale_vector from compas.geometry import normalize_vector from compas.geometry import add_vectors from compas.geometry import subtract_vectors from compas.geometry import cross_vectors from compas.geometry import centroid_points from compas.geometry import intersection_line_line from compas.geometry import normal_polygon from compas.geometry import is_colinear from compas.data import is_item_iterable from compas.utilities import iterable_like from compas.utilities import pairwise def intersect_lines(l1, l2, tol): x1, x2 = intersection_line_line(l1, l2, tol) if x1 and x2: return centroid_points([x1, x2]) def intersect_lines_colinear(l1, l2, tol): def are_segments_colinear(l1, l2, tol): a, b = l1 d, c = l2 return is_colinear(a, b, c, tol) if are_segments_colinear(l1, l2, tol): return centroid_points([l1[1], l2[0]]) def intersect(l1, l2, tol): supported_funcs = [intersect_lines, intersect_lines_colinear] for func in supported_funcs: point = func(l1, l2, tol) if point: return point msg = "Intersection not found for line: {}, and line: {}".format(l1, l2) raise ValueError(msg) def offset_segments(point_list, distances, normal): segments = [] for line, distance in zip(pairwise(point_list), distances): segments.append(offset_line(line, distance, normal)) return segments def offset_line(line, distance, normal=[0.0, 0.0, 1.0]): """Offset a line by a distance. Parameters ---------- line : [point, point] | :class:`~compas.geometry.Line` A line defined by two points. distances : float or list[float] The offset distance as float. A single value determines a constant offset. A list of two offset values can be used to a create variable offset at the start and end. normal : [float, float, float] | :class:`~compas.geometry.Vector`, optional The normal of the offset plane. Returns ------- tuple[[float, float, float], [float, float, float]] Two points defining the offset line. Notes ----- The offset direction is chosen such that if the line were along the positve X axis and the normal of the offset plane is along the positive Z axis, the offset line is in the direction of the postive Y axis. Examples -------- >>> """ a, b = line ab = subtract_vectors(b, a) direction = normalize_vector(cross_vectors(normal, ab)) if not is_item_iterable(distance): distance = [distance] distances = list(iterable_like(line, distance, distance[-1])) u = scale_vector(direction, distances[0]) v = scale_vector(direction, distances[1]) c = add_vectors(a, u) d = add_vectors(b, v) return c, d def offset_polygon(polygon, distance, tol=1e-6): """Offset a polygon (closed) by a distance. Parameters ---------- polygon : sequence[point] | :class:`~compas.geometry.Polygon` The XYZ coordinates of the corners of the polygon. The first and last coordinates must not be identical. distance : float | list[tuple[float, float]] The offset distance as float. A single value determines a constant offset globally. A list of pairs of local offset values per line segment can be used to create variable offsets. tol : float, optional A tolerance value for intersection calculations. Returns ------- list[[float, float, float]] The XYZ coordinates of the corners of the offset polygon. The first and last coordinates are identical. Notes ----- The offset direction is determined by the normal of the polygon. If the polygon is in the XY plane and the normal is along the positive Z axis, positive offset distances will result in an offset towards the inside of the polygon. The algorithm works also for spatial polygons that do not perfectly fit a plane. Examples -------- >>> from compas.geometry import Polygon >>> polygon = Polygon([(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)]) >>> offsetted_polygon = offset_polygon(polygon, 0.5) >>> offsetted_polygon Polygon[[0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0]] """ normal = normal_polygon(polygon) if not is_item_iterable(distance): distance = [distance] distances = iterable_like(polygon, distance, distance[-1]) polygon = polygon[:] + polygon[:1] segments = offset_segments(polygon, distances, normal) offset = [] for s1, s2 in pairwise(segments[-1:] + segments): point = intersect(s1, s2, tol) offset.append(point) return offset def METHOD_NAME(polyline, distance, normal=[0.0, 0.0, 1.0], tol=1e-6): """Offset a polyline by a distance. Parameters ---------- polyline : sequence[point] | :class:`~compas.geometry.Polyline` The XYZ coordinates of the vertices of a polyline. distance : float | list[tuple[float, float]] The offset distance as float. A single value determines a constant offset globally. Alternatively, pairs of local offset values per line segment can be used to create variable offsets. normal : [float, float, float] | :class:`~compas.geometry.Vector`, optional The normal of the offset plane. tol : float, optional A tolerance value for intersection calculations. Returns ------- list[[float, float, float]] The XYZ coordinates of the resulting polyline. Notes ----- The offset direction is determined by the provided normal vector. If the polyline is in the XY plane and the normal is along the positive Z axis, positive offset distances will result in counterclockwise offsets, and negative values in clockwise direction. Examples -------- >>> """ if not is_item_iterable(distance): distance = [distance] distances = iterable_like(polyline, distance, distance[-1]) segments = offset_segments(polyline, distances, normal) offset = [segments[0][0]] for s1, s2 in pairwise(segments): point = intersect(s1, s2, tol) offset.append(point) offset.append(segments[-1][1]) return offset
3,623
init skale
# -*- coding: utf-8 -*- # # This file is part of SKALE Admin # # Copyright (C) 2019 SKALE Labs # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. import os import json import time import psutil import yaml import logging import itertools import subprocess from subprocess import PIPE import requests from filelock import FileLock from jinja2 import Environment from skale import Skale from skale.wallets import BaseWallet from tools.configs import INIT_LOCK_PATH from tools.configs.web3 import ENDPOINT, ABI_FILEPATH, STATE_FILEPATH, ZERO_ADDRESS logger = logging.getLogger(__name__) POST_REQUEST_TIMEOUT = 30 def post_request(url, json, cookies=None, timeout=None): timeout = timeout or POST_REQUEST_TIMEOUT try: return requests.post( url, json=json, cookies=cookies, timeout=timeout ) except requests.exceptions.RequestException as err: logger.error(f'Post request failed with: {err}') return None def read_json(path, mode='r'): with open(path, mode=mode, encoding='utf-8') as data_file: return json.load(data_file) def write_json(path, content): with open(path, 'w') as outfile: json.dump(content, outfile, indent=4) def init_file(path, content=None): if not os.path.exists(path): write_json(path, content) def files(path): for file in os.listdir(path): if os.path.isfile(os.path.join(path, file)): yield file def sanitize_filename(filename): return "".join(x for x in filename if x.isalnum() or x == '_') def namedtuple_to_dict(tuple): return tuple._asdict() def run_cmd(cmd, env={}, shell=False): logger.info(f'Running: {cmd}') res = subprocess.run(cmd, shell=shell, stdout=PIPE, stderr=PIPE, env={**env, **os.environ}) if res.returncode: logger.error('Error during shell execution:') logger.error(res.stderr.decode('UTF-8').rstrip()) raise subprocess.CalledProcessError(res.returncode, cmd) return res def format_output(res): return res.stdout.decode('UTF-8').rstrip(), \ res.stderr.decode('UTF-8').rstrip() def merged_unique(*args): seen = set() for item in itertools.chain(*args): if item not in seen: yield item seen.add(item) def process_template(source, destination, data): """ :param source: j2 template source path :param destination: out file path :param data: dictionary with fields for template :return: Nothing """ template = None with open(source) as template_file: template = template_file.read() processed_template = Environment().from_string(template).render(data) with open(destination, "w") as f: f.write(processed_template) def wait_until_admin_inited(): logger.info('Checking if skale-admin inited ...') lock = FileLock(INIT_LOCK_PATH) with lock: logger.info('Skale admin inited') def METHOD_NAME(wallet: BaseWallet) -> Skale: return Skale(ENDPOINT, ABI_FILEPATH, wallet, state_path=STATE_FILEPATH) def safe_load_yml(filepath): with open(filepath, 'r') as stream: return yaml.safe_load(stream) def check_pid(pid): """ Check For the existence of a unix pid. """ try: os.kill(pid, 0) except OSError: return False else: return True def check_pid_psutil(pid): p = psutil.Process(pid) return p.is_running() and p.status() != psutil.STATUS_ZOMBIE def get_endpoint_call_speed(web3): scores = [] for _ in range(10): start = time.time() result = web3.eth.gas_price if result: scores.append(time.time() - start) if len(scores) == 0: return None call_avg_speed = round(sum(scores) / len(scores), 2) logger.info(f'Endpoint call speed scores: {scores}, avg: {call_avg_speed}') return call_avg_speed def is_node_part_of_chain(skale, schain_name, node_id) -> bool: if not skale.schains_internal.is_schain_exist(schain_name): return False node_ids = skale.schains_internal.get_node_ids_for_schain(schain_name) return node_id in node_ids def is_zero_address(address: str) -> bool: """Returns true if provided string is equal to Ethereum zero address""" return address == ZERO_ADDRESS def is_address_contract(web3, address) -> bool: """Returns true if contract is deployed at the requested address""" return web3.eth.get_code(address) != b''
3,624
search pagination
import base64 from stix_shifter_utils.stix_transmission.utils.RestApiClientAsync import RestApiClientAsync from stix_shifter_utils.utils import logger import json import re DEFAULT_LIMIT = 10000 class APIClient(): PING_ENDPOINT = '_cluster/health?pretty' def __init__(self, connection, configuration): self.logger = logger.set_logger(__name__) headers = dict() url_modifier_function = None auth = configuration.get('auth') self.indices = connection.get('indices', None) if self.indices and type(self.indices) == str: self.indices = self.indices.split(",") if isinstance(self.indices, list): # Get list of all indices self.indices = [i.strip(' ') for i in self.indices] self.indices = ",".join(self.indices) if self.indices: self.endpoint = self.indices + '/' + '_search' self.pit_endpoint = self.indices + '/' + '_pit' self.setting_endpoint = self.indices + '/' + '_settings' else: self.endpoint = '_search' self.pit_endpoint = '_pit' self.setting_endpoint = '_settings' if auth: if 'username' in auth and 'password' in auth: token_decoded = auth['username'] + ':' + auth['password'] token = base64.b64encode(token_decoded.encode('ascii')) headers['Authorization'] = "Basic %s" % token.decode('ascii') elif 'api_key' in auth and 'id' in auth: token_decoded = auth['id'] + ':' + auth['api_key'] token = base64.b64encode(token_decoded.encode('ascii')) headers['Authorization'] = "ApiKey %s" % token.decode('ascii') elif 'access_token' in auth: headers['Authorization'] = "Bearer " + auth['access_token'] self.client = RestApiClientAsync(connection.get('host'), connection.get('port'), headers, url_modifier_function=url_modifier_function, cert_verify=connection.get('selfSignedCert', True) ) self.timeout = connection['options'].get('timeout') async def ping_box(self): return await self.client.call_api(self.PING_ENDPOINT, 'GET', timeout=self.timeout) async def METHOD_NAME(self, query_expression, lastsortvalue=None, length=DEFAULT_LIMIT): headers = dict() headers['Content-Type'] = 'application/json' data = { "_source": { "includes": ["@timestamp", "source.*", "destination.*", "event.*", "client.*", "server.*", "observer.*", "host.*", "network.*", "process.*", "user.*", "file.*", "url.*", "registry.*", "dns.*", "tags"] }, "size": length, "query": { "query_string": { "query": query_expression } }, "sort": [ {"@timestamp": "asc"}, ] } if lastsortvalue: data["search_after"] = lastsortvalue self.logger.debug("URL endpoint: " + self.endpoint) self.logger.debug("URL data: " + json.dumps(data)) return await self.client.call_api(self.endpoint, 'GET', headers, data=json.dumps(data), timeout=self.timeout) async def get_max_result_window(self): max_result_window_url = self.setting_endpoint + "/index.max_result_window?include_defaults=true" return await self.client.call_api(max_result_window_url, 'GET', timeout=self.timeout) async def set_pit(self): headers = dict() headers['Content-Type'] = 'application/json' # GET PIT # POST /my-index-000001/_pit?keep_alive=1m endpoint = "{}?keep_alive=1m&pretty".format(self.pit_endpoint) return await self.client.call_api(endpoint, 'POST', headers, timeout=self.timeout)
3,625
test 2020
# python-holidays # --------------- # A fast, efficient Python library for generating country, province and state # specific sets of holidays on the fly. It aims to make determining whether a # specific date is a holiday as fast and flexible as possible. # # Authors: dr-prodigy <dr.prodigy.github@gmail.com> (c) 2017-2023 # ryanss <ryanssdev@icloud.com> (c) 2014-2017 # Website: https://github.com/dr-prodigy/python-holidays # License: MIT (see LICENSE file) from holidays.countries.guatemala import Guatemala, GT, GUA from tests.common import TestCase class TestGuatemala(TestCase): @classmethod def setUpClass(cls): super().setUpClass(Guatemala) def test_country_aliases(self): self.assertCountryAliases(Guatemala, GT, GUA) def test_2016(self): # https://calendariohispanohablante.com/2016/calendario-guatemala-2016.html dt = ( "2016-01-01", "2016-03-24", "2016-03-25", "2016-03-26", "2016-05-01", "2016-06-30", "2016-08-15", "2016-09-15", "2016-10-20", "2016-11-01", "2016-12-25", ) self.assertHoliday(dt) def test_2017(self): # https://calendariohispanohablante.com/2017/calendario-guatemala-2017.html dt = ( "2017-01-01", "2017-04-13", "2017-04-14", "2017-04-15", "2017-05-01", "2017-06-30", "2017-08-15", "2017-09-15", "2017-10-20", "2017-11-01", "2017-12-25", ) self.assertHoliday(dt) def test_2018(self): # https://calendariohispanohablante.com/2018/calendario-guatemala-2018.html dt = ( "2018-01-01", "2018-03-29", "2018-03-30", "2018-03-31", "2018-05-01", "2018-06-30", "2018-08-15", "2018-09-15", "2018-10-22", "2018-11-01", "2018-12-25", ) self.assertHoliday(dt) def test_2019(self): # https://calendariohispanohablante.com/2019/calendario-guatemala-2019.html dt = ( "2019-01-01", "2019-04-18", "2019-04-19", "2019-04-20", "2019-04-29", "2019-07-01", "2019-08-15", "2019-09-15", "2019-10-21", "2019-11-01", "2019-12-25", ) self.assertHoliday(dt) def METHOD_NAME(self): # https://calendariohispanohablante.com/2020/calendario-guatemala-2020.html dt = ( "2020-01-01", "2020-04-09", "2020-04-10", "2020-04-11", "2020-05-01", "2020-06-29", "2020-08-15", "2020-09-15", "2020-10-20", "2020-11-01", "2020-12-25", ) self.assertHoliday(dt) def test_2021(self): # https://calendariohispanohablante.com/2021/calendario-guatemala-2021.html dt = ( "2021-01-01", "2021-04-01", "2021-04-02", "2021-04-03", "2021-05-01", "2021-06-28", "2021-08-15", "2021-09-15", "2021-10-20", "2021-11-01", "2021-12-25", ) self.assertHoliday(dt) def test_2022(self): # https://publicholidays.la/guatemala/es/2022-dates/ dt = ( "2022-01-01", "2022-04-14", "2022-04-15", "2022-04-16", "2022-05-01", "2022-07-04", "2022-08-15", "2022-09-15", "2022-10-20", "2022-11-01", "2022-12-25", ) self.assertHoliday(dt) def test_2023(self): # https://publicholidays.la/guatemala/es/2023-dates/ dt = ( "2023-01-01", "2023-04-06", "2023-04-07", "2023-04-08", "2023-05-01", "2023-07-03", "2023-08-15", "2023-09-15", "2023-10-20", "2023-11-01", "2023-12-25", ) self.assertHoliday(dt) def test_2024(self): # https://publicholidays.la/guatemala/es/2024-dates/ dt = ( "2024-01-01", "2024-03-28", "2024-03-29", "2024-03-30", "2024-05-01", "2024-07-01", "2024-08-15", "2024-09-15", "2024-10-20", "2024-11-01", "2024-12-25", ) self.assertHoliday(dt) def test_l10n_default(self): self.assertLocalizedHolidays( ("2024-01-01", "Año Nuevo"), ("2024-03-28", "Jueves Santo"), ("2024-03-29", "Viernes Santo"), ("2024-03-30", "Sabado Santo"), ("2024-05-01", "Dia del Trabajo"), ("2024-07-01", "Dia del Ejército"), ("2024-08-15", "Dia de la Asunción"), ("2024-09-15", "Día de la Independencia"), ("2024-10-20", "Dia de la Revolución"), ("2024-11-01", "Dia de Todos los Santos"), ("2024-12-25", "Dia de Navidad"), ) def test_l10n_en_us(self): self.assertLocalizedHolidays( "en_US", ("2024-01-01", "New Year's Day"), ("2024-03-28", "Good Thursday"), ("2024-03-29", "Good Friday"), ("2024-03-30", "Good Saturday"), ("2024-05-01", "Labor Day"), ("2024-07-01", "Army Day"), ("2024-08-15", "Assumption Day"), ("2024-09-15", "Independence Day"), ("2024-10-20", "Revolution Day"), ("2024-11-01", "All Saints' Day"), ("2024-12-25", "Christmas Day"), )
3,626
crop process
# Copyright (c) Alibaba, Inc. and its affiliates. from typing import Any, Dict, Optional, Union import torch from torchvision import transforms from modelscope.metainfo import Pipelines from modelscope.models import Model from modelscope.models.cv.image_denoise import NAFNetForImageDenoise from modelscope.outputs import OutputKeys from modelscope.pipelines.base import Input, Pipeline from modelscope.pipelines.builder import PIPELINES from modelscope.preprocessors import ImageDenoisePreprocessor, LoadImage from modelscope.utils.constant import Tasks from modelscope.utils.logger import get_logger logger = get_logger() __all__ = ['ImageDenoisePipeline'] @PIPELINES.register_module( Tasks.image_denoising, module_name=Pipelines.image_denoise) class ImageDenoisePipeline(Pipeline): def __init__(self, model: Union[NAFNetForImageDenoise, str], preprocessor: Optional[ImageDenoisePreprocessor] = None, **kwargs): """ use `model` and `preprocessor` to create a cv image denoise pipeline for prediction Args: model: model id on modelscope hub. """ super().__init__(model=model, preprocessor=preprocessor, **kwargs) self.model.eval() self.config = self.model.config if torch.cuda.is_available(): self._device = torch.device('cuda') else: self._device = torch.device('cpu') logger.info('load image denoise model done') def preprocess(self, input: Input) -> Dict[str, Any]: img = LoadImage.convert_to_img(input) test_transforms = transforms.Compose([transforms.ToTensor()]) img = test_transforms(img) result = {'img': img.unsqueeze(0).to(self._device)} return result def METHOD_NAME(self, input): output = torch.zeros_like(input) # [1, C, H, W] # determine crop_h and crop_w ih, iw = input.shape[-2:] crop_rows, crop_cols = max(ih // 512, 1), max(iw // 512, 1) overlap = 16 step_h, step_w = ih // crop_rows, iw // crop_cols for y in range(crop_rows): for x in range(crop_cols): crop_y = step_h * y crop_x = step_w * x crop_h = step_h if y < crop_rows - 1 else ih - crop_y crop_w = step_w if x < crop_cols - 1 else iw - crop_x crop_frames = input[:, :, max(0, crop_y - overlap ):min(crop_y + crop_h + overlap, ih), max(0, crop_x - overlap ):min(crop_x + crop_w + overlap, iw)].contiguous() h_start = overlap if max(0, crop_y - overlap) > 0 else 0 w_start = overlap if max(0, crop_x - overlap) > 0 else 0 h_end = h_start + crop_h if min(crop_y + crop_h + overlap, ih) < ih else ih w_end = w_start + crop_w if min(crop_x + crop_w + overlap, iw) < iw else iw output[:, :, crop_y:crop_y + crop_h, crop_x:crop_x + crop_w] = self.model._inference_forward( crop_frames)['outputs'][:, :, h_start:h_end, w_start:w_end] return output def forward(self, input: Dict[str, Any]) -> Dict[str, Any]: def set_phase(model, is_train): if is_train: model.train() else: model.eval() is_train = False set_phase(self.model, is_train) with torch.no_grad(): output = self.METHOD_NAME(input['img']) # output Tensor return {'output_tensor': output} def postprocess(self, input: Dict[str, Any]) -> Dict[str, Any]: output_img = (input['output_tensor'].squeeze(0) * 255).cpu().permute( 1, 2, 0).numpy().astype('uint8') return {OutputKeys.OUTPUT_IMG: output_img[:, :, ::-1]}
3,627
describe cost category definition
"""CostExplorerBackend class with methods for supported APIs.""" from .exceptions import CostCategoryNotFound from moto.core import BaseBackend, BackendDict, BaseModel from moto.utilities.tagging_service import TaggingService from moto.core.utils import iso_8601_datetime_without_milliseconds from moto.moto_api._internal import mock_random from datetime import datetime from typing import Any, Dict, List, Tuple, Optional def first_day() -> str: as_date = ( datetime.today() .replace(day=1) .replace(hour=0) .replace(minute=0) .replace(second=0) ) return iso_8601_datetime_without_milliseconds(as_date) # type: ignore[return-value] class CostCategoryDefinition(BaseModel): def __init__( self, account_id: str, name: str, effective_start: Optional[str], rule_version: str, rules: List[Dict[str, Any]], default_value: str, split_charge_rules: List[Dict[str, Any]], ): self.name = name self.rule_version = rule_version self.rules = rules self.default_value = default_value self.split_charge_rules = split_charge_rules self.arn = f"arn:aws:ce::{account_id}:costcategory/{str(mock_random.uuid4())}" self.effective_start: str = effective_start or first_day() def update( self, rule_version: str, effective_start: Optional[str], rules: List[Dict[str, Any]], default_value: str, split_charge_rules: List[Dict[str, Any]], ) -> None: self.rule_version = rule_version self.rules = rules self.default_value = default_value self.split_charge_rules = split_charge_rules self.effective_start = effective_start or first_day() def to_json(self) -> Dict[str, Any]: return { "CostCategoryArn": self.arn, "Name": self.name, "EffectiveStart": self.effective_start, "RuleVersion": self.rule_version, "Rules": self.rules, "DefaultValue": self.default_value, "SplitChargeRules": self.split_charge_rules, } class CostExplorerBackend(BaseBackend): """Implementation of CostExplorer APIs.""" def __init__(self, region_name: str, account_id: str): super().__init__(region_name, account_id) self.cost_categories: Dict[str, CostCategoryDefinition] = dict() self.tagger = TaggingService() def create_cost_category_definition( self, name: str, effective_start: Optional[str], rule_version: str, rules: List[Dict[str, Any]], default_value: str, split_charge_rules: List[Dict[str, Any]], tags: List[Dict[str, str]], ) -> Tuple[str, str]: """ The EffectiveOn and ResourceTags-parameters are not yet implemented """ ccd = CostCategoryDefinition( self.account_id, name, effective_start, rule_version, rules, default_value, split_charge_rules, ) self.cost_categories[ccd.arn] = ccd self.tag_resource(ccd.arn, tags) return ccd.arn, ccd.effective_start def METHOD_NAME( self, cost_category_arn: str ) -> CostCategoryDefinition: """ The EffectiveOn-parameter is not yet implemented """ if cost_category_arn not in self.cost_categories: ccd_id = cost_category_arn.split("/")[-1] raise CostCategoryNotFound(ccd_id) return self.cost_categories[cost_category_arn] def delete_cost_category_definition( self, cost_category_arn: str ) -> Tuple[str, str]: """ The EffectiveOn-parameter is not yet implemented """ self.cost_categories.pop(cost_category_arn, None) return cost_category_arn, "" def update_cost_category_definition( self, cost_category_arn: str, effective_start: Optional[str], rule_version: str, rules: List[Dict[str, Any]], default_value: str, split_charge_rules: List[Dict[str, Any]], ) -> Tuple[str, str]: """ The EffectiveOn-parameter is not yet implemented """ cost_category = self.METHOD_NAME(cost_category_arn) cost_category.update( rule_version=rule_version, rules=rules, default_value=default_value, split_charge_rules=split_charge_rules, effective_start=effective_start, ) return cost_category_arn, cost_category.effective_start def list_tags_for_resource(self, resource_arn: str) -> List[Dict[str, str]]: return self.tagger.list_tags_for_resource(arn=resource_arn)["Tags"] def tag_resource(self, resource_arn: str, tags: List[Dict[str, str]]) -> None: self.tagger.tag_resource(resource_arn, tags) def untag_resource(self, resource_arn: str, tag_keys: List[str]) -> None: self.tagger.untag_resource_using_names(resource_arn, tag_keys) ce_backends = BackendDict( CostExplorerBackend, "ce", use_boto3_regions=False, additional_regions=["global"] )
3,628
test getopt
# test_getopt.py # David Goodger <dgoodger@bigfoot.com> 2000-08-19 from test.support import verbose, run_doctest from test.support.os_helper import EnvironmentVarGuard import unittest import getopt sentinel = object() class GetoptTests(unittest.TestCase): def setUp(self): self.env = self.enterContext(EnvironmentVarGuard()) if "POSIXLY_CORRECT" in self.env: del self.env["POSIXLY_CORRECT"] def assertError(self, *args, **kwargs): self.assertRaises(getopt.GetoptError, *args, **kwargs) def test_short_has_arg(self): self.assertTrue(getopt.short_has_arg('a', 'a:')) self.assertFalse(getopt.short_has_arg('a', 'a')) self.assertError(getopt.short_has_arg, 'a', 'b') def test_long_has_args(self): has_arg, option = getopt.long_has_args('abc', ['abc=']) self.assertTrue(has_arg) self.assertEqual(option, 'abc') has_arg, option = getopt.long_has_args('abc', ['abc']) self.assertFalse(has_arg) self.assertEqual(option, 'abc') has_arg, option = getopt.long_has_args('abc', ['abcd']) self.assertFalse(has_arg) self.assertEqual(option, 'abcd') self.assertError(getopt.long_has_args, 'abc', ['def']) self.assertError(getopt.long_has_args, 'abc', []) self.assertError(getopt.long_has_args, 'abc', ['abcd','abcde']) def test_do_shorts(self): opts, args = getopt.do_shorts([], 'a', 'a', []) self.assertEqual(opts, [('-a', '')]) self.assertEqual(args, []) opts, args = getopt.do_shorts([], 'a1', 'a:', []) self.assertEqual(opts, [('-a', '1')]) self.assertEqual(args, []) #opts, args = getopt.do_shorts([], 'a=1', 'a:', []) #self.assertEqual(opts, [('-a', '1')]) #self.assertEqual(args, []) opts, args = getopt.do_shorts([], 'a', 'a:', ['1']) self.assertEqual(opts, [('-a', '1')]) self.assertEqual(args, []) opts, args = getopt.do_shorts([], 'a', 'a:', ['1', '2']) self.assertEqual(opts, [('-a', '1')]) self.assertEqual(args, ['2']) self.assertError(getopt.do_shorts, [], 'a1', 'a', []) self.assertError(getopt.do_shorts, [], 'a', 'a:', []) def test_do_longs(self): opts, args = getopt.do_longs([], 'abc', ['abc'], []) self.assertEqual(opts, [('--abc', '')]) self.assertEqual(args, []) opts, args = getopt.do_longs([], 'abc=1', ['abc='], []) self.assertEqual(opts, [('--abc', '1')]) self.assertEqual(args, []) opts, args = getopt.do_longs([], 'abc=1', ['abcd='], []) self.assertEqual(opts, [('--abcd', '1')]) self.assertEqual(args, []) opts, args = getopt.do_longs([], 'abc', ['ab', 'abc', 'abcd'], []) self.assertEqual(opts, [('--abc', '')]) self.assertEqual(args, []) # Much like the preceding, except with a non-alpha character ("-") in # option name that precedes "="; failed in # http://python.org/sf/126863 opts, args = getopt.do_longs([], 'foo=42', ['foo-bar', 'foo=',], []) self.assertEqual(opts, [('--foo', '42')]) self.assertEqual(args, []) self.assertError(getopt.do_longs, [], 'abc=1', ['abc'], []) self.assertError(getopt.do_longs, [], 'abc', ['abc='], []) def METHOD_NAME(self): # note: the empty string between '-a' and '--beta' is significant: # it simulates an empty string option argument ('-a ""') on the # command line. cmdline = ['-a', '1', '-b', '--alpha=2', '--beta', '-a', '3', '-a', '', '--beta', 'arg1', 'arg2'] opts, args = getopt.getopt(cmdline, 'a:b', ['alpha=', 'beta']) self.assertEqual(opts, [('-a', '1'), ('-b', ''), ('--alpha', '2'), ('--beta', ''), ('-a', '3'), ('-a', ''), ('--beta', '')]) # Note ambiguity of ('-b', '') and ('-a', '') above. This must be # accounted for in the code that calls getopt(). self.assertEqual(args, ['arg1', 'arg2']) self.assertError(getopt.getopt, cmdline, 'a:b', ['alpha', 'beta']) def test_gnu_getopt(self): # Test handling of GNU style scanning mode. cmdline = ['-a', 'arg1', '-b', '1', '--alpha', '--beta=2'] # GNU style opts, args = getopt.gnu_getopt(cmdline, 'ab:', ['alpha', 'beta=']) self.assertEqual(args, ['arg1']) self.assertEqual(opts, [('-a', ''), ('-b', '1'), ('--alpha', ''), ('--beta', '2')]) # recognize "-" as an argument opts, args = getopt.gnu_getopt(['-a', '-', '-b', '-'], 'ab:', []) self.assertEqual(args, ['-']) self.assertEqual(opts, [('-a', ''), ('-b', '-')]) # Posix style via + opts, args = getopt.gnu_getopt(cmdline, '+ab:', ['alpha', 'beta=']) self.assertEqual(opts, [('-a', '')]) self.assertEqual(args, ['arg1', '-b', '1', '--alpha', '--beta=2']) # Posix style via POSIXLY_CORRECT self.env["POSIXLY_CORRECT"] = "1" opts, args = getopt.gnu_getopt(cmdline, 'ab:', ['alpha', 'beta=']) self.assertEqual(opts, [('-a', '')]) self.assertEqual(args, ['arg1', '-b', '1', '--alpha', '--beta=2']) def test_libref_examples(self): s = """ Examples from the Library Reference: Doc/lib/libgetopt.tex An example using only Unix style options: >>> import getopt >>> args = '-a -b -cfoo -d bar a1 a2'.split() >>> args ['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2'] >>> optlist, args = getopt.getopt(args, 'abc:d:') >>> optlist [('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')] >>> args ['a1', 'a2'] Using long option names is equally easy: >>> s = '--condition=foo --testing --output-file abc.def -x a1 a2' >>> args = s.split() >>> args ['--condition=foo', '--testing', '--output-file', 'abc.def', '-x', 'a1', 'a2'] >>> optlist, args = getopt.getopt(args, 'x', [ ... 'condition=', 'output-file=', 'testing']) >>> optlist [('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x', '')] >>> args ['a1', 'a2'] """ import types m = types.ModuleType("libreftest", s) run_doctest(m, verbose) def test_issue4629(self): longopts, shortopts = getopt.getopt(['--help='], '', ['help=']) self.assertEqual(longopts, [('--help', '')]) longopts, shortopts = getopt.getopt(['--help=x'], '', ['help=']) self.assertEqual(longopts, [('--help', 'x')]) self.assertRaises(getopt.GetoptError, getopt.getopt, ['--help='], '', ['help']) if __name__ == "__main__": unittest.main()
3,629
open all channels
""" Driver for the Keithley S46 RF switch """ import re from itertools import product from typing import Any, Optional from qcodes.instrument import Instrument, VisaInstrument from qcodes.parameters import Parameter, ParamRawDataType class KeithleyS46LockAcquisitionError(Exception): pass class KeithleyS46RelayLock: """ The S46 either has six pole or a four pole relays. For example, channels 'A1' to 'A6' are all on relay 'A'. However, channels 'R1' to 'R8' are all on individual relays. Only one channel per relay may be closed at any given time to prevent degradation of RF performance and even switch damage. See page 2-11 of the manual. To enforce this, a lock mechanism has been implemented. """ def __init__(self, relay_name: str): self.relay_name = relay_name self._locked_by: Optional[int] = None def acquire(self, channel_number: int) -> None: """ Request a lock acquisition """ if self._locked_by is not None and self._locked_by != channel_number: raise KeithleyS46LockAcquisitionError( f"Relay {self.relay_name} is already in use by channel " f"{self._locked_by}" ) else: self._locked_by = channel_number def release(self, channel_number: int) -> None: """ Release a lock. """ if self._locked_by == channel_number: self._locked_by = None class S46Parameter(Parameter): """ A parameter class for S46 channels. We do not use the QCoDeS InstrumentChannel class because our channel has one state parameter, which can either be "open" or "close". Args: name instrument channel_number lock: Acquire the lock when closing and release when opening """ def __init__( self, name: str, instrument: Optional[Instrument], channel_number: int, lock: KeithleyS46RelayLock, **kwargs: Any, ): super().__init__(name, instrument, **kwargs) self._lock = lock self._channel_number = channel_number if self._get(get_cached=True) == "close": try: self._lock.acquire(self._channel_number) except KeithleyS46LockAcquisitionError as e: raise RuntimeError( "The driver is initialized from an undesirable instrument " "state where more then one channel on a single relay is " "closed. It is advised to power cycle the instrument. " "Refusing to initialize driver!" ) from e def _get(self, get_cached: bool) -> str: assert isinstance(self.instrument, KeithleyS46) closed_channels = self.instrument.closed_channels.get_latest() if not get_cached or closed_channels is None: closed_channels = self.instrument.closed_channels.get() return "close" if self.name in closed_channels else "open" def get_raw(self) -> ParamRawDataType: return self._get(get_cached=False) def set_raw(self, value: ParamRawDataType) -> None: if value == "close": self._lock.acquire(self._channel_number) elif value == "open": self._lock.release(self._channel_number) if self.instrument is None: raise RuntimeError( "Cannot set the value on a parameter " "that is not attached to an instrument." ) self.instrument.write(f":{value} (@{self._channel_number})") def is_closed(self) -> bool: """ Returns: True if channels is closed, False otherwise. """ return self.get() == "close" @property def channel_number(self) -> int: return self._channel_number class KeithleyS46(VisaInstrument): relay_names: list[str] = ["A", "B", "C", "D"] + [f"R{j}" for j in range(1, 9)] # Make a dictionary where keys are channel aliases (e.g. 'A1', 'B3', etc) # and values are corresponding channel numbers. channel_numbers: dict[str, int] = { f"{a}{b}": count + 1 for count, (a, b) in enumerate(product(["A", "B", "C", "D"], range(1, 7))) } channel_numbers.update({f"R{i}": i + 24 for i in range(1, 9)}) # Make a reverse dict for efficient alias lookup given a channel number aliases = {v: k for k, v in channel_numbers.items()} def __init__(self, name: str, address: str, **kwargs: Any): super().__init__(name, address, terminator="\n", **kwargs) self.add_parameter( "closed_channels", get_cmd=":CLOS?", get_parser=self._get_closed_channels_parser, ) self._available_channels: list[str] = [] for relay_name, channel_count in zip( KeithleyS46.relay_names, self.relay_layout ): relay_lock = KeithleyS46RelayLock(relay_name) for channel_index in range(1, channel_count + 1): # E.g. For channel 'B2', channel_index is 2 if channel_count > 1: alias = f"{relay_name}{channel_index}" else: alias = relay_name # For channels R1 to R8, we have one # channel per relay. Channel alias = relay name self.add_parameter( alias, channel_number=KeithleyS46.channel_numbers[alias], lock=relay_lock, parameter_class=S46Parameter, ) self._available_channels.append(alias) @staticmethod def _get_closed_channels_parser(reply: str) -> list[str]: """ The SCPI command ":CLOS ?" returns a reply in the form "(@1,9)", if channels 1 and 9 are closed. Return a list of strings, representing the aliases of the closed channels """ closed_channels_str = re.findall(r"\d+", reply) return [KeithleyS46.aliases[int(i)] for i in closed_channels_str] def METHOD_NAME(self) -> None: for channel_name in self.closed_channels(): self.parameters[channel_name].set("open") @property def relay_layout(self) -> list[int]: """ The relay layout tells us how many channels we have per relay. Note that we can have zero channels per relay. """ return [int(i) for i in self.ask(":CONF:CPOL?").split(",")] @property def available_channels(self) -> list[str]: return self._available_channels
3,630
mass erase
# Test user script. @command(help="test command") def testcmd(f: float, i: int, s: str): assert isinstance(f, float) assert isinstance(i, int) assert isinstance(s, str) @command("anothertestcmd", help="second test command") def testcmd2(*args): assert isinstance(args, tuple) assert all(isinstance(s, str) for s in args) # Provides stub implementations of all hooks. def will_connect(board): """@brief Pre-init hook for the board. @param self @param board A Board instance that is about to be initialized. @return Ignored. """ pass def did_connect(board): """@brief Post-initialization hook for the board. @param self @param board A Board instance. @return Ignored. """ pass def will_init_target(target, init_sequence): """@brief Hook to review and modify init call sequence prior to execution. @param self @param target A CoreSightTarget object about to be initialized. @param init_sequence The CallSequence that will be invoked. Because call sequences are mutable, this parameter can be modified before return to change the init calls. @return Ignored. """ pass def did_init_target(target): """@brief Post-initialization hook. @param self @param target A CoreSightTarget. @return Ignored. """ pass def will_start_debug_core(core): """@brief Hook to enable debug for the given core. @param self @param core A CortexM object about to be initialized. @retval True Do not perform the normal procedure to start core debug. @retval "False or None" Continue with normal behaviour. """ pass def did_start_debug_core(core): """@brief Post-initialization hook. @param self @param core A CortexM object. @return Ignored. """ pass def will_stop_debug_core(core): """@brief Pre-cleanup hook for the core. @param self @param core A CortexM object. @retval True Do not perform the normal procedure to disable core debug. @retval "False or None" Continue with normal behaviour. """ pass def did_stop_debug_core(core): """@brief Post-cleanup hook for the core. @param self @param core A CortexM object. @return Ignored. """ pass def will_disconnect(target, resume): """@brief Pre-disconnect hook. @param self @param target Either a CoreSightTarget or CortexM object. @param resume The value of the `disconnect_on_resume` option. @return Ignored. """ pass def did_disconnect(target, resume): """@brief Post-disconnect hook. @param self @param target Either a CoreSightTarget or CortexM object. @param resume The value of the `disconnect_on_resume` option. @return Ignored.""" pass def will_reset(core, reset_type): """@brief Pre-reset hook. @param self @param core A CortexM instance. @param reset_type One of the Target.ResetType enumerations. @retval True @retval "False or None" """ pass def did_reset(core, reset_type): """@brief Post-reset hook. @param self @param core A CortexM instance. @param reset_type One of the Target.ResetType enumerations. @return Ignored. """ pass def set_reset_catch(core, reset_type): """@brief Hook to prepare target for halting on reset. @param self @param core A CortexM instance. @param reset_type One of the Target.ResetType enumerations. @retval True @retval "False or None" """ pass def clear_reset_catch(core, reset_type): """@brief Hook to clean up target after a reset and halt. @param self @param core A CortexM instance. @param reset_type @return Ignored. """ pass def METHOD_NAME(target): """@brief Hook to override mass erase. @param self @param target A CoreSightTarget object. @retval True Indicate that mass erase was performed by the hook. @retval "False or None" Mass erase was not overridden and the caller should proceed with the standard mass erase procedure. """ pass def trace_start(target, mode): """@brief Hook to prepare for tracing the target. @param self @param target A CoreSightTarget object. @param mode The trace mode. Currently always 0 to indicate SWO. @return Ignored. """ pass def trace_stop(target, mode): """@brief Hook to clean up after tracing the target. @param self @param target A CoreSightTarget object. @param mode The trace mode. Currently always 0 to indicate SWO. @return Ignored. """ pass
3,631
ok clicked
import string from PyQt5 import QtCore, QtGui from PyQt5.QtWidgets import * import envi.memory as e_mem import envi.const as e_const import envi.memcanvas as e_canvas import envi.memcanvas.renderers as e_render from vqt.main import getSaveFileName class MemSearchDialog(QDialog): ''' gui for search cli command. ''' def __init__(self): QDialog.__init__(self) self.modes = ['ascii', 'hex', 'regex', 'utf-8', 'utf-16-le', 'utf-16-be'] self.pattern = None self.filename = None rend = e_render.ByteRend() self.canvas = e_canvas.StringMemoryCanvas(None) self.canvas.addRenderer('bytes', rend) hbox1 = QHBoxLayout() mode_label = QLabel('Input: ') self.mode_combo = QComboBox() self.mode_combo.addItems(self.modes) self.mode_combo.currentIndexChanged.connect(self.encodingChanged) hbox1.addWidget(mode_label) hbox1.addWidget(self.mode_combo, alignment=QtCore.Qt.AlignLeft) hbox1.addStretch(1) hbox2 = QHBoxLayout() data_label = QLabel('Bytes: ') self.data_edit = QLineEdit() hbox2.addWidget(data_label) hbox2.addWidget(self.data_edit) vbox1 = QVBoxLayout() vbox1.addLayout(hbox1) vbox1.addLayout(hbox2) gbox1 = QGroupBox('Search Criteria') gbox1.setLayout(vbox1) hbox3 = QHBoxLayout() vbox_hex_label = QVBoxLayout() # for align to top. hex_label = QLabel('Hex: ') vbox_hex_label.addWidget(hex_label, alignment=QtCore.Qt.AlignTop) self.hex_edit = QPlainTextEdit() self.hex_edit.setReadOnly(True) font = QtGui.QFont('Courier') # should use actual memcanvas. self.hex_edit.setFont(font) hbox3.addLayout(vbox_hex_label) hbox3.addWidget(self.hex_edit) vbox2 = QVBoxLayout() vbox2.addLayout(hbox3) gbox2 = QGroupBox('Bytes to Search For') gbox2.setLayout(vbox2) hbox4 = QHBoxLayout() save_check = QCheckBox('Save Search Results') save_check.stateChanged.connect(self.checkChanged) self.fname_label = QLabel('') buttons = QDialogButtonBox() buttons.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) buttons.accepted.connect(self.METHOD_NAME) buttons.rejected.connect(self.cancelClicked) hbox4.addWidget(save_check) hbox4.addWidget(self.fname_label) hbox4.addWidget(buttons) vbox = QVBoxLayout() vbox.addWidget(gbox1) vbox.addWidget(gbox2) vbox.addLayout(hbox4) self.setLayout(vbox) self.setWindowTitle('Memory Search') self.resize(650, 300) self.data_edit.setFocus() def keyReleaseEvent(self, event): encoding = self.mode_combo.currentText() self.encodingChanged(None) def checkChanged(self, state): if state == QtCore.Qt.Checked: self.showSaveAsDialog() else: self.fname_label.setText('') def encodingChanged(self, idx): encoding = str(self.mode_combo.currentText()) validator = None if encoding == 'hex': # only clear the box if there are non-hex chars # before setting the validator. txt = str(self.data_edit.text()) if not all(c in string.hexdigits for c in txt): self.data_edit.setText('') regex = QtCore.QRegExp('^[0-9A-Fa-f]+$') validator = QtGui.QRegExpValidator(regex) self.data_edit.setValidator(validator) txt = str(self.data_edit.text()) txt_encoded = self.encodeData(txt, encoding) self.updateHexPreview(txt_encoded) def encodeData(self, txt, encoding): if encoding == 'hex' and (len(txt) % 2) != 0: txt = txt[:-1] # trim last if odd length if encoding == 'hex': if not all(c in string.hexdigits for c in txt): return None return txt.decode(encoding) elif encoding == 'regex': return None return txt.encode(encoding) def updateHexPreview(self, bytez): if bytez is None: self.hex_edit.setPlainText('') return self.canvas.clearCanvas() mem = e_mem.MemoryObject() mem.addMemoryMap(0, e_const.MM_READ, b'', bytez) self.canvas.mem = mem self.canvas.renderMemory(0, len(bytez)) self.hex_edit.setPlainText(str(self.canvas)) def showSaveAsDialog(self): fname = str(getSaveFileName(caption='Select file to save results to')) self.fname_label.setText(fname) def cancelClicked(self): self.close() def METHOD_NAME(self): self.pattern = (self.data_edit.text()) self.filename = str(self.fname_label.text()) self.accept() self.close() def getResults(self): return self.pattern, self.filename
3,632
filter ac
#!/usr/bin/env python # # Copyright (C) 2018 Gautier Hattenberger <gautier.hattenberger@enac.fr> # # This file is part of paparazzi. # # paparazzi is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # # paparazzi is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with paparazzi; see the file COPYING. If not, see # <http://www.gnu.org/licenses/>. # ''' Get air traffic information from the opensky-network system (https://opensky-network.org/) The python API is required and should be installed using the instruction from https://github.com/openskynetwork/opensky-api Positions of the UAVs are used to request for the surrounding aircraft and INTRUDER messages are sent to the IVY bus for display in the GCS ''' from __future__ import print_function import sys from os import path, getenv from time import sleep, time from opensky_api import OpenSkyApi # if PAPARAZZI_HOME not set, then assume the tree containing this # file is a reasonable substitute PPRZ_HOME = getenv("PAPARAZZI_HOME", path.normpath(path.join(path.dirname(path.abspath(__file__)), '../../../..'))) sys.path.append(PPRZ_HOME + "/var/lib/python") from pprzlink.ivy import IvyMessagesInterface from pprzlink.message import PprzMessage class OpenSkyTraffic(object): def __init__(self, period=10., margin=1., timeout=60., verbose=False): self.period = period self.margin = margin self.timeout = timeout self.last_receive = time() self.verbose = verbose self._interface = IvyMessagesInterface("OpenSkyTraffic") self._opensky = OpenSkyApi() self.ac_list = {} self.intruder_list = {} self.running = False if self.verbose: print("Starting opensky interface...") # subscribe to FLIGHT_PARAM ground message self._interface.subscribe(self.update_ac, PprzMessage("ground", "FLIGHT_PARAM")) def stop(self): if self.verbose: print("Shutting down opensky interface...") self.running = False if self._interface is not None: self._interface.shutdown() def __del__(self): self.stop() def update_ac(self, ac_id, msg): # update A/C info self.last_receive = time() self.ac_list[ac_id] = (self.last_receive, float(msg['lat']), float(msg['long'])) def METHOD_NAME(self): # purge timeout A/C timeout = time() - self.timeout for ac, (t, lat, lon) in self.ac_list.items(): if t < timeout: del self.ac_list[ac] def compute_bbox_list(self): bbox = [] # for now assume that all UAVs are close enough, so merge all boxes into one # future improvement could handle groups of UAVs far appart lat_min, lat_max, lon_min, lon_max = None, None, None, None for ac, (t, lat, lon) in self.ac_list.items(): if lat_min is None: lat_min = lat lat_max = lat lon_min = lon lon_max = lon else: lat_min = min(lat, lat_min) lat_max = max(lat, lat_max) lon_min = min(lon, lon_min) lon_max = max(lon, lon_max) if lat_min is not None: bbox.append((lat_min-self.margin, lat_max+self.margin, lon_min-self.margin, lon_max+self.margin)) return bbox def get_intruders(self): self.METHOD_NAME() bbox = self.compute_bbox_list() # request surounding aircraft to opensky-network self.intruder_list = {} for bb in bbox: states = self._opensky.get_states(bbox=bb) if states is not None: for s in states.states: self.intruder_list[s.callsign] = s def send_intruder_msgs(self): self.get_intruders() def val_or_default(val, default): if val is None: return default else: return val for i in self.intruder_list: intruder = self.intruder_list[i] if intruder.callsign is not None and len(intruder.callsign) > 0: msg = PprzMessage("ground", "INTRUDER") msg['id'] = intruder.icao24 msg['name'] = intruder.callsign.replace(" ", "") msg['lat'] = int(intruder.latitude * 1e7) msg['lon'] = int(intruder.longitude * 1e7) msg['alt'] = int(val_or_default(intruder.geo_altitude, 0.) * 1000.) msg['course'] = val_or_default(intruder.heading, 0.) msg['speed'] = val_or_default(intruder.velocity, 0.) msg['climb'] = val_or_default(intruder.vertical_rate, 0.) msg['itow'] = intruder.time_position if self.verbose: print(msg) self._interface.send(msg) def run(self): try: self.running = True t = 0. while self.running: t = t + 0.1 # increment timer until next update time is reach if t > self.period: self.send_intruder_msgs() t = 0. sleep(0.1) # wait a short time except KeyboardInterrupt: self.stop() except Exception as e: print("Failing with: "+str(e)) self.stop() if __name__ == '__main__': import argparse parser = argparse.ArgumentParser(description="OpenSky-Network traffic information") parser.add_argument('-p', '--period', dest='period', default=10., type=float, help="update period") parser.add_argument('-m', '--margin', dest='margin', default=1., type=float, help="margin in degree to define the bounding box") parser.add_argument('-t', '--timeout', dest='timeout', default=60., type=float, help="timeout to remove A/C") parser.add_argument('-v', '--verbose', dest='verbose', default=False, action='store_true', help="display debug messages") args = parser.parse_args() osn = OpenSkyTraffic(args.period, args.margin, args.timeout, args.verbose) osn.run()
3,633
test outside component root request
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022) # # 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 mock import tornado.testing import tornado.web from streamlit.components.v1.components import ComponentRegistry, declare_component from streamlit.web.server import ComponentRequestHandler URL = "http://not.a.real.url:3001" PATH = "not/a/real/path" class ComponentRequestHandlerTest(tornado.testing.AsyncHTTPTestCase): """Test /component endpoint.""" def tearDown(self) -> None: ComponentRegistry._instance = None super().tearDown() def get_app(self): ComponentRegistry._instance = None return tornado.web.Application( [ ( "/component/(.*)", ComponentRequestHandler, dict(registry=ComponentRegistry.instance()), ) ] ) def _request_component(self, path): return self.fetch("/component/%s" % path, method="GET") def test_success_request(self): """Test request success when valid parameters are provided.""" with mock.patch("streamlit.components.v1.components.os.path.isdir"): # We don't need the return value in this case. declare_component("test", path=PATH) with mock.patch( "streamlit.web.server.component_request_handler.open", mock.mock_open(read_data="Test Content"), ): response = self._request_component( "tests.streamlit.web.server.component_request_handler_test.test" ) self.assertEqual(200, response.code) self.assertEqual(b"Test Content", response.body) def METHOD_NAME(self): """Tests to ensure a path based on the root directory (and therefore outside of the component root) is disallowed.""" with mock.patch("streamlit.components.v1.components.os.path.isdir"): # We don't need the return value in this case. declare_component("test", path=PATH) response = self._request_component( "tests.streamlit.web.server.component_request_handler_test.test//etc/hosts" ) self.assertEqual(403, response.code) self.assertEqual(b"forbidden", response.body) def test_relative_outside_component_root_request(self): """Tests to ensure a path relative to the component root directory (and specifically outside of the component root) is disallowed.""" with mock.patch("streamlit.components.v1.components.os.path.isdir"): # We don't need the return value in this case. declare_component("test", path=PATH) response = self._request_component( "tests.streamlit.web.server.component_request_handler_test.test/../foo" ) self.assertEqual(403, response.code) self.assertEqual(b"forbidden", response.body) def test_symlink_outside_component_root_request(self): """Tests to ensure a path symlinked to a file outside the component root directory is disallowed.""" with mock.patch("streamlit.components.v1.components.os.path.isdir"): # We don't need the return value in this case. declare_component("test", path=PATH) with mock.patch( "streamlit.web.server.component_request_handler.os.path.realpath", side_effect=[PATH, "/etc/hosts"], ): response = self._request_component( "tests.streamlit.web.server.component_request_handler_test.test" ) self.assertEqual(403, response.code) self.assertEqual(b"forbidden", response.body) def test_invalid_component_request(self): """Test request failure when invalid component name is provided.""" response = self._request_component("invalid_component") self.assertEqual(404, response.code) self.assertEqual(b"not found", response.body) def test_invalid_content_request(self): """Test request failure when invalid content (file) is provided.""" with mock.patch("streamlit.components.v1.components.os.path.isdir"): declare_component("test", path=PATH) with mock.patch("streamlit.web.server.component_request_handler.open") as m: m.side_effect = OSError("Invalid content") response = self._request_component( "tests.streamlit.web.server.component_request_handler_test.test" ) self.assertEqual(404, response.code) self.assertEqual( b"read error", response.body, ) def test_support_binary_files_request(self): """Test support for binary files reads.""" def _open_read(m, payload): is_binary = False args, kwargs = m.call_args if len(args) > 1: if "b" in args[1]: is_binary = True encoding = "utf-8" if "encoding" in kwargs: encoding = kwargs["encoding"] if is_binary: from io import BytesIO return BytesIO(payload) else: from io import TextIOWrapper return TextIOWrapper(str(payload, encoding=encoding)) with mock.patch("streamlit.components.v1.components.os.path.isdir"): declare_component("test", path=PATH) payload = b"\x00\x01\x00\x00\x00\x0D\x00\x80" # binary non utf-8 payload with mock.patch("streamlit.web.server.component_request_handler.open") as m: m.return_value.__enter__ = lambda _: _open_read(m, payload) response = self._request_component( "tests.streamlit.web.server.component_request_handler_test.test" ) self.assertEqual(200, response.code) self.assertEqual( payload, response.body, )
3,634
test delete and contains
import copy import unittest from scrapy.http import Headers class HeadersTest(unittest.TestCase): def assertSortedEqual(self, first, second, msg=None): return self.assertEqual(sorted(first), sorted(second), msg) def test_basics(self): h = Headers({"Content-Type": "text/html", "Content-Length": 1234}) assert h["Content-Type"] assert h["Content-Length"] self.assertRaises(KeyError, h.__getitem__, "Accept") self.assertEqual(h.get("Accept"), None) self.assertEqual(h.getlist("Accept"), []) self.assertEqual(h.get("Accept", "*/*"), b"*/*") self.assertEqual(h.getlist("Accept", "*/*"), [b"*/*"]) self.assertEqual( h.getlist("Accept", ["text/html", "images/jpeg"]), [b"text/html", b"images/jpeg"], ) def test_single_value(self): h = Headers() h["Content-Type"] = "text/html" self.assertEqual(h["Content-Type"], b"text/html") self.assertEqual(h.get("Content-Type"), b"text/html") self.assertEqual(h.getlist("Content-Type"), [b"text/html"]) def test_multivalue(self): h = Headers() h["X-Forwarded-For"] = hlist = ["ip1", "ip2"] self.assertEqual(h["X-Forwarded-For"], b"ip2") self.assertEqual(h.get("X-Forwarded-For"), b"ip2") self.assertEqual(h.getlist("X-Forwarded-For"), [b"ip1", b"ip2"]) assert h.getlist("X-Forwarded-For") is not hlist def test_multivalue_for_one_header(self): h = Headers((("a", "b"), ("a", "c"))) self.assertEqual(h["a"], b"c") self.assertEqual(h.get("a"), b"c") self.assertEqual(h.getlist("a"), [b"b", b"c"]) def test_encode_utf8(self): h = Headers({"key": "\xa3"}, encoding="utf-8") key, val = dict(h).popitem() assert isinstance(key, bytes), key assert isinstance(val[0], bytes), val[0] self.assertEqual(val[0], b"\xc2\xa3") def test_encode_latin1(self): h = Headers({"key": "\xa3"}, encoding="latin1") key, val = dict(h).popitem() self.assertEqual(val[0], b"\xa3") def test_encode_multiple(self): h = Headers({"key": ["\xa3"]}, encoding="utf-8") key, val = dict(h).popitem() self.assertEqual(val[0], b"\xc2\xa3") def METHOD_NAME(self): h = Headers() h["Content-Type"] = "text/html" assert "Content-Type" in h del h["Content-Type"] assert "Content-Type" not in h def test_setdefault(self): h = Headers() hlist = ["ip1", "ip2"] olist = h.setdefault("X-Forwarded-For", hlist) assert h.getlist("X-Forwarded-For") is not hlist assert h.getlist("X-Forwarded-For") is olist h = Headers() olist = h.setdefault("X-Forwarded-For", "ip1") self.assertEqual(h.getlist("X-Forwarded-For"), [b"ip1"]) assert h.getlist("X-Forwarded-For") is olist def test_iterables(self): idict = {"Content-Type": "text/html", "X-Forwarded-For": ["ip1", "ip2"]} h = Headers(idict) self.assertDictEqual( dict(h), {b"Content-Type": [b"text/html"], b"X-Forwarded-For": [b"ip1", b"ip2"]}, ) self.assertSortedEqual(h.keys(), [b"X-Forwarded-For", b"Content-Type"]) self.assertSortedEqual( h.items(), [(b"X-Forwarded-For", [b"ip1", b"ip2"]), (b"Content-Type", [b"text/html"])], ) self.assertSortedEqual(h.values(), [b"ip2", b"text/html"]) def test_update(self): h = Headers() h.update({"Content-Type": "text/html", "X-Forwarded-For": ["ip1", "ip2"]}) self.assertEqual(h.getlist("Content-Type"), [b"text/html"]) self.assertEqual(h.getlist("X-Forwarded-For"), [b"ip1", b"ip2"]) def test_copy(self): h1 = Headers({"header1": ["value1", "value2"]}) h2 = copy.copy(h1) self.assertEqual(h1, h2) self.assertEqual(h1.getlist("header1"), h2.getlist("header1")) assert h1.getlist("header1") is not h2.getlist("header1") assert isinstance(h2, Headers) def test_appendlist(self): h1 = Headers({"header1": "value1"}) h1.appendlist("header1", "value3") self.assertEqual(h1.getlist("header1"), [b"value1", b"value3"]) h1 = Headers() h1.appendlist("header1", "value1") h1.appendlist("header1", "value3") self.assertEqual(h1.getlist("header1"), [b"value1", b"value3"]) def test_setlist(self): h1 = Headers({"header1": "value1"}) self.assertEqual(h1.getlist("header1"), [b"value1"]) h1.setlist("header1", [b"value2", b"value3"]) self.assertEqual(h1.getlist("header1"), [b"value2", b"value3"]) def test_setlistdefault(self): h1 = Headers({"header1": "value1"}) h1.setlistdefault("header1", ["value2", "value3"]) h1.setlistdefault("header2", ["value2", "value3"]) self.assertEqual(h1.getlist("header1"), [b"value1"]) self.assertEqual(h1.getlist("header2"), [b"value2", b"value3"]) def test_none_value(self): h1 = Headers() h1["foo"] = "bar" h1["foo"] = None h1.setdefault("foo", "bar") self.assertEqual(h1.get("foo"), None) self.assertEqual(h1.getlist("foo"), []) def test_int_value(self): h1 = Headers({"hey": 5}) h1["foo"] = 1 h1.setdefault("bar", 2) h1.setlist("buz", [1, "dos", 3]) self.assertEqual(h1.getlist("foo"), [b"1"]) self.assertEqual(h1.getlist("bar"), [b"2"]) self.assertEqual(h1.getlist("buz"), [b"1", b"dos", b"3"]) self.assertEqual(h1.getlist("hey"), [b"5"]) def test_invalid_value(self): self.assertRaisesRegex( TypeError, "Unsupported value type", Headers, {"foo": object()} ) self.assertRaisesRegex( TypeError, "Unsupported value type", Headers().__setitem__, "foo", object() ) self.assertRaisesRegex( TypeError, "Unsupported value type", Headers().setdefault, "foo", object() ) self.assertRaisesRegex( TypeError, "Unsupported value type", Headers().setlist, "foo", [object()] )
3,635
get beam divergence ver
# -*- coding: utf-8 -*- """ [Name] BeamInfo [Description] BeamInfo hardware object informs mxCuBE (HutchMenuBrick) about the beam position and size. This is the Soleil PX1 version [Emited signals] beamInfoChanged beamPosChanged [Included Hardware Objects] [Example XML file] <device class = "BeaminfoPX2"> <username>Beamstop</username> <channel type="tango" tangoname="i11-ma-cx1/ex/md2" polling="1000" name="beamsizex">BeamSizeHorizontal</channel> <channel type="tango" tangoname="i11-ma-cx1/ex/md2" polling="1000" name="beamsizey">BeamSizeVertical</channel> <channel type="tango" tangoname="i11-ma-cx1/ex/md2" polling="1000" name="positionx">BeamPositionHorizontal</channel> <channel type="tango" tangoname="i11-ma-cx1/ex/md2" polling="1000" name="positiony">BeamPositionVertical</channel> <object role="zoom" hwrid="/zoom"></object> </device> """ import logging from mxcubecore.BaseHardwareObjects import Equipment class PX2BeamInfo(Equipment): def __init__(self, *args): Equipment.__init__(self, *args) self.beam_position = [328, 220] # [None, None] self.beam_size = [0.010, 0.005] # [None, None] self.shape = "rectangular" self.beam_info_dict = {"size_x": None, "size_y": None, "shape": self.shape} self.beam_info_dict["size_x"] = 0.010 self.beam_info_dict["size_y"] = 0.005 self.beam_info_dict["shape"] = "ellipse" # Channels self.chanBeamSizeX = None self.chanBeamSizeY = None self.chanBeamPosX = None self.chanBeamPosY = None # Zoom motor self.zoomMotor = None # self.minidiff = None self.positionTable = {} def init(self): try: self.chanBeamSizeX = self.get_channel_object("beamsizex") self.chanBeamSizeX.connect_signal("update", self.beamSizeXChanged) except KeyError: logging.getLogger().warning( "%s: cannot connect to beamsize x channel ", self.name() ) try: self.chanBeamSizeY = self.get_channel_object("beamsizey") self.chanBeamSizeY.connect_signal("update", self.beamSizeYChanged) except KeyError: logging.getLogger().warning( "%s: cannot connect to beamsize y channel ", self.name() ) try: self.chanBeamPosX = self.get_channel_object("positionx") self.chanBeamPosX.connect_signal("update", self.beamPosXChanged) except KeyError: logging.getLogger().warning( "%s: cannot connect to beamposition x channel ", self.name() ) try: self.chanBeamPosY = self.get_channel_object("positiony") self.chanBeamPosY.connect_signal("update", self.beamPosYChanged) except KeyError: logging.getLogger().warning( "%s: cannot connect to beamposition z channel ", self.name() ) self.zoomMotor = self.get_deviceby_role("zoom") self.beam_position[0], self.beam_position[1] = ( self.chanBeamPosX.value, self.chanBeamPosY.value, ) if self.zoomMotor is not None: self.connect( self.zoomMotor, "predefinedPositionChanged", self.zoomPositionChanged ) else: logging.getLogger().info("Zoom - motor is not good ") def beamSizeXChanged(self, value): logging.getLogger().info("beamSizeX changed. It is %s " % value) self.beam_size[0] = value self.sizeUpdated() def beamSizeYChanged(self, value): logging.getLogger().info("beamSizeY changed. It is %s " % value) self.beam_size[1] = value self.sizeUpdated() def beamPosXChanged(self, value): logging.getLogger().info("beamPosX changed. It is %s " % value) self.beam_position[0] = value self.positionUpdated() def beamPosYChanged(self, value): logging.getLogger().info("beamPosY changed. It is %s " % value) self.beam_position[1] = value self.positionUpdated() def zoomPositionChanged(self, name, offset): logging.getLogger().info( "zoom position changed. It is %s / offset=%s " % (name, offset) ) self.beam_position[0], self.beam_position[1] = ( self.chanBeamPosX.value, self.chanBeamPosY.value, ) def sizeUpdated(self): # TODO check values give by md2 it appears that beamSizeXChanged beamSize self.beam_info_dict["size_x"] = 0.010 # in micro channel in MD2 doesn't work self.beam_info_dict["size_y"] = 0.005 # self.emit("beamInfoChanged", (self.beam_info_dict,)) def sizeUpdated2(self): # not used if None in self.beam_size: return self.beam_info_dict["size_x"] = self.beam_size[0] self.beam_info_dict["size_y"] = self.beam_size[1] self.emit("beamInfoChanged", (self.beam_info_dict,)) def positionUpdated(self): self.emit("beamPosChanged", (self.beam_position,)) self.sizeUpdated() def get_beam_info(self): # logging.getLogger().warning('returning beam info It is %s ' % str(self.beam_info_dict)) return self.beam_info_dict def get_beam_position(self): # logging.getLogger().warning('returning beam positions. It is %s ' % str(self.beam_position)) return self.beam_position def get_beam_size(self): """ Descript. : returns beam size in millimeters Return : list with two integers """ # self.evaluate_beam_info() return self.beam_info_dict["size_x"], self.beam_info_dict["size_y"] def get_beam_shape(self): """ Descript. : Arguments : Return : """ # self.evaluate_beam_info() return self.shape def get_slit_gaps(self): return None, None def get_beam_divergence_hor(self): return self.get_property("beam_divergence_hor") def METHOD_NAME(self): return self.get_property("beam_divergence_vert")
3,636
create es infotainment
from cereal import car from openpilot.selfdrive.car.subaru.values import CanBus VisualAlert = car.CarControl.HUDControl.VisualAlert def create_steering_control(packer, apply_steer, steer_req): values = { "LKAS_Output": apply_steer, "LKAS_Request": steer_req, "SET_1": 1 } return packer.make_can_msg("ES_LKAS", 0, values) def create_steering_status(packer): return packer.make_can_msg("ES_LKAS_State", 0, {}) def create_es_distance(packer, es_distance_msg, bus, pcm_cancel_cmd, long_enabled = False, brake_cmd = False, cruise_throttle = 0): values = {s: es_distance_msg[s] for s in [ "CHECKSUM", "COUNTER", "Signal1", "Cruise_Fault", "Cruise_Throttle", "Signal2", "Car_Follow", "Low_Speed_Follow", "Cruise_Soft_Disable", "Signal7", "Cruise_Brake_Active", "Distance_Swap", "Cruise_EPB", "Signal4", "Close_Distance", "Signal5", "Cruise_Cancel", "Cruise_Set", "Cruise_Resume", "Signal6", ]} values["COUNTER"] = (values["COUNTER"] + 1) % 0x10 if long_enabled: values["Cruise_Throttle"] = cruise_throttle # Do not disable openpilot on Eyesight Soft Disable, if openpilot is controlling long values["Cruise_Soft_Disable"] = 0 if brake_cmd: values["Cruise_Brake_Active"] = 1 if pcm_cancel_cmd: values["Cruise_Cancel"] = 1 values["Cruise_Throttle"] = 1818 # inactive throttle return packer.make_can_msg("ES_Distance", bus, values) def create_es_lkas_state(packer, es_lkas_state_msg, enabled, visual_alert, left_line, right_line, left_lane_depart, right_lane_depart): values = {s: es_lkas_state_msg[s] for s in [ "CHECKSUM", "COUNTER", "LKAS_Alert_Msg", "Signal1", "LKAS_ACTIVE", "LKAS_Dash_State", "Signal2", "Backward_Speed_Limit_Menu", "LKAS_Left_Line_Enable", "LKAS_Left_Line_Light_Blink", "LKAS_Right_Line_Enable", "LKAS_Right_Line_Light_Blink", "LKAS_Left_Line_Visible", "LKAS_Right_Line_Visible", "LKAS_Alert", "Signal3", ]} # Filter the stock LKAS "Keep hands on wheel" alert if values["LKAS_Alert_Msg"] == 1: values["LKAS_Alert_Msg"] = 0 # Filter the stock LKAS sending an audible alert when it turns off LKAS if values["LKAS_Alert"] == 27: values["LKAS_Alert"] = 0 # Filter the stock LKAS sending an audible alert when "Keep hands on wheel" alert is active (2020+ models) if values["LKAS_Alert"] == 28 and values["LKAS_Alert_Msg"] == 7: values["LKAS_Alert"] = 0 # Filter the stock LKAS sending an audible alert when "Keep hands on wheel OFF" alert is active (2020+ models) if values["LKAS_Alert"] == 30: values["LKAS_Alert"] = 0 # Filter the stock LKAS sending "Keep hands on wheel OFF" alert (2020+ models) if values["LKAS_Alert_Msg"] == 7: values["LKAS_Alert_Msg"] = 0 # Show Keep hands on wheel alert for openpilot steerRequired alert if visual_alert == VisualAlert.steerRequired: values["LKAS_Alert_Msg"] = 1 # Ensure we don't overwrite potentially more important alerts from stock (e.g. FCW) if visual_alert == VisualAlert.ldw and values["LKAS_Alert"] == 0: if left_lane_depart: values["LKAS_Alert"] = 12 # Left lane departure dash alert elif right_lane_depart: values["LKAS_Alert"] = 11 # Right lane departure dash alert if enabled: values["LKAS_ACTIVE"] = 1 # Show LKAS lane lines values["LKAS_Dash_State"] = 2 # Green enabled indicator else: values["LKAS_Dash_State"] = 0 # LKAS Not enabled values["LKAS_Left_Line_Visible"] = int(left_line) values["LKAS_Right_Line_Visible"] = int(right_line) return packer.make_can_msg("ES_LKAS_State", CanBus.main, values) def create_es_dashstatus(packer, dashstatus_msg, enabled, long_enabled, long_active, lead_visible): values = {s: dashstatus_msg[s] for s in [ "CHECKSUM", "COUNTER", "PCB_Off", "LDW_Off", "Signal1", "Cruise_State_Msg", "LKAS_State_Msg", "Signal2", "Cruise_Soft_Disable", "Cruise_Status_Msg", "Signal3", "Cruise_Distance", "Signal4", "Conventional_Cruise", "Signal5", "Cruise_Disengaged", "Cruise_Activated", "Signal6", "Cruise_Set_Speed", "Cruise_Fault", "Cruise_On", "Display_Own_Car", "Brake_Lights", "Car_Follow", "Signal7", "Far_Distance", "Cruise_State", ]} if enabled and long_active: values["Cruise_State"] = 0 values["Cruise_Activated"] = 1 values["Cruise_Disengaged"] = 0 values["Car_Follow"] = int(lead_visible) if long_enabled: values["PCB_Off"] = 1 # AEB is not presevered, so show the PCB_Off on dash # Filter stock LKAS disabled and Keep hands on steering wheel OFF alerts if values["LKAS_State_Msg"] in (2, 3): values["LKAS_State_Msg"] = 0 return packer.make_can_msg("ES_DashStatus", CanBus.main, values) def create_es_brake(packer, es_brake_msg, enabled, brake_value): values = {s: es_brake_msg[s] for s in [ "CHECKSUM", "COUNTER", "Signal1", "Brake_Pressure", "AEB_Status", "Cruise_Brake_Lights", "Cruise_Brake_Fault", "Cruise_Brake_Active", "Cruise_Activated", "Signal3", ]} if enabled: values["Cruise_Activated"] = 1 values["Brake_Pressure"] = brake_value if brake_value > 0: values["Cruise_Brake_Active"] = 1 values["Cruise_Brake_Lights"] = 1 if brake_value >= 70 else 0 return packer.make_can_msg("ES_Brake", CanBus.main, values) def create_es_status(packer, es_status_msg, long_enabled, long_active, cruise_rpm): values = {s: es_status_msg[s] for s in [ "CHECKSUM", "COUNTER", "Signal1", "Cruise_Fault", "Cruise_RPM", "Signal2", "Cruise_Activated", "Brake_Lights", "Cruise_Hold", "Signal3", ]} if long_enabled: values["Cruise_RPM"] = cruise_rpm if long_active: values["Cruise_Activated"] = 1 return packer.make_can_msg("ES_Status", CanBus.main, values) def METHOD_NAME(packer, es_infotainment_msg, visual_alert): # Filter stock LKAS disabled and Keep hands on steering wheel OFF alerts values = {s: es_infotainment_msg[s] for s in [ "CHECKSUM", "COUNTER", "LKAS_State_Infotainment", "LKAS_Blue_Lines", "Signal1", "Signal2", ]} if values["LKAS_State_Infotainment"] in (3, 4): values["LKAS_State_Infotainment"] = 0 # Show Keep hands on wheel alert for openpilot steerRequired alert if visual_alert == VisualAlert.steerRequired: values["LKAS_State_Infotainment"] = 3 # Show Obstacle Detected for fcw if visual_alert == VisualAlert.fcw: values["LKAS_State_Infotainment"] = 2 return packer.make_can_msg("ES_Infotainment", CanBus.main, values) # *** Subaru Pre-global *** def subaru_preglobal_checksum(packer, values, addr, checksum_byte=7): dat = packer.make_can_msg(addr, 0, values)[2] return (sum(dat[:checksum_byte]) + sum(dat[checksum_byte+1:])) % 256 def create_preglobal_steering_control(packer, frame, apply_steer, steer_req): values = { "COUNTER": frame % 0x08, "LKAS_Command": apply_steer, "LKAS_Active": steer_req, } values["Checksum"] = subaru_preglobal_checksum(packer, values, "ES_LKAS") return packer.make_can_msg("ES_LKAS", CanBus.main, values) def create_preglobal_es_distance(packer, cruise_button, es_distance_msg): values = {s: es_distance_msg[s] for s in [ "Cruise_Throttle", "Signal1", "Car_Follow", "Signal2", "Cruise_Brake_Active", "Distance_Swap", "Standstill", "Signal3", "Close_Distance", "Signal4", "Standstill_2", "Cruise_Fault", "Signal5", "COUNTER", "Signal6", "Cruise_Button", "Signal7", ]} values["Cruise_Button"] = cruise_button values["Checksum"] = subaru_preglobal_checksum(packer, values, "ES_Distance") return packer.make_can_msg("ES_Distance", CanBus.main, values)
3,637
get concept filter
# SPDX-License-Identifier: EUPL-1.2 # Copyright (C) 2019 - 2020 Dimpact from django.db.models import Q from django.utils.translation import ugettext_lazy as _ from rest_framework import viewsets from rest_framework.exceptions import ValidationError from vng_api_common.caching import conditional_retrieve from vng_api_common.viewsets import CheckQueryParamsMixin from openzaak.utils.pagination import OptimizedPagination from openzaak.utils.permissions import AuthRequired from openzaak.utils.schema import AutoSchema from ...models import ZaakTypeInformatieObjectType from ..filters import ZaakTypeInformatieObjectTypeFilter from ..scopes import ( SCOPE_CATALOGI_FORCED_DELETE, SCOPE_CATALOGI_FORCED_WRITE, SCOPE_CATALOGI_READ, SCOPE_CATALOGI_WRITE, ) from ..serializers import ZaakTypeInformatieObjectTypeSerializer from .mixins import ConceptDestroyMixin, ConceptFilterMixin class ZaakTypeInformatieObjectTypeSchema(AutoSchema): def get_operation_id(self, operation_keys=None): return f"zaakinformatieobjecttype_{operation_keys[-1]}" @conditional_retrieve() class ZaakTypeInformatieObjectTypeViewSet( CheckQueryParamsMixin, ConceptFilterMixin, ConceptDestroyMixin, viewsets.ModelViewSet, ): """ Opvragen en bewerken van ZAAKTYPE-INFORMATIEOBJECTTYPE relaties. Geeft aan welke INFORMATIEOBJECTTYPEn binnen een ZAAKTYPE mogelijk zijn en hoe de richting is. create: Maak een ZAAKTYPE-INFORMATIEOBJECTTYPE relatie aan. Maak een ZAAKTYPE-INFORMATIEOBJECTTYPE relatie aan. Dit kan alleen als het bijbehorende ZAAKTYPE een concept betreft. Er wordt gevalideerd op: - `zaaktype` en `informatieobjecttype` behoren tot dezelfde `catalogus` list: Alle ZAAKTYPE-INFORMATIEOBJECTTYPE relaties opvragen. Deze lijst kan gefilterd wordt met query-string parameters. retrieve: Een specifieke ZAAKTYPE-INFORMATIEOBJECTTYPE relatie opvragen. Een specifieke ZAAKTYPE-INFORMATIEOBJECTTYPE relatie opvragen. update: Werk een ZAAKTYPE-INFORMATIEOBJECTTYPE relatie in zijn geheel bij. Werk een ZAAKTYPE-INFORMATIEOBJECTTYPE relatie in zijn geheel bij. Dit kan alleen als het bijbehorende ZAAKTYPE een concept betreft. Er wordt gevalideerd op: - `zaaktype` en `informatieobjecttype` behoren tot dezelfde `catalogus` partial_update: Werk een ZAAKTYPE-INFORMATIEOBJECTTYPE relatie deels bij. Werk een ZAAKTYPE-INFORMATIEOBJECTTYPE relatie deels bij. Dit kan alleen als het bijbehorende ZAAKTYPE een concept betreft. Er wordt gevalideerd op: - `zaaktype` en `informatieobjecttype` behoren tot dezelfde `catalogus` destroy: Verwijder een ZAAKTYPE-INFORMATIEOBJECTTYPE relatie. Verwijder een ZAAKTYPE-INFORMATIEOBJECTTYPE relatie. Dit kan alleen als het bijbehorende ZAAKTYPE een concept betreft. Er wordt gevalideerd op: - `zaaktype` of `informatieobjecttype` is nog niet gepubliceerd """ queryset = ( ZaakTypeInformatieObjectType.objects.all() .select_related("zaaktype", "informatieobjecttype", "zaaktype__catalogus") .order_by("-pk") ) serializer_class = ZaakTypeInformatieObjectTypeSerializer filterset_class = ZaakTypeInformatieObjectTypeFilter lookup_field = "uuid" pagination_class = OptimizedPagination permission_classes = (AuthRequired,) required_scopes = { "list": SCOPE_CATALOGI_READ, "retrieve": SCOPE_CATALOGI_READ, "create": SCOPE_CATALOGI_WRITE | SCOPE_CATALOGI_FORCED_WRITE, "update": SCOPE_CATALOGI_WRITE | SCOPE_CATALOGI_FORCED_WRITE, "partial_update": SCOPE_CATALOGI_WRITE | SCOPE_CATALOGI_FORCED_WRITE, "destroy": SCOPE_CATALOGI_WRITE | SCOPE_CATALOGI_FORCED_DELETE, } swagger_schema = ZaakTypeInformatieObjectTypeSchema def get_concept(self, instance): ziot = self.get_object() zaaktype = getattr(instance, "zaaktype", None) or ziot.zaaktype informatieobjecttype = ( getattr(instance, "informatieobjecttype", None) or ziot.informatieobjecttype ) return zaaktype.concept or informatieobjecttype.concept def METHOD_NAME(self): return ~(Q(zaaktype__concept=True) | Q(informatieobjecttype__concept=True)) def perform_destroy(self, instance): forced_delete = self.request.jwt_auth.has_auth( scopes=SCOPE_CATALOGI_FORCED_DELETE, init_component=self.queryset.model._meta.app_label, ) if not forced_delete: if not self.get_concept(instance): msg = _("Objects related to non-concept objects can't be destroyed") raise ValidationError( {"nonFieldErrors": msg}, code="non-concept-relation" ) super().perform_destroy(instance)
3,638
unpack uint256
############################################################################### # # The MIT License (MIT) # # Copyright (c) typedef int GmbH # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # ############################################################################### import struct from binascii import a2b_hex, b2a_hex from typing import Union, Dict, List import web3 def make_w3(gateway_config=None): """ Create a Web3 instance configured and ready-to-use gateway to the blockchain. :param gateway_config: Blockchain gateway configuration. :type gateway_config: dict :return: Configured Web3 instance. :rtype: :class:`web3.Web3` """ if gateway_config is None or gateway_config['type'] == 'auto': w3 = web3.Web3() elif gateway_config['type'] == 'user': request_kwargs = gateway_config.get('http_options', {}) w3 = web3.Web3(web3.Web3.HTTPProvider(gateway_config['http'], request_kwargs=request_kwargs)) elif gateway_config['type'] == 'infura': request_kwargs = gateway_config.get('http_options', {}) project_id = gateway_config['key'] # project_secret = gateway_config['secret'] http_url = 'https://{}.infura.io/v3/{}'.format(gateway_config['network'], project_id) w3 = web3.Web3(web3.Web3.HTTPProvider(http_url, request_kwargs=request_kwargs)) # https://web3py.readthedocs.io/en/stable/middleware.html#geth-style-proof-of-authority if gateway_config.get('network', None) == 'rinkeby': # This middleware is required to connect to geth --dev or the Rinkeby public network. from web3.middleware import geth_poa_middleware # inject the poa compatibility middleware to the innermost layer w3.middleware_onion.inject(geth_poa_middleware, layer=0) # FIXME elif gateway_config['type'] == 'cloudflare': # https://developers.cloudflare.com/web3/ethereum-gateway/reference/supported-networks/ raise NotImplementedError() # FIXME elif gateway_config['type'] == 'zksync': # https://v2-docs.zksync.io/dev/testnet/important-links.html raise NotImplementedError() else: raise RuntimeError('invalid blockchain gateway type "{}"'.format(gateway_config['type'])) return w3 def unpack_uint128(data): assert data is None or type(data) == bytes, 'data must by bytes, was {}'.format(type(data)) if data and type(data) == bytes: assert len(data) == 16, 'data must be bytes[16], but was bytes[{}]'.format(len(data)) if data: return web3.Web3.toInt(data) else: return 0 def pack_uint128(value): assert value is None or (type(value) == int and value >= 0 and value < 2**128) if value: data = web3.Web3.toBytes(value) return b'\x00' * (16 - len(data)) + data else: return b'\x00' * 16 def METHOD_NAME(data): assert data is None or type(data) == bytes, 'data must by bytes, was {}'.format(type(data)) if data and type(data) == bytes: assert len(data) == 32, 'data must be bytes[32], but was bytes[{}]'.format(len(data)) if data: return int(web3.Web3.toInt(data)) else: return 0 def pack_uint256(value): assert value is None or (type(value) == int and value >= 0 and value < 2**256), 'value must be uint256, but was {}'.format(value) if value: data = web3.Web3.toBytes(value) return b'\x00' * (32 - len(data)) + data else: return b'\x00' * 32 def pack_ethadr(value: Union[bytes, str], return_dict: bool = False) -> Union[List[int], Dict[str, int]]: """ :param value: :param return_dict: :return: """ if type(value) == str: if value.startswith('0x'): value_bytes = a2b_hex(value[2:]) else: value_bytes = a2b_hex(value) elif type(value) == bytes: value_bytes = value else: assert False, 'invalid type {} for value'.format(type(value)) assert len(value_bytes) == 20 w = [] for i in range(5): w.append(struct.unpack('<I', value_bytes[0 + i * 4:4 + i * 4])[0]) if return_dict: packed_value = {'w0': w[0], 'w1': w[1], 'w2': w[2], 'w3': w[3], 'w4': w[4]} else: packed_value = w return packed_value def unpack_ethadr(packed_value: Union[List[int], Dict[str, int]], return_str=False) -> Union[bytes, str]: """ :param packed_value: :param return_str: :return: """ w = [] if type(packed_value) == dict: for i in range(5): w.append(struct.pack('<I', packed_value['w{}'.format(i)])) elif type(packed_value) == list: for i in range(5): w.append(struct.pack('<I', packed_value[i])) else: assert False, 'should not arrive here' if return_str: return web3.Web3.toChecksumAddress('0x' + b2a_hex(b''.join(w)).decode()) else: return b''.join(w)
3,639
test no indent
import errno import os import sys import textwrap import unittest import subprocess from test import support from test.support import os_helper from test.support.script_helper import assert_python_ok class TestTool(unittest.TestCase): data = """ [["blorpie"],[ "whoops" ] , [ ],\t"d-shtaeou",\r"d-nthiouh", "i-vhbjkhnth", {"nifty":87}, {"morefield" :\tfalse,"field" :"yes"} ] """ expect_without_sort_keys = textwrap.dedent("""\ [ [ "blorpie" ], [ "whoops" ], [], "d-shtaeou", "d-nthiouh", "i-vhbjkhnth", { "nifty": 87 }, { "field": "yes", "morefield": false } ] """) expect = textwrap.dedent("""\ [ [ "blorpie" ], [ "whoops" ], [], "d-shtaeou", "d-nthiouh", "i-vhbjkhnth", { "nifty": 87 }, { "morefield": false, "field": "yes" } ] """) jsonlines_raw = textwrap.dedent("""\ {"ingredients":["frog", "water", "chocolate", "glucose"]} {"ingredients":["chocolate","steel bolts"]} """) jsonlines_expect = textwrap.dedent("""\ { "ingredients": [ "frog", "water", "chocolate", "glucose" ] } { "ingredients": [ "chocolate", "steel bolts" ] } """) def test_stdin_stdout(self): args = sys.executable, '-m', 'json.tool' process = subprocess.run(args, input=self.data, capture_output=True, text=True, check=True) self.assertEqual(process.stdout, self.expect) self.assertEqual(process.stderr, '') def _create_infile(self, data=None): infile = os_helper.TESTFN with open(infile, "w", encoding="utf-8") as fp: self.addCleanup(os.remove, infile) fp.write(data or self.data) return infile def test_infile_stdout(self): infile = self._create_infile() rc, out, err = assert_python_ok('-m', 'json.tool', infile) self.assertEqual(rc, 0) self.assertEqual(out.splitlines(), self.expect.encode().splitlines()) self.assertEqual(err, b'') def test_non_ascii_infile(self): data = '{"msg": "\u3053\u3093\u306b\u3061\u306f"}' expect = textwrap.dedent('''\ { "msg": "\\u3053\\u3093\\u306b\\u3061\\u306f" } ''').encode() infile = self._create_infile(data) rc, out, err = assert_python_ok('-m', 'json.tool', infile) self.assertEqual(rc, 0) self.assertEqual(out.splitlines(), expect.splitlines()) self.assertEqual(err, b'') def test_infile_outfile(self): infile = self._create_infile() outfile = os_helper.TESTFN + '.out' rc, out, err = assert_python_ok('-m', 'json.tool', infile, outfile) self.addCleanup(os.remove, outfile) with open(outfile, "r", encoding="utf-8") as fp: self.assertEqual(fp.read(), self.expect) self.assertEqual(rc, 0) self.assertEqual(out, b'') self.assertEqual(err, b'') def test_writing_in_place(self): infile = self._create_infile() rc, out, err = assert_python_ok('-m', 'json.tool', infile, infile) with open(infile, "r", encoding="utf-8") as fp: self.assertEqual(fp.read(), self.expect) self.assertEqual(rc, 0) self.assertEqual(out, b'') self.assertEqual(err, b'') def test_jsonlines(self): args = sys.executable, '-m', 'json.tool', '--json-lines' process = subprocess.run(args, input=self.jsonlines_raw, capture_output=True, text=True, check=True) self.assertEqual(process.stdout, self.jsonlines_expect) self.assertEqual(process.stderr, '') def test_help_flag(self): rc, out, err = assert_python_ok('-m', 'json.tool', '-h') self.assertEqual(rc, 0) self.assertTrue(out.startswith(b'usage: ')) self.assertEqual(err, b'') def test_sort_keys_flag(self): infile = self._create_infile() rc, out, err = assert_python_ok('-m', 'json.tool', '--sort-keys', infile) self.assertEqual(rc, 0) self.assertEqual(out.splitlines(), self.expect_without_sort_keys.encode().splitlines()) self.assertEqual(err, b'') def test_indent(self): input_ = '[1, 2]' expect = textwrap.dedent('''\ [ 1, 2 ] ''') args = sys.executable, '-m', 'json.tool', '--indent', '2' process = subprocess.run(args, input=input_, capture_output=True, text=True, check=True) self.assertEqual(process.stdout, expect) self.assertEqual(process.stderr, '') def METHOD_NAME(self): input_ = '[1,\n2]' expect = '[1, 2]\n' args = sys.executable, '-m', 'json.tool', '--no-indent' process = subprocess.run(args, input=input_, capture_output=True, text=True, check=True) self.assertEqual(process.stdout, expect) self.assertEqual(process.stderr, '') def test_tab(self): input_ = '[1, 2]' expect = '[\n\t1,\n\t2\n]\n' args = sys.executable, '-m', 'json.tool', '--tab' process = subprocess.run(args, input=input_, capture_output=True, text=True, check=True) self.assertEqual(process.stdout, expect) self.assertEqual(process.stderr, '') def test_compact(self): input_ = '[ 1 ,\n 2]' expect = '[1,2]\n' args = sys.executable, '-m', 'json.tool', '--compact' process = subprocess.run(args, input=input_, capture_output=True, text=True, check=True) self.assertEqual(process.stdout, expect) self.assertEqual(process.stderr, '') def test_no_ensure_ascii_flag(self): infile = self._create_infile('{"key":"💩"}') outfile = os_helper.TESTFN + '.out' self.addCleanup(os.remove, outfile) assert_python_ok('-m', 'json.tool', '--no-ensure-ascii', infile, outfile) with open(outfile, "rb") as f: lines = f.read().splitlines() # asserting utf-8 encoded output file expected = [b'{', b' "key": "\xf0\x9f\x92\xa9"', b"}"] self.assertEqual(lines, expected) def test_ensure_ascii_default(self): infile = self._create_infile('{"key":"💩"}') outfile = os_helper.TESTFN + '.out' self.addCleanup(os.remove, outfile) assert_python_ok('-m', 'json.tool', infile, outfile) with open(outfile, "rb") as f: lines = f.read().splitlines() # asserting an ascii encoded output file expected = [b'{', rb' "key": "\ud83d\udca9"', b"}"] self.assertEqual(lines, expected) @unittest.skipIf(sys.platform =="win32", "The test is failed with ValueError on Windows") def test_broken_pipe_error(self): cmd = [sys.executable, '-m', 'json.tool'] proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE) # bpo-39828: Closing before json.tool attempts to write into stdout. proc.stdout.close() proc.communicate(b'"{}"') self.assertEqual(proc.returncode, errno.EPIPE)
3,640
try find existing pattern by ip type
import click import ipaddress from flow_counter_util.route import FLOW_COUNTER_ROUTE_PATTERN_TABLE, FLOW_COUNTER_ROUTE_MAX_MATCH_FIELD, DEFAULT_VRF, PATTERN_SEPARATOR from flow_counter_util.route import build_route_pattern, extract_route_pattern, exit_if_route_flow_counter_not_support from utilities_common.cli import AbbreviationGroup, pass_db from utilities_common import cli # To make mock work in unit test # # 'flowcnt-route' group ('config flowcnt-route ...') # @click.group(cls=AbbreviationGroup, invoke_without_command=False) def flowcnt_route(): """Route flow counter related configuration tasks""" pass @flowcnt_route.group() def pattern(): """Set pattern for route flow counter""" pass @pattern.command(name='add') @click.option('-y', '--yes', is_flag=True) @click.option('--vrf', help='VRF/VNET name or default VRF') @click.option('--max', 'max_allowed_match', type=click.IntRange(1, 50), default=30, show_default=True, help='Max allowed match count') @click.argument('prefix-pattern', required=True) @pass_db def pattern_add(db, yes, vrf, max_allowed_match, prefix_pattern): """Add pattern for route flow counter""" _update_route_flow_counter_config(db, vrf, max_allowed_match, prefix_pattern, True, yes) @pattern.command(name='remove') @click.option('--vrf', help='VRF/VNET name or default VRF') @click.argument('prefix-pattern', required=True) @pass_db def pattern_remove(db, vrf, prefix_pattern): """Remove pattern for route flow counter""" _update_route_flow_counter_config(db, vrf, None, prefix_pattern, False) def _update_route_flow_counter_config(db, vrf, max_allowed_match, prefix_pattern, add, yes=False): """ Update route flow counter config :param db: db object :param vrf: vrf string, empty vrf will be treated as default vrf :param max_allowed_match: max allowed match count, $FLOW_COUNTER_ROUTE_MAX_MATCH_FIELD will be used if not specified :param prefix_pattern: route prefix pattern, automatically add prefix length if not specified :param add: True to add/set the configuration, otherwise remove :param yes: Don't ask question if True :return: """ exit_if_route_flow_counter_not_support() if add: try: net = ipaddress.ip_network(prefix_pattern, strict=False) except ValueError as e: click.echo('Invalid prefix pattern: {}'.format(prefix_pattern)) exit(1) if '/' not in prefix_pattern: prefix_pattern += '/' + str(net.prefixlen) key = build_route_pattern(vrf, prefix_pattern) for _, cfgdb in db.cfgdb_clients.items(): if METHOD_NAME(cfgdb, net, key, yes): entry_data = cfgdb.get_entry(FLOW_COUNTER_ROUTE_PATTERN_TABLE, key) old_max_allowed_match = entry_data.get(FLOW_COUNTER_ROUTE_MAX_MATCH_FIELD) if old_max_allowed_match is not None and int(old_max_allowed_match) == max_allowed_match: click.echo('The route pattern already exists, nothing to be changed') exit(1) cfgdb.mod_entry(FLOW_COUNTER_ROUTE_PATTERN_TABLE, key, {FLOW_COUNTER_ROUTE_MAX_MATCH_FIELD: str(max_allowed_match)}) else: found = False key = build_route_pattern(vrf, prefix_pattern) for _, cfgdb in db.cfgdb_clients.items(): pattern_table = cfgdb.get_table(FLOW_COUNTER_ROUTE_PATTERN_TABLE) for existing_key in pattern_table: exist_vrf, existing_prefix = extract_route_pattern(existing_key) if (exist_vrf == vrf or (vrf is None and exist_vrf == DEFAULT_VRF)) and existing_prefix == prefix_pattern: found = True cfgdb.set_entry(FLOW_COUNTER_ROUTE_PATTERN_TABLE, key, None) if not found: click.echo("Failed to remove route pattern: {} does not exist".format(key)) exit(1) def METHOD_NAME(cfgdb, input_net, input_key, yes): """Try to find the same IP type pattern from CONFIG DB. 1. If found a pattern with the same IP type, but the patter does not equal, ask user if need to replace the old with new one a. If user types "yes", remove the old one, return False b. If user types "no", exit 2. If found a pattern with the same IP type and the pattern equal, return True 3. If not found a pattern with the same IP type, return False Args: cfgdb (object): CONFIG DB object input_net (object): Input ip_network object input_key (str): Input key yes (bool): Whether ask user question Returns: bool: True if found the same pattern in CONFIG DB """ input_type = type(input_net) # IPv4 or IPv6 found_invalid = [] found = None pattern_table = cfgdb.get_table(FLOW_COUNTER_ROUTE_PATTERN_TABLE) for existing_key in pattern_table: if isinstance(existing_key, tuple): existing_prefix = existing_key[1] existing_key = PATTERN_SEPARATOR.join(existing_key) else: _, existing_prefix = extract_route_pattern(existing_key) # In case user configures an invalid pattern via CONFIG DB. if not existing_prefix: # Invalid pattern such as: "vrf1|" click.echo('Detect invalid route pattern in existing configuration {}'.format(existing_key)) found_invalid.append(existing_key) continue try: existing_net = ipaddress.ip_network(existing_prefix, strict=False) except ValueError as e: # Invalid pattern such as: "vrf1|invalid" click.echo('Detect invalid route pattern in existing configuration {}'.format(existing_key)) found_invalid.append(existing_key) continue if type(existing_net) == input_type: found = existing_key break if found == input_key: return True if not found and found_invalid: # If not found but there is an invalid one, ask user to replace the invalid one found = found_invalid[0] if found: if not yes: answer = cli.query_yes_no('Only support 1 IPv4 route pattern and 1 IPv6 route pattern, remove existing pattern {}?'.format(found)) else: answer = True if answer: click.echo('Replacing existing route pattern {} with {}'.format(existing_key, input_key)) cfgdb.set_entry(FLOW_COUNTER_ROUTE_PATTERN_TABLE, existing_key, None) else: exit(0) return False
3,641
build waveform
from typing import Optional, List, Union, Set, Dict, Sequence, Any, Tuple from numbers import Real import itertools import numbers import sympy import numpy as np from qupulse.utils.sympy import IndexedBroadcast from qupulse.utils.types import ChannelID from qupulse.expressions import Expression, ExpressionScalar from qupulse.program.waveforms import TableWaveform, TableWaveformEntry from qupulse.pulses.parameters import ParameterConstraint, ParameterConstrainer from qupulse.pulses.pulse_template import AtomicPulseTemplate, MeasurementDeclaration from qupulse.pulses.table_pulse_template import TableEntry, EntryInInit from qupulse.pulses.multi_channel_pulse_template import MultiChannelWaveform from qupulse.serialization import Serializer, PulseRegistryType __all__ = ["PointWaveform", "PointPulseTemplate", "PointPulseEntry", "PointWaveformEntry", "InvalidPointDimension"] PointWaveform = TableWaveform PointWaveformEntry = TableWaveformEntry class PointPulseEntry(TableEntry): def instantiate(self, parameters: Dict[str, numbers.Real], num_channels: int) -> Sequence[PointWaveformEntry]: t = self.t.evaluate_in_scope(parameters) vs = self.v.evaluate_in_scope(parameters) if isinstance(vs, numbers.Number): vs = (vs,) * num_channels elif len(vs) != num_channels: raise InvalidPointDimension(expected=num_channels, received=len(vs)) return tuple(PointWaveformEntry(t, v, self.interp) for v in vs) class PointPulseTemplate(AtomicPulseTemplate, ParameterConstrainer): def __init__(self, time_point_tuple_list: List[EntryInInit], channel_names: Sequence[ChannelID], *, parameter_constraints: Optional[List[Union[str, ParameterConstraint]]]=None, measurements: Optional[List[MeasurementDeclaration]]=None, identifier: Optional[str]=None, registry: PulseRegistryType=None) -> None: AtomicPulseTemplate.__init__(self, identifier=identifier, measurements=measurements) ParameterConstrainer.__init__(self, parameter_constraints=parameter_constraints) self._channels = tuple(channel_names) self._entries = [PointPulseEntry(*tpt) for tpt in time_point_tuple_list] self._register(registry=registry) @property def defined_channels(self) -> Set[ChannelID]: return set(self._channels) def METHOD_NAME(self, parameters: Dict[str, Real], channel_mapping: Dict[ChannelID, Optional[ChannelID]]) -> Optional[Union[TableWaveform, MultiChannelWaveform]]: self.validate_parameter_constraints(parameters=parameters, volatile=set()) if all(channel_mapping[channel] is None for channel in self.defined_channels): return None if self.duration.evaluate_in_scope(parameters) == 0: return None mapped_channels = tuple(channel_mapping[c] for c in self._channels) waveform_entries = list([] for _ in range(len(self._channels))) for entry in self._entries: instantiated_entries = entry.instantiate(parameters, len(self._channels)) for ch_entries, wf_entry in zip(waveform_entries, instantiated_entries): ch_entries.append(wf_entry) if waveform_entries[0][0].t > 0: for ch_entries in waveform_entries: ch_entries[:0] = [PointWaveformEntry(0, ch_entries[0].v, ch_entries[0].interp)] # filter mappings to None channel_entries = [(ch, ch_entries) for (ch, ch_entries) in zip(mapped_channels, waveform_entries) if ch is not None] mapped_channels, waveform_entries = zip(*channel_entries) waveforms = [PointWaveform.from_table(mapped_channel, ch_entries) for mapped_channel, ch_entries in zip(mapped_channels, waveform_entries)] return MultiChannelWaveform.from_parallel(waveforms) @property def point_pulse_entries(self) -> Sequence[PointPulseEntry]: return self._entries def get_serialization_data(self, serializer: Optional[Serializer]=None) -> Dict[str, Any]: data = super().get_serialization_data(serializer) if serializer: # compatibility to old serialization routines, deprecated data = dict() data['time_point_tuple_list'] = [entry.get_serialization_data() for entry in self._entries] data['channel_names'] = self._channels if self.parameter_constraints: data['parameter_constraints'] = [str(c) for c in self.parameter_constraints] if self.measurement_declarations: data['measurements'] = self.measurement_declarations return data @property def duration(self) -> Expression: return self._entries[-1].t @property def point_parameters(self) -> Set[str]: return set( var for time, point, *_ in self._entries for var in itertools.chain(time.variables, point.variables) ) @property def parameter_names(self) -> Set[str]: return self.point_parameters | self.measurement_parameters | self.constrained_parameters @property def integral(self) -> Dict[ChannelID, ExpressionScalar]: expressions = {} shape = (len(self.defined_channels),) for i, channel in enumerate(self._channels): def value_trafo(v): try: return v.underlying_expression[i] except TypeError: return IndexedBroadcast(v.underlying_expression, shape, i) pre_entry = TableEntry(0, self._entries[0].v, None) entries = [pre_entry] + self._entries expressions[channel] = TableEntry._sequence_integral(entries, expression_extractor=value_trafo) return expressions def _as_expression(self) -> Dict[ChannelID, ExpressionScalar]: t = self._AS_EXPRESSION_TIME shape = (len(self.defined_channels),) expressions = {} for i, channel in enumerate(self._channels): def value_trafo(v): try: return v.underlying_expression[i] except TypeError: return IndexedBroadcast(v.underlying_expression, shape, i) pre_value = value_trafo(self._entries[0].v) post_value = value_trafo(self._entries[-1].v) pw = TableEntry._sequence_as_expression(self._entries, expression_extractor=value_trafo, t=t, post_value=post_value, pre_value=pre_value) expressions[channel] = pw return expressions @property def initial_values(self) -> Dict[ChannelID, ExpressionScalar]: shape = (len(self._channels),) return { ch: ExpressionScalar(IndexedBroadcast(self._entries[0].v, shape, ch_idx)) for ch_idx, ch in enumerate(self._channels) } @property def final_values(self) -> Dict[ChannelID, ExpressionScalar]: shape = (len(self._channels),) return { ch: ExpressionScalar(IndexedBroadcast(self._entries[-1].v, shape, ch_idx)) for ch_idx, ch in enumerate(self._channels) } class InvalidPointDimension(Exception): def __init__(self, expected, received): super().__init__('Expected a point of dimension {} but received {}'.format(expected, received)) self.expected = expected self.received = received
3,642
s3 exception handler
import functools import logging from dataclasses import dataclass from typing import Final, Optional from botocore import exceptions as botocore_exc from pydantic import ByteSize, parse_obj_as from servicelib.aiohttp.long_running_tasks.server import ( ProgressMessage, ProgressPercent, TaskProgress, ) from .exceptions import S3AccessError, S3BucketInvalidError, S3KeyNotFoundError logger = logging.getLogger(__name__) # this is artifically defined, if possible we keep a maximum number of requests for parallel # uploading. If that is not possible then we create as many upload part as the max part size allows _MULTIPART_UPLOADS_TARGET_MAX_PART_SIZE: Final[list[ByteSize]] = [ parse_obj_as(ByteSize, x) for x in [ "10Mib", "50Mib", "100Mib", "200Mib", "400Mib", "600Mib", "800Mib", "1Gib", "2Gib", "3Gib", "4Gib", "5Gib", ] ] _MULTIPART_MAX_NUMBER_OF_PARTS: Final[int] = 10000 def compute_num_file_chunks(file_size: ByteSize) -> tuple[int, ByteSize]: for chunk in _MULTIPART_UPLOADS_TARGET_MAX_PART_SIZE: num_upload_links = int(file_size / chunk) + (1 if file_size % chunk > 0 else 0) if num_upload_links < _MULTIPART_MAX_NUMBER_OF_PARTS: return (num_upload_links, chunk) raise ValueError( f"Could not determine number of upload links for {file_size=}", ) def METHOD_NAME(log: logging.Logger): """converts typical aiobotocore/boto exceptions to storage exceptions NOTE: this is a work in progress as more exceptions might arise in different use-cases """ def decorator(func): @functools.wraps(func) async def wrapper(self, *args, **kwargs): try: response = await func(self, *args, **kwargs) except self.client.exceptions.NoSuchBucket as exc: raise S3BucketInvalidError( bucket=exc.response.get("Error", {}).get("BucketName", "undefined") ) from exc except botocore_exc.ClientError as exc: if exc.response.get("Error", {}).get("Code") == "404": if exc.operation_name == "HeadObject": raise S3KeyNotFoundError(bucket=args[0], key=args[1]) from exc if exc.operation_name == "HeadBucket": raise S3BucketInvalidError(bucket=args[0]) from exc if exc.response.get("Error", {}).get("Code") == "403": if exc.operation_name == "HeadBucket": raise S3BucketInvalidError(bucket=args[0]) from exc raise S3AccessError from exc except botocore_exc.EndpointConnectionError as exc: raise S3AccessError from exc except botocore_exc.BotoCoreError as exc: log.exception("Unexpected error in s3 client: ") raise S3AccessError from exc return response return wrapper return decorator def update_task_progress( task_progress: Optional[TaskProgress], message: Optional[ProgressMessage] = None, progress: Optional[ProgressPercent] = None, ) -> None: logger.debug("%s [%s]", message or "", progress or "n/a") if task_progress: task_progress.update(message=message, percent=progress) @dataclass class S3TransferDataCB: task_progress: Optional[TaskProgress] total_bytes_to_transfer: ByteSize task_progress_message_prefix: str = "" _total_bytes_copied: int = 0 def __post_init__(self): self.copy_transfer_cb(0) def finalize_transfer(self): self.copy_transfer_cb(self.total_bytes_to_transfer - self._total_bytes_copied) def copy_transfer_cb(self, copied_bytes: int): self._total_bytes_copied += copied_bytes if self.total_bytes_to_transfer != 0: update_task_progress( self.task_progress, f"{self.task_progress_message_prefix} - " f"{parse_obj_as(ByteSize,self._total_bytes_copied).human_readable()}" f"/{self.total_bytes_to_transfer.human_readable()}]", self._total_bytes_copied / self.total_bytes_to_transfer, )
3,643
handle bad data
import os import struct import blackboxprotobuf from datetime import datetime from time import mktime from io import StringIO from io import BytesIO from scripts.artifact_report import ArtifactHtmlReport from scripts.ilapfuncs import logfunc, tsv, timeline, is_platform_windows, open_sqlite_db_readonly def utf8_in_extended_ascii(input_string, *, raise_on_unexpected=False): """Returns a tuple of bool (whether mis-encoded utf-8 is present) and str (the converted string)""" output = [] # individual characters, join at the end is_in_multibyte = False # True if we're currently inside a utf-8 multibyte character multibytes_expected = 0 multibyte_buffer = [] mis_encoded_utf8_present = False def METHOD_NAME(index, character): if not raise_on_unexpected: # not raising, so we dump the buffer into output and append this character output.extend(multibyte_buffer) multibyte_buffer.clear() output.append(character) nonlocal is_in_multibyte is_in_multibyte = False nonlocal multibytes_expected multibytes_expected = 0 else: raise ValueError(f"Expected multibyte continuation at index: {index}") for idx, c in enumerate(input_string): code_point = ord(c) if code_point <= 0x7f or code_point > 0xf4: # ASCII Range data or higher than you get for mis-encoded utf-8: if not is_in_multibyte: output.append(c) # not in a multibyte, valid ascii-range data, so we append else: METHOD_NAME(idx, c) else: # potentially utf-8 if (code_point & 0xc0) == 0x80: # continuation byte if is_in_multibyte: multibyte_buffer.append(c) else: METHOD_NAME(idx, c) else: # start-byte if not is_in_multibyte: assert multibytes_expected == 0 assert len(multibyte_buffer) == 0 while (code_point & 0x80) != 0: multibytes_expected += 1 code_point <<= 1 multibyte_buffer.append(c) is_in_multibyte = True else: METHOD_NAME(idx, c) if is_in_multibyte and len(multibyte_buffer) == multibytes_expected: # output utf-8 character if complete utf_8_character = bytes(ord(x) for x in multibyte_buffer).decode("utf-8") output.append(utf_8_character) multibyte_buffer.clear() is_in_multibyte = False multibytes_expected = 0 mis_encoded_utf8_present = True if multibyte_buffer: # if we have left-over data METHOD_NAME(len(input_string), "") return mis_encoded_utf8_present, "".join(output) def timestampsconv(webkittime): unix_timestamp = webkittime + 978307200 finaltime = datetime.utcfromtimestamp(unix_timestamp) return(finaltime) def get_biomeDevplugin(files_found, report_folder, seeker, wrap_text): typess = {'1': {'type': 'message', 'message_typedef': {'1': {'type': 'str', 'name': ''}, '2': {'type': 'message', 'message_typedef': {'1': {'type': 'int', 'name': ''}, '2': {'type': 'int', 'name': ''}}, 'name': ''}}, 'name': ''}, '2': {'type': 'double', 'name': ''}, '3': {'type': 'double', 'name': ''}, '4': {'type': 'message', 'message_typedef': {'1': {'type': 'message', 'message_typedef': {'1': {'type': 'int', 'name': ''}, '2': {'type': 'int', 'name': ''}}, 'name': ''}, '4': {'type': 'int', 'name': ''}}, 'name': ''}, '5': {'type': 'str', 'name': ''}, '7': {'type': 'message', 'message_typedef': {'1': {'type': 'message', 'message_typedef': {}, 'name': ''}, '2': {'type': 'message', 'message_typedef': {'1': {'type': 'message', 'message_typedef': {'1': {'type': 'int', 'name': ''}, '2': {'type': 'int', 'name': ''}}, 'name': ''}, '4': {'type': 'int', 'name': ''}}, 'name': ''}, '3': {'type': 'int', 'name': ''}}, 'name': ''}, '8': {'type': 'double', 'name': ''}, '10': {'type': 'int', 'name': ''}} for file_found in files_found: file_found = str(file_found) filename = os.path.basename(file_found) if filename.startswith('.'): continue if os.path.isfile(file_found): if 'tombstone' in file_found: continue else: pass else: continue with open(file_found, 'rb') as file: data = file.read() data_list = [] headerloc = data.index(b'SEGB') #print(headerloc) b = data ab = BytesIO(b) ab.seek(headerloc) ab.read(4) #Main header #print('---- Start of Notifications ----') while True: #print('----') sizeofnotificatoninhex = (ab.read(4)) try: sizeofnotificaton = (struct.unpack_from("<i",sizeofnotificatoninhex)[0]) except: break if sizeofnotificaton == 0: break allocation = ab.read(4) date1 = ab.read(8) date1 = (struct.unpack_from("<d",date1)[0]) convertedtime1 = timestampsconv(date1) #print(convertedtime1) date2 = ab.read(8) date2 = (struct.unpack_from("<d",date2)[0]) convertedtime2 = timestampsconv(date2) #print(convertedtime2) ignore1 = ab.read(8) protostuff = ab.read(sizeofnotificaton) checkforempty = BytesIO(protostuff) check = checkforempty.read(1) if check == b'\x00': pass else: protostuff, types = blackboxprotobuf.decode_message(protostuff,typess) #pp = pprint.PrettyPrinter(indent=4) #pp.pprint(protostuff) #print(types) activity = (protostuff['1']['1']) timestart = (timestampsconv(protostuff['2'])) timeend = (timestampsconv(protostuff['3'])) timewrite = (timestampsconv(protostuff['8'])) con = (protostuff['4']['4']) actionguid = (protostuff['5']) data_list.append((timestart, timeend, timewrite, activity, con, actionguid)) modresult = (sizeofnotificaton % 8) resultante = 8 - modresult if modresult == 0: pass else: ab.read(resultante) if len(data_list) > 0: description = '' report = ArtifactHtmlReport(f'Biome Device PluggedIn') report.start_artifact_report(report_folder, f'Biome Device PluggedIn - {filename}', description) report.add_script() data_headers = ('Time Start','Time End','Time Write','Activity', 'Status', 'Action GUID') report.write_artifact_data_table(data_headers, data_list, file_found) report.end_artifact_report() tsvname = f'Biome Device PluggedIn - {filename}' tsv(report_folder, data_headers, data_list, tsvname) # TODO: _csv.Error: need to escape, but no escapechar set tlactivity = f'Biome Device PluggedIn - {filename}' timeline(report_folder, tlactivity, data_list, data_headers) else: logfunc(f'No data available for Biome Device PluggedIn') __artifacts__ = { "biomeDevplugin": ( "Biome Device Plug", ('*/biome/streams/restricted/_DKEvent.Device.IsPluggedIn/local/*'), get_biomeDevplugin) }
3,644
apply mapping to voxel
#!/usr/bin/env python3 from argparse import ArgumentParser import zipfile import shutil import os import random import string import wkw import numpy as np import re import json import itertools data_zip_filename = 'data.zip' data_zip_dirname = 'data_zip' def main(): args = create_parser().parse_args() mapping = read_mapping(args) tracing_tmpdir_path = extract_tracing_zip(args) tracing_dataset = wkw.Dataset.open(os.path.join(os.path.join(tracing_tmpdir_path, data_zip_dirname), '1')) tracing_bboxes = file_bboxes(tracing_dataset) print("Found {} tracing files".format(len(tracing_bboxes))) dtype = tracing_dataset.header.voxel_type def METHOD_NAME(voxel): voxel_str = str(voxel) if voxel_str in mapping: return parse_to_dtype(mapping[voxel_str]) else: return voxel def parse_to_dtype(string): if dtype == np.uint64: return np.uint64(string) if dtype == np.uint32: return np.uint32(string) if dtype == np.uint16: return np.uint16(string) if dtype == np.uint8: return np.uint8(string) raise Exception("Unsupported data type in tracing: ", dtype) def is_mapped(voxel): return str(voxel) in mapping changed_count = 0 for counter, tracing_bbox in enumerate(tracing_bboxes): print("Processing tracing file {} of {}, bounding box: {}...".format(counter+1, len(tracing_bboxes), tracing_bbox)) data = tracing_dataset.read(tracing_bbox[0], tracing_bbox[1]) transformed = np.vectorize(METHOD_NAME)(data) tracing_dataset.write(tracing_bbox[0], transformed) changed_count += np.count_nonzero(np.vectorize(is_mapped)(data)) print("Changed {} Voxels".format(changed_count)) pack_tracing_zip(tracing_tmpdir_path, args.tracing_path) print("Done") def read_mapping(args): if not (args.mapping_path or args.mapping_str): raise Exception("""No mapping supplied, please add a mapping string in the format '{"7":"3", "12":"3"}' or a mapping file path via -f my_mapping.json""") if (args.mapping_path and args.mapping_str): print("Warning: both mapping string and mapping file path were supplied, ignoring the file.") if (args.mapping_str): mapping = json.loads(args.mapping_str) else: with open(args.mapping_path) as mapping_file: mapping = json.load(mapping_file) print_mapping_clipped(mapping) return mapping def print_mapping_clipped(mapping): print("Using mapping: ", end='') max_entries = 5 for k,v in list(itertools.islice(mapping.items(), max_entries)): print("{}->{} ".format(k,v), sep='',end='') if len(mapping) > max_entries: print("... ({} more)".format(len(mapping) - max_entries)) else: print("") def extract_tracing_zip(args): tracing_tmpdir_path = tmp_filename() os.makedirs(tracing_tmpdir_path) with zipfile.ZipFile(args.tracing_path) as outer_zip: zipfile.ZipFile.extractall(outer_zip, path=tracing_tmpdir_path) with zipfile.ZipFile(os.path.join(tracing_tmpdir_path, data_zip_filename)) as data_zip: zipfile.ZipFile.extractall(data_zip, path=os.path.join(tracing_tmpdir_path, data_zip_dirname)) return tracing_tmpdir_path def pack_tracing_zip(tracing_tmpdir_path, tracing_path): os.remove(os.path.join(tracing_tmpdir_path, data_zip_filename)) zip_dir(os.path.join(tracing_tmpdir_path, data_zip_dirname), os.path.join(tracing_tmpdir_path, data_zip_filename)) shutil.rmtree(os.path.join(tracing_tmpdir_path, data_zip_dirname)) outfile_path = "{0}_mapped{1}".format(*os.path.splitext(tracing_path)) zip_dir(os.path.join(tracing_tmpdir_path), outfile_path) print("Wrote", outfile_path) shutil.rmtree(tracing_tmpdir_path) def zip_dir(dir_path, outfile_path): zip_file = zipfile.ZipFile(outfile_path, 'w', zipfile.ZIP_DEFLATED) for root, dirs, files in os.walk(dir_path): for file in files: zip_file.write(os.path.join(root, file), os.path.relpath(os.path.join(root, file), dir_path)) zip_file.close() def file_bboxes(dataset): file_len_voxels = dataset.header.block_len * dataset.header.file_len p = re.compile('(.*)/z([0-9]+)/y([0-9]+)/x([0-9]+).wkw') bboxes = [] for file in dataset.list_files(): m = p.match(file) file_coords = [m.group(4), m.group(3), m.group(2)] offset = [int(x) * file_len_voxels for x in file_coords] shape = [file_len_voxels, file_len_voxels, file_len_voxels] bboxes.append((offset, shape)) return bboxes def create_parser(): parser = ArgumentParser() parser.add_argument('tracing_path', help='Volume tracing zip file') parser.add_argument('-f', action='store', dest='mapping_path', help='JSON file containing a direct mapping (e.g. {"7":"3", "12":"3"})') parser.add_argument('mapping_str', nargs='?') return parser def tmp_filename(): return 'tmp-' + ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10)) if __name__ == '__main__': main()
3,645
get next
# ------------------------------------ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ import sys from typing import Any, List, Iterable, Optional import urllib.parse from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.rest import HttpRequest from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.mgmt.core.exceptions import ARMErrorFormat from ._vaults_operations import VaultsOperations as _VaultsOperations, ClsType, build_list_request from .. import models as _models from .._vendor import _convert_request if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports class VaultsOperations(_VaultsOperations): @distributed_trace def list(self, top: Optional[int] = None, **kwargs: Any) -> Iterable["_models.Resource"]: """The List operation gets information about the vaults associated with the subscription. :param top: Maximum number of results to return. Default value is None. :type top: int :keyword filter: The filter to apply on the operation. Default value is "resourceType eq 'Microsoft.KeyVault/vaults'". Note that overriding this default value may result in unsupported behavior. :paramtype filter: str :keyword api_version: Azure Resource Manager Api Version. Default value is "2015-11-01". Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Resource or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.keyvault.v2023_02_01.models.Resource] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) filter: Literal["resourceType eq 'Microsoft.KeyVault/vaults'"] = kwargs.pop( "filter", _params.pop("$filter", "resourceType eq 'Microsoft.KeyVault/vaults'") ) api_version: Literal["2015-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2015-11-01")) cls: ClsType[_models.ResourceListResult] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_request( subscription_id=self._config.subscription_id, top=top, filter=filter, api_version=api_version, template_url=self.list.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) # change this line to use the passed in api version _next_request_params["api-version"] = api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("ResourceListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def METHOD_NAME(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(METHOD_NAME, extract_data) list.metadata = {"url": "/subscriptions/{subscriptionId}/resources"} __all__: List[str] = ["VaultsOperations"] # Add all objects you want publicly available to users at this package level def patch_sdk(): """Do not remove from this file. `patch_sdk` is a last resort escape hatch that allows you to do customizations you can't accomplish using the techniques described in https://aka.ms/azsdk/python/dpcodegen/python/customize """
3,646
mailchimp config
import json from typing import Any, Dict, Generator import pydash import pytest from sqlalchemy.orm import Session from fides.api.db import session from fides.api.models.connectionconfig import ( AccessLevel, ConnectionConfig, ConnectionType, ) from fides.api.models.datasetconfig import DatasetConfig from fides.api.models.sql_models import Dataset as CtlDataset from fides.api.schemas.saas.saas_config import SaaSRequest from fides.api.schemas.saas.shared_schemas import HTTPMethod, SaaSRequestParams from fides.api.service.connectors.saas_connector import SaaSConnector from fides.api.util.saas_util import ( load_config_with_replacement, load_dataset_with_replacement, ) from tests.ops.test_helpers.vault_client import get_secrets secrets = get_secrets("mailchimp") @pytest.fixture(scope="session") def mailchimp_secrets(saas_config): return { "domain": pydash.get(saas_config, "mailchimp.domain") or secrets["domain"], "username": pydash.get(saas_config, "mailchimp.username") or secrets["username"], "api_key": pydash.get(saas_config, "mailchimp.api_key") or secrets["api_key"], } @pytest.fixture(scope="session") def mailchimp_identity_email(saas_config): return ( pydash.get(saas_config, "mailchimp.identity_email") or secrets["identity_email"] ) @pytest.fixture def METHOD_NAME() -> Dict[str, Any]: return load_config_with_replacement( "data/saas/config/mailchimp_config.yml", "<instance_fides_key>", "mailchimp_instance", ) @pytest.fixture def mailchimp_dataset() -> Dict[str, Any]: return load_dataset_with_replacement( "data/saas/dataset/mailchimp_dataset.yml", "<instance_fides_key>", "mailchimp_instance", )[0] @pytest.fixture(scope="function") def mailchimp_connection_config( db: session, METHOD_NAME, mailchimp_secrets ) -> Generator: fides_key = METHOD_NAME["fides_key"] connection_config = ConnectionConfig.create( db=db, data={ "key": fides_key, "name": fides_key, "connection_type": ConnectionType.saas, "access": AccessLevel.write, "secrets": mailchimp_secrets, "saas_config": METHOD_NAME, }, ) yield connection_config connection_config.delete(db) @pytest.fixture def mailchimp_dataset_config( db: Session, mailchimp_connection_config: ConnectionConfig, mailchimp_dataset: Dict[str, Any], ) -> Generator: fides_key = mailchimp_dataset["fides_key"] mailchimp_connection_config.name = fides_key mailchimp_connection_config.key = fides_key mailchimp_connection_config.save(db=db) ctl_dataset = CtlDataset.create_from_dataset_dict(db, mailchimp_dataset) dataset = DatasetConfig.create( db=db, data={ "connection_config_id": mailchimp_connection_config.id, "fides_key": fides_key, "ctl_dataset_id": ctl_dataset.id, }, ) yield dataset dataset.delete(db=db) ctl_dataset.delete(db=db) @pytest.fixture(scope="function") def reset_mailchimp_data( mailchimp_connection_config, mailchimp_identity_email ) -> Generator: """ Gets the current value of the resource and restores it after the test is complete. Used for erasure tests. """ connector = SaaSConnector(mailchimp_connection_config) connector.set_saas_request_state( SaaSRequest(path="test_path", method=HTTPMethod.GET) ) # dummy request as connector requires it request: SaaSRequestParams = SaaSRequestParams( method=HTTPMethod.GET, path="/3.0/search-members", query_params={"query": mailchimp_identity_email}, ) response = connector.create_client().send(request) body = response.json() member = body["exact_matches"]["members"][0] yield member request: SaaSRequestParams = SaaSRequestParams( method=HTTPMethod.PUT, headers={"Content-Type": "application/json"}, path=f'/3.0/lists/{member["list_id"]}/members/{member["id"]}', body=json.dumps(member), ) connector.create_client().send(request)
3,647
flatten
# -*- coding: utf-8 -*- # FIXME: decide on whether we want mathics.core.expression.Atom vs. # mathics.core.parser.Atom # both having Atom at the end. Or should one # subclass the other? """ Classes and Objects that the parser uses to create an initial Expression (an M-Expression). The parser's AST is an M-Expression. Note that some of these classes also appear with the same name in the mathics.core.expression module. So we have mathics.core.expression.Atom vs. mathics.core.parser.Atom """ from typing import Optional class Node: """ The base class for a node or "elements" of an M-Expression. Really there are only two kinds of nodes: Atoms which are the expression's leaves and a non-leaf nodes. """ def __init__(self, head, *children): if isinstance(head, Node): self.head = head else: self.head = Symbol(head) self.value = None self.children = list(children) self.parenthesised = False def get_head_name(self): if isinstance(self.head, Symbol): return self.head.value else: return "" def __repr__(self): return "%s[%s]" % (self.head, ", ".join(str(child) for child in self.children)) def __eq__(self, other): if not isinstance(other, Node): raise TypeError() return ( (self.get_head_name() == other.get_head_name()) and (len(self.children) == len(other.children)) and all(cs == co for cs, co in zip(self.children, other.children)) ) def METHOD_NAME(self): head_name = self.get_head_name() new_children = [] for child in self.children: if child.get_head_name() == head_name and not child.parenthesised: new_children.extend(child.children) else: new_children.append(child) self.children = new_children return self class Atom(Node): """ Atoms form the leaves of an M-Expression and have no internal structure of their own. You can however compare Atoms for equality. """ def __init__(self, value): self.head = Symbol(self.__class__.__name__) self.value = value self.children = [] self.parenthesised = False def __repr__(self): return "%s[%s]" % (self.head, self.value) def __eq__(self, other): return self.__class__ == other.__class__ and self.value == other.value # What remains below are all of the different kinds of Atoms. class Number(Atom): """ An Atom with a numeric value. Later on though in evaluation, a Number can get refined into a particular kind of number such as an Integer or a Real. Note that these too are Atoms. """ def __init__( self, value: str, sign: int = 1, base: int = 10, suffix=None, exp: int = 0 ): assert isinstance(value, str) assert sign in (-1, 1) assert isinstance(base, int) assert 2 <= base <= 36 assert isinstance(exp, int) assert suffix is None or isinstance(suffix, str) super(Number, self).__init__(None) self.value = value self.sign = sign self.base = base self.suffix = suffix self.exp = exp def __repr__(self): result = self.value if self.base != 10: result = "%i^^%s" % (self.base, result) if self.sign == -1: result = "-%s" % result if self.suffix is not None: result = "%s`%s" % (result, self.suffix) if self.exp != 0: result = "%s*^%i" % (result, self.exp) return result def __eq__(self, other): return isinstance(other, Number) and repr(self) == repr(other) class Symbol(Atom): """ Symbols are like variables in a programming language. But initially in an M-Expression the only properties it has is its name and a representation of its name. Devoid of a binding to the Symbol, which is done via a Definition, Symbols are unique as they are say in Lisp, or Python. """ def __init__(self, value: str, context: Optional[str] = "System"): self.context = context self.value = value self.children = [] # avoids recursive definition @property def head(self): return Symbol(self.__class__.__name__) def __repr__(self): return self.value class String(Atom): """ A string is is pretty much the same as in any other programming language, a sequence of characters. Having this in a class is useful so that we can distinguish it from Symbols. The display of a String is surrounded by double quotes. """ def __repr__(self): return '"' + self.value + '"' class Filename(Atom): """ A filename is printed the same way a Symbol prints, in contrast to a String. However, like String, it doesn't have any other properties. """ def __repr__(self): return self.value # Some common literals NullSymbol = Symbol("Null") NullString = String("") Number1 = Number("1") NumberM1 = Number("1", sign=-1)
3,648
set cell
import os from contextlib import contextmanager from typing import Generator from unittest import mock import pytest from google.rpc.status_pb2 import Status from sentry.nodestore.bigtable.backend import BigtableNodeStorage from sentry.utils.kvstore.bigtable import BigtableKVStorage class MockedBigtableKVStorage(BigtableKVStorage): class Cell: def __init__(self, value, timestamp): self.value = value self.timestamp = timestamp class Row: def __init__(self, table, row_key): self.row_key = row_key.encode("utf8") self.table = table def delete(self): self.table._rows.pop(self.row_key, None) def METHOD_NAME(self, family, col, value, timestamp): assert family == "x" self.table._rows.setdefault(self.row_key, {})[col] = [ MockedBigtableKVStorage.Cell(value, timestamp) ] def commit(self): # commits not implemented, changes are applied immediately return Status(code=0) @property def cells(self): return {"x": dict(self.table._rows.get(self.row_key) or ())} class Table: def __init__(self): self._rows = {} def direct_row(self, key): return MockedBigtableKVStorage.Row(self, key) def read_row(self, key): return MockedBigtableKVStorage.Row(self, key) def read_rows(self, row_set): assert not row_set.row_ranges, "unsupported" return [self.read_row(key) for key in row_set.row_keys] def mutate_rows(self, rows): # commits not implemented, changes are applied immediately return [Status(code=0) for row in rows] def _get_table(self, admin: bool = False): try: table = self.__table except AttributeError: table = self.__table = MockedBigtableKVStorage.Table() return table def bootstrap(self, automatic_expiry): pass class MockedBigtableNodeStorage(BigtableNodeStorage): store_class = MockedBigtableKVStorage @contextmanager def get_temporary_bigtable_nodestorage() -> Generator[BigtableNodeStorage, None, None]: if "BIGTABLE_EMULATOR_HOST" not in os.environ: pytest.skip( "Bigtable is not available, set BIGTABLE_EMULATOR_HOST enironment variable to enable" ) ns = BigtableNodeStorage(project="test") ns.bootstrap() try: yield ns finally: ns.store.destroy() @pytest.fixture(params=[MockedBigtableNodeStorage, BigtableNodeStorage]) def ns(request): if request.param is BigtableNodeStorage: with get_temporary_bigtable_nodestorage() as ns: yield ns else: yield MockedBigtableNodeStorage(project="test") def test_cache(ns): node_1 = ("a" * 32, {"foo": "a"}) node_2 = ("b" * 32, {"foo": "b"}) node_3 = ("c" * 32, {"foo": "c"}) for node_id, data in [node_1, node_2, node_3]: ns.set(node_id, data) # Get / get multi populates cache assert ns.get(node_1[0]) == node_1[1] assert ns.get_multi([node_2[0], node_3[0]]) == { node_2[0]: node_2[1], node_3[0]: node_3[1], } table = ns.store._get_table() with mock.patch.object(table, "read_row") as mock_read_row: assert ns.get(node_1[0]) == node_1[1] assert ns.get(node_2[0]) == node_2[1] assert ns.get(node_3[0]) == node_3[1] assert mock_read_row.call_count == 0 with mock.patch.object(table, "read_rows") as mock_read_rows: assert ns.get_multi([node_1[0], node_2[0], node_3[0]]) assert mock_read_rows.call_count == 0 # Manually deleted item should still retrievable from cache row = table.direct_row(node_1[0]) row.delete() row.commit() assert ns.get(node_1[0]) == node_1[1] assert ns.get_multi([node_1[0], node_2[0]]) == { node_1[0]: node_1[1], node_2[0]: node_2[1], } # Deletion clears cache ns.delete(node_1[0]) assert ns.get_multi([node_1[0], node_2[0]]) == {node_1[0]: None, node_2[0]: node_2[1]} ns.delete_multi([node_1[0], node_2[0]]) assert ns.get_multi([node_1[0], node_2[0]]) == {node_1[0]: None, node_2[0]: None} # Setting the item updates cache new_value = {"event_id": "d" * 32} ns.set(node_1[0], new_value) with mock.patch.object(table, "read_row") as mock_read_row: assert ns.get(node_1[0]) == new_value assert mock_read_row.call_count == 0 # Missing rows are never cached assert ns.get("node_4") is None with mock.patch.object(table, "read_row") as mock_read_row: mock_read_row.return_value = None ns.get("node_4") ns.get("node_4") assert mock_read_row.call_count == 2
3,649
abort file upload
from abc import ABC, abstractmethod from collections.abc import Callable from dataclasses import dataclass, field from aiohttp import web from models_library.api_schemas_storage import LinkType, UploadedPart from models_library.projects_nodes_io import LocationID, LocationName, StorageFileID from models_library.users import UserID from pydantic import AnyUrl, ByteSize from .models import DatasetMetaData, FileMetaData, UploadLinks class BaseDataManager(ABC): @property def location_id(self) -> LocationID: """returns the location Identifier (must be unique)""" return self.get_location_id() @classmethod @abstractmethod def get_location_id(cls) -> LocationID: """returns the location Identifier (must be unique)""" @property def location_name(self) -> LocationName: """returns the location human readable name (must be unique)""" return self.get_location_name() @classmethod @abstractmethod def get_location_name(cls) -> LocationName: """returns the location human readable name (must be unique)""" @abstractmethod async def authorized(self, user_id: UserID) -> bool: """returns True if user with user_id is authorized to access the storage""" @abstractmethod async def list_datasets(self, user_id: UserID) -> list[DatasetMetaData]: """returns all the top level datasets a user has access to""" @abstractmethod async def list_files_in_dataset( self, user_id: UserID, dataset_id: str, *, expand_dirs: bool ) -> list[FileMetaData]: """returns all the file meta data inside dataset with dataset_id""" # NOTE: expand_dirs will be replaced by pagination in the future @abstractmethod async def list_files( self, user_id: UserID, *, expand_dirs: bool, uuid_filter: str = "" ) -> list[FileMetaData]: """returns all the file meta data a user has access to (uuid_filter may be used)""" # NOTE: expand_dirs will be replaced by pagination in the future @abstractmethod async def get_file(self, user_id: UserID, file_id: StorageFileID) -> FileMetaData: """returns the file meta data of file_id if user_id has the rights to""" @abstractmethod async def create_file_upload_links( self, user_id: UserID, file_id: StorageFileID, link_type: LinkType, file_size_bytes: ByteSize, *, is_directory: bool, ) -> UploadLinks: """creates one or more upload file links if user has the rights to, expects the client to complete/abort upload""" @abstractmethod async def complete_file_upload( self, file_id: StorageFileID, user_id: UserID, uploaded_parts: list[UploadedPart], ) -> FileMetaData: """completes an upload if the user has the rights to""" @abstractmethod async def METHOD_NAME(self, user_id: UserID, file_id: StorageFileID) -> None: """aborts an upload if user has the rights to, and reverts to the latest version if available, else will delete the file""" @abstractmethod async def create_file_download_link( self, user_id: UserID, file_id: StorageFileID, link_type: LinkType ) -> AnyUrl: """creates a download file link if user has the rights to""" @abstractmethod async def delete_file(self, user_id: UserID, file_id: StorageFileID) -> None: """deletes file if user has the rights to""" @dataclass class DataManagerProvider: app: web.Application _builders: dict[ LocationID, tuple[Callable[[web.Application], BaseDataManager], type[BaseDataManager]], ] = field(default_factory=dict) _services: list[BaseDataManager] = field(default_factory=list) def register_builder( self, location_id: LocationID, builder: Callable[[web.Application], BaseDataManager], dsm_type: type[BaseDataManager], ): self._builders[location_id] = (builder, dsm_type) def _create(self, location_id: LocationID, **kwargs) -> BaseDataManager: builder_and_type = self._builders.get(location_id) if not builder_and_type: raise ValueError(location_id) builder, _dsm_type = builder_and_type new_dsm = builder(self.app, **kwargs) self._services.append(new_dsm) return new_dsm def get(self, location_id: LocationID) -> BaseDataManager: for dsm in self._services: if dsm.location_id == location_id: return dsm # try to create it return self._create(location_id) def locations(self) -> list[LocationID]: return list(self._builders.keys())
3,650
set up
from datetime import datetime from uuid import uuid4 from tracardi.domain.entity import Entity from tracardi.domain.event import EventSession from tracardi.domain.metadata import ProfileMetadata from tracardi.domain.profile import Profile from tracardi.domain.session import Session, SessionMetadata, SessionTime from tracardi.domain.time import ProfileTime, ProfileVisit from tracardi.domain.value_object.operation import Operation from tracardi.service.plugin.domain.register import Plugin, Spec, MetaData, Documentation, PortDoc, Form, FormGroup, \ FormField, FormComponent from tracardi.service.plugin.domain.result import Result from tracardi.service.plugin.runner import ActionRunner from .config import Config def validate(config: dict) -> Config: return Config(**config) class AddEmptyProfileAction(ActionRunner): config: Config async def METHOD_NAME(self, init): self.config = validate(init) async def run(self, payload: dict, in_edge=None) -> Result: now = datetime.utcnow() profile = Profile( id=str(uuid4()), metadata=ProfileMetadata( time=ProfileTime( insert=now, visit=ProfileVisit( count=1, current=datetime.utcnow() ) ) ), operation=Operation(update=True) ) self.event.profile = profile self.event.metadata.profile_less = False self.event.operation.update = True self.tracker_payload.profile_less = False self.execution_graph.set_profiles(profile) if self.config.session == 'never': return Result(port='payload', value=payload) if self.config.session == 'if-not-exists' and self.session is not None \ and self.tracker_payload.is_on('saveSession', default=True): return Result(port='payload', value=payload) # Create session session = Session( id=str(uuid4()), profile=Entity(id=profile.id), metadata=SessionMetadata( time=SessionTime(insert=datetime.utcnow(), timestamp=datetime.timestamp(datetime.utcnow()))), operation=Operation(update=True) ) # todo set session in tracker payload if self.session is not None: self.console.warning(f"Old session {self.session.id} was replaced by new session {session.id}. " f"Replacing session is not a good practice if you already have a session.") self.session = session self.event.session = EventSession( id=session.id, start=session.metadata.time.insert, duration=session.metadata.time.duration ) self.execution_graph.set_sessions(session) self.tracker_payload.session.id = session.id self.tracker_payload.options.update({"saveSession": True}) return Result(port='payload', value=payload) def register() -> Plugin: return Plugin( start=False, spec=Spec( module=__name__, className='AddEmptyProfileAction', inputs=["payload"], outputs=['payload'], version='0.8.0', license="MIT", author="Risto Kowaczewski", manual="internal/add_empty_profile", init={ "session": 'always' }, form=Form( groups=[ FormGroup( name="New profile configuration", fields=[ FormField( name="New session", id="session", description="Create new session for new profile.", component=FormComponent(type="select", props={ "label": "New session", "items": { "if-not-exists": "If not exists", "always": "Always", "never": "Never" } }) ) ] ) ] ) ), metadata=MetaData( name='Create empty profile', desc='Ads new profile to the event. Empty profile gets created with random id.', icon='profile', keywords=['new', 'create', 'add'], group=["Operations"], documentation=Documentation( inputs={ "payload": PortDoc(desc="This port takes payload object.") }, outputs={ "payload": PortDoc(desc="Returns input payload.") } ) ) )
3,651
load data
# SPDX-License-Identifier: BSD-3-Clause # Copyright (c) 2023 Scipp contributors (https://github.com/scipp) """ Plot the results of benchmarks. The script parses the CSV files generated by Google Benchmark with the options ``--benchmark_out_format=csv --benchmark_out=<path>.csv --benchmark_repetitions=<n>``. """ import argparse import math import re from pathlib import Path import matplotlib.pyplot as plt import pandas as pd # Regex to identify the header of the table containing the actual data. TABLE_HEADER_PATTERN = re.compile(r'^name,iterations,.*') # Regex to turn full names (BM_xxx/yyy_zzz) into base names (xxx) # and 'aggregates' (zzz). NAME_PATTERN = re.compile(r'(BM_)?(?P<name>[^/]+)(/[^_]*)?(_(?P<aggregate>\w+))?') # Table columns written by Google Benchmark by default. DEFAULT_COLUMN_NAMES = [ 'name', 'iterations', 'real_time', 'cpu_time', 'time_unit', 'bytes_per_second', 'items_per_second', 'label', ] def seek_table(file_handle): """Advance file_handle to the beginning of the table.""" line = '' pos = 0 while not TABLE_HEADER_PATTERN.match(line): pos = file_handle.tell() line = file_handle.readline() file_handle.seek(pos) def process_errors(dataframe): """Search for errors and remove the error columns.""" # if there was no error => error_occurred = NaN errors = dataframe.query('error_occurred == error_occurred') del dataframe['error_occurred'] del dataframe['error_message'] if not errors.empty: print('There are errors in the input files:') print(errors) raise RuntimeError('Input files contain errors') def preprocess(dataframe, name_filter): """Prepare a DataFrame for plotting.""" dataframe = dataframe[dataframe.name.str.contains(name_filter)] if dataframe.empty: raise ValueError(f'No benchmarks with name {name_filter.pattern}') dataframe['aggregate'] = dataframe.name.map( lambda full_name: NAME_PATTERN.match(full_name)['aggregate'] ) dataframe.name = dataframe.name.map( lambda full_name: NAME_PATTERN.match(full_name)['name'] ) process_errors(dataframe) time_units = dataframe['time_unit'].unique() if time_units != ['ns']: raise NotImplementedError(f'Unsupported time units: {time_units}') return dataframe def load_file(fname): """Load a single file with benchmark results.""" assert fname.suffix == '.csv' with open(fname, 'r') as f: seek_table(f) data = pd.read_csv(f) data['file'] = fname return data def METHOD_NAME(fnames, name_filter): """Load multiple files and merge their contents.""" return preprocess(pd.concat([load_file(fname) for fname in fnames]), name_filter) def designate_columns(data, plot_dims, ignored): """Return a list with roles for each column in ``data``.""" return [ 'stack' if c == 'file' else 'aggregate' if c == 'aggregate' else 'plot_dim' if c in plot_dims else 'ignored' if c in ignored or c in DEFAULT_COLUMN_NAMES else 'meta' for c in data.columns ] def group_plots(data, designations): """Return the number of distinct plot groups and the groups themselves.""" meta_columns = [c for c, d in zip(data.columns, designations) if d == 'meta'] groups = data.groupby(meta_columns) return len(groups), [group for _, group in groups] def plot_title(data, designations): """Format a title for a plot of ``data``.""" return ', '.join( f'{c}={data[c].unique()[0]}' for c, d in zip(data.columns, designations) if d == 'meta' ) def get_unit(data, name): """Return the unit for an axis label for column ``name``.""" if name in ('real_time', 'cpu_time'): return f' [{data.time_unit.unique()[0]}]' return '' def plot(data, xname, yname, ignored, xscale='log'): """Plot the data.""" designations = designate_columns(data, (xname, yname), ignored) n_subplots, groups = group_plots(data, designations) if n_subplots == 0: return fig = plt.figure() fig.suptitle(data.name.unique()[0]) nx = min(3, n_subplots) if nx == 0: plt.close(fig) return ny = math.ceil(n_subplots / nx) for igroup, group in enumerate(groups): ax = fig.add_subplot(nx, ny, igroup + 1) ax.set_title(plot_title(group, designations)) ax.set_xlabel(xname + get_unit(data, xname)) ax.set_ylabel(yname + get_unit(data, yname)) ax.set_xscale(xscale) for iline, (fname, line) in enumerate(group.groupby('file')): mean = line.query('aggregate == "mean"') median = line.query('aggregate == "median"') # TODO custom counters are all 0 in the stddev row # => can't use it here # stddev = line.query('aggregate == "stddev"') ax.plot( mean[xname].to_numpy(), mean[yname].to_numpy(), marker='.', c=f'C{iline}', label=fname, ) ax.plot( median[xname].to_numpy(), median[yname].to_numpy(), marker='_', ls='', c=f'C{iline}', ) ax.set_ylim((0, ax.get_ylim()[1])) if igroup == 0: ax.legend() fig.tight_layout() def make_name_filter(names): """Return a regex that filters out the given name(s).""" name_pattern = NAME_PATTERN.match(names)['name'] return re.compile(name_pattern) def parse_args(): """Parse command line arguments.""" parser = argparse.ArgumentParser() parser.add_argument('infile', nargs='+', type=Path, help='Input files') parser.add_argument( '-n', '--names', type=make_name_filter, help='Filter for benchmark names (regex)', metavar='filter', default='.*', ) parser.add_argument( '-x', '--xaxis', default='size', help='Quantity to display on the x-axis' ) parser.add_argument( '-y', '--yaxis', default='real_time', help='Quantity to display on the y-axis' ) parser.add_argument( '--xscale', default='log', help='Use a linear scale on the x-axis' ) parser.add_argument( '--ignore', type=lambda s: s.split(','), default='', help='Quantities to ignore when splitting benchmarks into groups.', ) return parser.parse_args() def main(): args = parse_args() data = METHOD_NAME(args.infile, args.names) for _, benchmark_data in data.groupby('name'): plot(benchmark_data, args.xaxis, args.yaxis, args.ignore, xscale=args.xscale) plt.show() if __name__ == '__main__': main()
3,652
py unicode range literal
#!/usr/bin/env python3 """Generate code to be inserted into Python or Lex sources containing (parts of) regular expressions matching unicode characters belonging to particular categories. """ __copyright__ = "Copyright (C) 2018 Adrián Medraño Calvo" __license__ = "GNU GPLv2" import sys import unicodedata import argparse from itertools import count, groupby from collections import defaultdict # pylint: disable=invalid-name def list_chunks(l, n): """Split list in chunks of size n.""" for it in range(0, len(l), n): yield l[it:it+n] def groupby_sequences(iterable, keyfunc): """ Group items of iterable in groups such that the result of applying keyfunc to them is consecutive. """ if keyfunc is None: keyfunc = lambda x: x return groupby(iterable, lambda i, c=count(): keyfunc(i)-next(c)) def categorize_unicode(): """ Return a dictionary mapping Unicode general category names to the characters that belong to them. """ bycat = defaultdict(list) for c in map(chr, range(sys.maxunicode + 1)): bycat[unicodedata.category(c)].append(c) return bycat def bytes_prefix(bs): """ Return all but the last byte from a byte sequence. """ return bs[0:-1] def bytes_last(bs): """ Return the last byte from a byte sequence. """ return bs[-1] def py_unicode_literal(c): """ Convert a character into a Python unicode literal (e.g. \u0064). """ codepoint = ord(c) if codepoint < 65536: return "\\u{:04x}".format(codepoint) else: return "\\U{:08x}".format(codepoint) def METHOD_NAME(beg, end): """ Convert a range of characters into an unicode range literal (e.g. \u0064-\u006f), to be used in a Python regular expression's bracket expression. """ if beg == end: return py_unicode_literal(beg) else: return "{}-{}".format( py_unicode_literal(beg), py_unicode_literal(end)) def py_unicode_ranges(chars): """ Convert a set of characters into an string to be used in a Python regular expression's bracket expression (e.g. \u0062\u0064-\u006f). """ ranges = [] for _, seq in groupby_sequences(chars, ord): seq = list(seq) beg = seq[0] end = seq[-1] ranges.append(METHOD_NAME(beg, end)) return "r'" + "".join(ranges) + "'" def lex_byte_literal(b): """ Convert a byte into a byte literal, as supported by lex (e.g., "\x40"). """ return "\\x{:02x}".format(b) def lex_byte_literals(bs): """ Convert a sequence of bytes into a sequence of byte literals, as supported by lex (e.g., "\x40"). """ return "".join(["\\x{:02x}".format(b) for b in bs]) def lex_byte_range_literal(prefix, beg, end): pat = lex_byte_literals(prefix) if beg == end: pat += lex_byte_literal(beg) else: pat += "[" pat += lex_byte_literal(beg) pat += "-" pat += lex_byte_literal(end) pat += "]" return pat def lex_unicode_ranges(name, chars): """ Convert a set of characters into a string to be used in a lex regular expression """ res = "" bss = [c.encode("utf-8") for c in chars] pats = [] for prefix, byprefix in groupby(bss, bytes_prefix): for _, bysuffix_sequence in groupby_sequences(byprefix, bytes_last): bysuffix_sequence = list(bysuffix_sequence) beg = bysuffix_sequence[0][-1] end = bysuffix_sequence[-1][-1] pat = lex_byte_range_literal(prefix, beg, end) pats.append(pat) partnames = [] MAXPATS = 50 if len(pats) > MAXPATS: i = 0 for pats in list_chunks(pats, MAXPATS): partname = "{}-{}".format(name, i) res += "{}\t{}\n".format( partname, "|".join(pats)) partnames.append(partname) i += 1 res += "{}\t{{{}}}".format( name, "}|{".join(partnames)) else: res += "{}\t{}".format( name, "|".join(pats)) return res def main(): parser = argparse.ArgumentParser(description=__doc__.strip()) parser.add_argument( '--name', required=True, help='name to assign the result') parser.add_argument( '--categories', required=True, help='unicode categories to print, separated by commas (e.g. Lu,Ll)') parser.add_argument( '--format', required=True, choices=['py', 'lex'], help='output format') args = parser.parse_args() bycategory = categorize_unicode() chars = [] for cat in args.categories.split(","): chars += bycategory[cat] chars.sort() if args.format == 'py': print(py_unicode_ranges(chars)) elif args.format == 'lex': print(lex_unicode_ranges(args.name, chars)) if __name__ == '__main__': main()
3,653
log error
# Copyright (c) Yugabyte, 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. import logging import os from yugabyte.common_util import get_home_dir_aliases, YB_SRC_ROOT from typing import Dict, List, Any, Optional, cast def replace_home_dir_with_tilde(p: str) -> str: """ Transforms a path before logging by replacing the home directory path with ~. >>> replace_home_dir_with_tilde(os.path.expanduser('~/foo')) '~/foo' >>> replace_home_dir_with_tilde(os.path.expanduser('~')) '~' >>> replace_home_dir_with_tilde(os.path.realpath(os.path.expanduser('~'))) '~' >>> replace_home_dir_with_tilde('/usr/bin') '/usr/bin' """ for home_dir in get_home_dir_aliases(): if p == home_dir: return '~' home_dir_prefix = home_dir + '/' if p.startswith(home_dir_prefix): return '~/%s' % p[len(home_dir_prefix):] return p class LogArgRewriter: path_to_var_name: Dict[str, str] var_name_to_path: Dict[str, str] paths_by_decreasing_length: List[str] def __init__(self) -> None: self.path_to_var_name = {} self.var_name_to_path = {} self.paths_by_decreasing_length = [] def add_rewrite(self, var_name: str, path: str) -> None: if var_name in self.var_name_to_path: if path == self.var_name_to_path[var_name]: # Ignore duplicate. return raise ValueError( f"Variable {var_name} is already mapped to path {self.var_name_to_path[var_name]} " f"for the purposes of rewriting log messages, cannot map it to {path}.") logging.info("Will shorten the path %s as ${%s} going forward", path, var_name) self.path_to_var_name[path] = var_name self.var_name_to_path[var_name] = path self.paths_by_decreasing_length = sorted([ path for path in self.path_to_var_name.keys() ], key=lambda s: len(s), reverse=True) def rewrite_arg(self, arg: str) -> str: for path in self.paths_by_decreasing_length: if arg.startswith(path + '/'): return "${%s}/%s" % (self.path_to_var_name[path], arg[len(path) + 1:]) if arg == path: return "${%s}" % self.path_to_var_name[path] return arg g_log_arg_rewriter: Optional[LogArgRewriter] = None def get_log_arg_rewriter() -> LogArgRewriter: global g_log_arg_rewriter if g_log_arg_rewriter is not None: return g_log_arg_rewriter g_log_arg_rewriter = LogArgRewriter() g_log_arg_rewriter.add_rewrite('YB_SRC_ROOT', YB_SRC_ROOT) return g_log_arg_rewriter def rewrite_args(args: List[Any]) -> List[Any]: return [ get_log_arg_rewriter().rewrite_arg(arg) if isinstance(arg, str) else arg for arg in args ] def log_info(format_str: str, *args: Any) -> None: logging.info(format_str, *rewrite_args(cast(List[Any], args))) def log_warning(format_str: str, *args: Any) -> None: logging.warning(format_str, *rewrite_args(cast(List[Any], args))) def METHOD_NAME(format_str: str, *args: Any) -> None: logging.error(format_str, *rewrite_args(cast(List[Any], args))) def set_thirdparty_dir(thirdparty_dir: str) -> None: get_log_arg_rewriter().add_rewrite('YB_THIRDPARTY_DIR', thirdparty_dir) def set_thirdparty_installed_dir(thirdparty_installed_dir: str) -> None: get_log_arg_rewriter().add_rewrite('YB_THIRDPARTY_INSTALLED_DIR', thirdparty_installed_dir) def set_build_root(build_root: str) -> None: get_log_arg_rewriter().add_rewrite('YB_BUILD_ROOT', build_root) def set_linuxbrew_dir(linuxbrew_dir: str) -> None: get_log_arg_rewriter().add_rewrite('YB_LINUXBREW_DIR', linuxbrew_dir) def rewrite_logging_arg(arg: str) -> str: return get_log_arg_rewriter().rewrite_arg(arg)
3,654
admin user
from dataikuapi.dss.app import DSSApp from dataikuapi.dss.dataset import DSSDataset from dataikuapi.dss.wiki import DSSWikiArticle class DSSWorkspace: """ A handle to interact with a workspace on the DSS instance. Do not create this class directly, instead use :meth:`dataikuapi.DSSClient.get_workspace` """ def __init__(self, client, workspace_key): self.client = client self.workspace_key = workspace_key def get_settings(self): """ Gets the settings of this workspace. :returns: a handle to read, modify and save the settings :rtype: :class:`DSSWorkspaceSettings` """ return DSSWorkspaceSettings(self, self.client._perform_json("GET", "/workspaces/%s" % self.workspace_key)) def list_objects(self): """ List the objects in this workspace :returns: The list of the objects :rtype: list of :class:`.DSSWorkspaceObject` """ objects = self.client._perform_json("GET", "/workspaces/%s/objects" % self.workspace_key) return [DSSWorkspaceObject(self, object) for object in objects] def add_object(self, object): """ Add an object to this workspace. Object can be of different shapes (:class:`dataikuapi.dss.dataset.DSSDataset`, :class:`dataikuapi.dss.wiki.DSSWikiArticle`, :class:`dataikuapi.dss.app.DSSApp`, :class:`.DSSWorkspaceHtmlLinkObject` or a :class:`.dict` that contains the raw data) """ if isinstance(object, DSSDataset): data = {"reference": {"projectKey": object.project_key, "type": "DATASET", "id": object.dataset_name}} elif isinstance(object, DSSWikiArticle): data = {"reference": {"projectKey": object.project_key, "type": "ARTICLE", "id": object.article_id}} elif isinstance(object, DSSApp): data = {"appId": object.app_id} elif isinstance(object, DSSWorkspaceHtmlLinkObject): data = {"htmlLink": {"name": object.name, "url": object.url, "description": object.description}} elif isinstance(object, dict): data = object else: raise ValueError("Unsupported object type") self.client._perform_json("POST", "/workspaces/%s/objects" % self.workspace_key, body=data) def delete(self): """ Delete the workspace This call requires Administrator rights on the workspace. """ return self.client._perform_empty("DELETE", "/workspaces/%s" % self.workspace_key) class DSSWorkspaceHtmlLinkObject: def __init__(self, name, url, description): self.name = name self.url = url self.description = description class DSSWorkspaceObject: """ A handle on an object of a workspace Do not create this class directly, instead use :meth:`dataikuapi.dss.DSSWorkspace.list_objects` """ def __init__(self, workspace, data): self.workspace = workspace self.data = data def get_raw(self): return self.data def remove(self): """ Remove this object from the workspace This call requires Contributor rights on the workspace. """ self.workspace.client._perform_empty( "DELETE", "/workspaces/%s/objects/%s" % (self.workspace.workspace_key, self.data['id'])) class DSSWorkspaceSettings: """ A handle on the settings of a workspace Do not create this class directly, instead use :meth:`dataikuapi.dss.DSSWorkspace.get_settings` """ def __init__(self, workspace, settings): self.workspace = workspace self.settings = settings def get_raw(self): return self.settings @property def display_name(self): """ Get or set the name of the workspace :rtype: :class:`str` """ return self.settings['displayName'] @display_name.setter def display_name(self, value): self.settings['displayName'] = value @property def color(self): """ Get or set the background color of the workspace (using #xxxxxx syntax) :rtype: :class:`str` """ return self.settings['color'] @color.setter def color(self, value): self.settings['color'] = value @property def description(self): """ Get or set the description of the workspace :rtype: :class:`str` """ return self.settings['description'] @description.setter def description(self, value): self.settings['description'] = value @property def permissions(self): """ Get or set the permissions controlling who is a member, contributor or admin of the workspace :rtype: list of :class:`.DSSWorkspacePermissionItem` """ return [DSSWorkspacePermissionItem(permission) for permission in self.settings['permissions']] @permissions.setter def permissions(self, value): self.settings['permissions'] = value @property def current_user_permissions(self): """ Permissions of the current user (read-only) :rtype: :class:`.DSSWorkspacePermissionItem` """ return DSSWorkspacePermissionItem(self.settings['currentUserPermissions']) def save(self): """ Save the changes made on the settings This call requires Administrator rights on the workspace. """ self.workspace.client._perform_empty( "PUT", "/workspaces/%s" % self.workspace.workspace_key, body=self.settings) class DSSWorkspacePermissionItem(dict): def __init__(self, data): super(DSSWorkspacePermissionItem, self).__init__(data) @classmethod def admin_group(cls, group): return cls({"group": group, "admin": True, "write": True, "read": True}) @classmethod def contributor_group(cls, group): return cls({"group": group, "admin": False, "write": True, "read": True}) @classmethod def member_group(cls, group): return cls({"group": group, "admin": False, "write": False, "read": True}) @classmethod def METHOD_NAME(cls, user): return cls({"user": user, "admin": True, "write": True, "read": True}) @classmethod def contributor_user(cls, user): return cls({"user": user, "admin": False, "write": True, "read": True}) @classmethod def member_user(cls, user): return cls({"user": user, "admin": False, "write": False, "read": True}) @property def user(self): """ Get user login :rtype: :class:`str` """ return self['user'] @property def group(self): """ Get group name :rtype: :class:`str` """ return self['group'] @property def admin(self): """ Get admin permission :rtype: :class:`boolean` """ return self['admin'] @property def write(self): """ Get write permission :rtype: :class:`boolean` """ return self['write'] @property def read(self): """ Get read permission :rtype: :class:`boolean` """ return self['read']
3,655
test get hospitalization data
############################################################################# # Copyright (C) 2020-2021 German Aerospace Center (DLR-SC) # # Authors: Patrick Lenz # # Contact: Martin J. Kuehn <Martin.Kuehn@DLR.de> # # 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 os import random import unittest from unittest.mock import call, patch import numpy as np import pandas as pd from pyfakefs import fake_filesystem_unittest from memilio.epidata import getDataIntoPandasDataFrame as gd from memilio.epidata import getHospitalizationData as ghd from memilio.epidata import progress_indicator class TestGetHospitalizationData(fake_filesystem_unittest.TestCase): maxDiff = None path = '/home/HospitalizationData' here = os.path.dirname(os.path.abspath(__file__)) test_data_file = os.path.join( here, "test_data", "TestSetFullHospitalizationData.json") df_test = pd.read_json(test_data_file) six_day_offset = [0, 0, 0, 0, 0, 0] array_to_test_constant = np.array(six_day_offset + [1 for i in range(15)]) output_constant = [1/7 for i in range(21)] # start with a seven day offset output_random = [random.randint(0, 5)for i in range(200)] array_to_test_random = np.array([0 for i in range(len(output_random))]) for j in range(len(array_to_test_random)): for i in range(7): try: array_to_test_random[i+j] += output_random[j] except: pass array_to_test_random[:6] = 0 output_standart = six_day_offset + [ 3, 2, 0, 5, 0, 1, 4, 5, 4, 1, 6, 5, 4, 0, 4, 8, 1, 0, 0, 1, 0, 1, 0, 5, 2, 20, 8, 0, 8, 9, 6, 5, 7, 1, 8, 4, 0, 0, 1, 0, 1, 0, 2, 0, 5, 6, 4, 0, 6, 0, 4, 1, 5, 0, 4, 0, 6, 0, 4, 9, 0, 4, 7, 4, 4, 12, 2, 8, 2, 4, 8, 2, 6, 9, 2, 4, 2, 4, 7, 0, 5, 0, 2, 0, 4, 1] array_to_test_standart = np.array([0 for i in range(len(output_standart))]) for j in range(len(array_to_test_standart)): for i in range(7): try: array_to_test_standart[i+j] += output_standart[j] except: pass def setUp(self): self.setUpPyfakefs() progress_indicator.ProgressIndicator.disable_indicators(True) @patch('builtins.print') def test_divi_data_hospit_sanity_checks(self, mock_print): # first test # test empty Dataframe df = pd.DataFrame() with self.assertRaises(gd.DataError) as error: ghd.hospit_sanity_checks(df) error_message = "Download of Hospitalization Data failed. File is empty." self.assertEqual(str(error.exception), error_message) # second test # get dataframe with wanted columns and one additional column df = pd.DataFrame( {'Datum': [1, 2, 3], 'Bundesland': ['A', 'B', 'C'], 'Altersgruppe': ['00', '2+', 'alle'], 'Bundesland_Id': [4, 5, 6], 'a': [1, 2, 3], '7T_Hospitalisierung_Inzidenz': [4, 5, 6], '7T_Hospitalisierung_Faelle': [100, 1001, 100]}) ghd.hospit_sanity_checks(df) expected_print = [call("Warning: Number of data categories changed.")] mock_print.assert_has_calls(expected_print) # third test # get dataframe with 6 columns but different names df = pd.DataFrame( {'date_fake': [1, 2, 3], '6': [6, 7, 8], '7': [7, 8, 9], '8': [8, 9, 0], 'bundesland': [2, 3, 4], '9': [9, 0, 1]}) with self.assertRaises(gd.DataError) as error: ghd.hospit_sanity_checks(df) error_message = "Error: Data categories have changed." self.assertEqual(str(error.exception), error_message) @patch('builtins.input', return_value='Y') @patch('memilio.epidata.getHospitalizationData.pd.read_csv', return_value=df_test) def METHOD_NAME(self, mock_file, mock_in): # this should not raise any errors ghd.get_hospitalization_data(out_folder=self.path) # check if all files are written self.assertEqual( len(os.listdir(os.path.join(self.path, 'Germany'))), 5) def test_compute_hospitailzations_per_day(self): # test constant input array inputarray_c = self.array_to_test_constant result_c = ghd.get_hospitailzations_per_day(inputarray_c) self.assertEqual(list(result_c), self.output_constant) # test standart input inputarray_s = self.array_to_test_standart result_s = ghd.get_hospitailzations_per_day(inputarray_s) self.assertEqual(list(result_s), self.output_standart) # test random input inputarray_r = self.array_to_test_random result_r = ghd.get_hospitailzations_per_day(inputarray_r) # for random inputs the values in the result doesn't necessarily have to be integers. # Therefore we check the 7 day sum: control_sum = np.array([0. for i in range(len(result_r))]) for j in range(len(control_sum)): for i in range(7): try: control_sum[i+j] += result_r[j] except: pass # should be equal to the input array np.testing.assert_array_almost_equal( inputarray_r[6:], control_sum[6:], 10) if __name__ == '__main__': unittest.main()
3,656
create fake modifier builder
# Copyright (c) 2021 - present / Neuralmagic, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import random import pytest from sparseml.optim import BaseModifier, ModifierProp from sparseml.sparsification import ModifierYAMLBuilder, RecipeYAMLBuilder, to_yaml_str class FakeModifier(BaseModifier): def __init__(self, prop_one, prop_two): self._prop_one = prop_one self._prop_two = prop_two @ModifierProp() def prop_one(self): return self._prop_one @ModifierProp() def prop_two(self): return self._prop_two @ModifierProp(serializable=False) def hidden_prop(self): return f"{self._prop_one} {self._prop_two}" @pytest.mark.parametrize( "modifier_class", [FakeModifier], ) def test_modifier_builder_setters_getters(modifier_class): builder = ModifierYAMLBuilder(modifier_class) found_prop = False for attr in dir(modifier_class): prop = getattr(modifier_class, attr) if not isinstance(prop, ModifierProp): continue found_prop = True if prop.serializable: # check set and get supported assert getattr(builder, attr) is None random_val = random.random() setattr(builder, attr, random_val) assert getattr(builder, attr) == random_val else: # check set and get not supported with pytest.raises(ValueError): getattr(builder, attr) with pytest.raises(ValueError): setattr(builder, attr, random.random()) assert found_prop # ensure that modifier class is well formed and tests ran def METHOD_NAME(prop_one, prop_two): return ModifierYAMLBuilder(FakeModifier, prop_one=prop_one, prop_two=prop_two) def _expected_fake_modifier_yaml_str(prop_one, prop_two): prop_one = to_yaml_str(prop_one) prop_two = to_yaml_str(prop_two) return f"- !FakeModifier\n prop_one: {prop_one}\n prop_two: {prop_two}" def _reduce_white_space(s): return " ".join(s.strip().split()) @pytest.mark.parametrize( "builder,expected_yaml_str", [ ( METHOD_NAME("val_1", 2), _expected_fake_modifier_yaml_str("val_1", 2), ), ( METHOD_NAME({"key_1": [1, 2, "c"]}, [-1, 2, 3]), _expected_fake_modifier_yaml_str({"key_1": [1, 2, "c"]}, [-1, 2, 3]), ), ], ) def test_modifier_builder_build_yaml(builder, expected_yaml_str): yaml_str = builder.build_yaml_str() yaml_str = _reduce_white_space(yaml_str) expected_yaml_str = _reduce_white_space(expected_yaml_str) assert yaml_str == expected_yaml_str def _get_test_recipe_builder(): return RecipeYAMLBuilder( variables={"init_lr": 0.01, "num_epochs": 100}, modifier_groups={ "test_modifiers": [ METHOD_NAME(1, 2), METHOD_NAME("a", "b"), ] }, ) _EXPECTED_TEST_RECIPE_YAML = """ init_lr: 0.01 num_epochs: 100 test_modifiers: - !FakeModifier prop_one: 1 prop_two: 2 - !FakeModifier prop_one: a prop_two: b """.strip() def test_recipe_builder_build_yaml_str(): recipe_builder = _get_test_recipe_builder() recipe_yaml = recipe_builder.build_yaml_str() recipe_yaml = _reduce_white_space(recipe_yaml) expected_yaml = _reduce_white_space(_EXPECTED_TEST_RECIPE_YAML) assert recipe_yaml == expected_yaml def test_recipe_builder_build_variables(): recipe_builder = _get_test_recipe_builder() assert recipe_builder.has_variable("num_epochs") assert not recipe_builder.has_variable("target_sparsity") assert recipe_builder.get_variable("init_lr") == 0.01 assert recipe_builder.get_variable("target_sparsity") is None recipe_builder.set_variable("init_lr", 0.05) builder_ref = recipe_builder.set_variable("target_sparsity", 0.9) assert builder_ref is recipe_builder # test that setter is chainable assert recipe_builder.get_variable("init_lr") == 0.05 assert recipe_builder.get_variable("target_sparsity") == 0.9 def test_recipe_builder_modifier_groups(): recipe_builder = _get_test_recipe_builder() assert recipe_builder.get_modifier_group("modifiers") is None assert isinstance(recipe_builder.get_modifier_group("test_modifiers"), list) assert len(recipe_builder.get_modifier_group("test_modifiers")) == 2 with pytest.raises(KeyError): # duplicate name recipe_builder.add_modifier_group("test_modifiers") with pytest.raises(ValueError): # group names must contain 'modifiers' recipe_builder.add_modifier_group("invalid_name") builder_ref = recipe_builder.add_modifier_group("modifiers") assert builder_ref is recipe_builder # test method is chainable assert isinstance(recipe_builder.get_modifier_group("modifiers"), list) assert len(recipe_builder.get_modifier_group("modifiers")) == 0 def test_recipe_builder_get_modifier_builders(): recipe_builder = _get_test_recipe_builder() assert len(recipe_builder.get_modifier_builders()) == 2 assert len(recipe_builder.get_modifier_builders(modifier_type=FakeModifier)) == 2 assert len(recipe_builder.get_modifier_builders(modifier_type=BaseModifier)) == 2 assert len(recipe_builder.get_modifier_builders(modifier_type="FakeModifier")) == 2 assert ( len( recipe_builder.get_modifier_builders( modifier_type=FakeModifier, modifier_groups=["test_modifiers"] ) ) == 2 ) # filters that should produce no matches assert len(recipe_builder.get_modifier_builders(modifier_type="BaseModifier")) == 0 assert len(recipe_builder.get_modifier_builders(modifier_type=str)) == 0 assert len(recipe_builder.get_modifier_builders(modifier_groups=["modifiers"])) == 0
3,657
conditional variance
# Copyright 2020 The GPflow Contributors. 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. from typing import Any, Callable, Optional, Type import tensorflow as tf import tensorflow_probability as tfp from check_shapes import check_shapes, inherit_check_shapes from ..base import TensorType from ..utilities import positive from .base import QuadratureLikelihood class MultiLatentLikelihood(QuadratureLikelihood): r""" A Likelihood which assumes that a single dimensional observation is driven by multiple latent GPs. Note that this implementation does not allow for taking into account covariance between outputs. """ def __init__(self, latent_dim: int, **kwargs: Any) -> None: super().__init__( input_dim=None, latent_dim=latent_dim, observation_dim=1, **kwargs, ) class MultiLatentTFPConditional(MultiLatentLikelihood): """ MultiLatent likelihood where the conditional distribution is given by a TensorFlow Probability Distribution. """ def __init__( self, latent_dim: int, conditional_distribution: Callable[..., tfp.distributions.Distribution], **kwargs: Any, ): """ :param latent_dim: number of arguments to the `conditional_distribution` callable :param conditional_distribution: function from F to a tfp Distribution, where F has shape [..., latent_dim] """ super().__init__(latent_dim, **kwargs) self.conditional_distribution = conditional_distribution @inherit_check_shapes def _log_prob(self, X: TensorType, F: TensorType, Y: TensorType) -> tf.Tensor: """ The log probability density log p(Y|F) :param F: function evaluation Tensor, with shape [..., latent_dim] :param Y: observation Tensor, with shape [..., 1]: :returns: log pdf, with shape [...] """ return tf.squeeze(self.conditional_distribution(F).log_prob(Y), -1) @inherit_check_shapes def _conditional_mean(self, X: TensorType, F: TensorType) -> tf.Tensor: """ The conditional marginal mean of Y|F: [E(Y₁|F)] :param F: function evaluation Tensor, with shape [..., latent_dim] :returns: mean [..., 1] """ return self.conditional_distribution(F).mean() @inherit_check_shapes def METHOD_NAME(self, X: TensorType, F: TensorType) -> tf.Tensor: """ The conditional marginal variance of Y|F: [Var(Y₁|F)] :param F: function evaluation Tensor, with shape [..., latent_dim] :returns: variance [..., 1] """ return self.conditional_distribution(F).variance() class HeteroskedasticTFPConditional(MultiLatentTFPConditional): """ Heteroskedastic Likelihood where the conditional distribution is given by a TensorFlow Probability Distribution. The `loc` and `scale` of the distribution are given by a two-dimensional multi-output GP. """ def __init__( self, distribution_class: Type[tfp.distributions.Distribution] = tfp.distributions.Normal, scale_transform: Optional[tfp.bijectors.Bijector] = None, **kwargs: Any, ) -> None: """ :param distribution_class: distribution class parameterized by `loc` and `scale` as first and second argument, respectively. :param scale_transform: callable/bijector applied to the latent function modelling the scale to ensure its positivity. Typically, `tf.exp` or `tf.softplus`, but can be any function f: R -> R^+. Defaults to exp if not explicitly specified. """ if scale_transform is None: scale_transform = positive(base="exp") self.scale_transform = scale_transform @check_shapes( "F: [batch..., 2]", ) def conditional_distribution(F: TensorType) -> tfp.distributions.Distribution: loc = F[..., :1] scale = self.scale_transform(F[..., 1:]) return distribution_class(loc, scale) super().__init__( latent_dim=2, conditional_distribution=conditional_distribution, **kwargs, )
3,658
type
# coding=utf-8 # *** WARNING: this file was generated by pulumi. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import copy import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities __all__ = [ 'GetNetworkSecurityPerimeterResult', 'AwaitableGetNetworkSecurityPerimeterResult', 'get_network_security_perimeter', 'get_network_security_perimeter_output', ] @pulumi.output_type class GetNetworkSecurityPerimeterResult: """ The Network Security Perimeter resource """ def __init__(__self__, id=None, location=None, name=None, perimeter_guid=None, provisioning_state=None, tags=None, METHOD_NAME=None): if id and not isinstance(id, str): raise TypeError("Expected argument 'id' to be a str") pulumi.set(__self__, "id", id) if location and not isinstance(location, str): raise TypeError("Expected argument 'location' to be a str") pulumi.set(__self__, "location", location) if name and not isinstance(name, str): raise TypeError("Expected argument 'name' to be a str") pulumi.set(__self__, "name", name) if perimeter_guid and not isinstance(perimeter_guid, str): raise TypeError("Expected argument 'perimeter_guid' to be a str") pulumi.set(__self__, "perimeter_guid", perimeter_guid) if provisioning_state and not isinstance(provisioning_state, str): raise TypeError("Expected argument 'provisioning_state' to be a str") pulumi.set(__self__, "provisioning_state", provisioning_state) if tags and not isinstance(tags, dict): raise TypeError("Expected argument 'tags' to be a dict") pulumi.set(__self__, "tags", tags) if METHOD_NAME and not isinstance(METHOD_NAME, str): raise TypeError("Expected argument 'type' to be a str") pulumi.set(__self__, "type", METHOD_NAME) @property @pulumi.getter def id(self) -> str: """ Resource ID. """ return pulumi.get(self, "id") @property @pulumi.getter def location(self) -> Optional[str]: """ Resource location. """ return pulumi.get(self, "location") @property @pulumi.getter def name(self) -> str: """ Resource name. """ return pulumi.get(self, "name") @property @pulumi.getter(name="perimeterGuid") def perimeter_guid(self) -> str: """ perimeter guid of the network security perimeter. """ return pulumi.get(self, "perimeter_guid") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> str: """ The provisioning state of the scope assignment resource. """ return pulumi.get(self, "provisioning_state") @property @pulumi.getter def tags(self) -> Optional[Mapping[str, str]]: """ Resource tags. """ return pulumi.get(self, "tags") @property @pulumi.getter def METHOD_NAME(self) -> str: """ Resource type. """ return pulumi.get(self, "type") class AwaitableGetNetworkSecurityPerimeterResult(GetNetworkSecurityPerimeterResult): # pylint: disable=using-constant-test def __await__(self): if False: yield self return GetNetworkSecurityPerimeterResult( id=self.id, location=self.location, name=self.name, perimeter_guid=self.perimeter_guid, provisioning_state=self.provisioning_state, tags=self.tags, METHOD_NAME=self.METHOD_NAME) def get_network_security_perimeter(network_security_perimeter_name: Optional[str] = None, resource_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetNetworkSecurityPerimeterResult: """ Gets the specified network security perimeter by the name. :param str network_security_perimeter_name: The name of the network security perimeter. :param str resource_group_name: The name of the resource group. """ __args__ = dict() __args__['networkSecurityPerimeterName'] = network_security_perimeter_name __args__['resourceGroupName'] = resource_group_name opts = pulumi.InvokeOptions.merge(_utilities.get_invoke_opts_defaults(), opts) __ret__ = pulumi.runtime.invoke('azure-native:network/v20210201preview:getNetworkSecurityPerimeter', __args__, opts=opts, typ=GetNetworkSecurityPerimeterResult).value return AwaitableGetNetworkSecurityPerimeterResult( id=pulumi.get(__ret__, 'id'), location=pulumi.get(__ret__, 'location'), name=pulumi.get(__ret__, 'name'), perimeter_guid=pulumi.get(__ret__, 'perimeter_guid'), provisioning_state=pulumi.get(__ret__, 'provisioning_state'), tags=pulumi.get(__ret__, 'tags'), METHOD_NAME=pulumi.get(__ret__, 'type')) @_utilities.lift_output_func(get_network_security_perimeter) def get_network_security_perimeter_output(network_security_perimeter_name: Optional[pulumi.Input[str]] = None, resource_group_name: Optional[pulumi.Input[str]] = None, opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetNetworkSecurityPerimeterResult]: """ Gets the specified network security perimeter by the name. :param str network_security_perimeter_name: The name of the network security perimeter. :param str resource_group_name: The name of the resource group. """ ...
3,659
get
# coding=utf-8 # *** WARNING: this file was generated by pulumi. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import copy 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__ = ['ReportArgs', 'Report'] @pulumi.input_type class ReportArgs: def __init__(__self__, *, properties: pulumi.Input['ReportPropertiesArgs'], report_name: Optional[pulumi.Input[str]] = None): """ The set of arguments for constructing a Report resource. :param pulumi.Input['ReportPropertiesArgs'] properties: Report property. :param pulumi.Input[str] report_name: Report Name. """ pulumi.set(__self__, "properties", properties) if report_name is not None: pulumi.set(__self__, "report_name", report_name) @property @pulumi.getter def properties(self) -> pulumi.Input['ReportPropertiesArgs']: """ Report property. """ return pulumi.METHOD_NAME(self, "properties") @properties.setter def properties(self, value: pulumi.Input['ReportPropertiesArgs']): pulumi.set(self, "properties", value) @property @pulumi.getter(name="reportName") def report_name(self) -> Optional[pulumi.Input[str]]: """ Report Name. """ return pulumi.METHOD_NAME(self, "report_name") @report_name.setter def report_name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "report_name", value) class Report(pulumi.CustomResource): @overload def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, properties: Optional[pulumi.Input[pulumi.InputType['ReportPropertiesArgs']]] = None, report_name: Optional[pulumi.Input[str]] = None, __props__=None): """ A class represent an AppComplianceAutomation report resource. Azure REST API version: 2022-11-16-preview. Prior API version in Azure Native 1.x: 2022-11-16-preview :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[pulumi.InputType['ReportPropertiesArgs']] properties: Report property. :param pulumi.Input[str] report_name: Report Name. """ ... @overload def __init__(__self__, resource_name: str, args: ReportArgs, opts: Optional[pulumi.ResourceOptions] = None): """ A class represent an AppComplianceAutomation report resource. Azure REST API version: 2022-11-16-preview. Prior API version in Azure Native 1.x: 2022-11-16-preview :param str resource_name: The name of the resource. :param ReportArgs 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(ReportArgs, 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, properties: Optional[pulumi.Input[pulumi.InputType['ReportPropertiesArgs']]] = None, report_name: Optional[pulumi.Input[str]] = None, __props__=None): opts = pulumi.ResourceOptions.merge(_utilities.get_resource_opts_defaults(), opts) if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') 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__ = ReportArgs.__new__(ReportArgs) if properties is None and not opts.urn: raise TypeError("Missing required property 'properties'") __props__.__dict__["properties"] = properties __props__.__dict__["report_name"] = report_name __props__.__dict__["name"] = None __props__.__dict__["system_data"] = None __props__.__dict__["type"] = None alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_="azure-native:appcomplianceautomation/v20221116preview:Report")]) opts = pulumi.ResourceOptions.merge(opts, alias_opts) super(Report, __self__).__init__( 'azure-native:appcomplianceautomation:Report', resource_name, __props__, opts) @staticmethod def METHOD_NAME(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None) -> 'Report': """ Get an existing Report 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__ = ReportArgs.__new__(ReportArgs) __props__.__dict__["name"] = None __props__.__dict__["properties"] = None __props__.__dict__["system_data"] = None __props__.__dict__["type"] = None return Report(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter def name(self) -> pulumi.Output[str]: """ The name of the resource """ return pulumi.METHOD_NAME(self, "name") @property @pulumi.getter def properties(self) -> pulumi.Output['outputs.ReportPropertiesResponse']: """ Report property. """ return pulumi.METHOD_NAME(self, "properties") @property @pulumi.getter(name="systemData") def system_data(self) -> pulumi.Output['outputs.SystemDataResponse']: """ Azure Resource Manager metadata containing createdBy and modifiedBy information. """ return pulumi.METHOD_NAME(self, "system_data") @property @pulumi.getter def type(self) -> pulumi.Output[str]: """ The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" """ return pulumi.METHOD_NAME(self, "type")
3,660
validate tr tensor
""" Core operations on tensors in Tensor Ring (TR) format """ import warnings import numpy as np import tensorly as tl from ._factorized_tensor import FactorizedTensor def tr_to_tensor(factors): """Returns the full tensor whose TR decomposition is given by 'factors' Re-assembles 'factors', which represent a tensor in TR format into the corresponding full tensor Parameters ---------- factors : list of 3D-arrays TR factors (TR-cores) Returns ------- output_tensor : ndarray tensor whose TR decomposition was given by 'factors' """ full_shape = [f.shape[1] for f in factors] full_tensor = tl.reshape(factors[0], (-1, factors[0].shape[2])) for factor in factors[1:-1]: rank_prev, _, rank_next = factor.shape factor = tl.reshape(factor, (rank_prev, -1)) full_tensor = tl.dot(full_tensor, factor) full_tensor = tl.reshape(full_tensor, (-1, rank_next)) full_tensor = tl.reshape( full_tensor, (factors[-1].shape[2], -1, factors[-1].shape[0]) ) full_tensor = tl.moveaxis(full_tensor, 0, -1) full_tensor = tl.reshape( full_tensor, (-1, factors[-1].shape[0] * factors[-1].shape[2]) ) factor = tl.moveaxis(factors[-1], -1, 1) factor = tl.reshape(factor, (-1, full_shape[-1])) full_tensor = tl.dot(full_tensor, factor) return tl.reshape(full_tensor, full_shape) def tr_to_unfolded(factors, mode): """Returns the unfolding matrix of a tensor given in TR format Reassembles a full tensor from 'factors' and returns its unfolding matrix with mode given by 'mode' Parameters ---------- factors: list of 3D-arrays TR factors mode: int unfolding matrix to be computed along this mode Returns ------- 2-D array unfolding matrix at mode given by 'mode' """ return tl.unfold(tr_to_tensor(factors), mode) def tr_to_vec(factors): """Returns the tensor defined by its TR format ('factors') into its vectorized format Parameters ---------- factors: list of 3D-arrays TR factors Returns ------- 1-D array vectorized format of tensor defined by 'factors' """ return tl.tensor_to_vec(tr_to_tensor(factors)) def METHOD_NAME(tr_tensor): factors = tr_tensor n_factors = len(factors) if n_factors < 2: raise ValueError( "A Tensor Ring tensor should be composed of at least two factors." f"However, {n_factors} factor was given." ) rank = [] shape = [] for index, factor in enumerate(factors): current_rank, current_shape, next_rank = tl.shape(factor) # Check that factors are third order tensors if not tl.ndim(factor) == 3: raise ValueError( "TR expresses a tensor as third order factors (tr-cores).\n" f"However, tl.ndim(factors[{index}]) = {tl.ndim(factor)}" ) # Consecutive factors should have matching ranks if tl.shape(factors[index - 1])[2] != current_rank: raise ValueError( "Consecutive factors should have matching ranks\n" " -- e.g. tl.shape(factors[0])[2]) == tl.shape(factors[1])[0])\n" f"However, tl.shape(factor[{index-1}])[2] == {tl.shape(factors[index-1])[2]} but" f" tl.shape(factor[{index}])[0] == {current_rank}" ) shape.append(current_shape) rank.append(current_rank) # Add last rank (boundary condition) rank.append(next_rank) return tuple(shape), tuple(rank) def _tr_n_param(tensor_shape, rank): """Number of parameters of a TR decomposition for a given `rank` and full `tensor_shape`. Parameters ---------- tensor_shape : int tuple shape of the full tensor to decompose (or approximate) rank : tuple rank of the TR decomposition Returns ------- n_params : int Number of parameters of a TR decomposition of rank `rank` of a full tensor of shape `tensor_shape` """ factor_params = [] for i, s in enumerate(tensor_shape): factor_params.append(rank[i] * s * rank[i + 1]) return np.sum(factor_params) def validate_tr_rank(tensor_shape, rank="same", rounding="round"): """Returns the rank of a Tensor Ring Decomposition Parameters ---------- tensor_shape : tuple shape of the tensor to decompose rank : {'same', float, tuple, int}, default is same way to determine the rank, by default 'same' if 'same': rank is computed to keep the number of parameters (at most) the same if float, computes a rank so as to keep rank percent of the original number of parameters if int or tuple, just returns rank rounding : {'round', 'floor', 'ceil'} Returns ------- rank : int tuple rank of the decomposition """ if rounding == "ceil": rounding_fun = np.ceil elif rounding == "floor": rounding_fun = np.floor elif rounding == "round": rounding_fun = np.round else: raise ValueError(f"Rounding should be round, floor or ceil, but got {rounding}") if rank == "same": rank = float(1) n_dim = len(tensor_shape) if n_dim == 2: warnings.warn( "Determining the TR-rank for the trivial case of a matrix" f" (order 2 tensor) of shape {tensor_shape}, not a higher-order tensor." ) if isinstance(rank, float): # Choose the *same* rank for each mode n_param_tensor = np.prod(tensor_shape) * rank # R_k I_k R_{k+1} = R^2 I_k solution = int(rounding_fun(np.sqrt(n_param_tensor / np.sum(tensor_shape)))) rank = (solution,) * (n_dim + 1) else: # Check user input for potential errors n_dim = len(tensor_shape) if isinstance(rank, int): rank = (rank,) * (n_dim + 1) elif n_dim + 1 != len(rank): message = ( "Provided incorrect number of ranks. " "Should verify len(rank) == tl.ndim(tensor)+1, " f"but len(rank) = {len(rank)} while tl.ndim(tensor)+1 = {n_dim + 1}" ) raise ValueError(message) # Check first and last rank if rank[0] != rank[-1]: message = ( f"Provided rank[0] == {rank[0]} and rank[-1] == {rank[-1]}" " but boundaring conditions dictatate rank[0] == rank[-1]" ) raise ValueError(message) return list(rank) class TRTensor(FactorizedTensor): def __init__(self, factors): super().__init__() # Will raise an error if invalid shape, rank = METHOD_NAME(factors) self.shape = tuple(shape) self.rank = tuple(rank) self.factors = factors def __getitem__(self, index): return self.factors[index] def __setitem__(self, index, value): self.factors[index] = value def __iter__(self): for index in range(len(self)): yield self[index] def __len__(self): return len(self.factors) def __repr__(self): message = ( f"factors list : rank-{self.rank} tensor ring tensor of shape {self.shape}" ) return message def to_tensor(self): return tr_to_tensor(self) def to_unfolding(self, mode): return tr_to_unfolded(self, mode) def to_vec(self): return tr_to_vec(self)
3,661
logs
# Copyright 2021 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "LICENSE.txt" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES # OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions and # limitations under the License. import os from pcluster.aws.batch import BatchClient from pcluster.aws.cfn import CfnClient from pcluster.aws.dynamo import DynamoResource from pcluster.aws.ec2 import Ec2Client from pcluster.aws.efs import EfsClient from pcluster.aws.elb import ElbClient from pcluster.aws.fsx import FSxClient from pcluster.aws.iam import IamClient from pcluster.aws.imagebuilder import ImageBuilderClient from pcluster.aws.kms import KmsClient from pcluster.aws.METHOD_NAME import LogsClient from pcluster.aws.resource_groups import ResourceGroupsClient from pcluster.aws.route53 import Route53Client from pcluster.aws.s3 import S3Client from pcluster.aws.s3_resource import S3Resource from pcluster.aws.secretsmanager import SecretsManagerClient from pcluster.aws.ssm import SsmClient from pcluster.aws.sts import StsClient class AWSApi: """ Proxy class for all AWS API clients used in the CLI. A singleton instance can be retrieved from everywhere in the code by calling AWSApi.instance(). Specific API client wrappers are provided through properties of this instance; for instance AWSApi.instance().ec2 will return the client wrapper for EC2 service. """ _instance = None def __init__(self): self.aws_region = os.environ.get("AWS_DEFAULT_REGION") self._batch = None self._cfn = None self._ec2 = None self._efs = None self._elb = None self._fsx = None self._dynamodb = None self._s3 = None # pylint: disable=C0103 self._kms = None self._imagebuilder = None self._sts = None self._s3_resource = None self._iam = None self._ddb_resource = None self._logs = None self._route53 = None self._secretsmanager = None self._ssm = None self._resource_groups = None @property def cfn(self): """CloudFormation client.""" # noqa: D403 if not self._cfn: self._cfn = CfnClient() return self._cfn @property def batch(self): """AWS Batch client.""" if not self._batch: self._batch = BatchClient() return self._batch @property def ec2(self): """EC2 client.""" if not self._ec2: self._ec2 = Ec2Client() return self._ec2 @property def efs(self): """EFS client.""" if not self._efs: self._efs = EfsClient(ec2_client=self.ec2) return self._efs @property def elb(self): """ELB client.""" if not self._elb: self._elb = ElbClient() return self._elb @property def fsx(self): """FSX client.""" if not self._fsx: self._fsx = FSxClient() return self._fsx @property def s3(self): # pylint: disable=C0103 """S3 client.""" if not self._s3: self._s3 = S3Client() return self._s3 @property def kms(self): """KMS client.""" if not self._kms: self._kms = KmsClient() return self._kms @property def imagebuilder(self): """ImageBuilder client.""" # noqa: D403 if not self._imagebuilder: self._imagebuilder = ImageBuilderClient() return self._imagebuilder @property def sts(self): """STS client.""" if not self._sts: self._sts = StsClient() return self._sts @property def s3_resource(self): """S3Resource client.""" if not self._s3_resource: self._s3_resource = S3Resource() return self._s3_resource @property def iam(self): """IAM client.""" if not self._iam: self._iam = IamClient() return self._iam @property def ddb_resource(self): """DynamoResource client.""" # noqa: D403 if not self._ddb_resource: self._ddb_resource = DynamoResource() return self._ddb_resource @property def METHOD_NAME(self): """Log client.""" if not self._logs: self._logs = LogsClient() return self._logs @property def route53(self): """Route53 client.""" if not self._route53: self._route53 = Route53Client() return self._route53 @property def secretsmanager(self): """Secrets Manager client.""" if not self._secretsmanager: self._secretsmanager = SecretsManagerClient() return self._secretsmanager @property def ssm(self): """SSM client.""" if not self._ssm: self._ssm = SsmClient() return self._ssm @property def resource_groups(self): """Resource Groups client.""" if not self._resource_groups: self._resource_groups = ResourceGroupsClient() return self._resource_groups @staticmethod def instance(): """Return the singleton AWSApi instance.""" if not AWSApi._instance or AWSApi._instance.aws_region != os.environ.get("AWS_DEFAULT_REGION"): AWSApi._instance = AWSApi() return AWSApi._instance @staticmethod def reset(): """Reset the instance to clear all caches.""" AWSApi._instance = None class KeyPairInfo: """Object to store Ec2 Keypair information, initialized with the key name.""" def __init__(self, key_name: str): self.key_name = key_name self.key_data = AWSApi.instance().ec2.describe_key_pair(key_name) self.key_type = self.key_data["KeyPairs"][0]["KeyType"]
3,662
method or attr
import __main__ import re class Completer: """ [FUTURE] """ def __init__(self, namespace = None): """Create a new completer for the command line. Completer([namespace]) -> completer instance. Completer instances should be used as the completion mechanism of readline via the set_completer() call: readline.set_completer(Completer(my_namespace).complete) """ if namespace and not isinstance(namespace, dict): raise TypeError('namespace must be a dictionary') # Don't bind to namespace quite yet, but flag whether the user wants a # specific namespace or to use __main__.__dict__. This will allow us # to bind to __main__.__dict__ at completion time, not now. if namespace is None: self.use_main_ns = 1 else: self.use_main_ns = 0 self.namespace = namespace def complete(self, text, state): """Return the next possible completion for 'text'. This is called successively with state == 0, 1, 2, ... until it returns None. The completion should begin with 'text'. """ if self.use_main_ns: self.namespace = __main__.__dict__ if state == 0: self.matches = self.attr_matches(text) try: return self.matches[state] except IndexError: return None def attr_matches(self, text): """Compute matches when text contains a dot. Assuming the text is of the form NAME.NAME....[NAME], and is evaluable in self.namespace, it will be evaluated and its attributes (as revealed by dir()) are used as possible completions. (For class instances, class members are also considered.) WARNING: this can still invoke arbitrary C code, if an object with a __getattr__ hook is evaluated. """ def METHOD_NAME(thisobject, item): # decide whether to append a '(' to the end of the attr based # on whether its callable if hasattr(getattr(thisobject, item), '__call__'): return item + '(' else: return item tb_compl_commands = { '.': {}, '[': {}, '.get(': {}, '.set(': {}, '.filter(': {}, '.filter_or_get(': {}, '.get_parameter(': {}, '.remove_parameter(': {}, '.remove_parameters_all(': {}, '.get_value(': {}, '.set_value(': {}, '.set_value_all(': {}, # TODO: default_unit, adjust, prior, posterior, enabled? '.get_history(': {'context': 'history'}, '.remove_history(': {'context': 'history'}, '.get_component(': {'context': 'system'}, '.remove_component(': {'context': 'system'}, '.get_mesh(': {'context': 'mesh'}, '.remove_mesh(': {'context': 'mesh'}, '.get_constraint(': {'context': 'constraint'}, '.remove_constraint(': {'context': 'constraint'}, '.flip_constraint(': {'context': 'constraint'}, '.run_constraint(': {'context': 'constraint'}, '.get_compute(': {'context': 'compute'}, '.remove_compute(': {'context': 'compute'}, '.run_compute(': {'context': 'compute'}, '.get_distribution(': {'context': 'distribution'}, '.sample_distribution(': {'context': 'distribution'}, '.remove_distribution(': {'context': 'distribution'}, '.get_solver(': {'context': 'solver'}, '.remove_solver(': {'context': 'solver'}, '.run_solver(': {'context': 'solver'}, '.get_solution(': {'context': 'solution'}, '.remove_solution(': {'context': 'solution'}, # TODO: plots, plugins } expr = None for cmd,filter_kwargs in tb_compl_commands.items(): if cmd in text: expr, attr = text.rsplit(cmd, 1) #~ if len(attr)==0: #~ return [] if attr[0] not in ["'",'"'] and cmd != '.': return [] else: if cmd == '.': # then we're just looking for attributes and don't # need to offset for the ' or " stringchar = '' attr = attr else: # then we're the first argument of some method # and need to account for the starting ' or " stringchar = attr[0] attr = attr[1:] break if expr is None: # then we haven't found a match return [] try: thisobject = eval(expr, self.namespace) except Exception: return [] if cmd == '.': # then we're looking for attributes of thisobject (PS or bundle) that start with attr words = [METHOD_NAME(thisobject, item) for item in dir(thisobject) if item[:len(attr)] == attr] else: # then we're looking to autocomplete the twig attr for thisobject (PS or bundle) words = thisobject.filter_or_get(attr, autocomplete=True, **filter_kwargs) matches = [] n = len(attr) for word in words: matches.append('{}{}{}{}'.format(expr,cmd,stringchar,word)) return matches
3,663
imread
# Copyright 2020,2021 Sony Corporation. # 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. from __future__ import absolute_import, division import numpy as np import pydicom from .common import _imread_before, _imread_after from .image_utils_backend import ImageUtilsBackend def _apply_gamma_correction(dicom_dataset): d_min = 0 d_max = 255 bpp = dicom_dataset.BitsAllocated spp = dicom_dataset.SamplesPerPixel if 'WindowCenter' in dicom_dataset: win_center = float(dicom_dataset.WindowCenter) else: win_center = (1 << bpp) / 2 if 'WindowWidth' in dicom_dataset: win_width = float(dicom_dataset.WindowWidth) else: win_width = (1 << bpp) ################ NCTB ####### if 'PhotometricInterpretation' in dicom_dataset: photo_interpretation = dicom_dataset.PhotometricInterpretation else: photo_interpretation = 'MONOCHROME2' if 'RescaleSlope' in dicom_dataset: rescale_slope = float(dicom_dataset.RescaleSlope) else: rescale_slope = 1.0 if 'RescaleIntercept' in dicom_dataset: rescale_intercept = float(dicom_dataset.RescaleIntercept) else: rescale_intercept = 0 ############################ win_max = win_center + 0.5 * win_width - 0.5 win_min = win_max - win_width - 0.5 range = max(win_max - win_min, 1) factor = (d_max - d_min) / range img = np.array(dicom_dataset.pixel_array) dtype = img.dtype if photo_interpretation == 'MONOCHROME1': img = (1 << bpp) - (img * rescale_slope + rescale_intercept) img = img.astype(dtype) else: img = (img * rescale_slope + rescale_intercept).astype(dtype) dest = np.zeros_like(img).astype(np.uint8) dest[img <= win_min] = d_min dest[img > win_max] = d_max dest[(win_min < img) & (img <= win_max)] = ( img[(win_min < img) & (img <= win_max)] - win_min) * factor + d_min if spp == 1: rgb_img = np.stack([dest, dest, dest], axis=2) else: rgb_img = dest return rgb_img class DicomBackend(ImageUtilsBackend): def __init__(self): ImageUtilsBackend.__init__(self) def accept(self, path, ext, operator): if operator in ['resize', 'save']: return "NG" else: if ext in ['.dcm', '.dicom']: return "OK" else: return "NG" def METHOD_NAME(self, path, grayscale=False, size=None, interpolate="bilinear", channel_first=False, as_uint16=False, num_channels=-1, return_palette_indices=False): """ Read image by DICOM module. Notice that PIL only supports uint8 for RGB (not uint16). So this imread function returns only uint8 array for both RGB and gray-scale. (Currently ignore "I" mode for gray-scale (32bit integer).) Args: path (str or 'file object'): File path or object to read. grayscale (bool): size (tupple of int): (width, height). If None, output img shape depends on the files to read. channel_first (bool): This argument specifies the shape of img is whether (height, width, channel) or (channel, height, width). Default value is False, which means the img shape is (height, width, channel). interpolate (str): must be one of ["nearest", "box", "bilinear", "hamming", "bicubic", "lanczos"]. as_uint16 (bool): If you specify this argument, you can use only False for pil backend. num_channels (int): channel size of output array. Default is -1 which preserves raw image shape. return_palette_indices (bool): Whether to return a raw palette indices without any conversion or not. If this flag is True and read Image has the mode "P", then this function returns 2-D array containing the indices into palette. We recommend that this flag should be False unless you intend to use the raw palette indices. Returns: numpy.ndarray """ _imread_before(grayscale, num_channels) dicom_dataset = pydicom.dcmread(path) img = _apply_gamma_correction(dicom_dataset) return _imread_after(img, size, interpolate, channel_first, self.imresize)
3,664
get storage account credential
# coding=utf-8 # *** WARNING: this file was generated by pulumi. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import copy import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities from . import outputs __all__ = [ 'GetStorageAccountCredentialResult', 'AwaitableGetStorageAccountCredentialResult', 'get_storage_account_credential', 'get_storage_account_credential_output', ] @pulumi.output_type class GetStorageAccountCredentialResult: """ The storage account credential. """ def __init__(__self__, access_key=None, end_point=None, id=None, kind=None, name=None, ssl_status=None, type=None, volumes_count=None): if access_key and not isinstance(access_key, dict): raise TypeError("Expected argument 'access_key' to be a dict") pulumi.set(__self__, "access_key", access_key) if end_point and not isinstance(end_point, str): raise TypeError("Expected argument 'end_point' to be a str") pulumi.set(__self__, "end_point", end_point) if id and not isinstance(id, str): raise TypeError("Expected argument 'id' to be a str") pulumi.set(__self__, "id", id) if kind and not isinstance(kind, str): raise TypeError("Expected argument 'kind' to be a str") pulumi.set(__self__, "kind", kind) if name and not isinstance(name, str): raise TypeError("Expected argument 'name' to be a str") pulumi.set(__self__, "name", name) if ssl_status and not isinstance(ssl_status, str): raise TypeError("Expected argument 'ssl_status' to be a str") pulumi.set(__self__, "ssl_status", ssl_status) if type and not isinstance(type, str): raise TypeError("Expected argument 'type' to be a str") pulumi.set(__self__, "type", type) if volumes_count and not isinstance(volumes_count, int): raise TypeError("Expected argument 'volumes_count' to be a int") pulumi.set(__self__, "volumes_count", volumes_count) @property @pulumi.getter(name="accessKey") def access_key(self) -> Optional['outputs.AsymmetricEncryptedSecretResponse']: """ The details of the storage account password. """ return pulumi.get(self, "access_key") @property @pulumi.getter(name="endPoint") def end_point(self) -> str: """ The storage endpoint """ return pulumi.get(self, "end_point") @property @pulumi.getter def id(self) -> str: """ The path ID that uniquely identifies the object. """ return pulumi.get(self, "id") @property @pulumi.getter def kind(self) -> Optional[str]: """ The Kind of the object. Currently only Series8000 is supported """ return pulumi.get(self, "kind") @property @pulumi.getter def name(self) -> str: """ The name of the object. """ return pulumi.get(self, "name") @property @pulumi.getter(name="sslStatus") def ssl_status(self) -> str: """ Signifies whether SSL needs to be enabled or not. """ return pulumi.get(self, "ssl_status") @property @pulumi.getter def type(self) -> str: """ The hierarchical type of the object. """ return pulumi.get(self, "type") @property @pulumi.getter(name="volumesCount") def volumes_count(self) -> int: """ The count of volumes using this storage account credential. """ return pulumi.get(self, "volumes_count") class AwaitableGetStorageAccountCredentialResult(GetStorageAccountCredentialResult): # pylint: disable=using-constant-test def __await__(self): if False: yield self return GetStorageAccountCredentialResult( access_key=self.access_key, end_point=self.end_point, id=self.id, kind=self.kind, name=self.name, ssl_status=self.ssl_status, type=self.type, volumes_count=self.volumes_count) def METHOD_NAME(manager_name: Optional[str] = None, resource_group_name: Optional[str] = None, storage_account_credential_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetStorageAccountCredentialResult: """ Gets the properties of the specified storage account credential name. Azure REST API version: 2017-06-01. :param str manager_name: The manager name :param str resource_group_name: The resource group name :param str storage_account_credential_name: The name of storage account credential to be fetched. """ __args__ = dict() __args__['managerName'] = manager_name __args__['resourceGroupName'] = resource_group_name __args__['storageAccountCredentialName'] = storage_account_credential_name opts = pulumi.InvokeOptions.merge(_utilities.get_invoke_opts_defaults(), opts) __ret__ = pulumi.runtime.invoke('azure-native:storsimple:getStorageAccountCredential', __args__, opts=opts, typ=GetStorageAccountCredentialResult).value return AwaitableGetStorageAccountCredentialResult( access_key=pulumi.get(__ret__, 'access_key'), end_point=pulumi.get(__ret__, 'end_point'), id=pulumi.get(__ret__, 'id'), kind=pulumi.get(__ret__, 'kind'), name=pulumi.get(__ret__, 'name'), ssl_status=pulumi.get(__ret__, 'ssl_status'), type=pulumi.get(__ret__, 'type'), volumes_count=pulumi.get(__ret__, 'volumes_count')) @_utilities.lift_output_func(METHOD_NAME) def get_storage_account_credential_output(manager_name: Optional[pulumi.Input[str]] = None, resource_group_name: Optional[pulumi.Input[str]] = None, storage_account_credential_name: Optional[pulumi.Input[str]] = None, opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetStorageAccountCredentialResult]: """ Gets the properties of the specified storage account credential name. Azure REST API version: 2017-06-01. :param str manager_name: The manager name :param str resource_group_name: The resource group name :param str storage_account_credential_name: The name of storage account credential to be fetched. """ ...
3,665
asksaveasfilename
# # Instant Python # $Id: tkFileDialog.py 36560 2004-07-18 06:16:08Z tim_one $ # # tk common file dialogues # # this module provides interfaces to the native file dialogues # available in Tk 4.2 and newer, and the directory dialogue available # in Tk 8.3 and newer. # # written by Fredrik Lundh, May 1997. # # # options (all have default values): # # - defaultextension: added to filename if not explicitly given # # - filetypes: sequence of (label, pattern) tuples. the same pattern # may occur with several patterns. use "*" as pattern to indicate # all files. # # - initialdir: initial directory. preserved by dialog instance. # # - initialfile: initial file (ignored by the open dialog). preserved # by dialog instance. # # - parent: which window to place the dialog on top of # # - title: dialog title # # - multiple: if true user may select more than one file # # options for the directory chooser: # # - initialdir, parent, title: see above # # - mustexist: if true, user must pick an existing directory # # from tkCommonDialog import Dialog class _Dialog(Dialog): def _fixoptions(self): try: # make sure "filetypes" is a tuple self.options["filetypes"] = tuple(self.options["filetypes"]) except KeyError: pass def _fixresult(self, widget, result): if result: # keep directory and filename until next time import os # convert Tcl path objects to strings try: result = result.string except AttributeError: # it already is a string pass path, file = os.path.split(result) self.options["initialdir"] = path self.options["initialfile"] = file self.filename = result # compatibility return result # # file dialogs class Open(_Dialog): "Ask for a filename to open" command = "tk_getOpenFile" def _fixresult(self, widget, result): if isinstance(result, tuple): # multiple results: result = tuple([getattr(r, "string", r) for r in result]) if result: import os path, file = os.path.split(result[0]) self.options["initialdir"] = path # don't set initialfile or filename, as we have multiple of these return result if not widget.tk.wantobjects() and "multiple" in self.options: # Need to split result explicitly return self._fixresult(widget, widget.tk.splitlist(result)) return _Dialog._fixresult(self, widget, result) class SaveAs(_Dialog): "Ask for a filename to save as" command = "tk_getSaveFile" # the directory dialog has its own _fix routines. class Directory(Dialog): "Ask for a directory" command = "tk_chooseDirectory" def _fixresult(self, widget, result): if result: # convert Tcl path objects to strings try: result = result.string except AttributeError: # it already is a string pass # keep directory until next time self.options["initialdir"] = result self.directory = result # compatibility return result # # convenience stuff def askopenfilename(**options): "Ask for a filename to open" return Open(**options).show() def METHOD_NAME(**options): "Ask for a filename to save as" return SaveAs(**options).show() def askopenfilenames(**options): """Ask for multiple filenames to open Returns a list of filenames or empty list if cancel button selected """ options["multiple"]=1 return Open(**options).show() # FIXME: are the following perhaps a bit too convenient? def askopenfile(mode = "r", **options): "Ask for a filename to open, and returned the opened file" filename = Open(**options).show() if filename: return open(filename, mode) return None def askopenfiles(mode = "r", **options): """Ask for multiple filenames and return the open file objects returns a list of open file objects or an empty list if cancel selected """ files = askopenfilenames(**options) if files: ofiles=[] for filename in files: ofiles.append(open(filename, mode)) files=ofiles return files def asksaveasfile(mode = "w", **options): "Ask for a filename to save as, and returned the opened file" filename = SaveAs(**options).show() if filename: return open(filename, mode) return None def askdirectory (**options): "Ask for a directory, and return the file name" return Directory(**options).show() # -------------------------------------------------------------------- # test stuff if __name__ == "__main__": # Since the file name may contain non-ASCII characters, we need # to find an encoding that likely supports the file name, and # displays correctly on the terminal. # Start off with UTF-8 enc = "utf-8" import sys # See whether CODESET is defined try: import locale locale.setlocale(locale.LC_ALL,'') enc = locale.nl_langinfo(locale.CODESET) except (ImportError, AttributeError): pass # dialog for openening files openfilename=askopenfilename(filetypes=[("all files", "*")]) try: fp=open(openfilename,"r") fp.close() except: print "Could not open File: " print sys.exc_info()[1] print "open", openfilename.encode(enc) # dialog for saving files saveasfilename=METHOD_NAME() print "saveas", saveasfilename.encode(enc)
3,666
get test list
# Copyright 2019 Axel Huebl, Luca Fedeli, Maxence Thevenet # # # This file is part of WarpX. # # License: BSD-3-Clause-LBNL # requirements: # - module load python/3.7.0-anaconda3-5.3.0 import copy import os from functions_perftest import test_element def executable_name(compiler,architecture): return 'perf_tests3d.' + compiler + '.TPROF.MTMPI.CUDA.QED.GPUCLOCK.ex' def get_config_command(compiler, architecture): config_command = '' config_command += 'module load gcc;' config_command += 'module load cuda;' return config_command # This function runs a batch script with # dependencies to perform the analysis # after all performance tests are done. def process_analysis(automated, cwd, compiler, architecture, n_node_list, start_date, path_source, path_results): batch_string = '''#!/bin/bash #BSUB -P APH114 #BSUB -W 00:10 #BSUB -nnodes 1 #BSUB -J perf_test #BSUB -o read_output.txt #BSUB -e read_error.txt ''' f_log = open(cwd + 'log_jobids_tmp.txt' ,'r') for line in f_log.readlines(): dependency = line.split()[1][1:-1] batch_string += '#BSUB -w ended(' + dependency + ')\n' batch_string += 'python run_automated.py --compiler=' + \ compiler + ' --architecture=' + architecture + \ ' --mode=read' + \ ' --n_node_list=' + '"' + n_node_list + '"' + \ ' --start_date=' + start_date + \ ' --path_source=' + path_source + \ ' --path_results=' + path_results if automated == True: batch_string += ' --automated' batch_string += '\n' batch_file = 'bsub_perfread' f_exe = open(batch_file,'w') f_exe.write(batch_string) f_exe.close() os.system('chmod 700 ' + batch_file) print( 'process_analysis line: ' + 'bsub ' + batch_file) os.system('bsub ' + batch_file) # Calculate simulation time. Take 2 min + 2 min / simulation def time_min(nb_simulations): return 2. + nb_simulations*2. def get_submit_job_command(): return ' bsub ' def get_batch_string(test_list, job_time_min, Cname, n_node): job_time_str = str(int(job_time_min/60)) + ':' + str(int(job_time_min%60)) batch_string = '' batch_string += '#!/bin/bash\n' batch_string += '#BSUB -P APH114\n' batch_string += '#BSUB -W ' + job_time_str + '\n' batch_string += '#BSUB -nnodes ' + str(n_node) + '\n' batch_string += '#BSUB -J ' + test_list[0].input_file + '\n' batch_string += '#BSUB -e error.txt\n' batch_string += 'module load gcc\n' batch_string += 'module load cuda\n' return batch_string def get_run_string(current_test, architecture, n_node, count, bin_name, runtime_param_string): output_filename = 'out_' + '_'.join([current_test.input_file, str(n_node), str(current_test.n_mpi_per_node), str(current_test.n_omp), str(count)]) + '.txt' ngpu = str(current_test.n_mpi_per_node) srun_string = '' srun_string += 'jsrun ' srun_string += ' -n ' + str(n_node) srun_string += ' -a ' + ngpu + ' -g ' + ngpu + ' -c ' + ngpu + ' --bind=packed:1 ' srun_string += ' ./' + bin_name + ' ' srun_string += current_test.input_file + ' ' srun_string += runtime_param_string srun_string += ' > ' + output_filename + '\n' return srun_string def METHOD_NAME(n_repeat): test_list_unq = [] # n_node is kept to None and passed in functions as an external argument # That way, several test_element_instance run with the same n_node on the same batch job test_list_unq.append( test_element(input_file='automated_test_1_uniform_rest_32ppc', n_mpi_per_node=6, n_omp=1, n_cell=[128, 128, 192], max_grid_size=256, blocking_factor=32, n_step=10) ) test_list_unq.append( test_element(input_file='automated_test_2_uniform_rest_1ppc', n_mpi_per_node=6, n_omp=1, n_cell=[256, 512, 768], max_grid_size=512, blocking_factor=256, n_step=10) ) test_list_unq.append( test_element(input_file='automated_test_3_uniform_drift_4ppc', n_mpi_per_node=6, n_omp=1, n_cell=[128, 128, 384], max_grid_size=256, blocking_factor=64, n_step=10) ) test_list_unq.append( test_element(input_file='automated_test_4_labdiags_2ppc', n_mpi_per_node=6, n_omp=1, n_cell=[384, 256, 512], max_grid_size=256, blocking_factor=128, n_step=50) ) test_list_unq.append( test_element(input_file='automated_test_5_loadimbalance', n_mpi_per_node=6, n_omp=1, n_cell=[64, 64, 192], max_grid_size=64, blocking_factor=32, n_step=10) ) test_list_unq.append( test_element(input_file='automated_test_6_output_2ppc', n_mpi_per_node=6, n_omp=1, n_cell=[384, 256, 512], max_grid_size=256, blocking_factor=64, n_step=1) ) test_list = [copy.deepcopy(item) for item in test_list_unq for _ in range(n_repeat) ] return test_list
3,667
test scalar
# Copyright 2017 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. # ============================================================================= """Tests for tpu_function helpers.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.framework import tensor_shape from tensorflow.python.platform import test from tensorflow.python.tpu import tpu_sharding class ShardingTest(test.TestCase): def testFreeze(self): """Tests that freezing a policy applies default values.""" p1 = tpu_sharding.ShardingPolicy() p1.freeze() self.assertEqual(p1.number_of_shards, tpu_sharding._DEFAULT_NUMBER_OF_SHARDS) self.assertEqual(p1.shard_dimension, tpu_sharding._DEFAULT_SHARD_DIMENSION) p2 = tpu_sharding.ShardingPolicy() p2.set_number_of_shards(17) p2.set_shard_dimension(23) p2.freeze() self.assertEqual(p2.number_of_shards, 17) self.assertEqual(p2.shard_dimension, 23) def testFrozen(self): """Tests that frozen policies can't be changed.""" p1 = tpu_sharding.ShardingPolicy() p1.freeze() with self.assertRaises(ValueError): p1.set_number_of_shards(17) with self.assertRaises(ValueError): p1.set_shard_dimension(22) def testStr(self): """Tests the string representation.""" p1 = tpu_sharding.ShardingPolicy() self.assertEqual(str(p1), "ShardingPolicy(unset)") p1.set_number_of_shards(17) self.assertEqual(str(p1), "ShardingPolicy(unset)") p1.set_shard_dimension(8) self.assertEqual(str(p1), "ShardingPolicy(17 shards dimension 8)") def testMerge(self): """Tests that merging works.""" p1 = tpu_sharding.ShardingPolicy() p1.set_number_of_shards(17) p1.set_shard_dimension(23) p2 = tpu_sharding.ShardingPolicy() p2.merge(p1) self.assertEqual(p2.number_of_shards, 17) self.assertEqual(p2.shard_dimension, 23) p1 = tpu_sharding.ShardingPolicy() p1.set_shard_dimension(12) p2.merge(p1) self.assertEqual(p2.number_of_shards, 17) self.assertEqual(p2.shard_dimension, 12) p2.freeze() p2.merge(p1) self.assertEqual(p2.number_of_shards, 17) self.assertEqual(p2.shard_dimension, 12) p1.set_number_of_shards(1) with self.assertRaises(ValueError): p2.merge(p1) p1 = tpu_sharding.ShardingPolicy() p1.set_number_of_shards(17) p2.merge(p1) p1.set_shard_dimension(2) with self.assertRaises(ValueError): p2.merge(p1) def testGetShardedShape(self): """Tests getting a sharded shape.""" p = tpu_sharding.ShardingPolicy() p.set_number_of_shards(3) p.set_shard_dimension(1) self.assertEqual(p.get_sharded_shape([4, 9]), [4, 3]) p.freeze() with self.assertRaises(ValueError): p.set_shard_dimension(0) with self.assertRaises(ValueError): _ = p.get_sharded_shape([4, 9], shard_index=4) with self.assertRaises(ValueError): _ = p.get_sharded_shape([4, 9], shard_index=-1) with self.assertRaises(TypeError): _ = p.get_sharded_shape("not_a_shape") with self.assertRaises(ValueError): _ = p.get_sharded_shape(tensor_shape.TensorShape(None)) with self.assertRaises(ValueError): _ = p.get_sharded_shape([4, 10], shard_index=-1) def testGetUnshardedShape(self): """Tests getting an unsharded shape.""" p = tpu_sharding.ShardingPolicy() p.set_number_of_shards(2) p.set_shard_dimension(1) self.assertEqual(p.get_unsharded_shape([[4, 3], [4, 3]]), [4, 6]) with self.assertRaises(ValueError): _ = p.get_unsharded_shape([[4, 3]]) with self.assertRaises(ValueError): _ = p.get_unsharded_shape([[4, 3], [4, 3], [4, 3]]) with self.assertRaises(ValueError): _ = p.get_unsharded_shape([[4, 3], [4, 2]]) with self.assertRaises(TypeError): _ = p.get_unsharded_shape([[4, 3], "not_a_shape"]) with self.assertRaises(ValueError): _ = p.get_unsharded_shape([None, [4, 3]]) with self.assertRaises(ValueError): _ = p.get_unsharded_shape([[2], [4, 3]]) def METHOD_NAME(self): """Tests sharding and unsharding scalars.""" p = tpu_sharding.ShardingPolicy() p.freeze() self.assertEqual(p.get_sharded_shape([]), []) self.assertEqual(p.get_unsharded_shape([[]]), []) if __name__ == "__main__": test.main()
3,668
on message sent
from pychess.System.Log import log from pychess.System.prefix import addDataPrefix from pychess.Utils.const import LOCAL from pychess.widgets.ChatView import ChatView from pychess.ic.ICGameModel import ICGameModel from pychess.ic.icc import DG_PLAYERS_IN_MY_GAME __title__ = _("Chat") __icon__ = addDataPrefix("glade/panel_chat.svg") __desc__ = _( "The chat panel lets you communicate with your opponent during the game, assuming he or she is interested" ) class Sidepanel: def load(self, gmwidg): self.gamemodel = gmwidg.gamemodel self.player_cid = None self.model_cids = [ self.gamemodel.connect("game_started", self.onGameStarted), self.gamemodel.connect_after("game_terminated", self.on_game_terminated), ] self.chatView = ChatView(self.gamemodel) self.chatView.disable("Waiting for game to load") self.chatview_cid = self.chatView.connect("messageTyped", self.METHOD_NAME) if isinstance(self.gamemodel, ICGameModel): self.model_cids.append( self.gamemodel.connect( "observers_received", self.chatView.update_observers ) ) self.model_cids.append( self.gamemodel.connect("message_received", self.onICMessageReieved) ) return self.chatView def on_game_terminated(self, model): self.chatView.disconnect(self.chatview_cid) if ( hasattr(self, "player") and hasattr(self, "player_cid") and not self.gamemodel.examined ): self.player.disconnect(self.player_cid) for cid in self.model_cids: self.gamemodel.disconnect(cid) def onGameStarted(self, gamemodel): if gamemodel.examined: if gamemodel.players[0].name == gamemodel.connection.username: self.player = gamemodel.players[0] self.opplayer = gamemodel.players[1] else: self.player = gamemodel.players[1] self.opplayer = gamemodel.players[0] elif gamemodel.isObservationGame(): # no local player but enable chat to send/receive whisper/kibitz pass elif gamemodel.players[0].__type__ == LOCAL: self.player = gamemodel.players[0] self.opplayer = gamemodel.players[1] if gamemodel.players[1].__type__ == LOCAL: log.warning("Chatpanel loaded with two local players") elif gamemodel.players[1].__type__ == LOCAL: self.player = gamemodel.players[1] self.opplayer = gamemodel.players[0] else: log.info("Chatpanel loaded with no local players") self.chatView.hide() if isinstance(gamemodel, ICGameModel): if gamemodel.connection.ICC: gamemodel.connection.client.run_command( "set-2 %s 1" % DG_PLAYERS_IN_MY_GAME ) else: allob = "allob " + str(gamemodel.ficsgame.gameno) gamemodel.connection.client.run_command(allob) if ( hasattr(self, "player") and not gamemodel.examined and self.player_cid is None ): self.player_cid = self.player.connect( "messageReceived", self.onMessageRecieved ) self.chatView.enable() def onMessageRecieved(self, player, text): sender = ( "pychessbot" if player.gamemodel.offline_lecture else repr(self.opplayer) ) self.chatView.addMessage(sender, text) def onICMessageReieved(self, icgamemodel, player, text): self.chatView.addMessage(player, text) # emit an allob <gameno> to FICS if not icgamemodel.connection.ICC: allob = "allob " + str(icgamemodel.ficsgame.gameno) icgamemodel.connection.client.run_command(allob) def METHOD_NAME(self, chatView, text): if hasattr(self, "player") or self.gamemodel.examined: if text.startswith("# "): text = text[2:] self.gamemodel.connection.cm.whisper(text) elif text.startswith("whisper "): text = text[8:] self.gamemodel.connection.cm.whisper(text) else: if not hasattr(self, "player"): if ( self.gamemodel.players[0].name == self.gamemodel.connection.username ): self.player = self.gamemodel.players[0] self.opplayer = self.gamemodel.players[1] else: self.player = self.gamemodel.players[1] self.opplayer = self.gamemodel.players[0] if self.gamemodel.examined: self.opplayer.putMessage(text) else: self.player.sendMessage(text) self.chatView.addMessage(repr(self.player), text) else: self.gamemodel.connection.cm.whisper(text)
3,669
test actions
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from django.test import TestCase from django.contrib import admin from ..admin.database_change_parameter import DatabaseChangeParameterAdmin from ..models import DatabaseChangeParameter from .factory import DatabaseChangeParameterFactory SEARCH_FIELDS = ("database__name", "task__id", "task__task_id") LIST_FILTER = [ "database__team", "status", ] LIST_DISPLAY = ( "database", "database_team", "current_step", "friendly_status", "maintenance_action", "link_task", "started_at", "finished_at" ) READONLY_FIELDS = ( "current_step_class", "database", "link_task", "started_at", "finished_at", "current_step", "status", "maintenance_action", "task_schedule" ) EXCLUDE = ("task", "can_do_retry") ORDERING = ["-started_at"] ACTIONS = None LIST_SELECT_RELATED = None NO_ACTION = 'N/A' class DatabaseChangeParameterTestCase(TestCase): def setUp(self): self.database_change_parameter = DatabaseChangeParameterFactory() self.admin = DatabaseChangeParameterAdmin( DatabaseChangeParameter, admin.sites.AdminSite() ) def tearDown(self): self.database_change_parameter.delete() def test_search_fields(self): self.assertEqual(SEARCH_FIELDS, self.admin.search_fields) def test_list_fields(self): self.assertEqual(LIST_FILTER, self.admin.list_filter) def test_list_display(self): self.assertEqual(LIST_DISPLAY, self.admin.list_display) def test_readonly_fields(self): self.assertEqual(READONLY_FIELDS, self.admin.readonly_fields) def test_exclude(self): self.assertEqual(EXCLUDE, self.admin.exclude) def test_ordering(self): self.assertEqual(ORDERING, self.admin.ordering) def METHOD_NAME(self): self.assertEqual(ACTIONS, self.admin.actions) def test_list_select_related(self): self.assertEqual(LIST_SELECT_RELATED, self.admin.list_select_related) def test_cannot_add(self): self.assertFalse(self.admin.has_add_permission(None)) def test_cannot_delete(self): self.assertFalse(self.admin.has_delete_permission(None)) def test_friendly_status_waiting(self): self.database_change_parameter.status = DatabaseChangeParameter.WAITING status_html = self.admin.friendly_status( self.database_change_parameter ) self.assertIn('label-warning', status_html) self.assertIn('Waiting', status_html) def test_friendly_status_running(self): self.database_change_parameter.status = DatabaseChangeParameter.RUNNING status_html = self.admin.friendly_status( self.database_change_parameter ) self.assertIn('label-success', status_html) self.assertIn('Running', status_html) def test_friendly_status_error(self): self.database_change_parameter.status = DatabaseChangeParameter.ERROR status_html = self.admin.friendly_status( self.database_change_parameter ) self.assertIn('label-important', status_html) self.assertIn('Error', status_html) def test_friendly_status_success(self): self.database_change_parameter.status = DatabaseChangeParameter.SUCCESS status_html = self.admin.friendly_status( self.database_change_parameter ) self.assertIn('label-info', status_html) self.assertIn('Success', status_html) def test_database_team(self): database_team = self.database_change_parameter.database.team.name admin_team = self.admin.database_team(self.database_change_parameter) self.assertEqual(database_team, admin_team) def test_link_task(self): admin_task = self.admin.link_task(self.database_change_parameter) self.assertIn(str(self.database_change_parameter.task.id), admin_task) def test_maintenance_action(self): self.database_change_parameter.status = DatabaseChangeParameter.ERROR url = (self.database_change_parameter.database .get_change_parameters_retry_url()) button = self.admin.maintenance_action(self.database_change_parameter) self.assertIn(url, button) def test_maintenance_action_without_error_and_cannot_do_retry(self): self.database_change_parameter.status = DatabaseChangeParameter.SUCCESS self.database_change_parameter.can_do_retry = False button = self.admin.maintenance_action(self.database_change_parameter) self.assertEqual(NO_ACTION, button) def test_maintenance_action_with_error_and_cannot_do_retry(self): self.database_change_parameter.status = DatabaseChangeParameter.ERROR self.database_change_parameter.can_do_retry = False button = self.admin.maintenance_action(self.database_change_parameter) self.assertEqual(NO_ACTION, button) def test_maintenance_action_without_error_and_can_do_retry(self): self.database_change_parameter.status = DatabaseChangeParameter.SUCCESS self.database_change_parameter.can_do_retry = True button = self.admin.maintenance_action(self.database_change_parameter) self.assertEqual(NO_ACTION, button) def test_maintenance_action_with_error_and_can_do_retry(self): self.database_change_parameter.status = DatabaseChangeParameter.ERROR self.database_change_parameter.can_do_retry = True url = (self.database_change_parameter .database.get_change_parameters_retry_url()) button = self.admin.maintenance_action(self.database_change_parameter) self.assertIn(url, button)
3,670
random boxes
# Copyright (c) Facebook, Inc. and its affiliates. import numpy as np import unittest from copy import copy import cv2 import torch from fvcore.common.benchmark import benchmark from torch.nn import functional as F from detectron2.layers.roi_align import ROIAlign, roi_align class ROIAlignTest(unittest.TestCase): def test_forward_output(self): input = np.arange(25).reshape(5, 5).astype("float32") """ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 """ output = self._simple_roialign(input, [1, 1, 3, 3], (4, 4), aligned=False) output_correct = self._simple_roialign(input, [1, 1, 3, 3], (4, 4), aligned=True) # without correction: old_results = [ [7.5, 8, 8.5, 9], [10, 10.5, 11, 11.5], [12.5, 13, 13.5, 14], [15, 15.5, 16, 16.5], ] # with 0.5 correction: correct_results = [ [4.5, 5.0, 5.5, 6.0], [7.0, 7.5, 8.0, 8.5], [9.5, 10.0, 10.5, 11.0], [12.0, 12.5, 13.0, 13.5], ] # This is an upsampled version of [[6, 7], [11, 12]] self.assertTrue(np.allclose(output.flatten(), np.asarray(old_results).flatten())) self.assertTrue( np.allclose(output_correct.flatten(), np.asarray(correct_results).flatten()) ) # Also see similar issues in tensorflow at # https://github.com/tensorflow/tensorflow/issues/26278 def test_resize(self): H, W = 30, 30 input = np.random.rand(H, W).astype("float32") * 100 box = [10, 10, 20, 20] output = self._simple_roialign(input, box, (5, 5), aligned=True) input2x = cv2.resize(input, (W // 2, H // 2), interpolation=cv2.INTER_LINEAR) box2x = [x / 2 for x in box] output2x = self._simple_roialign(input2x, box2x, (5, 5), aligned=True) diff = np.abs(output2x - output) self.assertTrue(diff.max() < 1e-4) def test_grid_sample_equivalence(self): H, W = 30, 30 input = np.random.rand(H, W).astype("float32") * 100 box = [10, 10, 20, 20] for ratio in [1, 2, 3]: output = self._simple_roialign(input, box, (5, 5), sampling_ratio=ratio) output_grid_sample = grid_sample_roi_align( torch.from_numpy(input[None, None, :, :]).float(), torch.as_tensor(box).float()[None, :], 5, 1.0, ratio, ) self.assertTrue(torch.allclose(output, output_grid_sample)) def _simple_roialign(self, img, box, resolution, sampling_ratio=0, aligned=True): """ RoiAlign with scale 1.0. """ if isinstance(resolution, int): resolution = (resolution, resolution) op = ROIAlign(resolution, 1.0, sampling_ratio, aligned=aligned) input = torch.from_numpy(img[None, None, :, :].astype("float32")) rois = [0] + list(box) rois = torch.from_numpy(np.asarray(rois)[None, :].astype("float32")) output = op.forward(input, rois) if torch.cuda.is_available(): output_cuda = op.forward(input.cuda(), rois.cuda()).cpu() self.assertTrue(torch.allclose(output, output_cuda)) return output[0, 0] def _simple_roialign_with_grad(self, img, box, resolution, device): if isinstance(resolution, int): resolution = (resolution, resolution) op = ROIAlign(resolution, 1.0, 0, aligned=True) input = torch.from_numpy(img[None, None, :, :].astype("float32")) rois = [0] + list(box) rois = torch.from_numpy(np.asarray(rois)[None, :].astype("float32")) input = input.to(device=device) rois = rois.to(device=device) input.requires_grad = True output = op.forward(input, rois) return input, output def test_empty_box(self): img = np.random.rand(5, 5) box = [3, 4, 5, 4] o = self._simple_roialign(img, box, 7) self.assertTrue(o.shape == (7, 7)) self.assertTrue((o == 0).all()) for dev in ["cpu"] + ["cuda"] if torch.cuda.is_available() else []: input, output = self._simple_roialign_with_grad(img, box, 7, torch.device(dev)) output.sum().backward() self.assertTrue(torch.allclose(input.grad, torch.zeros_like(input))) def test_empty_batch(self): input = torch.zeros(0, 3, 10, 10, dtype=torch.float32) rois = torch.zeros(0, 5, dtype=torch.float32) op = ROIAlign((7, 7), 1.0, 0, aligned=True) output = op.forward(input, rois) self.assertTrue(output.shape == (0, 3, 7, 7)) def grid_sample_roi_align(input, boxes, output_size, scale, sampling_ratio): # unlike true roi_align, this does not support different batch_idx from detectron2.projects.point_rend.point_features import ( generate_regular_grid_point_coords, get_point_coords_wrt_image, point_sample, ) N, _, H, W = input.shape R = len(boxes) assert N == 1 boxes = boxes * scale grid = generate_regular_grid_point_coords(R, output_size * sampling_ratio, device=boxes.device) coords = get_point_coords_wrt_image(boxes, grid) coords = coords / torch.as_tensor([W, H], device=coords.device) # R, s^2, 2 res = point_sample(input, coords.unsqueeze(0), align_corners=False) # 1,C, R,s^2 res = ( res.squeeze(0) .permute(1, 0, 2) .reshape(R, -1, output_size * sampling_ratio, output_size * sampling_ratio) ) res = F.avg_pool2d(res, sampling_ratio) return res def benchmark_roi_align(): def METHOD_NAME(mean_box, stdev, N, maxsize): ret = torch.rand(N, 4) * stdev + torch.tensor(mean_box, dtype=torch.float) ret.clamp_(min=0, max=maxsize) return ret def func(shape, nboxes_per_img, sampling_ratio, device, box_size="large"): N, _, H, _ = shape input = torch.rand(*shape) boxes = [] batch_idx = [] for k in range(N): if box_size == "large": b = METHOD_NAME([80, 80, 130, 130], 24, nboxes_per_img, H) else: b = METHOD_NAME([100, 100, 110, 110], 4, nboxes_per_img, H) boxes.append(b) batch_idx.append(torch.zeros(nboxes_per_img, 1, dtype=torch.float32) + k) boxes = torch.cat(boxes, axis=0) batch_idx = torch.cat(batch_idx, axis=0) boxes = torch.cat([batch_idx, boxes], axis=1) input = input.to(device=device) boxes = boxes.to(device=device) def bench(): if False and sampling_ratio > 0 and N == 1: # enable to benchmark grid_sample (slower) grid_sample_roi_align(input, boxes[:, 1:], 7, 1.0, sampling_ratio) else: roi_align(input, boxes, 7, 1.0, sampling_ratio, True) if device == "cuda": torch.cuda.synchronize() return bench def gen_args(arg): args = [] for size in ["small", "large"]: for ratio in [0, 2]: args.append(copy(arg)) args[-1]["sampling_ratio"] = ratio args[-1]["box_size"] = size return args arg = dict(shape=(1, 512, 256, 256), nboxes_per_img=512, device="cuda") benchmark(func, "cuda_roialign", gen_args(arg), num_iters=20, warmup_iters=1) arg.update({"device": "cpu", "shape": (1, 256, 128, 128)}) benchmark(func, "cpu_roialign", gen_args(arg), num_iters=5, warmup_iters=1) if __name__ == "__main__": if torch.cuda.is_available(): benchmark_roi_align() unittest.main()
3,671
array agg
# postgresql/ext.py # Copyright (C) 2005-2017 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php from ...sql import expression from ...sql import elements from ...sql import functions from ...sql.schema import ColumnCollectionConstraint from .array import ARRAY class aggregate_order_by(expression.ColumnElement): """Represent a PostgreSQL aggregate order by expression. E.g.:: from sqlalchemy.dialects.postgresql import aggregate_order_by expr = func.array_agg(aggregate_order_by(table.c.a, table.c.b.desc())) stmt = select([expr]) would represent the expression:: SELECT array_agg(a ORDER BY b DESC) FROM table; Similarly:: expr = func.string_agg( table.c.a, aggregate_order_by(literal_column("','"), table.c.a) ) stmt = select([expr]) Would represent:: SELECT string_agg(a, ',' ORDER BY a) FROM table; .. versionadded:: 1.1 .. seealso:: :class:`.array_agg` """ __visit_name__ = 'aggregate_order_by' def __init__(self, target, order_by): self.target = elements._literal_as_binds(target) self.order_by = elements._literal_as_binds(order_by) def self_group(self, against=None): return self def get_children(self, **kwargs): return self.target, self.order_by def _copy_internals(self, clone=elements._clone, **kw): self.target = clone(self.target, **kw) self.order_by = clone(self.order_by, **kw) @property def _from_objects(self): return self.target._from_objects + self.order_by._from_objects class ExcludeConstraint(ColumnCollectionConstraint): """A table-level EXCLUDE constraint. Defines an EXCLUDE constraint as described in the `postgres documentation`__. __ http://www.postgresql.org/docs/9.0/\ static/sql-createtable.html#SQL-CREATETABLE-EXCLUDE """ __visit_name__ = 'exclude_constraint' where = None def __init__(self, *elements, **kw): r""" Create an :class:`.ExcludeConstraint` object. E.g.:: const = ExcludeConstraint( (Column('period'), '&&'), (Column('group'), '='), where=(Column('group') != 'some group') ) The constraint is normally embedded into the :class:`.Table` construct directly, or added later using :meth:`.append_constraint`:: some_table = Table( 'some_table', metadata, Column('id', Integer, primary_key=True), Column('period', TSRANGE()), Column('group', String) ) some_table.append_constraint( ExcludeConstraint( (some_table.c.period, '&&'), (some_table.c.group, '='), where=some_table.c.group != 'some group', name='some_table_excl_const' ) ) :param \*elements: A sequence of two tuples of the form ``(column, operator)`` where "column" is a SQL expression element or a raw SQL string, most typically a :class:`.Column` object, and "operator" is a string containing the operator to use. .. note:: A plain string passed for the value of "column" is interpreted as an arbitrary SQL expression; when passing a plain string, any necessary quoting and escaping syntaxes must be applied manually. In order to specify a column name when a :class:`.Column` object is not available, while ensuring that any necessary quoting rules take effect, an ad-hoc :class:`.Column` or :func:`.sql.expression.column` object may be used. :param name: Optional, the in-database name of this constraint. :param deferrable: Optional bool. If set, emit DEFERRABLE or NOT DEFERRABLE when issuing DDL for this constraint. :param initially: Optional string. If set, emit INITIALLY <value> when issuing DDL for this constraint. :param using: Optional string. If set, emit USING <index_method> when issuing DDL for this constraint. Defaults to 'gist'. :param where: Optional SQL expression construct or literal SQL string. If set, emit WHERE <predicate> when issuing DDL for this constraint. .. note:: A plain string passed here is interpreted as an arbitrary SQL expression; when passing a plain string, any necessary quoting and escaping syntaxes must be applied manually. """ columns = [] render_exprs = [] self.operators = {} expressions, operators = zip(*elements) for (expr, column, strname, add_element), operator in zip( self._extract_col_expression_collection(expressions), operators ): if add_element is not None: columns.append(add_element) name = column.name if column is not None else strname if name is not None: # backwards compat self.operators[name] = operator expr = expression._literal_as_text(expr) render_exprs.append( (expr, name, operator) ) self._render_exprs = render_exprs ColumnCollectionConstraint.__init__( self, *columns, name=kw.get('name'), deferrable=kw.get('deferrable'), initially=kw.get('initially') ) self.using = kw.get('using', 'gist') where = kw.get('where') if where is not None: self.where = expression._literal_as_text(where) def copy(self, **kw): elements = [(col, self.operators[col]) for col in self.columns.keys()] c = self.__class__(*elements, name=self.name, deferrable=self.deferrable, initially=self.initially, where=self.where, using=self.using) c.dispatch._update(self.dispatch) return c def METHOD_NAME(*arg, **kw): """PostgreSQL-specific form of :class:`.array_agg`, ensures return type is :class:`.postgresql.ARRAY` and not the plain :class:`.types.ARRAY`. .. versionadded:: 1.1 """ kw['type_'] = ARRAY(functions._type_from_args(arg)) return functions.func.METHOD_NAME(*arg, **kw)
3,672
ingest
import magic import logging from tempfile import mkdtemp from datetime import datetime from pkg_resources import get_distribution from followthemoney import model from banal import ensure_list from normality import stringify from pantomime import normalize_mimetype from ftmstore.utils import safe_fragment from servicelayer.archive import init_archive from servicelayer.archive.util import ensure_path from servicelayer.extensions import get_extensions from sentry_sdk import capture_exception from followthemoney.helpers import entity_filename from followthemoney.namespace import Namespace from ingestors.directory import DirectoryIngestor from ingestors.exc import ProcessingException from ingestors.util import filter_text, remove_directory from ingestors import settings log = logging.getLogger(__name__) class Manager(object): """Handles the lifecycle of an ingestor. This can be subclassed to embed it into a larger processing framework.""" #: Indicates that during the processing no errors or failures occured. STATUS_SUCCESS = "success" #: Indicates occurance of errors during the processing. STATUS_FAILURE = "failure" MAGIC = magic.Magic(mime=True) def __init__(self, dataset, stage, context): self.dataset = dataset self.writer = dataset.bulk() self.stage = stage self.context = context self.ns = Namespace(self.context.get("namespace")) self.work_path = ensure_path(mkdtemp(prefix="ingestor-")) self.emitted = set() @property def archive(self): if not hasattr(settings, "_archive"): settings._archive = init_archive() return settings._archive def make_entity(self, schema, parent=None): schema = model.get(schema) entity = model.make_entity(schema, key_prefix=self.stage.job.dataset.name) self.make_child(parent, entity) return entity def make_child(self, parent, child): """Derive entity properties by knowing it's parent folder.""" if parent is not None and child is not None: # Folder hierarchy: child.add("parent", parent.id) child.add("ancestors", parent.get("ancestors")) child.add("ancestors", parent.id) self.apply_context(child, parent) def apply_context(self, entity, source): # Aleph-specific context data: entity.context = { "created_at": source.context.get("created_at"), "updated_at": source.context.get("updated_at"), "role_id": source.context.get("role_id"), "mutable": False, } def emit_entity(self, entity, fragment=None): entity = self.ns.apply(entity) self.writer.put(entity.to_dict(), fragment) self.emitted.add(entity.id) def emit_text_fragment(self, entity, texts, fragment): texts = [t for t in ensure_list(texts) if filter_text(t)] if len(texts): doc = self.make_entity(entity.schema) doc.id = entity.id doc.add("indexText", texts) self.emit_entity(doc, fragment=safe_fragment(fragment)) def auction(self, file_path, entity): if not entity.has("mimeType"): if file_path.is_dir(): entity.add("mimeType", DirectoryIngestor.MIME_TYPE) return DirectoryIngestor entity.add("mimeType", self.MAGIC.from_file(file_path.as_posix())) best_score, best_cls = 0, None for cls in get_extensions("ingestors"): score = cls.match(file_path, entity) if score > best_score: best_score = score best_cls = cls if best_cls is None: raise ProcessingException("Format not supported") return best_cls def queue_entity(self, entity): log.debug("Queue: %r", entity) self.stage.queue(entity.to_dict(), self.context) def store(self, file_path, mime_type=None): file_path = ensure_path(file_path) mime_type = normalize_mimetype(mime_type) if file_path is not None and file_path.is_file(): return self.archive.archive_file(file_path, mime_type=mime_type) def load(self, content_hash, file_name=None): # log.info("Local archive name: %s", file_name) return self.archive.load_file( content_hash, file_name=file_name, temp_path=self.work_path ) def ingest_entity(self, entity): for content_hash in entity.get("contentHash", quiet=True): file_name = entity_filename(entity) file_path = self.load(content_hash, file_name=file_name) if file_path is None or not file_path.exists(): log.warning( f"Couldn't find file named {file_name} at path {file_path}." "Skipping ingestion." ) continue self.METHOD_NAME(file_path, entity) return self.finalize(entity) def METHOD_NAME(self, file_path, entity, **kwargs): """Main execution step of an ingestor.""" file_path = ensure_path(file_path) if file_path.is_file() and not entity.has("fileSize"): entity.add("fileSize", file_path.stat().st_size) now = datetime.now() now_string = now.strftime("%Y-%m-%dT%H:%M:%S.%f") entity.set("processingStatus", self.STATUS_FAILURE) entity.set("processingAgent", get_distribution("ingest").version) entity.set("processedAt", now_string) try: ingestor_class = self.auction(file_path, entity) log.info("Ingestor [%r]: %s", entity, ingestor_class.__name__) self.delegate(ingestor_class, file_path, entity) entity.set("processingStatus", self.STATUS_SUCCESS) except ProcessingException as pexc: entity.set("processingError", stringify(pexc)) log.exception("[%r] Failed to process: %s", entity, pexc) capture_exception(pexc) finally: self.finalize(entity) def finalize(self, entity): self.emit_entity(entity) self.writer.flush() remove_directory(self.work_path) def delegate(self, ingestor_class, file_path, entity): ingestor_class(self).METHOD_NAME(file_path, entity) def close(self): self.writer.flush() remove_directory(self.work_path)
3,673
read image content
import base64 import io import json from typing import Any, Callable, Dict, cast import cloudpickle as pickle import pandas as pd from aqueduct_executor.operators.utils.enums import ArtifactType, SerializationType from PIL import Image _DEFAULT_ENCODING = "utf8" _DEFAULT_IMAGE_FORMAT = "jpeg" def _read_table_content(content: bytes) -> pd.DataFrame: return pd.read_json(io.BytesIO(content), orient="table") def _read_json_content(content: bytes) -> Any: return json.loads(content.decode(_DEFAULT_ENCODING)) def _read_pickle_content(content: bytes) -> Any: return pickle.loads(content) def METHOD_NAME(content: bytes) -> Image.Image: return Image.open(io.BytesIO(content)) def _read_string_content(content: bytes) -> str: return content.decode(_DEFAULT_ENCODING) def _read_bytes_content(content: bytes) -> bytes: return content deserialization_function_mapping: Dict[str, Callable[[bytes], Any]] = { SerializationType.TABLE: _read_table_content, SerializationType.JSON: _read_json_content, SerializationType.PICKLE: _read_pickle_content, SerializationType.IMAGE: METHOD_NAME, SerializationType.STRING: _read_string_content, SerializationType.BYTES: _read_bytes_content, } def _write_table_output(output: pd.DataFrame) -> bytes: output_str = cast(str, output.to_json(orient="table", date_format="iso", index=False)) return output_str.encode(_DEFAULT_ENCODING) def _write_image_output(output: Image.Image) -> bytes: img_bytes = io.BytesIO() output.save(img_bytes, format=_DEFAULT_IMAGE_FORMAT) return img_bytes.getvalue() def _write_string_output(output: str) -> bytes: return output.encode(_DEFAULT_ENCODING) def _write_bytes_output(output: bytes) -> bytes: return output def _write_pickle_output(output: Any) -> bytes: return bytes(pickle.dumps(output)) def _write_json_output(output: Any) -> bytes: return json.dumps(output).encode(_DEFAULT_ENCODING) serialization_function_mapping: Dict[str, Callable[..., bytes]] = { SerializationType.TABLE: _write_table_output, SerializationType.JSON: _write_json_output, SerializationType.PICKLE: _write_pickle_output, SerializationType.IMAGE: _write_image_output, SerializationType.STRING: _write_string_output, SerializationType.BYTES: _write_bytes_output, } def serialize_val(val: Any, serialization_type: SerializationType) -> str: val_bytes = serialization_function_mapping[serialization_type](val) return _bytes_to_base64_string(val_bytes) def _bytes_to_base64_string(content: bytes) -> str: """Helper to convert any bytes-type to a string, by first encoding it with base64 it. For example, image-serialized bytes are not `utf8` encoded, so if we want to convert such bytes to string, we must use this function. """ return base64.b64encode(content).decode(_DEFAULT_ENCODING) def artifact_type_to_serialization_type( artifact_type: ArtifactType, content: Any ) -> SerializationType: """Copy of the same method on in aqueduct executor.""" if artifact_type == ArtifactType.TABLE: serialization_type = SerializationType.TABLE elif artifact_type == ArtifactType.IMAGE: serialization_type = SerializationType.IMAGE elif artifact_type == ArtifactType.JSON or artifact_type == ArtifactType.STRING: serialization_type = SerializationType.STRING elif artifact_type == ArtifactType.BYTES: serialization_type = SerializationType.BYTES elif artifact_type == ArtifactType.BOOL or artifact_type == ArtifactType.NUMERIC: serialization_type = SerializationType.JSON elif artifact_type == ArtifactType.PICKLABLE: serialization_type = SerializationType.PICKLE elif artifact_type == ArtifactType.DICT or artifact_type == ArtifactType.TUPLE: try: json.dumps(content) serialization_type = SerializationType.JSON except: serialization_type = SerializationType.PICKLE else: raise Exception("Unsupported artifact type %s" % artifact_type) assert serialization_type is not None return serialization_type
3,674
test change name should change perm name
# -*- coding: utf-8 -*- from django.contrib.auth import get_user_model from django.contrib.auth.models import Permission from django.test import RequestFactory from ralph.lib.transitions.decorators import transition_action from ralph.lib.transitions.exceptions import ( TransitionModelNotFoundError, TransitionNotAllowedError ) from ralph.lib.transitions.models import ( _check_and_get_transition, _create_graph_from_actions, run_field_transition, Transition, TransitionModel ) from ralph.lib.transitions.tests import TransitionTestCase from ralph.tests.models import Foo, Order, OrderStatus @transition_action() def mocked_action(*args, **kwargs): """ Mark action as runned. """ mocked_action.runned = True return None class PermissionsTest(TransitionTestCase): def test_create_transition_should_create_perm(self): name = 'Foo' _, transition, _ = self._create_transition(Order, name) perm_exist = Permission.objects.filter( **transition.permission_info ).exists() self.assertTrue(perm_exist) def test_delete_transition_should_delete_perm(self): name = 'Foo' _, transition, _ = self._create_transition(Order, name) transition.delete() perm_exist = Permission.objects.filter( **transition.permission_info ).exists() self.assertFalse(perm_exist) def METHOD_NAME(self): name = 'Foo' _, transition, _ = self._create_transition(Order, name) transition.name = 'Bar' transition.save() perm_exist = Permission.objects.filter( **transition.permission_info ).exists() self.assertTrue(perm_exist) class TransitionsTest(TransitionTestCase): def setUp(self): super().setUp() self.request = RequestFactory() self.request.user = get_user_model().objects.create_user( username='test1', password='password', ) def test_model_should_not_found_in_registry(self): foo = Foo() irrelevant_arg = None with self.assertRaises(TransitionModelNotFoundError): _check_and_get_transition(foo, irrelevant_arg, irrelevant_arg) def test_transition_change_status(self): order = Order.objects.create() _, transition, _ = self._create_transition( model=order, name='prepare', source=[OrderStatus.new.id], target=OrderStatus.to_send.id, actions=['go_to_post_office'] ) self.assertEqual(order.status, OrderStatus.new.id) run_field_transition( [order], transition, requester=self.request.user, field='status' ) self.assertEqual(order.status, OrderStatus.to_send.id) def test_run_action_during_transition(self): order = Order.objects.create(status=OrderStatus.to_send.id) _, transition, actions = self._create_transition( model=order, name='send', source=[OrderStatus.to_send.id], target=OrderStatus.sended.id, actions=['go_to_post_office'] ) order.__class__.go_to_post_office = mocked_action run_field_transition( [order], transition, requester=self.request.user, field='status' ) self.assertTrue(order.go_to_post_office.runned) def test_action_is_added_to_model_when_registered_on_model(self): # action is registered in tests/models.py self.assertTrue(hasattr(Order, 'action_registered_on_model')) def test_transition_runs_action_registered_on_model(self): # action is registered in tests/models.py order = Order.objects.create() _, transition, _ = self._create_transition( model=order, name='action_name', source=[OrderStatus.new.id], target=OrderStatus.to_send.id, actions=['action_registered_on_model'] ) self.assertNotEqual(order.remarks, 'done') run_field_transition( [order], transition, requester=self.request.user, field='status' ) self.assertEqual(order.remarks, 'done') def test_run_transition_from_string(self): transition_name = 'send' order = Order.objects.create(status=OrderStatus.to_send.id) Transition.objects.create( name=transition_name, model=TransitionModel.get_for_field(order, 'status'), source=[OrderStatus.to_send.id], target=OrderStatus.sended.id, ) self.assertTrue( run_field_transition( [order], transition_name, requester=self.request.user, field='status' ) ) def test_run_non_existent_transition(self): transition_name = 'non_existent_transition' order = Order.objects.create() with self.assertRaises(Transition.DoesNotExist): run_field_transition( [order], transition_name, requester=self.request.user, field='status' ) def test_available_transitions(self): order = Order.objects.create() transition = Transition.objects.create( name='send', model=TransitionModel.get_for_field(order, 'status'), source=[OrderStatus.new.id], target=OrderStatus.sended.id, ) self.assertEqual( list(order.get_available_transitions_for_status()), [transition] ) order.status = OrderStatus.sended.id self.assertEqual( list(order.get_available_transitions_for_status()), [] ) def test_transition_exception(self): order = Order.objects.create() _, transition, actions = self._create_transition( model=order, name='generate_exception', source=[OrderStatus.new.id], target=OrderStatus.sended.id, actions=['generate_exception'] ) result, _ = run_field_transition( [order], transition, requester=self.request.user, field='status' ) self.assertFalse(result) def test_forbidden_transition(self): order = Order.objects.create() transition = Transition.objects.create( name='send', model=TransitionModel.get_for_field(order, 'status'), source=[OrderStatus.to_send.id], target=OrderStatus.sended.id, ) self.assertEqual( list(order.get_available_transitions_for_status()), [] ) with self.assertRaises(TransitionNotAllowedError): run_field_transition( [order], transition, requester=self.request.user, field='status' ) def test_create_graph_from_actions(self): order = Order.objects.create() _, transition, _ = self._create_transition( model=order, name='prepare', source=[OrderStatus.new.id], target=OrderStatus.to_send.id, actions=['go_to_post_office', 'pack'] ) graph = _create_graph_from_actions(transition.actions.all(), order) self.assertEqual(graph, { 'pack': ['go_to_post_office'], 'go_to_post_office': [], }) def test_create_graph_from_actions_when_requirement_not_in_transition(self): order = Order.objects.create() _, transition, _ = self._create_transition( model=order, name='prepare', source=[OrderStatus.new.id], target=OrderStatus.to_send.id, actions=['go_to_post_office'] ) graph = _create_graph_from_actions(transition.actions.all(), order) self.assertEqual(graph, { 'go_to_post_office': [], })
3,675
icu object
# -*- encoding: utf-8 -*- """ pdt_locales All of the included locale classes shipped with pdt. """ import datetime try: range = xrange except NameError: pass try: import icu as pyicu except ImportError: try: import PyICU as pyicu except ImportError: pyicu = None def METHOD_NAME(mapping): return type('_icu', (object,), mapping) def merge_weekdays(base_wd, icu_wd): result = [] for left, right in zip(base_wd, icu_wd): if left == right: result.append(left) continue left = set(left.split('|')) right = set(right.split('|')) result.append('|'.join(left | right)) return result def get_icu(locale): def _sanitize_key(k): import re return re.sub("\\.(\\||$)", "\\1", k) from . import base result = dict([(key, getattr(base, key)) for key in dir(base) if not key.startswith('_')]) result['icu'] = None if pyicu is None: return METHOD_NAME(result) if locale is None: locale = 'en_US' result['icu'] = icu = pyicu.Locale(locale) if icu is None: return METHOD_NAME(result) # grab spelled out format of all numbers from 0 to 100 rbnf = pyicu.RuleBasedNumberFormat(pyicu.URBNFRuleSetTag.SPELLOUT, icu) result['numbers'].update([(rbnf.format(i), i) for i in range(0, 100)]) symbols = result['symbols'] = pyicu.DateFormatSymbols(icu) # grab ICU list of weekdays, skipping first entry which # is always blank wd = [_sanitize_key(w.lower()) for w in symbols.getWeekdays()[1:]] swd = [_sanitize_key(sw.lower()) for sw in symbols.getShortWeekdays()[1:]] # store them in our list with Monday first (ICU puts Sunday first) result['Weekdays'] = merge_weekdays(result['Weekdays'], wd[1:] + wd[0:1]) result['shortWeekdays'] = merge_weekdays(result['shortWeekdays'], swd[1:] + swd[0:1]) result['Months'] = [_sanitize_key(m.lower()) for m in symbols.getMonths()] result['shortMonths'] = [_sanitize_key(sm.lower()) for sm in symbols.getShortMonths()] keys = ['full', 'long', 'medium', 'short'] createDateInstance = pyicu.DateFormat.createDateInstance createTimeInstance = pyicu.DateFormat.createTimeInstance icu_df = result['icu_df'] = { 'full': createDateInstance(pyicu.DateFormat.kFull, icu), 'long': createDateInstance(pyicu.DateFormat.kLong, icu), 'medium': createDateInstance(pyicu.DateFormat.kMedium, icu), 'short': createDateInstance(pyicu.DateFormat.kShort, icu), } icu_tf = result['icu_tf'] = { 'full': createTimeInstance(pyicu.DateFormat.kFull, icu), 'long': createTimeInstance(pyicu.DateFormat.kLong, icu), 'medium': createTimeInstance(pyicu.DateFormat.kMedium, icu), 'short': createTimeInstance(pyicu.DateFormat.kShort, icu), } result['dateFormats'] = {} result['timeFormats'] = {} for x in keys: result['dateFormats'][x] = icu_df[x].toPattern() result['timeFormats'][x] = icu_tf[x].toPattern() am = pm = ts = '' # ICU doesn't seem to provide directly the date or time separator # so we have to figure it out o = result['icu_tf']['short'] s = result['timeFormats']['short'] result['usesMeridian'] = 'a' in s result['uses24'] = 'H' in s # '11:45 AM' or '11:45' s = o.format(datetime.datetime(2003, 10, 30, 11, 45)) # ': AM' or ':' s = s.replace('11', '').replace('45', '') if len(s) > 0: ts = s[0] if result['usesMeridian']: # '23:45 AM' or '23:45' am = s[1:].strip() s = o.format(datetime.datetime(2003, 10, 30, 23, 45)) if result['uses24']: s = s.replace('23', '') else: s = s.replace('11', '') # 'PM' or '' pm = s.replace('45', '').replace(ts, '').strip() result['timeSep'] = [ts] result['meridian'] = [am, pm] if am and pm else [] o = result['icu_df']['short'] s = o.format(datetime.datetime(2003, 10, 30, 11, 45)) s = s.replace('10', '').replace('30', '').replace( '03', '').replace('2003', '') if len(s) > 0: ds = s[0] else: ds = '/' result['dateSep'] = [ds] s = result['dateFormats']['short'] ll = s.lower().split(ds) dp_order = [] for s in ll: if len(s) > 0: dp_order.append(s[:1]) result['dp_order'] = dp_order return METHOD_NAME(result)
3,676
test scrape
# Copyright (c) 2017 LINE Corporation # These sources are released under the terms of the MIT license: see LICENSE from unittest import mock import requests from django.test import override_settings from django.urls import reverse from promgen import models, tests, views TEST_SETTINGS = tests.Data("examples", "promgen.yml").yaml() TEST_IMPORT = tests.Data("examples", "import.json").raw() TEST_REPLACE = tests.Data("examples", "replace.json").raw() class RouteTests(tests.PromgenTest): def setUp(self): self.user = self.force_login(username="demo") @override_settings(PROMGEN=TEST_SETTINGS) @override_settings(CELERY_TASK_ALWAYS_EAGER=True) @mock.patch("promgen.signals._trigger_write_config") @mock.patch("promgen.tasks.reload_prometheus") def test_import(self, mock_write, mock_reload): self.add_user_permissions( "promgen.change_rule", "promgen.change_site", "promgen.change_exporter" ) response = self.client.post(reverse("import"), {"config": TEST_IMPORT}) self.assertRoute(response, views.Import, 302, "Redirect to imported object") self.assertCount(models.Service, 3, "Import one service (Fixture has two services)") self.assertCount(models.Project, 4, "Import two projects") self.assertCount(models.Exporter, 2, "Import two exporters") self.assertCount(models.Host, 3, "Import three hosts") @override_settings(PROMGEN=TEST_SETTINGS) @override_settings(CELERY_TASK_ALWAYS_EAGER=True) @mock.patch("promgen.signals._trigger_write_config") @mock.patch("promgen.tasks.reload_prometheus") def test_replace(self, mock_write, mock_reload): self.add_user_permissions( "promgen.change_rule", "promgen.change_site", "promgen.change_exporter" ) response = self.client.post(reverse("import"), {"config": TEST_IMPORT}) self.assertRoute(response, views.Import, 302, "Redirect to imported object") response = self.client.post(reverse("import"), {"config": TEST_REPLACE}) self.assertRoute(response, views.Import, 302, "Redirect to imported object (2)") self.assertCount(models.Service, 3, "Import one service (Fixture has two services)") self.assertCount(models.Project, 4, "Import two projects (Fixture has 2 projectsa)") self.assertCount(models.Exporter, 2, "Import two exporters") self.assertCount( models.Farm, 4, "Original two farms and one new farm (fixture has one farm)" ) self.assertCount(models.Host, 5, "Original 3 hosts and two new ones") @mock.patch("requests.get") def METHOD_NAME(self, mock_get): shard = models.Shard.objects.create(name="test_scrape_shard") service = models.Service.objects.create(name="test_scrape_service") farm = models.Farm.objects.create(name="test_scrape_farm") farm.host_set.create(name="example.com") project = models.Project.objects.create( name="test_scrape_project", service=service, shard=shard, farm=farm ) # Uses the scrape target as the key, and the POST body that should # result in that URL exporters = { "http://example.com:8000/metrics": { "target": "#exporterresult", "job": "foo", "port": 8000, "scheme": "http", }, "https://example.com:8000/foo": { "target": "#exporterresult", "job": "foo", "port": 8000, "path": "/foo", "scheme": "https", }, } for url, body in exporters.items(): response = requests.Response() response.url = url response.status_code = 200 mock_get.return_value = response # For each POST body, check to see that we generate and attempt to # scrape the correct URL response = self.client.post(reverse("exporter-scrape", kwargs={"pk": project.pk}), body) self.assertRoute(response, views.ExporterScrape, 200) self.assertEqual(mock_get.call_args[0][0], url) def test_failed_permission(self): # Test for redirect for request in [{"viewname": "rule-new", "args": ("site", 1)}]: response = self.client.get(reverse(**request)) self.assertRoute(response, views.AlertRuleRegister, 302) self.assertTrue(response.url.startswith("/login")) def test_other_routes(self): self.add_user_permissions("promgen.add_rule", "promgen.change_site") for request in [{"viewname": "rule-new", "args": ("site", 1)}]: response = self.client.get(reverse(**request)) self.assertRoute(response, views.AlertRuleRegister, 200)
3,677
from shareable
# Copyright (c) 2023, NVIDIA CORPORATION. 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. from abc import ABC, abstractmethod from typing import Any, Dict, Optional from nvflare.apis.dxo import DXO, DataKind, METHOD_NAME from nvflare.apis.fl_context import FLContext from nvflare.apis.shareable import Shareable from nvflare.app_common.abstract.fl_model import FLModel, FLModelConst, MetaKey, ParamsType from nvflare.app_common.app_constant import AppConstants from nvflare.fuel.utils.validation_utils import check_object_type MODEL_ATTRS = [ FLModelConst.PARAMS_TYPE, FLModelConst.PARAMS, FLModelConst.METRICS, FLModelConst.OPTIMIZER_PARAMS, FLModelConst.CURRENT_ROUND, FLModelConst.TOTAL_ROUNDS, FLModelConst.META, ] params_type_to_data_kind = { ParamsType.FULL.value: DataKind.WEIGHTS, ParamsType.DIFF.value: DataKind.WEIGHT_DIFF, } data_kind_to_params_type = {v: k for k, v in params_type_to_data_kind.items()} class ParamsConverter(ABC): """This class converts params from one format to the other.""" @abstractmethod def convert(self, params: Dict) -> Dict: pass class FLModelUtils: @staticmethod def to_shareable(fl_model: FLModel, params_converter: Optional[ParamsConverter] = None) -> Shareable: """From FLModel to NVFlare side shareable. This is a temporary solution to converts FLModel to the shareable of existing style, so that we can reuse the existing components we have. In the future, we should be using the to_dxo, from_dxo directly. And all the components should be changed to accept the standard DXO. """ if fl_model.params is None and fl_model.metrics is None: raise ValueError("FLModel without params and metrics is NOT supported.") elif fl_model.params is not None: if fl_model.params_type is None: raise ValueError(f"Invalid ParamsType: ({fl_model.params_type}).") data_kind = params_type_to_data_kind.get(fl_model.params_type) if data_kind is None: raise ValueError(f"Invalid ParamsType: ({fl_model.params_type}).") if params_converter is not None: fl_model.params = params_converter.convert(fl_model.params) if fl_model.metrics is None: dxo = DXO(data_kind, data=fl_model.params, meta={}) else: # if both params and metrics are presented, will be treated as initial evaluation on the global model dxo = DXO(data_kind, data=fl_model.params, meta={MetaKey.INITIAL_METRICS: fl_model.metrics}) else: dxo = DXO(DataKind.METRICS, data=fl_model.metrics, meta={}) meta = fl_model.meta if fl_model.meta is not None else {} dxo.meta.update(meta) shareable = dxo.to_shareable() if fl_model.current_round is not None: shareable.set_header(AppConstants.CURRENT_ROUND, fl_model.current_round) if fl_model.total_rounds is not None: shareable.set_header(AppConstants.NUM_ROUNDS, fl_model.total_rounds) if MetaKey.VALIDATE_TYPE in meta: shareable.set_header(AppConstants.VALIDATE_TYPE, meta[MetaKey.VALIDATE_TYPE]) return shareable @staticmethod def METHOD_NAME( shareable: Shareable, params_converter: Optional[ParamsConverter] = None, fl_ctx: Optional[FLContext] = None ) -> FLModel: """From NVFlare side shareable to FLModel. This is a temporary solution to converts the shareable of existing style to FLModel, so that we can reuse the existing components we have. In the future, we should be using the to_dxo, from_dxo directly. And all the components should be changed to accept the standard DXO. """ dxo = METHOD_NAME(shareable) metrics = None params_type = None params = None if dxo.data_kind == DataKind.METRICS: metrics = dxo.data else: params_type = data_kind_to_params_type.get(dxo.data_kind) if params_type is None: raise ValueError(f"Invalid shareable with dxo that has data kind: {dxo.data_kind}") params_type = ParamsType(params_type) if params_converter: dxo.data = params_converter.convert(dxo.data) params = dxo.data current_round = shareable.get_header(AppConstants.CURRENT_ROUND, None) total_rounds = shareable.get_header(AppConstants.NUM_ROUNDS, None) validate_type = shareable.get_header(AppConstants.VALIDATE_TYPE, None) meta = dict(dxo.meta) if validate_type is not None: meta[MetaKey.VALIDATE_TYPE] = validate_type if fl_ctx is not None: meta[MetaKey.JOB_ID] = fl_ctx.get_job_id() meta[MetaKey.SITE_NAME] = fl_ctx.get_identity_name() result = FLModel( params_type=params_type, params=params, metrics=metrics, current_round=current_round, total_rounds=total_rounds, meta=meta, ) return result @staticmethod def to_dxo(fl_model: FLModel) -> DXO: """Converts FLModel to a DXO.""" attr_dict = {} for attr in MODEL_ATTRS: value = getattr(fl_model, attr, None) if value is not None: attr_dict[attr] = value result = DXO(data_kind=DataKind.FL_MODEL, data=attr_dict) return result @staticmethod def from_dxo(dxo: DXO) -> FLModel: """Converts DXO to FLModel.""" if dxo.data_kind != DataKind.FL_MODEL: raise ValueError(f"Invalid dxo with data_kind: {dxo.data_kind}") if not isinstance(dxo.data, dict): raise ValueError(f"Invalid dxo with data of type: {type(dxo.data)}") params = dxo.data.get(FLModelConst.PARAMS, None) params_type = dxo.data.get(FLModelConst.PARAMS_TYPE, None) metrics = dxo.data.get(FLModelConst.METRICS, None) optimizer_params = dxo.data.get(FLModelConst.OPTIMIZER_PARAMS, None) current_round = dxo.data.get(FLModelConst.CURRENT_ROUND, None) total_rounds = dxo.data.get(FLModelConst.TOTAL_ROUNDS, None) meta = dxo.data.get(FLModelConst.META, None) return FLModel( params=params, params_type=params_type, metrics=metrics, optimizer_params=optimizer_params, current_round=current_round, total_rounds=total_rounds, meta=meta, ) @staticmethod def get_meta_prop(model: FLModel, key: str, default=None): check_object_type("model", model, FLModel) if not model.meta: return default else: return model.meta.get(key, default) @staticmethod def set_meta_prop(model: FLModel, key: str, value: Any): check_object_type("model", model, FLModel) model.meta[key] = value @staticmethod def get_configs(model: FLModel) -> Optional[dict]: return FLModelUtils.get_meta_prop(model, MetaKey.CONFIGS)
3,678
test blank input
from django.core import mail from django.urls import reverse from ...conf.test import override_dynamic_settings from ..test import AuthenticatedUserTestCase class UserChangePasswordTests(AuthenticatedUserTestCase): """tests for user change password RPC (/api/users/1/change-password/)""" def setUp(self): super().setUp() self.link = "/api/users/%s/change-password/" % self.user.pk def test_unsupported_methods(self): """api isn't supporting GET""" response = self.client.get(self.link) self.assertEqual(response.status_code, 405) def test_empty_input(self): """api errors correctly for empty input""" response = self.client.post(self.link, data={}) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "new_password": ["This field is required."], "password": ["This field is required."], }, ) def test_invalid_password(self): """api errors correctly for invalid password""" response = self.client.post( self.link, data={"new_password": "N3wP@55w0rd", "password": "Lor3mIpsum"} ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"password": ["Entered password is invalid."]} ) def METHOD_NAME(self): """api errors correctly for blank input""" response = self.client.post( self.link, data={"new_password": "", "password": self.USER_PASSWORD} ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), {"new_password": ["This field may not be blank."]} ) def test_short_new_pasword(self): """api errors correctly for short new password""" response = self.client.post( self.link, data={"new_password": "n", "password": self.USER_PASSWORD} ) self.assertEqual(response.status_code, 400) self.assertEqual( response.json(), { "new_password": [ "This password is too short. It must contain at least 7 characters." ] }, ) @override_dynamic_settings(forum_address="http://test.com/") def test_change_password(self): """api allows users to change their passwords""" new_password = "N3wP@55w0rd" response = self.client.post( self.link, data={"new_password": new_password, "password": self.USER_PASSWORD}, ) self.assertEqual(response.status_code, 200) self.assertIn("Confirm password change", mail.outbox[0].subject) for line in [l.strip() for l in mail.outbox[0].body.splitlines()]: if line.startswith("http://"): token = line.rstrip("/").split("/")[-1] break else: self.fail("E-mail sent didn't contain confirmation url") response = self.client.get( reverse("misago:options-confirm-password-change", kwargs={"token": token}) ) self.assertEqual(response.status_code, 200) self.reload_user() self.assertTrue(self.user.check_password(new_password)) @override_dynamic_settings(forum_address="http://test.com/") def test_change_password_with_whitespaces(self): """api handles users with whitespaces around their passwords""" old_password = " old password " new_password = " N3wP@55w0rd " self.user.set_password(old_password) self.user.save() self.login_user(self.user) response = self.client.post( self.link, data={"new_password": new_password, "password": old_password} ) self.assertEqual(response.status_code, 200) self.assertIn("Confirm password change", mail.outbox[0].subject) for line in [l.strip() for l in mail.outbox[0].body.splitlines()]: if line.startswith("http://"): token = line.rstrip("/").split("/")[-1] break else: self.fail("E-mail sent didn't contain confirmation url") response = self.client.get( reverse("misago:options-confirm-password-change", kwargs={"token": token}) ) self.assertEqual(response.status_code, 200) self.reload_user() self.assertTrue(self.user.check_password(new_password)) @override_dynamic_settings( enable_oauth2_client=True, oauth2_provider="Lorem", ) def test_change_password_api_returns_403_if_oauth_is_enabled(self): new_password = " N3wP@55w0rd " self.login_user(self.user) response = self.client.post( self.link, data={"new_password": new_password, "password": self.USER_PASSWORD}, ) self.assertEqual(response.status_code, 403) self.assertEqual(len(mail.outbox), 0) @override_dynamic_settings(forum_address="http://test.com/") def test_confirm_change_password_view_returns_403_if_oauth_is_enabled(self): new_password = " N3wP@55w0rd " self.login_user(self.user) response = self.client.post( self.link, data={"new_password": new_password, "password": self.USER_PASSWORD}, ) self.assertEqual(response.status_code, 200) self.assertIn("Confirm password change", mail.outbox[0].subject) for line in [l.strip() for l in mail.outbox[0].body.splitlines()]: if line.startswith("http://"): token = line.rstrip("/").split("/")[-1] break else: self.fail("E-mail sent didn't contain confirmation url") with override_dynamic_settings( enable_oauth2_client=True, oauth2_provider="Lorem" ): response = self.client.get( reverse( "misago:options-confirm-password-change", kwargs={"token": token} ) ) self.assertEqual(response.status_code, 403)
3,679
method from exposed
from pathlib import Path import pytorch_lightning as pl import torch from flash.core.serve import ModelComponent, expose from flash.core.serve.types import Image, Label, Number, Repeated from flash.core.utilities.imports import _TORCHVISION_AVAILABLE from torch import Tensor if _TORCHVISION_AVAILABLE: from torchvision.models import squeezenet1_1 CWD = Path(__file__).parent.joinpath("data").absolute() class LightningSqueezenet(pl.LightningModule): def __init__(self): super().__init__() self.model = squeezenet1_1(pretrained=True).eval() def forward(self, x): return self.model(x) class LightningSqueezenetServable(pl.LightningModule): def __init__(self, model): super().__init__() self.model = model def forward(self, x): return self.model(x) def _func_from_exposed(arg): return ("func", arg) class ClassificationInference(ModelComponent): def __init__(self, model): # skipcq: PYL-W0621 self.model = model @expose( inputs={"img": Image(extension="JPG")}, outputs={"prediction": Label(path=str(CWD / "imagenet_labels.txt"))}, ) def classify(self, img): img = img.float() / 255 mean = torch.tensor([[[0.485, 0.456, 0.406]]]).float() std = torch.tensor([[[0.229, 0.224, 0.225]]]).float() img = (img - mean) / std img = img.permute(0, 3, 2, 1) out = self.model(img) method_res = self.METHOD_NAME(42) assert method_res == ("method", 42) func_res = _func_from_exposed("DouglasAdams") assert func_res == ("func", "DouglasAdams") return out.argmax() @staticmethod def never_should_run(): raise RuntimeError() @staticmethod def METHOD_NAME(arg): return ("method", arg) try: class ClassificationInferenceRepeated(ModelComponent): def __init__(self, model): self.model = model @expose( inputs={"img": Repeated(Image(extension="JPG"))}, outputs={ "prediction": Repeated(Label(path=str(CWD / "imagenet_labels.txt"))), "other": Number(), }, ) def classify(self, img): img = img[0].float() / 255 mean = torch.tensor([[[0.485, 0.456, 0.406]]]).float() std = torch.tensor([[[0.229, 0.224, 0.225]]]).float() img = (img - mean) / std img = img.permute(0, 3, 2, 1) out = self.model(img) return ([out.argmax(), out.argmax()], Tensor([21])) except TypeError: ClassificationInferenceRepeated = None try: class ClassificationInferenceModelSequence(ModelComponent): def __init__(self, model): self.model1 = model[0] self.model2 = model[1] @expose( inputs={"img": Image(extension="JPG")}, outputs={"prediction": Label(path=str(CWD / "imagenet_labels.txt"))}, ) def classify(self, img): img = img.float() / 255 mean = torch.tensor([[[0.485, 0.456, 0.406]]]).float() std = torch.tensor([[[0.229, 0.224, 0.225]]]).float() img = (img - mean) / std img = img.permute(0, 3, 2, 1) out = self.model1(img) out2 = self.model2(img) assert out.argmax() == out2.argmax() return out.argmax() except TypeError: ClassificationInferenceRepeated = None try: class ClassificationInferenceModelMapping(ModelComponent): def __init__(self, model): self.model1 = model["model_one"] self.model2 = model["model_two"] @expose( inputs={"img": Image(extension="JPG")}, outputs={"prediction": Label(path=str(CWD / "imagenet_labels.txt"))}, ) def classify(self, img): img = img.float() / 255 mean = torch.tensor([[[0.485, 0.456, 0.406]]]).float() std = torch.tensor([[[0.229, 0.224, 0.225]]]).float() img = (img - mean) / std img = img.permute(0, 3, 2, 1) out = self.model1(img) out2 = self.model2(img) assert out.argmax() == out2.argmax() return out.argmax() except TypeError: ClassificationInferenceModelMapping = None try: class ClassificationInferenceComposable(ModelComponent): def __init__(self, model): self.model = model @expose( inputs={ "img": Image(extension="JPG"), "tag": Label(path=str(CWD / "imagenet_labels.txt")), }, outputs={ "predicted_tag": Label(path=str(CWD / "imagenet_labels.txt")), "cropped_img": Image(), }, ) def classify(self, img, tag): im_div = img.float() / 255 mean = torch.tensor([[[0.485, 0.456, 0.406]]]).float() std = torch.tensor([[[0.229, 0.224, 0.225]]]).float() img_new = (im_div - torch.mean(mean)) / torch.mean(std) img_new = img_new.permute(0, 3, 2, 1) out = self.model(img_new) return out.argmax(), img except TypeError: ClassificationInferenceComposable = None try: class SeatClassifier(ModelComponent): def __init__(self, model, config): self.sport = config["sport"] @expose( inputs={ "section": Number(), "isle": Number(), "row": Number(), "stadium": Label(path=str(CWD / "imagenet_labels.txt")), }, outputs={ "seat_number": Number(), "team": Label(path=str(CWD / "imagenet_labels.txt")), }, ) def predict(self, section, isle, row, stadium): seat_num = section.item() * isle.item() * row.item() * stadium * len(self.sport) stadium_idx = torch.tensor(1000) return Tensor([seat_num]), stadium_idx except TypeError: SeatClassifier = None
3,680
read string
#!/usr/bin/python3 import argparse import glob import os import time import random COLOURS = (b'\xFF\x00\x00', b'\x00\xFF\x00', b'\x00\x00\xFF', b'\xFF\xFF\x00', b'\xFF\x00\xFF', b'\x00\xFF\xFF') def write_binary(driver_path, device_file, payload): with open(os.path.join(driver_path, device_file), 'wb') as open_file: open_file.write(payload) def METHOD_NAME(driver_path, device_file): with open(os.path.join(driver_path, device_file), 'r') as open_file: return open_file.read().rstrip('\n') def write_string(driver_path, device_file, payload): with open(os.path.join(driver_path, device_file), 'w') as open_file: open_file.write(payload) def find_devices(vid, pid): driver_paths = glob.glob(os.path.join('/sys/bus/hid/drivers/razeraccessory', '*:{0:04X}:{1:04X}.*'.format(vid, pid))) for driver_path in driver_paths: device_type_path = os.path.join(driver_path, 'device_type') if os.path.exists(device_type_path): yield driver_path def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('--skip-standard', action='store_true') parser.add_argument('--skip-custom', action='store_true') parser.add_argument('--skip-game-led', action='store_true') parser.add_argument('--skip-macro-led', action='store_true') return parser.parse_args() if __name__ == '__main__': args = parse_args() found_chroma = False for index, driver_path in enumerate(find_devices(0x1532, 0x0C04), start=1): found_chroma = True print("Razer Firefly_hyperflux {0}\n".format(index)) print("Driver version: {0}".format(METHOD_NAME(driver_path, 'version'))) print("Driver firmware version: {0}".format(METHOD_NAME(driver_path, 'firmware_version'))) print("Device serial: {0}".format(METHOD_NAME(driver_path, 'device_serial'))) print("Device type: {0}".format(METHOD_NAME(driver_path, 'device_type'))) print("Device mode: {0}".format(METHOD_NAME(driver_path, 'device_mode'))) # Set to static red so that we have something standard write_binary(driver_path, 'matrix_effect_static', b'\xFF\x00\x00') if not args.skip_standard: print("Starting brightness test. Press enter to begin.") input() print("Max brightness...", end='') write_string(driver_path, 'matrix_brightness', '255') time.sleep(1) print("brightness ({0})".format(METHOD_NAME(driver_path, 'matrix_brightness'))) time.sleep(1) print("Half brightness...", end='') write_string(driver_path, 'matrix_brightness', '128') time.sleep(1) print("brightness ({0})".format(METHOD_NAME(driver_path, 'matrix_brightness'))) time.sleep(1) print("Zero brightness...", end='') write_string(driver_path, 'matrix_brightness', '0') time.sleep(1) print("brightness ({0})".format(METHOD_NAME(driver_path, 'matrix_brightness'))) time.sleep(1) write_string(driver_path, 'matrix_brightness', '255') print("Starting other colour effect tests. Press enter to begin.") input() print("Green Static") write_binary(driver_path, 'matrix_effect_static', b'\x00\xFF\x00') time.sleep(5) print("Cyan Static") write_binary(driver_path, 'matrix_effect_static', b'\x00\xFF\xFF') time.sleep(5) print("Spectrum") write_binary(driver_path, 'matrix_effect_spectrum', b'\x00') time.sleep(10) print("None") write_binary(driver_path, 'matrix_effect_none', b'\x00') time.sleep(5) print("Wave Left") write_string(driver_path, 'matrix_effect_wave', '1') time.sleep(5) print("Wave Right") write_string(driver_path, 'matrix_effect_wave', '2') time.sleep(5) print("Breathing random") write_binary(driver_path, 'matrix_effect_breath', b'\x00') time.sleep(10) print("Breathing red") write_binary(driver_path, 'matrix_effect_breath', b'\xFF\x00\x00') time.sleep(10) print("Breathing blue-green") write_binary(driver_path, 'matrix_effect_breath', b'\x00\xFF\x00\x00\x00\xFF') time.sleep(10) if not args.skip_custom: # Custom LEDs all rows payload_all = b'\x00\x00\x12' for i in range(0, 19): # 19 colours 0x00-0x12 payload_all += random.choice(COLOURS) payload_m1_5 = b'' for led in (0x00, 0x12): led_byte = led.to_bytes(1, byteorder='big') payload_m1_5 += b'\x00' + led_byte + led_byte + b'\xFF\xFF\xFF' print("Custom LED matrix colours test. Press enter to begin.") input() write_binary(driver_path, 'matrix_custom_frame', payload_all) write_binary(driver_path, 'matrix_effect_custom', b'\x00') print("Custom LED matrix partial colours test. First and last led to white. Press enter to begin.") input() write_binary(driver_path, 'matrix_custom_frame', payload_m1_5) write_binary(driver_path, 'matrix_effect_custom', b'\x00') time.sleep(0.5) print("Finished") if not found_chroma: print("No Fireflies V2 found")
3,681
setup reset nvram
import os import re from avocado.utils import process from virttest import data_dir from virttest import libvirt_version from virttest import virsh from virttest.libvirt_xml import vm_xml from virttest.utils_test import libvirt def get_size_birth_from_nvram(vm_name, test): """ Get the size and birth values from nvram file :param vm_name: vm name :return: (size, birth) """ cmd = 'stat /var/lib/libvirt/qemu/nvram/%s_VARS.fd' % vm_name ret = process.run(cmd, ignore_status=False, shell=True) size = re.search(r"Size:\s*(\d*)", ret.stdout_text).group(1) birth = re.search(r"Birth:\s*(.*)", ret.stdout_text).group(1) test.log.debug("Return current nvram file with " "size({}) and birth({})".format(size, birth)) return size, birth def METHOD_NAME(guest_xml, params, virsh_func, test, *args): """ Setup for the tests, including 1. Configure os firmware attribute 2. Create nvram file and make its size invalid :param guest_xml: the guest xml :param params: dict for parameters of the tests :param virsh_func: virsh function will be invoked :param args: tuple, virsh function uses """ test.log.info("Config guest xml with firmware efi") vm_name = params.get("main_vm", "avocado-vt-vm1") os_attrs = eval(params.get('os_attrs')) if os_attrs: osxml = vm_xml.VMOSXML() osxml.setup_attrs(**os_attrs) guest_xml.os = osxml guest_xml.sync() test.log.debug("After configuration, vm xml:\n%s", vm_xml.VMXML.new_from_inactive_dumpxml(vm_name)) test.log.info("Start vm to create %s_VARS.fd file" % vm_name) virsh.start(vm_name) test.log.info("Modify the nvram file to make it invalid") cmd = 'echo > /var/lib/libvirt/qemu/nvram/%s_VARS.fd' % vm_name process.run(cmd, ignore_status=False, shell=True) test.log.debug("Prepare the required vm state") if len(args) > 1: virsh_func(args[0], args[1], ignore_status=False) else: virsh_func(args[0], ignore_status=False) def common_test_steps(virsh_func, func_args, params, test): """ The common test steps shared by test cases :param virsh_func: virsh function to be invoked :param func_args: str, parameter value for virsh function :param params: dict, test parameters :param test: test object :raises: test.fail if size or birth was not changed """ vm_name = params.get("main_vm", "avocado-vt-vm1") test.log.debug("Step 1: Get the invalid nvram file size and birth ") old_size, old_birth = get_size_birth_from_nvram(vm_name, test) test.log.debug("Step 2: Operate on the vm and check expected result") ret = virsh_func(func_args) err_msg = params.get('err_msg') libvirt.check_result(ret, expected_fails=err_msg) test.log.debug("Step 3: Operate on the vm again but with --reset-nvram option") ret = virsh_func(func_args, options=params.get('option')) libvirt.check_exit_status(ret) test.log.debug("Step 4: Verify the valid nvram file was recreated") new_size, new_birth = get_size_birth_from_nvram(vm_name, test) if (new_size == old_size or new_birth == old_birth): test.fail("New nvram file with size '{}' birth '{}' " "should not be equal to old ones".format(new_size, new_birth)) def test_start_destroyed_vm(guest_xml, params, test): """ Test scenario: - Destroyed the vm - Start the vm and failure is expected with invalid nvram file size - Start the vm successfully with --reset-nvram - Check the nvram file is recreated as expected :param guest_xml: guest xml :param params: dict, test parameters :param test: test object """ vm_name = params.get("main_vm", "avocado-vt-vm1") METHOD_NAME(guest_xml, params, virsh.destroy, test, vm_name) common_test_steps(virsh.start, vm_name, params, test) def test_start_managedsaved_vm(guest_xml, params, test): """ Test scenario: - Managedsave the vm - Start the vm and failure is expected with invalid nvram file size - Start the vm successfully with --reset-nvram - Check the nvram file is recreated as expected :param guest_xml: guest xml :param params: dict, test parameters :param test: test object """ vm_name = params.get("main_vm", "avocado-vt-vm1") METHOD_NAME(guest_xml, params, virsh.managedsave, test, vm_name) common_test_steps(virsh.start, vm_name, params, test) def test_restore_saved_vm(guest_xml, params, test): """ Test scenario: - Save the vm - Restore the vm and failure is expected with invalid nvram file size - Restore the vm successfully with --reset-nvram - Check the nvram file is recreated as expected :param guest_xml: guest xml :param params: dict, test parameters :param test: test object """ vm_name = params.get("main_vm", "avocado-vt-vm1") save_file = os.path.join(data_dir.get_data_dir(), params.get('output_file')) METHOD_NAME(guest_xml, params, virsh.save, test, vm_name, save_file) common_test_steps(virsh.restore, save_file, params, test) def test_create_destroyed_vm(guest_xml, params, test): """ Test scenario: - Destroyed the vm - Create the vm and failure is expected with invalid nvram file size - Create the vm successfully with --reset-nvram - Check the nvram file is recreated as expected :param guest_xml: guest xml :param params: dict, test parameters :param test: test object """ vm_name = params.get("main_vm", "avocado-vt-vm1") METHOD_NAME(guest_xml, params, virsh.destroy, test, vm_name) vm_file = os.path.join(data_dir.get_data_dir(), params.get('output_file')) virsh.dumpxml(vm_name, to_file=vm_file) common_test_steps(virsh.create, vm_file, params, test) def teardown_reset_nvram(params): """ Clean up test environment :param params: dict, test parameters """ output_file = params.get('output_file') if output_file: output_file = os.path.join(data_dir.get_data_dir(), output_file) if os.path.exists(output_file): os.remove(output_file) def run(test, params, env): """ Test cases for --reset-nvram option """ libvirt_version.is_libvirt_feature_supported(params) case = params.get('test_case', '') vm_name = params.get('main_vm', '') guest_xml = vm_xml.VMXML.new_from_inactive_dumpxml(vm_name) bk_guest_xml = guest_xml.copy() run_test = eval('test_%s' % case) try: run_test(guest_xml, params, test) finally: bk_guest_xml.sync(options='--nvram') teardown_reset_nvram(params)
3,682
project
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import copy import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities from . import outputs __all__ = [ 'GetEnvironmentResult', 'AwaitableGetEnvironmentResult', 'get_environment', 'get_environment_output', ] @pulumi.output_type class GetEnvironmentResult: """ A collection of values returned by getEnvironment. """ def __init__(__self__, configs=None, id=None, labels=None, name=None, METHOD_NAME=None, region=None): if configs and not isinstance(configs, list): raise TypeError("Expected argument 'configs' to be a list") pulumi.set(__self__, "configs", configs) if id and not isinstance(id, str): raise TypeError("Expected argument 'id' to be a str") pulumi.set(__self__, "id", id) if labels and not isinstance(labels, dict): raise TypeError("Expected argument 'labels' to be a dict") pulumi.set(__self__, "labels", labels) if name and not isinstance(name, str): raise TypeError("Expected argument 'name' to be a str") pulumi.set(__self__, "name", name) if METHOD_NAME and not isinstance(METHOD_NAME, str): raise TypeError("Expected argument 'project' to be a str") pulumi.set(__self__, "project", METHOD_NAME) if region and not isinstance(region, str): raise TypeError("Expected argument 'region' to be a str") pulumi.set(__self__, "region", region) @property @pulumi.getter def configs(self) -> Sequence['outputs.GetEnvironmentConfigResult']: """ Configuration parameters for the environment. """ return pulumi.get(self, "configs") @property @pulumi.getter def id(self) -> str: """ The provider-assigned unique ID for this managed resource. """ return pulumi.get(self, "id") @property @pulumi.getter def labels(self) -> Mapping[str, str]: return pulumi.get(self, "labels") @property @pulumi.getter def name(self) -> str: return pulumi.get(self, "name") @property @pulumi.getter def METHOD_NAME(self) -> Optional[str]: return pulumi.get(self, "project") @property @pulumi.getter def region(self) -> Optional[str]: return pulumi.get(self, "region") class AwaitableGetEnvironmentResult(GetEnvironmentResult): # pylint: disable=using-constant-test def __await__(self): if False: yield self return GetEnvironmentResult( configs=self.configs, id=self.id, labels=self.labels, name=self.name, METHOD_NAME=self.METHOD_NAME, region=self.region) def get_environment(name: Optional[str] = None, METHOD_NAME: Optional[str] = None, region: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetEnvironmentResult: """ Provides access to Cloud Composer environment configuration in a region for a given project. :param str name: Name of the environment. :param str project: The ID of the project in which the resource belongs. If it is not provided, the provider project is used. :param str region: The location or Compute Engine region of the environment. """ __args__ = dict() __args__['name'] = name __args__['project'] = METHOD_NAME __args__['region'] = region opts = pulumi.InvokeOptions.merge(_utilities.get_invoke_opts_defaults(), opts) __ret__ = pulumi.runtime.invoke('gcp:composer/getEnvironment:getEnvironment', __args__, opts=opts, typ=GetEnvironmentResult).value return AwaitableGetEnvironmentResult( configs=pulumi.get(__ret__, 'configs'), id=pulumi.get(__ret__, 'id'), labels=pulumi.get(__ret__, 'labels'), name=pulumi.get(__ret__, 'name'), METHOD_NAME=pulumi.get(__ret__, 'project'), region=pulumi.get(__ret__, 'region')) @_utilities.lift_output_func(get_environment) def get_environment_output(name: Optional[pulumi.Input[str]] = None, METHOD_NAME: Optional[pulumi.Input[Optional[str]]] = None, region: Optional[pulumi.Input[Optional[str]]] = None, opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetEnvironmentResult]: """ Provides access to Cloud Composer environment configuration in a region for a given project. :param str name: Name of the environment. :param str project: The ID of the project in which the resource belongs. If it is not provided, the provider project is used. :param str region: The location or Compute Engine region of the environment. """ ...
3,683
set inventory
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type from collections.abc import Mapping from ansible.template import Templar, AnsibleUndefined STATIC_VARS = [ 'ansible_version', 'ansible_play_hosts', 'ansible_dependent_role_names', 'ansible_play_role_names', 'ansible_role_names', 'inventory_hostname', 'inventory_hostname_short', 'inventory_file', 'inventory_dir', 'groups', 'group_names', 'omit', 'playbook_dir', 'play_hosts', 'role_names', 'ungrouped', ] __all__ = ['HostVars', 'HostVarsVars'] # Note -- this is a Mapping, not a MutableMapping class HostVars(Mapping): ''' A special view of vars_cache that adds values from the inventory when needed. ''' def __init__(self, inventory, variable_manager, loader): self._inventory = inventory self._loader = loader self._variable_manager = variable_manager variable_manager._hostvars = self def set_variable_manager(self, variable_manager): self._variable_manager = variable_manager variable_manager._hostvars = self def METHOD_NAME(self, inventory): self._inventory = inventory def _find_host(self, host_name): # does not use inventory.hosts so it can create localhost on demand return self._inventory.get_host(host_name) def raw_get(self, host_name): ''' Similar to __getitem__, however the returned data is not run through the templating engine to expand variables in the hostvars. ''' host = self._find_host(host_name) if host is None: return AnsibleUndefined(name="hostvars['%s']" % host_name) return self._variable_manager.get_vars(host=host, include_hostvars=False) def __setstate__(self, state): self.__dict__.update(state) # Methods __getstate__ and __setstate__ of VariableManager do not # preserve _loader and _hostvars attributes to improve pickle # performance and memory utilization. Since HostVars holds values # of those attributes already, assign them if needed. if self._variable_manager._loader is None: self._variable_manager._loader = self._loader if self._variable_manager._hostvars is None: self._variable_manager._hostvars = self def __getitem__(self, host_name): data = self.raw_get(host_name) if isinstance(data, AnsibleUndefined): return data return HostVarsVars(data, loader=self._loader) def set_host_variable(self, host, varname, value): self._variable_manager.set_host_variable(host, varname, value) def set_nonpersistent_facts(self, host, facts): self._variable_manager.set_nonpersistent_facts(host, facts) def set_host_facts(self, host, facts): self._variable_manager.set_host_facts(host, facts) def __contains__(self, host_name): # does not use inventory.hosts so it can create localhost on demand return self._find_host(host_name) is not None def __iter__(self): for host in self._inventory.hosts: yield host def __len__(self): return len(self._inventory.hosts) def __repr__(self): out = {} for host in self._inventory.hosts: out[host] = self.get(host) return repr(out) def __deepcopy__(self, memo): # We do not need to deepcopy because HostVars is immutable, # however we have to implement the method so we can deepcopy # variables' dicts that contain HostVars. return self class HostVarsVars(Mapping): def __init__(self, variables, loader): self._vars = variables self._loader = loader def __getitem__(self, var): templar = Templar(variables=self._vars, loader=self._loader) return templar.template(self._vars[var], fail_on_undefined=False, static_vars=STATIC_VARS) def __contains__(self, var): return (var in self._vars) def __iter__(self): for var in self._vars.keys(): yield var def __len__(self): return len(self._vars.keys()) def __repr__(self): templar = Templar(variables=self._vars, loader=self._loader) return repr(templar.template(self._vars, fail_on_undefined=False, static_vars=STATIC_VARS))
3,684
topojson convert
import contextlib import os import os.path import subprocess from datetime import datetime import geojson from django.conf import settings from django.core.management.base import BaseCommand from elections.models import Election TOPOJSON_BIN = os.path.join( settings.BASE_DIR, "..", "node_modules", "topojson", "node_modules", ".bin" ) def set_precision(coords, precision): result = [] try: return round(coords, int(precision)) except TypeError: for coord in coords: result.append(set_precision(coord, precision)) return result def parse_date(date_string): return datetime.strptime(date_string, "%Y-%m-%d").date() class Command(BaseCommand): help = "Export static boundary GeoJSON files for each group of elections." def add_arguments(self, parser): output_dir = os.path.join(settings.BASE_DIR, "static", "exports") parser.add_argument( "--from", dest="from", help="Export elections from this date", type=parse_date, ) parser.add_argument( "--to", dest="to", help="Export elections until this date", type=parse_date, ) parser.add_argument( "--output", dest="output", help="Output directory (default every_election/static/exports)", default=output_dir, ) def handle(self, *args, **options): with contextlib.suppress(FileExistsError): os.mkdir(options["output"]) if not (options["from"] or options["to"]): elections = Election.public_objects.future().filter( group_type="election" ) else: elections = Election.public_objects.all().filter( group_type="election" ) if options["from"]: elections = elections.filter( poll_open_date__gte=options["from"] ) if options["to"]: elections = elections.filter(poll_open_date__lte=options["to"]) for election in elections: self.stdout.write("Exporting elections for group %s" % election) data = self.export_election(election) gj_path = os.path.join( options["output"], "%s.json" % election.election_id ) with open(gj_path, "w") as output_file: geojson.dump(data, output_file) tj_path = os.path.join( options["output"], "%s-topo.json" % election.election_id ) self.METHOD_NAME(gj_path, tj_path) tj_simple_path = os.path.join( options["output"], "%s-topo-simplified.json" % election.election_id, ) self.topojson_simplify(tj_path, tj_simple_path) def METHOD_NAME(self, source, dest): "Convert GeoJSON to TopoJSON by calling out to the topojson package" subprocess.check_call( [os.path.join(TOPOJSON_BIN, "geo2topo"), "-o", dest, source] ) def topojson_simplify(self, source, dest): "Simplify a TopoJSON file" # The toposimplify settings here were arrived at by trial and error to keep the # simplified 2018-05-03 local elections topojson below 2.5MB. subprocess.check_call( [ os.path.join(TOPOJSON_BIN, "toposimplify"), "-S", "0.2", "-F", "-o", dest, source, ] ) def export_election(self, parent): "Return GeoJSON containing all leaf elections below this parent" features = [] elections = self.get_ballots(parent) for election in elections: if election.geography: gj = geojson.loads(election.geography.geography.json) # Round coordinates to 6 decimal places (~10cm) precision to reduce # output size. This is probably as good as the source data accuracy. gj["coordinates"] = set_precision(gj["coordinates"], 6) else: self.stderr.write("Election %s has no geography" % election) gj = None feat = geojson.Feature( geometry=gj, id=election.election_id, properties={ "name": election.election_title, "division": election.division.name if election.division else None, "organisation": election.organisation.official_name, }, ) features.append(feat) return geojson.FeatureCollection( features, election_group=parent.election_id ) def get_ballots(self, group): "Return the ballots for a group of elections." to_visit = [group] leaf_nodes = [] while len(to_visit) > 0: e = to_visit.pop() children = e.get_children("public_objects").all() if e.identifier_type == "ballot": leaf_nodes.append(e) else: to_visit += children return leaf_nodes
3,685
root
########################################################################## # # Copyright (c) 2011-2012, John Haddon. All rights reserved. # Copyright (c) 2012-2013, Image Engine Design Inc. 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 John Haddon nor the names of # any other contributors to this software may be used to endorse or # promote products derived from this software without specific prior # written permission. # # 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. # ########################################################################## import os import sys import inspect import cProfile import IECore import Gaffer class Application( IECore.Parameterised ) : def __init__( self, description="" ) : IECore.Parameterised.__init__( self, inspect.cleandoc( description ) ) self.parameters().addParameters( [ IECore.BoolParameter( name = "help", description = "Prints names and descriptions of each parameter " "rather than running the application.", defaultValue = False, ), IECore.IntParameter( name = "threads", description = "The maximum number of threads used for computation. " "The default value of zero matches the number of threads to " "the available hardware cores. Negative values specify a thread count " "relative to the available cores, leaving some in reserve for other " "applications. Positive values specify the thread count explicitly, " "but are clamped so it does not exceed the available cores.", defaultValue = 0, ), IECore.FileNameParameter( name = "profileFileName", description = "If this is specified, then the application " "is run using the cProfile profiling module, and the " "results saved to the file for later examination.", defaultValue = "", allowEmptyString = True ), ] ) self.__root = _NonSlicingApplicationRoot( self.__class__.__name__ ) ## All Applications have an ApplicationRoot which forms the root of the # hierarchy for all scripts, preferences, nodes etc. def METHOD_NAME( self ) : return self.__root ## Called to run the application and return a status value. def run( self ) : if self.parameters()["help"].getTypedValue() : self.__formatHelp() return 0 profileFileName = self.parameters()["profileFileName"].getTypedValue() if profileFileName : contextDict = { "self" : self, } cProfile.runctx( "result = self._Application__run()", contextDict, contextDict, profileFileName ) return contextDict["result"] else : return self.__run() ## Must be implemented by subclasses to do the actual work of # running the application and returning a status value. The args # argument contains the already validated parameter values. def _run( self, args ) : raise NotImplementedError ## Executes the startup files for the specified application. This # is called automatically for this application before _run is called, # but applications may call it in order to "borrow" the startup files # for other applications. See the screengrab app for a good use case. def _executeStartupFiles( self, applicationName ) : if "GAFFER_STARTUP_PATHS" not in os.environ : IECore.msg( IECore.Msg.Level.Warning, "Gaffer.Application._executeStartupFiles", "GAFFER_STARTUP_PATHS environment variable not set" ) return contextDict = { "application" : self } IECore.loadConfig( "GAFFER_STARTUP_PATHS", contextDict, subdirectory = applicationName ) def __run( self ) : maxThreads = IECore.hardwareConcurrency() threads = self.parameters()["threads"].getTypedValue() if threads <= 0 : threads = max( maxThreads + threads, 1 ) elif threads > maxThreads : IECore.msg( IECore.Msg.Level.Warning, "Application", f"Clamping to `-threads {maxThreads}` to avoid oversubscription" ) threads = maxThreads with IECore.tbb_global_control( IECore.tbb_global_control.parameter.max_allowed_parallelism, threads ) : self._executeStartupFiles( self.METHOD_NAME().getName() ) # Append DEBUG message with process information to all messages defaultMessageHandler = IECore.MessageHandler.getDefaultHandler() if not isinstance( defaultMessageHandler, Gaffer.ProcessMessageHandler ) : IECore.MessageHandler.setDefaultHandler( Gaffer.ProcessMessageHandler( defaultMessageHandler ) ) return self._run( self.parameters().getValidatedValue() ) def __formatHelp( self ) : formatter = IECore.WrappedTextFormatter( sys.stdout ) formatter.paragraph( "Name : " + self.typeName() ) if self.description : formatter.paragraph( self.description + "\n" ) if len( self.parameters().values() ): formatter.heading( "Parameters" ) formatter.indent() for p in self.parameters().values() : IECore.formatParameterHelp( p, formatter ) formatter.unindent() IECore.registerRunTimeTyped( Application, typeName = "Gaffer::Application" ) # Various parts of the UI try to store their state as attributes on # the root object, and therefore require it's identity in python to # be stable, even when acquiring it from separate calls to C++ methods # like `ancestor( ApplicationRoot )`. The IECorePython::RunTimeTypedWrapper # only guarantees this stability if we've derived from it in Python, # which is what we do here. ## \todo Either : # # - Fix the object identity problem in Cortex # - Or at least add a way of requesting that identity be # preserved without needing to derive. # - Or stop the UI relying on storing it's own members on # the root. class _NonSlicingApplicationRoot( Gaffer.ApplicationRoot ) : def __init__( self, name ) : Gaffer.ApplicationRoot.__init__( self, name )
3,686
get flag new locals value
# Copyright 2023, Kay Hayen, mailto:kay.hayen@gmail.com # # Part of "Nuitka", an optimizing Python compiler that is compatible and # integrates with CPython, but also works on its own. # # 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. # """ Code object specifications. For code objects that will be attached to module, function, and generator objects, as well as tracebacks. They might be shared. """ from nuitka.utils.InstanceCounters import ( counted_del, counted_init, isCountingInstances, ) class CodeObjectSpec(object): # One attribute for each code object aspect, and even flags, # pylint: disable=too-many-arguments,too-many-instance-attributes __slots__ = ( "co_name", "co_qualname", "co_kind", "co_varnames", "co_argcount", "co_freevars", "co_posonlyargcount", "co_kwonlyargcount", "co_has_starlist", "co_has_stardict", "filename", "line_number", "future_spec", "new_locals", "is_optimized", ) @counted_init def __init__( self, co_name, co_qualname, co_kind, co_varnames, co_freevars, co_argcount, co_posonlyargcount, co_kwonlyargcount, co_has_starlist, co_has_stardict, co_filename, co_lineno, future_spec, co_new_locals=None, co_is_optimized=None, ): # pylint: disable=I0021,too-many-locals self.co_name = co_name self.co_qualname = co_qualname self.co_kind = co_kind self.future_spec = future_spec assert future_spec # Strings happens from XML parsing, make sure to convert them. if type(co_varnames) is str: if co_varnames == "": co_varnames = () else: co_varnames = co_varnames.split(",") if type(co_freevars) is str: if co_freevars == "": co_freevars = () else: co_freevars = co_freevars.split(",") if type(co_has_starlist) is not bool: co_has_starlist = co_has_starlist != "False" if type(co_has_stardict) is not bool: co_has_stardict = co_has_stardict != "False" self.co_varnames = tuple(co_varnames) self.co_freevars = tuple(co_freevars) self.co_argcount = int(co_argcount) self.co_posonlyargcount = int(co_posonlyargcount) self.co_kwonlyargcount = int(co_kwonlyargcount) self.co_has_starlist = co_has_starlist self.co_has_stardict = co_has_stardict self.filename = co_filename self.line_number = int(co_lineno) if type(co_has_starlist) is not bool: co_new_locals = co_new_locals != "False" if type(co_has_starlist) is not bool: co_is_optimized = co_is_optimized != "False" self.new_locals = co_new_locals self.is_optimized = co_is_optimized if isCountingInstances(): __del__ = counted_del() def __repr__(self): return ( """\ <CodeObjectSpec %(co_kind)s '%(co_name)s' with %(co_varnames)r>""" % self.getDetails() ) def getDetails(self): return { "co_name": self.co_name, "co_kind": self.co_kind, "co_varnames": ",".join(self.co_varnames), "co_freevars": ",".join(self.co_freevars), "co_argcount": self.co_argcount, "co_posonlyargcount": self.co_posonlyargcount, "co_kwonlyargcount": self.co_kwonlyargcount, "co_has_starlist": self.co_has_starlist, "co_has_stardict": self.co_has_stardict, "co_filename": self.filename, "co_lineno": self.line_number, "co_new_locals": self.new_locals, "co_is_optimized": self.is_optimized, "code_flags": ",".join(self.future_spec.asFlags()), } def getCodeObjectKind(self): return self.co_kind def updateLocalNames(self, local_names, freevar_names): """Move detected local variables after closure has been decided.""" self.co_varnames += tuple( local_name for local_name in local_names if local_name not in self.co_varnames # TODO: This is actually a bug, but we have a hard time without it to know # frame locals easily. We use this in compiled function run time, that all # variables, including closure variables are found there. This would have to # be cleaned up, for potentially little gain. # if local_name not in freevar_names ) self.co_freevars = tuple(freevar_names) def removeFreeVarname(self, freevar_name): self.co_freevars = tuple( var_name for var_name in self.co_freevars if var_name != freevar_name ) def setFlagIsOptimizedValue(self, value): self.is_optimized = value def getFlagIsOptimizedValue(self): return self.is_optimized def setFlagNewLocalsValue(self, value): self.new_locals = value def METHOD_NAME(self): return self.new_locals def getFutureSpec(self): return self.future_spec def getVarNames(self): return self.co_varnames def getFreeVarNames(self): return self.co_freevars def getArgumentCount(self): return self.co_argcount def getPosOnlyParameterCount(self): return self.co_posonlyargcount def getKwOnlyParameterCount(self): return self.co_kwonlyargcount def getCodeObjectName(self): return self.co_name def getCodeObjectQualname(self): return self.co_name def hasStarListArg(self): return self.co_has_starlist def hasStarDictArg(self): return self.co_has_stardict def getFilename(self): return self.filename def getLineNumber(self): return self.line_number
3,687
get categories
from enum import Enum from typing import List, Union import logging import math try: from flask_babel import _ except ModuleNotFoundError: def _(str): return str class VehicleType(Enum): CAR = 1 TRUCK_UPTO_4 = 2 PICKUP_UPTO_4 = 3 TRUCK_4_TO_10 = 4 TRUCK_12_TO_16 = 5 TRUCK_16_TO_34 = 6 TRUCK_ABOVE_34 = 7 MOTORCYCLE_UPTO_50 = 8 MOTORCYCLE_50_TO_250 = 9 MOTORCYCLE_250_TO_500 = 10 BUS = 11 TAXI = 12 WORK = 13 TRACTOR = 14 BIKE = 15 TRAIN = 16 OTHER_AND_UNKNOWN = 17 MINIBUS = 18 MOTORCYCLE_ABOVE_500 = 19 ELECTRIC_SCOOTER = 21 MOBILITY_SCOOTER = 22 ELECTRIC_BIKE = 23 TRUCK_3_5_TO_10 = 24 TRUCK_10_TO_12 = 25 def METHOD_NAME(self) -> List[int]: res = [] for t in list(VehicleCategory): if self in t.value: res.append(t) return res def get_english_display_name(self): english_vehicle_type_display_names = { VehicleType.CAR: "private car", VehicleType.TRUCK_UPTO_4: "truck upto 4 tons", VehicleType.PICKUP_UPTO_4: "pickup upto 4 tons", VehicleType.TRUCK_4_TO_10: "truck 4 to 10 tons", VehicleType.TRUCK_12_TO_16: "truck 12 to 16 tons", VehicleType.TRUCK_16_TO_34: "truck 16 to 34 tons", VehicleType.TRUCK_ABOVE_34: "truck above 34 tons", VehicleType.MOTORCYCLE_UPTO_50: "motorcycle upto 50 cc", VehicleType.MOTORCYCLE_50_TO_250: "motorcycle 50 to 250 cc", VehicleType.MOTORCYCLE_250_TO_500: "motorcycle 250 to 500 cc", VehicleType.BUS: "bus", VehicleType.TAXI: "taxi", VehicleType.WORK: "work vehicle", VehicleType.TRACTOR: "tractor", VehicleType.BIKE: "bike", VehicleType.TRAIN: "train", VehicleType.OTHER_AND_UNKNOWN: "other and unknown", VehicleType.MINIBUS: "minibus", VehicleType.MOTORCYCLE_ABOVE_500: "motorcycle above 500 cc", VehicleType.ELECTRIC_SCOOTER: "electric scooter", VehicleType.MOBILITY_SCOOTER: "mobility scooter", VehicleType.ELECTRIC_BIKE: "electric bike", VehicleType.TRUCK_3_5_TO_10: "truck 3.5 to 10 tons", VehicleType.TRUCK_10_TO_12: "truck 10 to 12 tons", } try: return english_vehicle_type_display_names[self] except (KeyError, TypeError): logging.exception(f"VehicleType.get_display_name: {self}: no display string defined") return "no display name defined" @staticmethod def to_type_code(db_val: Union[float, int]) -> int: """Values read from DB may arrive as float, and empty values come as nan""" if isinstance(db_val, float): if math.isnan(db_val): return VehicleType.OTHER_AND_UNKNOWN.value else: return int(db_val) elif isinstance(db_val, int): return db_val else: logging.error( f"VehicleType.fo_type_code: unknown value: {db_val}({type(db_val)})" ". returning OTHER_AND_UNKNOWN" ) return VehicleType.OTHER_AND_UNKNOWN.value VT = VehicleType class VehicleCategory(Enum): PROFESSIONAL_DRIVER = 1 PRIVATE_DRIVER = 2 LIGHT_ELECTRIC = 3 CAR = 4 LARGE = 5 MOTORCYCLE = 6 BICYCLE_AND_SMALL_MOTOR = 7 OTHER = 8 def get_codes(self) -> List[int]: """returns VehicleType codes of category""" category_vehicle_types = { VehicleCategory.PROFESSIONAL_DRIVER: [ VehicleType.TRUCK_UPTO_4, VehicleType.PICKUP_UPTO_4, VehicleType.TRUCK_4_TO_10, VehicleType.TRUCK_12_TO_16, VehicleType.TRUCK_16_TO_34, VehicleType.TRUCK_ABOVE_34, VehicleType.BUS, VehicleType.TAXI, VehicleType.WORK, VehicleType.TRACTOR, VehicleType.MINIBUS, VehicleType.TRUCK_3_5_TO_10, VehicleType.TRUCK_10_TO_12, ], VehicleCategory.PRIVATE_DRIVER: [ VehicleType.CAR, VehicleType.MOTORCYCLE_UPTO_50, VehicleType.MOTORCYCLE_50_TO_250, VehicleType.MOTORCYCLE_250_TO_500, VehicleType.MOTORCYCLE_ABOVE_500, ], VehicleCategory.LIGHT_ELECTRIC: [ VehicleType.ELECTRIC_SCOOTER, VehicleType.MOBILITY_SCOOTER, VehicleType.ELECTRIC_BIKE, ], VehicleCategory.CAR: [VehicleType.CAR, VehicleType.TAXI], VehicleCategory.LARGE: [ VehicleType.TRUCK_UPTO_4, VehicleType.PICKUP_UPTO_4, VehicleType.TRUCK_4_TO_10, VehicleType.TRUCK_12_TO_16, VehicleType.TRUCK_16_TO_34, VehicleType.TRUCK_ABOVE_34, VehicleType.BUS, VehicleType.WORK, VehicleType.TRACTOR, VehicleType.MINIBUS, VehicleType.TRUCK_3_5_TO_10, VehicleType.TRUCK_10_TO_12, ], VehicleCategory.MOTORCYCLE: [ VehicleType.MOTORCYCLE_UPTO_50, VehicleType.MOTORCYCLE_50_TO_250, VehicleType.MOTORCYCLE_250_TO_500, VehicleType.MOTORCYCLE_ABOVE_500, ], VehicleCategory.BICYCLE_AND_SMALL_MOTOR: [ VehicleType.BIKE, VehicleType.ELECTRIC_SCOOTER, VehicleType.ELECTRIC_BIKE, ], VehicleCategory.OTHER: [ VehicleType.BIKE, VehicleType.TRAIN, VehicleType.OTHER_AND_UNKNOWN, ], } return list(map(lambda x: x.value, category_vehicle_types[self])) def contains(self, vt_code: int) -> bool: # noinspection PyTypeChecker if not isinstance(int, vt_code): logging.warning(f"VehicleCategory.contains: {vt_code}:{type(vt_code)}: not int") return False return vt_code in self.get_codes() def get_english_display_name(self): english_vehicle_type_display_names = { VehicleCategory.PROFESSIONAL_DRIVER: "professional driver", VehicleCategory.PRIVATE_DRIVER: "private driver", VehicleCategory.LIGHT_ELECTRIC: "light electric vehicles", VehicleCategory.CAR: "private car", VehicleCategory.LARGE: "large vehicle", VehicleCategory.MOTORCYCLE: "motorcycle", VehicleCategory.BICYCLE_AND_SMALL_MOTOR: "bicycle and small motor vehicles", VehicleCategory.OTHER: "other vehicle", } try: return english_vehicle_type_display_names[self] except (KeyError, TypeError): logging.exception(f"VehicleType.get_display_name: {self}: no display string defined") return "no display name defined" _("professional driver") _("private driver") _("light electric vehicles") _("private car") _("large vehicle") _("motorcycle") _("bicycle and small motor vehicles") _("other vehicle")
3,688
create
# Copyright 2015 The Emscripten Authors. All rights reserved. # Emscripten is available under two separate licenses, the MIT license and the # University of Illinois/NCSA Open Source License. Both these licenses can be # found in the LICENSE file. import os TAG = 'version_7' HASH = 'a921dab254f21cf5d397581c5efe58faf147c31527228b4fb34aed75164c736af4b3347092a8d9ec1249160230fa163309a87a20c2b9ceef8554566cc215de9d' variants = {'regal-mt': {'PTHREADS': 1}} def needed(settings): return settings.USE_REGAL def get_lib_name(settings): return 'libregal' + ('-mt' if settings.PTHREADS else '') + '.a' def get(ports, settings, shared): ports.fetch_project('regal', f'https://github.com/emscripten-ports/regal/archive/{TAG}.zip', sha512hash=HASH) def METHOD_NAME(final): source_path = os.path.join(ports.get_dir(), 'regal', 'regal-' + TAG) # copy sources # only what is needed is copied: regal, boost, lookup3 source_path_src = os.path.join(source_path, 'src') source_path_regal = os.path.join(source_path_src, 'regal') source_path_boost = os.path.join(source_path_src, 'boost') source_path_lookup3 = os.path.join(source_path_src, 'lookup3') # includes source_path_include = os.path.join(source_path, 'include', 'GL') ports.install_headers(source_path_include, target='GL') # build srcs_regal = ['regal/RegalShaderInstance.cpp', 'regal/RegalIff.cpp', 'regal/RegalQuads.cpp', 'regal/Regal.cpp', 'regal/RegalLog.cpp', 'regal/RegalInit.cpp', 'regal/RegalBreak.cpp', 'regal/RegalUtil.cpp', 'regal/RegalEmu.cpp', 'regal/RegalEmuInfo.cpp', 'regal/RegalFrame.cpp', 'regal/RegalHelper.cpp', 'regal/RegalMarker.cpp', 'regal/RegalTexC.cpp', 'regal/RegalCacheShader.cpp', 'regal/RegalCacheTexture.cpp', 'regal/RegalConfig.cpp', 'regal/RegalContext.cpp', 'regal/RegalContextInfo.cpp', 'regal/RegalDispatch.cpp', 'regal/RegalStatistics.cpp', 'regal/RegalLookup.cpp', 'regal/RegalPlugin.cpp', 'regal/RegalShader.cpp', 'regal/RegalToken.cpp', 'regal/RegalDispatchGlobal.cpp', 'regal/RegalDispatcher.cpp', 'regal/RegalDispatcherGL.cpp', 'regal/RegalDispatcherGlobal.cpp', 'regal/RegalDispatchEmu.cpp', 'regal/RegalDispatchGLX.cpp', 'regal/RegalDispatchLog.cpp', 'regal/RegalDispatchCode.cpp', 'regal/RegalDispatchCache.cpp', 'regal/RegalDispatchError.cpp', 'regal/RegalDispatchLoader.cpp', 'regal/RegalDispatchDebug.cpp', 'regal/RegalDispatchPpapi.cpp', 'regal/RegalDispatchStatistics.cpp', 'regal/RegalDispatchStaticES2.cpp', 'regal/RegalDispatchStaticEGL.cpp', 'regal/RegalDispatchTrace.cpp', 'regal/RegalDispatchMissing.cpp', 'regal/RegalPixelConversions.cpp', 'regal/RegalHttp.cpp', 'regal/RegalDispatchHttp.cpp', 'regal/RegalJson.cpp', 'regal/RegalFavicon.cpp', 'regal/RegalMac.cpp', 'regal/RegalSo.cpp', 'regal/RegalFilt.cpp', 'regal/RegalXfer.cpp', 'regal/RegalX11.cpp', 'regal/RegalDllMain.cpp'] srcs_regal = [os.path.join(source_path_src, s) for s in srcs_regal] flags = [ '-DNDEBUG', '-DREGAL_LOG=0', # Set to 1 if you need to have some logging info '-DREGAL_MISSING=0', # Set to 1 if you don't want to crash in case of missing GL implementation '-std=gnu++14', '-fno-rtti', '-fno-exceptions', # Disable exceptions (in STL containers mostly), as they are not used at all '-O3', '-I' + source_path_regal, '-I' + source_path_lookup3, '-I' + source_path_boost, '-Wall', '-Werror', '-Wno-deprecated-register', '-Wno-unused-parameter' ] if settings.PTHREADS: flags += ['-pthread'] ports.build_port(source_path_src, final, 'regal', srcs=srcs_regal, flags=flags) return [shared.cache.get_lib(get_lib_name(settings), METHOD_NAME, what='port')] def clear(ports, settings, shared): shared.cache.erase_lib(get_lib_name(settings)) def linker_setup(ports, settings): settings.FULL_ES2 = 1 def process_args(ports): return [] def show(): return 'regal (USE_REGAL=1; Regal license)'
3,689
tear down
""" Test CRUD for authorization. """ import copy from cms.djangoapps.contentstore.tests.utils import AjaxEnabledTestClient from cms.djangoapps.contentstore.utils import reverse_course_url, reverse_url from common.djangoapps.student import auth from common.djangoapps.student.roles import CourseInstructorRole, CourseStaffRole, OrgInstructorRole, OrgStaffRole from common.djangoapps.student.tests.factories import UserFactory from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase # lint-amnesty, pylint: disable=wrong-import-order class TestCourseAccess(ModuleStoreTestCase): """ Course-based access (as opposed to access of a non-course xblock) """ def setUp(self): """ Create a staff user and log them in (creating the client). Create a pool of users w/o granting them any permissions """ super().setUp() self.client = AjaxEnabledTestClient() self.client.login(username=self.user.username, password=self.user_password) # create a course via the view handler which has a different strategy for permissions than the factory self.course_key = self.store.make_course_key('myu', 'mydept.mycourse', 'myrun') course_url = reverse_url('course_handler') self.client.ajax_post( course_url, { 'org': self.course_key.org, 'number': self.course_key.course, 'display_name': 'My favorite course', 'run': self.course_key.run, }, ) self.users = self._create_users() def _create_users(self): """ Create 8 users and return them """ users = [] for i in range(8): username = f"user{i}" email = f"test+user{i}@edx.org" user = UserFactory.create(username=username, email=email, password='foo') user.is_active = True user.save() users.append(user) return users def METHOD_NAME(self): """ Reverse the setup """ self.client.logout() ModuleStoreTestCase.METHOD_NAME(self) # pylint: disable=non-parent-method-called def test_get_all_users(self): """ Test getting all authors for a course where their permissions run the gamut of allowed group types. """ # first check the course creator.has explicit access (don't use has_access as is_staff # will trump the actual test) self.assertTrue( CourseInstructorRole(self.course_key).has_user(self.user), "Didn't add creator as instructor." ) users = copy.copy(self.users) # doesn't use role.users_with_role b/c it's verifying the roles.py behavior user_by_role = {} # add the misc users to the course in different groups for role in [CourseInstructorRole, CourseStaffRole, OrgStaffRole, OrgInstructorRole]: user_by_role[role] = [] # Org-based roles are created via org name, rather than course_key if (role is OrgStaffRole) or (role is OrgInstructorRole): group = role(self.course_key.org) else: group = role(self.course_key) # NOTE: this loop breaks the roles.py abstraction by purposely assigning # users to one of each possible groupname in order to test that has_course_author_access # and remove_user work user = users.pop() group.add_users(user) user_by_role[role].append(user) self.assertTrue(auth.has_course_author_access(user, self.course_key), f"{user} does not have access") # lint-amnesty, pylint: disable=line-too-long course_team_url = reverse_course_url('course_team_handler', self.course_key) response = self.client.get_html(course_team_url) for role in [CourseInstructorRole, CourseStaffRole]: # Global and org-based roles don't appear on this page for user in user_by_role[role]: self.assertContains(response, user.email) # test copying course permissions copy_course_key = self.store.make_course_key('copyu', 'copydept.mycourse', 'myrun') for role in [CourseInstructorRole, CourseStaffRole, OrgStaffRole, OrgInstructorRole]: if (role is OrgStaffRole) or (role is OrgInstructorRole): auth.add_users( self.user, role(copy_course_key.org), *role(self.course_key.org).users_with_role() ) else: auth.add_users( self.user, role(copy_course_key), *role(self.course_key).users_with_role() ) # verify access in copy course and verify that removal from source course w/ the various # groupnames works for role in [CourseInstructorRole, CourseStaffRole, OrgStaffRole, OrgInstructorRole]: for user in user_by_role[role]: # forcefully decache the groups: premise is that any real request will not have # multiple objects repr the same user but this test somehow uses different instance # in above add_users call if hasattr(user, '_roles'): del user._roles self.assertTrue(auth.has_course_author_access(user, copy_course_key), f"{user} no copy access") if (role is OrgStaffRole) or (role is OrgInstructorRole): auth.remove_users(self.user, role(self.course_key.org), user) else: auth.remove_users(self.user, role(self.course_key), user) self.assertFalse(auth.has_course_author_access(user, self.course_key), f"{user} remove didn't work") # lint-amnesty, pylint: disable=line-too-long
3,690
rewrite alias
import contextlib from pathlib import Path from uuid import UUID from pydantic import UUID4 from mealie.core import root_logger from mealie.core.exceptions import UnexpectedNone from mealie.repos.all_repositories import AllRepositories from mealie.schema.recipe import Recipe from mealie.schema.recipe.recipe_settings import RecipeSettings from mealie.schema.reports.reports import ( ReportCategory, ReportCreate, ReportEntryCreate, ReportOut, ReportSummary, ReportSummaryStatus, ) from mealie.services.recipe.recipe_service import RecipeService from mealie.services.scraper import cleaner from .._base_service import BaseService from .utils.database_helpers import DatabaseMigrationHelpers from .utils.migration_alias import MigrationAlias class BaseMigrator(BaseService): key_aliases: list[MigrationAlias] report_entries: list[ReportEntryCreate] report_id: UUID4 report: ReportOut helpers: DatabaseMigrationHelpers def __init__( self, archive: Path, db: AllRepositories, session, user_id: UUID4, group_id: UUID, add_migration_tag: bool ): self.archive = archive self.db = db self.session = session self.add_migration_tag = add_migration_tag user = db.users.get_one(user_id) if not user: raise UnexpectedNone(f"Cannot find user {user_id}") group = db.groups.get_one(group_id) if not group: raise UnexpectedNone(f"Cannot find group {group_id}") self.user = user self.group = group self.name = "migration" self.report_entries = [] self.logger = root_logger.get_logger() self.helpers = DatabaseMigrationHelpers(self.db, self.session, self.group.id, self.user.id) self.recipe_service = RecipeService(db, user, group) super().__init__() def _migrate(self) -> None: raise NotImplementedError def _create_report(self, report_name: str) -> None: report_to_save = ReportCreate( name=report_name, category=ReportCategory.migration, status=ReportSummaryStatus.in_progress, group_id=self.group.id, ) self.report = self.db.group_reports.create(report_to_save) self.report_id = self.report.id def _save_all_entries(self) -> None: is_success = True is_failure = True for entry in self.report_entries: if is_failure and entry.success: is_failure = False if is_success and not entry.success: is_success = False self.db.group_report_entries.create(entry) if is_success: self.report.status = ReportSummaryStatus.success if is_failure: self.report.status = ReportSummaryStatus.failure if not is_success and not is_failure: self.report.status = ReportSummaryStatus.partial self.db.group_reports.update(self.report.id, self.report) def migrate(self, report_name: str) -> ReportSummary: self._create_report(report_name) self._migrate() self._save_all_entries() result = self.db.group_reports.get_one(self.report_id) if not result: raise ValueError("Report not found") return result def import_recipes_to_database(self, validated_recipes: list[Recipe]) -> list[tuple[str, UUID4, bool]]: """ Used as a single access point to process a list of Recipe objects into the database in a predictable way. If an error occurs the session is rolled back and the process will continue. All import information is appended to the 'migration_report' attribute to be returned to the frontend for display. Args: validated_recipes (list[Recipe]): """ if self.add_migration_tag: migration_tag = self.helpers.get_or_set_tags([self.name])[0] return_vars: list[tuple[str, UUID4, bool]] = [] if not self.group.preferences: raise ValueError("Group preferences not found") default_settings = RecipeSettings( public=self.group.preferences.recipe_public, show_nutrition=self.group.preferences.recipe_show_nutrition, show_assets=self.group.preferences.recipe_show_assets, landscape_view=self.group.preferences.recipe_landscape_view, disable_comments=self.group.preferences.recipe_disable_comments, disable_amount=self.group.preferences.recipe_disable_amount, ) for recipe in validated_recipes: recipe.settings = default_settings recipe.user_id = self.user.id recipe.group_id = self.group.id if recipe.tags: recipe.tags = self.helpers.get_or_set_tags(x.name for x in recipe.tags) else: recipe.tags = [] if recipe.recipe_category: recipe.recipe_category = self.helpers.get_or_set_category(x.name for x in recipe.recipe_category) if self.add_migration_tag: recipe.tags.append(migration_tag) exception: str | Exception = "" status = False try: recipe = self.recipe_service.create_one(recipe) status = True except Exception as inst: exception = str(inst) self.logger.exception(inst) self.session.rollback() if status: message = f"Imported {recipe.name} successfully" else: message = f"Failed to import {recipe.name}" return_vars.append((recipe.slug, recipe.id, status)) # type: ignore self.report_entries.append( ReportEntryCreate( report_id=self.report_id, success=status, message=message, exception=str(exception), ) ) return return_vars def METHOD_NAME(self, recipe_dict: dict) -> dict: """A helper function to reassign attributes by an alias using a list of MigrationAlias objects to rewrite the alias attribute found in the recipe_dict to a Args: recipe_dict (dict): [description] key_aliases (list[MigrationAlias]): [description] Returns: dict: [description] """ if not self.key_aliases: return recipe_dict for alias in self.key_aliases: try: prop_value = recipe_dict.pop(alias.alias) except KeyError: continue if alias.func: prop_value = alias.func(prop_value) recipe_dict[alias.key] = prop_value return recipe_dict def clean_recipe_dictionary(self, recipe_dict: dict) -> Recipe: """ Calls the rewrite_alias function and the Cleaner.clean function on a dictionary and returns the result unpacked into a Recipe object """ recipe_dict = self.METHOD_NAME(recipe_dict) with contextlib.suppress(KeyError): del recipe_dict["id"] recipe_dict = cleaner.clean(recipe_dict, url=recipe_dict.get("org_url", None)) return Recipe(**recipe_dict)
3,691
get defaults
# -*- coding: utf-8 -*- """ Created on Sat May 1 13:50:36 2021 @author: erwan """ import numpy as np import radis KNOWN_CONTEXT = ["paper", "notebook", "talk", "poster"] def METHOD_NAME(plotlib, context, style): expected_format = { "plot": { "plotlib": "ANY OF " + "/".join(['"publib"', '"seaborn"', '"matplotlib"', '"none"']), "context": "ANY OF " + "/".join(f'"{c}"' for c in KNOWN_CONTEXT), "style": "ANY OF the publib / seaborn / matplotlib themes", } } # Get defaults if plotlib == "config-default": try: plotlib = radis.config["plot"]["plotlib"] except KeyError: raise ValueError( "Missing key in your ~/radis.json user config file. Expected format :\n\n {0}".format( expected_format ) ) if context == "config-default": try: context = radis.config["plot"]["context"] except KeyError: raise ValueError( "Missing key `context` in your ~/radis.json user config file. Expected format :\n\n {0}".format( expected_format ) ) if style == "config-default": try: style = radis.config["plot"]["style"] except KeyError: raise ValueError( "Missing key `style` in your ~/radis.json user config file. Expected format :\n\n {0}".format( expected_format ) ) if context and context not in KNOWN_CONTEXT: raise ValueError(f"context must be in {KNOWN_CONTEXT}. Got {context}") if plotlib == "publib": if not isinstance(style, list): style = [style] if context == "paper": style = style + ["article"] elif context in ["poster", "notebook", "talk"]: style = style + [context] return plotlib, context, style def set_style( plotlib="config-default", context="config-default", style="config-default" ): """Set styles used by Radis plot functions (:py:func:`~radis.spectrum.spectrum.Spectrum.plot`, :py:func:`~radis.spectrum.compare.plot_diff`, :py:func:`~radis.tools.slit.plot_slit`, etc.) Parameters ---------- plotlib: ``"publib"``, ``"seaborn"``, ``"matplotlib"`` `publib <https://github.com/erwanp/publib>`__ , :py:mod:`seaborn`, :py:mod:`matplotlib` context: ``"poster"``, ``"talk"``, ``"paper"``, ``"notebook"`` See :py:func:`seaborn.set_theme` style: a ``publib`` or ``matplotlib`` style, or a ``seaborn`` theme if ``"oring"``, use your current defaults. if ``"none"``, use your current defaults. Examples -------- .. minigallery:: radis.misc.plot.set_style See also -------- :py:func:`seaborn.set_theme`, :py:func:`publib.main.set_style` """ plotlib, context, style = METHOD_NAME(plotlib, context, style) if plotlib != "none": import matplotlib matplotlib.rc_file_defaults() # Apply style if plotlib == "publib": import publib publib.set_style(style) elif plotlib == "seaborn": import seaborn as sns sns.set_theme(context=context, style=style) elif plotlib == "matplotlib": import matplotlib.pyplot as plt plt.style.use(style) elif plotlib == "none": pass else: raise ValueError(f"plot library: {plotlib}") def fix_style( plotlib="config-default", context="config-default", style="config-default", *args, **kwargs, ): """A posteriori improvement of the last figure generated Effective when ``plotlib`` is `publib <https://github.com/erwanp/publib>`__ Parameters ---------- plotlib: ``"publib"``, ``"seaborn"``, ``"matplotlib"`` `publib <https://github.com/erwanp/publib>`__ , :py:mod:`seaborn`, :py:mod:`matplotlib` context: ``"poster"``, ``"talk"``, ``"paper"``, ``"notebook"`` See :py:func:`seaborn.set_theme` style: a ``publib`` or ``matplotlib`` style, or a ``seaborn`` theme if ``"oring"``, use your current defaults. if ``"none"``, use your current defaults. Examples -------- .. minigallery:: radis.misc.plot.fix_style See also -------- :py:func:`publib.main.fix_style` """ plotlib, context, style = METHOD_NAME(plotlib, context, style) # Apply style if plotlib == "publib": import publib publib.fix_style(style, *args, **kwargs) elif plotlib == "seaborn": pass elif plotlib == "matplotlib": pass elif plotlib == "none": pass else: raise ValueError(f"plot library: {plotlib}") def split_and_plot_by_parts(w, I, *args, **kwargs): """Plot two discontinued arrays (typically a spectrum) without showing junctions: first identify junctions then split and plot separately. Useful for plotting an experimental spectrum defined on different, non overlapping ranges without showing connecting lines between the ranges, or to plot an experimental spectrum defined on overlapping ranges, without showing connecting lines neither. Parameters ---------- w, I: arrays typically output of :py:func:`~numpy.hstack`. Other Parameters ---------------- split_threshold: int number of standard deviation for threshold. Default 10 ax: matplotlib axe plot on a particular axe kwargs: dict forwarded to :func:`~matplotlib.pyplot.plot` cutwings: int discard elements on the side. Default 0 Returns ------- ax.plot """ import matplotlib.pyplot as plt from publib.tools import keep_color # Get defaults ax = kwargs.pop("ax", None) if ax is None: ax = plt.gca() split_threshold = kwargs.pop("split_threshold", 10) # type: int cutwings = kwargs.pop("cutwings", 0) # type: int label = kwargs.pop("label", None) # type: str # identify joints dw = np.diff(w) dwmean = dw.mean() joints = np.argwhere((abs(dw - dwmean) > split_threshold * dw.std())) + 1 # Split if len(joints) > 0: ws = np.split(w, joints.flatten()) Is = np.split(I, joints.flatten()) # Plot separately out = [] for i, (wi, Ii) in enumerate(zip(ws, Is)): if cutwings: wi = wi[cutwings:-cutwings] Ii = Ii[cutwings:-cutwings] if i == 0: # label once only out.append( ax.plot( wi, Ii, *args, **dict(list(kwargs.items()) + [("label", label)]) ) ) else: keep_color() out.append(ax.plot(wi, Ii, *args, **kwargs)) return list(zip(*out)) else: if cutwings: w = w[cutwings:-cutwings] I = I[cutwings:-cutwings] return ax.plot(w, I, *args, **dict(list(kwargs.items()) + [("label", label)]))
3,692
forward train
# Copyright (c) OpenMMLab. All rights reserved. import warnings from typing import Dict, List, Optional, Sequence, Union import torch import torch.nn as nn from mmocr.models.common.dictionary import Dictionary from mmocr.registry import MODELS from mmocr.structures import TextRecogDataSample from .base import BaseDecoder @MODELS.register_module() class ABIFuser(BaseDecoder): r"""A special decoder responsible for mixing and aligning visual feature and linguistic feature. `ABINet <https://arxiv.org/abs/2103.06495>`_ Args: dictionary (dict or :obj:`Dictionary`): The config for `Dictionary` or the instance of `Dictionary`. The dictionary must have an end token. vision_decoder (dict): The config for vision decoder. language_decoder (dict, optional): The config for language decoder. num_iters (int): Rounds of iterative correction. Defaults to 1. d_model (int): Hidden size :math:`E` of model. Defaults to 512. max_seq_len (int): Maximum sequence length :math:`T`. The sequence is usually generated from decoder. Defaults to 40. module_loss (dict, optional): Config to build loss. Defaults to None. postprocessor (dict, optional): Config to build postprocessor. Defaults to None. init_cfg (dict or list[dict], optional): Initialization configs. Defaults to None. """ def __init__(self, dictionary: Union[Dict, Dictionary], vision_decoder: Dict, language_decoder: Optional[Dict] = None, d_model: int = 512, num_iters: int = 1, max_seq_len: int = 40, module_loss: Optional[Dict] = None, postprocessor: Optional[Dict] = None, init_cfg: Optional[Union[Dict, List[Dict]]] = None, **kwargs) -> None: super().__init__( dictionary=dictionary, module_loss=module_loss, postprocessor=postprocessor, max_seq_len=max_seq_len, init_cfg=init_cfg) assert self.dictionary.end_idx is not None,\ 'Dictionary must contain an end token! (with_end=True)' self.d_model = d_model self.num_iters = num_iters if language_decoder is not None: self.w_att = nn.Linear(2 * d_model, d_model) self.cls = nn.Linear(d_model, self.dictionary.num_classes) self.vision_decoder = vision_decoder self.language_decoder = language_decoder for cfg_name in ['vision_decoder', 'language_decoder']: if getattr(self, cfg_name, None) is not None: cfg = getattr(self, cfg_name) if cfg.get('dictionary', None) is None: cfg.update(dictionary=self.dictionary) else: warnings.warn(f"Using dictionary {cfg['dictionary']} " "in decoder's config.") if cfg.get('max_seq_len', None) is None: cfg.update(max_seq_len=max_seq_len) else: warnings.warn(f"Using max_seq_len {cfg['max_seq_len']} " "in decoder's config.") setattr(self, cfg_name, MODELS.build(cfg)) self.softmax = nn.Softmax(dim=-1) def METHOD_NAME( self, feat: Optional[torch.Tensor] = None, out_enc: torch.Tensor = None, data_samples: Optional[Sequence[TextRecogDataSample]] = None ) -> Dict: """ Args: feat (torch.Tensor, optional): Not required. Feature map placeholder. Defaults to None. out_enc (Tensor): Raw language logitis. Shape :math:`(N, T, C)`. Defaults to None. data_samples (list[TextRecogDataSample], optional): Not required. DataSample placeholder. Defaults to None. Returns: A dict with keys ``out_enc``, ``out_decs`` and ``out_fusers``. - out_vis (dict): Dict from ``self.vision_decoder`` with keys ``feature``, ``logits`` and ``attn_scores``. - out_langs (dict or list): Dict from ``self.vision_decoder`` with keys ``feature``, ``logits`` if applicable, or an empty list otherwise. - out_fusers (dict or list): Dict of fused visual and language features with keys ``feature``, ``logits`` if applicable, or an empty list otherwise. """ out_vis = self.vision_decoder(feat, out_enc, data_samples) out_langs = [] out_fusers = [] if self.language_decoder is not None: text_logits = out_vis['logits'] for _ in range(self.num_iters): out_dec = self.language_decoder(feat, text_logits, data_samples) out_langs.append(out_dec) out_fuser = self.fuse(out_vis['feature'], out_dec['feature']) text_logits = out_fuser['logits'] out_fusers.append(out_fuser) outputs = dict( out_vis=out_vis, out_langs=out_langs, out_fusers=out_fusers) return outputs def forward_test( self, feat: Optional[torch.Tensor], logits: torch.Tensor, data_samples: Optional[Sequence[TextRecogDataSample]] = None ) -> torch.Tensor: """ Args: feat (torch.Tensor, optional): Not required. Feature map placeholder. Defaults to None. logits (Tensor): Raw language logitis. Shape :math:`(N, T, C)`. data_samples (list[TextRecogDataSample], optional): Not required. DataSample placeholder. Defaults to None. Returns: Tensor: Character probabilities. of shape :math:`(N, self.max_seq_len, C)` where :math:`C` is ``num_classes``. """ raw_result = self.METHOD_NAME(feat, logits, data_samples) if 'out_fusers' in raw_result and len(raw_result['out_fusers']) > 0: ret = raw_result['out_fusers'][-1]['logits'] elif 'out_langs' in raw_result and len(raw_result['out_langs']) > 0: ret = raw_result['out_langs'][-1]['logits'] else: ret = raw_result['out_vis']['logits'] return self.softmax(ret) def fuse(self, l_feature: torch.Tensor, v_feature: torch.Tensor) -> Dict: """Mix and align visual feature and linguistic feature. Args: l_feature (torch.Tensor): (N, T, E) where T is length, N is batch size and E is dim of model. v_feature (torch.Tensor): (N, T, E) shape the same as l_feature. Returns: dict: A dict with key ``logits``. of shape :math:`(N, T, C)` where N is batch size, T is length and C is the number of characters. """ f = torch.cat((l_feature, v_feature), dim=2) f_att = torch.sigmoid(self.w_att(f)) output = f_att * v_feature + (1 - f_att) * l_feature logits = self.cls(output) # (N, T, C) return {'logits': logits}
3,693
table configs
from typing import Optional from uuid import uuid4 from citrine.exceptions import NotFound from citrine.resources.project import Project, ProjectCollection from tests.utils.fakes import FakeDatasetCollection from tests.utils.fakes import FakeDesignSpaceCollection, FakeDesignWorkflowCollection from tests.utils.fakes import FakeGemTableCollection, FakeTableConfigCollection from tests.utils.fakes import FakePredictorCollection, FakePredictorEvaluationWorkflowCollection from tests.utils.fakes import FakePredictorEvaluationExecutionCollection from tests.utils.fakes import FakeDescriptorMethods from tests.utils.session import FakeSession class FakeProjectCollection(ProjectCollection): def __init__(self, search_implemented: bool = True): ProjectCollection.__init__(self, session=FakeSession) self.projects = [] self.search_implemented = search_implemented def register(self, name: str, description: Optional[str] = None) -> Project: project = FakeProject(name=name) self.projects.append(project) return project def list(self, page: Optional[int] = None, per_page: int = 100): if page is None: return self.projects else: return self.projects[(page - 1)*per_page:page*per_page] def search(self, search_params: Optional[dict] = None, per_page: int = 100): if not self.search_implemented: raise NotFound("search") ans = self.projects if search_params.get("name"): method = search_params["name"]["search_method"] value = search_params["name"]["value"] if method == "EXACT": ans = [x for x in ans if x.name == value] elif method == "SUBSTRING": ans = [x for x in ans if value in x.name] if search_params.get("description"): method = search_params["description"]["search_method"] value = search_params["description"]["value"] if method == "EXACT": ans = [x for x in ans if x.description == value] elif method == "SUBSTRING": ans = [x for x in ans if value in x.description] return ans def delete(self, uuid): raise NotImplementedError class FakeProject(Project): def __init__(self, name="foo", description="bar", num_properties=3, session=FakeSession()): Project.__init__(self, name=name, description=description, session=session) self.uid = uuid4() self._design_spaces = FakeDesignSpaceCollection(self.uid, self.session) self._design_workflows = FakeDesignWorkflowCollection(self.uid, self.session) self._descriptor_methods = FakeDescriptorMethods(num_properties) self._datasets = FakeDatasetCollection(self.uid, self.session) self._predictors = FakePredictorCollection(self.uid, self.session) self._pees = FakePredictorEvaluationExecutionCollection(self.uid, self.session) self._pews = FakePredictorEvaluationWorkflowCollection(self.uid, self.session) self._tables = FakeGemTableCollection(self.uid, self.session) self._table_configs = FakeTableConfigCollection(self.uid, self.session) @property def datasets(self) -> FakeDatasetCollection: return self._datasets @property def design_spaces(self) -> FakeDesignSpaceCollection: return self._design_spaces @property def design_workflows(self) -> FakeDesignWorkflowCollection: return self._design_workflows @property def descriptors(self) -> FakeDescriptorMethods: return self._descriptor_methods @property def predictors(self) -> FakePredictorCollection: return self._predictors @property def predictor_evaluation_executions(self) -> FakePredictorEvaluationExecutionCollection: return self._pees @property def predictor_evaluation_workflows(self) -> FakePredictorEvaluationWorkflowCollection: return self._pews @property def tables(self) -> FakeGemTableCollection: return self._tables @property def METHOD_NAME(self) -> FakeTableConfigCollection: return self._table_configs
3,694
execute
# Copyright 2019 Google LLC # # 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 changed code in current branch.""" import os import sys import yaml from local.butler import common from local.butler import format as formatter _GOLINT_EXCEPTIONS = [ 'types.go' # Not all model names conform to Go naming conventions. ] _LICENSE_CHECK_FILENAMES = ['Dockerfile'] _LICENSE_CHECK_EXTENSIONS = [ '.bash', '.c', '.cc', '.cpp', '.css', '.h', '.htm', '.html', '.js', '.go', '.proto', '.ps1', '.py', '.sh', '.yaml', ] _LICENSE_CHECK_IGNORE_FILENAMES = ['technology.css'] _LICENSE_CHECK_IGNORE_DIRECTORIES = [ 'third_party', 'templates', # Generated code. ] _LICENSE_CHECK_STRING = 'http://www.apache.org/licenses/LICENSE-2.0' _LICENSE_CHECK_IGNORE = 'LICENSE_CHECK_IGNORE' _PY_TEST_SUFFIX = '_test.py' _PY_INIT_FILENAME = '__init__.py' _YAML_EXCEPTIONS = ['bad.yaml'] _error_occurred = False def _error(message=None): """Print error and track state via a global.""" if message: print(message) global _error_occurred _error_occurred = True def _execute_command_and_track_error(command): """Executes command, tracks error state.""" returncode, output = common.METHOD_NAME(command, exit_on_error=False) if returncode != 0: _error() return output.decode('utf-8') def license_validate(file_path): """Run license header validation.""" filename = os.path.basename(file_path) extension = os.path.splitext(file_path)[1] if (filename not in _LICENSE_CHECK_FILENAMES and extension not in _LICENSE_CHECK_EXTENSIONS): return path_directories = file_path.split(os.sep) if any(d in _LICENSE_CHECK_IGNORE_DIRECTORIES for d in path_directories): return source_filename = os.path.basename(file_path) if source_filename in _LICENSE_CHECK_IGNORE_FILENAMES: return with open(file_path) as f: data = f.read() if _LICENSE_CHECK_STRING in data or _LICENSE_CHECK_IGNORE in data: return _error('Failed: Missing license header for %s.' % file_path) def py_import_order(file_path): """Validate that python imports are alphabetized.""" def _validate_block(import_block): """Ensure that a single block is ordered properly.""" if not import_block: return [] sorted_import_block = sorted(import_block, key=lambda i: i.lower()) if sorted_import_block == import_block: return [] return ['\n'.join(sorted_import_block)] with open(file_path) as f: file_content = f.read() imports = [] corrected_import_blocks = [] for line in file_content.splitlines(): if line.startswith('import ') or line.startswith('from '): imports.append(line) else: corrected_import_blocks += _validate_block(imports) imports = [] # Though rare, if a file ends with an import we must still validate them. corrected_import_blocks += _validate_block(imports) if not corrected_import_blocks: return suggestions = '\n\n--------\n\n'.join(corrected_import_blocks) _error(('Failed: File {filename} has non-alphabetized import blocks. ' 'Suggested order:\n\n{suggestions}').format( filename=file_path, suggestions=suggestions)) def py_test_init_check(file_path): """Check test directory has a __init__.py file. Otherwise, the test does not execute at all.""" if not file_path.endswith(_PY_TEST_SUFFIX): return test_directory = os.path.dirname(file_path) if _PY_INIT_FILENAME not in os.listdir(test_directory): _error(f'Failed: Missing {_PY_INIT_FILENAME} file in test ' f'directory {test_directory}.') def yaml_validate(file_path): """Run yaml validation.""" if os.path.basename(file_path) in _YAML_EXCEPTIONS: return try: with open(file_path) as f: yaml.safe_load(f.read()) except Exception as e: _error('Failed: Invalid yaml file %s.\n\n%s' % (file_path, e)) def is_auto_generated_file(filepath): """Check if file is auto-generated so we dont lint it""" return (filepath.endswith('_pb2.py') or filepath.endswith('pb2_grpc.py') or os.path.dirname(filepath) == os.path.join( 'src', 'clusterfuzz', '_internal', 'bot', 'tokenizer', 'grammars')) def METHOD_NAME(_): """Lint changed code.""" pythonpath = os.getenv('PYTHONPATH', '') module_parent_path = os.path.abspath(os.path.join(__file__, '..', '..', '..')) third_party_path = os.path.join(module_parent_path, 'third_party') os.environ['PYTHONPATH'] = ':'.join( [third_party_path, module_parent_path, pythonpath]) if 'GOOGLE_CLOUDBUILD' in os.environ: # Explicitly compare against master if we're running on the CI _, output = common.METHOD_NAME('git diff --name-only master FETCH_HEAD') else: _, output = common.METHOD_NAME('git diff --name-only FETCH_HEAD') file_paths = [ f.decode('utf-8') for f in output.splitlines() if os.path.exists(f) ] module_path = os.path.join(module_parent_path, 'clusterfuzz') py_changed_tests = [] py_changed_noncf_module = [] py_changed_nontests = [] go_changed_file_paths = [] yaml_changed_file_paths = [] for file_path in file_paths: if file_path.endswith('.go'): go_changed_file_paths.append(file_path) continue if file_path.endswith('.yaml'): yaml_changed_file_paths.append(file_path) continue if not file_path.endswith('.py') or is_auto_generated_file(file_path): continue if file_path.endswith('_test.py'): py_changed_tests.append(file_path) else: py_changed_nontests.append(file_path) if not os.path.abspath(file_path).startswith(module_path): py_changed_noncf_module.append(file_path) # Use --score no to make output less noisy. base_pylint_cmd = 'pylint --score=no --jobs=0' # Test for existence of files before running tools to avoid errors from # misusing the tools. if py_changed_nontests: _execute_command_and_track_error( f'{base_pylint_cmd} --ignore=protos,tests,grammars clusterfuzz ' + ' '.join(py_changed_noncf_module)) if py_changed_tests: _execute_command_and_track_error( f'{base_pylint_cmd} --ignore=protos,grammars --max-line-length=240 ' '--disable no-member clusterfuzz._internal.tests') py_changed_file_paths = py_changed_nontests + py_changed_tests if py_changed_file_paths: _execute_command_and_track_error( f'yapf -p -d {" ".join(py_changed_file_paths)}') _execute_command_and_track_error(f'{formatter.ISORT_CMD} -c ' f'{" ".join(py_changed_file_paths)}') for file_path in py_changed_file_paths: py_test_init_check(file_path) golint_path = os.path.join('local', 'bin', 'golint') for file_path in go_changed_file_paths: if not os.path.basename(file_path) in _GOLINT_EXCEPTIONS: _execute_command_and_track_error(golint_path + ' ' + file_path) output = _execute_command_and_track_error('gofmt -d ' + file_path) if output.strip(): _error() for file_path in yaml_changed_file_paths: yaml_validate(file_path) for file_path in file_paths: license_validate(file_path) if _error_occurred: print('Linting failed, see errors above.') sys.exit(1) else: print('Linting passed.')
3,695
make ethereum transaction
import base64 import random import string from typing import Any, Optional from eth_utils.address import to_checksum_address from rotkehlchen.accounting.structures.balance import Balance from rotkehlchen.accounting.structures.evm_event import EvmEvent, EvmProduct from rotkehlchen.accounting.structures.types import HistoryEventSubType, HistoryEventType from rotkehlchen.assets.asset import CryptoAsset, EvmToken from rotkehlchen.chain.evm.types import string_to_evm_address from rotkehlchen.constants import ONE, ZERO from rotkehlchen.constants.assets import A_ETH, A_USDC from rotkehlchen.exchanges.data_structures import Trade from rotkehlchen.fval import FVal from rotkehlchen.types import ( AddressbookEntry, ApiKey, ApiSecret, AssetAmount, ChainID, ChecksumEvmAddress, EvmTokenKind, EvmTransaction, EVMTxHash, Fee, Location, Price, SupportedBlockchain, Timestamp, TimestampMS, TradeType, deserialize_evm_tx_hash, ) from rotkehlchen.utils.misc import ts_now DEFAULT_START_TS = Timestamp(1451606400) ZERO_TIMESTAMP_MS = TimestampMS(0) def make_random_bytes(size: int) -> bytes: return bytes(bytearray(random.getrandbits(8) for _ in range(size))) def make_random_b64bytes(size: int) -> bytes: return base64.b64encode(make_random_bytes(size)) def make_random_uppercasenumeric_string(size: int) -> str: return ''.join(random.choices(string.ascii_uppercase + string.digits, k=size)) def make_random_positive_fval(max_num: int = 1000000) -> FVal: return FVal(random.uniform(0, max_num)) def make_random_timestamp( start: Optional[Timestamp] = DEFAULT_START_TS, end: Optional[Timestamp] = None, ) -> Timestamp: if end is None: end = ts_now() if start is None: start = DEFAULT_START_TS return Timestamp(random.randint(start, end)) def make_api_key() -> ApiKey: return ApiKey(make_random_b64bytes(128).decode()) def make_api_secret() -> ApiSecret: return ApiSecret(base64.b64encode(make_random_b64bytes(128))) def make_evm_address() -> ChecksumEvmAddress: return to_checksum_address('0x' + make_random_bytes(20).hex()) def make_evm_tx_hash() -> EVMTxHash: return deserialize_evm_tx_hash(make_random_bytes(32)) def METHOD_NAME( tx_hash: Optional[bytes] = None, timestamp: Optional[Timestamp] = None, ) -> EvmTransaction: if tx_hash is None: tx_hash = make_random_bytes(42) timestamp = timestamp if timestamp is not None else Timestamp(0) return EvmTransaction( tx_hash=deserialize_evm_tx_hash(tx_hash), chain_id=ChainID.ETHEREUM, timestamp=timestamp, block_number=0, from_address=make_evm_address(), to_address=make_evm_address(), value=1, gas=1, gas_price=1, gas_used=1, input_data=b'', nonce=0, ) CUSTOM_USDT = EvmToken.initialize( address=string_to_evm_address('0xdAC17F958D2ee523a2206206994597C13D831ec7'), chain_id=ChainID.ETHEREUM, token_kind=EvmTokenKind.ERC20, name='Tether', symbol='USDT', started=Timestamp(1402358400), forked=None, swapped_for=None, coingecko='tether', cryptocompare=None, decimals=6, protocol=None, ) def make_ethereum_event( index: int, tx_hash: Optional[bytes] = None, location_label: Optional[str] = None, asset: CryptoAsset = CUSTOM_USDT, counterparty: Optional[str] = None, event_type: HistoryEventType = HistoryEventType.UNKNOWN, event_subtype: HistoryEventSubType = HistoryEventSubType.NONE, timestamp: TimestampMS = ZERO_TIMESTAMP_MS, address: Optional[ChecksumEvmAddress] = None, product: Optional[EvmProduct] = None, ) -> EvmEvent: if tx_hash is None: tx_hash = make_random_bytes(32) return EvmEvent( tx_hash=deserialize_evm_tx_hash(tx_hash), sequence_index=index, location_label=location_label, identifier=index, timestamp=timestamp, location=Location.ETHEREUM, event_type=event_type, event_subtype=event_subtype, asset=asset, balance=Balance(amount=ONE, usd_value=ONE), counterparty=counterparty, address=address, product=product, ) def generate_events_response( data: list['EvmEvent'], ) -> list: return [{'entry': x.serialize()} for x in data] def make_addressbook_entries() -> list[AddressbookEntry]: return [ AddressbookEntry( address=to_checksum_address('0x9d904063e7e120302a13c6820561940538a2ad57'), name='My dear friend Fred', blockchain=SupportedBlockchain.ETHEREUM, ), AddressbookEntry( address=to_checksum_address('0x368B9ad9B6AAaeFCE33b8c21781cfF375e09be67'), name='Neighbour Thomas', blockchain=SupportedBlockchain.OPTIMISM, ), AddressbookEntry( address=to_checksum_address('0x368B9ad9B6AAaeFCE33b8c21781cfF375e09be67'), name='Neighbour Thomas but in Ethereum', blockchain=SupportedBlockchain.ETHEREUM, ), AddressbookEntry( address=to_checksum_address('0x3D61AEBB1238062a21BE5CC79df308f030BF0c1B'), name='Secret agent Rose', blockchain=SupportedBlockchain.OPTIMISM, ), ] def make_user_notes_entries() -> list[dict[str, Any]]: return [ { 'title': 'TODO List', 'content': '*Sleep* *Wake Up!*', 'location': 'manual balances', 'is_pinned': False, }, { 'title': 'Coins Watchlist #1', 'content': '$NEAR $SCRT $ETH $BTC $AVAX', 'location': 'ledger actions', 'is_pinned': False, }, { 'title': 'Programming Languages', 'content': '-Python -GoLang -Haskell -OCaml -Dart -Rust', 'location': 'manual balances', 'is_pinned': False, }, ] def make_random_user_notes(num_notes: int) -> list[dict[str, Any]]: """Make random user notes to be used in tests""" return [{ 'title': f'Note #{note_number + 1}', 'content': 'I am a random note', 'location': 'manual balances', 'is_pinned': random.choice([True, False]), } for note_number in range(num_notes)] def make_random_trades(num_trades: int) -> list[Trade]: """Make random trades to be used in tests.""" trades = [] for idx in range(num_trades): trade_type = random.choice([TradeType.BUY, TradeType.SELL]) trades.append( Trade( timestamp=Timestamp(random.randint(100000, 10000000)), trade_type=trade_type, location=Location.EXTERNAL, base_asset=A_ETH, quote_asset=A_USDC, amount=AssetAmount(FVal(idx)), rate=Price(FVal(idx)), fee=Fee(ZERO), fee_currency=A_USDC, link='', notes='', ), ) return trades UNIT_BTC_ADDRESS1 = '1BvBMSEYstWetqTFn5Au4m4GFg7xJaNVN2' UNIT_BTC_ADDRESS2 = '1CounterpartyXXXXXXXXXXXXXXXUWLpVr' UNIT_BTC_ADDRESS3 = '18ddjB7HWTVxzvTbLp1nWvaBxU3U2oTZF2' ZERO_ETH_ADDRESS = string_to_evm_address('0x' + '0' * 40)
3,696
test validator chain validation fails
# Copyright Amazon.com, Inc. or its affiliates. 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. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file 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. # language governing permissions and limitations under the License. from __future__ import absolute_import from typing import Callable import pytest import test_data_helpers as tdh from mock import Mock from sagemaker.feature_store.feature_processor._validation import ( SparkUDFSignatureValidator, Validator, ValidatorChain, ) def test_validator_chain(): fp_config = tdh.create_fp_config() udf = Mock(Callable) first_validator = Mock(Validator) second_validator = Mock(Validator) validator_chain = ValidatorChain([first_validator, second_validator]) validator_chain.validate(udf, fp_config) first_validator.validate.assert_called_with(udf, fp_config) second_validator.validate.assert_called_with(udf, fp_config) def METHOD_NAME(): fp_config = tdh.create_fp_config() udf = Mock(Callable) first_validator = Mock(validate=Mock(side_effect=ValueError())) second_validator = Mock(validate=Mock()) validator_chain = ValidatorChain([first_validator, second_validator]) with pytest.raises(ValueError): validator_chain.validate(udf, fp_config) def test_spark_udf_signature_validator_valid(): # One Input fp_config = tdh.create_fp_config(inputs=[tdh.FEATURE_GROUP_DATA_SOURCE]) def one_data_source(fg_data_source, params, spark): return None SparkUDFSignatureValidator().validate(one_data_source, fp_config) # Two Inputs fp_config = tdh.create_fp_config(inputs=[tdh.FEATURE_GROUP_DATA_SOURCE, tdh.S3_DATA_SOURCE]) def two_data_sources(fg_data_source, s3_data_source, params, spark): return None SparkUDFSignatureValidator().validate(two_data_sources, fp_config) # No Optional Args (params and spark) fp_config = tdh.create_fp_config(inputs=[tdh.FEATURE_GROUP_DATA_SOURCE, tdh.S3_DATA_SOURCE]) def no_optional_args(fg_data_source, s3_data_source): return None SparkUDFSignatureValidator().validate(no_optional_args, fp_config) # Optional Args (no params) fp_config = tdh.create_fp_config(inputs=[tdh.FEATURE_GROUP_DATA_SOURCE, tdh.S3_DATA_SOURCE]) def no_optional_params_arg(fg_data_source, s3_data_source, spark): return None SparkUDFSignatureValidator().validate(no_optional_params_arg, fp_config) # No Optional Args (no spark) fp_config = tdh.create_fp_config(inputs=[tdh.FEATURE_GROUP_DATA_SOURCE, tdh.S3_DATA_SOURCE]) def no_optional_spark_arg(fg_data_source, s3_data_source, params): return None SparkUDFSignatureValidator().validate(no_optional_spark_arg, fp_config) def test_spark_udf_signature_validator_udf_input_mismatch(): fp_config = tdh.create_fp_config(inputs=[tdh.FEATURE_GROUP_DATA_SOURCE, tdh.S3_DATA_SOURCE]) def one_input(one, params, spark): return None def three_inputs(one, two, three, params, spark): return None exception_string = ( r"feature_processor expected a function with \(2\) parameter\(s\) before any" r" optional 'params' or 'spark' parameters for the \(2\) requested data source\(s\)\." ) with pytest.raises(ValueError, match=exception_string): SparkUDFSignatureValidator().validate(one_input, fp_config) with pytest.raises(ValueError, match=exception_string): SparkUDFSignatureValidator().validate(three_inputs, fp_config) def test_spark_udf_signature_validator_zero_input_params(): def zero_inputs(params, spark): return None with pytest.raises(ValueError, match="feature_processor expects at least 1 input parameter."): fp_config = tdh.create_fp_config(inputs=[tdh.FEATURE_GROUP_DATA_SOURCE, tdh.S3_DATA_SOURCE]) SparkUDFSignatureValidator().validate(zero_inputs, fp_config) def test_spark_udf_signature_validator_udf_invalid_non_input_position(): fp_config = tdh.create_fp_config(inputs=[tdh.FEATURE_GROUP_DATA_SOURCE, tdh.S3_DATA_SOURCE]) with pytest.raises( ValueError, match="feature_processor expected the 'params' parameter to be the last or second last" " parameter after input parameters.", ): def invalid_params_position(params, fg_data_source, s3_data_source): return None SparkUDFSignatureValidator().validate(invalid_params_position, fp_config) with pytest.raises( ValueError, match="feature_processor expected the 'spark' parameter to be the last or second last" " parameter after input parameters.", ): def invalid_spark_position(spark, fg_data_source, s3_data_source): return None SparkUDFSignatureValidator().validate(invalid_spark_position, fp_config)
3,697
main
#!/usr/bin/python3 # This file is part of Cockpit. # # Copyright (C) 2018 Red Hat, Inc. # # Cockpit is free software; you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation; either version 2.1 of the License, or # (at your option) any later version. # # Cockpit is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Cockpit; If not, see <http://www.gnu.org/licenses/>. # # This command is meant to be used as an authentication command launched # by cockpit-ws. It asks for authentication from cockpit-ws and expects # to receive a basic auth header in response. If COCKPIT_SSH_KEY_PATH is set # we will try to decrypt the key with the given password. If successful # we send the decrypted key to cockpit-ws for use with cockpit-ssh. # Once finished we exec cockpit-ssh to actually establish the ssh connection. # All communication with cockpit-ws happens on stdin and stdout using the # cockpit protocol # (https://github.com/cockpit-project/cockpit/blob/main/doc/protocol.md) import base64 import json import os import subprocess import sys import time COCKPIT_SSH_COMMAND = "/usr/libexec/cockpit-ssh" def usage(): print("usage", sys.argv[0], "[user@]host[:port]", file=sys.stderr) sys.exit(os.EX_USAGE) def send_frame(content): data = json.dumps(content).encode('utf-8') os.write(1, str(len(data) + 1).encode('utf-8')) os.write(1, b"\n\n") os.write(1, data) def send_auth_command(challenge, response): cmd = { "command": "authorize", } if challenge: cmd["cookie"] = f"session{os.getpid()}{time.time()}" cmd["challenge"] = challenge if response: cmd["response"] = response send_frame(cmd) def send_problem_init(problem, message, auth_methods): cmd = { "command": "init", "problem": problem } if message: cmd["message"] = message if auth_methods: cmd["auth-method-results"] = auth_methods send_frame(cmd) def read_size(fd): sep = b'\n' size = 0 seen = 0 while True: t = os.read(fd, 1) if not t: return 0 if t == sep: break size = (size * 10) + int(t) seen = seen + 1 if seen > 7: raise ValueError("Invalid frame: size too long") return size def read_frame(fd): size = read_size(fd) data = b"" while size > 0: d = os.read(fd, size) size = size - len(d) data += d return data.decode("UTF-8") def read_auth_reply(): data = read_frame(1) cmd = json.loads(data) response = cmd.get("response") if cmd.get("command") != "authorize" or \ not cmd.get("cookie") or not response: raise ValueError("Did not receive a valid authorize command") return response def decode_basic_header(response): starts = "Basic " assert response assert response.startswith(starts), response val = base64.b64decode(response[len(starts):].encode('utf-8')).decode("utf-8") user, password = val.split(':', 1) return user, password def load_key(fname, password): # ssh-add has the annoying behavior that it re-asks without any limit if the password is wrong # to mitigate, self-destruct to only allow one iteration with open("/run/askpass", "w") as fd: fd.write("""#!/bin/sh rm -f $0 cat /run/password""") os.fchmod(fd.fileno(), 0o755) env = os.environ.copy() env["SSH_ASKPASS_REQUIRE"] = "force" env["SSH_ASKPASS"] = "/run/askpass" pass_fd = os.open("/run/password", os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_CLOEXEC, mode=0o600) try: os.write(pass_fd, password.encode("UTF-8")) os.close(pass_fd) p = subprocess.run(["ssh-add", "-t", "30", fname], check=False, env=env, capture_output=True, encoding="UTF-8") finally: os.unlink("/run/password") if p.returncode == 0: send_auth_command(None, "ssh-agent") return True else: print("Couldn't load private key:", p.stderr, file=sys.stderr) return False def METHOD_NAME(args): if len(args) != 2: usage() host = args[1] key_name = os.environ.get("COCKPIT_SSH_KEY_PATH") if key_name: send_auth_command("*", None) try: resp = read_auth_reply() user, password = decode_basic_header(resp) except (ValueError, TypeError, AssertionError) as e: send_problem_init("internal-error", str(e), {}) raise if load_key(key_name, password): host = f"{user}@{host}" else: send_problem_init("authentication-failed", "Couldn't open private key", {"password": "denied"}) return os.execlpe(COCKPIT_SSH_COMMAND, COCKPIT_SSH_COMMAND, host, os.environ) if __name__ == '__main__': METHOD_NAME(sys.argv)
3,698
is column list text encoding dict
__all__ = ['UdtfNode', 'ArgNode', 'PrimitiveNode', 'ComposedNode', 'AnnotationNode', 'TemplateNode'] import sys from abc import abstractmethod import TableFunctionsFactory_transformers as transformers import TableFunctionsFactory_util as util if sys.version_info > (3, 0): from abc import ABC from collections.abc import Iterable else: from abc import ABCMeta as ABC from collections import Iterable class Node(object): __metaclass__ = ABC @abstractmethod def accept(self, visitor): pass def get_parent(self, cls): if isinstance(self, cls): return self if self.parent is not None: return self.parent.get_parent(cls) raise ValueError("could not find parent with given class %s" % (cls)) def copy(self, *args): other = self.__class__(*args) # copy parent and arg_pos for attr in ['parent', 'arg_pos']: if attr in self.__dict__: setattr(other, attr, getattr(self, attr)) return other class PrintNode(object): def __str__(self): return self.accept(transformers.AstPrinter()) def __repr__(self): return str(self) class IterableNode(Iterable): pass class UdtfNode(Node, IterableNode, PrintNode): def __init__(self, name, inputs, outputs, annotations, templates, sizer, line): """ Parameters ---------- name : str inputs : list[ArgNode] outputs : list[ArgNode] annotations : Optional[List[AnnotationNode]] templates : Optional[list[TemplateNode]] sizer : Optional[str] line: str """ self.name = name self.inputs = inputs self.outputs = outputs self.annotations = annotations self.templates = templates self.sizer = sizer self.line = line def accept(self, visitor): return visitor.visit_udtf_node(self) def __iter__(self): for i in self.inputs: yield i for o in self.outputs: yield o for a in self.annotations: yield a if self.templates: for t in self.templates: yield t class ArgNode(Node, IterableNode, PrintNode): def __init__(self, type, annotations): """ Parameters ---------- type : TypeNode annotations : List[AnnotationNode] """ self.type = type self.annotations = annotations self.arg_pos = None self.kind = None def accept(self, visitor): return visitor.visit_arg_node(self) def __iter__(self): yield self.type for a in self.annotations: yield a def get_annotation(self, key, default=None): for a in self.annotations: if a.key == key: return a.value return default def set_annotation(self, key, value): found = False for i, a in enumerate(self.annotations): if a.key == key: assert not found, (i, a) # annotations with the same key not supported self.annotations[i] = AnnotationNode(key, value) found = True if not found: self.annotations.append(AnnotationNode(key, value)) class TypeNode(Node): def is_array(self): return self.type == "Array" def is_column_any(self): return self.is_column() or self.is_column_list() def is_column(self): return self.type == "Column" def is_column_list(self): return self.type == "ColumnList" def is_cursor(self): return self.type == "Cursor" def is_output_buffer_sizer(self): t = self.type return util.translate_map.get(t, t) in util.OutputBufferSizeTypes def is_text_encoding_dict(self): return self.type == 'TextEncodingDict' def is_array_text_encoding_dict(self): return self.type == 'ArrayTextEncodingDict' def is_integer_scalar(self): return self.type.lower() in ('int8_t', 'int16_t', 'int32_t', 'int64_t') def is_float_scalar(self): return self.type.lower() in ('float', 'double') def is_boolean_scalar(self): return self.type.lower() == 'bool' def is_string_scalar(self): # we only support 'TextEncodingNone' string scalars atm return self.type == "TextEncodingNone" def is_scalar(self): return self.is_integer_scalar() or self.is_float_scalar() or self.is_boolean_scalar() or self.is_string_scalar() class PrimitiveNode(TypeNode, PrintNode): def __init__(self, type): """ Parameters ---------- type : str """ self.type = type def accept(self, visitor): return visitor.visit_primitive_node(self) def __eq__(self, other): if isinstance(other, PrimitiveNode): return self.type == other.type return False class ComposedNode(TypeNode, IterableNode, PrintNode): def __init__(self, type, inner): """ Parameters ---------- type : str inner : list[TypeNode] """ self.type = type self.inner = inner def accept(self, visitor): return visitor.visit_composed_node(self) def cursor_length(self): assert self.is_cursor() return len(self.inner) def __iter__(self): for i in self.inner: yield i def is_text_encoding_dict(self): return False def is_array_text_encoding_dict(self): return self.is_array() and self.inner[0].is_text_encoding_dict() def is_column_text_encoding_dict(self): return self.is_column() and self.inner[0].is_text_encoding_dict() def METHOD_NAME(self): return self.is_column_list() and self.inner[0].is_text_encoding_dict() def is_column_array_text_encoding_dict(self): return self.is_column() and self.inner[0].is_array_text_encoding_dict() def is_any_text_encoding_dict(self): return self.inner[0].is_text_encoding_dict() or self.inner[0].is_array_text_encoding_dict() def is_column_of(self, T): return self.is_column() and self.inner[0] == T def is_column_list_of(self, T): return self.is_column_list() and self.inner[0] == T class AnnotationNode(Node, PrintNode): def __init__(self, key, value): """ Parameters ---------- key : str value : {str, list} """ self.key = key self.value = value def accept(self, visitor): return visitor.visit_annotation_node(self) class TemplateNode(Node, PrintNode): def __init__(self, key, types): """ Parameters ---------- key : str types : tuple[str] """ self.key = key self.types = types def accept(self, visitor): return visitor.visit_template_node(self)
3,699
context encoder input
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # hack to make sure -m transformer/generator works as expected """ Poly-encoder agent that ingests image features. """ from typing import Optional from parlai.core.params import ParlaiParser from parlai.core.opt import Opt from typing import Any, Dict import torch from parlai.agents.image_seq2seq.modules import ContextWithImageEncoder from parlai.agents.transformer.polyencoder import PolyencoderAgent, PolyEncoderModule from parlai.core.torch_agent import Batch from parlai.core.torch_image_agent import TorchImageAgent from parlai.utils.misc import warn_once class ImagePolyencoderAgent(PolyencoderAgent, TorchImageAgent): """ Poly-encoder Agent that ingests image features. Agent that allows encoding image features and adding or concatenating them to the context encoding. """ @classmethod def add_cmdline_args( cls, parser: ParlaiParser, partial_opt: Optional[Opt] = None ) -> ParlaiParser: """ Add command-line arguments specifically for this agent. """ PolyencoderAgent.add_cmdline_args(parser, partial_opt=partial_opt) TorchImageAgent.add_cmdline_args(parser, partial_opt=partial_opt) agent = parser.add_argument_group('ImagePolyencoder Args') agent.add_argument( '--image-combination-mode', type=str, default='prepend', choices=['add', 'append', 'prepend'], help='How to combine image embedding (if used) with context embedding', ) # TODO: more thoroughly test out whether one of these choices is best and add a # 'recommended' arg here. 'add' and 'prepend' seem to be roughly similar in # performance agent.set_defaults(reduction_type=None) # This agent doesn't support any encoder output reductions return agent def build_model(self, states=None): """ Return built model. """ return ImagePolyencoderModule(self.opt, self.dict, self.NULL_IDX) def batchify_image_features(self, batch: Batch) -> Batch: """ Return the image features as a Tensor of the correct type. Fill in missing feature vectors. Here, we require image features to be saved in `batch` as a Tensor for passing through the image encoder. This is required for data_parallel. """ # Checks/formatting of batch.image bsz = self._get_batch_size(batch) if batch.image is None or len(batch.image) == 0: batch.image = [None] * bsz else: assert len(batch.image) == bsz # Process all image feature vectors, or add in zero vectors if missing processed_features_list = [] processed_zero_features = self._process_image_features( torch.zeros((self.image_features_dim,)) ) for orig_features in batch.image: if isinstance(orig_features, torch.Tensor): processed_features_list.append( self._process_image_features(orig_features) ) else: if orig_features is not None: warn_once( 'Unsupported image feature format. Image features will be ignored!' ) processed_features_list.append(processed_zero_features) # Turn into batchsize x image_features_dim for DataParallel batch.image = torch.stack(processed_features_list) return batch def _get_batch_size(self, batch) -> int: """ Return the size of the batch. Use the size of the text vec if it exists; otherwise, use the length of the image feature list. """ if batch.text_vec is not None: return batch.text_vec.size(0) else: return len(batch.image) def _model_context_input(self, batch) -> Dict[str, Any]: """ Override PolyencoderAgent's context inputs into the model. """ return {'ctxt_tokens': batch.text_vec, 'ctxt_image': batch.image} def load_state_dict(self, state_dict): """ Override to account for weights used for image features. """ for tensor in ['dummy_image_enc', 'ones_mask']: key = f'encoder_ctxt.{tensor}' if hasattr(self.model.encoder_ctxt, tensor) and key not in state_dict: state_dict[key] = getattr(self.model.encoder_ctxt, tensor) if hasattr(self.model.encoder_ctxt, 'image_encoder'): for layer_idx, layer in enumerate(self.model.encoder_ctxt.image_encoder): for tensor in ['weight', 'bias']: key = f'encoder_ctxt.image_encoder.{layer_idx}.{tensor}' if hasattr(layer, tensor) and key not in state_dict: state_dict[key] = getattr(layer, tensor) super().load_state_dict(state_dict) class ImagePolyencoderModule(PolyEncoderModule): """ Poly-encoder model with image features. Model that allows encoding image features and adding or concatenating them to the context encoding. """ def get_encoder(self, opt, dict_, null_idx, reduction_type, for_context: bool): """ Return encoder that allows for image features to be passed in, given options. :param opt: opt dict :param dict: dictionary agent :param null_idx: null/pad index into dict :param reduction_type: only used for compatibility with the superclass method :param for_context: whether this is the context encoder (as opposed to the candidate encoder) :return: either a TransformerEncoder or a ContextWithImageEncoder, initialized correctly """ if for_context: if reduction_type is not None: raise NotImplementedError('No encoder output reductions supported!') embeddings = self._get_embeddings( dict_=dict_, null_idx=null_idx, embedding_size=opt['embedding_size'] ) return ContextWithImageEncoder( opt=opt, vocabulary_size=len(dict_), embedding=embeddings, padding_idx=null_idx, image_encoder_num_layers=opt['image_encoder_num_layers'], image_features_dim=opt['image_features_dim'], image_combination_mode=opt['image_combination_mode'], n_image_tokens=opt['n_image_tokens'], ) else: # The candidate encoder is the same as for PolyEncoderModule return super().get_encoder( opt=opt, dict_=dict_, null_idx=null_idx, reduction_type=reduction_type, for_context=for_context, ) def METHOD_NAME(self, ctxt_inputs: Dict[str, Any]) -> Dict[str, Any]: """ Override PolyEncoderModule's inputs into the context encoder. """ assert set(ctxt_inputs.keys()) == {'ctxt_tokens', 'ctxt_image'} return { 'src_tokens': ctxt_inputs['ctxt_tokens'], 'image_features': ctxt_inputs['ctxt_image'], } def _get_context_batch_size(self, **ctxt_inputs: torch.Tensor) -> int: """ Return the batch size of the context. """ if ctxt_inputs['ctxt_tokens'] is not None: return ctxt_inputs['ctxt_tokens'].size(0) else: return ctxt_inputs['ctxt_image'].size(0)