max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
2,690
# Copyright ClusterHQ Inc. See LICENSE file for details. """ Functional tests for ``flocker.node.agents.ebs`` using an EC2 cluster. """ from uuid import uuid4 from bitmath import Byte, GiB from datetime import timedelta from botocore.exceptions import ClientError from testtools.matchers import AllMatch, ContainsAll from twisted.python.constants import Names, NamedConstant from eliot.testing import ( LoggedAction, capture_logging, assertHasMessage, LoggedMessage, ) from ..blockdevice import MandatoryProfiles from ..ebs import ( _wait_for_volume_state_change, VolumeOperations, VolumeStateTable, VolumeStates, TimeoutException, _reached_end_state, UnexpectedStateException, EBSMandatoryProfileAttributes, _get_volume_tag, AttachUnexpectedInstance, VolumeBusy, _next_device, ) from ....testtools import AsyncTestCase, async_runner from .._logging import ( AWS_CODE, AWS_MESSAGE, AWS_REQUEST_ID, BOTO_LOG_HEADER, CREATE_VOLUME_FAILURE, AWS_ACTION, VOLUME_BUSY_MESSAGE, ) from ..testtools import ( InvalidConfig, get_blockdevice_config, get_blockdeviceapi_with_cleanup, get_ec2_client_for_test, make_iblockdeviceapi_tests, make_icloudapi_tests, make_iprofiledblockdeviceapi_tests, require_backend, ) TIMEOUT = 5 ONE_GIB = 1073741824 @require_backend('aws') def ebsblockdeviceapi_for_test(test_case): """ Create an ``EBSBlockDeviceAPI`` for use by tests. """ return get_blockdeviceapi_with_cleanup(test_case) class EBSBlockDeviceAPIInterfaceTests( make_iblockdeviceapi_tests( blockdevice_api_factory=( lambda test_case: ebsblockdeviceapi_for_test( test_case=test_case, ) ), unknown_blockdevice_id_factory=lambda test: u"vol-00000000", ) ): """ Due to AWS eventual consistency sometimes taking too long, give these tests some extra time, such that they are limited only by the CI system max time. We are addressing eventual consistency issues; see https://clusterhq.atlassian.net/browse/FLOC-3219 """ run_tests_with = async_runner(timeout=timedelta(hours=1)) """ Interface adherence Tests for ``EBSBlockDeviceAPI``. """ def repeat_retries(self): """ Override retry policy from base class. EBS is eventually consistent, so e.g. a newly created volume may not show up in listing results for a while. So, we retry for up to 30 seconds. """ return [1] * 30 @capture_logging(None) def test_volume_busy_error_on_busy_state(self, logger): """ A ``VolumeBusy`` is raised if a volume's attachment state is "busy" when attempting to detach the volume. This can occur if an attempt is made to detach a volume that has not been unmounted. """ try: config = get_blockdevice_config() except InvalidConfig as e: self.skipTest(str(e)) # Create a volume dataset_id = uuid4() flocker_volume = self.api.create_volume( dataset_id=dataset_id, size=self.minimum_allocatable_size, ) ec2_client = get_ec2_client_for_test(config) # Attach the volume. instance_id = self.api.compute_instance_id() self.api.attach_volume(flocker_volume.blockdevice_id, instance_id) volume = ec2_client.connection.Volume(flocker_volume.blockdevice_id) def clean_volume(volume): volume.detach_from_instance() _wait_for_volume_state_change(VolumeOperations.DETACH, volume) volume.delete() self.addCleanup(clean_volume, volume) # Artificially set the volume's attachment state to "busy", by # monkey-patching the EBS driver's ``_get_ebs_volume`` method. def busy_ebs_volume(volume_id): busy_volume = ec2_client.connection.Volume(volume_id) busy_volume.load() if busy_volume.attachments: busy_volume.attachments[0]['State'] = "busy" return busy_volume self.patch(self.api, "_get_ebs_volume", busy_ebs_volume) # Try to detach and get the VolumeBusy exception. self.assertRaises( VolumeBusy, self.api.detach_volume, flocker_volume.blockdevice_id) expected_keys = set(["volume_id", "attachments"]) messages = [ message.message for message in LoggedMessage.of_type(logger.messages, VOLUME_BUSY_MESSAGE) ] self.assertThat(messages, AllMatch(ContainsAll(expected_keys))) def test_attach_foreign_instance_error(self): """ Attempting to attach a volume to a non-local instance will raise an ``AttachUnexpectedInstance`` error. """ dataset_id = uuid4() volume = self.api.create_volume(dataset_id=dataset_id, size=ONE_GIB) self.addCleanup(self.api.destroy_volume, volume.blockdevice_id) bad_instance_id = u'i-12345678' self.assertRaises( AttachUnexpectedInstance, self.api.attach_volume, volume.blockdevice_id, bad_instance_id ) def test_attach_when_foreign_device_has_next_device(self): """ ``attach_volume`` does not attempt to use device paths that are already assigned to volumes that have been attached outside of Flocker. """ try: config = get_blockdevice_config() except InvalidConfig as e: self.skipTest(str(e)) dataset_id = uuid4() ec2_client = get_ec2_client_for_test(config) meta_client = ec2_client.connection.meta.client # Create a volume directly using boto. requested_volume = meta_client.create_volume( Size=1, AvailabilityZone=ec2_client.zone) created_volume = ec2_client.connection.Volume( requested_volume['VolumeId']) def clean_volume(volume): volume.detach_from_instance() _wait_for_volume_state_change(VolumeOperations.DETACH, volume) volume.delete() self.addCleanup(clean_volume, created_volume) _wait_for_volume_state_change(VolumeOperations.CREATE, created_volume) # Get this instance ID. instance_id = self.api.compute_instance_id() # Attach manual volume using /xvd* device. device_name = _next_device().replace(u'/sd', u'/xvd') self.api._attach_ebs_volume( created_volume.id, instance_id, device_name) _wait_for_volume_state_change(VolumeOperations.ATTACH, created_volume) # Now create a volume via Flocker EBS backend. blockdevice_volume = self.api.create_volume( dataset_id=dataset_id, size=ONE_GIB) flocker_volume = ec2_client.connection.Volume( blockdevice_volume.blockdevice_id) self.addCleanup(clean_volume, flocker_volume) # Attach the blockdevice volume to this instance. # The assertion in this test is that this operation does not # raise an ``AttachedUnexpectedDevice`` error. self.api.attach_volume( blockdevice_volume.blockdevice_id, instance_id) def test_foreign_volume(self): """ ``list_volumes`` lists only those volumes belonging to the current Flocker cluster. """ try: config = get_blockdevice_config() except InvalidConfig as e: self.skipTest(str(e)) ec2_client = get_ec2_client_for_test(config) meta_client = ec2_client.connection.meta.client requested_volume = meta_client.create_volume( Size=int(Byte(self.minimum_allocatable_size).to_GiB().value), AvailabilityZone=ec2_client.zone) created_volume = ec2_client.connection.Volume( requested_volume['VolumeId']) self.addCleanup(created_volume.delete) _wait_for_volume_state_change(VolumeOperations.CREATE, created_volume) self.assertEqual(self.api.list_volumes(), []) def test_foreign_cluster_volume(self): """ ``list_volumes`` excludes volumes belonging to other Flocker clusters. """ blockdevice_api2 = ebsblockdeviceapi_for_test( test_case=self, ) flocker_volume = blockdevice_api2.create_volume( dataset_id=uuid4(), size=self.minimum_allocatable_size, ) self.assert_foreign_volume(flocker_volume) def test_naming(self): """ Newly created volumes get the "Name" tag set to a human-readable name. """ try: config = get_blockdevice_config() except InvalidConfig as e: self.skipTest(str(e)) dataset_id = uuid4() flocker_volume = self.api.create_volume( dataset_id=dataset_id, size=self.minimum_allocatable_size, ) ec2_client = get_ec2_client_for_test(config) volume = ec2_client.connection.Volume(flocker_volume.blockdevice_id) name = _get_volume_tag(volume, u"Name") self.assertEqual(name, u"flocker-{}".format(dataset_id)) @capture_logging(lambda self, logger: None) def test_boto_ec2response_error(self, logger): """ 1. Invalid parameters to Boto's EBS API calls raise the right exception after logging to Eliot. 2. Verify Eliot log output for expected message fields from logging decorator for boto.exception.EC2Exception originating from boto.ec2.connection.EC2Connection. """ # Test 1: Create volume with size 0. # Raises: ClientError self.assertRaises(ClientError, self.api.create_volume, dataset_id=uuid4(), size=0,) # Test 2: Set EC2 connection zone to an invalid string. # Raises: ClientError self.api.zone = u'invalid_zone' self.assertRaises( ClientError, self.api.create_volume, dataset_id=uuid4(), size=self.minimum_allocatable_size, ) # Validate decorated method for exception logging # actually logged to ``Eliot`` logger. expected_message_keys = {AWS_CODE.key, AWS_MESSAGE.key, AWS_REQUEST_ID.key} for logged in LoggedAction.of_type(logger.messages, AWS_ACTION,): key_subset = set(key for key in expected_message_keys if key in logged.end_message.keys()) self.assertEqual(expected_message_keys, key_subset) @capture_logging(None) def test_boto_request_logging(self, logger): """ Boto is configured to send log events to Eliot when it makes an AWS API request. """ self.api.list_volumes() messages = list( message for message in logger.messages if message.get("message_type") == BOTO_LOG_HEADER ) self.assertNotEqual( [], messages, "Didn't find Boto messages in logged messages {}".format( messages ) ) def test_create_volume_gold_profile(self): """ Requesting ``gold`` profile during volume creation honors ``gold`` attributes. """ self._assert_create_volume_with_mandatory_profile( MandatoryProfiles.GOLD) @capture_logging(assertHasMessage, CREATE_VOLUME_FAILURE) def test_create_volume_violate_requested_profile(self, logger): """ Volume creation request that cannot satisfy attributes of requested profile makes a second (successful) attempt to create the volume with default profile. """ self._assert_create_volume_with_mandatory_profile( MandatoryProfiles.GOLD, created_profile=MandatoryProfiles.DEFAULT, size_GiB=1) def test_create_too_large_volume_with_profile(self): """ Create a volume so large that none of the ``MandatoryProfiles`` can be assigned to it. """ self.assertRaises(ClientError, self._assert_create_volume_with_mandatory_profile, MandatoryProfiles.GOLD, size_GiB=1024*1024) def test_create_volume_silver_profile(self): """ Requesting ``silver`` profile during volume creation honors ``silver`` attributes. """ self._assert_create_volume_with_mandatory_profile( MandatoryProfiles.SILVER) def test_create_too_large_volume_silver_profile(self): """ Too large volume (> 16TiB) for ``silver`` profile. """ self.assertRaises(ClientError, self._assert_create_volume_with_mandatory_profile, MandatoryProfiles.SILVER, size_GiB=1024*1024) def test_create_volume_bronze_profile(self): """ Requesting ``bronze`` profile during volume creation honors ``bronze`` attributes. """ self._assert_create_volume_with_mandatory_profile( MandatoryProfiles.BRONZE) def _assert_create_volume_with_mandatory_profile(self, profile, created_profile=None, size_GiB=4): """ Volume created with given profile has the attributes expected from the profile. :param ValueConstant profile: Name of profile to use for creation. :param ValueConstant created_profile: Name of the profile volume is expected to be created with. :param int size_GiB: Size of volume to be created. """ if created_profile is None: created_profile = profile volume1 = self.api.create_volume_with_profile( dataset_id=uuid4(), size=self.minimum_allocatable_size * size_GiB, profile_name=profile.value) cannonical_profile = MandatoryProfiles.lookupByValue( created_profile.value) A = EBSMandatoryProfileAttributes.lookupByName( cannonical_profile.name).value ebs_volume = self.api._get_ebs_volume(volume1.blockdevice_id) self.assertEqual(ebs_volume.volume_type, A.volume_type.value) requested_iops = A.requested_iops(ebs_volume.size) self.assertEqual(ebs_volume.iops if requested_iops is not None else None, requested_iops) class EBSProfiledBlockDeviceAPIInterfaceTests( make_iprofiledblockdeviceapi_tests( profiled_blockdevice_api_factory=ebsblockdeviceapi_for_test, dataset_size=GiB(4).to_Byte().value ) ): """ Interface adherence tests for ``IProfiledBlockDeviceAPI``. """ pass class VolumeStub(object): """ Stub object to represent properties found on the immutable `boto3.resources.factory.ec2.Volume`. This allows a ``Volume`` with properties to be compared to expected values. """ def __init__(self, **kwargs): self._volume_attributes = dict( id=None, create_time=None, tags=None, attachments=None, size=None, snapshot_id=None, zone=None, volume_type=None, iops=None, state=None, encrypted=None ) for key, value in kwargs.items(): if key in self._volume_attributes: self._volume_attributes[key] = value def __getattr__(self, name): if name in self._volume_attributes: return self._volume_attributes[name] else: raise AttributeError def __eq__(self, other): """ Compare set attributes on this stub to a boto3 ``Volume``. """ equal = True for key, value in self._volume_attributes.items(): other_value = getattr(other, key, None) if value is not None: if value != other_value: equal = False if other_value is not None: if value != other_value: equal = False return equal def __ne__(self, other): """ Negative comparison. See ``VolumeStub.__eq__``. """ return not self.__eq__(other) class VolumeStateTransitionTests(AsyncTestCase): """ Tests for volume state operations and resulting volume state changes. """ class VolumeEndStateTypes(Names): """ Types of volume states to simulate. """ ERROR_STATE = NamedConstant() TRANSIT_STATE = NamedConstant() DESTINATION_STATE = NamedConstant() class VolumeAttachDataTypes(Names): """ Types of volume's attach data states to simulate. """ MISSING_ATTACH_DATA = NamedConstant() MISSING_INSTANCE_ID = NamedConstant() MISSING_DEVICE = NamedConstant() ATTACH_SUCCESS = NamedConstant() DETACH_SUCCESS = NamedConstant() V = VolumeOperations S = VolumeEndStateTypes A = VolumeAttachDataTypes def _create_template_ebs_volume(self, operation): """ Helper function to create template EBS volume to work on. :param NamedConstant operation: Intended use of created template. A value from ``VolumeOperations``. :returns: Suitable volume in the right start state for input operation. :rtype: ``VolumeStub`` """ volume = VolumeStub() # Irrelevant volume attributes. volume.id = u'vol-9c48a689' volume.create_time = u'2015-07-14T22:46:00.447Z' volume.size = 1 volume.snapshot_id = '' volume.zone = u'us-west-2b' volume.type = u'standard' volume_state_table = VolumeStateTable() state_flow = volume_state_table.table[operation] start_state = state_flow.start_state.value # Interesting volume attribute. volume.state = start_state return volume def _pick_end_state(self, operation, state_type): """ Helper function to pick a desired volume state for given input operation. :param NamedConstant operation: Volume operation to pick a state for. A value from ``VolumeOperations``. :param NamedConstant state_type: Volume state type request. :returns: A state from ``VolumeStates`` that will not be part of a volume's states resulting from input operation. :rtype: ValueConstant """ volume_state_table = VolumeStateTable() state_flow = volume_state_table.table[operation] if state_type == self.S.ERROR_STATE: valid_states = set([state_flow.start_state, state_flow.transient_state, state_flow.end_state]) err_states = set(VolumeStates._enumerants.values()) - valid_states err_state = err_states.pop() return err_state.value elif state_type == self.S.TRANSIT_STATE: return state_flow.transient_state.value elif state_type == self.S.DESTINATION_STATE: return state_flow.end_state.value def _pick_attach_data(self, attach_type): """ Helper function to create desired volume attach data. :param NamedConstant attach_type: Type of attach data to create. :returns: Volume attachment set that conforms to requested attach type. :rtype: `dict` """ if attach_type == self.A.MISSING_ATTACH_DATA: return None elif attach_type == self.A.MISSING_INSTANCE_ID: attach_data = dict() attach_data['Device'] = u'/dev/sdf' attach_data['InstanceId'] = '' return attach_data elif attach_type == self.A.MISSING_DEVICE: attach_data = dict() attach_data['Device'] = '' attach_data['InstanceId'] = u'i-xyz' return attach_data elif attach_type == self.A.ATTACH_SUCCESS: attach_data = dict() attach_data['Device'] = u'/dev/sdf' attach_data['InstanceId'] = u'i-xyz' return attach_data elif attach_type == self.A.DETACH_SUCCESS: return None def _custom_update(self, operation, state_type, attach_data=A.MISSING_ATTACH_DATA): """ Create a custom update function for a volume. """ def update(volume): """ Transition volume to desired end state and attach data. :param boto.ec2.volume.Volume volume: Volume to move to invalid state. """ volume.state = self._pick_end_state(operation, state_type) volume.attachments = [self._pick_attach_data(attach_data)] return update def _assert_unexpected_state_exception(self, operation, volume_end_state_type, attach_type=A.MISSING_ATTACH_DATA): """ Assert that configured volume state change for given testcase indicates incomplete operation execution. """ volume = self._create_template_ebs_volume(operation) update = self._custom_update(operation, volume_end_state_type, attach_type) self.assertRaises(UnexpectedStateException, _reached_end_state, operation, volume, update, 0, TIMEOUT) def _assert_fail(self, operation, volume_end_state_type, attach_data_type=A.MISSING_ATTACH_DATA): """ Assert that configured volume state change for given testcase indicates incomplete operation execution. """ volume = self._create_template_ebs_volume(operation) update = self._custom_update(operation, volume_end_state_type, attach_data_type) finish_result = _reached_end_state(operation, volume, update, 0) self.assertEqual(False, finish_result) def _assert_timeout(self, operation, testcase, attach_data_type=A.MISSING_ATTACH_DATA): """ Helper function to validate that ``TimeoutException`` is raised as a result of performing input operation for given testcase on a volume. """ volume = self._create_template_ebs_volume(operation) update = self._custom_update(operation, testcase, attach_data_type) self.assertRaises(TimeoutException, _reached_end_state, operation, volume, update, TIMEOUT + 1, TIMEOUT) def _process_volume(self, operation, testcase, attach_data_type=A.ATTACH_SUCCESS): """ Helper function to validate that performing given operation for given testcase on a volume succeeds. """ volume = self._create_template_ebs_volume(operation) _wait_for_volume_state_change(operation, volume, self._custom_update(operation, testcase, attach_data_type), TIMEOUT) return volume def test_create_invalid_state(self): """ Assert that error volume state during creation raises ``UnexpectedStateException``. """ self._assert_unexpected_state_exception(self.V.CREATE, self.S.ERROR_STATE) def test_destroy_invalid_state(self): """ Assert that error volume state during destroy raises ``UnexpectedStateException``. """ self._assert_unexpected_state_exception(self.V.DESTROY, self.S.ERROR_STATE) def test_attach_invalid_state(self): """ Assert that error volume state during attach raises ``UnexpectedStateException``. """ self._assert_unexpected_state_exception(self.V.ATTACH, self.S.ERROR_STATE) def test_detach_invalid_state(self): """ Assert that error volume state during detach raises ``UnexpectedStateException``. """ self._assert_unexpected_state_exception(self.V.DETACH, self.S.ERROR_STATE) def test_stuck_create(self): """ Assert that stuck create state indicates operation in progress. """ self._assert_fail(self.V.CREATE, self.S.TRANSIT_STATE) def test_stuck_destroy(self): """ Assert that stuck destroy state indicates operation in progress. """ self._assert_fail(self.V.DESTROY, self.S.TRANSIT_STATE) def test_stuck_attach(self): """ Assert that stuck attach state indicates operation in progress. """ self._assert_fail(self.V.ATTACH, self.S.TRANSIT_STATE) def test_stuck_detach(self): """ Assert that stuck detach state indicates operation in progress. """ self._assert_fail(self.V.DETACH, self.S.TRANSIT_STATE) def test_attach_missing_attach_data(self): """ Assert that missing attach data indicates attach in progress. """ self._assert_fail(self.V.ATTACH, self.S.DESTINATION_STATE) def test_attach_missing_instance_id(self): """ Assert that missing attach instance id indicates attach in progress. """ self._assert_fail(self.V.ATTACH, self.S.DESTINATION_STATE, self.A.MISSING_INSTANCE_ID) def test_attach_missing_device(self): """ Assert that missing attached device name indicates attach in progress. """ self._assert_fail(self.V.ATTACH, self.S.DESTINATION_STATE, self.A.MISSING_DEVICE) def test_timeout(self): """ Assert that ``TimeoutException`` is thrown if volume state transition takes longer than configured timeout. """ self._assert_timeout(self.V.ATTACH, self.S.DESTINATION_STATE) def test_create_success(self): """ Assert that successful volume creation leads to valid volume end state. """ volume = self._process_volume(self.V.CREATE, self.S.DESTINATION_STATE) self.assertEqual(volume.state, u'available') def test_destroy_success(self): """ Assert that successful volume destruction leads to valid end state. """ volume = self._process_volume(self.V.DESTROY, self.S.DESTINATION_STATE) self.assertEquals(volume.state, u'') def test_attach_success(self): """ Test if successful attach volume operation leads to expected state. """ volume = self._process_volume(self.V.ATTACH, self.S.DESTINATION_STATE) self.assertEqual([volume.state, volume.attachments[0]['Device'], volume.attachments[0]['InstanceId']], [u'in-use', u'/dev/sdf', u'i-xyz']) def test_detach_success(self): """ Test if successful detach volume operation leads to expected state. """ volume = self._process_volume(self.V.DETACH, self.S.DESTINATION_STATE, self.A.DETACH_SUCCESS) self.assertEqual(volume.state, u'available') class EBSCloudInterfaceTests( make_icloudapi_tests( blockdevice_api_factory=( lambda test_case: ebsblockdeviceapi_for_test( test_case=test_case)))): """ ``ICloudAPI`` adherence tests for ``EBSBlockDeviceAPI``. """
12,485
971
<filename>src/include/optimizer/statistics/table_stats.h #pragma once #include <memory> #include <shared_mutex> #include <unordered_map> #include <utility> #include <vector> #include "catalog/catalog_defs.h" #include "common/macros.h" #include "common/managed_pointer.h" #include "optimizer/statistics/column_stats.h" namespace noisepage::optimizer { /** * Represents the statistics of a given table. Stores relevant oids and * other important information, as well as a list of all the ColumnStats objects for * the columns in the table. Can manipulate its ColumnStats objects (adding/deleting). */ class TableStats { public: /** * Constructor * @param database_id - database oid of table * @param table_id - table oid of table * @param col_stats_list - initial list of ColumnStats objects to be inserted in the TableStats object */ TableStats(catalog::db_oid_t database_id, catalog::table_oid_t table_id, std::vector<std::unique_ptr<ColumnStatsBase>> *col_stats_list) : database_id_(database_id), table_id_(table_id) { // Every column should have the same number of rows num_rows_ = col_stats_list->empty() ? 0 : (*col_stats_list)[0]->GetNumRows(); for (auto &col_stat : *col_stats_list) { // taking each ColumnStats object and storing it in a map NOISEPAGE_ASSERT(col_stat->GetNumRows() == num_rows_, "Every column should have the same number of rows"); column_stats_.emplace(col_stat->GetColumnID(), std::move(col_stat)); } } /** * Default constructor for deserialization */ TableStats() = default; /** * Adds a ColumnStats object to the map of ColumnStats objects * @param col_stats - ColumnStats object to add * @return whether the ColumnStats object is successfully added */ bool AddColumnStats(std::unique_ptr<ColumnStatsBase> col_stats); /** * Gets the number of columns in the table * @return the number of columns */ size_t GetColumnCount() const { return column_stats_.size(); } /** * Checks to see if there's a ColumnStats object for the given column oid * @param column_id - the oid of the column * @return whether the ColumnStats object exists */ bool HasColumnStats(catalog::col_oid_t column_id) const; /** * Retrieves the ColumnStats object for the given column oid in the ColumnStats map * @param column_id - the oid of the column * @return the pointer to the ColumnStats object */ common::ManagedPointer<ColumnStatsBase> GetColumnStats(catalog::col_oid_t column_id) const; /** * Retrieves all ColumnStats objects in the ColumnStats map * @return pointers to all ColumnStats objects */ std::vector<common::ManagedPointer<ColumnStatsBase>> GetColumnStats() const; /** * Removes the ColumnStats object for the given column oid in the ColumnStats map * @param column_id - the oid of the column */ void RemoveColumnStats(catalog::col_oid_t column_id); /** * Gets the number of rows in the table * @return the number of rows */ size_t GetNumRows() const { return num_rows_; } /** * Updates the number of rows in the table * @param num_rows new number of rows */ void SetNumRows(size_t num_rows) { num_rows_ = num_rows; } /** * Checks if any of the columns statistics within this table statistics is stale * @return true if table statistics contains stale column, false otherwise */ bool HasStaleValues() const { return std::any_of(column_stats_.begin(), column_stats_.end(), [](const auto &it) { return it.second->IsStale(); }); } /** * Serializes a table stats object * @return table stats object serialized to json */ nlohmann::json ToJson() const; /** * Deserializes a table stats object * @param j - serialized table stats object */ void FromJson(const nlohmann::json &j); private: /** * database oid */ catalog::db_oid_t database_id_; /** * table oid */ catalog::table_oid_t table_id_; /** * number of rows in table */ size_t num_rows_; /** * stores the ColumnStats objects for the columns in the table */ std::unordered_map<catalog::col_oid_t, std::unique_ptr<ColumnStatsBase>> column_stats_; }; DEFINE_JSON_HEADER_DECLARATIONS(TableStats); } // namespace noisepage::optimizer
1,406
743
# GPIO Zero: a library for controlling the Raspberry Pi's GPIO pins # # Copyright (c) 2021 <NAME> <<EMAIL>> # # SPDX-License-Identifier: BSD-3-Clause from __future__ import ( unicode_literals, absolute_import, print_function, division, ) str = type('') import io from collections import Counter from itertools import zip_longest def load_segment_font(filename_or_obj, width, height, pins): """ A generic function for parsing segment font definition files. If you're working with "standard" `7-segment`_ or `14-segment`_ displays you *don't* want this function; see :func:`load_font_7seg` or :func:`load_font_14seg` instead. However, if you are working with another style of segmented display and wish to construct a parser for a custom format, this is the function you want. The *filename_or_obj* parameter is simply the file-like object or filename to load. This is typically passed in from the calling function. The *width* and *height* parameters give the width and height in characters of each character definition. For example, these are 3 and 3 for 7-segment displays. Finally, *pins* is a list of tuples that defines the position of each pin definition in the character array, and the character that marks that position "active". For example, for 7-segment displays this function is called as follows:: load_segment_font(filename_or_obj, width=3, height=3, pins=[ (1, '_'), (5, '|'), (8, '|'), (7, '_'), (6, '|'), (3, '|'), (4, '_')]) This dictates that each character will be defined by a 3x3 character grid which will be converted into a nine-character string like so: .. code-block:: text 012 345 ==> '012345678' 678 Position 0 is always assumed to be the character being defined. The *pins* list then specifies: the first pin is the character at position 1 which will be "on" when that character is "_". The second pin is the character at position 5 which will be "on" when that character is "|", and so on. .. _7-segment: https://en.wikipedia.org/wiki/Seven-segment_display .. _14-segment: https://en.wikipedia.org/wiki/Fourteen-segment_display """ assert 0 < len(pins) <= (width * height) - 1 if isinstance(filename_or_obj, bytes): filename_or_obj = filename_or_obj.decode('utf-8') opened = isinstance(filename_or_obj, str) if opened: filename_or_obj = io.open(filename_or_obj, 'r') try: lines = filename_or_obj.read() if isinstance(lines, bytes): lines = lines.decode('utf-8') lines = lines.splitlines() finally: if opened: filename_or_obj.close() # Strip out comments and blank lines, but remember the original line # numbers of each row for error reporting purposes rows = [ (index, line) for index, line in enumerate(lines, start=1) # Strip comments and blank (or whitespace) lines if line.strip() and not line.startswith('#') ] line_numbers = { row_index: line_index for row_index, (line_index, row) in enumerate(rows) } rows = [row for index, row in rows] if len(rows) % height: raise ValueError('number of definition lines is not divisible by ' '{height}'.format(height=height)) # Strip out blank columns then transpose back to rows, and make sure # everything is the right "shape" for n in range(0, len(rows), height): cols = [ col for col in zip_longest(*rows[n:n + height], fillvalue=' ') # Strip blank (or whitespace) columns if ''.join(col).strip() ] rows[n:n + height] = list(zip(*cols)) for row_index, row in enumerate(rows): if len(row) % width: raise ValueError( 'length of definitions starting on line {line} is not ' 'divisible by {width}'.format( line=line_numbers[row_index], width=width)) # Split rows up into character definitions. After this, chars will be a # list of strings each with width x height characters. The first character # in each string will be the character being defined chars = [ ''.join( char for row in rows[y::height] for char in row )[x::width] for y in range(height) for x in range(width) ] chars = [''.join(char) for char in zip(*chars)] # Strip out blank entries (a consequence of zip_longest above) and check # there're no repeat definitions chars = [char for char in chars if char.strip()] counts = Counter(char[0] for char in chars) for char, count in counts.most_common(): if count > 1: raise ValueError( 'multiple definitions for {char!r}'.format(char=char)) return { char[0]: tuple(int(char[pos] == on) for pos, on in pins) for char in chars } def load_font_7seg(filename_or_obj): """ Given a filename or a file-like object, parse it as an font definition for a `7-segment display`_, returning a :class:`dict` suitable for use with :class:`~gpiozero.LEDCharDisplay`. The file-format is a simple text-based format in which blank and #-prefixed lines are ignored. All other lines are assumed to be groups of character definitions which are cells of 3x3 characters laid out as follows: .. code-block:: text Ca fgb edc Where C is the character being defined, and a-g define the states of the LEDs for that position. a, d, and g are on if they are "_". b, c, e, and f are on if they are "|". Any other character in these positions is considered off. For example, you might define the following characters: .. code-block:: text . 0_ 1. 2_ 3_ 4. 5_ 6_ 7_ 8_ 9_ ... |.| ..| ._| ._| |_| |_. |_. ..| |_| |_| ... |_| ..| |_. ._| ..| ._| |_| ..| |_| ._| In the example above, empty locations are marked with "." but could mostly be left as spaces. However, the first item defines the space (" ") character and needs *some* non-space characters in its definition as the parser also strips empty columns (as typically occur between character definitions). This is also why the definition for "1" must include something to fill the middle column. .. _7-segment display: https://en.wikipedia.org/wiki/Seven-segment_display """ return load_segment_font(filename_or_obj, width=3, height=3, pins=[ (1, '_'), (5, '|'), (8, '|'), (7, '_'), (6, '|'), (3, '|'), (4, '_')]) def load_font_14seg(filename_or_obj): """ Given a filename or a file-like object, parse it as a font definition for a `14-segment display`_, returning a :class:`dict` suitable for use with :class:`~gpiozero.LEDCharDisplay`. The file-format is a simple text-based format in which blank and #-prefixed lines are ignored. All other lines are assumed to be groups of character definitions which are cells of 5x5 characters laid out as follows: .. code-block:: text X.a.. fijkb .g.h. elmnc ..d.. Where X is the character being defined, and a-n define the states of the LEDs for that position. a, d, g, and h are on if they are "-". b, c, e, f, j, and m are on if they are "|". i and n are on if they are "\\". Finally, k and l are on if they are "/". Any other character in these positions is considered off. For example, you might define the following characters: .. code-block:: text .... 0--- 1.. 2--- 3--- 4 5--- 6--- 7---. 8--- 9--- ..... | /| /| | | | | | | / | | | | ..... | / | | --- -- ---| --- |--- | --- ---| ..... |/ | | | | | | | | | | | | ..... --- --- --- --- --- --- In the example above, several locations have extraneous characters. For example, the "/" in the center of the "0" definition, or the "-" in the middle of the "8". These locations are ignored, but filled in nonetheless to make the shape more obvious. These extraneous locations could equally well be left as spaces. However, the first item defines the space (" ") character and needs *some* non-space characters in its definition as the parser also strips empty columns (as typically occur between character definitions) and verifies that definitions are 5 columns wide and 5 rows high. This also explains why place-holder characters (".") have been inserted at the top of the definition of the "1" character. Otherwise the parser will strip these empty columns and decide the definition is invalid (as the result is only 3 columns wide). .. _14-segment display: https://en.wikipedia.org/wiki/Fourteen-segment_display """ return load_segment_font(filename_or_obj, width=5, height=5, pins=[ (2, '-'), (9, '|'), (19, '|'), (22, '-'), (15, '|'), (5, '|'), (11, '-'), (13, '-'), (6, '\\'), (7, '|'), (8, '/'), (16, '/'), (17, '|'), (18, '\\')])
3,518
587
<filename>src/libs6/s6_svc_writectl.c /* ISC license. */ #include <skalibs/sysdeps.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <string.h> #include <skalibs/djbunix.h> #include <skalibs/unix-transactional.h> #include <s6/supervise.h> int s6_svc_writectl (char const *service, char const *subdir, char const *s, size_t len) { size_t svlen = strlen(service) ; size_t sublen = strlen(subdir) ; int r ; char fn[svlen + sublen + 10] ; memcpy(fn, service, svlen) ; fn[svlen] = '/' ; memcpy(fn + svlen + 1, subdir, sublen) ; memcpy(fn + svlen + 1 + sublen, "/control", 9) ; r = s6_svc_write(fn, s, len) ; if (r != -2) return r ; #ifdef SKALIBS_HASODIRECTORY /* Investigate what went wrong */ { int fd, fdsub ; fd = open(service, O_RDONLY | O_DIRECTORY) ; if (fd < 0) return -1 ; fdsub = open2_at(fd, subdir, O_RDONLY | O_DIRECTORY) ; fd_close(fd) ; if (fdsub < 0) return (errno == ENOENT) ? 0 : -2 ; fd_close(fdsub) ; return -2 ; } #else /* Too bad, get a better system */ return -2 ; #endif }
506
2,293
#include "SupportBarF32.h" #include "Error.h" void SupportBarF32::test_barycenter_f32() { arm_barycenter_f32(this->inp, this->coefsp, this->outp, this->nbVectors, this->vecDim); } void SupportBarF32::setUp(Testing::testID_t id,std::vector<Testing::param_t>& params,Client::PatternMgr *mgr) { std::vector<Testing::param_t>::iterator it = params.begin(); this->nbVectors = *it++; this->vecDim = *it; switch(id) { case TEST_BARYCENTER_F32_1: input.reload(SupportBarF32::SAMPLES_F32_ID,mgr,this->nbVectors*this->vecDim); coefs.reload(SupportBarF32::COEFS_F32_ID,mgr,this->nbVectors); output.create(this->vecDim,SupportBarF32::OUT_SAMPLES_F32_ID,mgr); this->inp = input.ptr(); this->coefsp = coefs.ptr(); this->outp = output.ptr(); break; } } void SupportBarF32::tearDown(Testing::testID_t id,Client::PatternMgr *mgr) { }
569
506
<reponame>tabulon-ext/imapfilter<gh_stars>100-1000 #include <stdio.h> #include <unistd.h> #include <string.h> #include <strings.h> #include <errno.h> #include <netinet/in.h> #include <netdb.h> #include <sys/socket.h> #include <sys/types.h> #include <sys/time.h> #include <sys/select.h> #include <openssl/ssl.h> #include <openssl/err.h> #include <openssl/x509v3.h> #include "imapfilter.h" #include "session.h" #if OPENSSL_VERSION_NUMBER >= 0x1010000fL SSL_CTX *sslctx = NULL; #else SSL_CTX *ssl23ctx = NULL; #ifndef OPENSSL_NO_SSL3_METHOD SSL_CTX *ssl3ctx = NULL; #endif #ifndef OPENSSL_NO_TLS1_METHOD SSL_CTX *tls1ctx = NULL; #endif #ifndef OPENSSL_NO_TLS1_1_METHOD SSL_CTX *tls11ctx = NULL; #endif #ifndef OPENSSL_NO_TLS1_2_METHOD SSL_CTX *tls12ctx = NULL; #endif #endif /* * Connect to mail server. */ int open_connection(session *ssn) { struct addrinfo hints, *res, *ressave; int n, sockfd; memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; n = getaddrinfo(ssn->server, ssn->port, &hints, &res); if (n < 0) { error("gettaddrinfo; %s\n", gai_strerror(n)); return -1; } ressave = res; sockfd = -1; while (res) { sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol); if (sockfd >= 0) { if (connect(sockfd, res->ai_addr, res->ai_addrlen) == 0) break; sockfd = -1; } res = res->ai_next; } if (ressave) freeaddrinfo(ressave); if (sockfd == -1) { error("error while initiating connection to %s at port %s\n", ssn->server, ssn->port); return -1; } ssn->socket = sockfd; if (ssn->sslproto) { if (open_secure_connection(ssn) == -1) { close_connection(ssn); return -1; } } return ssn->socket; } /* * Initialize SSL/TLS connection. */ int open_secure_connection(session *ssn) { int r, e; SSL_CTX *ctx = NULL; #if OPENSSL_VERSION_NUMBER >= 0x1010000fL if (sslctx) ctx = sslctx; #else if (ssl23ctx) ctx = ssl23ctx; if (ssn->sslproto) { #ifndef OPENSSL_NO_SSL3_METHOD if (ssl3ctx && !strcasecmp(ssn->sslproto, "ssl3")) ctx = ssl3ctx; #endif #ifndef OPENSSL_NO_TLS1_METHOD if (tls1ctx && !strcasecmp(ssn->sslproto, "tls1")) ctx = tls1ctx; #endif #ifndef OPENSSL_NO_TLS1_1_METHOD if (tls11ctx && !strcasecmp(ssn->sslproto, "tls1.1")) ctx = tls11ctx; #endif #ifndef OPENSSL_NO_TLS1_2_METHOD if (tls12ctx && !strcasecmp(ssn->sslproto, "tls1.2")) ctx = tls12ctx; #endif } #endif if (ctx == NULL) { error("initiating SSL connection to %s; protocol version " "not supported by current build", ssn->server); goto fail; } if (!(ssn->sslconn = SSL_new(ctx))) goto fail; if (get_option_boolean("hostnames")) { #if OPENSSL_VERSION_NUMBER >= 0x10100000L SSL_set_hostflags(ssn->sslconn, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS); if (!SSL_set1_host(ssn->sslconn, ssn->server)) { error("failed setting hostname validation to " "%s; %s\n ", ssn->server, ERR_error_string(ERR_get_error(), NULL)); goto fail; } r = SSL_set_tlsext_host_name(ssn->sslconn, ssn->server); if (r == 0) { error("failed setting the Server Name Indication (SNI)" " to %s; %s\n", ssn->server, ERR_error_string(ERR_get_error(), NULL)); goto fail; } SSL_set_verify(ssn->sslconn, SSL_VERIFY_PEER, NULL); #elif OPENSSL_VERSION_NUMBER >= 0x10002000L X509_VERIFY_PARAM *param = SSL_get0_param(ssn->sslconn); X509_VERIFY_PARAM_set_hostflags(param, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS); if (!X509_VERIFY_PARAM_set1_host(param, ssn->server, strlen(ssn->server))) { error("failed setting hostname validation to " "%s; %s\n ", ssn->server, ERR_error_string(ERR_get_error(), NULL)); goto fail; } SSL_set_verify(ssn->sslconn, SSL_VERIFY_PEER, NULL); #else #error "hostname validation supported in OpenSSL version 1.0.2 and later" #endif } SSL_set_fd(ssn->sslconn, ssn->socket); for (;;) { if ((r = SSL_connect(ssn->sslconn)) > 0) break; switch (SSL_get_error(ssn->sslconn, r)) { case SSL_ERROR_ZERO_RETURN: error("initiating SSL connection to %s; the " "connection has been closed cleanly\n", ssn->server); goto fail; case SSL_ERROR_NONE: case SSL_ERROR_WANT_CONNECT: case SSL_ERROR_WANT_ACCEPT: case SSL_ERROR_WANT_X509_LOOKUP: case SSL_ERROR_WANT_READ: case SSL_ERROR_WANT_WRITE: break; case SSL_ERROR_SYSCALL: e = ERR_get_error(); if (e == 0 && r == 0) error("initiating SSL connection to %s; EOF in " "violation of the protocol\n", ssn->server); else if (e == 0 && r == -1) error("initiating SSL connection to %s; %s\n", ssn->server, strerror(errno)); else error("initiating SSL connection to %s; %s\n", ssn->server, ERR_error_string(e, NULL)); goto fail; case SSL_ERROR_SSL: e = ERR_get_error(); if (!strcmp("certificate verify failed", ERR_reason_error_string(e))) fatal(ERROR_CERTIFICATE, "initiating SSL connection to %s; %s\n", ssn->server, ERR_error_string(e, NULL)); error("initiating SSL connection to %s; %s\n", ssn->server, ERR_error_string(e, NULL)); goto fail; default: break; } } if (get_option_boolean("certificates") && get_cert(ssn) == -1) goto fail; return 0; fail: ssn->sslconn = NULL; return -1; } /* * Disconnect from mail server. */ int close_connection(session *ssn) { int r; r = 0; close_secure_connection(ssn); if (ssn->socket != -1) { r = close(ssn->socket); ssn->socket = -1; if (r == -1) error("closing socket; %s\n", strerror(errno)); } return r; } /* * Shutdown SSL/TLS connection. */ int close_secure_connection(session *ssn) { if (ssn->sslconn) { SSL_shutdown(ssn->sslconn); SSL_free(ssn->sslconn); ssn->sslconn = NULL; } return 0; } /* * Read data from socket. */ ssize_t socket_read(session *ssn, char *buf, size_t len, long timeout, int timeoutfail, int *interrupt) { int s; ssize_t r; fd_set fds; struct timeval tv; struct timeval *tvp; r = 0; s = 1; tvp = NULL; memset(buf, 0, len + 1); if (timeout > 0) { tv.tv_sec = timeout; tv.tv_usec = 0; tvp = &tv; } FD_ZERO(&fds); FD_SET(ssn->socket, &fds); if (ssn->sslconn) { if (SSL_pending(ssn->sslconn) > 0) { r = socket_secure_read(ssn, buf, len); if (r <= 0) goto fail; } else { if (interrupt != NULL) catch_user_signals(); if ((s = select(ssn->socket + 1, &fds, NULL, NULL, tvp)) > 0) { if (interrupt != NULL) ignore_user_signals(); if (FD_ISSET(ssn->socket, &fds)) { r = socket_secure_read(ssn, buf, len); if (r <= 0) goto fail; } } } } else { if (interrupt != NULL) catch_user_signals(); if ((s = select(ssn->socket + 1, &fds, NULL, NULL, tvp)) > 0) { if (interrupt != NULL) ignore_user_signals(); if (FD_ISSET(ssn->socket, &fds)) { r = read(ssn->socket, buf, len); if (r == -1) { error("reading data; %s\n", strerror(errno)); goto fail; } else if (r == 0) { goto fail; } } } } if (s == -1) { if (interrupt != NULL && errno == EINTR) { *interrupt = 1; return -1; } error("waiting to read from socket; %s\n", strerror(errno)); goto fail; } else if (s == 0 && timeoutfail) { error("timeout period expired while waiting to read data\n"); goto fail; } return r; fail: close_connection(ssn); return -1; } /* * Read data from a TLS/SSL connection. */ ssize_t socket_secure_read(session *ssn, char *buf, size_t len) { int r, e; for (;;) { if ((r = (ssize_t) SSL_read(ssn->sslconn, buf, len)) > 0) break; switch (SSL_get_error(ssn->sslconn, r)) { case SSL_ERROR_ZERO_RETURN: error("reading data through SSL; the connection has " "been closed cleanly\n"); goto fail; case SSL_ERROR_NONE: case SSL_ERROR_WANT_READ: case SSL_ERROR_WANT_WRITE: case SSL_ERROR_WANT_CONNECT: case SSL_ERROR_WANT_ACCEPT: case SSL_ERROR_WANT_X509_LOOKUP: break; case SSL_ERROR_SYSCALL: e = ERR_get_error(); if (e == 0 && r == 0) error("reading data through SSL; EOF in " "violation of the protocol\n"); else if (e == 0 && r == -1) error("reading data through SSL; %s\n", strerror(errno)); else error("reading data through SSL; %s\n", ERR_error_string(e, NULL)); goto fail; case SSL_ERROR_SSL: error("reading data through SSL; %s\n", ERR_error_string(ERR_get_error(), NULL)); goto fail; default: break; } } return r; fail: SSL_set_shutdown(ssn->sslconn, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN); return -1; } /* * Write data to socket. */ ssize_t socket_write(session *ssn, const char *buf, size_t len) { int s; ssize_t r, t; fd_set fds; r = t = 0; s = 1; FD_ZERO(&fds); FD_SET(ssn->socket, &fds); while (len) { if ((s = select(ssn->socket + 1, NULL, &fds, NULL, NULL) > 0 && FD_ISSET(ssn->socket, &fds))) { if (ssn->sslconn) { r = socket_secure_write(ssn, buf, len); if (r <= 0) goto fail; } else { r = write(ssn->socket, buf, len); if (r == -1) { error("writing data; %s\n", strerror(errno)); goto fail; } else if (r == 0) { goto fail; } } if (r > 0) { len -= r; buf += r; t += r; } } } if (s == -1) { error("waiting to write to socket; %s\n", strerror(errno)); goto fail; } else if (s == 0) { error("timeout period expired while waiting to write data\n"); goto fail; } return t; fail: close_connection(ssn); return -1; } /* * Write data to a TLS/SSL connection. */ ssize_t socket_secure_write(session *ssn, const char *buf, size_t len) { int r, e; for (;;) { if ((r = (ssize_t) SSL_write(ssn->sslconn, buf, len)) > 0) break; switch (SSL_get_error(ssn->sslconn, r)) { case SSL_ERROR_ZERO_RETURN: error("writing data through SSL; the connection has " "been closed cleanly\n"); goto fail; case SSL_ERROR_NONE: case SSL_ERROR_WANT_READ: case SSL_ERROR_WANT_WRITE: case SSL_ERROR_WANT_CONNECT: case SSL_ERROR_WANT_ACCEPT: case SSL_ERROR_WANT_X509_LOOKUP: break; case SSL_ERROR_SYSCALL: e = ERR_get_error(); if (e == 0 && r == 0) error("writing data through SSL; EOF in " "violation of the protocol\n"); else if (e == 0 && r == -1) error("writing data through SSL; %s\n", strerror(errno)); else error("writing data through SSL; %s\n", ERR_error_string(e, NULL)); goto fail; case SSL_ERROR_SSL: error("writing data through SSL; %s\n", ERR_error_string(ERR_get_error(), NULL)); goto fail; default: break; } } return r; fail: SSL_set_shutdown(ssn->sslconn, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN); return -1; }
5,052
2,633
def application(scope, receive=None, send=None): assert scope['type'] == 'http' if receive == None and send == None: return app_http else: return app_http(receive, send) async def app_http(receive, send): await send( { 'type': 'http.response.start', 'status': 200, 'headers': [(b'content-length', b'0'),], } )
186
566
<gh_stars>100-1000 { "extends": [ "config:base" ], "commitBody": "Signed-off-by: {{{gitAuthor}}}", "automerge": true, "labels": [ "dependencies" ], "major": { "automerge": false } }
98
11,356
<filename>deps/src/boost_1_65_1/libs/math/test/test_legacy_nonfinite.cpp // Copyright (c) 2006 <NAME> // Copyright (c) 2011 <NAME> // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt // or copy at http://www.boost.org/LICENSE_1_0.txt) /*! \file \brief Legacy (non-C99) tests of the nonfinite num facets. \detail legacy_test outputs using nonfinite_num_put facet with legacy flag, and reads back in using nonfinite_num_ facet, and checks loopback OK. Also checks that output of infinity, -infinity and NaN are as expected, including the 'legacy' "1.#IND", "1.#QNAN", "1.#SNAN" representations (was used by MSVC but now all represented on output by "1.#QNAN") and qnan snan nanq nans (used by other systems) excluding C99 specification "nan -nan nan -nan" and "inf -inf". */ #ifdef _MSC_VER # pragma warning(disable : 4702) #endif #include <iomanip> #include <locale> #include <sstream> #define BOOST_TEST_MAIN #include <boost/test/auto_unit_test.hpp> //#include "almost_equal.hpp" //#include "S_.hpp" #include <boost/math/special_functions/nonfinite_num_facets.hpp> namespace { // The anonymous namespace resolves ambiguities on platforms // with fpclassify etc functions declared at global scope. using namespace boost::math; using boost::math::signbit; using boost::math::changesign; using boost::math::isnan; //------------------------------------------------------------------------------ void legacy_test_inf(); void legacy_test_nan(); BOOST_AUTO_TEST_CASE(legacy_test) { legacy_test_inf(); legacy_test_nan(); } //------------------------------------------------------------------------------ template<class CharType, class ValType> void legacy_test_inf_impl(); void legacy_test_inf() { legacy_test_inf_impl<char, float>(); legacy_test_inf_impl<char, double>(); legacy_test_inf_impl<char, long double>(); legacy_test_inf_impl<wchar_t, float>(); legacy_test_inf_impl<wchar_t, double>(); legacy_test_inf_impl<wchar_t, long double>(); } template<class CharType, class ValType> void legacy_test_inf_impl() { std::locale old_locale; std::locale new_locale(old_locale, new nonfinite_num_get<CharType>(legacy)); std::basic_stringstream<CharType> ss; ss.imbue(new_locale); ValType a1 = std::numeric_limits<ValType>::infinity(); ValType a2 = -std::numeric_limits<ValType>::infinity(); ss << a1 << ' ' << a2; ss << " 1.#INF"; ValType b1, b2, b3; ss >> b1 >> b2 >> b3; BOOST_CHECK(b1 == a1); BOOST_CHECK(b2 == a2); BOOST_CHECK(b3 == std::numeric_limits<ValType>::infinity()); BOOST_CHECK(ss.rdstate() == std::ios_base::eofbit); } //------------------------------------------------------------------------------ template<class CharType, class ValType> void legacy_test_nan_impl(); void legacy_test_nan() { legacy_test_nan_impl<char, float>(); legacy_test_nan_impl<char, double>(); legacy_test_nan_impl<char, long double>(); legacy_test_nan_impl<wchar_t, float>(); legacy_test_nan_impl<wchar_t, double>(); legacy_test_nan_impl<wchar_t, long double>(); } template<class CharType, class ValType> void legacy_test_nan_impl() { std::locale old_locale; std::locale new_locale(old_locale, new nonfinite_num_get<CharType>(legacy)); std::basic_stringstream<CharType> ss; ss.imbue(new_locale); ValType a1 = std::numeric_limits<ValType>::quiet_NaN(); ValType a2 = -std::numeric_limits<ValType>::quiet_NaN(); ValType a3 = std::numeric_limits<ValType>::signaling_NaN(); ValType a4 = -std::numeric_limits<ValType>::signaling_NaN(); ss << a1 << ' ' << a2 << ' ' << a3 << ' ' << a4; ss << " qnan snan nanq nans 1.#IND 1.#QNAN 1.#SNAN"; ValType b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11; ss >> b1 >> b2 >> b3 >> b4 >> b5 >> b6 >> b7 >> b8 >> b9 >> b10 >> b11; // std::cout << b11 << std::endl; // Confirms that legacy // IND, SNAN and QNAN are considered the same, // and both output the legacy string "1.#QNAN". BOOST_CHECK((isnan)(b1)); BOOST_CHECK((isnan)(b2)); BOOST_CHECK((isnan)(b3)); BOOST_CHECK((isnan)(b4)); BOOST_CHECK((isnan)(b5)); BOOST_CHECK((isnan)(b6)); BOOST_CHECK((isnan)(b7)); BOOST_CHECK((isnan)(b8)); BOOST_CHECK((isnan)(b9)); BOOST_CHECK((isnan)(b10)); BOOST_CHECK((isnan)(b11)); // Johan V3 1.#SNAN failed on MSVC 10. // Change in nonfinite_num_facet.hpp <NAME> 11 Apr 11 makes work OK. /* // These tests fail on platforms, such as gcc, // that use the same representation of +nan and -nan. BOOST_CHECK(!(signbit)(b1)); BOOST_CHECK((signbit)(b2)); BOOST_CHECK(!(signbit)(b3)); BOOST_CHECK((signbit)(b4)); */ BOOST_CHECK(!(signbit)(b5)); BOOST_CHECK(!(signbit)(b6)); BOOST_CHECK(!(signbit)(b7)); BOOST_CHECK(!(signbit)(b8)); BOOST_CHECK(!(signbit)(b9)); BOOST_CHECK(!(signbit)(b10)); BOOST_CHECK(!(signbit)(b11)); // Johan V3 1.#SNAN failed MSVC 10. BOOST_CHECK(ss.rdstate() == std::ios_base::eofbit); // Fails if SNAN test fails. } //------------------------------------------------------------------------------ } // anonymous namespace /* Output: legacy_test.vcxproj -> J:\Cpp\fp_facet\fp_facet\Debug\legacy_test.exe Running 1 test case... 1.#QNAN 1.#QNAN 1.#QNAN 1.#QNAN 1.#QNAN 1.#QNAN *** No errors detected */
2,144
2,151
package org.skia.skqp; import android.content.Context; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; public class SkQPActivity extends AppCompatActivity implements Runnable { private SkQP testRunner = new SkQP(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_skqp); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); // Start the tests. run(); } // run implements the Runnable interface. public void run() { // Note: /sdcard/Android/data/<package-name> is a location an app is allowed to write to. // When running tests on Firebase it expects any result files to have a '/sdcard // prefix or it won't trigger tests from the CLI. Context context = getApplicationContext(); String outputDirPath = "/sdcard/Android/data/" + context.getPackageName(); testRunner.runTests(context, outputDirPath); finish(); } }
423
1,861
#!/usr/bin/env python3 # # Author: # <NAME> (@skelsec) # import io from pypykatz.commons.common import KatzSystemArchitecture, WindowsMinBuild, WindowsBuild from pypykatz.alsadecryptor.win_datatypes import BOOLEAN, HANDLE, USHORT, ULONG, LSA_UNICODE_STRING, LSAISO_DATA_BLOB, \ BYTE, PVOID, WORD, DWORD, POINTER, LUID, PSID, ANSI_STRING from pypykatz.alsadecryptor.package_commons import PackageTemplate class MsvTemplate(PackageTemplate): def __init__(self): super().__init__('Msv') self.signature = None self.first_entry_offset = None self.offset2 = None self.list_entry = None self.encrypted_credentials_list_struct = None self.encrypted_credential_struct = None self.decrypted_credential_struct = None @staticmethod def get_template(sysinfo): template = MsvTemplate() template.encrypted_credentials_list_struct = KIWI_MSV1_0_CREDENTIAL_LIST template.log_template('encrypted_credentials_list_struct', template.encrypted_credentials_list_struct) template.encrypted_credential_struct = KIWI_MSV1_0_PRIMARY_CREDENTIAL_ENC template.log_template('encrypted_credential_struct', template.encrypted_credential_struct) #identify credential session list structure to be used if sysinfo.buildnumber < WindowsMinBuild.WIN_2K3.value: template.list_entry = PKIWI_MSV1_0_LIST_51 elif sysinfo.buildnumber < WindowsMinBuild.WIN_VISTA.value: template.list_entry = PKIWI_MSV1_0_LIST_52 elif sysinfo.buildnumber < WindowsMinBuild.WIN_7.value: template.list_entry = PKIWI_MSV1_0_LIST_60 elif sysinfo.buildnumber < WindowsMinBuild.WIN_8.value: #do not do that :) if sysinfo.msv_dll_timestamp > 0x53480000: template.list_entry = PKIWI_MSV1_0_LIST_61_ANTI_MIMIKATZ else: template.list_entry = PKIWI_MSV1_0_LIST_61 elif sysinfo.buildnumber < WindowsMinBuild.WIN_BLUE.value: #template.list_entry = PKIWI_MSV1_0_LIST_62 if sysinfo.msv_dll_timestamp > 0x53480000: template.list_entry = PKIWI_MSV1_0_LIST_63 else: template.list_entry = PKIWI_MSV1_0_LIST_62 else: template.list_entry = PKIWI_MSV1_0_LIST_63 template.log_template('list_entry', template.list_entry) if sysinfo.buildnumber < WindowsBuild.WIN_10_1507.value: template.decrypted_credential_struct = MSV1_0_PRIMARY_CREDENTIAL_DEC elif sysinfo.buildnumber < WindowsBuild.WIN_10_1511.value: template.decrypted_credential_struct = MSV1_0_PRIMARY_CREDENTIAL_10_OLD_DEC elif sysinfo.buildnumber < WindowsBuild.WIN_10_1607.value: template.decrypted_credential_struct = MSV1_0_PRIMARY_CREDENTIAL_10_DEC else: template.decrypted_credential_struct = MSV1_0_PRIMARY_CREDENTIAL_10_1607_DEC template.log_template('decrypted_credential_struct', template.decrypted_credential_struct) if sysinfo.architecture == KatzSystemArchitecture.X64: if WindowsMinBuild.WIN_XP.value <= sysinfo.buildnumber < WindowsMinBuild.WIN_2K3.value: template.signature = b'\x4c\x8b\xdf\x49\xc1\xe3\x04\x48\x8b\xcb\x4c\x03\xd8' template.first_entry_offset = -4 template.offset2 = 0 elif WindowsMinBuild.WIN_2K3.value <= sysinfo.buildnumber < WindowsMinBuild.WIN_VISTA.value: template.signature = b'\x4c\x8b\xdf\x49\xc1\xe3\x04\x48\x8b\xcb\x4c\x03\xd8' template.first_entry_offset = -4 template.offset2 = -45 elif WindowsMinBuild.WIN_VISTA.value <= sysinfo.buildnumber < WindowsMinBuild.WIN_7.value: template.signature = b'\x33\xff\x45\x85\xc0\x41\x89\x75\x00\x4c\x8b\xe3\x0f\x84' template.first_entry_offset = 21#-4 template.offset2 = -4 elif WindowsMinBuild.WIN_7.value <= sysinfo.buildnumber < WindowsMinBuild.WIN_8.value: template.signature = b'\x33\xf6\x45\x89\x2f\x4c\x8b\xf3\x85\xff\x0f\x84' template.first_entry_offset = 19 template.offset2 = -4 elif WindowsMinBuild.WIN_8.value <= sysinfo.buildnumber < WindowsMinBuild.WIN_BLUE.value: template.signature = b'\x33\xff\x41\x89\x37\x4c\x8b\xf3\x45\x85\xc0\x74' template.first_entry_offset = 16 template.offset2 = -4 elif WindowsMinBuild.WIN_BLUE.value <= sysinfo.buildnumber < WindowsBuild.WIN_10_1507.value: template.signature = b'\x8b\xde\x48\x8d\x0c\x5b\x48\xc1\xe1\x05\x48\x8d\x05' template.first_entry_offset = 36 template.offset2 = -6 elif WindowsBuild.WIN_10_1507.value <= sysinfo.buildnumber < WindowsBuild.WIN_10_1703.value: #1503 and 1603 template.signature = b'\x33\xff\x41\x89\x37\x4c\x8b\xf3\x45\x85\xc0\x74' template.first_entry_offset = 16 template.offset2 = -4 elif WindowsBuild.WIN_10_1703.value <= sysinfo.buildnumber < WindowsBuild.WIN_10_1803.value: #1703 template.signature = b'\x33\xff\x45\x89\x37\x48\x8b\xf3\x45\x85\xc9\x74' template.first_entry_offset = 23 template.offset2 = -4 elif WindowsBuild.WIN_10_1803.value <= sysinfo.buildnumber < WindowsBuild.WIN_10_1903.value: #1803 template.signature = b'\x33\xff\x41\x89\x37\x4c\x8b\xf3\x45\x85\xc9\x74' template.first_entry_offset = 23 template.offset2 = -4 else: #1903 template.signature = b'\x33\xff\x41\x89\x37\x4c\x8b\xf3\x45\x85\xc0\x74' template.first_entry_offset = 23 template.offset2 = -4 elif sysinfo.architecture == KatzSystemArchitecture.X86: if WindowsMinBuild.WIN_XP.value <= sysinfo.buildnumber < WindowsMinBuild.WIN_2K3.value: template.signature = b'\xff\x50\x10\x85\xc0\x0f\x84' template.first_entry_offset = 24 template.offset2 = 0 elif WindowsMinBuild.WIN_2K3.value <= sysinfo.buildnumber < WindowsMinBuild.WIN_VISTA.value: template.signature = b'\x89\x71\x04\x89\x30\x8d\x04\xbd' template.first_entry_offset = -11 template.offset2 = -43 elif WindowsMinBuild.WIN_VISTA.value <= sysinfo.buildnumber < WindowsMinBuild.WIN_8.value: template.signature = b'\x89\x71\x04\x89\x30\x8d\x04\xbd' template.first_entry_offset = -11 template.offset2 = -42 elif WindowsMinBuild.WIN_8.value <= sysinfo.buildnumber < WindowsMinBuild.WIN_BLUE.value: template.signature = b'\x8b\x45\xf8\x8b\x55\x08\x8b\xde\x89\x02\x89\x5d\xf0\x85\xc9\x74' template.first_entry_offset = 18 template.offset2 = -4 elif WindowsMinBuild.WIN_BLUE.value <= sysinfo.buildnumber < WindowsBuild.WIN_10_1507.value: template.signature = b'\x8b\x4d\xe4\x8b\x45\xf4\x89\x75\xe8\x89\x01\x85\xff\x74' template.first_entry_offset = 16 template.offset2 = -4 elif sysinfo.buildnumber >= WindowsBuild.WIN_10_1507.value: template.signature = b'\x8b\x4d\xe8\x8b\x45\xf4\x89\x75\xec\x89\x01\x85\xff\x74' template.first_entry_offset = 16 template.offset2 = -4 else: raise Exception('Could not identify template! sysinfo.buildnumber: %d' % sysinfo.buildnumber) else: raise Exception('Unknown Architecture: %s , Build number %s' % (sysinfo.architecture, sysinfo.buildnumber)) return template class MSV1_0_PRIMARY_CREDENTIAL_STRANGE_DEC: #this structure doesnt have username nor domainname, but has credentials :S #starts with size = 0x60 def __init__(self): self.unk1 = None self.unk2 = None self.unk_tag = None self.unk_remaining_size = None self.LengthOfNtOwfPassword = None self.NtOwfPassword = None self.LengthOfShaOwfPassword = None self.ShaOwPassword = None self.LogonDomainName = None self.UserName = None self.LmOwfPassword = None self.isNtOwfPassword = None self.isLmOwfPassword = None self.isShaOwPassword = None @staticmethod async def load(reader): res = MSV1_0_PRIMARY_CREDENTIAL_STRANGE_DEC() res.unk1 = await USHORT.loadvalue(reader) res.unk2 = await USHORT.loadvalue(reader) res.unk_tag = await reader.read(4) #0xcccccc res.unk_remaining_size = await ULONG.loadvalue(reader) await reader.read(40) res.LengthOfNtOwfPassword = await ULONG.loadvalue(reader) res.NtOwfPassword = await reader.read(16) res.LengthOfShaOwfPassword = await ULONG.loadvalue(reader) res.ShaOwPassword = await reader.read(20) res.LogonDomainName = None res.UserName = None res.LmOwfPassword = None res.isNtOwfPassword = None res.isLmOwfPassword = None res.isShaOwPassword = None return res class MSV1_0_PRIMARY_CREDENTIAL_DEC: def __init__(self): self.LogonDomainName = None self.UserName = None self.NtOwfPassword = None self.LmOwfPassword = None self.ShaOwPassword = None self.isNtOwfPassword = None self.isLmOwfPassword = None self.isShaOwPassword = None @staticmethod async def load(reader): res = MSV1_0_PRIMARY_CREDENTIAL_DEC() res.LogonDomainName = await LSA_UNICODE_STRING.load(reader) res.UserName = await LSA_UNICODE_STRING.load(reader) res.NtOwfPassword = await reader.read(16) res.LmOwfPassword = await reader.read(16) res.ShaOwPassword = await reader.read(20) res.isNtOwfPassword = await BOOLEAN.loadvalue(reader) res.isLmOwfPassword = await BOOLEAN.loadvalue(reader) res.isShaOwPassword = await BOOLEAN.loadvalue(reader) return res class MSV1_0_PRIMARY_CREDENTIAL_10_OLD_DEC: def __init__(self): self.LogonDomainName = None self.UserName = None self.isIso = None self.isNtOwfPassword = None self.isLmOwfPassword = None self.isShaOwPassword = None self.align0 = None self.align1 = None self.NtOwfPassword = None self.LmOwfPassword = None self.ShaOwPassword = None @staticmethod async def load(reader): res = MSV1_0_PRIMARY_CREDENTIAL_10_OLD_DEC() res.LogonDomainName = await LSA_UNICODE_STRING.load(reader) res.UserName = await LSA_UNICODE_STRING.load(reader) res.isIso = await BOOLEAN.loadvalue(reader) res.isNtOwfPassword = await BOOLEAN.loadvalue(reader) res.isLmOwfPassword = await BOOLEAN.loadvalue(reader) res.isShaOwPassword = await BOOLEAN.loadvalue(reader) res.align0 = await BYTE.loadvalue(reader) res.align1 = await BYTE.loadvalue(reader) res.NtOwfPassword = await reader.read(16) res.LmOwfPassword = await reader.read(16) res.ShaOwPassword = await reader.read(20) return res class MSV1_0_PRIMARY_CREDENTIAL_10_DEC: def __init__(self): self.LogonDomainName = None self.UserName = None self.isIso = None self.isNtOwfPassword = None self.isLmOwfPassword = None self.isShaOwPassword = None self.align0 = None self.align1 = None self.align2 = None self.align3 = None self.NtOwfPassword = None self.LmOwfPassword = None self.ShaOwPassword = None @staticmethod async def load(reader): res = MSV1_0_PRIMARY_CREDENTIAL_10_DEC() res.LogonDomainName = await LSA_UNICODE_STRING.load(reader) res.UserName = await LSA_UNICODE_STRING.load(reader) res.isIso = await BOOLEAN.loadvalue(reader) res.isNtOwfPassword = await BOOLEAN.loadvalue(reader) res.isLmOwfPassword = await BOOLEAN.loadvalue(reader) res.isShaOwPassword = await BOOLEAN.loadvalue(reader) res.align0 = await BYTE.loadvalue(reader) res.align1 = await BYTE.loadvalue(reader) res.align2 = await BYTE.loadvalue(reader) res.align3 = await BYTE.loadvalue(reader) res.NtOwfPassword = await reader.read(16) res.LmOwfPassword = await reader.read(16) res.ShaOwPassword = await reader.read(20) return res class MSV1_0_PRIMARY_CREDENTIAL_10_1607_DEC: def __init__(self): self.LogonDomainName = None self.UserName = None self.pNtlmCredIsoInProc = None self.isIso = None self.isNtOwfPassword = None self.isLmOwfPassword = None self.isShaOwPassword = None self.isDPAPIProtected = None self.align0 = None self.align1 = None self.align2 = None self.unkD = None # stuff to be done! #pragma pack(push, 2) self.isoSize = None self.DPAPIProtected = None self.align3 = None # stuff to be done! #pragma pack(pop) self.NtOwfPassword = None self.LmOwfPassword = None self.ShaOwPassword = None @staticmethod async def load(reader): res = MSV1_0_PRIMARY_CREDENTIAL_10_1607_DEC() res.LogonDomainName = await LSA_UNICODE_STRING.load(reader) res.UserName = await LSA_UNICODE_STRING.load(reader) res.pNtlmCredIsoInProc = await PVOID.loadvalue(reader) res.isIso = await BOOLEAN.loadvalue(reader) res.isNtOwfPassword = await BOOLEAN.loadvalue(reader) res.isLmOwfPassword = await BOOLEAN.loadvalue(reader) res.isShaOwPassword = await BOOLEAN.loadvalue(reader) res.isDPAPIProtected = await BOOLEAN.loadvalue(reader) res.align0 = await BYTE.loadvalue(reader) res.align1 = await BYTE.loadvalue(reader) res.align2 = await BYTE.loadvalue(reader) res.unkD = await DWORD.loadvalue(reader) # // 1/2 # stuff to be done! #pragma pack(push, 2) res.isoSize = await WORD.loadvalue(reader) #// 0000 res.DPAPIProtected = await reader.read(16) res.align3 = await DWORD.loadvalue(reader) #// 00000000 # stuff to be done! #pragma pack(pop) res.NtOwfPassword = await reader.read(16) res.LmOwfPassword = await reader.read(16) res.ShaOwPassword = await reader.read(20) return res class KIWI_MSV1_0_PRIMARY_CREDENTIAL_ENC: def __init__(self): self.Flink = None self.Primary = None self.encrypted_credentials = None @staticmethod async def load(reader): res = KIWI_MSV1_0_PRIMARY_CREDENTIAL_ENC() res.Flink = await PKIWI_MSV1_0_PRIMARY_CREDENTIAL_ENC.load(reader) res.Primary = await ANSI_STRING.load(reader) await reader.align() res.encrypted_credentials = await LSA_UNICODE_STRING.load(reader) return res class PKIWI_MSV1_0_PRIMARY_CREDENTIAL_ENC(POINTER): def __init__(self): super().__init__() @staticmethod async def load(reader): p = PKIWI_MSV1_0_PRIMARY_CREDENTIAL_ENC() p.location = reader.tell() p.value = await reader.read_uint() p.finaltype = KIWI_MSV1_0_PRIMARY_CREDENTIAL_ENC return p #class PKIWI_MSV1_0_CREDENTIAL_LIST(POINTER): # def __init__(self, reader): # super().__init__(reader, PKIWI_MSV1_0_CREDENTIAL_LIST) class KIWI_MSV1_0_CREDENTIAL_LIST: def __init__(self): self.Flink = None self.AuthenticationPackageId = None self.PrimaryCredentials_ptr = None @staticmethod async def load(reader): res = KIWI_MSV1_0_CREDENTIAL_LIST() res.Flink = await PKIWI_MSV1_0_CREDENTIAL_LIST.load(reader) res.AuthenticationPackageId = await DWORD.loadvalue(reader) await reader.align() res.PrimaryCredentials_ptr = await PKIWI_MSV1_0_PRIMARY_CREDENTIAL_ENC.load(reader) return res class PKIWI_MSV1_0_CREDENTIAL_LIST(POINTER): def __init__(self): super().__init__() @staticmethod async def load(reader): p = PKIWI_MSV1_0_CREDENTIAL_LIST() p.location = reader.tell() p.value = await reader.read_uint() p.finaltype = KIWI_MSV1_0_CREDENTIAL_LIST return p class PKIWI_MSV1_0_LIST_51(POINTER): def __init__(self): super().__init__() @staticmethod async def load(reader): p = PKIWI_MSV1_0_LIST_51() p.location = reader.tell() p.value = await reader.read_uint() p.finaltype = KIWI_MSV1_0_LIST_51 return p class KIWI_MSV1_0_LIST_51: def __init__(self): self.Flink = None self.Blink = None self.LocallyUniqueIdentifier = None self.UserName = None self.Domaine = None self.unk0 = None self.unk1 = None self.pSid = None self.LogonType = None self.Session = None self.LogonTime = None self.LogonServer = None self.Credentials_list_ptr = None self.unk19 = None self.unk20 = None self.unk21 = None self.unk22 = None self.unk23 = None self.CredentialManager = None @staticmethod async def load(reader): res = KIWI_MSV1_0_LIST_51() res.Flink = await PKIWI_MSV1_0_LIST_51.load(reader) res.Blink = await PKIWI_MSV1_0_LIST_51.load(reader) res.LocallyUniqueIdentifier = await LUID.loadvalue(reader) res.UserName = await LSA_UNICODE_STRING.load(reader) res.Domaine = await LSA_UNICODE_STRING.load(reader) res.unk0 = await PVOID.loadvalue(reader) res.unk1 = await PVOID.loadvalue(reader) res.pSid = await PSID.load(reader) res.LogonType = await ULONG.loadvalue(reader) res.Session = await ULONG.loadvalue(reader) await reader.align(8) t = t = await reader.read(8) res.LogonTime = int.from_bytes(t, byteorder = 'little', signed = False) #autoalign x86 await reader.align() res.LogonServer = await LSA_UNICODE_STRING.load(reader) res.Credentials_list_ptr = await PKIWI_MSV1_0_CREDENTIAL_LIST.load(reader) res.unk19 = await ULONG.loadvalue(reader) await reader.align() res.unk20 = await PVOID.loadvalue(reader) res.unk21 = await PVOID.loadvalue(reader) res.unk22 = await PVOID.loadvalue(reader) res.unk23 = await ULONG.loadvalue(reader) await reader.align() res.CredentialManager = await PVOID.load(reader) return res class PKIWI_MSV1_0_LIST_52(POINTER): def __init__(self): super().__init__() @staticmethod async def load(reader): p = PKIWI_MSV1_0_LIST_52() p.location = reader.tell() p.value = await reader.read_uint() p.finaltype = KIWI_MSV1_0_LIST_52 return p class KIWI_MSV1_0_LIST_52: def __init__(self): self.Flink = None self.Blink = None self.LocallyUniqueIdentifier = None self.UserName = None self.Domaine = None self.unk0 = None self.unk1 = None self.pSid = None self.LogonType = None self.Session = None self.LogonTime = None self.LogonServer = None self.Credentials_list_ptr = None self.unk19 = None self.unk20 = None self.unk21 = None self.unk22 = None self.CredentialManager = None @staticmethod async def load(reader): res = KIWI_MSV1_0_LIST_52() res.Flink = await PKIWI_MSV1_0_LIST_52.load(reader) res.Blink = await PKIWI_MSV1_0_LIST_52.load(reader) res.LocallyUniqueIdentifier = await LUID.loadvalue(reader) res.UserName = await LSA_UNICODE_STRING.load(reader) res.Domaine = await LSA_UNICODE_STRING.load(reader) res.unk0 = await PVOID.loadvalue(reader) res.unk1 = await PVOID.loadvalue(reader) res.pSid = await PSID.load(reader) res.LogonType = await ULONG.loadvalue(reader) res.Session = await ULONG.loadvalue(reader) await reader.align(8) t = await reader.read(8) res.LogonTime = int.from_bytes(t, byteorder = 'little', signed = False) #autoalign x86 res.LogonServer = await LSA_UNICODE_STRING.load(reader) res.Credentials_list_ptr = await PKIWI_MSV1_0_CREDENTIAL_LIST.load(reader) res.unk19 = await ULONG.loadvalue(reader) await reader.align() res.unk20 = await PVOID.loadvalue(reader) res.unk21 = await PVOID.loadvalue(reader) res.unk22 = await ULONG.loadvalue(reader) await reader.align() res.CredentialManager = await PVOID.load(reader) return res class PKIWI_MSV1_0_LIST_60(POINTER): def __init__(self): super().__init__() @staticmethod async def load(reader): p = PKIWI_MSV1_0_LIST_60() p.location = reader.tell() p.value = await reader.read_uint() p.finaltype = KIWI_MSV1_0_LIST_60 return p class KIWI_MSV1_0_LIST_60: def __init__(self): self.Flink = None self.Blink = None self.unk0 = None self.unk1 = None self.unk2 = None self.unk3 = None self.unk4 = None self.unk5 = None self.hSemaphore6 = None self.unk7 = None self.hSemaphore8 = None self.unk9 = None self.unk10 = None self.unk11 = None self.unk12 = None self.unk13 = None self.LocallyUniqueIdentifier = None self.SecondaryLocallyUniqueIdentifier = None self.UserName = None self.Domaine = None self.unk14 = None self.unk15 = None self.pSid = None self.LogonType = None self.Session = None self.LogonTime = None self.LogonServer = None self.Credentials_list_ptr = None self.unk19 = None self.unk20 = None self.unk21 = None self.unk22 = None self.unk23 = None self.CredentialManager = None @staticmethod async def load(reader): res = KIWI_MSV1_0_LIST_60() res.Flink = await PKIWI_MSV1_0_LIST_60.load(reader) res.Blink = await PKIWI_MSV1_0_LIST_60.load(reader) await reader.align() res.unk0 = await PVOID.loadvalue(reader) res.unk1 = await ULONG.loadvalue(reader) await reader.align() res.unk2 = await PVOID.loadvalue(reader) res.unk3 = await ULONG.loadvalue(reader) res.unk4 = await ULONG.loadvalue(reader) res.unk5 = await ULONG.loadvalue(reader) await reader.align() res.hSemaphore6 = await HANDLE.loadvalue(reader) await reader.align() res.unk7 = await PVOID.loadvalue(reader) await reader.align() res.hSemaphore8 = await HANDLE.loadvalue(reader) await reader.align() res.unk9 = await PVOID.loadvalue(reader) await reader.align() res.unk10 = await PVOID.loadvalue(reader) res.unk11 = await ULONG.loadvalue(reader) res.unk12 = await ULONG.loadvalue(reader) await reader.align() res.unk13 = await PVOID.loadvalue(reader) await reader.align() t = await reader.read(8) res.LocallyUniqueIdentifier = int.from_bytes(t, byteorder = 'little', signed = False) t = await reader.read(8) res.SecondaryLocallyUniqueIdentifier = int.from_bytes(t, byteorder = 'little', signed = False) await reader.align() res.UserName = await LSA_UNICODE_STRING.load(reader) res.Domaine = await LSA_UNICODE_STRING.load(reader) res.unk14 = await PVOID.loadvalue(reader) res.unk15 = await PVOID.loadvalue(reader) res.pSid = await PSID.load(reader) res.LogonType = await ULONG.loadvalue(reader) res.Session = await ULONG.loadvalue(reader) await reader.align(8) t = await reader.read(8) res.LogonTime = int.from_bytes(t, byteorder = 'little', signed = False) #autoalign x86 res.LogonServer = await LSA_UNICODE_STRING.load(reader) res.Credentials_list_ptr = await PKIWI_MSV1_0_CREDENTIAL_LIST.load(reader) res.unk19 = await ULONG.loadvalue(reader) await reader.align() res.unk20 = await PVOID.loadvalue(reader) res.unk21 = await PVOID.loadvalue(reader) res.unk22 = await PVOID.loadvalue(reader) res.unk23 = await ULONG.loadvalue(reader) await reader.align() res.CredentialManager = await PVOID.load(reader) return res class PKIWI_MSV1_0_LIST_61(POINTER): def __init__(self): super().__init__() @staticmethod async def load(reader): p = PKIWI_MSV1_0_LIST_61() p.location = reader.tell() p.value = await reader.read_uint() p.finaltype = KIWI_MSV1_0_LIST_61 return p class KIWI_MSV1_0_LIST_61: def __init__(self): self.Flink = None self.Blink = None self.unk0 = None self.unk1 = None self.unk2 = None self.unk3 = None self.unk4 = None self.unk5 = None self.hSemaphore6 = None self.unk7 = None self.hSemaphore8 = None self.unk9 = None self.unk10 = None self.unk11 = None self.unk12 = None self.unk13 = None self.LocallyUniqueIdentifier = None self.SecondaryLocallyUniqueIdentifier = None self.UserName = None self.Domaine = None self.unk14 = None self.unk15 = None self.pSid = None self.LogonType = None self.Session = None self.LogonTime = None self.LogonServer = None self.Credentials_list_ptr = None self.unk19 = None self.unk20 = None self.unk21 = None self.unk22 = None self.CredentialManager = None @staticmethod async def load(reader): res = KIWI_MSV1_0_LIST_61() res.Flink = await PKIWI_MSV1_0_LIST_61.load(reader) res.Blink = await PKIWI_MSV1_0_LIST_61.load(reader) res.unk0 = await PVOID.loadvalue(reader) res.unk1 = await ULONG.loadvalue(reader) await reader.align() res.unk2 = await PVOID.loadvalue(reader) res.unk3 = await ULONG.loadvalue(reader) res.unk4 = await ULONG.loadvalue(reader) res.unk5 = await ULONG.loadvalue(reader) await reader.align() res.hSemaphore6 = await HANDLE.loadvalue(reader) res.unk7 = await PVOID.loadvalue(reader) res.hSemaphore8 = await HANDLE.loadvalue(reader) res.unk9 = await PVOID.loadvalue(reader) res.unk10 = await PVOID.loadvalue(reader) res.unk11 = await ULONG.loadvalue(reader) res.unk12 = await ULONG.loadvalue(reader) res.unk13 = await PVOID.loadvalue(reader) res.LocallyUniqueIdentifier = await LUID.loadvalue(reader) res.SecondaryLocallyUniqueIdentifier = await LUID.loadvalue(reader) res.UserName = await LSA_UNICODE_STRING.load(reader) res.Domaine = await LSA_UNICODE_STRING.load(reader) res.unk14 = await PVOID.loadvalue(reader) res.unk15 = await PVOID.loadvalue(reader) res.pSid = await PSID.load(reader) res.LogonType = await ULONG.loadvalue(reader) res.Session = await ULONG.loadvalue(reader) await reader.align(8) t = await reader.read(8) res.LogonTime = int.from_bytes(t, byteorder = 'little', signed = False) #autoalign x86 res.LogonServer = await LSA_UNICODE_STRING.load(reader) res.Credentials_list_ptr = await PKIWI_MSV1_0_CREDENTIAL_LIST.load(reader) res.unk19 = await PVOID.loadvalue(reader) res.unk20 = await PVOID.loadvalue(reader) res.unk21 = await PVOID.loadvalue(reader) res.unk22 = await ULONG.loadvalue(reader) await reader.align() res.CredentialManager = await PVOID.load(reader) return res class PKIWI_MSV1_0_LIST_61_ANTI_MIMIKATZ(POINTER): def __init__(self): super().__init__() @staticmethod async def load(reader): p = PKIWI_MSV1_0_LIST_61_ANTI_MIMIKATZ() p.location = reader.tell() p.value = await reader.read_uint() p.finaltype = KIWI_MSV1_0_LIST_61_ANTI_MIMIKATZ return p class KIWI_MSV1_0_LIST_61_ANTI_MIMIKATZ: def __init__(self): self.Flink = None self.Blink = None self.unk0 = None self.unk1 = None self.unk2 = None self.unk3 = None self.unk4 = None self.unk5 = None self.hSemaphore6 = None self.unk7 = None self.hSemaphore8 = None self.unk9 = None self.unk10 = None self.unk11 = None self.unk12 = None self.unk13 = None self.LocallyUniqueIdentifier = None self.SecondaryLocallyUniqueIdentifier = None self.waza = None self.UserName = None self.Domaine = None self.unk14 = None self.unk15 = None self.pSid = None self.LogonType = None self.Session = None self.LogonTime = None self.LogonServer = None self.Credentials_list_ptr = None self.unk19 = None self.unk20 = None self.unk21 = None self.unk22 = None self.CredentialManager = None @staticmethod async def load(reader): res = KIWI_MSV1_0_LIST_61_ANTI_MIMIKATZ() res.Flink = await PKIWI_MSV1_0_LIST_61_ANTI_MIMIKATZ.load(reader) res.Blink = await PKIWI_MSV1_0_LIST_61_ANTI_MIMIKATZ.load(reader) res.unk0 = await PVOID.loadvalue(reader) res.unk1 = await ULONG.loadvalue(reader) await reader.align() res.unk2 = await PVOID.loadvalue(reader) res.unk3 = await ULONG.loadvalue(reader) res.unk4 = await ULONG.loadvalue(reader) res.unk5 = await ULONG.loadvalue(reader) await reader.align() res.hSemaphore6 = await HANDLE.loadvalue(reader) res.unk7 = await PVOID.loadvalue(reader) res.hSemaphore8 = await HANDLE.loadvalue(reader) res.unk9 = await PVOID.loadvalue(reader) res.unk10 = await PVOID.loadvalue(reader) res.unk11 = await ULONG.loadvalue(reader) res.unk12 = await ULONG.loadvalue(reader) res.unk13 = await PVOID.loadvalue(reader) res.LocallyUniqueIdentifier = await LUID.loadvalue(reader) res.SecondaryLocallyUniqueIdentifier = await LUID.loadvalue(reader) res.waza = await reader.read(12) await reader.align() res.UserName = await LSA_UNICODE_STRING.load(reader) res.Domaine = await LSA_UNICODE_STRING.load(reader) res.unk14 = await PVOID.loadvalue(reader) res.unk15 = await PVOID.loadvalue(reader) res.pSid = await PSID.load(reader) res.LogonType = await ULONG.loadvalue(reader) res.Session = await ULONG.loadvalue(reader) await reader.align(8) t = await reader.read(8) res.LogonTime = int.from_bytes(t, byteorder = 'little', signed = False) #autoalign x86 res.LogonServer = await LSA_UNICODE_STRING.load(reader) res.Credentials_list_ptr = await PKIWI_MSV1_0_CREDENTIAL_LIST.load(reader) res.unk19 = await PVOID.loadvalue(reader) res.unk20 = await PVOID.loadvalue(reader) res.unk21 = await PVOID.loadvalue(reader) res.unk22 = await ULONG.loadvalue(reader) await reader.align() res.CredentialManager = await PVOID.load(reader) return res class PKIWI_MSV1_0_LIST_62(POINTER): def __init__(self): super().__init__() @staticmethod async def load(reader): p = PKIWI_MSV1_0_LIST_62() p.location = reader.tell() p.value = await reader.read_uint() p.finaltype = KIWI_MSV1_0_LIST_62 return p class KIWI_MSV1_0_LIST_62: def __init__(self): self.Flink = None self.Blink = None self.unk0 = None self.unk1 = None self.unk2 = None self.unk3 = None self.unk4 = None self.unk5 = None self.hSemaphore6 = None self.unk7 = None self.hSemaphore8 = None self.unk9 = None self.unk10 = None self.unk11 = None self.unk12 = None self.unk13 = None self.LocallyUniqueIdentifier = None self.SecondaryLocallyUniqueIdentifier = None self.UserName = None self.Domaine = None self.unk14 = None self.unk15 = None self.Type = None self.pSid = None self.LogonType = None self.unk18 = None self.Session = None self.LogonTime = None self.LogonServer = None self.Credentials_list_ptr = None self.unk19 = None self.unk20 = None self.unk21 = None self.unk22 = None self.unk23 = None self.unk24 = None self.unk25 = None self.unk26 = None self.unk27 = None self.unk28 = None self.unk29 = None self.CredentialManager = None @staticmethod async def load(reader): res = KIWI_MSV1_0_LIST_62() res.Flink = await PKIWI_MSV1_0_LIST_62.load(reader) res.Blink = await PKIWI_MSV1_0_LIST_62.load(reader) res.unk0 = await PVOID.loadvalue(reader) res.unk1 = await ULONG.loadvalue(reader) await reader.align() res.unk2 = await PVOID.loadvalue(reader) res.unk3 = await ULONG.loadvalue(reader) res.unk4 = await ULONG.loadvalue(reader) res.unk5 = await ULONG.loadvalue(reader) await reader.align() res.hSemaphore6 = await HANDLE.loadvalue(reader) res.unk7 = await PVOID.loadvalue(reader) res.hSemaphore8 = await HANDLE.loadvalue(reader) res.unk9 = await PVOID.loadvalue(reader) res.unk10 = await PVOID.loadvalue(reader) res.unk11 = await ULONG.loadvalue(reader) res.unk12 = await ULONG.loadvalue(reader) res.unk13 = await PVOID.loadvalue(reader) res.LocallyUniqueIdentifier = await LUID.loadvalue(reader) res.SecondaryLocallyUniqueIdentifier = await LUID.loadvalue(reader) res.UserName = await LSA_UNICODE_STRING.load(reader) res.Domaine = await LSA_UNICODE_STRING.load(reader) res.unk14 = await PVOID.loadvalue(reader) res.unk15 = await PVOID.loadvalue(reader) res.Type = await LSA_UNICODE_STRING.load(reader) res.pSid = await PSID.load(reader) res.LogonType = await ULONG.loadvalue(reader) await reader.align() res.unk18 = await PVOID.loadvalue(reader) res.Session = await ULONG.loadvalue(reader) await reader.align() t = await reader.read(8) res.LogonTime = int.from_bytes(t, byteorder = 'little', signed = False) #autoalign x86 res.LogonServer = await LSA_UNICODE_STRING.load(reader) res.Credentials_list_ptr = await PKIWI_MSV1_0_CREDENTIAL_LIST.load(reader) res.unk19 = await PVOID.loadvalue(reader) res.unk20 = await PVOID.loadvalue(reader) res.unk21 = await PVOID.loadvalue(reader) res.unk22 = await ULONG.loadvalue(reader) res.unk23 = await ULONG.loadvalue(reader) res.unk24 = await ULONG.loadvalue(reader) res.unk25 = await ULONG.loadvalue(reader) res.unk26 = await ULONG.loadvalue(reader) await reader.align() res.unk27 = await PVOID.loadvalue(reader) res.unk28 = await PVOID.loadvalue(reader) res.unk29 = await PVOID.loadvalue(reader) res.CredentialManager = await PVOID.load(reader) return res class PKIWI_MSV1_0_LIST_63(POINTER): def __init__(self): super().__init__() @staticmethod async def load(reader): p = PKIWI_MSV1_0_LIST_63() p.location = reader.tell() p.value = await reader.read_uint() p.finaltype = KIWI_MSV1_0_LIST_63 return p class KIWI_MSV1_0_LIST_63: def __init__(self): self.Flink = None self.Blink = None self.unk0 = None self.unk1 = None self.unk2 = None self.unk3 = None self.unk4 = None self.unk5 = None self.hSemaphore6 = None self.unk7 = None self.hSemaphore8 = None self.unk9 = None self.unk10 = None self.unk11 = None self.unk12 = None self.unk13 = None self.LocallyUniqueIdentifier = None self.SecondaryLocallyUniqueIdentifier = None self.waza = None self.UserName = None self.Domaine = None self.unk14 = None self.unk15 = None self.Type = None self.pSid = None self.LogonType = None self.unk18 = None self.Session = None self.LogonTime = None self.LogonServer = None self.Credentials_list_ptr = None self.unk19 = None self.unk20 = None self.unk21 = None self.unk22 = None self.unk23 = None self.unk24 = None self.unk25 = None self.unk26 = None self.unk27 = None self.unk28 = None self.unk29 = None self.CredentialManager = None @staticmethod async def load(reader): res = KIWI_MSV1_0_LIST_63() res.Flink = await PKIWI_MSV1_0_LIST_63.load(reader) res.Blink = await PKIWI_MSV1_0_LIST_63.load(reader) res.unk0 = await PVOID.loadvalue(reader) res.unk1 = await ULONG.loadvalue(reader) await reader.align() res.unk2 = await PVOID.loadvalue(reader) res.unk3 = await ULONG.loadvalue(reader) res.unk4 = await ULONG.loadvalue(reader) res.unk5 = await ULONG.loadvalue(reader) await reader.align() res.hSemaphore6 = await HANDLE.loadvalue(reader) res.unk7 = await PVOID.loadvalue(reader) res.hSemaphore8 = await HANDLE.loadvalue(reader) res.unk9 = await PVOID.loadvalue(reader) res.unk10 = await PVOID.loadvalue(reader) res.unk11 = await ULONG.loadvalue(reader) res.unk12 = await ULONG.loadvalue(reader) res.unk13 = await PVOID.loadvalue(reader) await reader.align() res.LocallyUniqueIdentifier = await LUID.loadvalue(reader) res.SecondaryLocallyUniqueIdentifier = await LUID.loadvalue(reader) res.waza = await reader.read(12) await reader.align() res.UserName = await LSA_UNICODE_STRING.load(reader) res.Domaine = await LSA_UNICODE_STRING.load(reader) res.unk14 = await PVOID.loadvalue(reader) res.unk15 = await PVOID.loadvalue(reader) res.Type = await LSA_UNICODE_STRING.load(reader) res.pSid = await PSID.load(reader) res.LogonType = await ULONG.loadvalue(reader) await reader.align() res.unk18 = await PVOID.loadvalue(reader) res.Session = await ULONG.loadvalue(reader) await reader.align(8) t = await reader.read(8) res.LogonTime = int.from_bytes(t, byteorder = 'little', signed = False) #autoalign x86 res.LogonServer = await LSA_UNICODE_STRING.load(reader) res.Credentials_list_ptr = await PKIWI_MSV1_0_CREDENTIAL_LIST.load(reader) res.unk19 = await PVOID.loadvalue(reader) res.unk20 = await PVOID.loadvalue(reader) res.unk21 = await PVOID.loadvalue(reader) res.unk22 = await ULONG.loadvalue(reader) res.unk23 = await ULONG.loadvalue(reader) res.unk24 = await ULONG.loadvalue(reader) res.unk25 = await ULONG.loadvalue(reader) res.unk26 = await ULONG.loadvalue(reader) await reader.align() #input('CredentialManager\n' + hexdump(reader.peek(0x100))) res.unk27 = await PVOID.loadvalue(reader) res.unk28 = await PVOID.loadvalue(reader) res.unk29 = await PVOID.loadvalue(reader) res.CredentialManager = await PVOID.load(reader) return res
14,958
3,170
// // Copyright (c) 2014-2016 THUNDERBEAST GAMES LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /* #include "AtomicEditor.h" #include <Atomic/Core/CoreEvents.h> #include "AtomicEditor.h" #include "BuildSettings.h" namespace ToolCore { BuildSettings::BuildSettings(Context* context) : Object(context) { } BuildSettings::~BuildSettings() { } String BuildSettings::GetStringMember(rapidjson::Value::Member* jobject, const String& name) { rapidjson::Value::Member* member = jobject->value.FindMember(name.CString()); if (!member || !member->value.IsString()) return ""; return member->value.GetString(); } void BuildSettings::Load(rapidjson::Value::Member* jobject) { // ANDROID ------ rapidjson::Value::Member* jandroid = jobject->value.FindMember("android"); if (jandroid && jandroid->value.IsObject()) { android_.appName = GetStringMember(jandroid, "app_name"); android_.package = GetStringMember(jandroid, "package"); android_.targetSDKVersion = GetStringMember(jandroid, "target_sdk_version"); android_.minSDKVersion = GetStringMember(jandroid, "min_sdk_version"); android_.activityName = GetStringMember(jandroid, "activity_name"); android_.companyName = GetStringMember(jandroid, "company_name"); android_.productName = GetStringMember(jandroid, "product_name"); } // END ANDROID ------ // IOS ------ rapidjson::Value::Member* jios = jobject->value.FindMember("ios"); if (jios && jios->value.IsObject()) { ios_.appName = GetStringMember(jios, "app_name"); ios_.package = GetStringMember(jios, "package"); ios_.provisionFile = GetStringMember(jios, "provision_file"); ios_.companyName = GetStringMember(jios, "company_name"); ios_.productName = GetStringMember(jios, "product_name"); ios_.appidPrefix = GetStringMember(jios, "appid_prefix"); } // END IOS ------ // Mac ------ rapidjson::Value::Member* jmac = jobject->value.FindMember("mac"); if (jmac && jmac->value.IsObject()) { mac_.appName = GetStringMember(jmac, "app_name"); mac_.package = GetStringMember(jmac, "package"); mac_.companyName = GetStringMember(jmac, "company_name"); mac_.productName = GetStringMember(jmac, "product_name"); } // END Mac ------ // Windows ------ rapidjson::Value::Member* jwindows = jobject->value.FindMember("windows"); if (jwindows && jwindows->value.IsObject()) { windows_.appName = GetStringMember(jwindows, "app_name"); windows_.package = GetStringMember(jwindows, "package"); windows_.companyName = GetStringMember(jwindows, "company_name"); windows_.productName = GetStringMember(jwindows, "product_name"); } // END Windows ------ // WebGL ------ rapidjson::Value::Member* jwebgl = jobject->value.FindMember("webgl"); if (jwebgl && jwebgl->value.IsObject()) { webgl_.appName = GetStringMember(jwebgl, "app_name"); webgl_.package = GetStringMember(jwebgl, "package"); webgl_.companyName = GetStringMember(jwebgl, "company_name"); webgl_.productName = GetStringMember(jwebgl, "product_name"); } // END WebGL ------ } void BuildSettings::Save(rapidjson::PrettyWriter<rapidjson::FileStream>& writer) { writer.String("build_settings"); writer.StartObject(); writer.String("version"); writer.Int(1); // ANDROID ------ writer.String("android"); writer.StartObject(); writer.String("app_name"); writer.String(android_.appName.CString()); writer.String("package"); writer.String(android_.package.CString()); writer.String("target_sdk_version"); writer.String(android_.targetSDKVersion.CString()); writer.String("min_sdk_version"); writer.String(android_.minSDKVersion.CString()); writer.String("activity_name"); writer.String(android_.activityName.CString()); writer.String("company_name"); writer.String(android_.companyName.CString()); writer.String("product_name"); writer.String(android_.productName.CString()); writer.EndObject(); // END ANDROID ------ // IOS ------ writer.String("ios"); writer.StartObject(); writer.String("app_name"); writer.String(ios_.appName.CString()); writer.String("package"); writer.String(ios_.package.CString()); writer.String("provision_file"); writer.String(ios_.provisionFile.CString()); writer.String("company_name"); writer.String(ios_.companyName.CString()); writer.String("product_name"); writer.String(ios_.productName.CString()); writer.String("appid_prefix"); writer.String(ios_.appidPrefix.CString()); writer.EndObject(); // END IOS ------ // Mac ------ writer.String("mac"); writer.StartObject(); writer.String("app_name"); writer.String(mac_.appName.CString()); writer.String("package"); writer.String(mac_.package.CString()); writer.String("company_name"); writer.String(mac_.companyName.CString()); writer.String("product_name"); writer.String(mac_.productName.CString()); writer.EndObject(); // END Mac ------ // Windows ------ writer.String("windows"); writer.StartObject(); writer.String("app_name"); writer.String(windows_.appName.CString()); writer.String("package"); writer.String(windows_.package.CString()); writer.String("company_name"); writer.String(windows_.companyName.CString()); writer.String("product_name"); writer.String(windows_.productName.CString()); writer.EndObject(); // END Windows ------ // WebGL ------ writer.String("webgl"); writer.StartObject(); writer.String("app_name"); writer.String(webgl_.appName.CString()); writer.String("package"); writer.String(webgl_.package.CString()); writer.String("company_name"); writer.String(webgl_.companyName.CString()); writer.String("product_name"); writer.String(webgl_.productName.CString()); writer.EndObject(); // END WebGL ------ writer.EndObject(); } } */
2,501
416
package org.simpleflatmapper.jdbc.test; import org.junit.Test; import org.simpleflatmapper.jdbc.DynamicJdbcMapper; import org.simpleflatmapper.jdbc.JdbcColumnKey; import org.simpleflatmapper.jdbc.JdbcMapperFactory; import org.simpleflatmapper.jdbc.property.JdbcGetterFactoryProperty; import org.simpleflatmapper.map.property.GetterFactoryProperty; import org.simpleflatmapper.reflect.Getter; import org.simpleflatmapper.reflect.getter.GetterFactory; import org.simpleflatmapper.test.jdbc.DbHelper; import org.simpleflatmapper.util.ConstantPredicate; import org.simpleflatmapper.util.Predicate; import java.lang.reflect.Type; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import static org.junit.Assert.assertEquals; public class JdbcEnumTest { @Test public void mapCustomEmum() throws SQLException { Connection conn = DbHelper.getDbConnection(DbHelper.TargetDB.POSTGRESQL); if (conn == null) return; try { DynamicJdbcMapper<EventLog> mapper = JdbcMapperFactory .newInstance() .addColumnProperty(ConstantPredicate.truePredicate(), JdbcGetterFactoryProperty.forType(TypeEnum.class, new JdbcGetterFactoryProperty.ResultSetGetter<TypeEnum>() { @Override public TypeEnum get(ResultSet rs, int index) throws SQLException { return TypeEnum.of(rs.getInt(index)); } })) .newMapper(EventLog.class); Statement st = conn.createStatement(); try { ResultSet rs = st.executeQuery("select 1 as id, 8 as type"); rs.next(); EventLog eventLog = mapper.map(rs); assertEquals(1, eventLog.id); assertEquals(TypeEnum.DATA_NOT_FOUND, eventLog.type); } finally { st.close(); } } finally { conn.close(); } } public enum TypeEnum { INFO(0), INVALID_API_ARGUMENT(7), DATA_NOT_FOUND(8), ERROR(9); int typeCode; TypeEnum(int typeCode) { this.typeCode = typeCode; } public int getTypeCode() { return typeCode; } public static TypeEnum of(int i) { switch (i) { case 0: return INFO; case 7: return INVALID_API_ARGUMENT; case 8 : return DATA_NOT_FOUND; case 9 : return ERROR; default: throw new IllegalArgumentException(); } } } public static class EventLog { private long id; private TypeEnum type; public EventLog(TypeEnum type) { this.type = type; } public long getId() { return id; } public void setId(long id) { this.id = id; } public TypeEnum getType() { return type; } } }
1,634
7,407
/* =========================================================================== Copyright (C) 1999-2005 Id Software, Inc., 2016 Google Inc. This file is part of Quake III Arena source code. Quake III Arena source code is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Quake III Arena source code 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 Quake III Arena source code; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA =========================================================================== */ // /* ======================================================================= MAIN MENU ======================================================================= */ #include "ui_local.h" #define ID_SINGLEPLAYER 10 #define ID_MULTIPLAYER 11 #define ID_SETUP 12 #define ID_DEMOS 13 #define ID_CINEMATICS 14 #define ID_TEAMARENA 15 #define ID_MODS 16 #define ID_EXIT 17 #define MAIN_BANNER_MODEL "models/mapobjects/banner/banner5.md3" #define MAIN_MENU_VERTICAL_SPACING 34 typedef struct { menuframework_s menu; menutext_s singleplayer; menutext_s multiplayer; menutext_s setup; menutext_s demos; menutext_s cinematics; menutext_s teamArena; menutext_s mods; menutext_s exit; qhandle_t bannerModel; } mainmenu_t; static mainmenu_t s_main; typedef struct { menuframework_s menu; char errorMessage[4096]; } errorMessage_t; static errorMessage_t s_errorMessage; /* ================= MainMenu_ExitAction ================= */ static void MainMenu_ExitAction( qboolean result ) { if( !result ) { return; } UI_PopMenu(); UI_CreditMenu(); } /* ================= Main_MenuEvent ================= */ void Main_MenuEvent (void* ptr, int event) { if( event != QM_ACTIVATED ) { return; } switch( ((menucommon_s*)ptr)->id ) { case ID_SINGLEPLAYER: UI_SPLevelMenu(); break; case ID_MULTIPLAYER: UI_ArenaServersMenu(); break; case ID_SETUP: UI_SetupMenu(); break; case ID_DEMOS: UI_DemosMenu(); break; case ID_CINEMATICS: UI_CinematicsMenu(); break; case ID_MODS: UI_ModsMenu(); break; case ID_TEAMARENA: trap_Cvar_Set( "fs_game", BASETA); trap_Cmd_ExecuteText( EXEC_APPEND, "vid_restart;" ); break; case ID_EXIT: UI_ConfirmMenu( "EXIT GAME?", 0, MainMenu_ExitAction ); break; } } /* =============== MainMenu_Cache =============== */ void MainMenu_Cache( void ) { s_main.bannerModel = trap_R_RegisterModel( MAIN_BANNER_MODEL ); } sfxHandle_t ErrorMessage_Key(int key) { trap_Cvar_Set( "com_errorMessage", "" ); UI_MainMenu(); return (menu_null_sound); } /* =============== Main_MenuDraw TTimo: this function is common to the main menu and errorMessage menu =============== */ static void Main_MenuDraw( void ) { refdef_t refdef; refEntity_t ent; vec3_t origin; vec3_t angles; float adjust; float x, y, w, h; vec4_t color = {0.5, 0, 0, 1}; // setup the refdef memset( &refdef, 0, sizeof( refdef ) ); refdef.rdflags = RDF_NOWORLDMODEL; AxisClear( refdef.viewaxis ); x = 0; y = 0; w = 640; h = 120; UI_AdjustFrom640( &x, &y, &w, &h ); refdef.x = x; refdef.y = y; refdef.width = w; refdef.height = h; adjust = 0; // JDC: Kenneth asked me to stop this 1.0 * sin( (float)uis.realtime / 1000 ); refdef.fov_x = 60 + adjust; refdef.fov_y = 19.6875 + adjust; refdef.time = uis.realtime; origin[0] = 300; origin[1] = 0; origin[2] = -32; trap_R_ClearScene(); // add the model memset( &ent, 0, sizeof(ent) ); adjust = 5.0 * sin( (float)uis.realtime / 5000 ); VectorSet( angles, 0, 180 + adjust, 0 ); AnglesToAxis( angles, ent.axis ); ent.hModel = s_main.bannerModel; VectorCopy( origin, ent.origin ); VectorCopy( origin, ent.lightingOrigin ); ent.renderfx = RF_LIGHTING_ORIGIN | RF_NOSHADOW; VectorCopy( ent.origin, ent.oldorigin ); trap_R_AddRefEntityToScene( &ent ); trap_R_RenderScene( &refdef ); if (strlen(s_errorMessage.errorMessage)) { UI_DrawProportionalString_AutoWrapped( 320, 192, 600, 20, s_errorMessage.errorMessage, UI_CENTER|UI_SMALLFONT|UI_DROPSHADOW, menu_text_color ); } else { // standard menu drawing Menu_Draw( &s_main.menu ); } if (uis.demoversion) { UI_DrawProportionalString( 320, 372, "DEMO FOR MATURE AUDIENCES DEMO", UI_CENTER|UI_SMALLFONT, color ); UI_DrawString( 320, 400, "Quake III Arena(c) 1999-2000, Id Software, Inc. All Rights Reserved", UI_CENTER|UI_SMALLFONT, color ); } else { UI_DrawString( 320, 450, "Quake III Arena(c) 1999-2000, Id Software, Inc. All Rights Reserved", UI_CENTER|UI_SMALLFONT, color ); } } /* =============== UI_TeamArenaExists =============== */ static qboolean UI_TeamArenaExists( void ) { int numdirs; char dirlist[2048]; char *dirptr; char *descptr; int i; int dirlen; numdirs = trap_FS_GetFileList( "$modlist", "", dirlist, sizeof(dirlist) ); dirptr = dirlist; for( i = 0; i < numdirs; i++ ) { dirlen = strlen( dirptr ) + 1; descptr = dirptr + dirlen; if (Q_stricmp(dirptr, BASETA) == 0) { return qtrue; } dirptr += dirlen + strlen(descptr) + 1; } return qfalse; } /* =============== UI_MainMenu The main menu only comes up when not in a game, so make sure that the attract loop server is down and that local cinematics are killed =============== */ void UI_MainMenu( void ) { int y; qboolean teamArena = qfalse; int style = UI_CENTER | UI_DROPSHADOW; trap_Cvar_Set( "sv_killserver", "1" ); if( !uis.demoversion && !ui_cdkeychecked.integer ) { char key[17]; trap_GetCDKey( key, sizeof(key) ); if( trap_VerifyCDKey( key, NULL ) == qfalse ) { UI_CDKeyMenu(); return; } } memset( &s_main, 0 ,sizeof(mainmenu_t) ); memset( &s_errorMessage, 0 ,sizeof(errorMessage_t) ); // com_errorMessage would need that too MainMenu_Cache(); trap_Cvar_VariableStringBuffer( "com_errorMessage", s_errorMessage.errorMessage, sizeof(s_errorMessage.errorMessage) ); if (strlen(s_errorMessage.errorMessage)) { s_errorMessage.menu.draw = Main_MenuDraw; s_errorMessage.menu.key = ErrorMessage_Key; s_errorMessage.menu.fullscreen = qtrue; s_errorMessage.menu.wrapAround = qtrue; s_errorMessage.menu.showlogo = qtrue; trap_Key_SetCatcher( KEYCATCH_UI ); uis.menusp = 0; UI_PushMenu ( &s_errorMessage.menu ); return; } s_main.menu.draw = Main_MenuDraw; s_main.menu.fullscreen = qtrue; s_main.menu.wrapAround = qtrue; s_main.menu.showlogo = qtrue; y = 134; s_main.singleplayer.generic.type = MTYPE_PTEXT; s_main.singleplayer.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS; s_main.singleplayer.generic.x = 320; s_main.singleplayer.generic.y = y; s_main.singleplayer.generic.id = ID_SINGLEPLAYER; s_main.singleplayer.generic.callback = Main_MenuEvent; s_main.singleplayer.string = "SINGLE PLAYER"; s_main.singleplayer.color = color_blue; s_main.singleplayer.style = style; y += MAIN_MENU_VERTICAL_SPACING; s_main.multiplayer.generic.type = MTYPE_PTEXT; s_main.multiplayer.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS; s_main.multiplayer.generic.x = 320; s_main.multiplayer.generic.y = y; s_main.multiplayer.generic.id = ID_MULTIPLAYER; s_main.multiplayer.generic.callback = Main_MenuEvent; s_main.multiplayer.string = "MULTIPLAYER"; s_main.multiplayer.color = color_blue; s_main.multiplayer.style = style; y += MAIN_MENU_VERTICAL_SPACING; s_main.setup.generic.type = MTYPE_PTEXT; s_main.setup.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS; s_main.setup.generic.x = 320; s_main.setup.generic.y = y; s_main.setup.generic.id = ID_SETUP; s_main.setup.generic.callback = Main_MenuEvent; s_main.setup.string = "SETUP"; s_main.setup.color = color_blue; s_main.setup.style = style; y += MAIN_MENU_VERTICAL_SPACING; s_main.demos.generic.type = MTYPE_PTEXT; s_main.demos.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS; s_main.demos.generic.x = 320; s_main.demos.generic.y = y; s_main.demos.generic.id = ID_DEMOS; s_main.demos.generic.callback = Main_MenuEvent; s_main.demos.string = "DEMOS"; s_main.demos.color = color_blue; s_main.demos.style = style; y += MAIN_MENU_VERTICAL_SPACING; s_main.cinematics.generic.type = MTYPE_PTEXT; s_main.cinematics.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS; s_main.cinematics.generic.x = 320; s_main.cinematics.generic.y = y; s_main.cinematics.generic.id = ID_CINEMATICS; s_main.cinematics.generic.callback = Main_MenuEvent; s_main.cinematics.string = "CINEMATICS"; s_main.cinematics.color = color_blue; s_main.cinematics.style = style; if ( !uis.demoversion && UI_TeamArenaExists() ) { teamArena = qtrue; y += MAIN_MENU_VERTICAL_SPACING; s_main.teamArena.generic.type = MTYPE_PTEXT; s_main.teamArena.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS; s_main.teamArena.generic.x = 320; s_main.teamArena.generic.y = y; s_main.teamArena.generic.id = ID_TEAMARENA; s_main.teamArena.generic.callback = Main_MenuEvent; s_main.teamArena.string = "TEAM ARENA"; s_main.teamArena.color = color_blue; s_main.teamArena.style = style; } if ( !uis.demoversion ) { y += MAIN_MENU_VERTICAL_SPACING; s_main.mods.generic.type = MTYPE_PTEXT; s_main.mods.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS; s_main.mods.generic.x = 320; s_main.mods.generic.y = y; s_main.mods.generic.id = ID_MODS; s_main.mods.generic.callback = Main_MenuEvent; s_main.mods.string = "MODS"; s_main.mods.color = color_blue; s_main.mods.style = style; } y += MAIN_MENU_VERTICAL_SPACING; s_main.exit.generic.type = MTYPE_PTEXT; s_main.exit.generic.flags = QMF_CENTER_JUSTIFY|QMF_PULSEIFFOCUS; s_main.exit.generic.x = 320; s_main.exit.generic.y = y; s_main.exit.generic.id = ID_EXIT; s_main.exit.generic.callback = Main_MenuEvent; s_main.exit.string = "EXIT"; s_main.exit.color = color_blue; s_main.exit.style = style; Menu_AddItem( &s_main.menu, &s_main.singleplayer ); Menu_AddItem( &s_main.menu, &s_main.multiplayer ); Menu_AddItem( &s_main.menu, &s_main.setup ); Menu_AddItem( &s_main.menu, &s_main.demos ); Menu_AddItem( &s_main.menu, &s_main.cinematics ); if (teamArena) { Menu_AddItem( &s_main.menu, &s_main.teamArena ); } if ( !uis.demoversion ) { Menu_AddItem( &s_main.menu, &s_main.mods ); } Menu_AddItem( &s_main.menu, &s_main.exit ); trap_Key_SetCatcher( KEYCATCH_UI ); uis.menusp = 0; UI_PushMenu ( &s_main.menu ); }
4,750
611
<reponame>packagesdev/dejalu // DejaLu // Copyright (c) 2015 <NAME>. All rights reserved. #import <Foundation/Foundation.h> #import <WebKit/WebKit.h> @protocol DJLURLHandlerDelegate; @interface DJLURLHandler : NSObject @property (nonatomic, assign, getter=isReady) BOOL ready; @property (nonatomic, assign) id <DJLURLHandlerDelegate> delegate; + (instancetype) sharedManager; - (BOOL) isRegisteredAsDefault; - (void) registerAsDefault; - (void) registerMailAsDefault; - (void) openURL:(NSURL *)url; @end @protocol DJLURLHandlerDelegate - (void) DJLURLHandler:(DJLURLHandler *)handler composeMessageWithTo:(NSString *)to cc:(NSString *)cc bcc:(NSString *)bcc subject:(NSString *)subject body:(NSString *)body; - (void) DJLURLHandler:(DJLURLHandler *)handler composeMessageWithTo:(NSString *)to cc:(NSString *)cc bcc:(NSString *)bcc subject:(NSString *)subject htmlBody:(NSString *)htmlBody; - (void) DJLURLHandler:(DJLURLHandler *)handler composeMessageWithTo:(NSString *)to cc:(NSString *)cc bcc:(NSString *)bcc subject:(NSString *)subject archive:(WebArchive *)archive; - (void) DJLURLHandler:(DJLURLHandler *)handler openMessageWithMessageID:(NSString *)messageID; @end
386
627
<reponame>YuanYuanDog/DesignPatterns-Objective-C<filename>DesignPatterns/FactoryMethod/UndergraduateFactory.h // // UndergraduateFactory.h // DesignPatterns // // Created by leichunfeng on 14-10-19. // Copyright (c) 2014年 zdnst. All rights reserved. // #import <Foundation/Foundation.h> #import "ILeiFengFactory.h" /// 学雷锋的大学生工厂类 @interface UndergraduateFactory : NSObject <ILeiFengFactory> @end
160
1,104
<reponame>Zorghts/roll20-character-sheets { "html": "PTA.html", "css": "PTA.css", "authors": "<NAME> (sepianra)", "roll20userid": "225131", "preview": "PTA.png", "instructions": "Characteristic Buttons will roll checks using modifiers", "legacy": true }
105
458
<reponame>Tazura/ngrest<filename>tools/ngrestcg/templates/common/enums.cpp ##foreach $(.enums) ##ifeq($(enum.isExtern),false) ##include "nsopt.cpp" // enum $(enum.name) const char* $(enum.ownerName.!replace/::/Serializer::/)Serializer::toCString($(enum.ownerName) value) { switch (value) { ##foreach $(enum.members) case $(enum.ownerName)::$(member.name): return "$(member.name)"; ##endfor default: NGREST_THROW_ASSERT("Can't serialize enum $(enum.name) from value: [" + ::ngrest::toString(static_cast<int>(value)) + "]"); } } $(enum.ownerName) $(enum.ownerName.!replace/::/Serializer::/)Serializer::fromCString(const char* str) { ##foreach $(enum.members) if (!strcmp(str, "$(member.name)")) return $(enum.ownerName)::$(member.name); ##endfor NGREST_THROW_ASSERT("Can't deserialize enum $(enum.name) from value: [" + std::string(str) + "]"); } ##endif ##endfor
373
14,668
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/platform/network/content_security_policy_parsers.h" #include "testing/gtest/include/gtest/gtest.h" namespace blink { TEST(ContentSecurityPolicyParsers, MatchesTheSerializedCSPGrammar) { struct { String value; bool expected; } testCases[]{ {"script-src 'none'; invalid-directive ", true}, {"script-src 'none'; invalid-directive;", true}, {" script-src 'none' https://www.example.org ; ;invalid-directive; ;", true}, {"script-src 'none', media-src 'none'", false}, {"script-src 'none'; /invalid-directive-name", false}, }; for (const auto& testCase : testCases) { EXPECT_EQ(MatchesTheSerializedCSPGrammar(testCase.value), testCase.expected); } } } // namespace blink
352
14,425
<filename>hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/protocol/JournalProtocol.java /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hdfs.server.protocol; import java.io.IOException; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.hdfs.DFSConfigKeys; import org.apache.hadoop.security.KerberosInfo; /** * Protocol used to journal edits to a remote node. Currently, * this is used to publish edits from the NameNode to a BackupNode. */ @KerberosInfo( serverPrincipal = DFSConfigKeys.DFS_NAMENODE_KERBEROS_PRINCIPAL_KEY, clientPrincipal = DFSConfigKeys.DFS_NAMENODE_KERBEROS_PRINCIPAL_KEY) @InterfaceAudience.Private public interface JournalProtocol { /** * * This class is used by both the Namenode (client) and BackupNode (server) * to insulate from the protocol serialization. * * If you are adding/changing DN's interface then you need to * change both this class and ALSO related protocol buffer * wire protocol definition in JournalProtocol.proto. * * For more details on protocol buffer wire protocol, please see * .../org/apache/hadoop/hdfs/protocolPB/overview.html */ public static final long versionID = 1L; /** * Journal edit records. * This message is sent by the active name-node to the backup node * via {@code EditLogBackupOutputStream} in order to synchronize meta-data * changes with the backup namespace image. * * @param journalInfo journal information * @param epoch marks beginning a new journal writer * @param firstTxnId the first transaction of this batch * @param numTxns number of transactions * @param records byte array containing serialized journal records * @throws FencedException if the resource has been fenced */ public void journal(JournalInfo journalInfo, long epoch, long firstTxnId, int numTxns, byte[] records) throws IOException; /** * Notify the BackupNode that the NameNode has rolled its edit logs * and is now writing a new log segment. * @param journalInfo journal information * @param epoch marks beginning a new journal writer * @param txid the first txid in the new log * @throws FencedException if the resource has been fenced */ public void startLogSegment(JournalInfo journalInfo, long epoch, long txid) throws IOException; /** * Request to fence any other journal writers. * Older writers with at previous epoch will be fenced and can no longer * perform journal operations. * * @param journalInfo journal information * @param epoch marks beginning a new journal writer * @param fencerInfo info about fencer for debugging purposes * @throws FencedException if the resource has been fenced */ public FenceResponse fence(JournalInfo journalInfo, long epoch, String fencerInfo) throws IOException; }
1,152
892
<gh_stars>100-1000 { "schema_version": "1.2.0", "id": "GHSA-5v65-cw5f-3jfp", "modified": "2022-04-30T18:19:21Z", "published": "2022-04-30T18:19:21Z", "aliases": [ "CVE-2002-0500" ], "details": "Internet Explorer 5.0 through 6.0 allows remote attackers to determine the existence of files on the client via an IMG tag with a dynsrc property that references the target file, which sets certain elements of the image object such as file size.", "severity": [ ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2002-0500" }, { "type": "WEB", "url": "http://archives.neohapsis.com/archives/bugtraq/2002-03/0331.html" }, { "type": "WEB", "url": "http://www.iss.net/security_center/static/8658.php" }, { "type": "WEB", "url": "http://www.securityfocus.com/bid/4371" } ], "database_specific": { "cwe_ids": [ ], "severity": "MODERATE", "github_reviewed": false } }
461
365
<reponame>rbabari/blender import bpy track = bpy.context.edit_movieclip.tracking.tracks.active track.color = (0.0, 1.0, 0.0) track.use_custom_color = True
63
575
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/offline_pages/core/auto_fetch.h" #include "components/offline_pages/core/client_namespace_constants.h" #include "testing/gtest/include/gtest/gtest.h" namespace offline_pages { namespace auto_fetch { namespace { TEST(AutoFetch, MakeClientId) { EXPECT_EQ(ClientId(kAutoAsyncNamespace, "A123"), auto_fetch::MakeClientId(auto_fetch::ClientIdMetadata(123))); } TEST(AutoFetch, ExtractMetadataSuccess) { base::Optional<auto_fetch::ClientIdMetadata> metadata = auto_fetch::ExtractMetadata( auto_fetch::MakeClientId(auto_fetch::ClientIdMetadata(123))); ASSERT_TRUE(metadata); EXPECT_EQ(123, metadata.value().android_tab_id); } TEST(AutoFetch, ExtractMetadataFail) { EXPECT_FALSE( auto_fetch::ExtractMetadata(ClientId(kAutoAsyncNamespace, "123"))); EXPECT_FALSE(auto_fetch::ExtractMetadata(ClientId(kAutoAsyncNamespace, ""))); EXPECT_FALSE(auto_fetch::ExtractMetadata(ClientId("other", "A123"))); } } // namespace } // namespace auto_fetch } // namespace offline_pages
446
1,144
// SPDX-License-Identifier: GPL-2.0+ /* * Copyright (C) 2016, <NAME> <<EMAIL>> */ #include <common.h> #include <dm.h> #include <pci.h> #include <vbe.h> static int vesa_video_probe(struct udevice *dev) { return vbe_setup_video(dev, NULL); } static const struct udevice_id vesa_video_ids[] = { { .compatible = "vesa-fb" }, { } }; U_BOOT_DRIVER(vesa_video) = { .name = "vesa_video", .id = UCLASS_VIDEO, .of_match = vesa_video_ids, .probe = vesa_video_probe, }; static struct pci_device_id vesa_video_supported[] = { { PCI_DEVICE_CLASS(PCI_CLASS_DISPLAY_VGA << 8, ~0) }, { }, }; U_BOOT_PCI_DEVICE(vesa_video, vesa_video_supported);
290
572
<reponame>cassiasamp/live-de-python<gh_stars>100-1000 s = 'Batatinha quando nasce espalha rama pelo chão' s.count('a') from collections import Counter print(Counter(s))
67
2,221
<filename>flume-ng-channels/flume-file-channel/src/test/java/org/apache/flume/channel/file/encryption/TestFileChannelEncryption.java<gh_stars>1000+ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.flume.channel.file.encryption; import com.google.common.base.Charsets; import com.google.common.base.Joiner; import com.google.common.collect.Maps; import com.google.common.io.Files; import org.apache.flume.ChannelException; import org.apache.flume.FlumeException; import org.apache.flume.channel.file.FileChannelConfiguration; import org.apache.flume.channel.file.TestFileChannelBase; import org.apache.flume.channel.file.TestUtils; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicBoolean; import static org.apache.flume.channel.file.TestUtils.compareInputAndOut; import static org.apache.flume.channel.file.TestUtils.consumeChannel; import static org.apache.flume.channel.file.TestUtils.fillChannel; import static org.apache.flume.channel.file.TestUtils.putEvents; import static org.apache.flume.channel.file.TestUtils.takeEvents; public class TestFileChannelEncryption extends TestFileChannelBase { protected static final Logger LOGGER = LoggerFactory.getLogger(TestFileChannelEncryption.class); private File keyStoreFile; private File keyStorePasswordFile; private Map<String, File> keyAliasPassword; @Before public void setup() throws Exception { super.setup(); keyStorePasswordFile = new File(baseDir, "keyStorePasswordFile"); Files.write("keyStorePassword", keyStorePasswordFile, Charsets.UTF_8); keyStoreFile = new File(baseDir, "keyStoreFile"); Assert.assertTrue(keyStoreFile.createNewFile()); keyAliasPassword = Maps.newHashMap(); keyAliasPassword.putAll(EncryptionTestUtils.configureTestKeyStore(baseDir, keyStoreFile)); } @After public void teardown() { super.teardown(); } private Map<String, String> getOverrides() throws Exception { Map<String, String> overrides = Maps.newHashMap(); overrides.put(FileChannelConfiguration.CAPACITY, String.valueOf(100)); overrides.put(FileChannelConfiguration.TRANSACTION_CAPACITY, String.valueOf(100)); return overrides; } private Map<String, String> getOverridesForEncryption() throws Exception { Map<String, String> overrides = getOverrides(); Map<String, String> encryptionProps = EncryptionTestUtils.configureForKeyStore(keyStoreFile, keyStorePasswordFile, keyAliasPassword); encryptionProps.put(EncryptionConfiguration.KEY_PROVIDER, KeyProviderType.JCEKSFILE.name()); encryptionProps.put(EncryptionConfiguration.CIPHER_PROVIDER, CipherProviderType.AESCTRNOPADDING.name()); encryptionProps.put(EncryptionConfiguration.ACTIVE_KEY, "key-1"); for (String key : encryptionProps.keySet()) { overrides.put(EncryptionConfiguration.ENCRYPTION_PREFIX + "." + key, encryptionProps.get(key)); } return overrides; } /** * Test fails without FLUME-1565 */ @Test public void testThreadedConsume() throws Exception { int numThreads = 20; Map<String, String> overrides = getOverridesForEncryption(); overrides.put(FileChannelConfiguration.CAPACITY, String.valueOf(10000)); overrides.put(FileChannelConfiguration.TRANSACTION_CAPACITY, String.valueOf(100)); channel = createFileChannel(overrides); channel.start(); Assert.assertTrue(channel.isOpen()); Executor executor = Executors.newFixedThreadPool(numThreads); Set<String> in = fillChannel(channel, "threaded-consume"); final AtomicBoolean error = new AtomicBoolean(false); final CountDownLatch startLatch = new CountDownLatch(numThreads); final CountDownLatch stopLatch = new CountDownLatch(numThreads); final Set<String> out = Collections.synchronizedSet(new HashSet<String>()); for (int i = 0; i < numThreads; i++) { executor.execute(new Runnable() { @Override public void run() { try { startLatch.countDown(); startLatch.await(); out.addAll(takeEvents(channel, 10)); } catch (Throwable t) { error.set(true); LOGGER.error("Error in take thread", t); } finally { stopLatch.countDown(); } } }); } stopLatch.await(); Assert.assertFalse(error.get()); compareInputAndOut(in, out); } @Test public void testThreadedProduce() throws Exception { int numThreads = 20; Map<String, String> overrides = getOverridesForEncryption(); overrides.put(FileChannelConfiguration.CAPACITY, String.valueOf(10000)); overrides.put(FileChannelConfiguration.TRANSACTION_CAPACITY, String.valueOf(100)); channel = createFileChannel(overrides); channel.start(); Assert.assertTrue(channel.isOpen()); Executor executor = Executors.newFixedThreadPool(numThreads); final AtomicBoolean error = new AtomicBoolean(false); final CountDownLatch startLatch = new CountDownLatch(numThreads); final CountDownLatch stopLatch = new CountDownLatch(numThreads); final Set<String> in = Collections.synchronizedSet(new HashSet<String>()); for (int i = 0; i < numThreads; i++) { executor.execute(new Runnable() { @Override public void run() { try { startLatch.countDown(); startLatch.await(); in.addAll(putEvents(channel, "thread-produce", 10, 10000, true)); } catch (Throwable t) { error.set(true); LOGGER.error("Error in put thread", t); } finally { stopLatch.countDown(); } } }); } stopLatch.await(); Set<String> out = consumeChannel(channel); Assert.assertFalse(error.get()); compareInputAndOut(in, out); } @Test public void testConfiguration() throws Exception { Map<String, String> overrides = Maps.newHashMap(); overrides.put("encryption.activeKey", "key-1"); overrides.put("encryption.cipherProvider", "AESCTRNOPADDING"); overrides.put("encryption.keyProvider", "JCEKSFILE"); overrides.put("encryption.keyProvider.keyStoreFile", keyStoreFile.getAbsolutePath()); overrides.put("encryption.keyProvider.keyStorePasswordFile", keyStorePasswordFile.getAbsolutePath()); overrides.put("encryption.keyProvider.keys", "key-0 key-1"); overrides.put("encryption.keyProvider.keys.key-0.passwordFile", keyAliasPassword.get("key-0").getAbsolutePath()); channel = createFileChannel(overrides); channel.start(); Assert.assertTrue(channel.isOpen()); Set<String> in = fillChannel(channel, "restart"); channel.stop(); channel = TestUtils.createFileChannel(checkpointDir.getAbsolutePath(), dataDir, overrides); channel.start(); Assert.assertTrue(channel.isOpen()); Set<String> out = consumeChannel(channel); compareInputAndOut(in, out); } @Test public void testBasicEncyrptionDecryption() throws Exception { Map<String, String> overrides = getOverridesForEncryption(); channel = createFileChannel(overrides); channel.start(); Assert.assertTrue(channel.isOpen()); Set<String> in = fillChannel(channel, "restart"); channel.stop(); channel = TestUtils.createFileChannel(checkpointDir.getAbsolutePath(), dataDir, overrides); channel.start(); Assert.assertTrue(channel.isOpen()); Set<String> out = consumeChannel(channel); compareInputAndOut(in, out); } @Test public void testEncryptedChannelWithoutEncryptionConfigFails() throws Exception { Map<String, String> overrides = getOverridesForEncryption(); channel = createFileChannel(overrides); channel.start(); Assert.assertTrue(channel.isOpen()); fillChannel(channel, "will-not-restart"); channel.stop(); Map<String, String> noEncryptionOverrides = getOverrides(); channel = createFileChannel(noEncryptionOverrides); channel.start(); if (channel.isOpen()) { try { takeEvents(channel, 1, 1); Assert.fail("Channel was opened and take did not throw exception"); } catch (ChannelException ex) { // expected } } } @Test public void testUnencyrptedAndEncryptedLogs() throws Exception { Map<String, String> noEncryptionOverrides = getOverrides(); channel = createFileChannel(noEncryptionOverrides); channel.start(); Assert.assertTrue(channel.isOpen()); Set<String> in = fillChannel(channel, "unencrypted-and-encrypted"); int numEventsToRemove = in.size() / 2; for (int i = 0; i < numEventsToRemove; i++) { Assert.assertTrue(in.removeAll(takeEvents(channel, 1, 1))); } // now we have logs with no encryption and the channel is half full channel.stop(); Map<String, String> overrides = getOverridesForEncryption(); channel = createFileChannel(overrides); channel.start(); Assert.assertTrue(channel.isOpen()); in.addAll(fillChannel(channel, "unencrypted-and-encrypted")); Set<String> out = consumeChannel(channel); compareInputAndOut(in, out); } @Test public void testBadKeyProviderInvalidValue() throws Exception { Map<String, String> overrides = getOverridesForEncryption(); overrides.put(Joiner.on(".").join(EncryptionConfiguration.ENCRYPTION_PREFIX, EncryptionConfiguration.KEY_PROVIDER), "invalid"); try { channel = createFileChannel(overrides); Assert.fail(); } catch (FlumeException ex) { Assert.assertEquals("java.lang.ClassNotFoundException: invalid", ex.getMessage()); } } @Test public void testBadKeyProviderInvalidClass() throws Exception { Map<String, String> overrides = getOverridesForEncryption(); overrides.put(Joiner.on(".").join(EncryptionConfiguration.ENCRYPTION_PREFIX, EncryptionConfiguration.KEY_PROVIDER), String.class.getName()); try { channel = createFileChannel(overrides); Assert.fail(); } catch (FlumeException ex) { Assert.assertEquals("Unable to instantiate Builder from java.lang.String", ex.getMessage()); } } @Test public void testBadCipherProviderInvalidValue() throws Exception { Map<String, String> overrides = getOverridesForEncryption(); overrides.put(Joiner.on(".").join(EncryptionConfiguration.ENCRYPTION_PREFIX, EncryptionConfiguration.CIPHER_PROVIDER), "invalid"); channel = createFileChannel(overrides); channel.start(); Assert.assertFalse(channel.isOpen()); } @Test public void testBadCipherProviderInvalidClass() throws Exception { Map<String, String> overrides = getOverridesForEncryption(); overrides.put(Joiner.on(".").join(EncryptionConfiguration.ENCRYPTION_PREFIX, EncryptionConfiguration.CIPHER_PROVIDER), String.class.getName()); channel = createFileChannel(overrides); channel.start(); Assert.assertFalse(channel.isOpen()); } @Test public void testMissingKeyStoreFile() throws Exception { Map<String, String> overrides = getOverridesForEncryption(); overrides.put(Joiner.on(".").join(EncryptionConfiguration.ENCRYPTION_PREFIX, EncryptionConfiguration.KEY_PROVIDER, EncryptionConfiguration.JCE_FILE_KEY_STORE_FILE), "/path/does/not/exist"); try { channel = createFileChannel(overrides); Assert.fail(); } catch (RuntimeException ex) { Assert.assertTrue("Exception message is incorrect: " + ex.getMessage(), ex.getMessage().startsWith("java.io.FileNotFoundException: /path/does/not/exist ")); } } @Test public void testMissingKeyStorePasswordFile() throws Exception { Map<String, String> overrides = getOverridesForEncryption(); overrides.put(Joiner.on(".").join(EncryptionConfiguration.ENCRYPTION_PREFIX, EncryptionConfiguration.KEY_PROVIDER, EncryptionConfiguration.JCE_FILE_KEY_STORE_PASSWORD_FILE), "/path/does/not/exist"); try { channel = createFileChannel(overrides); Assert.fail(); } catch (RuntimeException ex) { Assert.assertTrue("Exception message is incorrect: " + ex.getMessage(), ex.getMessage().startsWith("java.io.FileNotFoundException: /path/does/not/exist ")); } } @Test public void testBadKeyStorePassword() throws Exception { Files.write("invalid", keyStorePasswordFile, Charsets.UTF_8); Map<String, String> overrides = getOverridesForEncryption(); try { channel = TestUtils.createFileChannel(checkpointDir.getAbsolutePath(), dataDir, overrides); Assert.fail(); } catch (RuntimeException ex) { Assert.assertEquals("java.io.IOException: Keystore was tampered with, or " + "password was incorrect", ex.getMessage()); } } @Test public void testBadKeyAlias() throws Exception { Map<String, String> overrides = getOverridesForEncryption(); overrides.put(EncryptionConfiguration.ENCRYPTION_PREFIX + "." + EncryptionConfiguration.ACTIVE_KEY, "invalid"); channel = TestUtils.createFileChannel(checkpointDir.getAbsolutePath(), dataDir, overrides); channel.start(); Assert.assertFalse(channel.isOpen()); } }
5,368
4,036
<filename>python/tools/recorded-call-graph-metrics/tests/python-src/getsockname.py import socket sock = socket.socket() print(sock.getsockname())
50
335
<filename>O/Overspill_noun.json { "word": "Overspill", "definitions": [ "The action or result of spilling over or spreading into another area.", "A surplus population moving or forced to move from an overcrowded area to a less heavily populated one." ], "parts-of-speech": "Noun" }
109
32,544
<reponame>DBatOWL/tutorials package com.baeldung.persistence.dao; import com.baeldung.persistence.model.Event; import org.springframework.stereotype.Repository; @Repository public class EventDao extends AbstractHibernateDao<Event> implements IEventDao { public EventDao() { super(); setClazz(Event.class); } // API }
138
1,808
<reponame>keesg60/hyperion.ng #pragma once #include <QAbstractNativeEventFilter> // QT includes #include <QObject> #include <QJsonObject> #include <QJsonArray> #include <QJsonDocument> #include <utils/ColorRgb.h> #include <hyperion/Grabber.h> #include <sys/ipc.h> #include <sys/shm.h> #include <xcb/randr.h> #include <xcb/shm.h> #include <xcb/xcb.h> #include <xcb/xcb_image.h> class Logger; class XcbGrabber : public Grabber, public QAbstractNativeEventFilter { Q_OBJECT public: XcbGrabber(int cropLeft=0, int cropRight=0, int cropTop=0, int cropBottom=0); ~XcbGrabber() override; bool open(); bool setupDisplay(); int grabFrame(Image<ColorRgb> & image, bool forceUpdate = false); int updateScreenDimensions(bool force = false); void setVideoMode(VideoMode mode) override; bool setWidthHeight(int width, int height) override { return true; } bool setPixelDecimation(int pixelDecimation) override; void setCropping(int cropLeft, int cropRight, int cropTop, int cropBottom) override; /// /// @brief Discover XCB screens available (for configuration). /// /// @param[in] params Parameters used to overwrite discovery default behaviour /// /// @return A JSON structure holding a list of devices found /// QJsonObject discover(const QJsonObject& params); private: #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)) bool nativeEventFilter(const QByteArray & eventType, void * message, qintptr * result) override; #else bool nativeEventFilter(const QByteArray & eventType, void * message, long int * result) override; #endif void freeResources(); void setupResources(); void setupRender(); void setupRandr(); void setupShm(); xcb_screen_t * getScreen(const xcb_setup_t *setup, int screen_num) const; xcb_render_pictformat_t findFormatForVisual(xcb_visualid_t visual) const; xcb_connection_t * _connection; xcb_screen_t * _screen; xcb_pixmap_t _pixmap; xcb_render_pictformat_t _srcFormat; xcb_render_pictformat_t _dstFormat; xcb_render_picture_t _srcPicture; xcb_render_picture_t _dstPicture; xcb_render_transform_t _transform; xcb_shm_seg_t _shminfo; int _screen_num; unsigned _screenWidth; unsigned _screenHeight; unsigned _src_x; unsigned _src_y; bool _XcbRenderAvailable; bool _XcbRandRAvailable; bool _XcbShmAvailable; bool _XcbShmPixmapAvailable; bool _isWayland; Logger * _logger; uint8_t * _shmData; int _XcbRandREventBase; };
862
1,850
<filename>repeater-plugin-api/src/main/java/com/alibaba/jvm/sandbox/repeater/plugin/domain/Invocation.java package com.alibaba.jvm.sandbox.repeater.plugin.domain; /** * {@link Invocation} 描述一次调用 * * <p> * {@link Invocation} 调用信息抽象;一次完整的{@link RecordModel} 由一次入口{@link RecordModel#entranceInvocation}和若干次子{@link RecordModel#subInvocations}组装 * * {@link Invocation} 主要记录了调用时的入参、返回值、调用顺序等信息,用于回放流量的发起和子调用的Mock还原 * </p> * * @author zhaoyb1990 */ public class Invocation implements java.io.Serializable { /** * 调用类型 * * @see com.alibaba.jvm.sandbox.repeater.plugin.domain.InvokeType */ private InvokeType type; /** * @see com.alibaba.jvm.sandbox.api.event.InvokeEvent#invokeId */ private int invokeId; /** * @see com.alibaba.jvm.sandbox.api.event.InvokeEvent#processId */ private int processId; /** * 链路跟踪ID(仅应用内部,对于分布式系统需要自己重新定义) */ private String traceId; /** * 调用的身份识别 * * @see com.alibaba.jvm.sandbox.repeater.plugin.domain.Identity */ private Identity identity; /** * 调用发生在应用内部的sequence序号 */ private Integer index; /** * 是否是入口调用类型(类似 HTTP/DUBBO) */ private boolean entrance; /** * 请求参数 - snapshot 不做传输使用,传输需要序列化值 * * @see Invocation#requestSerialized */ private transient Object[] request; /** * 序列化之后的请求值,录制时候作为{@link Invocation#request}的载体传输;回放时候需要还原成{@link Invocation#request} */ private String requestSerialized; /** * 返回结果 - snapshot 不做传输使用 */ private transient Object response; /** * 序列化之后的请求值,录制时候作为{@link Invocation#response}的载体传输;回放时候需要还原成{@link Invocation#response} */ private String responseSerialized; /** * 异常信息 - snapshot 不做传输使用 */ private transient Throwable throwable; /** * 序列化之后的请求值,录制时候作为{@link Invocation#throwable}的载体传输;回放时候需要还原成{@link Invocation#throwable} */ private String throwableSerialized; /** * 调用开始时间 */ private Long start; /** * 调用结束时间 */ private Long end; /** * 序列化token */ private String serializeToken; /** * 目标调用的类加载(透传不做传输) */ private transient ClassLoader classLoader; public InvokeType getType() { return type; } public void setType(InvokeType type) { this.type = type; } public int getInvokeId() { return invokeId; } public void setInvokeId(int invokeId) { this.invokeId = invokeId; } public int getProcessId() { return processId; } public void setProcessId(int processId) { this.processId = processId; } public String getTraceId() { return traceId; } public void setTraceId(String traceId) { this.traceId = traceId; } public Identity getIdentity() { return identity; } public void setIdentity(Identity identity) { this.identity = identity; } public Integer getIndex() { return index; } public void setIndex(Integer index) { this.index = index; } public boolean isEntrance() { return entrance; } public void setEntrance(boolean entrance) { this.entrance = entrance; } public Object[] getRequest() { return request; } public void setRequest(Object[] request) { this.request = request; } public String getRequestSerialized() { return requestSerialized; } public void setRequestSerialized(String requestSerialized) { this.requestSerialized = requestSerialized; } public Object getResponse() { return response; } public void setResponse(Object response) { this.response = response; } public String getResponseSerialized() { return responseSerialized; } public void setResponseSerialized(String responseSerialized) { this.responseSerialized = responseSerialized; } public Throwable getThrowable() { return throwable; } public void setThrowable(Throwable throwable) { this.throwable = throwable; } public String getThrowableSerialized() { return throwableSerialized; } public void setThrowableSerialized(String throwableSerialized) { this.throwableSerialized = throwableSerialized; } public Long getStart() { return start; } public void setStart(Long start) { this.start = start; } public Long getEnd() { return end; } public void setEnd(Long end) { this.end = end; } public String getSerializeToken() { return serializeToken; } public void setSerializeToken(String serializeToken) { this.serializeToken = serializeToken; } public ClassLoader getClassLoader() { return classLoader; } public void setClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; } }
2,567
1,444
package mage.cards.n; import mage.abilities.effects.common.search.SearchLibraryPutInPlayEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.filter.StaticFilters; import mage.target.common.TargetCardInLibrary; import java.util.UUID; /** * * @author LevelX2 */ public final class NaturalConnection extends CardImpl { public NaturalConnection(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.INSTANT},"{2}{G}"); // Search your library for a basic land card, put it onto the battlefield tapped, then shuffle your library. TargetCardInLibrary target = new TargetCardInLibrary(StaticFilters.FILTER_CARD_BASIC_LAND); this.getSpellAbility().addEffect(new SearchLibraryPutInPlayEffect(target, true)); } private NaturalConnection(final NaturalConnection card) { super(card); } @Override public NaturalConnection copy() { return new NaturalConnection(this); } }
337
1,227
from .preprocess import HiddenOutput, UAE, preprocess_drift __all__ = [ "HiddenOutput", "UAE", "preprocess_drift" ]
52
6,304
// Copyright 2020 Google LLC. // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. #include "tools/fiddle/examples.h" REG_FIDDLE_ANIMATED(SkPath_cubicTo_example_parametric_animated, 512, 512, false, 0, 3) { /* If the starting point is (x0, y0), then this curve is defined as the paramentric curve as `t` goes from 0 to 1: s := 1 - t x := (s * s * s * x0) + (3 * s * s * t * x1) + (3 * s * t * t * x2) + (t * t * t * x3) y := (s * s * s * y0) + (3 * s * s * t * y1) + (3 * s * t * t * y2) + (t * t * t * y3) */ SkPoint cubic(SkPoint p0, SkPoint p1, SkPoint p2, SkPoint p3, float t) { // a simple mathematical definition of cubic curve. // There are faster ways to calculate this. float s = 1 - t; return {(s * s * s * p0.x()) + (3 * s * s * t * p1.x()) + (3 * s * t * t * p2.x()) + (t * t * t * p3.x()), (s * s * s * p0.y()) + (3 * s * s * t * p1.y()) + (3 * s * t * t * p2.y()) + (t * t * t * p3.y())}; } static SkPoint interpolate(SkPoint a, SkPoint b, float t) { return {SkScalarInterp(a.x(), b.x(), t), SkScalarInterp(a.y(), b.y(), t)}; } void draw(SkCanvas* canvas) { canvas->clear(SkColorSetARGB(255,255,255,255)); SkPoint a{136, 64}; SkPoint b{448, 448}; SkPoint c{64, 448}; SkPoint d{376, 64}; SkPoint ab = interpolate(a, b, frame); SkPoint bc = interpolate(b, c, frame); SkPoint cd = interpolate(c, d, frame); SkPoint abc = interpolate(ab, bc, frame); SkPoint bcd = interpolate(bc, cd, frame); SkPaint paint; paint.setAntiAlias(true); paint.setStyle(SkPaint::kStroke_Style); paint.setStrokeWidth(1); canvas->drawLine(ab, bc, paint); canvas->drawLine(bc, cd, paint); canvas->drawLine(abc, bcd, paint); paint.setStrokeWidth(3); canvas->drawLine(a, b, paint); canvas->drawLine(b, c, paint); canvas->drawLine(c, d, paint); paint.setStrokeWidth(5); paint.setColor(SkColorSetARGB(255, 0, 0, 255)); SkPath cubicCurve; cubicCurve.moveTo(a); cubicCurve.cubicTo(b, c, d); canvas->drawPath(cubicCurve, paint); SkFont font(nullptr, 32); SkPaint textPaint; textPaint.setColor(SkColorSetARGB(255, 0, 255, 0)); textPaint.setAntiAlias(true); sk_sp<SkFontMgr> mgr(SkFontMgr::RefDefault()); sk_sp<SkTypeface> face(mgr->matchFamilyStyle("DejaVu Sans Mono", SkFontStyle())); canvas->drawString("a", a.x(), a.y(), font, textPaint); canvas->drawString("b", b.x(), b.y(), font, textPaint); canvas->drawString("c", c.x()-20, c.y(), font, textPaint); canvas->drawString("d", d.x(), d.y(), font, textPaint); SkString msg = SkStringPrintf("%.4f", frame); textPaint.setColor(SkColorSetARGB(255, 204, 204, 204)); canvas->drawString(msg.c_str(), 4, 36, font, textPaint); SkPaint pointPaint; pointPaint.setAntiAlias(true); pointPaint.setStrokeWidth(8); pointPaint.setStrokeCap(SkPaint::kRound_Cap); pointPaint.setColor(SkColorSetARGB(255, 255, 0, 0)); canvas->drawPoint(interpolate(abc, bcd, frame), pointPaint); pointPaint.setColor(SkColorSetARGB(255, 0, 255, 0)); pointPaint.setStrokeWidth(7); canvas->drawPoint(cubic(a, b, c, d, frame), pointPaint); } } // END FIDDLE
1,627
444
<reponame>icoz69/DeepEMD<gh_stars>100-1000 import argparse import torch.nn as nn import tqdm from torch.utils.data import DataLoader from Models.dataloader.samplers import CategoriesSampler from Models.models.Network import DeepEMD from Models.utils import * from Models.dataloader.data_utils import * DATA_DIR='your/default/dataset/dir' # DATA_DIR='/home/zhangchi/dataset' MODEL_DIR='deepemd_trained_model/miniimagenet/fcn/max_acc.pth' parser = argparse.ArgumentParser() # about task parser.add_argument('-way', type=int, default=5) parser.add_argument('-shot', type=int, default=1) parser.add_argument('-query', type=int, default=15) # number of query image per class parser.add_argument('-dataset', type=str, default='miniimagenet', choices=['miniimagenet', 'cub','tieredimagenet','fc100','tieredimagenet_yao','cifar_fs']) parser.add_argument('-set', type=str, default='test', choices=['train','val', 'test']) # about model parser.add_argument('-temperature', type=float, default=12.5) parser.add_argument('-metric', type=str, default='cosine', choices=[ 'cosine' ]) parser.add_argument('-norm', type=str, default='center', choices=[ 'center']) parser.add_argument('-deepemd', type=str, default='fcn', choices=['fcn', 'grid', 'sampling']) #deepemd fcn only parser.add_argument('-feature_pyramid', type=str, default=None) #deepemd sampling only parser.add_argument('-num_patch',type=int,default=9) #deepemd grid only patch_list parser.add_argument('-patch_list',type=str,default='2,3') parser.add_argument('-patch_ratio',type=float,default=2) # solver parser.add_argument('-solver', type=str, default='opencv', choices=['opencv']) # SFC parser.add_argument('-sfc_lr', type=float, default=100) parser.add_argument('-sfc_wd', type=float, default=0, help='weight decay for SFC weight') parser.add_argument('-sfc_update_step', type=float, default=100) parser.add_argument('-sfc_bs', type=int, default=4) # others parser.add_argument('-test_episode', type=int, default=5000) parser.add_argument('-gpu', default='0,1') parser.add_argument('-data_dir', type=str, default=DATA_DIR) parser.add_argument('-model_dir', type=str, default=MODEL_DIR) parser.add_argument('-seed', type=int, default=1) args = parser.parse_args() if args.feature_pyramid is not None: args.feature_pyramid = [int(x) for x in args.feature_pyramid.split(',')] args.patch_list = [int(x) for x in args.patch_list.split(',')] pprint(vars(args)) set_seed(args.seed) num_gpu = set_gpu(args) Dataset=set_up_datasets(args) # model model = DeepEMD(args) model = load_model(model, args.model_dir) model = nn.DataParallel(model, list(range(num_gpu))) model = model.cuda() model.eval() # test dataset test_set = Dataset(args.set, args) sampler = CategoriesSampler(test_set.label, args.test_episode, args.way, args.shot + args.query) loader = DataLoader(test_set, batch_sampler=sampler, num_workers=8, pin_memory=True) tqdm_gen = tqdm.tqdm(loader) # label of query images ave_acc = Averager() test_acc_record = np.zeros((args.test_episode,)) label = torch.arange(args.way).repeat(args.query) label = label.type(torch.cuda.LongTensor) with torch.no_grad(): for i, batch in enumerate(tqdm_gen, 1): data, _ = [_.cuda() for _ in batch] k = args.way * args.shot model.module.mode = 'encoder' data = model(data) data_shot, data_query = data[:k], data[k:] # shot: 5,3,84,84 query:75,3,84,84 model.module.mode = 'meta' if args.shot > 1: data_shot = model.module.get_sfc(data_shot) logits = model((data_shot.unsqueeze(0).repeat(num_gpu, 1, 1, 1, 1), data_query)) acc = count_acc(logits, label) * 100 ave_acc.add(acc) test_acc_record[i - 1] = acc m, pm = compute_confidence_interval(test_acc_record[:i]) tqdm_gen.set_description('batch {}: This episode:{:.2f} average: {:.4f}+{:.4f}'.format(i, acc, m, pm)) m, pm = compute_confidence_interval(test_acc_record) result_list = ['test Acc {:.4f}'.format(ave_acc.item())] result_list.append('Test Acc {:.4f} + {:.4f}'.format(m, pm)) print(result_list[0]) print(result_list[1])
1,624
1,241
import pigpio import time class OdomDist(object): """ Take a tick input from odometry and compute the distance travelled """ def __init__(self, mm_per_tick, debug=False): self.mm_per_tick = mm_per_tick self.m_per_tick = mm_per_tick / 1000.0 self.meters = 0 self.last_time = time.time() self.meters_per_second = 0 self.debug = debug self.prev_ticks = 0 def run(self, ticks, throttle): """ inputs => total ticks since start inputs => throttle, used to determine positive or negative vel return => total dist (m), current vel (m/s), delta dist (m) """ new_ticks = ticks - self.prev_ticks self.prev_ticks = ticks #save off the last time interval and reset the timer start_time = self.last_time end_time = time.time() self.last_time = end_time #calculate elapsed time and distance traveled seconds = end_time - start_time distance = new_ticks * self.m_per_tick if throttle < 0.0: distance = distance * -1.0 velocity = distance / seconds #update the odometer values self.meters += distance self.meters_per_second = velocity #console output for debugging if(self.debug): print('seconds:', seconds) print('delta:', distance) print('velocity:', velocity) print('distance (m):', self.meters) print('velocity (m/s):', self.meters_per_second) return self.meters, self.meters_per_second, distance class PiPGIOEncoder(): def __init__(self, pin, pi): self.pin = pin self.pi = pi self.pi.set_mode(pin, pigpio.INPUT) self.pi.set_pull_up_down(pin, pigpio.PUD_UP) self.cb = pi.callback(self.pin, pigpio.FALLING_EDGE, self._cb) self.count = 0 def _cb(self, pin, level, tick): self.count += 1 def run(self): return self.count def shutdown(self): if self.cb != None: self.cb.cancel() self.cb = None self.pi.stop() if __name__ == "__main__": pi = pigpio.pi() e = PiPGIOEncoder(4, pi) while True: time.sleep(0.1) e.run()
1,073
2,504
<gh_stars>1000+ // --------------------------------------------------------------------- // THIS FILE IS AUTO-GENERATED BY BEHAVIAC DESIGNER, SO PLEASE DON'T MODIFY IT BY YOURSELF! // --------------------------------------------------------------------- #include "../types/behaviac_types.h" namespace behaviac { class bt_node_test_fsm_action_ut_1_2 { public: static bool Create(BehaviorTree* pBT); }; class bt_node_test_fsm_bt_ref_fsm { public: static bool Create(BehaviorTree* pBT); }; class bt_node_test_fsm_fsm_ref_bt_ut { public: static bool Create(BehaviorTree* pBT); }; class bt_node_test_fsm_fsm_ref_fsm_ut { public: static bool Create(BehaviorTree* pBT); }; class bt_node_test_fsm_fsm_ut_0 { public: static bool Create(BehaviorTree* pBT); }; class bt_node_test_fsm_fsm_ut_1 { public: static bool Create(BehaviorTree* pBT); }; class bt_node_test_htn_house_build_house { public: static bool Create(BehaviorTree* pBT); }; class bt_node_test_htn_house_construct { public: static bool Create(BehaviorTree* pBT); }; class bt_node_test_htn_house_root { public: static bool Create(BehaviorTree* pBT); }; class bt_node_test_htn_travel_root { public: static bool Create(BehaviorTree* pBT); }; class bt_node_test_htn_travel_travel { public: static bool Create(BehaviorTree* pBT); }; class bt_node_test_htn_travel_travel_by_air { public: static bool Create(BehaviorTree* pBT); }; class bt_node_test_PreconditionEffectorTest_PreconditionEffectorTest_0 { public: static bool Create(BehaviorTree* pBT); }; class bt_node_test_PreconditionEffectorTest_PreconditionEffectorTest_1 { public: static bool Create(BehaviorTree* pBT); }; class bt_node_test_PreconditionEffectorTest_PreconditionEffectorTest_2 { public: static bool Create(BehaviorTree* pBT); }; }
731
8,805
////////////////////////////////////////////////////////////////////////////// // // (C) Copyright <NAME> 2011-2013. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/container for documentation. // ////////////////////////////////////////////////////////////////////////////// #ifndef BOOST_CONTAINER_USES_ALLOCATOR_HPP #define BOOST_CONTAINER_USES_ALLOCATOR_HPP #include <boost/container/uses_allocator_fwd.hpp> #include <boost/container/detail/type_traits.hpp> namespace boost { namespace container { //! <b>Remark</b>: if a specialization constructible_with_allocator_suffix<X>::value is true, indicates that T may be constructed //! with an allocator as its last constructor argument. Ideally, all constructors of T (including the //! copy and move constructors) should have a variant that accepts a final argument of //! allocator_type. //! //! <b>Requires</b>: if a specialization constructible_with_allocator_suffix<X>::value is true, T must have a nested type, //! allocator_type and at least one constructor for which allocator_type is the last //! parameter. If not all constructors of T can be called with a final allocator_type argument, //! and if T is used in a context where a container must call such a constructor, then the program is //! ill-formed. //! //! <code> //! template <class T, class Allocator = allocator<T> > //! class Z { //! public: //! typedef Allocator allocator_type; //! //! // Default constructor with optional allocator suffix //! Z(const allocator_type& a = allocator_type()); //! //! // Copy constructor and allocator-extended copy constructor //! Z(const Z& zz); //! Z(const Z& zz, const allocator_type& a); //! }; //! //! // Specialize trait for class template Z //! template <class T, class Allocator = allocator<T> > //! struct constructible_with_allocator_suffix<Z<T,Allocator> > //! { static const bool value = true; }; //! </code> //! //! <b>Note</b>: This trait is a workaround inspired by "N2554: The Scoped A Model (Rev 2)" //! (<NAME>, 2008-02-29) to backport the scoped allocator model to C++03, as //! in C++03 there is no mechanism to detect if a type can be constructed from arbitrary arguments. //! Applications aiming portability with several compilers should always define this trait. //! //! In conforming C++11 compilers or compilers supporting SFINAE expressions //! (when BOOST_NO_SFINAE_EXPR is NOT defined), this trait is ignored and C++11 rules will be used //! to detect if a type should be constructed with suffix or prefix allocator arguments. template <class T> struct constructible_with_allocator_suffix { static const bool value = false; }; //! <b>Remark</b>: if a specialization constructible_with_allocator_prefix<X>::value is true, indicates that T may be constructed //! with allocator_arg and T::allocator_type as its first two constructor arguments. //! Ideally, all constructors of T (including the copy and move constructors) should have a variant //! that accepts these two initial arguments. //! //! <b>Requires</b>: specialization constructible_with_allocator_prefix<X>::value is true, T must have a nested type, //! allocator_type and at least one constructor for which allocator_arg_t is the first //! parameter and allocator_type is the second parameter. If not all constructors of T can be //! called with these initial arguments, and if T is used in a context where a container must call such //! a constructor, then the program is ill-formed. //! //! <code> //! template <class T, class Allocator = allocator<T> > //! class Y { //! public: //! typedef Allocator allocator_type; //! //! // Default constructor with and allocator-extended default constructor //! Y(); //! Y(allocator_arg_t, const allocator_type& a); //! //! // Copy constructor and allocator-extended copy constructor //! Y(const Y& yy); //! Y(allocator_arg_t, const allocator_type& a, const Y& yy); //! //! // Variadic constructor and allocator-extended variadic constructor //! template<class ...Args> Y(Args&& args...); //! template<class ...Args> //! Y(allocator_arg_t, const allocator_type& a, BOOST_FWD_REF(Args)... args); //! }; //! //! // Specialize trait for class template Y //! template <class T, class Allocator = allocator<T> > //! struct constructible_with_allocator_prefix<Y<T,Allocator> > //! { static const bool value = true; }; //! //! </code> //! //! <b>Note</b>: This trait is a workaround inspired by "N2554: The Scoped Allocator Model (Rev 2)" //! (<NAME>, 2008-02-29) to backport the scoped allocator model to C++03, as //! in C++03 there is no mechanism to detect if a type can be constructed from arbitrary arguments. //! Applications aiming portability with several compilers should always define this trait. //! //! In conforming C++11 compilers or compilers supporting SFINAE expressions //! (when BOOST_NO_SFINAE_EXPR is NOT defined), this trait is ignored and C++11 rules will be used //! to detect if a type should be constructed with suffix or prefix allocator arguments. template <class T> struct constructible_with_allocator_prefix { static const bool value = false; }; #ifndef BOOST_CONTAINER_DOXYGEN_INVOKED namespace container_detail { template<typename T, typename Allocator> struct uses_allocator_imp { // Use SFINAE (Substitution Failure Is Not An Error) to detect the // presence of an 'allocator_type' nested type convertilble from Allocator. private: typedef char yes_type; struct no_type{ char dummy[2]; }; // Match this function if T::allocator_type exists and is // implicitly convertible from Allocator template <class U> static yes_type test(typename U::allocator_type); // Match this function if T::allocator_type exists and it's type is `erased_type`. template <class U, class V> static typename container_detail::enable_if < container_detail::is_same<typename U::allocator_type, erased_type> , yes_type >::type test(const V&); // Match this function if TypeT::allocator_type does not exist or is // not convertible from Allocator. template <typename U> static no_type test(...); static Allocator alloc; // Declared but not defined public: static const bool value = sizeof(test<T>(alloc)) == sizeof(yes_type); }; } //namespace container_detail { #endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED //! <b>Remark</b>: Automatically detects whether T has a nested allocator_type that is convertible from //! Allocator. Meets the BinaryTypeTrait requirements ([meta.rqmts] 20.4.1). A program may //! specialize this type to define uses_allocator<X>::value as true for a T of user-defined type if T does not //! have a nested allocator_type but is nonetheless constructible using the specified Allocator where either: //! the first argument of a constructor has type allocator_arg_t and the second argument has type Alloc or //! the last argument of a constructor has type Alloc. //! //! <b>Result</b>: uses_allocator<T, Allocator>::value== true if a type T::allocator_type //! exists and either is_convertible<Alloc, T::allocator_type>::value != false or T::allocator_type //! is an alias `erased_type`. False otherwise. template <typename T, typename Allocator> struct uses_allocator : container_detail::uses_allocator_imp<T, Allocator> {}; }} //namespace boost::container #endif //BOOST_CONTAINER_USES_ALLOCATOR_HPP
2,549
4,261
/** * Copyright (c) 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #import <Foundation/Foundation.h> /** Defines an outgoing reference from Objective-C object. */ @protocol FBObjectReference <NSObject> /** What is the index of that reference in ivar layout? index * sizeof(void *) gives you offset from the beginning of the object. */ - (NSUInteger)indexInIvarLayout; /** For given object we need to be able to grab that object reference. */ - (nullable id)objectReferenceFromObject:(nullable id)object; /** For given reference in an object, there can be a path of names that leads to it. For example it can be an ivar, thus the path will consist of ivar name only: @[@"_myIvar"] But it also can be a reference in some nested struct like: struct SomeStruct { NSObject *myObject; }; If that struct will be used in class, then name path would look like this: @[@"_myIvar", @"SomeStruct", @"myObject"] */ - (nullable NSArray<NSString *> *)namePath; @end
330
333
package com.alipay.api.response; import com.alipay.api.internal.mapping.ApiField; import com.alipay.api.AlipayResponse; /** * ALIPAY API: mybank.finance.account.rysenterprise.query response. * * @author <NAME> * @since 1.0, 2021-07-14 10:10:20 */ public class MybankFinanceAccountRysenterpriseQueryResponse extends AlipayResponse { private static final long serialVersionUID = 1821977126393786259L; /** * 融易收账户Id */ @ApiField("account_no") private String accountNo; /** * 融易收账户可用余额 */ @ApiField("amount") private String amount; public void setAccountNo(String accountNo) { this.accountNo = accountNo; } public String getAccountNo( ) { return this.accountNo; } public void setAmount(String amount) { this.amount = amount; } public String getAmount( ) { return this.amount; } }
374
4,098
<filename>thirdparty/bullet/BulletCollision/BroadphaseCollision/btAxisSweep3.h //Bullet Continuous Collision Detection and Physics Library //Copyright (c) 2003-2006 <NAME> http://continuousphysics.com/Bullet/ // // btAxisSweep3.h // // Copyright (c) 2006 <NAME> // // This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source distribution. #ifndef BT_AXIS_SWEEP_3_H #define BT_AXIS_SWEEP_3_H #include "LinearMath/btVector3.h" #include "btOverlappingPairCache.h" #include "btBroadphaseInterface.h" #include "btBroadphaseProxy.h" #include "btOverlappingPairCallback.h" #include "btDbvtBroadphase.h" #include "btAxisSweep3Internal.h" /// The btAxisSweep3 is an efficient implementation of the 3d axis sweep and prune broadphase. /// It uses arrays rather then lists for storage of the 3 axis. Also it operates using 16 bit integer coordinates instead of floats. /// For large worlds and many objects, use bt32BitAxisSweep3 or btDbvtBroadphase instead. bt32BitAxisSweep3 has higher precision and allows more then 16384 objects at the cost of more memory and bit of performance. class btAxisSweep3 : public btAxisSweep3Internal<unsigned short int> { public: btAxisSweep3(const btVector3& worldAabbMin, const btVector3& worldAabbMax, unsigned short int maxHandles = 16384, btOverlappingPairCache* pairCache = 0, bool disableRaycastAccelerator = false); }; /// The bt32BitAxisSweep3 allows higher precision quantization and more objects compared to the btAxisSweep3 sweep and prune. /// This comes at the cost of more memory per handle, and a bit slower performance. /// It uses arrays rather then lists for storage of the 3 axis. class bt32BitAxisSweep3 : public btAxisSweep3Internal<unsigned int> { public: bt32BitAxisSweep3(const btVector3& worldAabbMin, const btVector3& worldAabbMax, unsigned int maxHandles = 1500000, btOverlappingPairCache* pairCache = 0, bool disableRaycastAccelerator = false); }; #endif
769
967
// // ECOCrashPlugin.h // EchoSDK // // Created by Lux on 2019/8/26. // #import "ECOBasePlugin.h" NS_ASSUME_NONNULL_BEGIN @interface ECOCrashPlugin : ECOBasePlugin @end NS_ASSUME_NONNULL_END
89
3,428
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef STDLIB_STRIDED_BASE_BINARY_H #define STDLIB_STRIDED_BASE_BINARY_H #include "binary/macros.h" #include "binary/typedefs.h" /* * The following is auto-generated. Do not manually edit. See scripts/loops.js. */ // BEGIN LOOPS #include "binary/bb_b.h" #include "binary/bb_c.h" #include "binary/bb_c_as_cc_c.h" #include "binary/bb_c_as_zz_z.h" #include "binary/bb_d.h" #include "binary/bb_d_as_dd_d.h" #include "binary/bb_f.h" #include "binary/bb_f_as_dd_d.h" #include "binary/bb_f_as_ff_f.h" #include "binary/bb_i.h" #include "binary/bb_i_as_ii_i.h" #include "binary/bb_k.h" #include "binary/bb_k_as_kk_k.h" #include "binary/bb_t.h" #include "binary/bb_t_as_tt_t.h" #include "binary/bb_u.h" #include "binary/bb_u_as_uu_u.h" #include "binary/bb_z.h" #include "binary/bb_z_as_zz_z.h" #include "binary/bc_c_as_cc_c.h" #include "binary/bc_c_as_zz_z.h" #include "binary/bc_z_as_zz_z.h" #include "binary/bd_d_as_dd_d.h" #include "binary/bd_z_as_zz_z.h" #include "binary/bf_c_as_cc_c.h" #include "binary/bf_c_as_zz_z.h" #include "binary/bf_d_as_dd_d.h" #include "binary/bf_f_as_dd_d.h" #include "binary/bf_f_as_ff_f.h" #include "binary/bf_z_as_zz_z.h" #include "binary/bi_d_as_dd_d.h" #include "binary/bi_i_as_ii_i.h" #include "binary/bi_z_as_zz_z.h" #include "binary/bk_c_as_cc_c.h" #include "binary/bk_c_as_zz_z.h" #include "binary/bk_d_as_dd_d.h" #include "binary/bk_f_as_dd_d.h" #include "binary/bk_f_as_ff_f.h" #include "binary/bk_i_as_ii_i.h" #include "binary/bk_k_as_kk_k.h" #include "binary/bk_z_as_zz_z.h" #include "binary/bs_c_as_cc_c.h" #include "binary/bs_c_as_zz_z.h" #include "binary/bs_d_as_dd_d.h" #include "binary/bs_f_as_dd_d.h" #include "binary/bs_f_as_ff_f.h" #include "binary/bs_i_as_ii_i.h" #include "binary/bs_k_as_kk_k.h" #include "binary/bs_z_as_zz_z.h" #include "binary/bt_c_as_cc_c.h" #include "binary/bt_c_as_zz_z.h" #include "binary/bt_d_as_dd_d.h" #include "binary/bt_f_as_dd_d.h" #include "binary/bt_f_as_ff_f.h" #include "binary/bt_i_as_ii_i.h" #include "binary/bt_t_as_tt_t.h" #include "binary/bt_u_as_uu_u.h" #include "binary/bt_z_as_zz_z.h" #include "binary/bu_d_as_dd_d.h" #include "binary/bu_u_as_uu_u.h" #include "binary/bu_z_as_zz_z.h" #include "binary/bz_z_as_zz_z.h" #include "binary/cb_c_as_cc_c.h" #include "binary/cb_c_as_zz_z.h" #include "binary/cb_z_as_zz_z.h" #include "binary/cc_c.h" #include "binary/cc_c_as_zz_z.h" #include "binary/cc_z.h" #include "binary/cc_z_as_zz_z.h" #include "binary/cd_z_as_zz_z.h" #include "binary/cf_c_as_cc_c.h" #include "binary/cf_c_as_zz_z.h" #include "binary/cf_z_as_zz_z.h" #include "binary/ci_z_as_zz_z.h" #include "binary/ck_c_as_cc_c.h" #include "binary/ck_c_as_zz_z.h" #include "binary/ck_z_as_zz_z.h" #include "binary/cs_c_as_cc_c.h" #include "binary/cs_c_as_zz_z.h" #include "binary/cs_z_as_zz_z.h" #include "binary/ct_c_as_cc_c.h" #include "binary/ct_c_as_zz_z.h" #include "binary/ct_z_as_zz_z.h" #include "binary/cu_z_as_zz_z.h" #include "binary/cz_z_as_zz_z.h" #include "binary/db_d_as_dd_d.h" #include "binary/db_z_as_zz_z.h" #include "binary/dc_z_as_zz_z.h" #include "binary/dd_d.h" #include "binary/dd_z.h" #include "binary/dd_z_as_zz_z.h" #include "binary/df_d_as_dd_d.h" #include "binary/df_z_as_zz_z.h" #include "binary/di_d_as_dd_d.h" #include "binary/di_z_as_zz_z.h" #include "binary/dk_d_as_dd_d.h" #include "binary/dk_z_as_zz_z.h" #include "binary/ds_d_as_dd_d.h" #include "binary/ds_z_as_zz_z.h" #include "binary/dt_d_as_dd_d.h" #include "binary/dt_z_as_zz_z.h" #include "binary/du_d_as_dd_d.h" #include "binary/du_z_as_zz_z.h" #include "binary/dz_z_as_zz_z.h" #include "binary/fb_c_as_cc_c.h" #include "binary/fb_c_as_zz_z.h" #include "binary/fb_d_as_dd_d.h" #include "binary/fb_f_as_dd_d.h" #include "binary/fb_f_as_ff_f.h" #include "binary/fb_z_as_zz_z.h" #include "binary/fc_c_as_cc_c.h" #include "binary/fc_c_as_zz_z.h" #include "binary/fc_z_as_zz_z.h" #include "binary/fd_d_as_dd_d.h" #include "binary/fd_z_as_zz_z.h" #include "binary/ff_c.h" #include "binary/ff_c_as_cc_c.h" #include "binary/ff_c_as_zz_z.h" #include "binary/ff_d.h" #include "binary/ff_d_as_dd_d.h" #include "binary/ff_f.h" #include "binary/ff_f_as_dd_d.h" #include "binary/ff_z.h" #include "binary/ff_z_as_zz_z.h" #include "binary/fi_d_as_dd_d.h" #include "binary/fi_z_as_zz_z.h" #include "binary/fk_c_as_cc_c.h" #include "binary/fk_c_as_zz_z.h" #include "binary/fk_d_as_dd_d.h" #include "binary/fk_f_as_dd_d.h" #include "binary/fk_f_as_ff_f.h" #include "binary/fk_z_as_zz_z.h" #include "binary/fs_c_as_cc_c.h" #include "binary/fs_c_as_zz_z.h" #include "binary/fs_d_as_dd_d.h" #include "binary/fs_f_as_dd_d.h" #include "binary/fs_f_as_ff_f.h" #include "binary/fs_z_as_zz_z.h" #include "binary/ft_c_as_cc_c.h" #include "binary/ft_c_as_zz_z.h" #include "binary/ft_d_as_dd_d.h" #include "binary/ft_f_as_dd_d.h" #include "binary/ft_f_as_ff_f.h" #include "binary/ft_z_as_zz_z.h" #include "binary/fu_d_as_dd_d.h" #include "binary/fu_z_as_zz_z.h" #include "binary/fz_z_as_zz_z.h" #include "binary/ib_d_as_dd_d.h" #include "binary/ib_i_as_ii_i.h" #include "binary/ib_z_as_zz_z.h" #include "binary/ic_z_as_zz_z.h" #include "binary/id_d_as_dd_d.h" #include "binary/id_z_as_zz_z.h" #include "binary/if_d_as_dd_d.h" #include "binary/if_z_as_zz_z.h" #include "binary/ii_d.h" #include "binary/ii_d_as_dd_d.h" #include "binary/ii_i.h" #include "binary/ii_z.h" #include "binary/ii_z_as_zz_z.h" #include "binary/ik_d_as_dd_d.h" #include "binary/ik_i_as_ii_i.h" #include "binary/ik_z_as_zz_z.h" #include "binary/is_d_as_dd_d.h" #include "binary/is_i_as_ii_i.h" #include "binary/is_z_as_zz_z.h" #include "binary/it_d_as_dd_d.h" #include "binary/it_i_as_ii_i.h" #include "binary/it_z_as_zz_z.h" #include "binary/iu_d_as_dd_d.h" #include "binary/iu_z_as_zz_z.h" #include "binary/iz_z_as_zz_z.h" #include "binary/kb_c_as_cc_c.h" #include "binary/kb_c_as_zz_z.h" #include "binary/kb_d_as_dd_d.h" #include "binary/kb_f_as_dd_d.h" #include "binary/kb_f_as_ff_f.h" #include "binary/kb_i_as_ii_i.h" #include "binary/kb_k_as_kk_k.h" #include "binary/kb_z_as_zz_z.h" #include "binary/kc_c_as_cc_c.h" #include "binary/kc_c_as_zz_z.h" #include "binary/kc_z_as_zz_z.h" #include "binary/kd_d_as_dd_d.h" #include "binary/kd_z_as_zz_z.h" #include "binary/kf_c_as_cc_c.h" #include "binary/kf_c_as_zz_z.h" #include "binary/kf_d_as_dd_d.h" #include "binary/kf_f_as_dd_d.h" #include "binary/kf_f_as_ff_f.h" #include "binary/kf_z_as_zz_z.h" #include "binary/ki_d_as_dd_d.h" #include "binary/ki_i_as_ii_i.h" #include "binary/ki_z_as_zz_z.h" #include "binary/kk_c.h" #include "binary/kk_c_as_cc_c.h" #include "binary/kk_c_as_zz_z.h" #include "binary/kk_d.h" #include "binary/kk_d_as_dd_d.h" #include "binary/kk_f.h" #include "binary/kk_f_as_dd_d.h" #include "binary/kk_f_as_ff_f.h" #include "binary/kk_i.h" #include "binary/kk_i_as_ii_i.h" #include "binary/kk_k.h" #include "binary/kk_z.h" #include "binary/kk_z_as_zz_z.h" #include "binary/ks_c_as_cc_c.h" #include "binary/ks_c_as_zz_z.h" #include "binary/ks_d_as_dd_d.h" #include "binary/ks_f_as_dd_d.h" #include "binary/ks_f_as_ff_f.h" #include "binary/ks_i_as_ii_i.h" #include "binary/ks_k_as_kk_k.h" #include "binary/ks_z_as_zz_z.h" #include "binary/kt_d_as_dd_d.h" #include "binary/kt_i_as_ii_i.h" #include "binary/kt_z_as_zz_z.h" #include "binary/ku_d_as_dd_d.h" #include "binary/ku_z_as_zz_z.h" #include "binary/kz_z_as_zz_z.h" #include "binary/sb_c_as_cc_c.h" #include "binary/sb_c_as_zz_z.h" #include "binary/sb_d_as_dd_d.h" #include "binary/sb_f_as_dd_d.h" #include "binary/sb_f_as_ff_f.h" #include "binary/sb_i_as_ii_i.h" #include "binary/sb_k_as_kk_k.h" #include "binary/sb_z_as_zz_z.h" #include "binary/sc_c_as_cc_c.h" #include "binary/sc_c_as_zz_z.h" #include "binary/sc_z_as_zz_z.h" #include "binary/sd_d_as_dd_d.h" #include "binary/sd_z_as_zz_z.h" #include "binary/sf_c_as_cc_c.h" #include "binary/sf_c_as_zz_z.h" #include "binary/sf_d_as_dd_d.h" #include "binary/sf_f_as_dd_d.h" #include "binary/sf_f_as_ff_f.h" #include "binary/sf_z_as_zz_z.h" #include "binary/si_d_as_dd_d.h" #include "binary/si_i_as_ii_i.h" #include "binary/si_z_as_zz_z.h" #include "binary/sk_c_as_cc_c.h" #include "binary/sk_c_as_zz_z.h" #include "binary/sk_d_as_dd_d.h" #include "binary/sk_f_as_dd_d.h" #include "binary/sk_f_as_ff_f.h" #include "binary/sk_i_as_ii_i.h" #include "binary/sk_k_as_kk_k.h" #include "binary/sk_z_as_zz_z.h" #include "binary/ss_c.h" #include "binary/ss_c_as_cc_c.h" #include "binary/ss_c_as_zz_z.h" #include "binary/ss_d.h" #include "binary/ss_d_as_dd_d.h" #include "binary/ss_f.h" #include "binary/ss_f_as_dd_d.h" #include "binary/ss_f_as_ff_f.h" #include "binary/ss_i.h" #include "binary/ss_i_as_ii_i.h" #include "binary/ss_k.h" #include "binary/ss_k_as_kk_k.h" #include "binary/ss_s.h" #include "binary/ss_z.h" #include "binary/ss_z_as_zz_z.h" #include "binary/st_d_as_dd_d.h" #include "binary/st_i_as_ii_i.h" #include "binary/st_z_as_zz_z.h" #include "binary/su_d_as_dd_d.h" #include "binary/su_z_as_zz_z.h" #include "binary/sz_z_as_zz_z.h" #include "binary/tb_c_as_cc_c.h" #include "binary/tb_c_as_zz_z.h" #include "binary/tb_d_as_dd_d.h" #include "binary/tb_f_as_dd_d.h" #include "binary/tb_f_as_ff_f.h" #include "binary/tb_i_as_ii_i.h" #include "binary/tb_t_as_tt_t.h" #include "binary/tb_u_as_uu_u.h" #include "binary/tb_z_as_zz_z.h" #include "binary/tc_c_as_cc_c.h" #include "binary/tc_c_as_zz_z.h" #include "binary/tc_z_as_zz_z.h" #include "binary/td_d_as_dd_d.h" #include "binary/td_z_as_zz_z.h" #include "binary/tf_c_as_cc_c.h" #include "binary/tf_c_as_zz_z.h" #include "binary/tf_d_as_dd_d.h" #include "binary/tf_f_as_dd_d.h" #include "binary/tf_f_as_ff_f.h" #include "binary/tf_z_as_zz_z.h" #include "binary/ti_d_as_dd_d.h" #include "binary/ti_i_as_ii_i.h" #include "binary/ti_z_as_zz_z.h" #include "binary/tk_d_as_dd_d.h" #include "binary/tk_i_as_ii_i.h" #include "binary/tk_z_as_zz_z.h" #include "binary/ts_d_as_dd_d.h" #include "binary/ts_i_as_ii_i.h" #include "binary/ts_z_as_zz_z.h" #include "binary/tt_c.h" #include "binary/tt_c_as_cc_c.h" #include "binary/tt_c_as_zz_z.h" #include "binary/tt_d.h" #include "binary/tt_d_as_dd_d.h" #include "binary/tt_f.h" #include "binary/tt_f_as_dd_d.h" #include "binary/tt_f_as_ff_f.h" #include "binary/tt_i.h" #include "binary/tt_i_as_ii_i.h" #include "binary/tt_t.h" #include "binary/tt_u.h" #include "binary/tt_u_as_uu_u.h" #include "binary/tt_z.h" #include "binary/tt_z_as_zz_z.h" #include "binary/tu_d_as_dd_d.h" #include "binary/tu_u_as_uu_u.h" #include "binary/tu_z_as_zz_z.h" #include "binary/tz_z_as_zz_z.h" #include "binary/ub_d_as_dd_d.h" #include "binary/ub_u_as_uu_u.h" #include "binary/ub_z_as_zz_z.h" #include "binary/uc_z_as_zz_z.h" #include "binary/ud_d_as_dd_d.h" #include "binary/ud_z_as_zz_z.h" #include "binary/uf_d_as_dd_d.h" #include "binary/uf_z_as_zz_z.h" #include "binary/ui_d_as_dd_d.h" #include "binary/ui_z_as_zz_z.h" #include "binary/uk_d_as_dd_d.h" #include "binary/uk_z_as_zz_z.h" #include "binary/us_d_as_dd_d.h" #include "binary/us_z_as_zz_z.h" #include "binary/ut_d_as_dd_d.h" #include "binary/ut_u_as_uu_u.h" #include "binary/ut_z_as_zz_z.h" #include "binary/uu_d.h" #include "binary/uu_d_as_dd_d.h" #include "binary/uu_u.h" #include "binary/uu_z.h" #include "binary/uu_z_as_zz_z.h" #include "binary/uz_z_as_zz_z.h" #include "binary/zb_z_as_zz_z.h" #include "binary/zc_z_as_zz_z.h" #include "binary/zd_z_as_zz_z.h" #include "binary/zf_z_as_zz_z.h" #include "binary/zi_z_as_zz_z.h" #include "binary/zk_z_as_zz_z.h" #include "binary/zs_z_as_zz_z.h" #include "binary/zt_z_as_zz_z.h" #include "binary/zu_z_as_zz_z.h" #include "binary/zz_z.h" // END LOOPS #endif // !STDLIB_STRIDED_BASE_BINARY_H
6,440
4,140
<filename>shims/common/src/main/java/org/apache/hadoop/fs/ProxyLocalFileSystem.java /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.fs; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.net.URI; import java.security.MessageDigest; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.util.Shell; import org.apache.hadoop.hive.shims.ShimLoader; import org.apache.hadoop.io.MD5Hash; /**************************************************************** * A Proxy for LocalFileSystem * * As an example, it serves uri's corresponding to: 'pfile:///' namespace with using a * LocalFileSystem *****************************************************************/ public class ProxyLocalFileSystem extends FilterFileSystem { protected LocalFileSystem localFs; /** * URI scheme */ private String scheme; public ProxyLocalFileSystem() { localFs = new LocalFileSystem(); } public ProxyLocalFileSystem(FileSystem fs) { throw new RuntimeException("Unsupported Constructor"); } @Override public void initialize(URI name, Configuration conf) throws IOException { // create a proxy for the local filesystem // the scheme/authority serving as the proxy is derived // from the supplied URI this.scheme = name.getScheme(); String authority = name.getAuthority() != null ? name.getAuthority() : ""; String proxyUriString = scheme + "://" + authority + "/"; fs = ShimLoader.getHadoopShims().createProxyFileSystem(localFs, URI.create(proxyUriString)); fs.initialize(name, conf); } @Override public String getScheme() { return scheme; } @Override // For pfile, calculate the checksum for use in testing public FileChecksum getFileChecksum(Path f) throws IOException { if (scheme.equalsIgnoreCase("pfile") && fs.isFile(f)) { return getPFileChecksum(f); } return fs.getFileChecksum(f); } private FileChecksum getPFileChecksum(Path f) throws IOException { MessageDigest md5Digest; try { md5Digest = MessageDigest.getInstance("MD5"); MD5Hash md5Hash = new MD5Hash(getMD5Checksum(fs.open(f))); return new PFileChecksum(md5Hash, md5Digest.getAlgorithm()); } catch (Exception e) { throw new IOException(e); } } /** * Calculate MD5 checksum from data in FSDataInputStream * @param fsInputStream * @return byte array with md5 checksum bytes * @throws Exception */ static byte[] getMD5Checksum(FSDataInputStream fsInputStream) throws Exception { byte[] buffer = new byte[1024]; MessageDigest md5Digest = MessageDigest.getInstance("MD5"); int numRead = 0; while (numRead != -1) { numRead = fsInputStream.read(buffer); if (numRead > 0) { md5Digest.update(buffer, 0, numRead); } } fsInputStream.close(); return md5Digest.digest(); } /** * Checksum implementation for PFile uses in testing */ public static class PFileChecksum extends FileChecksum { private MD5Hash md5; private String algorithmName; public PFileChecksum(MD5Hash md5, String algorithmName) { this.md5 = md5; this.algorithmName = algorithmName; } @Override public void write(DataOutput out) throws IOException { md5.write(out); } @Override public void readFields(DataInput in) throws IOException { md5.readFields(in); } @Override public String getAlgorithmName() { return algorithmName; } @Override public int getLength() { if (md5 != null) { return md5.getDigest().length; } return 0; } @Override public byte[] getBytes() { if (md5 != null) { return md5.getDigest(); } return new byte[0]; } } }
1,538
317
package com.googlecode.totallylazy.iterators; import java.util.Iterator; import java.util.NoSuchElementException; public class TakeIterator<T> extends ReadOnlyIterator<T> { private final Iterator<? extends T> iterator; private int count; public TakeIterator(Iterator<? extends T> iterator, int count) { this.iterator = iterator; this.count = count; } @Override public boolean hasNext() { return count > 0 && iterator.hasNext(); } @Override public T next() { if(hasNext()) { count--; return iterator.next(); } throw new NoSuchElementException(); } }
257
331
<filename>models/resnet.py #!/usr/bin/env python # -*- coding: utf-8 -*- import os import shutil from chainer.dataset import download from chainer.links.model.vision import resnet class ResNet(resnet.ResNetLayers): URLS = { 'resnet50': 'https://www.dropbox.com/s/f0sqe7za120msbs/' 'ResNet-50-model.caffemodel?dl=1', 'resnet101': 'https://www.dropbox.com/s/iesj1vpu440mju1/' 'ResNet-101-model.caffemodel?dl=1', 'resnet152': 'https://www.dropbox.com/s/fhmfc4x741iff6i/' 'ResNet-152-model.caffemodel?dl=1', } def __init__(self, n_layers): root = download.get_dataset_directory('pfnet/chainer/models/') caffemodel_path = os.path.join( root, 'ResNet-{}-model.caffemodel'.format(n_layers)) if not os.path.exists(caffemodel_path): if n_layers == 50: cache_path = download.cached_download(self.URLS['resnet50']) elif n_layers == 101: cache_path = download.cached_download(self.URLS['resnet101']) elif n_layers == 152: cache_path = download.cached_download(self.URLS['resnet152']) shutil.move(cache_path, caffemodel_path) super(ResNet, self).__init__( os.path.basename(caffemodel_path), n_layers=n_layers) self._children.remove('fc6') del self.fc6 del self.functions['fc6'] del self.functions['prob'] self.train = True def __call__(self, x): return super(ResNet, self).__call__( x, ['res5'], not self.train)['res5'] if __name__ == '__main__': model = ResNet(50) model.train = False import numpy as np x = np.zeros((1, 3, 224, 224), dtype=np.float32) y = model(x) print(y.shape)
930
613
<reponame>valli-dr/spring-cloud-aws /* * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://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. */ package org.springframework.cloud.aws.jdbc.config.xml; import java.util.List; import com.amazonaws.services.rds.AmazonRDS; import com.amazonaws.services.rds.AmazonRDSClient; import org.aopalliance.intercept.MethodInterceptor; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.RuntimeBeanReference; import org.springframework.cloud.aws.core.config.AmazonWebserviceClientConfigurationUtils; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.test.util.ReflectionTestUtils; import static org.assertj.core.api.Assertions.assertThat; /** * @author <NAME> */ public class AmazonRdsRetryInterceptorBeanDefinitionParserTest { @Test public void parseInternal_minimalConfiguration_createsRetryInterceptor() throws Exception { // Arrange ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext( getClass().getSimpleName() + "-minimal.xml", getClass()); // Act MethodInterceptor interceptor = classPathXmlApplicationContext.getBean(MethodInterceptor.class); // Assert assertThat(interceptor).isNotNull(); } @Test public void parseInternal_customRegionConfigured_createsAmazonRdsClientWithCustomRegionConfigured() throws Exception { // Arrange ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext( getClass().getSimpleName() + "-customRegion.xml", getClass()); // Act AmazonRDS amazonRDS = classPathXmlApplicationContext.getBean(AmazonRDS.class); // Assert assertThat(ReflectionTestUtils.getField(amazonRDS, "endpoint").toString()) .isEqualTo("https://rds.eu-west-1.amazonaws.com"); } @Test public void parseInternal_customRegionProviderConfigured_createAmazonRdsClientWithCustomRegionConfigured() throws Exception { // Arrange ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext( getClass().getSimpleName() + "-customRegionProvider.xml", getClass()); // Act AmazonRDS amazonRDS = classPathXmlApplicationContext.getBean(AmazonRDS.class); // Assert assertThat(ReflectionTestUtils.getField(amazonRDS, "endpoint").toString()) .isEqualTo("https://rds.eu-west-1.amazonaws.com"); } @Test public void parseInternal_customRDsClientConfigured_createInterceptorWithCustomRdsClient() throws Exception { // Arrange ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext( getClass().getSimpleName() + "-customRdsClient.xml", getClass()); // Act classPathXmlApplicationContext.getBean(MethodInterceptor.class); // Assert assertThat(classPathXmlApplicationContext .containsBean(AmazonWebserviceClientConfigurationUtils.getBeanName(AmazonRDSClient.class.getName()))) .isFalse(); } @Test public void parseInternal_customBackOffPolicy_createInterceptorWithCustomBackOffPolicy() throws Exception { // Arrange ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext( getClass().getSimpleName() + "-customBackOffPolicy.xml", getClass()); BeanDefinition beanDefinition = classPathXmlApplicationContext.getBeanFactory() .getBeanDefinition("interceptor"); // Act BeanDefinition retryOperations = (BeanDefinition) beanDefinition.getPropertyValues() .getPropertyValue("retryOperations").getValue(); // Assert assertThat(((RuntimeBeanReference) retryOperations.getPropertyValues().getPropertyValue("backOffPolicy") .getValue()).getBeanName()).isEqualTo("policy"); } @Test public void parseInternal_customNumberOfRetiresConfigured_createRetryPolicyWithCustomNumberOfRetriesConfigured() throws Exception { // Arrange ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext( getClass().getSimpleName() + "-maxNumberOfRetries.xml", getClass()); // Act BeanDefinition beanDefinition = classPathXmlApplicationContext.getBeanFactory() .getBeanDefinition("interceptor"); // Assert BeanDefinition retryOperations = (BeanDefinition) beanDefinition.getPropertyValues() .getPropertyValue("retryOperations").getValue(); BeanDefinition compositeRetryPolicy = (BeanDefinition) retryOperations.getPropertyValues() .getPropertyValue("retryPolicy").getValue(); @SuppressWarnings("unchecked") List<BeanDefinition> policies = (List<BeanDefinition>) compositeRetryPolicy.getPropertyValues() .getPropertyValue("policies").getValue(); BeanDefinition sqlPolicy = policies.get(1); assertThat(sqlPolicy.getPropertyValues().getPropertyValue("maxNumberOfRetries").getValue().toString()) .isEqualTo("4"); } }
1,657
3,372
/* * Copyright 2016-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" 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. */ package com.amazonaws.services.globalaccelerator.model; import java.io.Serializable; import javax.annotation.Generated; /** * * @see <a * href="http://docs.aws.amazon.com/goto/WebAPI/globalaccelerator-2018-08-08/ListCustomRoutingPortMappingsByDestination" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ListCustomRoutingPortMappingsByDestinationResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * <p> * The port mappings for the endpoint IP address that you specified in the request. * </p> */ private java.util.List<DestinationPortMapping> destinationPortMappings; /** * <p> * The token for the next set of results. You receive this token from a previous call. * </p> */ private String nextToken; /** * <p> * The port mappings for the endpoint IP address that you specified in the request. * </p> * * @return The port mappings for the endpoint IP address that you specified in the request. */ public java.util.List<DestinationPortMapping> getDestinationPortMappings() { return destinationPortMappings; } /** * <p> * The port mappings for the endpoint IP address that you specified in the request. * </p> * * @param destinationPortMappings * The port mappings for the endpoint IP address that you specified in the request. */ public void setDestinationPortMappings(java.util.Collection<DestinationPortMapping> destinationPortMappings) { if (destinationPortMappings == null) { this.destinationPortMappings = null; return; } this.destinationPortMappings = new java.util.ArrayList<DestinationPortMapping>(destinationPortMappings); } /** * <p> * The port mappings for the endpoint IP address that you specified in the request. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setDestinationPortMappings(java.util.Collection)} or * {@link #withDestinationPortMappings(java.util.Collection)} if you want to override the existing values. * </p> * * @param destinationPortMappings * The port mappings for the endpoint IP address that you specified in the request. * @return Returns a reference to this object so that method calls can be chained together. */ public ListCustomRoutingPortMappingsByDestinationResult withDestinationPortMappings(DestinationPortMapping... destinationPortMappings) { if (this.destinationPortMappings == null) { setDestinationPortMappings(new java.util.ArrayList<DestinationPortMapping>(destinationPortMappings.length)); } for (DestinationPortMapping ele : destinationPortMappings) { this.destinationPortMappings.add(ele); } return this; } /** * <p> * The port mappings for the endpoint IP address that you specified in the request. * </p> * * @param destinationPortMappings * The port mappings for the endpoint IP address that you specified in the request. * @return Returns a reference to this object so that method calls can be chained together. */ public ListCustomRoutingPortMappingsByDestinationResult withDestinationPortMappings(java.util.Collection<DestinationPortMapping> destinationPortMappings) { setDestinationPortMappings(destinationPortMappings); return this; } /** * <p> * The token for the next set of results. You receive this token from a previous call. * </p> * * @param nextToken * The token for the next set of results. You receive this token from a previous call. */ public void setNextToken(String nextToken) { this.nextToken = nextToken; } /** * <p> * The token for the next set of results. You receive this token from a previous call. * </p> * * @return The token for the next set of results. You receive this token from a previous call. */ public String getNextToken() { return this.nextToken; } /** * <p> * The token for the next set of results. You receive this token from a previous call. * </p> * * @param nextToken * The token for the next set of results. You receive this token from a previous call. * @return Returns a reference to this object so that method calls can be chained together. */ public ListCustomRoutingPortMappingsByDestinationResult withNextToken(String nextToken) { setNextToken(nextToken); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getDestinationPortMappings() != null) sb.append("DestinationPortMappings: ").append(getDestinationPortMappings()).append(","); if (getNextToken() != null) sb.append("NextToken: ").append(getNextToken()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ListCustomRoutingPortMappingsByDestinationResult == false) return false; ListCustomRoutingPortMappingsByDestinationResult other = (ListCustomRoutingPortMappingsByDestinationResult) obj; if (other.getDestinationPortMappings() == null ^ this.getDestinationPortMappings() == null) return false; if (other.getDestinationPortMappings() != null && other.getDestinationPortMappings().equals(this.getDestinationPortMappings()) == false) return false; if (other.getNextToken() == null ^ this.getNextToken() == null) return false; if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getDestinationPortMappings() == null) ? 0 : getDestinationPortMappings().hashCode()); hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode()); return hashCode; } @Override public ListCustomRoutingPortMappingsByDestinationResult clone() { try { return (ListCustomRoutingPortMappingsByDestinationResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
2,807
611
<reponame>ste93cry/idea-php-symfony2-plugin<gh_stars>100-1000 package fr.adrienbrault.idea.symfony2plugin.util; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; /** * All project related function */ public class ProjectUtil { /** * Single project usage is deprecated which wraps the single project resolving * * RootManager should be taken as is module based and allows more then one root; for now change all is too much * You should provide a file context, with this help we can search for in which root its given; see replacement function */ public static VirtualFile getProjectDir(@NotNull Project project) { return project.getBaseDir(); } /** * This function should be use as a replaced, with given a context we know a possible project root */ public static VirtualFile getProjectDir(@NotNull PsiElement context) { return getProjectDir(context.getProject()); } }
342
4,081
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the "License"). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio.master; import alluxio.ClientContext; import com.google.common.base.Preconditions; /** * This class can be used to obtain instances of a {@link MasterClientContext}. This is the * preferred method of creating master client configurations. */ public class MasterClientContextBuilder { protected ClientContext mContext; protected MasterInquireClient mMasterInquireClient; /** * Create an instance of a {@link MasterClientContextBuilder}. * * @param ctx The {@link ClientContext} to base the configuration on */ public MasterClientContextBuilder(ClientContext ctx) { mContext = Preconditions.checkNotNull(ctx, "ctx"); } /** * Set the {@link MasterInquireClient} that the config will use. * * @param masterInquireClient the master inquire client * @return the builder */ public MasterClientContextBuilder setMasterInquireClient( MasterInquireClient masterInquireClient) { mMasterInquireClient = masterInquireClient; return this; } /** * @return an instance of {@link MasterClientContext} */ public MasterClientContext build() { if (mMasterInquireClient == null) { mMasterInquireClient = MasterInquireClient.Factory.create(mContext.getClusterConf(), mContext.getUserState()); } return new MasterClientContext(mContext, mMasterInquireClient); } }
542
2,073
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq; import org.apache.activemq.broker.jmx.ManagementContext; import org.apache.activemq.util.DefaultTestAppender; import org.apache.activemq.util.Wait; import org.apache.log4j.Appender; import org.apache.log4j.spi.LoggingEvent; import org.junit.*; import static org.junit.Assert.assertFalse; import java.util.concurrent.*; import org.apache.activemq.broker.BrokerService; import javax.management.JMException; import javax.management.ObjectName; public class TcpTransportCloseConnectionTest { static boolean transportConnectionFailed = false; private BrokerService broker; private final String uri = "tcp://localhost:0?wireFormat.maxInactivityDuration=500"; static final Appender appender = new DefaultTestAppender() { @Override public void doAppend(LoggingEvent event) { if(event.getMessage().toString().contains("Transport Connection") && event.getMessage().toString().contains("failed") && (event.getMessage().toString().contains("java.net.SocketException") || event.getMessage().toString().contains("java.io.EOFException"))) { transportConnectionFailed = true; } } }; class CustomManagementContext extends ManagementContext { @Override public void unregisterMBean(ObjectName name) throws JMException { try { //Sleep for a second to emulate the MBean server being hung up of an unregister MBean call. TimeUnit.SECONDS.sleep(1); } catch(Throwable t) { } super.unregisterMBean(name); } } @BeforeClass public static void setUp() throws Exception { org.apache.log4j.Logger.getRootLogger().addAppender(appender); } @AfterClass public static void setDown() throws Exception { org.apache.log4j.Logger.getRootLogger().removeAppender(appender); } @Before public void startBroker() throws Exception { broker = new BrokerService(); broker.setPersistent(false); broker.addConnector(uri); ManagementContext customManagementContext = new CustomManagementContext(); broker.setManagementContext(customManagementContext); broker.start(); } @After public void tearDown() throws Exception { if (broker != null) { broker.stop(); broker.waitUntilStopped(); } } @Test public void tesCloseConnectionTest() throws Exception { final ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(broker.getDefaultSocketURIString()); activeMQConnectionFactory.setWatchTopicAdvisories(false); ActiveMQConnection connection = (ActiveMQConnection) activeMQConnectionFactory.createConnection(); connection.start(); connection.close(); assertFalse("The Transport has not failed", Wait.waitFor(new Wait.Condition() { @Override public boolean isSatisified() throws Exception { return transportConnectionFailed; } }, 2 * 1000)); } }
1,413
362
<reponame>hsiangawang/whois<filename>whois-update/src/main/java/net/ripe/db/whois/update/handler/validator/organisation/CountryRipeMaintainedValidator.java<gh_stars>100-1000 package net.ripe.db.whois.update.handler.validator.organisation; import com.google.common.collect.ImmutableList; import net.ripe.db.whois.common.rpsl.ObjectType; import net.ripe.db.whois.common.rpsl.RpslObject; import net.ripe.db.whois.update.authentication.Principal; import net.ripe.db.whois.update.authentication.Subject; import net.ripe.db.whois.update.domain.Action; import net.ripe.db.whois.update.domain.PreparedUpdate; import net.ripe.db.whois.update.domain.UpdateContext; import net.ripe.db.whois.update.domain.UpdateMessages; import net.ripe.db.whois.update.handler.validator.BusinessRuleValidator; import org.springframework.stereotype.Component; import static net.ripe.db.whois.common.rpsl.AttributeType.COUNTRY; import static net.ripe.db.whois.common.rpsl.ObjectType.ORGANISATION; import static net.ripe.db.whois.update.domain.Action.CREATE; import static net.ripe.db.whois.update.domain.Action.MODIFY; @Component public class CountryRipeMaintainedValidator implements BusinessRuleValidator { private static final ImmutableList<Action> ACTIONS = ImmutableList.of(CREATE, MODIFY); private static final ImmutableList<ObjectType> TYPES = ImmutableList.of(ORGANISATION); @Override public void validate(final PreparedUpdate update, final UpdateContext updateContext) { final Subject subject = updateContext.getSubject(update); if (subject.hasPrincipal(Principal.OVERRIDE_MAINTAINER) || subject.hasPrincipal(Principal.RS_MAINTAINER)) { return; } final RpslObject originalObject = update.getReferenceObject(); final RpslObject updatedObject = update.getUpdatedObject(); if (hasCountryChanged(originalObject, updatedObject, update.getAction())) { updateContext.addMessage(update, UpdateMessages.canOnlyBeChangedByRipeNCC(COUNTRY)); } } private boolean hasCountryChanged(final RpslObject originalObject, final RpslObject updatedObject, final Action action) { return (action == CREATE && updatedObject.containsAttribute(COUNTRY)) || // create (originalObject.containsAttribute(COUNTRY) && updatedObject.containsAttribute(COUNTRY) && !originalObject.getValuesForAttribute(COUNTRY).equals(updatedObject.getValuesForAttribute(COUNTRY))) || // modify country (originalObject.containsAttribute(COUNTRY) && !updatedObject.containsAttribute(COUNTRY)) || // remove country (!originalObject.containsAttribute(COUNTRY) && updatedObject.containsAttribute(COUNTRY)); // add country } @Override public ImmutableList<Action> getActions() { return ACTIONS; } @Override public ImmutableList<ObjectType> getTypes() { return TYPES; } }
1,038
561
import math import torch from torch import nn from torch.nn import Parameter, Linear from modules.commons.layers import LayerNorm, Embedding from utils.nn.seq_utils import get_incremental_state, set_incremental_state, softmax, make_positions import torch.nn.functional as F DEFAULT_MAX_SOURCE_POSITIONS = 2000 DEFAULT_MAX_TARGET_POSITIONS = 2000 class SinusoidalPositionalEmbedding(nn.Module): """This module produces sinusoidal positional embeddings of any length. Padding symbols are ignored. """ def __init__(self, embedding_dim, padding_idx, init_size=1024): super().__init__() self.embedding_dim = embedding_dim self.padding_idx = padding_idx self.weights = SinusoidalPositionalEmbedding.get_embedding( init_size, embedding_dim, padding_idx, ) self.register_buffer('_float_tensor', torch.FloatTensor(1)) @staticmethod def get_embedding(num_embeddings, embedding_dim, padding_idx=None): """Build sinusoidal embeddings. This matches the implementation in tensor2tensor, but differs slightly from the description in Section 3.5 of "Attention Is All You Need". """ half_dim = embedding_dim // 2 emb = math.log(10000) / (half_dim - 1) emb = torch.exp(torch.arange(half_dim, dtype=torch.float) * -emb) emb = torch.arange(num_embeddings, dtype=torch.float).unsqueeze(1) * emb.unsqueeze(0) emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1).view(num_embeddings, -1) if embedding_dim % 2 == 1: # zero pad emb = torch.cat([emb, torch.zeros(num_embeddings, 1)], dim=1) if padding_idx is not None: emb[padding_idx, :] = 0 return emb def forward(self, input, incremental_state=None, timestep=None, positions=None, **kwargs): """Input is expected to be of size [bsz x seqlen].""" bsz, seq_len = input.shape[:2] max_pos = self.padding_idx + 1 + seq_len if self.weights is None or max_pos > self.weights.size(0): # recompute/expand embeddings if needed self.weights = SinusoidalPositionalEmbedding.get_embedding( max_pos, self.embedding_dim, self.padding_idx, ) self.weights = self.weights.to(self._float_tensor) if incremental_state is not None: # positions is the same for every token when decoding a single step pos = timestep.view(-1)[0] + 1 if timestep is not None else seq_len return self.weights[self.padding_idx + pos, :].expand(bsz, 1, -1) positions = make_positions(input, self.padding_idx) if positions is None else positions return self.weights.index_select(0, positions.view(-1)).view(bsz, seq_len, -1).detach() def max_positions(self): """Maximum number of supported positions.""" return int(1e5) # an arbitrary large number class TransformerFFNLayer(nn.Module): def __init__(self, hidden_size, filter_size, padding="SAME", kernel_size=1, dropout=0., act='gelu'): super().__init__() self.kernel_size = kernel_size self.dropout = dropout self.act = act if padding == 'SAME': self.ffn_1 = nn.Conv1d(hidden_size, filter_size, kernel_size, padding=kernel_size // 2) elif padding == 'LEFT': self.ffn_1 = nn.Sequential( nn.ConstantPad1d((kernel_size - 1, 0), 0.0), nn.Conv1d(hidden_size, filter_size, kernel_size) ) self.ffn_2 = Linear(filter_size, hidden_size) def forward(self, x, incremental_state=None): # x: T x B x C if incremental_state is not None: saved_state = self._get_input_buffer(incremental_state) if 'prev_input' in saved_state: prev_input = saved_state['prev_input'] x = torch.cat((prev_input, x), dim=0) x = x[-self.kernel_size:] saved_state['prev_input'] = x self._set_input_buffer(incremental_state, saved_state) x = self.ffn_1(x.permute(1, 2, 0)).permute(2, 0, 1) x = x * self.kernel_size ** -0.5 if incremental_state is not None: x = x[-1:] if self.act == 'gelu': x = F.gelu(x) if self.act == 'relu': x = F.relu(x) x = F.dropout(x, self.dropout, training=self.training) x = self.ffn_2(x) return x def _get_input_buffer(self, incremental_state): return get_incremental_state( self, incremental_state, 'f', ) or {} def _set_input_buffer(self, incremental_state, buffer): set_incremental_state( self, incremental_state, 'f', buffer, ) def clear_buffer(self, incremental_state): if incremental_state is not None: saved_state = self._get_input_buffer(incremental_state) if 'prev_input' in saved_state: del saved_state['prev_input'] self._set_input_buffer(incremental_state, saved_state) class MultiheadAttention(nn.Module): def __init__(self, embed_dim, num_heads, kdim=None, vdim=None, dropout=0., bias=True, add_bias_kv=False, add_zero_attn=False, self_attention=False, encoder_decoder_attention=False): super().__init__() self.embed_dim = embed_dim self.kdim = kdim if kdim is not None else embed_dim self.vdim = vdim if vdim is not None else embed_dim self.qkv_same_dim = self.kdim == embed_dim and self.vdim == embed_dim self.num_heads = num_heads self.dropout = dropout self.head_dim = embed_dim // num_heads assert self.head_dim * num_heads == self.embed_dim, "embed_dim must be divisible by num_heads" self.scaling = self.head_dim ** -0.5 self.self_attention = self_attention self.encoder_decoder_attention = encoder_decoder_attention assert not self.self_attention or self.qkv_same_dim, 'Self-attention requires query, key and ' \ 'value to be of the same size' if self.qkv_same_dim: self.in_proj_weight = Parameter(torch.Tensor(3 * embed_dim, embed_dim)) else: self.k_proj_weight = Parameter(torch.Tensor(embed_dim, self.kdim)) self.v_proj_weight = Parameter(torch.Tensor(embed_dim, self.vdim)) self.q_proj_weight = Parameter(torch.Tensor(embed_dim, embed_dim)) if bias: self.in_proj_bias = Parameter(torch.Tensor(3 * embed_dim)) else: self.register_parameter('in_proj_bias', None) self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias) if add_bias_kv: self.bias_k = Parameter(torch.Tensor(1, 1, embed_dim)) self.bias_v = Parameter(torch.Tensor(1, 1, embed_dim)) else: self.bias_k = self.bias_v = None self.add_zero_attn = add_zero_attn self.reset_parameters() self.enable_torch_version = False if hasattr(F, "multi_head_attention_forward"): self.enable_torch_version = True else: self.enable_torch_version = False self.last_attn_probs = None def reset_parameters(self): if self.qkv_same_dim: nn.init.xavier_uniform_(self.in_proj_weight) else: nn.init.xavier_uniform_(self.k_proj_weight) nn.init.xavier_uniform_(self.v_proj_weight) nn.init.xavier_uniform_(self.q_proj_weight) nn.init.xavier_uniform_(self.out_proj.weight) if self.in_proj_bias is not None: nn.init.constant_(self.in_proj_bias, 0.) nn.init.constant_(self.out_proj.bias, 0.) if self.bias_k is not None: nn.init.xavier_normal_(self.bias_k) if self.bias_v is not None: nn.init.xavier_normal_(self.bias_v) def forward( self, query, key, value, key_padding_mask=None, incremental_state=None, need_weights=True, static_kv=False, attn_mask=None, before_softmax=False, need_head_weights=False, enc_dec_attn_constraint_mask=None, reset_attn_weight=None ): """Input shape: Time x Batch x Channel Args: key_padding_mask (ByteTensor, optional): mask to exclude keys that are pads, of shape `(batch, src_len)`, where padding elements are indicated by 1s. need_weights (bool, optional): return the attention weights, averaged over heads (default: False). attn_mask (ByteTensor, optional): typically used to implement causal attention, where the mask prevents the attention from looking forward in time (default: None). before_softmax (bool, optional): return the raw attention weights and values before the attention softmax. need_head_weights (bool, optional): return the attention weights for each head. Implies *need_weights*. Default: return the average attention weights over all heads. """ if need_head_weights: need_weights = True tgt_len, bsz, embed_dim = query.size() assert embed_dim == self.embed_dim assert list(query.size()) == [tgt_len, bsz, embed_dim] if self.enable_torch_version and incremental_state is None and not static_kv and reset_attn_weight is None: if self.qkv_same_dim: return F.multi_head_attention_forward(query, key, value, self.embed_dim, self.num_heads, self.in_proj_weight, self.in_proj_bias, self.bias_k, self.bias_v, self.add_zero_attn, self.dropout, self.out_proj.weight, self.out_proj.bias, self.training, key_padding_mask, need_weights, attn_mask) else: return F.multi_head_attention_forward(query, key, value, self.embed_dim, self.num_heads, torch.empty([0]), self.in_proj_bias, self.bias_k, self.bias_v, self.add_zero_attn, self.dropout, self.out_proj.weight, self.out_proj.bias, self.training, key_padding_mask, need_weights, attn_mask, use_separate_proj_weight=True, q_proj_weight=self.q_proj_weight, k_proj_weight=self.k_proj_weight, v_proj_weight=self.v_proj_weight) if incremental_state is not None: saved_state = self._get_input_buffer(incremental_state) if 'prev_key' in saved_state: # previous time steps are cached - no need to recompute # key and value if they are static if static_kv: assert self.encoder_decoder_attention and not self.self_attention key = value = None else: saved_state = None if self.self_attention: # self-attention q, k, v = self.in_proj_qkv(query) elif self.encoder_decoder_attention: # encoder-decoder attention q = self.in_proj_q(query) if key is None: assert value is None k = v = None else: k = self.in_proj_k(key) v = self.in_proj_v(key) else: q = self.in_proj_q(query) k = self.in_proj_k(key) v = self.in_proj_v(value) q *= self.scaling if self.bias_k is not None: assert self.bias_v is not None k = torch.cat([k, self.bias_k.repeat(1, bsz, 1)]) v = torch.cat([v, self.bias_v.repeat(1, bsz, 1)]) if attn_mask is not None: attn_mask = torch.cat([attn_mask, attn_mask.new_zeros(attn_mask.size(0), 1)], dim=1) if key_padding_mask is not None: key_padding_mask = torch.cat( [key_padding_mask, key_padding_mask.new_zeros(key_padding_mask.size(0), 1)], dim=1) q = q.contiguous().view(tgt_len, bsz * self.num_heads, self.head_dim).transpose(0, 1) if k is not None: k = k.contiguous().view(-1, bsz * self.num_heads, self.head_dim).transpose(0, 1) if v is not None: v = v.contiguous().view(-1, bsz * self.num_heads, self.head_dim).transpose(0, 1) if saved_state is not None: # saved states are stored with shape (bsz, num_heads, seq_len, head_dim) if 'prev_key' in saved_state: prev_key = saved_state['prev_key'].view(bsz * self.num_heads, -1, self.head_dim) if static_kv: k = prev_key else: k = torch.cat((prev_key, k), dim=1) if 'prev_value' in saved_state: prev_value = saved_state['prev_value'].view(bsz * self.num_heads, -1, self.head_dim) if static_kv: v = prev_value else: v = torch.cat((prev_value, v), dim=1) if 'prev_key_padding_mask' in saved_state and saved_state['prev_key_padding_mask'] is not None: prev_key_padding_mask = saved_state['prev_key_padding_mask'] if static_kv: key_padding_mask = prev_key_padding_mask else: key_padding_mask = torch.cat((prev_key_padding_mask, key_padding_mask), dim=1) saved_state['prev_key'] = k.view(bsz, self.num_heads, -1, self.head_dim) saved_state['prev_value'] = v.view(bsz, self.num_heads, -1, self.head_dim) saved_state['prev_key_padding_mask'] = key_padding_mask self._set_input_buffer(incremental_state, saved_state) src_len = k.size(1) # This is part of a workaround to get around fork/join parallelism # not supporting Optional types. if key_padding_mask is not None and key_padding_mask.shape == torch.Size([]): key_padding_mask = None if key_padding_mask is not None: assert key_padding_mask.size(0) == bsz assert key_padding_mask.size(1) == src_len if self.add_zero_attn: src_len += 1 k = torch.cat([k, k.new_zeros((k.size(0), 1) + k.size()[2:])], dim=1) v = torch.cat([v, v.new_zeros((v.size(0), 1) + v.size()[2:])], dim=1) if attn_mask is not None: attn_mask = torch.cat([attn_mask, attn_mask.new_zeros(attn_mask.size(0), 1)], dim=1) if key_padding_mask is not None: key_padding_mask = torch.cat( [key_padding_mask, torch.zeros(key_padding_mask.size(0), 1).type_as(key_padding_mask)], dim=1) attn_weights = torch.bmm(q, k.transpose(1, 2)) attn_weights = self.apply_sparse_mask(attn_weights, tgt_len, src_len, bsz) assert list(attn_weights.size()) == [bsz * self.num_heads, tgt_len, src_len] if attn_mask is not None: if len(attn_mask.shape) == 2: attn_mask = attn_mask.unsqueeze(0) elif len(attn_mask.shape) == 3: attn_mask = attn_mask[:, None].repeat([1, self.num_heads, 1, 1]).reshape( bsz * self.num_heads, tgt_len, src_len) attn_weights = attn_weights + attn_mask if enc_dec_attn_constraint_mask is not None: # bs x head x L_kv attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) attn_weights = attn_weights.masked_fill( enc_dec_attn_constraint_mask.unsqueeze(2).bool(), -1e8, ) attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len) if key_padding_mask is not None: # don't attend to padding symbols attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) attn_weights = attn_weights.masked_fill( key_padding_mask.unsqueeze(1).unsqueeze(2), -1e8, ) attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len) attn_logits = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) if before_softmax: return attn_weights, v attn_weights_float = softmax(attn_weights, dim=-1) attn_weights = attn_weights_float.type_as(attn_weights) attn_probs = F.dropout(attn_weights_float.type_as(attn_weights), p=self.dropout, training=self.training) if reset_attn_weight is not None: if reset_attn_weight: self.last_attn_probs = attn_probs.detach() else: assert self.last_attn_probs is not None attn_probs = self.last_attn_probs attn = torch.bmm(attn_probs, v) assert list(attn.size()) == [bsz * self.num_heads, tgt_len, self.head_dim] attn = attn.transpose(0, 1).contiguous().view(tgt_len, bsz, embed_dim) attn = self.out_proj(attn) if need_weights: attn_weights = attn_weights_float.view(bsz, self.num_heads, tgt_len, src_len).transpose(1, 0) if not need_head_weights: # average attention weights over heads attn_weights = attn_weights.mean(dim=0) else: attn_weights = None return attn, (attn_weights, attn_logits) def in_proj_qkv(self, query): return self._in_proj(query).chunk(3, dim=-1) def in_proj_q(self, query): if self.qkv_same_dim: return self._in_proj(query, end=self.embed_dim) else: bias = self.in_proj_bias if bias is not None: bias = bias[:self.embed_dim] return F.linear(query, self.q_proj_weight, bias) def in_proj_k(self, key): if self.qkv_same_dim: return self._in_proj(key, start=self.embed_dim, end=2 * self.embed_dim) else: weight = self.k_proj_weight bias = self.in_proj_bias if bias is not None: bias = bias[self.embed_dim:2 * self.embed_dim] return F.linear(key, weight, bias) def in_proj_v(self, value): if self.qkv_same_dim: return self._in_proj(value, start=2 * self.embed_dim) else: weight = self.v_proj_weight bias = self.in_proj_bias if bias is not None: bias = bias[2 * self.embed_dim:] return F.linear(value, weight, bias) def _in_proj(self, input, start=0, end=None): weight = self.in_proj_weight bias = self.in_proj_bias weight = weight[start:end, :] if bias is not None: bias = bias[start:end] return F.linear(input, weight, bias) def _get_input_buffer(self, incremental_state): return get_incremental_state( self, incremental_state, 'attn_state', ) or {} def _set_input_buffer(self, incremental_state, buffer): set_incremental_state( self, incremental_state, 'attn_state', buffer, ) def apply_sparse_mask(self, attn_weights, tgt_len, src_len, bsz): return attn_weights def clear_buffer(self, incremental_state=None): if incremental_state is not None: saved_state = self._get_input_buffer(incremental_state) if 'prev_key' in saved_state: del saved_state['prev_key'] if 'prev_value' in saved_state: del saved_state['prev_value'] self._set_input_buffer(incremental_state, saved_state) class EncSALayer(nn.Module): def __init__(self, c, num_heads, dropout, attention_dropout=0.1, relu_dropout=0.1, kernel_size=9, padding='SAME', act='gelu'): super().__init__() self.c = c self.dropout = dropout self.num_heads = num_heads if num_heads > 0: self.layer_norm1 = LayerNorm(c) self.self_attn = MultiheadAttention( self.c, num_heads, self_attention=True, dropout=attention_dropout, bias=False) self.layer_norm2 = LayerNorm(c) self.ffn = TransformerFFNLayer( c, 4 * c, kernel_size=kernel_size, dropout=relu_dropout, padding=padding, act=act) def forward(self, x, encoder_padding_mask=None, **kwargs): layer_norm_training = kwargs.get('layer_norm_training', None) if layer_norm_training is not None: self.layer_norm1.training = layer_norm_training self.layer_norm2.training = layer_norm_training if self.num_heads > 0: residual = x x = self.layer_norm1(x) x, _, = self.self_attn( query=x, key=x, value=x, key_padding_mask=encoder_padding_mask ) x = F.dropout(x, self.dropout, training=self.training) x = residual + x x = x * (1 - encoder_padding_mask.float()).transpose(0, 1)[..., None] residual = x x = self.layer_norm2(x) x = self.ffn(x) x = F.dropout(x, self.dropout, training=self.training) x = residual + x x = x * (1 - encoder_padding_mask.float()).transpose(0, 1)[..., None] return x class DecSALayer(nn.Module): def __init__(self, c, num_heads, dropout, attention_dropout=0.1, relu_dropout=0.1, kernel_size=9, act='gelu'): super().__init__() self.c = c self.dropout = dropout self.layer_norm1 = LayerNorm(c) self.self_attn = MultiheadAttention( c, num_heads, self_attention=True, dropout=attention_dropout, bias=False ) self.layer_norm2 = LayerNorm(c) self.encoder_attn = MultiheadAttention( c, num_heads, encoder_decoder_attention=True, dropout=attention_dropout, bias=False, ) self.layer_norm3 = LayerNorm(c) self.ffn = TransformerFFNLayer( c, 4 * c, padding='LEFT', kernel_size=kernel_size, dropout=relu_dropout, act=act) def forward( self, x, encoder_out=None, encoder_padding_mask=None, incremental_state=None, self_attn_mask=None, self_attn_padding_mask=None, attn_out=None, reset_attn_weight=None, **kwargs, ): layer_norm_training = kwargs.get('layer_norm_training', None) if layer_norm_training is not None: self.layer_norm1.training = layer_norm_training self.layer_norm2.training = layer_norm_training self.layer_norm3.training = layer_norm_training residual = x x = self.layer_norm1(x) x, _ = self.self_attn( query=x, key=x, value=x, key_padding_mask=self_attn_padding_mask, incremental_state=incremental_state, attn_mask=self_attn_mask ) x = F.dropout(x, self.dropout, training=self.training) x = residual + x attn_logits = None if encoder_out is not None or attn_out is not None: residual = x x = self.layer_norm2(x) if encoder_out is not None: x, attn = self.encoder_attn( query=x, key=encoder_out, value=encoder_out, key_padding_mask=encoder_padding_mask, incremental_state=incremental_state, static_kv=True, enc_dec_attn_constraint_mask=get_incremental_state(self, incremental_state, 'enc_dec_attn_constraint_mask'), reset_attn_weight=reset_attn_weight ) attn_logits = attn[1] elif attn_out is not None: x = self.encoder_attn.in_proj_v(attn_out) if encoder_out is not None or attn_out is not None: x = F.dropout(x, self.dropout, training=self.training) x = residual + x residual = x x = self.layer_norm3(x) x = self.ffn(x, incremental_state=incremental_state) x = F.dropout(x, self.dropout, training=self.training) x = residual + x return x, attn_logits def clear_buffer(self, input, encoder_out=None, encoder_padding_mask=None, incremental_state=None): self.encoder_attn.clear_buffer(incremental_state) self.ffn.clear_buffer(incremental_state) def set_buffer(self, name, tensor, incremental_state): return set_incremental_state(self, incremental_state, name, tensor) class TransformerEncoderLayer(nn.Module): def __init__(self, hidden_size, dropout, kernel_size=9, num_heads=2): super().__init__() self.hidden_size = hidden_size self.dropout = dropout self.num_heads = num_heads self.op = EncSALayer( hidden_size, num_heads, dropout=dropout, attention_dropout=0.0, relu_dropout=dropout, kernel_size=kernel_size) def forward(self, x, **kwargs): return self.op(x, **kwargs) class TransformerDecoderLayer(nn.Module): def __init__(self, hidden_size, dropout, kernel_size=9, num_heads=2): super().__init__() self.hidden_size = hidden_size self.dropout = dropout self.num_heads = num_heads self.op = DecSALayer( hidden_size, num_heads, dropout=dropout, attention_dropout=0.0, relu_dropout=dropout, kernel_size=kernel_size) def forward(self, x, **kwargs): return self.op(x, **kwargs) def clear_buffer(self, *args): return self.op.clear_buffer(*args) def set_buffer(self, *args): return self.op.set_buffer(*args) class FFTBlocks(nn.Module): def __init__(self, hidden_size, num_layers, ffn_kernel_size=9, dropout=0.0, num_heads=2, use_pos_embed=True, use_last_norm=True, use_pos_embed_alpha=True): super().__init__() self.num_layers = num_layers embed_dim = self.hidden_size = hidden_size self.dropout = dropout self.use_pos_embed = use_pos_embed self.use_last_norm = use_last_norm if use_pos_embed: self.max_source_positions = DEFAULT_MAX_TARGET_POSITIONS self.padding_idx = 0 self.pos_embed_alpha = nn.Parameter(torch.Tensor([1])) if use_pos_embed_alpha else 1 self.embed_positions = SinusoidalPositionalEmbedding( embed_dim, self.padding_idx, init_size=DEFAULT_MAX_TARGET_POSITIONS, ) self.layers = nn.ModuleList([]) self.layers.extend([ TransformerEncoderLayer(self.hidden_size, self.dropout, kernel_size=ffn_kernel_size, num_heads=num_heads) for _ in range(self.num_layers) ]) if self.use_last_norm: self.layer_norm = nn.LayerNorm(embed_dim) else: self.layer_norm = None def forward(self, x, padding_mask=None, attn_mask=None, return_hiddens=False): """ :param x: [B, T, C] :param padding_mask: [B, T] :return: [B, T, C] or [L, B, T, C] """ padding_mask = x.abs().sum(-1).eq(0).data if padding_mask is None else padding_mask nonpadding_mask_TB = 1 - padding_mask.transpose(0, 1).float()[:, :, None] # [T, B, 1] if self.use_pos_embed: positions = self.pos_embed_alpha * self.embed_positions(x[..., 0]) x = x + positions x = F.dropout(x, p=self.dropout, training=self.training) # B x T x C -> T x B x C x = x.transpose(0, 1) * nonpadding_mask_TB hiddens = [] for layer in self.layers: x = layer(x, encoder_padding_mask=padding_mask, attn_mask=attn_mask) * nonpadding_mask_TB hiddens.append(x) if self.use_last_norm: x = self.layer_norm(x) * nonpadding_mask_TB if return_hiddens: x = torch.stack(hiddens, 0) # [L, T, B, C] x = x.transpose(1, 2) # [L, B, T, C] else: x = x.transpose(0, 1) # [B, T, C] return x class FastSpeechEncoder(FFTBlocks): def __init__(self, dict_size, hidden_size=256, num_layers=4, kernel_size=9, num_heads=2, dropout=0.0): super().__init__(hidden_size, num_layers, kernel_size, num_heads=num_heads, use_pos_embed=False, dropout=dropout) # use_pos_embed_alpha for compatibility self.embed_tokens = Embedding(dict_size, hidden_size, 0) self.embed_scale = math.sqrt(hidden_size) self.padding_idx = 0 self.embed_positions = SinusoidalPositionalEmbedding( hidden_size, self.padding_idx, init_size=DEFAULT_MAX_TARGET_POSITIONS, ) def forward(self, txt_tokens, attn_mask=None): """ :param txt_tokens: [B, T] :return: { 'encoder_out': [B x T x C] } """ encoder_padding_mask = txt_tokens.eq(self.padding_idx).data x = self.forward_embedding(txt_tokens) # [B, T, H] if self.num_layers > 0: x = super(FastSpeechEncoder, self).forward(x, encoder_padding_mask, attn_mask=attn_mask) return x def forward_embedding(self, txt_tokens): # embed tokens and positions x = self.embed_scale * self.embed_tokens(txt_tokens) if self.use_pos_embed: positions = self.embed_positions(txt_tokens) x = x + positions x = F.dropout(x, p=self.dropout, training=self.training) return x class FastSpeechDecoder(FFTBlocks): def __init__(self, hidden_size=256, num_layers=4, kernel_size=9, num_heads=2): super().__init__(hidden_size, num_layers, kernel_size, num_heads=num_heads)
15,933
1,559
<reponame>msgi/nlp-tour import pickle from gensim.corpora import Dictionary from gensim.models import LdaModel, TfidfModel import jieba import os class LdaTopicModel(object): def __init__(self, model_path, config_path, train=False, file_path=None): self.model_path = model_path self.config_path = config_path if not train: self.dictionary, self.tf_idf = self.load_config() self.model = self.load_model() else: self.file_path = file_path self.dictionary, self.tf_idf, self.model = self.train() def train(self): corpus = self.preprocess() dictionary = Dictionary(corpus) doc2bow = [dictionary.doc2bow(text) for text in corpus] tf_idf = TfidfModel(doc2bow) corpus_tf_idf = tf_idf[doc2bow] model = LdaModel(corpus_tf_idf, num_topics=2) return dictionary, tf_idf, model def save_model(self): self.model.save(self.model_path) def load_model(self): try: model = LdaModel.load(self.model_path) except FileNotFoundError: model = None return model def predict(self, text): line_cut = list(jieba.cut(text)) doc2bow = self.dictionary.doc2bow(line_cut) corpus_tf_idf = self.tf_idf[doc2bow] return self.model[corpus_tf_idf] def save_config(self): with open(self.config_path, 'wb') as file: pickle.dump((self.dictionary, self.tf_idf), file) def load_config(self): with open(self.config_path, 'rb') as file: dictionary, tf_idf = pickle.load(file) return dictionary, tf_idf def preprocess(self): # 读取文件夹下所有的文件名 files = os.listdir(self.file_path) corpus = [] for file in files: dir_ = os.path.join(self.file_path, file) with open(dir_, 'r', encoding='utf-8') as file_: line = file_.read() line_cut = list(jieba.cut(line)) corpus.append(line_cut) return corpus
1,063
32,544
<reponame>DBatOWL/tutorials module jlinkModule { requires java.logging; }
31
1,053
/* * "Copyright (c) 2008, 2009 The Regents of the University of California. * All rights reserved." * * Permission to use, copy, modify, and distribute this software and its * documentation for any purpose, without fee, and without written agreement is * hereby granted, provided that the above copyright notice, the following * two paragraphs and the author appear in all copies of this software. * * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS." * */ #include <stdio.h> #include <string.h> #include "circ.h" /* void do_head_read(void *buf) { */ /* char *read_data; */ /* int i, data_len; */ /* data_len = circ_buf_read_head(buf, (void **)&read_data); */ /* printf("buf_read_head: %i\n", data_len); */ /* for (i = 0; i < data_len; i++) */ /* putc(((char *)read_data)[i], stdout); */ /* putc('\n', stdout); */ /* } */ void do_read(void *buf, uint32_t sseqno) { char data[20]; int data_len, i; data_len = circ_buf_read(buf, sseqno, data, 20); printf("buf_read: %i\n", data_len); for (i = 0; i < data_len; i++) putc(((char *)data)[i], stdout); putc('\n', stdout); } int main(int argc, char **argv) { char buf[200]; char data[20], readbuf[30]; int i = 20, data_len; char *read_data; memset(buf, 0, sizeof(buf)); if (circ_buf_init(buf, 200, 0) < 0) printf("cir_buf_init: error\n"); for (i=0;i<20;i++) data[i] = 'a' + i; if (circ_buf_write(buf, 0, data, 20) < 0) printf("circ_buf_write: error\n"); circ_buf_dump(buf); if (circ_buf_write(buf, 10, data, 20) < 0) printf("circ_buf_write: error\n"); circ_buf_dump(buf); if (circ_buf_write(buf, 50, data, 20) < 0) printf("circ_buf_write: error\n"); // circ_buf_dump(buf); // do_head_read(buf); // circ_buf_dump(buf); if (circ_buf_write(buf, 30, data, 20) < 0) printf("circ_buf_write: error\n"); // circ_buf_dump(buf); if (circ_buf_write(buf, 70, data, 20) < 0) printf("circ_buf_write: error\n"); circ_buf_dump(buf); circ_shorten_head(buf, 10); circ_buf_dump(buf); memset(buf, 0, sizeof(buf)); if (circ_buf_init(buf, 200, 0) < 0) printf("cir_buf_init: error\n"); printf("\n\nRESTART\n\n"); for (i = 0; i < 25; i++) { circ_buf_write(buf, i * 20, data, 20); do_read(buf, i * 20); circ_shorten_head(buf, (i > 0) ? (i - 1) * 20 : 0 * 10); circ_buf_dump(buf); } // do_read(buf, 50); /* do_head_read(buf); */ /* circ_buf_dump(buf); */ /* if (circ_buf_write(buf, 90, data, 20) < 0) */ /* printf("circ_buf_write: error\n"); */ /* if (circ_buf_write(buf, 110, data, 20) < 0) */ /* printf("circ_buf_write: error\n"); */ /* if (circ_buf_write(buf, 130, data, 20) < 0) */ /* printf("circ_buf_write: error\n"); */ /* circ_buf_dump(buf); */ /* do_head_read(buf); */ /* do_head_read(buf); */ /* circ_buf_dump(buf); */ }
1,404
2,094
//////////////////////////////////////////////////////////////////////////////////////////////////// // // Project: Embedded Learning Library (ELL) // File: HuberLoss.h (optimization) // Authors: <NAME>, <NAME> // //////////////////////////////////////////////////////////////////////////////////////////////////// #pragma once #include <math/include/Vector.h> namespace ell { namespace optimization { /// <summary> Implements the Huber Loss function, which is a version of the absolute loss with Huber smoothing. </summary> class HuberLoss { public: /// <summary> Checks if an output is compatible with this loss. </summary> template <typename OutputType> constexpr static bool VerifyOutput(OutputType) { return true; } /// <summary> Constructor. </summary> /// /// <param name="gamma"> The inverse smoothness parameter. </param> HuberLoss(double gamma = 2.0) : _gamma(gamma) {} /// <summary> Returns the smoothness of this loss, which is the Lipschitz coefficient of the loss gradient. </summary> double Smoothness() const { return 2.0 / _gamma; } /// <summary> Returns the loss of a scalar prediction, given the true scalar output. </summary> /// /// <param name="prediction"> The predicted output. </param> /// <param name="output"> The true output. </param> template <typename OutputType> double Value(double prediction, OutputType output) const; /// <summary> Returns the loss derivative at a given scalar point. </summary> /// /// <param name="prediction"> The predicted output. </param> /// <param name="output"> The true output. </param> template <typename OutputType> double Derivative(double prediction, OutputType output) const; /// <summary> Returns the value of the loss conjugate at a given point. </summary> /// /// <param name="v"> The point at which to evaluate the conjugate. </param> /// <param name="output"> The output. </param> template <typename OutputType> double Conjugate(double v, OutputType output) const; /// <summary> /// Returns the value of the proximal operator of the conjugate of the loss, which is /// /// argmin_b {theta*g(b) + (1/2)*(b - a)^2} /// /// where g() is the convex conjugate of f() /// </summary> /// /// <param name="theta"> The weight of the conjugate function in the proximal operator definition. </param> /// <param name="z"> The point at which the proximal operator is evaluated. </param> /// <param name="output"> The output. </param> template <typename OutputType> double ConjugateProx(double theta, double z, OutputType output) const; private: double _gamma; }; } // namespace optimization } // namespace ell #pragma region implementation namespace ell { namespace optimization { template <typename OutputType> double HuberLoss::Value(double prediction, OutputType output) const { double residual = prediction - output; if (residual >= -_gamma && residual <= _gamma) { return 0.5 / _gamma * residual * residual; } return std::abs(residual) - 0.5 * _gamma; } template <typename OutputType> double HuberLoss::Derivative(double prediction, OutputType output) const { double residual = prediction - output; if (residual >= -_gamma && residual <= _gamma) { return residual / _gamma; } if (residual > 0) { return 1.0; } return -1.0; } template <typename OutputType> double HuberLoss::Conjugate(double v, OutputType output) const { if (-1.0 <= v && v <= 1.0) { return output * v + 0.5 * _gamma * v * v; } return std::numeric_limits<double>::infinity(); } template <typename OutputType> double HuberLoss::ConjugateProx(double theta, double z, OutputType output) const { double a = (z - theta * output) / (1 + theta * _gamma); if (a <= -1.0) { return -1.0; } if (a >= 1.0) { return 1.0; } return a; } } // namespace optimization } // namespace ell #pragma endregion implementation
1,764
399
<reponame>adrianmgg/GRIP<filename>core/src/test/java/edu/wpi/grip/core/sockets/MockInputSocketFactory.java package edu.wpi.grip.core.sockets; import edu.wpi.grip.core.cuda.NullCudaDetector; import com.google.common.eventbus.EventBus; public class MockInputSocketFactory extends InputSocketImpl.FactoryImpl { public MockInputSocketFactory(EventBus eventBus) { super(eventBus, new NullCudaDetector()); } }
149
733
from rx.core import Observable from rx.internal import extensionmethod @extensionmethod(Observable, alias="every") def all(self, predicate): """Determines whether all elements of an observable sequence satisfy a condition. 1 - res = source.all(lambda value: value.length > 3) Keyword arguments: :param bool predicate: A function to test each element for a condition. :returns: An observable sequence containing a single element determining whether all elements in the source sequence pass the test in the specified predicate. """ return self.filter(lambda v: not predicate(v)).some().map(lambda b: not b)
183
368
/* * Copyright 2020 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA * * 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. */ package io.charlescd.villager.infrastructure.persistence; import io.quarkus.hibernate.orm.panache.PanacheRepository; import java.util.List; import javax.enterprise.context.ApplicationScoped; @ApplicationScoped public class BuildRepository implements PanacheRepository<BuildEntity> { public BuildEntity findById(String id) { return find("id", id).firstResult(); } public List<BuildEntity> findBuildsToNotify() { return find("callback_status = ?1", CallbackStatus.FAILURE.name()).list(); } }
349
1,276
{ "name": "@nuxtjs/browserconfig", "version": "0.0.13", "license": "MIT", "main": "index.js", "repository": "https://github.com/nuxt/modules", "homepage": "https://github.com/nuxt/modules/tree/master/packages/browserconfig", "dependencies": { "data2xml": "^1.3.4", "lodash": "^4.17.20" } }
137
376
<reponame>cjsmeele/Kvasir #pragma once #include <Register/Utility.hpp> namespace Kvasir { //Power Calculation Engine (PCE) namespace PcePintcr{ ///<PCE core interrupt control using Addr = Register::Address<0x4406f000,0xfffffff8,0x00000000,unsigned>; ///PCERST constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> pcerst{}; ///PCENMI constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> pcenmi{}; ///PCEINT constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> pceint{}; } namespace PceMintcr{ ///<Interrupt control to the main core using Addr = Register::Address<0x4406f004,0xfffffffe,0x00000000,unsigned>; ///MAININT constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> mainint{}; } namespace PcePclkcr{ ///<PCE core clock control) using Addr = Register::Address<0x4406f008,0xfffffffe,0x00000000,unsigned>; ///PCECLK constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> pceclk{}; } namespace PcePnmiflg{ ///<PCE core NMI event flag) using Addr = Register::Address<0x4406f00c,0xfffffffc,0x00000000,unsigned>; ///WDTNMIF constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> wdtnmif{}; ///PCEIFNMIF constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> pceifnmif{}; } namespace PcePnmiclr{ ///<PCE core NMI event clear) using Addr = Register::Address<0x4406f010,0xfffffffc,0x00000000,unsigned>; ///WDTNMIC constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> wdtnmic{}; ///PCEIFNMIC constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> pceifnmic{}; } }
1,043
1,794
# Copyright 2019-2021 The AmpliGraph Authors. All Rights Reserved. # # This file is Licensed under the Apache License, Version 2.0. # A copy of the Licence is available in LICENCE, or at: # # http://www.apache.org/licenses/LICENSE-2.0 # import numpy as np import pytest from sklearn.cluster import DBSCAN from ampligraph.discovery.discovery import discover_facts, generate_candidates, _setdiff2d, find_clusters, \ find_duplicates, query_topn, find_nearest_neighbours from ampligraph.latent_features import ComplEx, DistMult def test_discover_facts(): X = np.array([['a', 'y', 'b'], ['b', 'y', 'a'], ['a', 'y', 'c'], ['c', 'y', 'a'], ['a', 'y', 'd'], ['c', 'y', 'd'], ['b', 'y', 'c'], ['f', 'y', 'e']]) model = ComplEx(batches_count=1, seed=555, epochs=2, k=5) with pytest.raises(ValueError): discover_facts(X, model) model.fit(X) with pytest.raises(ValueError): discover_facts(X, model, strategy='error') with pytest.raises(ValueError): discover_facts(X, model, strategy='random_uniform', target_rel='error') def test_generate_candidates(): X = np.stack([['entity_{}'.format(np.mod(x, 15)) for x in range(50)], ['rel_{}'.format(np.mod(x, 5)) for x in range(50)], ['entity_{}'.format(np.mod(x, 20)) for x in range(50)]], axis=1) # Not sure this should be an error # with pytest.raises(ValueError): # generate_candidates(X, strategy='error', target_rel='y', # max_candidates=4) # with pytest.raises(ValueError): # generate_candidates(X, strategy='random_uniform', target_rel='y', # max_candidates=0) # Test X_candidates = generate_candidates(X, strategy='random_uniform', target_rel='rel_0', max_candidates=15, consolidate_sides=False, seed=1916) assert X_candidates.shape == (15, 3) # Test X_candidates = generate_candidates(X, strategy='random_uniform', target_rel='rel_1', max_candidates=20, consolidate_sides=True, seed=1916) assert X_candidates.shape == (20, 3) assert X_candidates[0, 0] == 'entity_16' assert np.all(X_candidates[:, 1] == 'rel_1') # Test that consolidate_sides LHS and RHS is respected X_candidates = generate_candidates(X, strategy='random_uniform', target_rel='rel_0', max_candidates=20, consolidate_sides=False, seed=0) assert np.all(np.isin(X_candidates[:, 0], np.unique(X[:, 0]))) assert np.all(np.isin(X_candidates[:, 2], np.unique(X[:, 2]))) # Test that consolidate_sides=True LHS and RHS entities are mixed X_candidates = generate_candidates(X, strategy='random_uniform', target_rel='rel_0', max_candidates=100, consolidate_sides=True, seed=1) # Check that any of the head or tail entities from X has been found # on the OTHER side of the candidates assert np.logical_or(np.any(np.isin(X_candidates[:, 2], np.unique(X[:, 0]))), np.all(np.isin(X_candidates[:, 0], np.unique(X[:, 2])))) # Test entity frequency generation X_candidates = generate_candidates(X, strategy='entity_frequency', target_rel='rel_0', max_candidates=20, consolidate_sides=False, seed=1) assert X_candidates.shape == (20, 3) X_candidates = generate_candidates(X, strategy='graph_degree', target_rel='rel_0', max_candidates=30, consolidate_sides=False, seed=1) assert X_candidates.shape == (30, 3) X_candidates = generate_candidates(X, strategy='cluster_coefficient', target_rel='rel_0', max_candidates=30, consolidate_sides=False, seed=2) assert X_candidates.shape == (30, 3) X_candidates = generate_candidates(X, strategy='cluster_triangles', target_rel='rel_0', max_candidates=50, consolidate_sides=False, seed=1) assert X_candidates.shape == (50, 3) X_candidates = generate_candidates(X, strategy='cluster_squares', target_rel='rel_0', max_candidates=60, consolidate_sides=False, seed=1) assert X_candidates.shape == (60, 3) def test_setdiff2d(): X = np.array([['a', 'y', 'b'], ['b', 'y', 'a'], ['a', 'y', 'c'], ['c', 'y', 'a'], ['a', 'y', 'd'], ['c', 'y', 'd'], ['b', 'y', 'c'], ['f', 'y', 'e']]) Y = np.array([['a', 'z', 'b'], ['b', 'z', 'a'], ['a', 'z', 'c'], ['c', 'z', 'a'], ['a', 'y', 'd'], ['c', 'y', 'd'], ['b', 'y', 'c'], ['f', 'y', 'e']]) ret1 = np.array([['a', 'y', 'b'], ['b', 'y', 'a'], ['a', 'y', 'c'], ['c', 'y', 'a']]) ret2 = np.array([['a', 'z', 'b'], ['b', 'z', 'a'], ['a', 'z', 'c'], ['c', 'z', 'a']]) assert np.array_equal(ret1, _setdiff2d(X, Y)) assert np.array_equal(ret2, _setdiff2d(Y, X)) # i.e., don't use it as setdiff1d with pytest.raises(RuntimeError): X = np.array([1, 2, 3, 4, 5, 6]) Y = np.array([1, 2, 3, 7, 8, 9]) _setdiff2d(X, Y) def test_find_clusters(): X = np.array([['a', 'y', 'b'], ['b', 'y', 'a'], ['a', 'y', 'c'], ['c', 'y', 'a'], ['a', 'y', 'd'], ['c', 'x', 'd'], ['b', 'y', 'c'], ['f', 'y', 'e']]) model = ComplEx(k=2, batches_count=2) model.fit(X) clustering_algorithm = DBSCAN(eps=1e-3, min_samples=1) labels = find_clusters(X, model, clustering_algorithm, mode='triple') assert np.array_equal(labels, np.array([0, 1, 2, 3, 4, 5, 6, 7])) labels = find_clusters(np.unique(X[:, 0]), model, clustering_algorithm, mode='entity') assert np.array_equal(labels, np.array([0, 1, 2, 3])) labels = find_clusters(np.unique(X[:, 1]), model, clustering_algorithm, mode='relation') assert np.array_equal(labels, np.array([0, 1])) labels = find_clusters(np.unique(X[:, 2]), model, clustering_algorithm, mode='entity') assert np.array_equal(labels, np.array([0, 1, 2, 3, 4])) with pytest.raises(ValueError): find_clusters(X, model, clustering_algorithm, mode='hah') with pytest.raises(ValueError): find_clusters(X, model, clustering_algorithm, mode='entity') with pytest.raises(ValueError): find_clusters(X, model, clustering_algorithm, mode='relation') with pytest.raises(ValueError): find_clusters(np.unique(X[:, 0]), model, clustering_algorithm, mode='triple') def test_find_duplicates(): X = np.array([['a', 'y', 'b'], ['b', 'y', 'a'], ['a', 'y', 'c'], ['c', 'y', 'a'], ['a', 'y', 'd'], ['c', 'x', 'd'], ['b', 'y', 'c'], ['f', 'y', 'e']]) model = ComplEx(k=2, batches_count=2) model.fit(X) entities = set('a b c d e f'.split()) relations = set('x y'.split()) def asserts(tol, dups, ent_rel, subspace): assert tol > 0.0 assert len(dups) <= len(ent_rel) assert all(len(d) <= len(ent_rel) for d in dups) assert all(d.issubset(subspace) for d in dups) dups, tol = find_duplicates(X, model, mode='triple', tolerance='auto', expected_fraction_duplicates=0.5) asserts(tol, dups, X, {tuple(x) for x in X}) dups, tol = find_duplicates(X, model, mode='triple', tolerance=1.0) assert tol == 1.0 asserts(tol, dups, X, {tuple(x) for x in X}) dups, tol = find_duplicates(np.unique(X[:, 0]), model, mode='entity', tolerance='auto', expected_fraction_duplicates=0.5) asserts(tol, dups, entities, entities) dups, tol = find_duplicates(np.unique(X[:, 2]), model, mode='entity', tolerance='auto', expected_fraction_duplicates=0.5) asserts(tol, dups, entities, entities) dups, tol = find_duplicates(np.unique(X[:, 1]), model, mode='relation', tolerance='auto', expected_fraction_duplicates=0.5) asserts(tol, dups, relations, relations) with pytest.raises(ValueError): find_duplicates(X, model, mode='hah') with pytest.raises(ValueError): find_duplicates(X, model, mode='entity') with pytest.raises(ValueError): find_duplicates(X, model, mode='relation') with pytest.raises(ValueError): find_duplicates(np.unique(X[:, 0]), model, mode='triple') def test_query_topn(): X = np.array([['a', 'y', 'b'], ['b', 'y', 'a'], ['a', 'y', 'c'], ['c', 'y', 'a'], ['a', 'y', 'd'], ['c', 'x', 'd'], ['b', 'y', 'c'], ['f', 'y', 'e'], ['a', 'z', 'f'], ['c', 'z', 'f'], ['b', 'z', 'f'], ]) model = ComplEx(k=2, batches_count=2) with pytest.raises(ValueError): # Model not fitted query_topn(model, top_n=2) model.fit(X) with pytest.raises(ValueError): query_topn(model, top_n=2) with pytest.raises(ValueError): query_topn(model, top_n=2, head='a') with pytest.raises(ValueError): query_topn(model, top_n=2, relation='y') with pytest.raises(ValueError): query_topn(model, top_n=2, tail='e') with pytest.raises(ValueError): query_topn(model, top_n=2, head='a', relation='y', tail='e') with pytest.raises(ValueError): query_topn(model, top_n=2, head='xx', relation='y') with pytest.raises(ValueError): query_topn(model, top_n=2, head='a', relation='yakkety') with pytest.raises(ValueError): query_topn(model, top_n=2, head='a', tail='sax') with pytest.raises(ValueError): query_topn(model, top_n=2, head='a', relation='x', rels_to_consider=['y', 'z']) with pytest.raises(ValueError): query_topn(model, top_n=2, head='a', tail='f', rels_to_consider=['y', 'z', 'error']) with pytest.raises(ValueError): query_topn(model, top_n=2, head='a', tail='e', rels_to_consider='y') with pytest.raises(ValueError): query_topn(model, top_n=2, head='a', relation='x', ents_to_consider=['zz', 'top']) with pytest.raises(ValueError): query_topn(model, top_n=2, head='a', tail='e', ents_to_consider=['a', 'b']) subj, pred, obj, top_n = 'a', 'x', 'e', 3 Y, S = query_topn(model, top_n=top_n, head=subj, relation=pred) assert len(Y) == len(S) assert len(Y) == top_n assert np.all(Y[:, 0] == subj) assert np.all(Y[:, 1] == pred) Y, S = query_topn(model, top_n=top_n, relation=pred, tail=obj) assert np.all(Y[:, 1] == pred) assert np.all(Y[:, 2] == obj) ents_to_con = ['a', 'b', 'c', 'd'] Y, S = query_topn(model, top_n=top_n, relation=pred, tail=obj, ents_to_consider=ents_to_con) assert np.all([x in ents_to_con for x in Y[:, 0]]) rels_to_con = ['y', 'x'] Y, S = query_topn(model, top_n=10, head=subj, tail=obj, rels_to_consider=rels_to_con) assert np.all([x in rels_to_con for x in Y[:, 1]]) Y, S = query_topn(model, top_n=10, relation=pred, tail=obj) assert all(S[i] >= S[i + 1] for i in range(len(S) - 1)) def test_find_neighbors(): model = DistMult(batches_count=2, seed=555, epochs=1, k=10, loss='pairwise', loss_params={'margin': 5}, optimizer='adagrad', optimizer_params={'lr': 0.1}) X = np.array([['a', 'y', 'b'], ['b', 'y', 'a'], ['e', 'y', 'c'], ['c', 'z', 'a'], ['a', 'z', 'd'], ['f', 'z', 'g'], ['c', 'z', 'g']]) with pytest.raises(AssertionError) as e: neighbors, dist = find_nearest_neighbours(model, entities=['b'], n_neighbors=3, entities_subset=['a', 'c', 'd', 'e', 'f']) assert str(e.value) == "KGE model is not fit!" model.fit(X) neighbors, dist = find_nearest_neighbours(model, entities=['b'], n_neighbors=3, entities_subset=['a', 'c', 'd', 'e', 'f']) assert np.all(neighbors == [['e', 'd', 'c']]) with pytest.raises(AssertionError) as e: neighbors, dist = find_nearest_neighbours(model, entities=['b'], n_neighbors=30, entities_subset=['a', 'c', 'd', 'e', 'f']) assert str(e.value) == "n_neighbors must be less than the number of entities being fit!" with pytest.raises(AssertionError) as e: neighbors, dist = find_nearest_neighbours(model, entities=['b'], n_neighbors=3, entities_subset='a') assert str(e.value) == "Invalid type for entities_subset! Must be a list or np.array" with pytest.raises(AssertionError) as e: neighbors, dist = find_nearest_neighbours(model, entities='b', n_neighbors=3, entities_subset=['a', 'c', 'd', 'e', 'f']) assert str(e.value) == "Invalid type for entities! Must be a list or np.array"
7,412
1,093
/* * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://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. */ package org.springframework.integration.jmx.config; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.integration.endpoint.SourcePollingChannelAdapter; import org.springframework.integration.test.util.TestUtils; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.PollableChannel; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * @author <NAME> * @author <NAME> * * @since 2.0 */ @ContextConfiguration @RunWith(SpringJUnit4ClassRunner.class) @DirtiesContext public class AttributePollingChannelAdapterParserTests { @Autowired private PollableChannel channel; @Autowired private SourcePollingChannelAdapter adapter; @Autowired private TestBean testBean; @Autowired private MessageChannel autoChannel; @Autowired @Qualifier("autoChannel.adapter") private SourcePollingChannelAdapter autoChannelAdapter; @Test public void pollForAttribute() throws Exception { this.testBean.test("foo"); this.adapter.start(); Message<?> result = this.channel.receive(10000); assertThat(result).isNotNull(); assertThat(result.getPayload()).isEqualTo("foo"); } @Test public void testAutoChannel() { assertThat(TestUtils.getPropertyValue(this.autoChannelAdapter, "outputChannel")).isSameAs(this.autoChannel); } }
682
7,713
<filename>ReactAndroid/src/main/java/com/facebook/react/devsupport/DevSettingsActivity.java<gh_stars>1000+ /** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ package com.facebook.react.devsupport; import android.os.Bundle; import android.preference.PreferenceActivity; import com.facebook.react.R; import com.facebook.react.common.DebugServerException; /** * Activity that display developers settings. Should be added to the debug manifest of the app. Can * be triggered through the developers option menu displayed by {@link DevSupportManager}. */ public class DevSettingsActivity extends PreferenceActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(R.string.catalyst_settings_title); addPreferencesFromResource(R.xml.preferences); } }
298
532
<reponame>MariaHammer/opensim-core_HaeufleMuscle /* -------------------------------------------------------------------------- * * OpenSim Moco: MocoControlBoundConstraint.cpp * * -------------------------------------------------------------------------- * * Copyright (c) 2019 Stanford University and the Authors * * * * Author(s): <NAME> * * * * 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. * * -------------------------------------------------------------------------- */ #include "MocoControlBoundConstraint.h" #include "MocoProblemInfo.h" #include <OpenSim/Common/GCVSpline.h> #include <OpenSim/Simulation/SimulationUtilities.h> using namespace OpenSim; MocoControlBoundConstraint::MocoControlBoundConstraint() { constructProperties(); } void MocoControlBoundConstraint::constructProperties() { constructProperty_control_paths(); constructProperty_lower_bound(); constructProperty_upper_bound(); constructProperty_equality_with_lower(false); } void MocoControlBoundConstraint::initializeOnModelImpl( const Model& model, const MocoProblemInfo& problemInfo) const { // Get all expected control names. auto controlNames = createControlNamesFromModel(model); // Check that the model controls are in the correct order. checkOrderSystemControls(model); m_hasLower = !getProperty_lower_bound().empty(); m_hasUpper = !getProperty_upper_bound().empty(); if (getProperty_control_paths().size() && !m_hasLower && !m_hasUpper) { log_warn("In MocoControlBoundConstraint '{}', control paths are " "specified but no bounds are provided.", getName()); } // Make sure there are no nonexistent controls. if (m_hasLower || m_hasUpper) { auto systemControlIndexMap = createSystemControlIndexMap(model); for (int i = 0; i < getProperty_control_paths().size(); ++i) { const auto& thisName = get_control_paths(i); OPENSIM_THROW_IF_FRMOBJ(systemControlIndexMap.count(thisName) == 0, Exception, "Control path '{}' was provided but no such " "control exists in the model.", thisName); m_controlIndices.push_back(systemControlIndexMap[thisName]); } } OPENSIM_THROW_IF_FRMOBJ(get_equality_with_lower() && m_hasUpper, Exception, "If equality_with_lower==true, upper bound function must not be " "set."); OPENSIM_THROW_IF_FRMOBJ(get_equality_with_lower() && !m_hasLower, Exception, "If equality_with_lower==true, lower bound function must be set."); auto checkTimeRange = [&](const Function& f) { if (auto* spline = dynamic_cast<const GCVSpline*>(&f)) { OPENSIM_THROW_IF_FRMOBJ( spline->getMinX() > problemInfo.minInitialTime, Exception, "The function's minimum domain value ({}) must " "be less than or equal to the minimum possible " "initial time ({}).", spline->getMinX(), problemInfo.minInitialTime); OPENSIM_THROW_IF_FRMOBJ( spline->getMaxX() < problemInfo.maxFinalTime, Exception, "The function's maximum domain value ({}) must " "be greater than or equal to the maximum possible " "final time ({}).", spline->getMaxX(), problemInfo.maxFinalTime); } }; if (m_hasLower) checkTimeRange(get_lower_bound()); if (m_hasUpper) checkTimeRange(get_upper_bound()); int numEqsPerControl; if (get_equality_with_lower()) { numEqsPerControl = 1; } else { numEqsPerControl = (int)m_hasLower + (int)m_hasUpper; } setNumEquations(numEqsPerControl * (int)m_controlIndices.size()); // TODO: setConstraintInfo() is not really intended for use here. MocoConstraintInfo info; std::vector<MocoBounds> bounds; for (int i = 0; i < (int)m_controlIndices.size(); ++i) { if (get_equality_with_lower()) { bounds.emplace_back(0, 0); } else { // The lower and upper bounds on the path constraint must be // constants, so we cannot use the lower and upper bound functions // directly. Therefore, we use a pair of constraints where the // lower/upper bound functions are part of the path constraint // functions and the lower/upper bounds for the path constraints are // -inf, 0, and/or inf. // If a lower bound function is provided, we enforce // lower_bound_function <= control // by creating the constraint // 0 <= control - lower_bound_function <= inf if (m_hasLower) { bounds.emplace_back(0, SimTK::Infinity); } // If an upper bound function is provided, we enforce // control <= upper_bound_function // by creating the constraint // -inf <= control - upper_bound_function <= 0 if (m_hasUpper) { bounds.emplace_back(-SimTK::Infinity, 0); } } } info.setBounds(bounds); const_cast<MocoControlBoundConstraint*>(this)->setConstraintInfo(info); } void MocoControlBoundConstraint::calcPathConstraintErrorsImpl( const SimTK::State& state, SimTK::Vector& errors) const { getModel().realizeVelocity(state); const auto& controls = getModel().getControls(state); int iconstr = 0; SimTK::Vector time(1); for (const auto& controlIndex : m_controlIndices) { const auto& control = controls[controlIndex]; time[0] = state.getTime(); // These if-statements work correctly for either value of // equality_with_lower. if (m_hasLower) { errors[iconstr++] = control - get_lower_bound().calcValue(time); } if (m_hasUpper) { errors[iconstr++] = control - get_upper_bound().calcValue(time); } } }
2,966
1,570
//===- subzero/crosstest/vectors.h - Common SIMD vector utilies -*- C++ -*-===// // // The Subzero Code Generator // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file provides declarations for PNaCl portable SIMD vector types. In // addition, this file provides utilies that may be useful for crosstesting // vector code. // //===----------------------------------------------------------------------===// #ifndef VECTORS_H #define VECTORS_H #include <sstream> #include <stdint.h> #include <string> // The driver and the test program may be compiled by different // versions of clang, with different standard libraries that have // different definitions of int8_t. Specifically, int8_t may be // typedef'd as either 'char' or 'signed char', which mangle to // different strings. Avoid int8_t and use an explicit myint8_t. typedef signed char myint8_t; #include "vectors.def" // PNaCl portable vector types // Types declared: v4si32, v4ui32, v8si16, v8ui16, v16si8, v16ui8, v4f32 #define X(ty, eltty, castty) typedef eltty ty __attribute__((vector_size(16))); VECTOR_TYPE_TABLE #undef X // i1 vector types are not native C++ SIMD vector types. Instead, for // testing, they are expanded by the test code into native 128 bit // SIMD vector types with the appropriate number of elements. // Representing the types in Vectors<> requires a unique label for each // type which this declaration provides. // Types declared: v4i1, v8i1, v16i1 #define X(ty, expandedty, numelements) class ty; I1_VECTOR_TYPE_TABLE #undef X namespace { template <typename T> struct Vectors; // Vectors<T> provides information about a vector type with label T: // * Vectors<T>::Ty is the C++ vector type // * Vectors<T>::ElementTy is the C++ element type // * Vectors<T>::CastTy is a type that is safe to cast elements to and from // and is used for getting the representation of elements in ostreams // * Vectors<T>::NumElements is the number of elements // * Vectors<T>::TypeName is a string that names the type #define DECLARE_VECTOR_TYPE(LABEL, TY, ELTTY, CASTTY, NUM_ELEMENTS) \ template <> struct Vectors<LABEL> { \ typedef TY Ty; \ typedef ELTTY ElementTy; \ typedef CASTTY CastTy; \ static const size_t NumElements; \ static const char *const TypeName; \ }; \ const size_t Vectors<LABEL>::NumElements = NUM_ELEMENTS; \ const char *const Vectors<LABEL>::TypeName = #LABEL; #define X(ty, eltty, castty) \ DECLARE_VECTOR_TYPE(ty, ty, eltty, castty, (sizeof(ty) / sizeof(eltty))) VECTOR_TYPE_TABLE #undef X #define X(ty, expandedty, numelements) \ DECLARE_VECTOR_TYPE(ty, expandedty, bool, int64_t, numelements) I1_VECTOR_TYPE_TABLE #undef X #undef DECLARE_VECTOR_TYPE // Return a string representation of the vector. template <typename T> std::string vectAsString(const typename Vectors<T>::Ty Vect) { std::ostringstream OS; for (size_t i = 0; i < Vectors<T>::NumElements; ++i) { if (i > 0) OS << " "; OS << (typename Vectors<T>::CastTy)Vect[i]; } return OS.str(); } // In some crosstests, test vectors are deterministically constructed by // selecting elements from a pool of scalar values based on a // pseudorandom sequence. Testing all possible combinations of scalar // values from the value pool is often not tractable. // // TODO: Replace with a portable PRNG from C++11. class PRNG { public: explicit PRNG(uint32_t Seed = 1) : State(Seed) {} uint32_t operator()() { // Lewis, Goodman, and Miller (1969) State = (16807 * State) % 2147483647; return State; } private: uint32_t State; }; } // end anonymous namespace #endif // VECTORS_H
1,781
6,034
<filename>user-service-project/user-service-api/src/main/java/cn/iocoder/mall/userservice/rpc/address/dto/UserAddressUpdateReqDTO.java package cn.iocoder.mall.userservice.rpc.address.dto; import cn.iocoder.common.framework.validator.InEnum; import cn.iocoder.common.framework.validator.Mobile; import cn.iocoder.mall.userservice.enums.address.UserAddressType; import lombok.Data; import lombok.experimental.Accessors; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import java.io.Serializable; /** * 用户收件地址更新 Request DTO */ @Data @Accessors(chain = true) public class UserAddressUpdateReqDTO implements Serializable { /** * 收件地址编号 */ @NotNull(message = "收件地址编号不能为空") private Integer id; /** * 用户编号 * * TODO 正在讨论 */ @NotNull(message = "用户编号不能为空") private Integer userId; /** * 收件人名称 */ @NotEmpty(message = "收件人名称不能为空") private String name; /** * 手机号 */ @NotEmpty(message = "手机号不能为空") @Mobile private String mobile; /** * 地区编码 */ @NotNull(message = "地区编码不能为空") private Integer areaCode; /** * 收件详细地址 */ @NotEmpty(message = "收件详细地址不能为空") private String detailAddress; /** * 地址类型 */ @NotNull(message = "地址类型不能为空") @InEnum(value = UserAddressType.class, message = "地址类型必须是 {value}") private Integer type; }
809
2,460
<reponame>shawkins/kubernetes-client /** * Copyright (C) 2015 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.fabric8.kubernetes.examples.kubectl.equivalents; import io.fabric8.kubernetes.client.DefaultKubernetesClient; import io.fabric8.kubernetes.client.KubernetesClient; import io.fabric8.kubernetes.client.dsl.ExecListener; import io.fabric8.kubernetes.client.dsl.ExecWatch; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.ByteArrayOutputStream; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; /** * This sample code is Java equivalent to `kubectl exec my-pod -- ls /`. It assumes that * a Pod with specified name exists in the cluster. */ public class PodExecEquivalent { private static final Logger logger = LoggerFactory.getLogger(PodExecEquivalent.class); private static final CountDownLatch execLatch = new CountDownLatch(1); public static void main(String[] args) { try (final KubernetesClient k8s = new DefaultKubernetesClient()) { ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream error = new ByteArrayOutputStream(); ExecWatch execWatch = k8s.pods().inNamespace("default").withName("my-pod") .writingOutput(out) .writingError(error) .usingListener(new MyPodExecListener()) .exec("ls", "/"); boolean latchTerminationStatus = execLatch.await(5, TimeUnit.SECONDS); if (!latchTerminationStatus) { logger.warn("Latch could not terminate within specified time"); } logger.info("Exec Output: {} ", out); execWatch.close(); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); logger.warn("Interrupted while waiting for the exec: {}", ie.getMessage()); } } private static class MyPodExecListener implements ExecListener { @Override public void onOpen() { logger.info("Shell was opened"); } @Override public void onFailure(Throwable t, Response failureResponse) { logger.info("Some error encountered"); execLatch.countDown(); } @Override public void onClose(int i, String s) { logger.info("Shell Closing"); execLatch.countDown(); } } }
932
305
//===- ForwardOpTree.h ------------------------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // Move instructions between statements. // //===----------------------------------------------------------------------===// #ifndef POLLY_FORWARDOPTREE_H #define POLLY_FORWARDOPTREE_H namespace llvm { class PassRegistry; void initializeForwardOpTreePass(PassRegistry &); } // namespace llvm namespace polly { class ScopPass; ScopPass *createForwardOpTreePass(); } // namespace polly #endif // POLLY_FORWARDOPTREE_H
225
333
void nop() { 123; } int main(void) { nop(); return 42; }
38
7,464
<filename>standard/sonar-vj/src/main/java/com/vip/vjkit/sonarvj/checks/MissingCurlyBracesCheck.java<gh_stars>1000+ package com.vip.vjkit.sonarvj.checks; import com.google.common.collect.ImmutableList; import org.sonar.check.Rule; import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; import org.sonar.plugins.java.api.tree.*; import java.util.List; /** * 1. equals 方法忽略if的检查 2. if(conditon) return true; 忽略在同一行的模式 * * https://github.com/SonarSource/sonar-java/blob/master/java-checks/src/main/java/org/sonar/java/checks/MissingCurlyBracesCheck.java * * 0d54578 Jan 8, 2018 */ @Rule(key = "S121") public class MissingCurlyBracesCheck extends IssuableSubscriptionVisitor { @Override public List<Tree.Kind> nodesToVisit() { return ImmutableList.of(Tree.Kind.IF_STATEMENT, Tree.Kind.FOR_EACH_STATEMENT, Tree.Kind.FOR_STATEMENT, Tree.Kind.WHILE_STATEMENT, Tree.Kind.DO_STATEMENT); } @Override public void visitNode(Tree tree) { switch (tree.kind()) { case WHILE_STATEMENT: WhileStatementTree whileStatementTree = (WhileStatementTree) tree; checkStatement(whileStatementTree.whileKeyword(), whileStatementTree.statement()); break; case DO_STATEMENT: DoWhileStatementTree doWhileStatementTree = (DoWhileStatementTree) tree; checkStatement(doWhileStatementTree.doKeyword(), doWhileStatementTree.statement()); break; case FOR_STATEMENT: ForStatementTree forStatementTree = (ForStatementTree) tree; checkStatement(forStatementTree.forKeyword(), forStatementTree.statement()); break; case FOR_EACH_STATEMENT: ForEachStatement forEachStatement = (ForEachStatement) tree; checkStatement(forEachStatement.forKeyword(), forEachStatement.statement()); break; case IF_STATEMENT: checkIfStatement((IfStatementTree) tree); break; default: break; } } private void checkIfStatement(IfStatementTree ifStmt) { // equals 方法忽略if的检查, 如果if 与处理函数在同一行忽略。 if (isInEqualsMethod(ifStmt)) { return; } if (!isSameLine(ifStmt)) { checkStatement(ifStmt.ifKeyword(), ifStmt.thenStatement()); } StatementTree elseStmt = ifStmt.elseStatement(); if (elseStmt != null && !elseStmt.is(Tree.Kind.IF_STATEMENT)) { checkStatement(ifStmt.elseKeyword(), elseStmt); } } private boolean isSameLine(IfStatementTree ifStmt) { StatementTree thenStmt = ifStmt.thenStatement(); if (thenStmt.is(Tree.Kind.BLOCK)) { return false; } return ifStmt.firstToken().line() == thenStmt.firstToken().line(); } private boolean isInEqualsMethod(IfStatementTree ifStmt) { Tree tree = ifStmt.parent(); while (tree != null && !(tree instanceof MethodTree)) { tree = tree.parent(); } if (tree == null) { return false; } MethodTree methodTree = (MethodTree) tree; if (methodTree.simpleName().toString().equals("equals")) { return true; } return false; } private void checkStatement(SyntaxToken reportToken, StatementTree statement) { if (!statement.is(Tree.Kind.BLOCK)) { reportIssue(reportToken, "Missing curly brace."); } } }
1,157
335
{ "word": "Terrorist", "definitions": [ "Unlawfully using violence and intimidation, especially against civilians, in the pursuit of political aims." ], "parts-of-speech": "Adjective" }
72
375
package io.lumify.palantir.model; import io.lumify.palantir.util.JGeometryWrapper; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Writable; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.sql.Struct; public class PtPropertyAndValue extends PtModelBase { private long id; private long realmId; private long linkObjectId; private long dataEventId; private Long originDataEventId; private boolean deleted; private long propertyValueId; private long crossResolutionId; private long accessControlListId; private long lastModifiedBy; private long lastModified; private long type; private String value; private long linkRoleId; private long linkType; private long priority; private boolean userDisabledKeyword; private String customKeywordTerm; private String geometryXml; private Long timeStart; private Long timeEnd; private long propertyStatus; private long createdBy; private long timeCreated; private JGeometryWrapper geometryGis; public long getId() { return id; } public void setId(long id) { this.id = id; } public long getRealmId() { return realmId; } public void setRealmId(long realmId) { this.realmId = realmId; } public long getLinkObjectId() { return linkObjectId; } public void setLinkObjectId(long linkObjectId) { this.linkObjectId = linkObjectId; } public long getDataEventId() { return dataEventId; } public void setDataEventId(long dataEventId) { this.dataEventId = dataEventId; } public Long getOriginDataEventId() { return originDataEventId; } public void setOriginDataEventId(Long originDataEventId) { this.originDataEventId = originDataEventId; } public boolean isDeleted() { return deleted; } public void setDeleted(boolean deleted) { this.deleted = deleted; } public long getPropertyValueId() { return propertyValueId; } public void setPropertyValueId(long propertyValueId) { this.propertyValueId = propertyValueId; } public long getCrossResolutionId() { return crossResolutionId; } public void setCrossResolutionId(long crossResolutionId) { this.crossResolutionId = crossResolutionId; } public long getAccessControlListId() { return accessControlListId; } public void setAccessControlListId(long accessControlListId) { this.accessControlListId = accessControlListId; } public long getLastModifiedBy() { return lastModifiedBy; } public void setLastModifiedBy(long lastModifiedBy) { this.lastModifiedBy = lastModifiedBy; } public long getLastModified() { return lastModified; } public void setLastModified(long lastModified) { this.lastModified = lastModified; } public long getType() { return type; } public void setType(long type) { this.type = type; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public long getLinkRoleId() { return linkRoleId; } public void setLinkRoleId(long linkRoleId) { this.linkRoleId = linkRoleId; } public long getLinkType() { return linkType; } public void setLinkType(long linkType) { this.linkType = linkType; } public long getPriority() { return priority; } public void setPriority(long priority) { this.priority = priority; } public boolean isUserDisabledKeyword() { return userDisabledKeyword; } public void setUserDisabledKeyword(boolean userDisabledKeyword) { this.userDisabledKeyword = userDisabledKeyword; } public String getCustomKeywordTerm() { return customKeywordTerm; } public void setCustomKeywordTerm(String customKeywordTerm) { this.customKeywordTerm = customKeywordTerm; } public String getGeometryXml() { return geometryXml; } public void setGeometryXml(String geometryXml) { this.geometryXml = geometryXml; } public Long getTimeStart() { return timeStart; } public void setTimeStart(Long timeStart) { this.timeStart = timeStart; } public Long getTimeEnd() { return timeEnd; } public void setTimeEnd(Long timeEnd) { this.timeEnd = timeEnd; } public long getPropertyStatus() { return propertyStatus; } public void setPropertyStatus(long propertyStatus) { this.propertyStatus = propertyStatus; } public long getCreatedBy() { return createdBy; } public void setCreatedBy(long createdBy) { this.createdBy = createdBy; } public long getTimeCreated() { return timeCreated; } public void setTimeCreated(long timeCreated) { this.timeCreated = timeCreated; } public JGeometryWrapper getGeometryGis() { return geometryGis; } public void setGeometryGis(Struct geometryGis) { if (geometryGis == null) { this.geometryGis = null; } else { this.geometryGis = JGeometryWrapper.load(geometryGis); } } @Override public Writable getKey() { return new LongWritable(getId()); } @Override public void write(DataOutput out) throws IOException { out.writeLong(getId()); out.writeLong(getRealmId()); out.writeLong(getLinkObjectId()); out.writeLong(getDataEventId()); writeFieldNullableLong(out, getOriginDataEventId()); out.writeBoolean(isDeleted()); out.writeLong(getPropertyValueId()); out.writeLong(getCrossResolutionId()); out.writeLong(getAccessControlListId()); out.writeLong(getLastModifiedBy()); out.writeLong(getLastModified()); out.writeLong(getType()); writeFieldNullableString(out, getValue()); out.writeLong(getLinkRoleId()); out.writeLong(getLinkType()); out.writeLong(getPriority()); out.writeBoolean(isUserDisabledKeyword()); writeFieldNullableString(out, getCustomKeywordTerm()); writeFieldNullableString(out, getGeometryXml()); writeFieldNullableLong(out, getTimeStart()); writeFieldNullableLong(out, getTimeEnd()); out.writeLong(getPropertyStatus()); out.writeLong(getCreatedBy()); out.writeLong(getTimeCreated()); writeFieldNullableObject(out, getGeometryGis()); } @Override public void readFields(DataInput in) throws IOException { setId(in.readLong()); setRealmId(in.readLong()); setLinkObjectId(in.readLong()); setDataEventId(in.readLong()); setOriginDataEventId(readFieldNullableLong(in)); setDeleted(in.readBoolean()); setPropertyValueId(in.readLong()); setCrossResolutionId(in.readLong()); setAccessControlListId(in.readLong()); setLastModifiedBy(in.readLong()); setLastModified(in.readLong()); setType(in.readLong()); setValue(readFieldNullableString(in)); setLinkRoleId(in.readLong()); setLinkType(in.readLong()); setPriority(in.readLong()); setUserDisabledKeyword(in.readBoolean()); setCustomKeywordTerm(readFieldNullableString(in)); setGeometryXml(readFieldNullableString(in)); setTimeStart(readFieldNullableLong(in)); setTimeEnd(readFieldNullableLong(in)); setPropertyStatus(in.readLong()); setCreatedBy(in.readLong()); setTimeCreated(in.readLong()); this.geometryGis = (JGeometryWrapper) readFieldNullableObject(in); } }
3,182
8,569
#define _POSIX_C_SOURCE 200809L #include <unistd.h> #include <errno.h> #include "sway/config.h" #include "sway/commands.h" #include "log.h" #include "stringop.h" struct cmd_results *input_cmd_xkb_file(int argc, char **argv) { struct cmd_results *error = NULL; if ((error = checkarg(argc, "xkb_file", EXPECTED_EQUAL_TO, 1))) { return error; } struct input_config *ic = config->handler_context.input_config; if (!ic) { return cmd_results_new(CMD_FAILURE, "No input device defined."); } if (strcmp(argv[0], "-") == 0) { free(ic->xkb_file); ic->xkb_file = NULL; } else { ic->xkb_file = strdup(argv[0]); if (!expand_path(&ic->xkb_file)) { error = cmd_results_new(CMD_INVALID, "Invalid syntax (%s)", ic->xkb_file); free(ic->xkb_file); ic->xkb_file = NULL; return error; } if (!ic->xkb_file) { sway_log(SWAY_ERROR, "Failed to allocate expanded path"); return cmd_results_new(CMD_FAILURE, "Unable to allocate resource"); } bool can_access = access(ic->xkb_file, F_OK) != -1; if (!can_access) { sway_log_errno(SWAY_ERROR, "Unable to access xkb file '%s'", ic->xkb_file); config_add_swaynag_warning("Unable to access xkb file '%s'", ic->xkb_file); } } ic->xkb_file_is_set = true; sway_log(SWAY_DEBUG, "set-xkb_file for config: %s file: %s", ic->identifier, ic->xkb_file); return cmd_results_new(CMD_SUCCESS, NULL); }
630
31,928
import json import logging import random import string from moto.iam.policy_validation import IAMPolicyDocumentValidator from moto.secretsmanager import models as secretsmanager_models from moto.secretsmanager.exceptions import SecretNotFoundException from moto.secretsmanager.models import SecretsManagerBackend, secretsmanager_backends from moto.secretsmanager.responses import SecretsManagerResponse from localstack.constants import TEST_AWS_ACCOUNT_ID from localstack.services.infra import start_moto_server from localstack.utils.aws import aws_stack from localstack.utils.common import wait_for_port_open # maps key names to ARNs SECRET_ARN_STORAGE = {} PORT_SECRETS_MANAGER_BACKEND = None def apply_patches(): def secretsmanager_models_secret_arn(region, secret_id): k = "{}_{}".format(region, secret_id) if k not in SECRET_ARN_STORAGE: id_string = "".join(random.choice(string.ascii_letters) for _ in range(6)) arn = "arn:aws:secretsmanager:{0}:{1}:secret:{2}-{3}".format( region, TEST_AWS_ACCOUNT_ID, secret_id, id_string ) SECRET_ARN_STORAGE[k] = arn return SECRET_ARN_STORAGE[k] secretsmanager_models.secret_arn = secretsmanager_models_secret_arn # patching resource policy in moto def get_resource_policy_model(self, secret_id): if self._is_valid_identifier(secret_id): result = { "ARN": self.secrets[secret_id].arn, "Name": self.secrets[secret_id].secret_id, } policy = getattr(self.secrets[secret_id], "policy", None) if policy: result["ResourcePolicy"] = json.dumps(policy) return json.dumps(result) else: raise SecretNotFoundException() setattr(SecretsManagerBackend, "get_resource_policy", get_resource_policy_model) def get_resource_policy_response(self): secret_id = self._get_param("SecretId") return secretsmanager_backends[self.region].get_resource_policy(secret_id=secret_id) setattr(SecretsManagerResponse, "get_resource_policy", get_resource_policy_response) def delete_resource_policy_model(self, secret_id): if self._is_valid_identifier(secret_id): self.secrets[secret_id].policy = None return json.dumps( { "ARN": self.secrets[secret_id].arn, "Name": self.secrets[secret_id].secret_id, } ) else: raise SecretNotFoundException() if not hasattr(SecretsManagerBackend, "delete_resource_policy"): setattr( SecretsManagerBackend, "delete_resource_policy", delete_resource_policy_model, ) def delete_resource_policy_response(self): secret_id = self._get_param("SecretId") return secretsmanager_backends[self.region].delete_resource_policy(secret_id=secret_id) if not hasattr(SecretsManagerResponse, "delete_resource_policy"): setattr( SecretsManagerResponse, "delete_resource_policy", delete_resource_policy_response, ) def put_resource_policy_model(self, secret_id, resource_policy): policy_validator = IAMPolicyDocumentValidator(resource_policy) policy_validator._validate_top_elements() policy_validator._validate_version_syntax() if self._is_valid_identifier(secret_id): self.secrets[secret_id].policy = resource_policy return json.dumps( { "ARN": self.secrets[secret_id].arn, "Name": self.secrets[secret_id].secret_id, } ) else: raise SecretNotFoundException() if not hasattr(SecretsManagerBackend, "put_resource_policy"): setattr(SecretsManagerBackend, "put_resource_policy", put_resource_policy_model) def put_resource_policy_response(self): secret_id = self._get_param("SecretId") resource_policy = self._get_param("ResourcePolicy") return secretsmanager_backends[self.region].put_resource_policy( secret_id=secret_id, resource_policy=json.loads(resource_policy) ) if not hasattr(SecretsManagerResponse, "put_resource_policy"): setattr(SecretsManagerResponse, "put_resource_policy", put_resource_policy_response) def start_secretsmanager(port=None, asynchronous=None, backend_port=None, update_listener=None): apply_patches() result = start_moto_server( key="secretsmanager", name="Secrets Manager", port=port, backend_port=backend_port, asynchronous=asynchronous, update_listener=update_listener, ) global PORT_SECRETS_MANAGER_BACKEND PORT_SECRETS_MANAGER_BACKEND = result.service_port return result def check_secretsmanager(expect_shutdown=False, print_error=False): out = None # noinspection PyBroadException try: wait_for_port_open(PORT_SECRETS_MANAGER_BACKEND, http_path="/", expect_success=False) endpoint_url = f"http://127.0.0.1:{PORT_SECRETS_MANAGER_BACKEND}" out = aws_stack.connect_to_service( service_name="secretsmanager", endpoint_url=endpoint_url ).list_secrets() except Exception: if print_error: logger = logging.getLogger(__name__) logger.exception("Secretsmanager health check failed") if expect_shutdown: assert out is None return assert isinstance(out["SecretList"], list)
2,377
1,144
<reponame>Keneral/asystem /* * Copyright (C) 2016 The Android Open Source Project * 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. * * 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. */ #ifndef SOCKET_MOCK_H_ #define SOCKET_MOCK_H_ #include <memory> #include <queue> #include <string> #include <android-base/macros.h> #include "socket.h" // A mock Socket implementation to be used for testing. Tests can set expectations for messages // to be sent and provide messages to be received in order to verify protocol behavior. // // Example: testing sending "foo" and receiving "bar". // SocketMock mock; // mock.ExpectSend("foo"); // mock.AddReceive("bar"); // EXPECT_TRUE(DoFooBar(&mock)); // // Example: testing sending "foo" and expecting "bar", but receiving "baz" instead. // SocketMock mock; // mock.ExpectSend("foo"); // mock.AddReceive("baz"); // EXPECT_FALSE(DoFooBar(&mock)); class SocketMock : public Socket { public: SocketMock(); ~SocketMock() override; bool Send(const void* data, size_t length) override; bool Send(std::vector<cutils_socket_buffer_t> buffers) override; ssize_t Receive(void* data, size_t length, int timeout_ms) override; int Close() override; virtual std::unique_ptr<Socket> Accept(); // Adds an expectation for Send(). void ExpectSend(std::string message); // Adds an expectation for Send() that returns false. void ExpectSendFailure(std::string message); // Adds data to provide for Receive(). void AddReceive(std::string message); // Adds a Receive() timeout after which ReceiveTimedOut() will return true. void AddReceiveTimeout(); // Adds a Receive() failure after which ReceiveTimedOut() will return false. void AddReceiveFailure(); // Adds a Socket to return from Accept(). void AddAccept(std::unique_ptr<Socket> sock); private: enum class EventType { kSend, kReceive, kAccept }; struct Event { Event(EventType _type, std::string _message, ssize_t _status, std::unique_ptr<Socket> _sock); EventType type; std::string message; bool status; // Return value for Send() or timeout status for Receive(). std::unique_ptr<Socket> sock; }; std::queue<Event> events_; DISALLOW_COPY_AND_ASSIGN(SocketMock); }; #endif // SOCKET_MOCK_H_
1,169
530
package org.carlspring.strongbox.security.authentication.suppliers; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import javax.servlet.http.HttpServletRequest; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; /** * @author <NAME> */ public class AuthenticationSuppliers implements AuthenticationSupplier { private static final Logger logger = LoggerFactory.getLogger(AuthenticationSuppliers.class); private final List<AuthenticationSupplier> suppliers; public AuthenticationSuppliers(List<AuthenticationSupplier> suppliers) { this.suppliers = suppliers; } @CheckForNull @Override public Authentication supply(@Nonnull HttpServletRequest request) { if (suppliers == null || suppliers.isEmpty()) { logger.debug("There was no [{}] provided.", AuthenticationSupplier.class); return null; } AuthenticationException lastException = null; for (final AuthenticationSupplier supplier : suppliers) { final String supplierName = supplier.getClass() .getName(); if (!supplier.supports(request)) { logger.debug("Supplier {} does not support this request [method: {}] [URI: {}] [ContentType {}]", supplierName, request.getMethod(), request.getRequestURI(), request.getContentType()); continue; } logger.debug("Authentication supplier attempt using {}", supplierName); Authentication authentication; try { authentication = supplier.supply(request); } catch (AuthenticationException e) { lastException = e; continue; } if (authentication != null) { logger.debug("Authentication supplied by {}", supplierName); return authentication; } } if (lastException != null) { throw lastException; } return null; } }
1,027
1,253
import java.util.*; public class ShellSort { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int[] elements; System.out.println("Enter the number of elements: "); int j, n = sc.nextInt(); elements = new int[n]; int gap = n / 2; System.out.println("Enter elements: "); for(int i = 0; i < n; i++) elements[i] = sc.nextInt(); while(gap >= 1) { for(int i = gap; i < n; i += gap) { int item = elements[i]; for(j = i - gap; j >= 0 && elements[j] > item; j -= gap) { elements[j + gap] = elements[j]; } elements[j + gap] = item; } gap /= 2; } for(int i = 0; i < n; i++) { System.out.print(elements[i] + " "); } System.out.println(); } }
361
1,178
/* * Copyright 2020 Makani Technologies 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. */ #include "avionics/firmware/drivers/gps_device.h" #include <assert.h> #include <stdbool.h> #include <stddef.h> // For NULL. #include "avionics/firmware/cpu/iomm.h" #include "avionics/firmware/cpu/registers.h" static void Init(void) { // GPS hardware configuration. // // TMS570 Pin Signal Type // ---------- -------- ---------- // N2HET1[16] GPS_nRST Open-drain // GIOA6 GPS_PPS Input // CAN2RX GPS_PV Open-drain // See Table 4-21 from TMS570 Reference Manual Rev A (TI P/N SPNU515A). // Select H2HET1[16] (default function). IommClearPinmux(34, 0); // Select GIOA6 (default function). IommClearPinmux(3, 16); // Place GPS into reset during initialization. N2HET(1).HETDIR.HETDIR16 = 1; // 1 = Output. N2HET(1).HETPDR.HETPDR16 = 1; // 1 = Open-drain. N2HET(1).HETDOUT.HETDOUT16 = 0; // 0 = Logic low. // Pull GIO module out of reset. GIO.GCR0.RESET = 1; // Configure GPS 1-PPS interrupt. GIO.DIRA.DIR6 = 0; // 0 = Input. GIO.PULDISA.PULDIS6 = 0; // 0 = Enable pulling. GIO.PSLA.PSL6 = 1; // 1 = Pull up. GIO.ENACLR.ENACLRA6 = 1; // 1 = Disable interrupts. GIO.INTDET.INTDETA6 = 0; // 0 = Either falling or rising edge. GIO.POL.POLA6 = 0; // 0 = Trigger on falling edge. GIO.FLG.raw = GIO_FLG_FLGA6; // 1 = Clear PPS interrupt flag. } static void SetReset(void) { // Safest to reinitialize all hardware. Init(); } static void ClearReset(void) { // Bring GPS out of reset. N2HET(1).HETDOUT.HETDOUT16 = 1; // 1 = High impedance. } static bool PollPps(void) { if (GIO.FLG.FLGA6) { GIO.FLG.raw = GIO_FLG_FLGA6; return true; } return false; } void GpsDeviceInit(const GpsDevice *dev) { assert(dev != NULL && dev->init != NULL); dev->init(); } void GpsDeviceSetReset(const GpsDevice *dev) { assert(dev != NULL && dev->set_reset != NULL); dev->set_reset(); } void GpsDeviceClearReset(const GpsDevice *dev) { assert(dev != NULL && dev->clear_reset != NULL); dev->clear_reset(); } bool GpsDevicePollPps(const GpsDevice *dev) { assert(dev != NULL && dev->poll_pps != NULL); return dev->poll_pps(); } const GpsDevice kGps = { .init = Init, .set_reset = SetReset, .clear_reset = ClearReset, .poll_pps = PollPps };
1,149
388
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. from .aiohttp_web_socket import AiohttpWebSocket __all__ = [ "AiohttpWebSocket", ]
58
634
/**************************************************************** * Licensed to the Apache Software Foundation (ASF) under one * * or more contributor license agreements. See the NOTICE file * * distributed with this work for additional information * * regarding copyright ownership. The ASF licenses this file * * to you under the Apache License, Version 2.0 (the * * "License"); you may not use this file except in compliance * * with the License. You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, * * software distributed under the License is distributed on an * * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * * KIND, either express or implied. See the License for the * * specific language governing permissions and limitations * * under the License. * ****************************************************************/ package org.apache.james.task; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.Test; public class TaskTest { @Test public void combineShouldReturnCompletedWhenBothCompleted() { assertThat(Task.combine(Task.Result.COMPLETED, Task.Result.COMPLETED)) .isEqualTo(Task.Result.COMPLETED); } @Test public void combineShouldReturnPartialWhenPartialLeft() { assertThat(Task.combine(Task.Result.PARTIAL, Task.Result.COMPLETED)) .isEqualTo(Task.Result.PARTIAL); } @Test public void combineShouldReturnPartialWhenPartialRight() { assertThat(Task.combine(Task.Result.COMPLETED, Task.Result.PARTIAL)) .isEqualTo(Task.Result.PARTIAL); } @Test public void combineShouldReturnPartialWhenBothPartial() { assertThat(Task.combine(Task.Result.PARTIAL, Task.Result.PARTIAL)) .isEqualTo(Task.Result.PARTIAL); } @Test public void onCompleteShouldExecuteOperationWhenCompleted() { AtomicInteger atomicInteger = new AtomicInteger(0); Task.Result.COMPLETED .onComplete(atomicInteger::incrementAndGet); assertThat(atomicInteger.get()) .isEqualTo(1); } @Test public void onFailureShouldNotExecuteOperationWhenCompleted() { AtomicInteger atomicInteger = new AtomicInteger(0); Task.Result.COMPLETED .onFailure(atomicInteger::incrementAndGet); assertThat(atomicInteger.get()) .isEqualTo(0); } @Test public void onCompleteShouldNotExecuteOperationWhenPartial() { AtomicInteger atomicInteger = new AtomicInteger(0); Task.Result.PARTIAL .onComplete(atomicInteger::incrementAndGet); assertThat(atomicInteger.get()) .isEqualTo(0); } @Test public void onFailureShouldExecuteOperationWhenPartial() { AtomicInteger atomicInteger = new AtomicInteger(0); Task.Result.PARTIAL .onFailure(atomicInteger::incrementAndGet); assertThat(atomicInteger.get()) .isEqualTo(1); } @Test public void onCompleteShouldReturnPartialWhenPartial() { assertThat( Task.Result.PARTIAL .onComplete(() -> { })) .isEqualTo(Task.Result.PARTIAL); } @Test public void onFailureShouldReturnCompletedWhenCompleted() { assertThat( Task.Result.COMPLETED .onFailure(() -> { })) .isEqualTo(Task.Result.COMPLETED); } @Test public void onCompleteShouldReturnCompletedWhenCompleted() { assertThat( Task.Result.COMPLETED .onComplete(() -> { })) .isEqualTo(Task.Result.COMPLETED); } @Test public void onFailureShouldReturnPartialWhenPartial() { assertThat( Task.Result.PARTIAL .onFailure(() -> { })) .isEqualTo(Task.Result.PARTIAL); } @Test public void onCompleteShouldReturnPartialWhenOperationThrows() { assertThat( Task.Result.COMPLETED .onComplete(() -> { throw new RuntimeException(); })) .isEqualTo(Task.Result.PARTIAL); } @Test public void onFailureShouldPreserveExceptions() { assertThatThrownBy(() -> Task.Result.PARTIAL .onFailure(() -> { throw new RuntimeException(); })) .isInstanceOf(RuntimeException.class); } }
2,069
12,824
<filename>tests/pos/chang/Outer.java package com.netgents.hello; public class Outer<A> { public Inner inner = new Inner(); public class Inner { public A a; } }
62
852
// // // File: hitfit/gentop.h // Purpose: Toy ttbar event generator for testing. // Created: Jul, 2000, sss. // // This is a very simple event generator for ttbar events, to allow some // basic tests of the mass fitting code. We generate random ttbars, // with kinematics pulled out of a hat, and then decay them into l+jets // events. No radiation or other such luxuries, and, as mentioned, any // kinematic distribuions will certainly be wrong. But the generated // events should satisfy the l+jets mass constraints. // // CMSSW File : interface/gentop.h // Original Author : <NAME> <<EMAIL>> for D0 // Imported to CMSSW by <NAME> <<EMAIL>> // /** @file gentop.h @brief A toy event generator for \f$t\bar{t} \to \ell + 4~\mathrm{jets}\f$ events. This is a very simple event generator for \f$t\bar{t} \to \ell + 4~\mathrm{jets}\f$ events, to allow some basic tests of the kinematic fitting code. The code generates random \f$t\bar{t}\f$ events with kinematics pulled out of a hat (a random number generator), and then decay them into \f$t\bar{t} \to \ell + 4~\mathrm{jets}\f$ events. No physics behind the generation except for four-momentum conservation and energy-mass-momentum relation. No luxuries such as radiation etc, and, as mentioned, any kinematic distribution will certainly not corresponding to physical reality. But the generated events should satisfy the \f$\ell + 4~\mathrm{jets}\f$ mass constraints, and therefore would be usable for testing. @author <NAME> <<EMAIL>> @par Creation date: Jul 2000. @par Modification History: Apr 2009: <NAME> <<EMAIL>>: Imported to CMSSW.<br> Nov 2009: <NAME> <<EMAIL>>: Added doxygen tags for automatic generation of documentation. @par Terms of Usage: With consent for the original author (<NAME>). */ #include <string> #include <iosfwd> #include "CLHEP/Random/Random.h" namespace hitfit { class Defaults; class Lepjets_Event; /** @class Gentop_Args. @brief Hold on to parameters for the toy event generator. */ class Gentop_Args // // Hold on to parameters for the toy event generator. // float mt - Generated top mass. // float sigma_mt - Width of top mass distribution. // // float mh - Generated Higgs mass. // float sigma_mh - Width of Higgs mass distribution. // // float mw - Generated W mass. // float sigma_mw - Width of W mass distribution. // // float mb - Generated b mass. // float sigma_mb - Width of b mass distribution. // // float t_pt_mean - Mean pt of the generated top quarks. // (It will be drawn from an exponential distribution.) // float recoil_pt_mean-Mean pt of ttbar system. // (It will be drawn from an exponential distribution.) // float boost_sigma - Width of z-boost of ttbar system. // float m_boost - Mass of z-boost of ttbar system. // float sxv_tageff - Assumed efficiency of SVX b-tag. // bool smear - If true, smear the event. // bool smear_dir - If false, smear only energies, not directions. // bool muon - If false, decay leptonic ts into electrons. // Otherwise, decay into muons. // string ele_res_str - Electron resolution, for Vector_Resolution. // string muo_res_str - Muon resolution, for Vector_Resolution. // string jet_res_str - Jet resolution, for Vector_Resolution. // string kt_res_str - Kt resolution, for Resolution. // { public: // Constructor. Initialize from a Defaults object. /** @brief Constructor, initialize an instance of Gentop_Args from an instance of Defaults object. @param defs The defaults instance from which to initialize. The instance must contain the following parameters with types and names: - double <i>t_pt_mean</i>. - double <i>mt</i>. - double <i>sigma_mt</i>. - double <i>mh</i>. - double <i>sigma_mh</i>. - double <i>recoil_pt_mean</i>. - double <i>boost_sigma</i>. - double <i>m_boost</i>. - double <i>mb</i>. - double <i>sigma_mb</i>. - double <i>mw</i>. - double <i>sigma_mw</i>. - double <i>svx_tageff</i>. - bool <i>smear</i>. - bool <i>smear_dir</i>. - bool <i>muon</i>. - string <i>ele_res_str</i>. - string <i>muo_res_str</i>. - string <i>jet_res_str</i>. - string <i>kt_res_str</i>. */ Gentop_Args(const Defaults& defs); // Retrieve parameter values. /** @brief Return the value of <i>t_pt_mean</i> parameter. */ double t_pt_mean() const; /** @brief Return the value of <i>mt</i> parameter. */ double mt() const; /** @brief Return the value of <i>sigma_mt</i> parameter. */ double sigma_mt() const; /** @brief Return the value of <i>mh</i> parameter. */ double mh() const; /** @brief Return the value of <i>sigma_mh</i> parameter. */ double sigma_mh() const; /** @brief Return the value of <i>recoil_pt_mean</i> parameter. */ double recoil_pt_mean() const; /** @brief Return the value of <i>boost_sigma</i> parameter. */ double boost_sigma() const; /** @brief Return the value of <i>m_boost</i> parameter. */ double m_boost() const; /** @brief Return the value of <i>mb</i> parameter. */ double mb() const; /** @brief Return the value of <i>sigma_mb</i> parameter. */ double sigma_mb() const; /** @brief Return the value of <i>mw</i> parameter. */ double mw() const; /** @brief Return the value of <i>sigma_mw</i> parameter. */ double sigma_mw() const; /** @brief Return the value of <i>svx_tageff</i> parameter. */ double svx_tageff() const; /** @brief Return the value of <i>smear</i> parameter. */ bool smear() const; /** @brief Return the value of <i>smear_dir</i> parameter. */ bool smear_dir() const; /** @brief Return the value of <i>muon</i> parameter. */ bool muon() const; /** @brief Return the value of <i>ele_res_str</i> parameter. */ std::string ele_res_str() const; /** @brief Return the value of <i>muon_res_str</i> parameter. */ std::string muo_res_str() const; /** @brief Return the value of <i>jet_res_str</i> parameter. */ std::string jet_res_str() const; /** @brief Return the value of <i>kt_res_str</i> parameter. */ std::string kt_res_str() const; private: // Hold on to parameter values. /** Mean transverse momentum \f$p_{T}\f$ of the generated top quarks, in GeV, drawn from an exponential distribution. */ double _t_pt_mean; /** Mass of the generated top quark, in GeV. */ double _mt; /** Width of the generated top quark mass distribution, in GeV. */ double _sigma_mt; /** Mass of the generated Higgs boson, in GeV. */ double _mh; /** Width of the generated Higgs boson mass distribution, in GeV. */ double _sigma_mh; /** Mean transverse momentum \f$p_{T}\f$ of the generated \f$t\bar{t}\f$ system, in GeV, drawn from an exponential distribution. */ double _recoil_pt_mean; /** Width of the \f$z-\f$boost of the \f$t\bar{t}\f$ system, in GeV. */ double _boost_sigma; /** Mass of the \f$z-\f$boost of the \f$t\bar{t}\f$ system, in GeV. */ double _m_boost; /** Mass of the generated <i>b</i> quark, in GeV. */ double _mb; /** Width of the generated <i>b</i> quark mass distribution, in GeV. */ double _sigma_mb; /** Mass of the generated <i>W</i> boson, in GeV. */ double _mw; /** Width of the generated <i>W</i> boson mass, in GeV. */ double _sigma_mw; /** Assumed efficiency of SVX (Secondary Vertex) b-tagging, for most cases it is irrelevant. */ double _svx_tageff; /** If TRUE, smear the event.<br> If FALSE, don't smear the event. */ bool _smear; /** If TRUE, smear the energy and direction of individual particles.<br> If FALSE, only smear the energy of individual particle. */ bool _smear_dir; /** If TRUE, decay the leptonic top quark into muon.<br> If FALSE, decay the leptonic top quark into electron. */ bool _muon; /** Electron resolution information in format suitable for Vector_Resolution. */ std::string _ele_res_str; /** Muon resolution information in format suitable for Vector_Resolution. */ std::string _muo_res_str; /** Jet resolution information in format suitable for Vector_Resolution. */ std::string _jet_res_str; /** \f$k_{T}\f$ resolution information in format suitable for Vector_Resolution. */ std::string _kt_res_str; }; // Generate a ttbar -> ljets event. /** @brief Generate a \f$t\bar{t} \to \ell + 4~\mathrm{jets}\f$ event. @param args The parameter settings for this event. @param engine The underlying random number generator. */ Lepjets_Event gentop(const Gentop_Args& args, CLHEP::HepRandomEngine& engine); // Generate a ttH -> ljets+bb event. /** @brief Generate a \f$t\bar{t}H \to \ell + b\bar{b} + 4~\mathrm{jets}\f$ event. @param args The parameter settings for this event. @param engine The underlying random number generator. */ Lepjets_Event gentth(const Gentop_Args& args, CLHEP::HepRandomEngine& engine); } // namespace hitfit
3,912
5,169
<filename>Specs/f/7/0/SmartechNudges/8.5.9/SmartechNudges.podspec.json { "name": "SmartechNudges", "version": "8.5.9", "platforms": { "ios": "10.0" }, "summary": "SmartechNudges is for adding no code nudges in the app.", "description": "SmartechNudges framework powers developers to rapidly experiment and add native iOS nudges without any code.", "homepage": "https://netcoresmartech.com", "license": { "type": "Commercial", "text": "See https://netcoresmartech.com/" }, "authors": { "netcoresmartech": "<EMAIL>" }, "documentation_url": "https://docs.netcoresmartech.com/", "pod_target_xcconfig": { "EXCLUDED_ARCHS[sdk=iphonesimulator*]": "arm64" }, "user_target_xcconfig": { "EXCLUDED_ARCHS[sdk=iphonesimulator*]": "arm64", "FRAMEWORK_SEARCH_PATHS": "$(inherited)" }, "source": { "git": "https://github.com/NetcoreSolutions/SmartechNudges.git", "tag": "8.5.9" }, "ios": { "vendored_frameworks": "SmartechNudges/framework/SmartechNudges.framework", "frameworks": [ "CFNetwork", "Security" ] }, "resource_bundles": { "iohanseliOS": [ "SmartechNudges/publickey.der", "SmartechNudges/Info.plist", "SmartechNudges/**/*.{png}", "SmartechNudges/allPublicViews.json}" ] }, "preserve_paths": "SmartechNudges/**/*", "libraries": [ "icucore", "sqlite3" ], "dependencies": { "Smartech-iOS-SDK": [ ">=3.1.0" ] } }
657
5,169
{ "name": "FTTimer", "version": "0.0.1", "summary": "Just a tiny library to make using NSTimer easier without retain cycle", "homepage": "https://github.com/futantan/FTTimer", "license": "MIT", "authors": { "futantan": "<EMAIL>" }, "source": { "git": "https://github.com/futantan/FTTimer.git", "tag": "0.0.1" }, "platforms": { "ios": "8.0" }, "source_files": "Sources/*.swift", "module_name": "FTTimerFramework" }
194
1,398
<gh_stars>1000+ /* * This file is part of the SDWebImage package. * (c) <NAME> <<EMAIL>> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #ifdef SD_WEBP #import <Foundation/Foundation.h> #import "SDWebImageCoder.h" /** Built in coder that supports WebP and animated WebP */ @interface SDWebImageWebPCoder : NSObject <SDWebImageProgressiveCoder> + (nonnull instancetype)sharedCoder; @end #endif
161
701
// // Pagination.h // mcapp // // Created by zhuchao on 14/11/7. // Copyright (c) 2014年 zhuchao. All rights reserved. // #import "Model.h" @interface Pagination : Model @property(nonatomic,retain)NSNumber *page; @property(nonatomic,retain)NSNumber *pageSize; @property(nonatomic,retain)NSNumber *total; @property(nonatomic,retain)NSNumber *isEnd; -(NSMutableArray *)success:(NSMutableArray *)originArray newArray:(NSArray *)newArray; @end
178
357
from . import expr from . import stmt
11
916
<filename>flexy-pool-core/src/test/java/com/vladmihalcea/flexypool/util/ClassLoaderUtilsTest.java<gh_stars>100-1000 package com.vladmihalcea.flexypool.util; import org.junit.Test; import java.io.IOException; import static org.junit.Assert.*; /** * ClassLoaderUtilsTest - ClassLoaderUtils Test * * @author <NAME> */ public class ClassLoaderUtilsTest extends AbstractUtilsTest<ClassLoaderUtils> { @Test public void testGetClassLoader() { ClassLoader classLoader = ClassLoaderUtils.getClassLoader(); assertSame(Thread.currentThread().getContextClassLoader(), classLoader); try { Thread.currentThread().setContextClassLoader(null); assertSame(ClassLoaderUtils.class.getClassLoader(), ClassLoaderUtils.getClassLoader()); } finally { Thread.currentThread().setContextClassLoader(classLoader); } } @Test public void testLoadClass() { try { ClassLoaderUtils.loadClass(ClassLoaderUtilsTest.class.getName()); } catch (ClassNotFoundException e) { fail(e.getMessage()); } try { ClassLoaderUtils.loadClass("org.abc.Def"); fail("Should throw ClassNotFoundException!"); } catch (ClassNotFoundException expected) { } } @Test public void testFindClass() { assertTrue(ClassLoaderUtils.findClass(ClassLoaderUtilsTest.class.getName())); assertFalse(ClassLoaderUtils.findClass("org.abc.Def")); } @Test public void testGetResource() { assertNotNull(ClassLoaderUtils.getResource("META-INF/services/com.vladmihalcea.flexypool.metric.MetricsFactoryService")); assertNull(ClassLoaderUtils.getResource("META-INF/no.file")); } @Test public void testGetResourceAsStream() { try { ClassLoaderUtils.getResourceAsStream("META-INF/services/com.vladmihalcea.flexypool.metric.MetricsFactoryService").close(); } catch (IOException e) { fail(e.getMessage()); } } @Override protected Class<ClassLoaderUtils> getUtilsClass() { return ClassLoaderUtils.class; } }
883
506
// https://cses.fi/problemset/task/1109/ #include <iostream> using namespace std; int x, y, n, a[1000001]; int main() { string s; cin >> s; n = s.size(); int i = 1; for (;i < n; i++) { a[i] = max(0, min(a[i - x], y - i + 1)); while (a[i] + i < n && s[a[i]] == s[a[i] + i]) { x = i; y = a[i] + i; a[i]++; } if (i + a[i] == n) break; } cout << s.substr(i, a[i]) << endl; }
220
374
<filename>src/parcsr_ls/par_add_cycle.c /****************************************************************************** * Copyright 1998-2019 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ /****************************************************************************** * * ParAMG cycling routine * *****************************************************************************/ #include "_hypre_parcsr_ls.h" #include "par_amg.h" /*-------------------------------------------------------------------------- * hypre_BoomerAMGCycle *--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGAdditiveCycle( void *amg_vdata) { hypre_ParAMGData *amg_data = (hypre_ParAMGData*) amg_vdata; /* Data Structure variables */ hypre_ParCSRMatrix **A_array; hypre_ParCSRMatrix **P_array; hypre_ParCSRMatrix **R_array; hypre_ParCSRMatrix *Lambda; hypre_ParCSRMatrix *Atilde; hypre_ParVector **F_array; hypre_ParVector **U_array; hypre_ParVector *Vtemp; hypre_ParVector *Ztemp; hypre_ParVector *Xtilde, *Rtilde; hypre_IntArray **CF_marker_array; HYPRE_Int *CF_marker; HYPRE_Int num_levels; HYPRE_Int addlvl, add_end; HYPRE_Int additive; HYPRE_Int mult_additive; HYPRE_Int simple; HYPRE_Int add_last_lvl; HYPRE_Int i, j, num_rows; HYPRE_Int n_global; HYPRE_Int rlx_order; /* Local variables */ HYPRE_Int Solve_err_flag = 0; HYPRE_Int level; HYPRE_Int coarse_grid; HYPRE_Int fine_grid; HYPRE_Int rlx_down; HYPRE_Int rlx_up; HYPRE_Int rlx_coarse; HYPRE_Int *grid_relax_type; HYPRE_Int *num_grid_sweeps; hypre_Vector **l1_norms; HYPRE_Real alpha, beta; HYPRE_Real *u_data; HYPRE_Real *v_data; hypre_Vector *l1_norms_lvl; HYPRE_Real *D_inv; HYPRE_Real *x_global; HYPRE_Real *r_global; HYPRE_Real *relax_weight; HYPRE_Real *omega; #if 0 HYPRE_Real *D_mat; HYPRE_Real *S_vec; #endif HYPRE_ANNOTATE_FUNC_BEGIN; /* Acquire data and allocate storage */ A_array = hypre_ParAMGDataAArray(amg_data); F_array = hypre_ParAMGDataFArray(amg_data); U_array = hypre_ParAMGDataUArray(amg_data); P_array = hypre_ParAMGDataPArray(amg_data); R_array = hypre_ParAMGDataRArray(amg_data); CF_marker_array = hypre_ParAMGDataCFMarkerArray(amg_data); Vtemp = hypre_ParAMGDataVtemp(amg_data); Ztemp = hypre_ParAMGDataZtemp(amg_data); num_levels = hypre_ParAMGDataNumLevels(amg_data); additive = hypre_ParAMGDataAdditive(amg_data); mult_additive = hypre_ParAMGDataMultAdditive(amg_data); simple = hypre_ParAMGDataSimple(amg_data); add_last_lvl = hypre_ParAMGDataAddLastLvl(amg_data); grid_relax_type = hypre_ParAMGDataGridRelaxType(amg_data); Lambda = hypre_ParAMGDataLambda(amg_data); Atilde = hypre_ParAMGDataAtilde(amg_data); Xtilde = hypre_ParAMGDataXtilde(amg_data); Rtilde = hypre_ParAMGDataRtilde(amg_data); l1_norms = hypre_ParAMGDataL1Norms(amg_data); D_inv = hypre_ParAMGDataDinv(amg_data); relax_weight = hypre_ParAMGDataRelaxWeight(amg_data); omega = hypre_ParAMGDataOmega(amg_data); rlx_order = hypre_ParAMGDataRelaxOrder(amg_data); num_grid_sweeps = hypre_ParAMGDataNumGridSweeps(amg_data); /* Initialize */ addlvl = hypre_max(additive, mult_additive); addlvl = hypre_max(addlvl, simple); if (add_last_lvl == -1 ) add_end = num_levels-1; else add_end = add_last_lvl; Solve_err_flag = 0; /*--------------------------------------------------------------------- * Main loop of cycling --- multiplicative version --- V-cycle *--------------------------------------------------------------------*/ /* down cycle */ rlx_down = grid_relax_type[1]; rlx_up = grid_relax_type[2]; rlx_coarse = grid_relax_type[3]; for (level = 0; level < num_levels-1; level++) { HYPRE_ANNOTATE_MGLEVEL_BEGIN(level); fine_grid = level; coarse_grid = level + 1; u_data = hypre_VectorData(hypre_ParVectorLocalVector(U_array[fine_grid])); v_data = hypre_VectorData(hypre_ParVectorLocalVector(Vtemp)); l1_norms_lvl = l1_norms[level]; hypre_ParVectorSetConstantValues(U_array[coarse_grid], 0.0); if (level < addlvl || level > add_end) /* multiplicative version */ { /* smoothing step */ if (rlx_down == 0) { HYPRE_Real *A_data = hypre_CSRMatrixData(hypre_ParCSRMatrixDiag(A_array[fine_grid])); HYPRE_Int *A_i = hypre_CSRMatrixI(hypre_ParCSRMatrixDiag(A_array[fine_grid])); num_rows = hypre_CSRMatrixNumRows(hypre_ParCSRMatrixDiag(A_array[fine_grid])); for (j=0; j < num_grid_sweeps[1]; j++) { hypre_ParVectorCopy(F_array[fine_grid],Vtemp); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows; i++) u_data[i] = relax_weight[level]*v_data[i] / A_data[A_i[i]]; } } else if (rlx_down != 18) { /*hypre_BoomerAMGRelax(A_array[fine_grid],F_array[fine_grid],NULL,rlx_down,0,*/ CF_marker = hypre_IntArrayData(CF_marker_array[fine_grid]); for (j=0; j < num_grid_sweeps[1]; j++) { hypre_BoomerAMGRelaxIF(A_array[fine_grid],F_array[fine_grid], CF_marker, rlx_down,rlx_order,1, relax_weight[fine_grid], omega[fine_grid], l1_norms[level] ? hypre_VectorData(l1_norms[level]) : NULL, U_array[fine_grid], Vtemp, Ztemp); hypre_ParVectorCopy(F_array[fine_grid],Vtemp); } } else { num_rows = hypre_CSRMatrixNumRows(hypre_ParCSRMatrixDiag(A_array[fine_grid])); for (j=0; j < num_grid_sweeps[1]; j++) { hypre_ParVectorCopy(F_array[fine_grid],Vtemp); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows; i++) { u_data[i] += v_data[i] / hypre_VectorData(l1_norms_lvl)[i]; } } } alpha = -1.0; beta = 1.0; hypre_ParCSRMatrixMatvec(alpha, A_array[fine_grid], U_array[fine_grid], beta, Vtemp); alpha = 1.0; beta = 0.0; hypre_ParCSRMatrixMatvecT(alpha,R_array[fine_grid],Vtemp, beta,F_array[coarse_grid]); } else /* additive version */ { hypre_ParVectorCopy(F_array[fine_grid],Vtemp); if (level == 0) /* compute residual */ { hypre_ParVectorCopy(Vtemp, Rtilde); hypre_ParVectorCopy(U_array[fine_grid],Xtilde); } alpha = 1.0; beta = 0.0; hypre_ParCSRMatrixMatvecT(alpha,R_array[fine_grid],Vtemp, beta,F_array[coarse_grid]); } HYPRE_ANNOTATE_MGLEVEL_END(level); } /* additive smoothing and solve coarse grid */ HYPRE_ANNOTATE_MGLEVEL_BEGIN(num_levels - 1); if (addlvl < num_levels) { if (simple > -1) { x_global = hypre_VectorData(hypre_ParVectorLocalVector(Xtilde)); r_global = hypre_VectorData(hypre_ParVectorLocalVector(Rtilde)); n_global = hypre_VectorSize(hypre_ParVectorLocalVector(Xtilde)); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i=0; i < n_global; i++) x_global[i] += D_inv[i]*r_global[i]; } else { if (num_grid_sweeps[1] > 1) { n_global = hypre_VectorSize(hypre_ParVectorLocalVector(Rtilde)); hypre_ParVector *Tmptilde = hypre_CTAlloc(hypre_ParVector, 1, HYPRE_MEMORY_HOST); hypre_Vector *Tmptilde_local = hypre_SeqVectorCreate(n_global); hypre_SeqVectorInitialize(Tmptilde_local); hypre_ParVectorLocalVector(Tmptilde) = Tmptilde_local; hypre_ParVectorOwnsData(Tmptilde) = 1; hypre_ParCSRMatrixMatvec(1.0, Lambda, Rtilde, 0.0, Tmptilde); hypre_ParVectorScale(2.0,Rtilde); hypre_ParCSRMatrixMatvec(-1.0, Atilde, Tmptilde, 1.0, Rtilde); hypre_ParVectorDestroy(Tmptilde); } hypre_ParCSRMatrixMatvec(1.0, Lambda, Rtilde, 1.0, Xtilde); } if (addlvl == 0) hypre_ParVectorCopy(Xtilde, U_array[0]); } if (add_end < num_levels -1) { fine_grid = num_levels -1; for (j=0; j < num_grid_sweeps[3]; j++) if (rlx_coarse == 18) hypre_ParCSRRelax(A_array[fine_grid], F_array[fine_grid], 1, 1, l1_norms[fine_grid] ? hypre_VectorData(l1_norms[fine_grid]) : NULL, 1.0, 1.0 ,0,0,0,0, U_array[fine_grid], Vtemp, Ztemp); else hypre_BoomerAMGRelaxIF(A_array[fine_grid],F_array[fine_grid], NULL, rlx_coarse,0,0, relax_weight[fine_grid], omega[fine_grid], l1_norms[fine_grid] ? hypre_VectorData(l1_norms[fine_grid]) : NULL, U_array[fine_grid], Vtemp, Ztemp); } HYPRE_ANNOTATE_MGLEVEL_END(num_levels - 1); /* up cycle */ for (level = num_levels-1; level > 0; level--) { HYPRE_ANNOTATE_MGLEVEL_BEGIN(level); fine_grid = level - 1; coarse_grid = level; if (level <= addlvl || level > add_end+1) /* multiplicative version */ { alpha = 1.0; beta = 1.0; hypre_ParCSRMatrixMatvec(alpha, P_array[fine_grid], U_array[coarse_grid], beta, U_array[fine_grid]); if (rlx_up != 18) { /*hypre_BoomerAMGRelax(A_array[fine_grid],F_array[fine_grid],NULL,rlx_up,0,*/ CF_marker = hypre_IntArrayData(CF_marker_array[fine_grid]); for (j=0; j < num_grid_sweeps[2]; j++) { hypre_BoomerAMGRelaxIF(A_array[fine_grid],F_array[fine_grid], CF_marker, rlx_up,rlx_order,2, relax_weight[fine_grid], omega[fine_grid], l1_norms[fine_grid] ? hypre_VectorData(l1_norms[fine_grid]) : NULL, U_array[fine_grid], Vtemp, Ztemp); } } else if (rlx_order) { CF_marker = hypre_IntArrayData(CF_marker_array[fine_grid]); HYPRE_Int loc_relax_points[2]; loc_relax_points[0] = -1; loc_relax_points[1] = 1; for (j=0; j < num_grid_sweeps[2]; j++) { for (i=0; i < 2; i++) { hypre_ParCSRRelax_L1_Jacobi(A_array[fine_grid],F_array[fine_grid], CF_marker, loc_relax_points[i], 1.0, l1_norms[fine_grid] ? hypre_VectorData(l1_norms[fine_grid]) : NULL, U_array[fine_grid], Vtemp); } } } else for (j=0; j < num_grid_sweeps[2]; j++) hypre_ParCSRRelax(A_array[fine_grid], F_array[fine_grid], 1, 1, l1_norms[fine_grid] ? hypre_VectorData(l1_norms[fine_grid]) : NULL, 1.0, 1.0 ,0,0,0,0, U_array[fine_grid], Vtemp, Ztemp); } else /* additive version */ { alpha = 1.0; beta = 1.0; hypre_ParCSRMatrixMatvec(alpha, P_array[fine_grid], U_array[coarse_grid], beta, U_array[fine_grid]); } HYPRE_ANNOTATE_MGLEVEL_END(level); } HYPRE_ANNOTATE_FUNC_END; return(Solve_err_flag); } HYPRE_Int hypre_CreateLambda(void *amg_vdata) { hypre_ParAMGData *amg_data = (hypre_ParAMGData*) amg_vdata; /* Data Structure variables */ MPI_Comm comm; hypre_ParCSRMatrix **A_array; hypre_ParVector **F_array; hypre_ParVector **U_array; hypre_ParCSRMatrix *A_tmp; hypre_ParCSRMatrix *Lambda; hypre_CSRMatrix *L_diag; hypre_CSRMatrix *L_offd; hypre_ParCSRMatrix *Atilde; hypre_CSRMatrix *Atilde_diag; hypre_CSRMatrix *Atilde_offd; HYPRE_Real *Atilde_diag_data; HYPRE_Real *Atilde_offd_data; hypre_CSRMatrix *A_tmp_diag; hypre_CSRMatrix *A_tmp_offd; hypre_ParVector *Xtilde; hypre_ParVector *Rtilde; hypre_Vector *Xtilde_local; hypre_Vector *Rtilde_local; hypre_ParCSRCommPkg *comm_pkg; hypre_ParCSRCommPkg *L_comm_pkg = NULL; hypre_ParCSRCommHandle *comm_handle; HYPRE_Real *L_diag_data; HYPRE_Real *L_offd_data; HYPRE_Real *buf_data = NULL; HYPRE_Real *tmp_data; HYPRE_Real *x_data; HYPRE_Real *r_data; hypre_Vector *l1_norms; HYPRE_Real *A_tmp_diag_data; HYPRE_Real *A_tmp_offd_data; HYPRE_Real *D_data = NULL; HYPRE_Real *D_data_offd = NULL; HYPRE_Int *L_diag_i; HYPRE_Int *L_diag_j; HYPRE_Int *L_offd_i; HYPRE_Int *L_offd_j; HYPRE_Int *Atilde_diag_i; HYPRE_Int *Atilde_diag_j; HYPRE_Int *Atilde_offd_i; HYPRE_Int *Atilde_offd_j; HYPRE_Int *A_tmp_diag_i; HYPRE_Int *A_tmp_offd_i; HYPRE_Int *A_tmp_diag_j; HYPRE_Int *A_tmp_offd_j; HYPRE_Int *L_recv_ptr = NULL; HYPRE_Int *L_send_ptr = NULL; HYPRE_Int *L_recv_procs = NULL; HYPRE_Int *L_send_procs = NULL; HYPRE_Int *L_send_map_elmts = NULL; HYPRE_Int *recv_procs; HYPRE_Int *send_procs; HYPRE_Int *send_map_elmts; HYPRE_Int *send_map_starts; HYPRE_Int *recv_vec_starts; HYPRE_Int *all_send_procs = NULL; HYPRE_Int *all_recv_procs = NULL; HYPRE_Int *remap = NULL; HYPRE_Int *level_start; HYPRE_Int addlvl; HYPRE_Int additive; HYPRE_Int mult_additive; HYPRE_Int num_levels; HYPRE_Int num_add_lvls; HYPRE_Int num_procs; HYPRE_Int num_sends, num_recvs; HYPRE_Int num_sends_L = 0; HYPRE_Int num_recvs_L = 0; HYPRE_Int send_data_L = 0; HYPRE_Int num_rows_L = 0; HYPRE_Int num_rows_tmp = 0; HYPRE_Int num_cols_offd_L = 0; HYPRE_Int num_cols_offd = 0; HYPRE_Int level, i, j, k; HYPRE_Int this_proc, cnt, cnt_diag, cnt_offd; HYPRE_Int A_cnt_diag, A_cnt_offd; HYPRE_Int cnt_recv, cnt_send, cnt_row, row_start; HYPRE_Int start_diag, start_offd, indx, cnt_map; HYPRE_Int start, j_indx, index, cnt_level; HYPRE_Int max_sends, max_recvs; HYPRE_Int ns; /* Local variables */ HYPRE_Int Solve_err_flag = 0; HYPRE_Int num_nonzeros_diag; HYPRE_Int num_nonzeros_offd; hypre_Vector **l1_norms_ptr = NULL; /*HYPRE_Real *relax_weight = NULL; HYPRE_Int relax_type; */ HYPRE_Int add_rlx; HYPRE_Int add_last_lvl, add_end; HYPRE_Real add_rlx_wt; /* Acquire data and allocate storage */ A_array = hypre_ParAMGDataAArray(amg_data); F_array = hypre_ParAMGDataFArray(amg_data); U_array = hypre_ParAMGDataUArray(amg_data); additive = hypre_ParAMGDataAdditive(amg_data); mult_additive = hypre_ParAMGDataMultAdditive(amg_data); add_last_lvl = hypre_ParAMGDataAddLastLvl(amg_data); num_levels = hypre_ParAMGDataNumLevels(amg_data); /*relax_weight = hypre_ParAMGDataRelaxWeight(amg_data); relax_type = hypre_ParAMGDataGridRelaxType(amg_data)[1];*/ comm = hypre_ParCSRMatrixComm(A_array[0]); add_rlx = hypre_ParAMGDataAddRelaxType(amg_data); add_rlx_wt = hypre_ParAMGDataAddRelaxWt(amg_data); ns = hypre_ParAMGDataNumGridSweeps(amg_data)[1]; hypre_MPI_Comm_size(comm,&num_procs); l1_norms_ptr = hypre_ParAMGDataL1Norms(amg_data); addlvl = hypre_max(additive, mult_additive); if (add_last_lvl != -1) add_end = add_last_lvl+1; else add_end = num_levels; num_add_lvls = add_end+1-addlvl; level_start = hypre_CTAlloc(HYPRE_Int, num_add_lvls+1, HYPRE_MEMORY_HOST); send_data_L = 0; num_rows_L = 0; num_cols_offd_L = 0; num_nonzeros_diag = 0; num_nonzeros_offd = 0; level_start[0] = 0; cnt = 1; max_sends = 0; max_recvs = 0; for (i=addlvl; i < add_end; i++) { A_tmp = A_array[i]; A_tmp_diag = hypre_ParCSRMatrixDiag(A_tmp); A_tmp_offd = hypre_ParCSRMatrixOffd(A_tmp); A_tmp_diag_i = hypre_CSRMatrixI(A_tmp_diag); A_tmp_offd_i = hypre_CSRMatrixI(A_tmp_offd); num_rows_tmp = hypre_CSRMatrixNumRows(A_tmp_diag); num_cols_offd = hypre_CSRMatrixNumCols(A_tmp_offd); num_rows_L += num_rows_tmp; level_start[cnt] = level_start[cnt-1] + num_rows_tmp; cnt++; num_cols_offd_L += num_cols_offd; num_nonzeros_diag += A_tmp_diag_i[num_rows_tmp]; num_nonzeros_offd += A_tmp_offd_i[num_rows_tmp]; comm_pkg = hypre_ParCSRMatrixCommPkg(A_tmp); if (comm_pkg) { num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); max_sends += num_sends; if (num_sends) send_data_L += hypre_ParCSRCommPkgSendMapStart(comm_pkg,num_sends); max_recvs += hypre_ParCSRCommPkgNumRecvs(comm_pkg); } } if (max_sends >= num_procs ||max_recvs >= num_procs) { max_sends = num_procs; max_recvs = num_procs; } if (max_sends) all_send_procs = hypre_CTAlloc(HYPRE_Int, max_sends, HYPRE_MEMORY_HOST); if (max_recvs) all_recv_procs = hypre_CTAlloc(HYPRE_Int, max_recvs, HYPRE_MEMORY_HOST); cnt_send = 0; cnt_recv = 0; if (max_sends || max_recvs) { if (max_sends < num_procs && max_recvs < num_procs) { for (i=addlvl; i < add_end; i++) { A_tmp = A_array[i]; comm_pkg = hypre_ParCSRMatrixCommPkg(A_tmp); if (comm_pkg) { num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); num_recvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg); send_procs = hypre_ParCSRCommPkgSendProcs(comm_pkg); recv_procs = hypre_ParCSRCommPkgRecvProcs(comm_pkg); for (j = 0; j < num_sends; j++) all_send_procs[cnt_send++] = send_procs[j]; for (j = 0; j < num_recvs; j++) all_recv_procs[cnt_recv++] = recv_procs[j]; } } if (max_sends) { hypre_qsort0(all_send_procs, 0, max_sends-1); num_sends_L = 1; this_proc = all_send_procs[0]; for (i=1; i < max_sends; i++) { if (all_send_procs[i] > this_proc) { this_proc = all_send_procs[i]; all_send_procs[num_sends_L++] = this_proc; } } L_send_procs = hypre_CTAlloc(HYPRE_Int, num_sends_L, HYPRE_MEMORY_HOST); for (j=0; j < num_sends_L; j++) L_send_procs[j] = all_send_procs[j]; hypre_TFree(all_send_procs, HYPRE_MEMORY_HOST); } if (max_recvs) { hypre_qsort0(all_recv_procs, 0, max_recvs-1); num_recvs_L = 1; this_proc = all_recv_procs[0]; for (i=1; i < max_recvs; i++) { if (all_recv_procs[i] > this_proc) { this_proc = all_recv_procs[i]; all_recv_procs[num_recvs_L++] = this_proc; } } L_recv_procs = hypre_CTAlloc(HYPRE_Int, num_recvs_L, HYPRE_MEMORY_HOST); for (j=0; j < num_recvs_L; j++) L_recv_procs[j] = all_recv_procs[j]; hypre_TFree(all_recv_procs, HYPRE_MEMORY_HOST); } L_recv_ptr = hypre_CTAlloc(HYPRE_Int, num_recvs_L+1, HYPRE_MEMORY_HOST); L_send_ptr = hypre_CTAlloc(HYPRE_Int, num_sends_L+1, HYPRE_MEMORY_HOST); for (i=addlvl; i < add_end; i++) { A_tmp = A_array[i]; comm_pkg = hypre_ParCSRMatrixCommPkg(A_tmp); if (comm_pkg) { num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); num_recvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg); send_procs = hypre_ParCSRCommPkgSendProcs(comm_pkg); recv_procs = hypre_ParCSRCommPkgRecvProcs(comm_pkg); send_map_starts = hypre_ParCSRCommPkgSendMapStarts(comm_pkg); recv_vec_starts = hypre_ParCSRCommPkgRecvVecStarts(comm_pkg); } else { num_sends = 0; num_recvs = 0; } for (k = 0; k < num_sends; k++) { this_proc = hypre_BinarySearch(L_send_procs,send_procs[k],num_sends_L); L_send_ptr[this_proc+1] += send_map_starts[k+1]-send_map_starts[k]; } for (k = 0; k < num_recvs; k++) { this_proc = hypre_BinarySearch(L_recv_procs,recv_procs[k],num_recvs_L); L_recv_ptr[this_proc+1] += recv_vec_starts[k+1]-recv_vec_starts[k]; } } L_recv_ptr[0] = 0; for (i=1; i < num_recvs_L; i++) L_recv_ptr[i+1] += L_recv_ptr[i]; L_send_ptr[0] = 0; for (i=1; i < num_sends_L; i++) L_send_ptr[i+1] += L_send_ptr[i]; } else { num_recvs_L = 0; num_sends_L = 0; for (i=addlvl; i < add_end; i++) { A_tmp = A_array[i]; comm_pkg = hypre_ParCSRMatrixCommPkg(A_tmp); if (comm_pkg) { num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); num_recvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg); send_procs = hypre_ParCSRCommPkgSendProcs(comm_pkg); recv_procs = hypre_ParCSRCommPkgRecvProcs(comm_pkg); send_map_starts = hypre_ParCSRCommPkgSendMapStarts(comm_pkg); recv_vec_starts = hypre_ParCSRCommPkgRecvVecStarts(comm_pkg); for (j = 0; j < num_sends; j++) { this_proc = send_procs[j]; if (all_send_procs[this_proc] == 0) num_sends_L++; all_send_procs[this_proc] += send_map_starts[j+1]-send_map_starts[j]; } for (j = 0; j < num_recvs; j++) { this_proc = recv_procs[j]; if (all_recv_procs[this_proc] == 0) num_recvs_L++; all_recv_procs[this_proc] += recv_vec_starts[j+1]-recv_vec_starts[j]; } } } if (max_sends) { L_send_procs = hypre_CTAlloc(HYPRE_Int, num_sends_L, HYPRE_MEMORY_HOST); L_send_ptr = hypre_CTAlloc(HYPRE_Int, num_sends_L+1, HYPRE_MEMORY_HOST); num_sends_L = 0; for (j=0; j < num_procs; j++) { this_proc = all_send_procs[j]; if (this_proc) { L_send_procs[num_sends_L++] = j; L_send_ptr[num_sends_L] = this_proc + L_send_ptr[num_sends_L-1]; } } } if (max_recvs) { L_recv_procs = hypre_CTAlloc(HYPRE_Int, num_recvs_L, HYPRE_MEMORY_HOST); L_recv_ptr = hypre_CTAlloc(HYPRE_Int, num_recvs_L+1, HYPRE_MEMORY_HOST); num_recvs_L = 0; for (j=0; j < num_procs; j++) { this_proc = all_recv_procs[j]; if (this_proc) { L_recv_procs[num_recvs_L++] = j; L_recv_ptr[num_recvs_L] = this_proc + L_recv_ptr[num_recvs_L-1]; } } } } } if (max_sends) hypre_TFree(all_send_procs, HYPRE_MEMORY_HOST); if (max_recvs) hypre_TFree(all_recv_procs, HYPRE_MEMORY_HOST); L_diag = hypre_CSRMatrixCreate(num_rows_L, num_rows_L, num_nonzeros_diag); L_offd = hypre_CSRMatrixCreate(num_rows_L, num_cols_offd_L, num_nonzeros_offd); hypre_CSRMatrixInitialize(L_diag); hypre_CSRMatrixInitialize(L_offd); if (num_nonzeros_diag) { L_diag_data = hypre_CSRMatrixData(L_diag); L_diag_j = hypre_CSRMatrixJ(L_diag); } L_diag_i = hypre_CSRMatrixI(L_diag); if (num_nonzeros_offd) { L_offd_data = hypre_CSRMatrixData(L_offd); L_offd_j = hypre_CSRMatrixJ(L_offd); } L_offd_i = hypre_CSRMatrixI(L_offd); if (ns > 1) { Atilde_diag = hypre_CSRMatrixCreate(num_rows_L, num_rows_L, num_nonzeros_diag); Atilde_offd = hypre_CSRMatrixCreate(num_rows_L, num_cols_offd_L, num_nonzeros_offd); hypre_CSRMatrixInitialize(Atilde_diag); hypre_CSRMatrixInitialize(Atilde_offd); if (num_nonzeros_diag) { Atilde_diag_data = hypre_CSRMatrixData(Atilde_diag); Atilde_diag_j = hypre_CSRMatrixJ(Atilde_diag); } Atilde_diag_i = hypre_CSRMatrixI(Atilde_diag); if (num_nonzeros_offd) { Atilde_offd_data = hypre_CSRMatrixData(Atilde_offd); Atilde_offd_j = hypre_CSRMatrixJ(Atilde_offd); } Atilde_offd_i = hypre_CSRMatrixI(Atilde_offd); } if (num_rows_L) D_data = hypre_CTAlloc(HYPRE_Real, num_rows_L, HYPRE_MEMORY_HOST); if (send_data_L) { L_send_map_elmts = hypre_CTAlloc(HYPRE_Int, send_data_L, HYPRE_MEMORY_HOST); buf_data = hypre_CTAlloc(HYPRE_Real, send_data_L, HYPRE_MEMORY_HOST); } if (num_cols_offd_L) { D_data_offd = hypre_CTAlloc(HYPRE_Real, num_cols_offd_L, HYPRE_MEMORY_HOST); /*L_col_map_offd = hypre_CTAlloc(HYPRE_Int, num_cols_offd_L);*/ remap = hypre_CTAlloc(HYPRE_Int, num_cols_offd_L, HYPRE_MEMORY_HOST); } Rtilde = hypre_CTAlloc(hypre_ParVector, 1, HYPRE_MEMORY_HOST); Rtilde_local = hypre_SeqVectorCreate(num_rows_L); hypre_SeqVectorInitialize(Rtilde_local); hypre_ParVectorLocalVector(Rtilde) = Rtilde_local; hypre_ParVectorOwnsData(Rtilde) = 1; Xtilde = hypre_CTAlloc(hypre_ParVector, 1, HYPRE_MEMORY_HOST); Xtilde_local = hypre_SeqVectorCreate(num_rows_L); hypre_SeqVectorInitialize(Xtilde_local); hypre_ParVectorLocalVector(Xtilde) = Xtilde_local; hypre_ParVectorOwnsData(Xtilde) = 1; x_data = hypre_VectorData(hypre_ParVectorLocalVector(Xtilde)); r_data = hypre_VectorData(hypre_ParVectorLocalVector(Rtilde)); cnt = 0; cnt_level = 0; cnt_diag = 0; cnt_offd = 0; cnt_row = 1; L_diag_i[0] = 0; L_offd_i[0] = 0; if (ns > 1) { A_cnt_diag = 0; A_cnt_offd = 0; Atilde_diag_i[0] = 0; Atilde_offd_i[0] = 0; } for (level=addlvl; level < add_end; level++) { row_start = level_start[cnt_level]; if (level != 0) { tmp_data = hypre_VectorData(hypre_ParVectorLocalVector(F_array[level])); if (tmp_data) { hypre_TFree(tmp_data, hypre_VectorMemoryLocation(hypre_ParVectorLocalVector(F_array[level]))); } hypre_VectorData(hypre_ParVectorLocalVector(F_array[level])) = &r_data[row_start]; hypre_VectorOwnsData(hypre_ParVectorLocalVector(F_array[level])) = 0; tmp_data = hypre_VectorData(hypre_ParVectorLocalVector(U_array[level])); if (tmp_data) { hypre_TFree(tmp_data, hypre_VectorMemoryLocation(hypre_ParVectorLocalVector(U_array[level]))); } hypre_VectorData(hypre_ParVectorLocalVector(U_array[level])) = &x_data[row_start]; hypre_VectorOwnsData(hypre_ParVectorLocalVector(U_array[level])) = 0; } cnt_level++; start_diag = L_diag_i[cnt_row-1]; start_offd = L_offd_i[cnt_row-1]; A_tmp = A_array[level]; A_tmp_diag = hypre_ParCSRMatrixDiag(A_tmp); A_tmp_offd = hypre_ParCSRMatrixOffd(A_tmp); comm_pkg = hypre_ParCSRMatrixCommPkg(A_tmp); A_tmp_diag_i = hypre_CSRMatrixI(A_tmp_diag); A_tmp_offd_i = hypre_CSRMatrixI(A_tmp_offd); A_tmp_diag_j = hypre_CSRMatrixJ(A_tmp_diag); A_tmp_offd_j = hypre_CSRMatrixJ(A_tmp_offd); A_tmp_diag_data = hypre_CSRMatrixData(A_tmp_diag); A_tmp_offd_data = hypre_CSRMatrixData(A_tmp_offd); num_rows_tmp = hypre_CSRMatrixNumRows(A_tmp_diag); if (comm_pkg) { num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); num_recvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg); send_procs = hypre_ParCSRCommPkgSendProcs(comm_pkg); recv_procs = hypre_ParCSRCommPkgRecvProcs(comm_pkg); send_map_starts = hypre_ParCSRCommPkgSendMapStarts(comm_pkg); send_map_elmts = hypre_ParCSRCommPkgSendMapElmts(comm_pkg); recv_vec_starts = hypre_ParCSRCommPkgRecvVecStarts(comm_pkg); } else { num_sends = 0; num_recvs = 0; } /* Compute new combined communication package */ for (i=0; i < num_sends; i++) { this_proc = hypre_BinarySearch(L_send_procs,send_procs[i],num_sends_L); indx = L_send_ptr[this_proc]; for (j=send_map_starts[i]; j < send_map_starts[i+1]; j++) { L_send_map_elmts[indx++] = row_start + send_map_elmts[j]; } L_send_ptr[this_proc] = indx; } cnt_map = 0; for (i = 0; i < num_recvs; i++) { this_proc = hypre_BinarySearch(L_recv_procs,recv_procs[i],num_recvs_L); indx = L_recv_ptr[this_proc]; for (j=recv_vec_starts[i]; j < recv_vec_starts[i+1]; j++) { remap[cnt_map++] = indx++; } L_recv_ptr[this_proc] = indx; } /* Compute Lambda */ if (add_rlx == 0) { /*HYPRE_Real rlx_wt = relax_weight[level];*/ #ifdef HYPRE_USING_OPENMP #pragma omp for private(i) HYPRE_SMP_SCHEDULE #endif for (i=0; i < num_rows_tmp; i++) { D_data[i] = add_rlx_wt/A_tmp_diag_data[A_tmp_diag_i[i]]; L_diag_i[cnt_row+i] = start_diag + A_tmp_diag_i[i+1]; L_offd_i[cnt_row+i] = start_offd + A_tmp_offd_i[i+1]; } if (ns > 1) for (i=0; i < num_rows_tmp; i++) { Atilde_diag_i[cnt_row+i] = start_diag + A_tmp_diag_i[i+1]; Atilde_offd_i[cnt_row+i] = start_offd + A_tmp_offd_i[i+1]; } } else { l1_norms = l1_norms_ptr[level]; #ifdef HYPRE_USING_OPENMP #pragma omp for private(i) HYPRE_SMP_SCHEDULE #endif for (i=0; i < num_rows_tmp; i++) { D_data[i] = 1.0 / hypre_VectorData(l1_norms)[i]; L_diag_i[cnt_row+i] = start_diag + A_tmp_diag_i[i+1]; L_offd_i[cnt_row+i] = start_offd + A_tmp_offd_i[i+1]; } if (ns > 1) { for (i=0; i < num_rows_tmp; i++) { Atilde_diag_i[cnt_row+i] = start_diag + A_tmp_diag_i[i+1]; Atilde_offd_i[cnt_row+i] = start_offd + A_tmp_offd_i[i+1]; } } } if (num_procs > 1) { index = 0; for (i=0; i < num_sends; i++) { start = send_map_starts[i]; for (j=start; j < send_map_starts[i+1]; j++) buf_data[index++] = D_data[send_map_elmts[j]]; } comm_handle = hypre_ParCSRCommHandleCreate(1, comm_pkg, buf_data, D_data_offd); hypre_ParCSRCommHandleDestroy(comm_handle); } for (i = 0; i < num_rows_tmp; i++) { j_indx = A_tmp_diag_i[i]; if (ns > 1) { Atilde_diag_data[A_cnt_diag] = A_tmp_diag_data[j_indx]; Atilde_diag_j[A_cnt_diag++] = i+row_start; } L_diag_data[cnt_diag] = (2.0 - A_tmp_diag_data[j_indx]*D_data[i])*D_data[i]; L_diag_j[cnt_diag++] = i+row_start; for (j=A_tmp_diag_i[i]+1; j < A_tmp_diag_i[i+1]; j++) { j_indx = A_tmp_diag_j[j]; L_diag_data[cnt_diag] = (- A_tmp_diag_data[j]*D_data[j_indx])*D_data[i]; L_diag_j[cnt_diag++] = j_indx+row_start; } for (j=A_tmp_offd_i[i]; j < A_tmp_offd_i[i+1]; j++) { j_indx = A_tmp_offd_j[j]; L_offd_data[cnt_offd] = (- A_tmp_offd_data[j]*D_data_offd[j_indx])*D_data[i]; L_offd_j[cnt_offd++] = remap[j_indx]; } if (ns > 1) { for (j=A_tmp_diag_i[i]+1; j < A_tmp_diag_i[i+1]; j++) { j_indx = A_tmp_diag_j[j]; Atilde_diag_data[A_cnt_diag] = A_tmp_diag_data[j]; Atilde_diag_j[A_cnt_diag++] = j_indx+row_start; } for (j=A_tmp_offd_i[i]; j < A_tmp_offd_i[i+1]; j++) { j_indx = A_tmp_offd_j[j]; Atilde_offd_data[A_cnt_offd] = A_tmp_offd_data[j]; Atilde_offd_j[A_cnt_offd++] = remap[j_indx]; } } } cnt_row += num_rows_tmp; } if (L_send_ptr) { for (i=num_sends_L-1; i > 0; i--) L_send_ptr[i] = L_send_ptr[i-1]; L_send_ptr[0] = 0; } else L_send_ptr = hypre_CTAlloc(HYPRE_Int, 1, HYPRE_MEMORY_HOST); if (L_recv_ptr) { for (i=num_recvs_L-1; i > 0; i--) L_recv_ptr[i] = L_recv_ptr[i-1]; L_recv_ptr[0] = 0; } else L_recv_ptr = hypre_CTAlloc(HYPRE_Int, 1, HYPRE_MEMORY_HOST); L_comm_pkg = hypre_CTAlloc(hypre_ParCSRCommPkg, 1, HYPRE_MEMORY_HOST); hypre_ParCSRCommPkgNumRecvs(L_comm_pkg) = num_recvs_L; hypre_ParCSRCommPkgNumSends(L_comm_pkg) = num_sends_L; hypre_ParCSRCommPkgRecvProcs(L_comm_pkg) = L_recv_procs; hypre_ParCSRCommPkgSendProcs(L_comm_pkg) = L_send_procs; hypre_ParCSRCommPkgRecvVecStarts(L_comm_pkg) = L_recv_ptr; hypre_ParCSRCommPkgSendMapStarts(L_comm_pkg) = L_send_ptr; hypre_ParCSRCommPkgSendMapElmts(L_comm_pkg) = L_send_map_elmts; hypre_ParCSRCommPkgComm(L_comm_pkg) = comm; Lambda = hypre_CTAlloc(hypre_ParCSRMatrix, 1, HYPRE_MEMORY_HOST); hypre_ParCSRMatrixDiag(Lambda) = L_diag; hypre_ParCSRMatrixOffd(Lambda) = L_offd; hypre_ParCSRMatrixCommPkg(Lambda) = L_comm_pkg; hypre_ParCSRMatrixComm(Lambda) = comm; hypre_ParCSRMatrixOwnsData(Lambda) = 1; if (ns > 1) { /*hypre_ParCSRCommPkg *A_comm_pkg = NULL; HYPRE_Int *A_recv_ptr = NULL; HYPRE_Int *A_send_ptr = NULL; HYPRE_Int *A_recv_procs = NULL; HYPRE_Int *A_send_procs = NULL; HYPRE_Int *A_send_map_elmts = NULL; A_comm_pkg = hypre_CTAlloc(hypre_ParCSRCommPkg, 1, HYPRE_MEMORY_HOST); A_recv_ptr = hypre_CTAlloc(HYPRE_Int, num_recvs+1, HYPRE_MEMORY_HOST); A_send_ptr = hypre_CTAlloc(HYPRE_Int, num_sends+1, HYPRE_MEMORY_HOST); A_recv_procs = hypre_CTAlloc(HYPRE_Int, num_recvs_L, HYPRE_MEMORY_HOST); A_send_procs = hypre_CTAlloc(HYPRE_Int, num_sends_L, HYPRE_MEMORY_HOST); A_send_map_elmts = hypre_CTAlloc(HYPRE_Int, L_send_ptr[num_sends_L], HYPRE_MEMORY_HOST); for (i=0; i<num_recvs_L+1; i++) A_recv_ptr[i] = L_recv_ptr[i]; for (i=0; i<num_sends_L+1; i++) A_send_ptr[i] = L_send_ptr[i]; for (i=0; i<num_recvs_L; i++) A_recv_procs[i] = L_recv_procs[i]; for (i=0; i<num_sends_L; i++) A_send_procs[i] = L_send_procs[i]; for (i=0; i < L_send_ptr[num_sends_L]; i++) A_send_map_elmts[i] = L_send_map_elmts[i]; hypre_ParCSRCommPkgNumRecvs(A_comm_pkg) = num_recvs_L; hypre_ParCSRCommPkgNumSends(A_comm_pkg) = num_sends_L; hypre_ParCSRCommPkgRecvProcs(A_comm_pkg) = A_recv_procs; hypre_ParCSRCommPkgSendProcs(A_comm_pkg) = A_send_procs; hypre_ParCSRCommPkgRecvVecStarts(A_comm_pkg) = A_recv_ptr; hypre_ParCSRCommPkgSendMapStarts(A_comm_pkg) = A_send_ptr; hypre_ParCSRCommPkgSendMapElmts(A_comm_pkg) = A_send_map_elmts; hypre_ParCSRCommPkgComm(A_comm_pkg) = comm; */ Atilde = hypre_CTAlloc(hypre_ParCSRMatrix, 1, HYPRE_MEMORY_HOST); hypre_ParCSRMatrixDiag(Atilde) = Atilde_diag; hypre_ParCSRMatrixOffd(Atilde) = Atilde_offd; hypre_ParCSRMatrixCommPkg(Atilde) = L_comm_pkg; hypre_ParCSRMatrixComm(Atilde) = comm; hypre_ParCSRMatrixOwnsData(Atilde) = 1; hypre_ParAMGDataAtilde(amg_data) = Atilde; } hypre_ParAMGDataLambda(amg_data) = Lambda; hypre_ParAMGDataRtilde(amg_data) = Rtilde; hypre_ParAMGDataXtilde(amg_data) = Xtilde; hypre_TFree(D_data_offd, HYPRE_MEMORY_HOST); hypre_TFree(D_data, HYPRE_MEMORY_HOST); if (num_procs > 1) hypre_TFree(buf_data, HYPRE_MEMORY_HOST); hypre_TFree(remap, HYPRE_MEMORY_HOST); hypre_TFree(buf_data, HYPRE_MEMORY_HOST); hypre_TFree(level_start, HYPRE_MEMORY_HOST); return Solve_err_flag; } HYPRE_Int hypre_CreateDinv(void *amg_vdata) { hypre_ParAMGData *amg_data = (hypre_ParAMGData*) amg_vdata; /* Data Structure variables */ hypre_ParCSRMatrix **A_array; hypre_ParVector **F_array; hypre_ParVector **U_array; hypre_ParCSRMatrix *A_tmp; hypre_CSRMatrix *A_tmp_diag; hypre_ParVector *Xtilde; hypre_ParVector *Rtilde; hypre_Vector *Xtilde_local; hypre_Vector *Rtilde_local; HYPRE_Real *x_data; HYPRE_Real *r_data; HYPRE_Real *tmp_data; HYPRE_Real *D_inv = NULL; /*HYPRE_Real *relax_weight = NULL; HYPRE_Real relax_type;*/ HYPRE_Int addlvl; HYPRE_Int num_levels; HYPRE_Int num_rows_L; HYPRE_Int num_rows_tmp; HYPRE_Int level, i; HYPRE_Int add_rlx; HYPRE_Real add_rlx_wt; HYPRE_Int add_last_lvl, add_end; /* Local variables */ HYPRE_Int Solve_err_flag = 0; hypre_Vector **l1_norms_ptr = NULL; hypre_Vector *l1_norms; HYPRE_Int l1_start; /* Acquire data and allocate storage */ A_array = hypre_ParAMGDataAArray(amg_data); F_array = hypre_ParAMGDataFArray(amg_data); U_array = hypre_ParAMGDataUArray(amg_data); addlvl = hypre_ParAMGDataSimple(amg_data); num_levels = hypre_ParAMGDataNumLevels(amg_data); add_rlx_wt = hypre_ParAMGDataAddRelaxWt(amg_data); add_rlx = hypre_ParAMGDataAddRelaxType(amg_data); add_last_lvl = hypre_ParAMGDataAddLastLvl(amg_data); /*relax_weight = hypre_ParAMGDataRelaxWeight(amg_data); relax_type = hypre_ParAMGDataGridRelaxType(amg_data)[1];*/ l1_norms_ptr = hypre_ParAMGDataL1Norms(amg_data); /* smooth_option = hypre_ParAMGDataSmoothOption(amg_data); */ if (add_last_lvl == -1 ) add_end = num_levels; else add_end = add_last_lvl; num_rows_L = 0; for (i=addlvl; i < add_end; i++) { A_tmp = A_array[i]; A_tmp_diag = hypre_ParCSRMatrixDiag(A_tmp); num_rows_tmp = hypre_CSRMatrixNumRows(A_tmp_diag); num_rows_L += num_rows_tmp; } Rtilde = hypre_CTAlloc(hypre_ParVector, 1, HYPRE_MEMORY_HOST); Rtilde_local = hypre_SeqVectorCreate(num_rows_L); hypre_SeqVectorInitialize(Rtilde_local); hypre_ParVectorLocalVector(Rtilde) = Rtilde_local; hypre_ParVectorOwnsData(Rtilde) = 1; Xtilde = hypre_CTAlloc(hypre_ParVector, 1, HYPRE_MEMORY_HOST); Xtilde_local = hypre_SeqVectorCreate(num_rows_L); hypre_SeqVectorInitialize(Xtilde_local); hypre_ParVectorLocalVector(Xtilde) = Xtilde_local; hypre_ParVectorOwnsData(Xtilde) = 1; x_data = hypre_VectorData(hypre_ParVectorLocalVector(Xtilde)); r_data = hypre_VectorData(hypre_ParVectorLocalVector(Rtilde)); D_inv = hypre_CTAlloc(HYPRE_Real, num_rows_L, HYPRE_MEMORY_HOST); l1_start = 0; for (level=addlvl; level < add_end; level++) { if (level != 0) { tmp_data = hypre_VectorData(hypre_ParVectorLocalVector(F_array[level])); if (tmp_data) { hypre_TFree(tmp_data, hypre_VectorMemoryLocation(hypre_ParVectorLocalVector(F_array[level]))); } hypre_VectorData(hypre_ParVectorLocalVector(F_array[level])) = &r_data[l1_start]; hypre_VectorOwnsData(hypre_ParVectorLocalVector(F_array[level])) = 0; tmp_data = hypre_VectorData(hypre_ParVectorLocalVector(U_array[level])); if (tmp_data) { hypre_TFree(tmp_data, hypre_VectorMemoryLocation(hypre_ParVectorLocalVector(U_array[level]))); } hypre_VectorData(hypre_ParVectorLocalVector(U_array[level])) = &x_data[l1_start]; hypre_VectorOwnsData(hypre_ParVectorLocalVector(U_array[level])) = 0; } A_tmp = A_array[level]; A_tmp_diag = hypre_ParCSRMatrixDiag(A_tmp); num_rows_tmp = hypre_CSRMatrixNumRows(A_tmp_diag); if (add_rlx == 0) { /*HYPRE_Real rlx_wt = relax_weight[level];*/ HYPRE_Int *A_tmp_diag_i = hypre_CSRMatrixI(A_tmp_diag); HYPRE_Real *A_tmp_diag_data = hypre_CSRMatrixData(A_tmp_diag); #ifdef HYPRE_USING_OPENMP #pragma omp for private(i) HYPRE_SMP_SCHEDULE #endif for (i=0; i < num_rows_tmp; i++) { D_inv[l1_start+i] = add_rlx_wt/A_tmp_diag_data[A_tmp_diag_i[i]]; } } else { l1_norms = l1_norms_ptr[level]; #ifdef HYPRE_USING_OPENMP #pragma omp for private(i) HYPRE_SMP_SCHEDULE #endif for (i=0; i < num_rows_tmp; i++) { D_inv[l1_start+i] = 1.0 / hypre_VectorData(l1_norms)[i]; } } l1_start += num_rows_tmp; } hypre_ParAMGDataDinv(amg_data) = D_inv; hypre_ParAMGDataRtilde(amg_data) = Rtilde; hypre_ParAMGDataXtilde(amg_data) = Xtilde; return Solve_err_flag; }
23,974
1,056
<gh_stars>1000+ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.javascript.karma.browsers; import org.junit.Test; import org.netbeans.modules.javascript.karma.browsers.util.TestUtils; public class OperaLegacyTest { @Test public void testValidFilePatterns() { assertFilePattern("<anonymous function>([arguments not available])@/home/gapon/NetBeansProjects/AngularSeeed/test/unit/directivesSpec.js:16", "/home/gapon/NetBeansProjects/AngularSeeed/test/unit/directivesSpec.js", 16); assertFilePattern("<anonymous function>([arguments not available])@/home/gapon/NetBeans Projects/AngularSeeed/test/unit/directivesSpec.js:16", "/home/gapon/NetBeans Projects/AngularSeeed/test/unit/directivesSpec.js", 16); assertFilePattern("<anonymous function>([arguments not available])@C:\\NetBeansProjects\\angular.js\\test\\ngCookies\\cookiesSpec.js:16", "C:\\NetBeansProjects\\angular.js\\test\\ngCookies\\cookiesSpec.js", 16); assertFilePattern("<anonymous function>([arguments not available])@C:\\NetBeans Projects\\angular.js\\test\\ngCookies\\cookiesSpec.js:16", "C:\\NetBeans Projects\\angular.js\\test\\ngCookies\\cookiesSpec.js", 16); assertFilePattern("workFn([arguments not available])@/home/gapon/NetBeansProjects/AngularSeeed/test/lib/angular/angular-mocks.js:1952", "/home/gapon/NetBeansProjects/AngularSeeed/test/lib/angular/angular-mocks.js", 1952); assertFilePattern("workFn([arguments not available])@/home/gapon/NetBeans Projects/AngularSeeed/test/lib/angular/angular-mocks.js:1952", "/home/gapon/NetBeans Projects/AngularSeeed/test/lib/angular/angular-mocks.js", 1952); assertFilePattern("workFn([arguments not available])@C:\\NetBeansProjects\\angular.js\\test\\ngCookies\\cookiesSpec.js:1952", "C:\\NetBeansProjects\\angular.js\\test\\ngCookies\\cookiesSpec.js", 1952); assertFilePattern("workFn([arguments not available])@C:\\NetBeans Projects\\angular.js\\test\\ngCookies\\cookiesSpec.js:1952", "C:\\NetBeans Projects\\angular.js\\test\\ngCookies\\cookiesSpec.js", 1952); assertFilePattern("@/home/gapon/NetBeansProjects/AngularSeeed/test/unit/directivesSpec.js:16", "/home/gapon/NetBeansProjects/AngularSeeed/test/unit/directivesSpec.js", 16); assertFilePattern("@/home/gapon/NetBeans Projects/AngularSeeed/test/unit/directivesSpec.js:16", "/home/gapon/NetBeans Projects/AngularSeeed/test/unit/directivesSpec.js", 16); assertFilePattern("@C:\\NetBeansProjects\\angular.js\\test\\ngCookies\\cookiesSpec.js:16", "C:\\NetBeansProjects\\angular.js\\test\\ngCookies\\cookiesSpec.js", 16); assertFilePattern("@C:\\NetBeans Projects\\angular.js\\test\\ngCookies\\cookiesSpec.js:16", "C:\\NetBeans Projects\\angular.js\\test\\ngCookies\\cookiesSpec.js", 16); } @Test public void testInvalidFilePatterns() { assertFilePattern("/home/gapon/NetBeansProjects/angular.js/src/auto/injector.js:6:12604", null, -1); assertFilePattern("C:\\NetBeansProjects\\angular.js\\src\\auto\\injector.js:6:12604", null, -1); assertFilePattern("(/home/gapon/NetBeansProjects/angular.js/src/auto/injector.js:6)", null, -1); } private void assertFilePattern(String input, String file, int line) { TestUtils.assertFileLinePattern(OperaLegacy.OUTPUT_FILE_LINE_PATTERN, input, file, line); } }
1,679
4,047
<gh_stars>1000+ #define PY_SSIZE_T_CLEAN #include <Python.h> #include <boost/python.hpp> struct World { void set(std::string msg) { this->msg = msg; } std::string greet() { return msg; } std::string version() { return std::to_string(PY_MAJOR_VERSION) + "." + std::to_string(PY_MINOR_VERSION); } std::string msg; }; BOOST_PYTHON_MODULE(MOD_NAME) { using namespace boost::python; class_<World>("World") .def("greet", &World::greet) .def("set", &World::set) .def("version", &World::version) ; }
241
328
/** * @file remoteconfig.cpp * */ /* Copyright (C) 2019-2021 by <NAME> mailto:<EMAIL> * * 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. */ #if !defined(__clang__) // Needed for compiling on MacOS # pragma GCC push_options # pragma GCC optimize ("Os") #endif #include <algorithm> #include <cstdint> #include <cstdio> #include <cstring> #include <cassert> #include "remoteconfig.h" #include "firmwareversion.h" #include "hardware.h" #include "network.h" #include "display.h" #include "properties.h" #include "propertiesconfig.h" #if defined(ENABLE_JSON_ONLY) # if !defined(DISABLE_BIN) # define DISABLE_BIN # endif #endif #include "remoteconfigjson.h" #include "spiflashstore.h" /* rconfig.txt */ #include "remoteconfigparams.h" #include "storeremoteconfig.h" /* network.txt */ #include "networkparams.h" #include "storenetwork.h" #if defined(DISPLAY_UDF) /* display.txt */ # include "displayudfparams.h" # include "storedisplayudf.h" #endif /** * NODE_ */ #if defined (NODE_ARTNET) /* artnet.txt */ # include "artnetparams.h" # include "storeartnet.h" # include "artnet4params.h" # include "storeartnet4.h" #endif #if defined (NODE_E131) /* e131.txt */ # include "e131params.h" # include "storee131.h" #endif #if defined (NODE_OSC_CLIENT) /* oscclnt.txt */ # include "oscclientparams.h" # include "storeoscclient.h" #endif #if defined (NODE_OSC_SERVER) /* osc.txt */ # include "oscserverparms.h" # include "storeoscserver.h" #endif #if defined (NODE_LTC_SMPTE) /* ltc.txt */ # include "ltcparams.h" # include "storeltc.h" /* ldisplay.txt */ # include "ltcdisplayparams.h" # include "storeltcdisplay.h" /* tcnet.txt */ # include "tcnetparams.h" # include "storetcnet.h" /* gps.txt */ # include "gpsparams.h" # include "storegps.h" #endif #if defined(NODE_SHOWFILE) /* show.txt */ # include "showfileparams.h" # include "storeshowfile.h" #endif #if defined(NODE_DDP_DISPLAY) /* ddpdisp.txt */ # include "ddpdisplayparams.h" # include "storeddpdisplay.h" #endif /** * OUTPUT_ */ #if defined (OUTPUT_DMX_SEND) /* params.txt */ # include "dmxparams.h" # include "storedmxsend.h" #endif #if defined (OUTPUT_DMX_PIXEL) /* devices.txt */ # include "ws28xxdmxparams.h" # include "storews28xxdmx.h" #endif #if defined (OUTPUT_DMX_TLC59711) /* devices.txt */ # include "tlc59711dmxparams.h" # include "storetlc59711.h" #endif #if defined (OUTPUT_DMX_MONITOR) /* mon.txt */ # include "dmxmonitorparams.h" # include "storemonitor.h" #endif #if defined(OUTPUT_DMX_STEPPER) /* sparkfun.txt */ # include "sparkfundmxparams.h" # include "storesparkfundmx.h" /* motor%.txt */ # include "modeparams.h" # include "motorparams.h" # include "l6470params.h" # include "storemotors.h" #endif #if defined (OUTPUT_DMX_SERIAL) /* serial.txt */ # include "dmxserialparams.h" # include "storedmxserial.h" #endif #if defined (OUTPUT_RGB_PANEL) /* rgbpanel.txt */ # include "rgbpanelparams.h" # include "storergbpanel.h" #endif #if defined (RDM_RESPONDER) /* sensors.txt */ # include "rdmsensorsparams.h" # include "storerdmsensors.h" /* "subdev.txt" */ # include "rdmsubdevicesparams.h" # include "storerdmdevice.h" #endif #if !defined(DISABLE_TFTP) // nuc-i5:~/uboot-spi/u-boot$ grep CONFIG_BOOTCOMMAND include/configs/sunxi-common.h // #define CONFIG_BOOTCOMMAND "sf probe; sf read 48000000 180000 22000; bootm 48000000" # define FIRMWARE_MAX_SIZE 0x22000 # include "tftp/tftpfileserver.h" # include "spiflashinstall.h" #endif #include "debug.h" namespace remoteconfig { namespace udp { static constexpr auto PORT = 0x2905; namespace cmd { namespace get { static constexpr char REBOOT[] = "?reboot##"; static constexpr char LIST[] = "?list#"; static constexpr char GET[] = "?get#"; static constexpr char UPTIME[] = "?uptime#"; static constexpr char VERSION[] = "?version#"; static constexpr char DISPLAY[] = "?display#"; #if !defined(DISABLE_BIN) static constexpr char STORE[] = "?store#"; #endif #if !defined(DISABLE_TFTP) static constexpr char TFTP[] = "?tftp#"; #endif static constexpr char FACTORY[] = "?factory##"; namespace length { static constexpr auto REBOOT = sizeof(cmd::get::REBOOT) - 1; static constexpr auto LIST = sizeof(cmd::get::LIST) - 1; static constexpr auto GET = sizeof(cmd::get::GET) - 1; static constexpr auto UPTIME = sizeof(cmd::get::UPTIME) - 1; static constexpr auto VERSION = sizeof(cmd::get::VERSION) - 1; static constexpr auto DISPLAY = sizeof(cmd::get::DISPLAY) - 1; #if !defined(DISABLE_BIN) static constexpr auto STORE = sizeof(cmd::get::STORE) - 1; #endif #if !defined(DISABLE_TFTP) static constexpr auto TFTP = sizeof(cmd::get::TFTP) - 1; #endif static constexpr auto FACTORY = sizeof(cmd::get::FACTORY) - 1; } // namespace length } // namespace get namespace set { static constexpr char DISPLAY[] = "!display#"; #if !defined(DISABLE_BIN) static constexpr char STORE[] = "!store#"; #endif #if !defined(DISABLE_TFTP) static constexpr char TFTP[] = "!tftp#"; #endif namespace length { static constexpr auto DISPLAY = sizeof(cmd::set::DISPLAY) - 1; #if !defined(DISABLE_BIN) static constexpr auto STORE = sizeof(cmd::set::STORE) - 1; #endif #if !defined(DISABLE_TFTP) static constexpr auto TFTP = sizeof(cmd::set::TFTP) - 1; #endif } // namespace length } // namespace set } // namespace cmd } // namespace udp } // namespace remoteconfig using namespace remoteconfig; static constexpr char s_Node[static_cast<uint32_t>(Node::LAST)][18] = { "Art-Net", "sACN E1.31", "OSC Server", "LTC", "OSC Client", "RDMNet LLRP Only", "Showfile", "MIDI", "DDP" }; static constexpr char s_Output[static_cast<uint32_t>(Output::LAST)][12] = { "DMX", "RDM", "Monitor", "Pixel", "TimeCode", "OSC", "Config", "Stepper", "Player", "Art-Net", "Serial", "RGB Panel" }; RemoteConfig *RemoteConfig::s_pThis = nullptr; ListBin RemoteConfig::s_RemoteConfigListBin; char *RemoteConfig::s_pUdpBuffer = nullptr; #if !defined(DISABLE_BIN) uint8_t RemoteConfig::s_StoreBuffer[udp::BUFFER_SIZE]; #endif RemoteConfig::RemoteConfig(Node tNode, Output tMode, uint32_t nOutputs): m_tNode(tNode), m_tOutput(tMode), m_nOutputs(nOutputs) { DEBUG_ENTRY assert(tNode < Node::LAST); assert(tMode < Output::LAST); assert(s_pThis == nullptr); s_pThis = this; Network::Get()->MacAddressCopyTo(s_RemoteConfigListBin.aMacAddress); s_RemoteConfigListBin.nNode = static_cast<uint8_t>(tNode); s_RemoteConfigListBin.nMode = static_cast<uint8_t>(tMode); s_RemoteConfigListBin.nOutputs = static_cast<uint8_t>(nOutputs); s_RemoteConfigListBin.aDisplayName[0] = '\0'; #ifndef NDEBUG DEBUG_PUTS("s_RemoteConfigListBin"); debug_dump(&s_RemoteConfigListBin, sizeof s_RemoteConfigListBin); #endif m_nHandle = Network::Get()->Begin(udp::PORT); assert(m_nHandle != -1); #if defined(ENABLE_HTTPD) m_HttpDaemon.Start(); #endif DEBUG_EXIT } RemoteConfig::~RemoteConfig() { DEBUG_ENTRY Network::Get()->End(udp::PORT); m_nHandle = -1; DEBUG_EXIT } const char *RemoteConfig::GetStringNode() const { return s_Node[s_RemoteConfigListBin.nNode]; } const char *RemoteConfig::GetStringMode() const { return s_Output[s_RemoteConfigListBin.nMode]; } void RemoteConfig::SetDisable(bool bDisable) { if (bDisable && !m_bDisable) { Network::Get()->End(udp::PORT); m_nHandle = -1; m_bDisable = true; } else if (!bDisable && m_bDisable) { m_nHandle = Network::Get()->Begin(udp::PORT); assert(m_nHandle != -1); m_bDisable = false; } DEBUG_PRINTF("m_bDisable=%d", m_bDisable); } void RemoteConfig::SetDisplayName(const char *pDisplayName) { DEBUG_ENTRY strncpy(s_RemoteConfigListBin.aDisplayName, pDisplayName, DISPLAY_NAME_LENGTH - 1); s_RemoteConfigListBin.aDisplayName[DISPLAY_NAME_LENGTH - 1] = '\0'; #ifndef NDEBUG debug_dump(&s_RemoteConfigListBin, sizeof s_RemoteConfigListBin); #endif DEBUG_EXIT } void RemoteConfig::Run() { if (__builtin_expect((m_bDisable), 1)) { return; } #if !defined(DISABLE_TFTP) if (__builtin_expect((m_pTFTPFileServer != nullptr), 0)) { m_pTFTPFileServer->Run(); } #endif #if defined(ENABLE_HTTPD) m_HttpDaemon.Run(); #endif uint16_t nForeignPort; m_nBytesReceived = Network::Get()->RecvFrom(m_nHandle, const_cast<const void **>(reinterpret_cast<void **>(&s_pUdpBuffer)), &m_nIPAddressFrom, &nForeignPort); if (__builtin_expect((m_nBytesReceived < 4), 1)) { return; } #ifndef NDEBUG debug_dump(s_pUdpBuffer, m_nBytesReceived); #endif if (s_pUdpBuffer[m_nBytesReceived - 1] == '\n') { m_nBytesReceived--; } if (s_pUdpBuffer[0] == '?') { DEBUG_PUTS("?"); if (m_bEnableReboot && (memcmp(s_pUdpBuffer, udp::cmd::get::REBOOT, udp::cmd::get::length::REBOOT) == 0)) { HandleReboot(); __builtin_unreachable(); return; } if (m_bEnableUptime && (memcmp(s_pUdpBuffer, udp::cmd::get::UPTIME, udp::cmd::get::length::UPTIME) == 0)) { HandleUptime(); return; } if (memcmp(s_pUdpBuffer, udp::cmd::get::VERSION, udp::cmd::get::length::VERSION) == 0) { HandleVersion(); return; } if (memcmp(s_pUdpBuffer, udp::cmd::get::LIST, udp::cmd::get::length::LIST) == 0) { HandleList(); return; } if ((m_nBytesReceived > udp::cmd::get::length::GET) && (memcmp(s_pUdpBuffer, udp::cmd::get::GET, udp::cmd::get::length::GET) == 0)) { HandleGet(); return; } #if !defined(DISABLE_BIN) if ((m_nBytesReceived > udp::cmd::get::length::STORE) && (memcmp(s_pUdpBuffer, udp::cmd::get::STORE, udp::cmd::get::length::STORE) == 0)) { HandleStoreGet(); return; } #endif if ((m_nBytesReceived == udp::cmd::get::length::DISPLAY) && (memcmp(s_pUdpBuffer, udp::cmd::get::DISPLAY, udp::cmd::get::length::DISPLAY) == 0)) { HandleDisplayGet(); return; } #if !defined(DISABLE_TFTP) if ((m_nBytesReceived == udp::cmd::get::length::TFTP) && (memcmp(s_pUdpBuffer, udp::cmd::get::TFTP, udp::cmd::get::length::TFTP) == 0)) { HandleTftpGet(); return; } #endif if (m_bEnableFactory && (memcmp(s_pUdpBuffer, udp::cmd::get::FACTORY, udp::cmd::get::length::FACTORY) == 0)) { HandleFactory(); return; } Network::Get()->SendTo(m_nHandle, "?#ERROR#\n", 9, m_nIPAddressFrom, udp::PORT); return; } if (!m_bDisableWrite) { if (s_pUdpBuffer[0] == '#') { DEBUG_PUTS("#"); m_tHandleMode = HandleMode::TXT; HandleTxtFile(); return; } else if (s_pUdpBuffer[0] == '!') { DEBUG_PUTS("!"); if ((m_nBytesReceived == udp::cmd::set::length::DISPLAY + 1) && (memcmp(s_pUdpBuffer, udp::cmd::set::DISPLAY, udp::cmd::set::length::DISPLAY) == 0)) { DEBUG_PUTS(udp::cmd::set::DISPLAY); HandleDisplaySet(); return; } #if !defined(DISABLE_TFTP) else if ((m_nBytesReceived == udp::cmd::set::length::TFTP + 1) && (memcmp(s_pUdpBuffer, udp::cmd::set::TFTP, udp::cmd::set::length::TFTP) == 0)) { DEBUG_PUTS(udp::cmd::set::TFTP); HandleTftpSet(); return; } #endif #if !defined(DISABLE_BIN) else if ((m_nBytesReceived > udp::cmd::set::length::STORE) && (memcmp(s_pUdpBuffer, udp::cmd::set::STORE, udp::cmd::set::length::STORE) == 0)) { DEBUG_PUTS(udp::cmd::set::STORE); m_tHandleMode = HandleMode::BIN; HandleTxtFile(); return; } #endif Network::Get()->SendTo(m_nHandle, "!#ERROR#\n", 9, m_nIPAddressFrom, udp::PORT); } return; } } void RemoteConfig::HandleUptime() { DEBUG_ENTRY const auto nUptime = Hardware::Get()->GetUpTime(); if (m_nBytesReceived == udp::cmd::get::length::UPTIME) { const auto nLength = snprintf(s_pUdpBuffer, udp::BUFFER_SIZE - 1, "uptime: %us\n", nUptime); Network::Get()->SendTo(m_nHandle, s_pUdpBuffer, static_cast<uint16_t>(nLength), m_nIPAddressFrom, udp::PORT); } #if !defined(DISABLE_BIN) else if (m_nBytesReceived == udp::cmd::get::length::UPTIME + 3) { if (memcmp(&s_pUdpBuffer[udp::cmd::get::length::UPTIME], "bin", 3) == 0) { Network::Get()->SendTo(m_nHandle, &nUptime, sizeof(uint32_t) , m_nIPAddressFrom, udp::PORT); } } #endif DEBUG_EXIT } void RemoteConfig::HandleVersion() { DEBUG_ENTRY if (m_nBytesReceived == udp::cmd::get::length::VERSION) { const auto *p = FirmwareVersion::Get()->GetPrint(); const auto nLength = snprintf(s_pUdpBuffer, udp::BUFFER_SIZE - 1, "version:%s", p); Network::Get()->SendTo(m_nHandle, s_pUdpBuffer, static_cast<uint16_t>(nLength), m_nIPAddressFrom, udp::PORT); } #if !defined(DISABLE_BIN) else if (m_nBytesReceived == udp::cmd::get::length::VERSION + 3) { if (memcmp(&s_pUdpBuffer[udp::cmd::get::length::VERSION], "bin", 3) == 0) { const auto *p = reinterpret_cast<const uint8_t*>(FirmwareVersion::Get()->GetVersion()); Network::Get()->SendTo(m_nHandle, p, sizeof(struct firmwareversion::Info) , m_nIPAddressFrom, udp::PORT); } } #endif DEBUG_EXIT } void RemoteConfig::HandleList() { DEBUG_ENTRY auto *pListResponse = &s_pUdpBuffer[udp::cmd::get::length::LIST + 1]; constexpr auto nListResponseBufferLength = udp::BUFFER_SIZE - (udp::cmd::get::length::LIST + 1); if (s_RemoteConfigListBin.aDisplayName[0] != '\0') { m_nIdLength = snprintf(pListResponse, nListResponseBufferLength - 1, "" IPSTR ",%s,%s,%d,%s\n", IP2STR(Network::Get()->GetIp()), s_Node[static_cast<uint32_t>(m_tNode)], s_Output[static_cast<uint32_t>(m_tOutput)], m_nOutputs, s_RemoteConfigListBin.aDisplayName); } else { m_nIdLength = snprintf(pListResponse, nListResponseBufferLength - 1, "" IPSTR ",%s,%s,%d\n", IP2STR(Network::Get()->GetIp()), s_Node[static_cast<uint32_t>(m_tNode)], s_Output[static_cast<uint32_t>(m_tOutput)], m_nOutputs); } if (m_nBytesReceived == udp::cmd::get::length::LIST) { Network::Get()->SendTo(m_nHandle, pListResponse, static_cast<uint16_t>(m_nIdLength), m_nIPAddressFrom, udp::PORT); DEBUG_EXIT return; } else if (m_nBytesReceived == udp::cmd::get::length::LIST + 1) { if (s_pUdpBuffer[udp::cmd::get::length::LIST] == '*') { Network::Get()->SendTo(m_nHandle, pListResponse, static_cast<uint16_t>(m_nIdLength), network::IP4_BROADCAST, udp::PORT); DEBUG_EXIT return; } } #if !defined(DISABLE_BIN) else if (m_nBytesReceived == udp::cmd::get::length::LIST + 3) { if (memcmp(&s_pUdpBuffer[udp::cmd::get::length::LIST], "bin", 3) == 0) { Network::Get()->SendTo(m_nHandle, &s_RemoteConfigListBin, sizeof(struct ListBin) , m_nIPAddressFrom, udp::PORT); return; } } else if (m_nBytesReceived == udp::cmd::get::length::LIST + 4) { if (memcmp(&s_pUdpBuffer[udp::cmd::get::length::LIST], "bin*", 4) == 0) { Network::Get()->SendTo(m_nHandle, &s_RemoteConfigListBin, sizeof(struct ListBin) , network::IP4_BROADCAST, udp::PORT); return; } } #endif Network::Get()->SendTo(m_nHandle, "?list#ERROR#\n", 13, m_nIPAddressFrom, udp::PORT); DEBUG_EXIT } void RemoteConfig::HandleDisplaySet() { DEBUG_ENTRY DEBUG_PRINTF("%c", s_pUdpBuffer[udp::cmd::set::length::DISPLAY]); Display::Get()->SetSleep(s_pUdpBuffer[udp::cmd::set::length::DISPLAY] == '0'); DEBUG_EXIT } void RemoteConfig::HandleDisplayGet() { DEBUG_ENTRY const bool isOn = !(Display::Get()->isSleep()); if (m_nBytesReceived == udp::cmd::get::length::DISPLAY) { const auto nLength = snprintf(s_pUdpBuffer, udp::BUFFER_SIZE - 1, "display:%s\n", isOn ? "On" : "Off"); Network::Get()->SendTo(m_nHandle, s_pUdpBuffer, static_cast<uint16_t>(nLength), m_nIPAddressFrom, udp::PORT); } #if !defined(DISABLE_BIN) else if (m_nBytesReceived == udp::cmd::get::length::DISPLAY + 3) { if (memcmp(&s_pUdpBuffer[udp::cmd::get::length::DISPLAY], "bin", 3) == 0) { Network::Get()->SendTo(m_nHandle, &isOn, sizeof(bool) , m_nIPAddressFrom, udp::PORT); } } #endif DEBUG_EXIT } #if !defined(DISABLE_BIN) void RemoteConfig::HandleStoreGet() { DEBUG_ENTRY uint32_t nLength = udp::BUFFER_SIZE - udp::cmd::get::length::STORE; const auto nIndex = GetIndex(&s_pUdpBuffer[udp::cmd::get::length::STORE], nLength); if (nIndex != TxtFile::LAST) { SpiFlashStore::Get()->CopyTo(GetStore(static_cast<TxtFile>(nIndex)), s_pUdpBuffer, nLength); } else { Network::Get()->SendTo(m_nHandle, "?store#ERROR#\n", 12, m_nIPAddressFrom, udp::PORT); return; } #ifndef NDEBUG debug_dump(s_pUdpBuffer, static_cast<uint16_t>(nLength)); #endif Network::Get()->SendTo(m_nHandle, s_pUdpBuffer, static_cast<uint16_t>(nLength), m_nIPAddressFrom, udp::PORT); DEBUG_EXIT } #endif uint32_t RemoteConfig::HandleGet(void *pBuffer, uint32_t nBufferLength) { DEBUG_ENTRY uint32_t nSize; TxtFile nIndex; if (pBuffer == nullptr) { nSize = udp::BUFFER_SIZE - udp::cmd::get::length::GET; assert(s_pUdpBuffer != nullptr); nIndex = GetIndex(&s_pUdpBuffer[udp::cmd::get::length::GET], nSize); } else { s_pUdpBuffer = reinterpret_cast<char *>(pBuffer); nSize = nBufferLength; nIndex = GetIndex(pBuffer, nSize); } switch (nIndex) { case TxtFile::RCONFIG: HandleGetRconfigTxt(nSize); break; case TxtFile::NETWORK: HandleGetNetworkTxt(nSize); break; #if defined (NODE_ARTNET) case TxtFile::ARTNET: HandleGetArtnetTxt(nSize); break; #endif #if defined (NODE_E131) case TxtFile::E131: HandleGetE131Txt(nSize); break; #endif #if defined (NODE_OSC_SERVER) case TxtFile::OSC_SERVER: HandleGetOscTxt(nSize); break; #endif #if defined (OUTPUT_DMX_SEND) case TxtFile::PARAMS: HandleGetParamsTxt(nSize); break; #endif #if defined (OUTPUT_DMX_PIXEL) || defined (OUTPUT_DMX_TLC59711) case TxtFile::DEVICES: HandleGetDevicesTxt(nSize); break; #endif #if defined (NODE_LTC_SMPTE) case TxtFile::LTC: HandleGetLtcTxt(nSize); break; case TxtFile::LTCDISPLAY: HandleGetLtcDisplayTxt(nSize); break; case TxtFile::TCNET: HandleGetTCNetTxt(nSize); break; case TxtFile::GPS: HandleGetGpsTxt(nSize); break; #endif #if defined (OUTPUT_DMX_MONITOR) case TxtFile::MONITOR: HandleGetMonTxt(nSize); break; #endif #if defined (NODE_OSC_CLIENT) case TxtFile::OSC_CLIENT: HandleGetOscClntTxt(nSize); break; #endif #if defined(DISPLAY_UDF) case TxtFile::DISPLAY: HandleGetDisplayTxt(nSize); break; #endif #if defined(OUTPUT_DMX_STEPPER) case TxtFile::SPARKFUN: HandleGetSparkFunTxt(nSize); break; case TxtFile::MOTOR0: case TxtFile::MOTOR1: case TxtFile::MOTOR2: case TxtFile::MOTOR3: HandleGetMotorTxt(static_cast<uint32_t>(nIndex) - static_cast<uint32_t>(TxtFile::MOTOR0), nSize); break; #endif #if defined(NODE_SHOWFILE) case TxtFile::SHOW: HandleGetShowTxt(nSize); break; #endif #if defined (OUTPUT_DMX_SERIAL) case TxtFile::SERIAL: HandleGetSerialTxt(nSize); break; #endif #if defined (OUTPUT_RGB_PANEL) case TxtFile::RGBPANEL: HandleGetRgbPanelTxt(nSize); break; #endif #if defined (NODE_DDP_DISPLAY) case TxtFile::DDPDISP: HandleGetDdpDisplayTxt(nSize); break; #endif default: if (pBuffer == nullptr) { Network::Get()->SendTo(m_nHandle, "?get#ERROR#\n", 12, m_nIPAddressFrom, udp::PORT); } else { DEBUG_PUTS(""); memcpy(pBuffer, "?get#ERROR#\n", std::min(12U, nBufferLength)); } DEBUG_EXIT return 12; __builtin_unreachable (); break; } #ifndef NDEBUG // debug_dump(s_pUdpBuffer, static_cast<uint16_t>(nSize)); #endif if (pBuffer == nullptr) { Network::Get()->SendTo(m_nHandle, s_pUdpBuffer, static_cast<uint16_t>(nSize), m_nIPAddressFrom, udp::PORT); } else { memcpy(pBuffer, s_pUdpBuffer, std::min(nSize, nBufferLength)); } DEBUG_EXIT return nSize; } void RemoteConfig::HandleGetRconfigTxt(uint32_t& nSize) { DEBUG_ENTRY RemoteConfigParams remoteConfigParams(StoreRemoteConfig::Get()); remoteConfigParams.Save(s_pUdpBuffer, udp::BUFFER_SIZE, nSize); DEBUG_EXIT } void RemoteConfig::HandleGetNetworkTxt(uint32_t& nSize) { DEBUG_ENTRY NetworkParams networkParams(StoreNetwork::Get()); networkParams.Save(s_pUdpBuffer, udp::BUFFER_SIZE, nSize); DEBUG_EXIT } #if defined (NODE_ARTNET) void RemoteConfig::HandleGetArtnetTxt(uint32_t& nSize) { DEBUG_ENTRY uint32_t nSizeArtNet3 = 0; assert(StoreArtNet::Get() != nullptr); ArtNetParams artnetparams(StoreArtNet::Get()); artnetparams.Save(s_pUdpBuffer, udp::BUFFER_SIZE, nSizeArtNet3); uint32_t nSizeArtNet4 = 0; assert(StoreArtNet4::Get() != nullptr); ArtNet4Params artnet4params(StoreArtNet4::Get()); artnet4params.Save(s_pUdpBuffer + nSizeArtNet3, udp::BUFFER_SIZE - nSizeArtNet3, nSizeArtNet4); nSize = nSizeArtNet3 + nSizeArtNet4; DEBUG_EXIT } #endif #if defined (NODE_E131) void RemoteConfig::HandleGetE131Txt(uint32_t& nSize) { DEBUG_ENTRY E131Params e131params(StoreE131::Get()); e131params.Save(s_pUdpBuffer, udp::BUFFER_SIZE, nSize); DEBUG_EXIT } #endif #if defined (NODE_OSC_SERVER) void RemoteConfig::HandleGetOscTxt(uint32_t& nSize) { DEBUG_ENTRY OSCServerParams oscServerParams(StoreOscServer::Get()); oscServerParams.Save(s_pUdpBuffer, udp::BUFFER_SIZE, nSize); DEBUG_EXIT } #endif #if defined (NODE_OSC_CLIENT) void RemoteConfig::HandleGetOscClntTxt(uint32_t& nSize) { DEBUG_ENTRY OscClientParams oscClientParams(StoreOscClient::Get()); oscClientParams.Save(s_pUdpBuffer, udp::BUFFER_SIZE, nSize); DEBUG_EXIT } #endif #if defined (OUTPUT_DMX_SEND) void RemoteConfig::HandleGetParamsTxt(uint32_t& nSize) { DEBUG_ENTRY DmxParams dmxparams(StoreDmxSend::Get()); dmxparams.Save(s_pUdpBuffer, udp::BUFFER_SIZE, nSize); DEBUG_EXIT } #endif #if defined (OUTPUT_DMX_PIXEL) || defined (OUTPUT_DMX_TLC59711) void RemoteConfig::HandleGetDevicesTxt(uint32_t& nSize) { DEBUG_ENTRY # if defined (OUTPUT_DMX_TLC59711) bool bIsSetLedType = false; TLC59711DmxParams tlc5911params(StoreTLC59711::Get()); if (tlc5911params.Load()) { # if defined (OUTPUT_DMX_PIXEL) if ((bIsSetLedType = tlc5911params.IsSetLedType()) == true) { # endif tlc5911params.Save(s_pUdpBuffer, udp::BUFFER_SIZE, nSize); # if defined (OUTPUT_DMX_PIXEL) } # endif } if (!bIsSetLedType) { # endif #if defined (OUTPUT_DMX_PIXEL) WS28xxDmxParams ws28xxparms(StoreWS28xxDmx::Get()); ws28xxparms.Save(s_pUdpBuffer, udp::BUFFER_SIZE, nSize); #endif # if defined (OUTPUT_DMX_TLC59711) } #endif DEBUG_EXIT } #endif #if defined (NODE_LTC_SMPTE) void RemoteConfig::HandleGetLtcTxt(uint32_t& nSize) { DEBUG_ENTRY LtcParams ltcParams(StoreLtc::Get()); ltcParams.Save(s_pUdpBuffer, udp::BUFFER_SIZE, nSize); DEBUG_EXIT } void RemoteConfig::HandleGetLtcDisplayTxt(uint32_t& nSize) { DEBUG_ENTRY LtcDisplayParams ltcDisplayParams(StoreLtcDisplay::Get()); ltcDisplayParams.Save(s_pUdpBuffer, udp::BUFFER_SIZE, nSize); DEBUG_EXIT } void RemoteConfig::HandleGetTCNetTxt(uint32_t& nSize) { DEBUG_ENTRY TCNetParams tcnetParams(StoreTCNet::Get()); tcnetParams.Save(s_pUdpBuffer, udp::BUFFER_SIZE, nSize); DEBUG_EXIT } void RemoteConfig::HandleGetGpsTxt(uint32_t& nSize) { DEBUG_ENTRY GPSParams gpsParams(StoreGPS::Get()); gpsParams.Save(s_pUdpBuffer, udp::BUFFER_SIZE, nSize); DEBUG_EXIT } #endif #if defined(OUTPUT_DMX_MONITOR) void RemoteConfig::HandleGetMonTxt(uint32_t& nSize) { DEBUG_ENTRY DMXMonitorParams monitorParams(StoreMonitor::Get()); monitorParams.Save(s_pUdpBuffer, udp::BUFFER_SIZE, nSize); DEBUG_EXIT } #endif #if defined(DISPLAY_UDF) void RemoteConfig::HandleGetDisplayTxt(uint32_t& nSize) { DEBUG_ENTRY DisplayUdfParams displayParams(StoreDisplayUdf::Get()); displayParams.Save(s_pUdpBuffer, udp::BUFFER_SIZE, nSize); DEBUG_EXIT } #endif #if defined(OUTPUT_DMX_STEPPER) void RemoteConfig::HandleGetSparkFunTxt(uint32_t& nSize) { DEBUG_ENTRY SparkFunDmxParams sparkFunParams(StoreSparkFunDmx::Get()); sparkFunParams.Save(s_pUdpBuffer, udp::BUFFER_SIZE, nSize); DEBUG_EXIT } void RemoteConfig::HandleGetMotorTxt(uint32_t nMotorIndex, uint32_t& nSize) { DEBUG_ENTRY DEBUG_PRINTF("nMotorIndex=%d", nMotorIndex); uint32_t nSizeSparkFun = 0; SparkFunDmxParams sparkFunParams(StoreSparkFunDmx::Get()); sparkFunParams.Save(s_pUdpBuffer, udp::BUFFER_SIZE, nSizeSparkFun, nMotorIndex); DEBUG_PRINTF("nSizeSparkFun=%d", nSizeSparkFun); uint32_t nSizeMode = 0; ModeParams modeParams(StoreMotors::Get()); modeParams.Save(nMotorIndex, s_pUdpBuffer + nSizeSparkFun, udp::BUFFER_SIZE - nSizeSparkFun, nSizeMode); DEBUG_PRINTF("nSizeMode=%d", nSizeMode); uint32_t nSizeMotor = 0; MotorParams motorParams(StoreMotors::Get()); motorParams.Save(nMotorIndex, s_pUdpBuffer + nSizeSparkFun + nSizeMode, udp::BUFFER_SIZE - nSizeSparkFun - nSizeMode, nSizeMotor); DEBUG_PRINTF("nSizeMotor=%d", nSizeMotor); uint32_t nSizeL6470 = 0; L6470Params l6470Params(StoreMotors::Get()); l6470Params.Save(nMotorIndex, s_pUdpBuffer + nSizeSparkFun + nSizeMode + nSizeMotor, udp::BUFFER_SIZE - nSizeSparkFun - nSizeMode - nSizeMotor, nSizeL6470); DEBUG_PRINTF("nSizeL6470=%d", nSizeL6470); nSize = nSizeSparkFun + nSizeMode + nSizeMotor + nSizeL6470; DEBUG_EXIT } #endif #if defined(NODE_SHOWFILE) void RemoteConfig::HandleGetShowTxt(uint32_t& nSize) { DEBUG_ENTRY ShowFileParams showFileParams(StoreShowFile::Get()); showFileParams.Save(s_pUdpBuffer, udp::BUFFER_SIZE, nSize); DEBUG_EXIT } #endif #if defined (OUTPUT_DMX_SERIAL) void RemoteConfig::HandleGetSerialTxt(uint32_t& nSize) { DEBUG_ENTRY DmxSerialParams dmxSerialParams(StoreDmxSerial::Get()); dmxSerialParams.Save(s_pUdpBuffer, udp::BUFFER_SIZE, nSize); DEBUG_EXIT } #endif #if defined (OUTPUT_RGB_PANEL) void RemoteConfig::HandleGetRgbPanelTxt(uint32_t& nSize) { DEBUG_ENTRY RgbPanelParams rgbPanelParams(StoreRgbPanel::Get()); rgbPanelParams.Save(s_pUdpBuffer, udp::BUFFER_SIZE, nSize); DEBUG_EXIT } #endif #if defined (NODE_DDP_DISPLAY) void RemoteConfig::HandleGetDdpDisplayTxt(uint32_t& nSize) { DEBUG_ENTRY DdpDisplayParams ddpDisplayParams(StoreDdpDisplay::Get()); ddpDisplayParams.Save(s_pUdpBuffer, udp::BUFFER_SIZE, nSize); DEBUG_EXIT } #endif /* * */ void RemoteConfig::HandleTxtFile(void *pBuffer, uint32_t nBufferLength) { DEBUG_ENTRY TxtFile i = TxtFile::LAST; uint32_t nLength; if (pBuffer == nullptr) { #if !defined(DISABLE_BIN) if (m_tHandleMode == HandleMode::TXT) { #endif nLength = udp::BUFFER_SIZE - 1; i = GetIndex(&s_pUdpBuffer[1], nLength); #if !defined(DISABLE_BIN) } else { nLength = udp::BUFFER_SIZE - udp::cmd::set::length::STORE; i = GetIndex(&s_pUdpBuffer[udp::cmd::set::length::STORE], nLength); if (i < TxtFile::LAST) { m_nBytesReceived = static_cast<uint16_t>(m_nBytesReceived - nLength - udp::cmd::set::length::STORE); memcpy(s_StoreBuffer, &s_pUdpBuffer[nLength + udp::cmd::set::length::STORE], udp::BUFFER_SIZE); debug_dump(s_StoreBuffer, m_nBytesReceived); } else { return; } } #endif } else if (nBufferLength <= udp::BUFFER_SIZE){ DEBUG_PUTS(""); m_tHandleMode = HandleMode::TXT; if (PropertiesConfig::IsJSON() && (reinterpret_cast<char *>(pBuffer)[0] == '{')) { DEBUG_PUTS("JSON"); int c; assert(nBufferLength > 1); if ((c = properties::convert_json_file(reinterpret_cast<char *>(pBuffer), static_cast<uint16_t>(nBufferLength - 1U))) <= 0) { DEBUG_EXIT return; } debug_dump(pBuffer, c); m_nBytesReceived = static_cast<uint16_t>(c); } else { m_nBytesReceived = static_cast<uint16_t>(nBufferLength); } s_pUdpBuffer = reinterpret_cast<char *>(pBuffer); i = GetIndex(&s_pUdpBuffer[1], nBufferLength); } else { return; } switch (i) { case TxtFile::RCONFIG: HandleTxtFileRconfig(); break; case TxtFile::NETWORK: HandleTxtFileNetwork(); break; #if defined (NODE_ARTNET) case TxtFile::ARTNET: HandleTxtFileArtnet(); break; #endif #if defined (NODE_E131) case TxtFile::E131: HandleTxtFileE131(); break; #endif #if defined (NODE_OSC_SERVER) case TxtFile::OSC_SERVER: HandleTxtFileOsc(); break; #endif #if defined (OUTPUT_DMX_SEND) case TxtFile::PARAMS: HandleTxtFileParams(); break; #endif #if defined (OUTPUT_DMX_PIXEL) || defined (OUTPUT_DMX_TLC59711) case TxtFile::DEVICES: HandleTxtFileDevices(); break; #endif #if defined (NODE_LTC_SMPTE) case TxtFile::LTC: HandleTxtFileLtc(); break; case TxtFile::LTCDISPLAY: HandleTxtFileLtcDisplay(); break; case TxtFile::TCNET: HandleTxtFileTCNet(); break; case TxtFile::GPS: HandleTxtFileGps(); break; #endif #if defined (NODE_OSC_CLIENT) case TxtFile::OSC_CLIENT: HandleTxtFileOscClient(); break; #endif #if defined(OUTPUT_DMX_MONITOR) case TxtFile::MONITOR: HandleTxtFileMon(); break; #endif #if defined(DISPLAY_UDF) case TxtFile::DISPLAY: HandleTxtFileDisplay(); break; #endif #if defined(OUTPUT_DMX_STEPPER) case TxtFile::SPARKFUN: HandleTxtFileSparkFun(); break; case TxtFile::MOTOR0: case TxtFile::MOTOR1: case TxtFile::MOTOR2: case TxtFile::MOTOR3: HandleTxtFileMotor(static_cast<uint32_t>(i) - static_cast<uint32_t>(TxtFile::MOTOR0)); break; #endif #if defined (NODE_SHOWFILE) case TxtFile::SHOW: HandleTxtFileShow(); break; #endif #if defined (OUTPUT_DMX_SERIAL) case TxtFile::SERIAL: HandleTxtFileSerial(); break; #endif #if defined (OUTPUT_RGB_PANEL) case TxtFile::RGBPANEL: HandleTxtFileRgbPanel(); break; #endif #if defined (NODE_DDP_DISPLAY) case TxtFile::DDPDISP: HandleTxtFileDdpDisplay(); break; #endif default: break; } DEBUG_EXIT } void RemoteConfig::HandleTxtFileRconfig() { DEBUG_ENTRY RemoteConfigParams remoteConfigParams(StoreRemoteConfig::Get()); #if !defined(DISABLE_BIN) if (m_tHandleMode == HandleMode::BIN) { if (m_nBytesReceived == sizeof(struct TRemoteConfigParams)) { uint32_t nSize; remoteConfigParams.Builder(reinterpret_cast<const struct TRemoteConfigParams*>(s_StoreBuffer), s_pUdpBuffer, udp::BUFFER_SIZE, nSize); m_nBytesReceived = static_cast<uint16_t>(nSize); } else { DEBUG_EXIT return; } } #endif remoteConfigParams.Load(s_pUdpBuffer, m_nBytesReceived); remoteConfigParams.Set(this); #ifndef NDEBUG remoteConfigParams.Dump(); #endif DEBUG_EXIT } void RemoteConfig::HandleTxtFileNetwork() { DEBUG_ENTRY NetworkParams params(StoreNetwork::Get()); #if !defined(DISABLE_BIN) if (m_tHandleMode == HandleMode::BIN) { if (m_nBytesReceived == sizeof(struct TNetworkParams)) { uint32_t nSize; params.Builder(reinterpret_cast<const struct TNetworkParams*>(s_StoreBuffer), s_pUdpBuffer, udp::BUFFER_SIZE, nSize); m_nBytesReceived = static_cast<uint16_t>(nSize); } else { DEBUG_EXIT return; } } #endif params.Load(s_pUdpBuffer, m_nBytesReceived); #ifndef NDEBUG params.Dump(); #endif DEBUG_EXIT } #if defined (NODE_ARTNET) void RemoteConfig::HandleTxtFileArtnet() { DEBUG_ENTRY static_assert(sizeof(struct TArtNet4Params) != sizeof(struct artnetparams::Params), ""); assert(StoreArtNet4::Get() != nullptr); ArtNet4Params artnet4params(StoreArtNet4::Get()); #if !defined(DISABLE_BIN) if (m_tHandleMode == HandleMode::BIN) { if (m_nBytesReceived == sizeof(struct artnetparams::Params)) { ArtNetParams artnetparams(StoreArtNet::Get()); uint32_t nSize; artnetparams.Builder(reinterpret_cast<const struct artnetparams::Params*>(s_StoreBuffer), s_pUdpBuffer, udp::BUFFER_SIZE, nSize); m_nBytesReceived = static_cast<uint16_t>(nSize); } else if (m_nBytesReceived == sizeof(struct TArtNet4Params)) { uint32_t nSize; artnet4params.Builder(reinterpret_cast<const struct TArtNet4Params*>(s_StoreBuffer), s_pUdpBuffer, udp::BUFFER_SIZE, nSize); m_nBytesReceived = static_cast<uint16_t>(nSize); } else { DEBUG_EXIT return; } } #endif artnet4params.Load(s_pUdpBuffer, m_nBytesReceived); #ifndef NDEBUG artnet4params.Dump(); #endif DEBUG_EXIT } #endif #if defined (NODE_E131) void RemoteConfig::HandleTxtFileE131() { DEBUG_ENTRY E131Params e131params(StoreE131::Get()); #if !defined(DISABLE_BIN) if (m_tHandleMode == HandleMode::BIN) { if (m_nBytesReceived == sizeof(struct e131params::Params)) { uint32_t nSize; e131params.Builder(reinterpret_cast<const struct e131params::Params*>(s_StoreBuffer), s_pUdpBuffer, udp::BUFFER_SIZE, nSize); m_nBytesReceived = static_cast<uint16_t>(nSize); } else { DEBUG_EXIT return; } } #endif e131params.Load(s_pUdpBuffer, m_nBytesReceived); #ifndef NDEBUG e131params.Dump(); #endif DEBUG_EXIT } #endif #if defined (NODE_OSC_SERVER) void RemoteConfig::HandleTxtFileOsc() { DEBUG_ENTRY OSCServerParams oscServerParams(StoreOscServer::Get()); #if !defined(DISABLE_BIN) if (m_tHandleMode == HandleMode::BIN) { if (m_nBytesReceived == sizeof(struct TOSCServerParams)) { uint32_t nSize; oscServerParams.Builder(reinterpret_cast<const struct TOSCServerParams*>(s_StoreBuffer), s_pUdpBuffer, udp::BUFFER_SIZE, nSize); m_nBytesReceived = static_cast<uint16_t>(nSize); } else { DEBUG_EXIT return; } } #endif oscServerParams.Load(s_pUdpBuffer, m_nBytesReceived); #ifndef NDEBUG oscServerParams.Dump(); #endif DEBUG_EXIT } #endif #if defined (NODE_OSC_CLIENT) void RemoteConfig::HandleTxtFileOscClient() { DEBUG_ENTRY OscClientParams oscClientParams(StoreOscClient::Get()); #if !defined(DISABLE_BIN) if (m_tHandleMode == HandleMode::BIN) { if (m_nBytesReceived == sizeof(struct TOscClientParams)) { uint32_t nSize; oscClientParams.Builder(reinterpret_cast<const struct TOscClientParams *>(s_StoreBuffer), s_pUdpBuffer, udp::BUFFER_SIZE, nSize); m_nBytesReceived = static_cast<uint16_t>(nSize); } else { DEBUG_EXIT return; } } #endif oscClientParams.Load(s_pUdpBuffer, m_nBytesReceived); #ifndef NDEBUG oscClientParams.Dump(); #endif DEBUG_EXIT } #endif #if defined (OUTPUT_DMX_SEND) void RemoteConfig::HandleTxtFileParams() { DEBUG_ENTRY DmxParams dmxparams(StoreDmxSend::Get()); #if !defined(DISABLE_BIN) if (m_tHandleMode == HandleMode::BIN) { if (m_nBytesReceived == sizeof(struct TDmxParams)) { uint32_t nSize; dmxparams.Builder(reinterpret_cast<const struct TDmxParams *>(s_StoreBuffer), s_pUdpBuffer, udp::BUFFER_SIZE, nSize); m_nBytesReceived = static_cast<uint16_t>(nSize); } else { DEBUG_EXIT return; } } #endif dmxparams.Load(s_pUdpBuffer, m_nBytesReceived); #ifndef NDEBUG dmxparams.Dump(); #endif DEBUG_EXIT } #endif #if defined (OUTPUT_DMX_PIXEL) || defined (OUTPUT_DMX_TLC59711) void RemoteConfig::HandleTxtFileDevices() { DEBUG_ENTRY # if defined (OUTPUT_DMX_TLC59711) # if defined (OUTPUT_DMX_PIXEL) static_assert(sizeof(struct TTLC59711DmxParams) != sizeof(struct TWS28xxDmxParams), ""); # endif TLC59711DmxParams tlc59711params(StoreTLC59711::Get()); #if !defined(DISABLE_BIN) if (m_tHandleMode == HandleMode::BIN) { if (m_nBytesReceived == sizeof(struct TTLC59711DmxParams)) { uint32_t nSize; tlc59711params.Builder(reinterpret_cast<const struct TTLC59711DmxParams*>(s_StoreBuffer), s_pUdpBuffer, udp::BUFFER_SIZE, nSize); m_nBytesReceived = static_cast<uint16_t>(nSize); } else { DEBUG_EXIT return; } } #endif tlc59711params.Load(s_pUdpBuffer, m_nBytesReceived); # ifndef NDEBUG tlc59711params.Dump(); # endif DEBUG_PRINTF("tlc5911params.IsSetLedType()=%d", tlc59711params.IsSetLedType()); if (!tlc59711params.IsSetLedType()) { # endif #if defined (OUTPUT_DMX_PIXEL) WS28xxDmxParams ws28xxparms(StoreWS28xxDmx::Get()); #if !defined(DISABLE_BIN) if (m_tHandleMode == HandleMode::BIN) { if (m_nBytesReceived == sizeof(struct TWS28xxDmxParams)) { uint32_t nSize; ws28xxparms.Builder(reinterpret_cast<const struct TWS28xxDmxParams *>(s_StoreBuffer), s_pUdpBuffer, udp::BUFFER_SIZE, nSize); m_nBytesReceived = static_cast<uint16_t>(nSize); } else { DEBUG_EXIT return; } } # endif ws28xxparms.Load(s_pUdpBuffer, m_nBytesReceived); # ifndef NDEBUG ws28xxparms.Dump(); # endif # endif # if defined (OUTPUT_DMX_TLC59711) } # endif DEBUG_EXIT } #endif #if defined (NODE_LTC_SMPTE) void RemoteConfig::HandleTxtFileLtc() { DEBUG_ENTRY LtcParams ltcParams(StoreLtc::Get()); #if !defined(DISABLE_BIN) if (m_tHandleMode == HandleMode::BIN) { if (m_nBytesReceived == sizeof(struct TLtcParams)) { uint32_t nSize; ltcParams.Builder(reinterpret_cast<const struct TLtcParams *>(s_StoreBuffer), s_pUdpBuffer, udp::BUFFER_SIZE, nSize); m_nBytesReceived = static_cast<uint16_t>(nSize); } else { DEBUG_EXIT return; } } #endif ltcParams.Load(s_pUdpBuffer, m_nBytesReceived); #ifndef NDEBUG ltcParams.Dump(); #endif DEBUG_EXIT } void RemoteConfig::HandleTxtFileLtcDisplay() { DEBUG_ENTRY LtcDisplayParams ltcDisplayParams(StoreLtcDisplay::Get()); #if !defined(DISABLE_BIN) if (m_tHandleMode == HandleMode::BIN) { if (m_nBytesReceived == sizeof(struct TLtcDisplayParams)) { uint32_t nSize; ltcDisplayParams.Builder(reinterpret_cast<const struct TLtcDisplayParams *>(s_StoreBuffer), s_pUdpBuffer, udp::BUFFER_SIZE, nSize); m_nBytesReceived = static_cast<uint16_t>(nSize); } else { DEBUG_EXIT return; } } #endif ltcDisplayParams.Load(s_pUdpBuffer, m_nBytesReceived); #ifndef NDEBUG ltcDisplayParams.Dump(); #endif DEBUG_EXIT } void RemoteConfig::HandleTxtFileTCNet() { DEBUG_ENTRY TCNetParams tcnetParams(StoreTCNet::Get()); #if !defined(DISABLE_BIN) if (m_tHandleMode == HandleMode::BIN) { if (m_nBytesReceived == sizeof(struct TTCNetParams)) { uint32_t nSize; tcnetParams.Builder(reinterpret_cast<const struct TTCNetParams*>(s_StoreBuffer), s_pUdpBuffer, udp::BUFFER_SIZE, nSize); m_nBytesReceived = static_cast<uint16_t>(nSize); } else { DEBUG_EXIT return; } } #endif tcnetParams.Load(s_pUdpBuffer, m_nBytesReceived); #ifndef NDEBUG tcnetParams.Dump(); #endif DEBUG_EXIT } void RemoteConfig::HandleTxtFileGps() { DEBUG_ENTRY GPSParams gpsParams(StoreGPS::Get()); #if !defined(DISABLE_BIN) if (m_tHandleMode == HandleMode::BIN) { if (m_nBytesReceived == sizeof(struct TGPSParams)) { uint32_t nSize; gpsParams.Builder(reinterpret_cast<const struct TGPSParams*>(s_StoreBuffer), s_pUdpBuffer, udp::BUFFER_SIZE, nSize); m_nBytesReceived = static_cast<uint16_t>(nSize); } else { DEBUG_EXIT return; } } #endif gpsParams.Load(s_pUdpBuffer, m_nBytesReceived); #ifndef NDEBUG gpsParams.Dump(); #endif DEBUG_EXIT } #endif #if defined(OUTPUT_DMX_MONITOR) void RemoteConfig::HandleTxtFileMon() { DEBUG_ENTRY DMXMonitorParams monitorParams(StoreMonitor::Get()); #if !defined(DISABLE_BIN) if (m_tHandleMode == HandleMode::BIN) { if (m_nBytesReceived == sizeof(struct TDMXMonitorParams)) { uint32_t nSize; monitorParams.Builder(reinterpret_cast<const struct TDMXMonitorParams*>(s_StoreBuffer), s_pUdpBuffer, udp::BUFFER_SIZE, nSize); m_nBytesReceived = static_cast<uint16_t>(nSize); } else { DEBUG_EXIT return; } } #endif monitorParams.Load(s_pUdpBuffer, m_nBytesReceived); #ifndef NDEBUG monitorParams.Dump(); #endif DEBUG_EXIT } #endif #if defined(DISPLAY_UDF) void RemoteConfig::HandleTxtFileDisplay() { DEBUG_ENTRY DisplayUdfParams displayParams(StoreDisplayUdf::Get()); #if !defined(DISABLE_BIN) if (m_tHandleMode == HandleMode::BIN) { if (m_nBytesReceived == sizeof(struct TDisplayUdfParams)) { uint32_t nSize; displayParams.Builder(reinterpret_cast<const struct TDisplayUdfParams*>(s_StoreBuffer), s_pUdpBuffer, udp::BUFFER_SIZE, nSize); m_nBytesReceived = static_cast<uint16_t>(nSize); } else { DEBUG_EXIT return; } } #endif displayParams.Load(s_pUdpBuffer, m_nBytesReceived); #ifndef NDEBUG displayParams.Dump(); #endif DEBUG_EXIT } #endif #if defined(OUTPUT_DMX_STEPPER) void RemoteConfig::HandleTxtFileSparkFun() { DEBUG_ENTRY SparkFunDmxParams sparkFunDmxParams(StoreSparkFunDmx::Get()); #if !defined(DISABLE_BIN) if (m_tHandleMode == HandleMode::BIN) { if (m_nBytesReceived == sizeof(struct TSparkFunDmxParams)) { uint32_t nSize; sparkFunDmxParams.Builder(reinterpret_cast<const struct TSparkFunDmxParams*>(s_StoreBuffer), s_pUdpBuffer, udp::BUFFER_SIZE, nSize); m_nBytesReceived = static_cast<uint16_t>(nSize); } else { DEBUG_EXIT return; } } #endif sparkFunDmxParams.Load(s_pUdpBuffer, m_nBytesReceived); #ifndef NDEBUG sparkFunDmxParams.Dump(); #endif DEBUG_EXIT } void RemoteConfig::HandleTxtFileMotor(uint32_t nMotorIndex) { DEBUG_ENTRY DEBUG_PRINTF("nMotorIndex=%d", nMotorIndex); #if !defined(DISABLE_BIN) if (m_tHandleMode == HandleMode::BIN) { // TODO HandleTxtFileMotor HandleMode::BIN return; } #endif SparkFunDmxParams sparkFunDmxParams(StoreSparkFunDmx::Get()); sparkFunDmxParams.Load(nMotorIndex, s_pUdpBuffer, m_nBytesReceived); #ifndef NDEBUG sparkFunDmxParams.Dump(); #endif ModeParams modeParams(StoreMotors::Get()); modeParams.Load(nMotorIndex, s_pUdpBuffer, m_nBytesReceived); #ifndef NDEBUG modeParams.Dump(); #endif MotorParams motorParams(StoreMotors::Get()); motorParams.Load(nMotorIndex, s_pUdpBuffer, m_nBytesReceived); #ifndef NDEBUG motorParams.Dump(); #endif L6470Params l6470Params(StoreMotors::Get()); l6470Params.Load(nMotorIndex, s_pUdpBuffer, m_nBytesReceived); #ifndef NDEBUG l6470Params.Dump(); #endif DEBUG_EXIT } #endif #if defined (NODE_SHOWFILE) void RemoteConfig::HandleTxtFileShow() { DEBUG_ENTRY ShowFileParams showFileParams(StoreShowFile::Get()); #if !defined(DISABLE_BIN) if (m_tHandleMode == HandleMode::BIN) { if (m_nBytesReceived == sizeof(struct TShowFileParams)) { uint32_t nSize; showFileParams.Builder(reinterpret_cast<const struct TShowFileParams*>(s_StoreBuffer), s_pUdpBuffer, udp::BUFFER_SIZE, nSize); m_nBytesReceived = static_cast<uint16_t>(nSize); } else { DEBUG_EXIT return; } } #endif showFileParams.Load(s_pUdpBuffer, m_nBytesReceived); #ifndef NDEBUG showFileParams.Dump(); #endif DEBUG_EXIT } #endif #if defined (OUTPUT_DMX_SERIAL) void RemoteConfig::HandleTxtFileSerial() { DEBUG_ENTRY DmxSerialParams dmxSerialParams(StoreDmxSerial::Get()); #if !defined(DISABLE_BIN) if (m_tHandleMode == HandleMode::BIN) { if (m_nBytesReceived == sizeof(struct TDmxSerialParams)) { uint32_t nSize; dmxSerialParams.Builder(reinterpret_cast<const struct TDmxSerialParams*>(s_StoreBuffer), s_pUdpBuffer, udp::BUFFER_SIZE, nSize); m_nBytesReceived = static_cast<uint16_t>(nSize); } else { DEBUG_EXIT return; } } #endif dmxSerialParams.Load(s_pUdpBuffer, m_nBytesReceived); #ifndef NDEBUG dmxSerialParams.Dump(); #endif DEBUG_EXIT } #endif #if defined (OUTPUT_RGB_PANEL) void RemoteConfig::HandleTxtFileRgbPanel() { DEBUG_ENTRY RgbPanelParams rgbPanelParams(StoreRgbPanel::Get()); #if !defined(DISABLE_BIN) if (m_tHandleMode == HandleMode::BIN) { if (m_nBytesReceived == sizeof(struct TRgbPanelParams)) { uint32_t nSize; rgbPanelParams.Builder(reinterpret_cast<const struct TRgbPanelParams*>(s_StoreBuffer), s_pUdpBuffer, udp::BUFFER_SIZE, nSize); m_nBytesReceived = static_cast<uint16_t>(nSize); } else { DEBUG_EXIT return; } } #endif rgbPanelParams.Load(s_pUdpBuffer, m_nBytesReceived); #ifndef NDEBUG rgbPanelParams.Dump(); #endif DEBUG_EXIT } #endif #if defined (NODE_DDP_DISPLAY) void RemoteConfig::HandleTxtFileDdpDisplay() { DEBUG_ENTRY DdpDisplayParams ddpDisplayParams(StoreDdpDisplay::Get()); #if !defined(DISABLE_BIN) if (m_tHandleMode == HandleMode::BIN) { if (m_nBytesReceived == sizeof(struct TDdpDisplayParams)) { uint32_t nSize; ddpDisplayParams.Builder(reinterpret_cast<const struct TDdpDisplayParams*>(s_StoreBuffer), s_pUdpBuffer, udp::BUFFER_SIZE, nSize); m_nBytesReceived = static_cast<uint16_t>(nSize); } else { DEBUG_EXIT return; } } #endif ddpDisplayParams.Load(s_pUdpBuffer, m_nBytesReceived); #ifndef NDEBUG ddpDisplayParams.Dump(); #endif DEBUG_EXIT } #endif #if !defined(DISABLE_TFTP) void RemoteConfig::TftpExit() { DEBUG_ENTRY s_pUdpBuffer[udp::cmd::set::length::TFTP] = '0'; HandleTftpSet(); DEBUG_EXIT } void RemoteConfig::HandleTftpSet() { DEBUG_ENTRY DEBUG_PRINTF("%c", s_pUdpBuffer[udp::cmd::set::length::TFTP]); m_bEnableTFTP = (s_pUdpBuffer[udp::cmd::set::length::TFTP] != '0'); if (m_bEnableTFTP) { Display::Get()->SetSleep(false); } if (m_bEnableTFTP && (m_pTFTPFileServer == nullptr)) { puts("Create TFTP Server"); m_pTFTPBuffer = new uint8_t[FIRMWARE_MAX_SIZE]; assert(m_pTFTPBuffer != nullptr); m_pTFTPFileServer = new TFTPFileServer(m_pTFTPBuffer, FIRMWARE_MAX_SIZE); assert(m_pTFTPFileServer != nullptr); Display::Get()->TextStatus("TFTP On", Display7SegmentMessage::INFO_TFTP_ON); } else if (!m_bEnableTFTP && (m_pTFTPFileServer != nullptr)) { const uint32_t nFileSize = m_pTFTPFileServer->GetFileSize(); DEBUG_PRINTF("nFileSize=%d, %d", nFileSize, m_pTFTPFileServer->isDone()); bool bSucces = true; if (m_pTFTPFileServer->isDone()) { bSucces = SpiFlashInstall::Get()->WriteFirmware(m_pTFTPBuffer, nFileSize); if (!bSucces) { Display::Get()->TextStatus("Error: TFTP", Display7SegmentMessage::ERROR_TFTP); } } puts("Delete TFTP Server"); delete m_pTFTPFileServer; m_pTFTPFileServer = nullptr; delete[] m_pTFTPBuffer; m_pTFTPBuffer = nullptr; if (bSucces) { // Keep error message Display::Get()->TextStatus("TFTP Off", Display7SegmentMessage::INFO_TFTP_OFF); } } DEBUG_EXIT } void RemoteConfig::HandleTftpGet() { DEBUG_ENTRY if (m_nBytesReceived == udp::cmd::get::length::TFTP) { const auto nLength = snprintf(s_pUdpBuffer, udp::BUFFER_SIZE - 1, "tftp:%s\n", m_bEnableTFTP ? "On" : "Off"); Network::Get()->SendTo(m_nHandle, s_pUdpBuffer, static_cast<uint16_t>(nLength), m_nIPAddressFrom, udp::PORT); } #if !defined(DISABLE_BIN) else if (m_nBytesReceived == udp::cmd::get::length::TFTP + 3) { if (memcmp(&s_pUdpBuffer[udp::cmd::get::length::TFTP], "bin", 3) == 0) { Network::Get()->SendTo(m_nHandle, &m_bEnableTFTP, sizeof(bool) , m_nIPAddressFrom, udp::PORT); } } #endif DEBUG_EXIT } #endif
19,568
660
/* * Copyright (c) 2019, Intel Corporation * * 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. */ // PatchInfo reader. // #include <cassert> #include <cstddef> #include <map> #include "PatchInfo.h" #include "PatchInfoRecord.h" #include "PatchInfoReader.h" namespace { class PatchInfoReader { const char *Data; std::size_t Size; unsigned ShEntries; const cm::patch::PInfoSectionHdr *Sh; // All symbol tables are merged into a single one. std::map<unsigned, cm::patch::Symbol *> SymbolTable; typedef std::map<unsigned, cm::patch::Binary *> BinarySectionMapTy; typedef std::map<unsigned, bool> SymbolTableSectionMapTy; BinarySectionMapTy BinarySectionMap; SymbolTableSectionMapTy SymbolTableSectionMap; public: PatchInfoReader(const char *B, std::size_t S) : Data(B), Size(S), ShEntries(0){Sh = nullptr;} bool read(cm::patch::Collection &C); protected: bool readHeader(cm::patch::Collection &C); bool readSections(cm::patch::Collection &C); bool readDummySection(cm::patch::Collection &C, unsigned n); bool readUnknownSection(cm::patch::Collection &C, unsigned n); bool readBinarySection(cm::patch::Collection &C, unsigned n); bool readRelocationSection(cm::patch::Collection &C, unsigned n); bool readSymbolTableSection(cm::patch::Collection &C, unsigned n); bool readStringTableSection(cm::patch::Collection &C, unsigned n); bool readInitRegAccessTableSection(cm::patch::Collection &C, unsigned n); bool readFiniRegAccessTableSection(cm::patch::Collection &C, unsigned n); bool readTokenTableSection(cm::patch::Collection &C, unsigned n); bool readRegisterAccessTableSection(cm::patch::Collection &C, unsigned n, cm::patch::PInfo_U16 ShType); bool isValidSection(unsigned n) { if (n >= ShEntries) return false; if (!Sh || Sh[n].ShOffset >= Size || Sh[n].ShOffset + Sh[n].ShSize > Size) return false; return true; } bool isValidSectionOfType(unsigned n, cm::patch::PInfo_U16 ShType) { if (!isValidSection(n)) return false; return Sh[n].ShType == ShType; } const char *getString(unsigned ShIdx, unsigned Idx) { const char *StringTable = Data + Sh[ShIdx].ShOffset; return StringTable + Idx; } std::pair<BinarySectionMapTy::iterator, bool> getOrReadBinarySection(cm::patch::Collection &C, unsigned n); std::pair<SymbolTableSectionMapTy::iterator, bool> getOrReadSymbolTableSection(cm::patch::Collection &C, unsigned n); }; } // End anonymous namespace bool readPatchInfo(const char *Buf, std::size_t Sz, cm::patch::Collection &C) { PatchInfoReader R(Buf, Sz); return R.read(C); } bool PatchInfoReader::read(cm::patch::Collection &C) { return readHeader(C) || readSections(C); } bool PatchInfoReader::readHeader(cm::patch::Collection &C) { if (Size < sizeof(cm::patch::PInfoHdr)) return true; const cm::patch::PInfoHdr *H = reinterpret_cast<const cm::patch::PInfoHdr *>(Data); if (!H->checkMagic()) return true; if (H->Version != cm::patch::PV_0) return true; if (!H->isValidPlatform()) return true; if (H->ShOffset >= Size) return true; if (H->ShOffset + H->ShNum * sizeof(cm::patch::PInfoSectionHdr) > Size) return true; if (C.getPlatform() != cm::patch::PP_NONE && C.getPlatform() != H->Platform) return true; C.setPlatform(H->Platform); Sh = reinterpret_cast<const cm::patch::PInfoSectionHdr *>(Data + H->ShOffset); ShEntries = H->ShNum; return false; } std::pair<PatchInfoReader::BinarySectionMapTy::iterator, bool> PatchInfoReader::getOrReadBinarySection(cm::patch::Collection &C, unsigned n) { auto BI = BinarySectionMap.end(); if (!readBinarySection(C, n)) { BI = BinarySectionMap.find(n); assert(BI != BinarySectionMap.end()); } return std::make_pair(BI, BI == BinarySectionMap.end()); } std::pair<PatchInfoReader::SymbolTableSectionMapTy::iterator, bool> PatchInfoReader::getOrReadSymbolTableSection(cm::patch::Collection &C, unsigned n) { auto SI = SymbolTableSectionMap.end(); if (!readSymbolTableSection(C, n)) { SI = SymbolTableSectionMap.find(n); assert(SI != SymbolTableSectionMap.end()); } return std::make_pair(SI, SI == SymbolTableSectionMap.end()); } bool PatchInfoReader::readSections(cm::patch::Collection &C) { if (!Sh) return true; for (unsigned n = 0; n != ShEntries; ++n) { switch (Sh[n].ShType) { case cm::patch::PSHT_NONE: if (readDummySection(C, n)) return true; break; case cm::patch::PSHT_BINARY: if (readBinarySection(C, n)) return true; break; case cm::patch::PSHT_REL: if (readRelocationSection(C, n)) return true; break; case cm::patch::PSHT_SYMTAB: if (readSymbolTableSection(C, n)) return true; break; case cm::patch::PSHT_STRTAB: if (readStringTableSection(C, n)) return true; break; case cm::patch::PSHT_INITREGTAB: if (readInitRegAccessTableSection(C, n)) return true; break; case cm::patch::PSHT_FINIREGTAB: if (readFiniRegAccessTableSection(C, n)) return true; break; case cm::patch::PSHT_TOKTAB: if (readTokenTableSection(C, n)) return true; break; default: if (readUnknownSection(C, n)) return true; break; } } return false; } bool PatchInfoReader::readDummySection(cm::patch::Collection &C, unsigned n) { if (!isValidSectionOfType(n, cm::patch::PSHT_NONE)) return true; return false; } bool PatchInfoReader::readBinarySection(cm::patch::Collection &C, unsigned n) { // Skip if this binary section is ready read. if (BinarySectionMap.count(n)) return false; // Bail out if it's not an valid binary section. if (!isValidSectionOfType(n, cm::patch::PSHT_BINARY)) return true; const char *Buf = nullptr; std::size_t Sz = Sh[n].ShSize; if (Sz) Buf = Data + Sh[n].ShOffset; cm::patch::Binary *Bin = C.addBinary(Buf, Sz); BinarySectionMap.insert(std::make_pair(n, Bin)); return false; } bool PatchInfoReader::readRelocationSection(cm::patch::Collection &C, unsigned n) { // Skip if this relocation section is already read. if (!isValidSectionOfType(n, cm::patch::PSHT_REL)) return true; bool Ret; BinarySectionMapTy::iterator BI; std::tie(BI, Ret) = getOrReadBinarySection(C, Sh[n].ShLink2); if (Ret) return true; cm::patch::Binary *Bin = BI->second; SymbolTableSectionMapTy::iterator SI; std::tie(SI, Ret) = getOrReadSymbolTableSection(C, Sh[n].ShLink); if (Ret) return true; // Scan through relocations. std::size_t Sz = Sh[n].ShSize; const cm::patch::PInfoRelocation *Rel = reinterpret_cast<const cm::patch::PInfoRelocation *>(Data + Sh[n].ShOffset); for (unsigned i = 0; Sz > 0; ++i, Sz -= sizeof(cm::patch::PInfoRelocation)) { auto I = SymbolTable.find(Rel[i].RelSym); if (I == SymbolTable.end()) return true; cm::patch::Symbol *S = I->second; Bin->addReloc(Rel[i].RelAddr, S); } return false; } bool PatchInfoReader::readSymbolTableSection(cm::patch::Collection &C, unsigned n) { // Skip if this section is ready read. if (SymbolTableSectionMap.count(n)) return false; // Bail out if it's an invalid section. if (!isValidSectionOfType(n, cm::patch::PSHT_SYMTAB)) return true; // Read string table. unsigned ShIdx = Sh[n].ShLink; if (readStringTableSection(C, ShIdx)) return true; // Scan through the symbol table. const cm::patch::PInfoSymbol *Sym = reinterpret_cast<const cm::patch::PInfoSymbol *>(Data + Sh[n].ShOffset); std::size_t Sz = Sh[n].ShSize; for (unsigned i = 0; Sz > 0; ++i, Sz -= sizeof(cm::patch::PInfoSymbol)) { // Skip unamed symbol. unsigned StrIdx = Sym[i].SymName; if (!StrIdx) continue; const char *Name = getString(ShIdx, StrIdx); cm::patch::Binary *Bin = nullptr; unsigned Ndx = Sym[i].SymShndx; if (Ndx) { // Only support binary section so far. bool Ret; BinarySectionMapTy::iterator BI; std::tie(BI, Ret) = getOrReadBinarySection(C, Ndx); if (Ret) return true; Bin = BI->second; } cm::patch::Symbol *S = C.getSymbol(Name); if (Bin) while (S && !S->isUnresolved()) { // In case a symbol has multiple definitions (due to combining a single // kernel multiple times), rename the conflicting one. Name = C.getUniqueName(Name); S = C.getSymbol(Name); } S = C.addSymbol(Name); if (Bin && S->isUnresolved()) { S->setBinary(Bin); S->setAddr(Sym[i].SymValue); S->setExtra(Sym[i].SymExtra); } // Assume there's just one symbol table section per patch info. SymbolTable.insert(std::make_pair(i, S)); } SymbolTableSectionMap.insert(std::make_pair(n, true)); return false; } bool PatchInfoReader::readStringTableSection(cm::patch::Collection &C, unsigned n) { if (!isValidSectionOfType(n, cm::patch::PSHT_STRTAB)) return true; return false; } bool PatchInfoReader::readRegisterAccessTableSection(cm::patch::Collection &C, unsigned n, cm::patch::PInfo_U16 ShType) { if (!isValidSectionOfType(n, ShType)) return true; BinarySectionMapTy::iterator BI; bool Ret; std::tie(BI, Ret) = getOrReadBinarySection(C, Sh[n].ShLink2); if (Ret) return true; cm::patch::Binary *Bin = BI->second; // Scan through register accesses. std::size_t Sz = Sh[n].ShSize; const cm::patch::PInfoRegAccess *Acc = reinterpret_cast<const cm::patch::PInfoRegAccess *>(Data + Sh[n].ShOffset); switch (ShType) { default: return true; case cm::patch::PSHT_INITREGTAB: for (unsigned i = 0; Sz > 0; ++i, Sz -= sizeof(cm::patch::PInfoRegAccess)) Bin->addInitRegAccess(Acc[i].RegAccAddr, Acc[i].RegAccRegNo, Acc[i].RegAccDUT); break; case cm::patch::PSHT_FINIREGTAB: for (unsigned i = 0; Sz > 0; ++i, Sz -= sizeof(cm::patch::PInfoRegAccess)) Bin->addFiniRegAccess(Acc[i].RegAccAddr, Acc[i].RegAccRegNo, Acc[i].RegAccDUT); break; } return false; } bool PatchInfoReader::readInitRegAccessTableSection(cm::patch::Collection &C, unsigned n) { return readRegisterAccessTableSection(C, n, cm::patch::PSHT_INITREGTAB); } bool PatchInfoReader::readFiniRegAccessTableSection(cm::patch::Collection &C, unsigned n) { return readRegisterAccessTableSection(C, n, cm::patch::PSHT_FINIREGTAB); } bool PatchInfoReader::readTokenTableSection(cm::patch::Collection &C, unsigned n) { if (!isValidSectionOfType(n, cm::patch::PSHT_TOKTAB)) return true; BinarySectionMapTy::iterator BI; bool Ret; std::tie(BI, Ret) = getOrReadBinarySection(C, Sh[n].ShLink2); if (Ret) return true; cm::patch::Binary *Bin = BI->second; // Scan through tokens. std::size_t Sz = Sh[n].ShSize; const cm::patch::PInfoToken *Tok = reinterpret_cast<const cm::patch::PInfoToken *>(Data + Sh[n].ShOffset); for (unsigned i = 0; Sz > 0; ++i, Sz -= sizeof(cm::patch::PInfoToken)) Bin->addToken(Tok[i].TokenNo); return false; } bool PatchInfoReader::readUnknownSection(cm::patch::Collection &C, unsigned n) { if (!isValidSection(n)) return true; return false; }
4,952
831
/* * Copyright 2000-2012 JetBrains s.r.o. * * 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. */ package org.jetbrains.android.refactoring; import com.android.resources.ResourceFolderType; import com.android.resources.ResourceType; import com.android.tools.idea.res.IdeResourcesUtil; import com.intellij.application.options.ModulesComboBox; import com.intellij.ide.util.PropertiesComponent; import com.intellij.openapi.actionSystem.ActionToolbarPosition; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.module.Module; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.ValidationInfo; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.xml.XmlAttribute; import com.intellij.ui.AnActionButton; import com.intellij.ui.CheckboxTree; import com.intellij.ui.CheckedTreeNode; import com.intellij.ui.SimpleTextAttributes; import com.intellij.ui.ToolbarDecorator; import com.intellij.ui.TreeSpeedSearch; import com.intellij.ui.components.JBCheckBox; import com.intellij.ui.components.JBLabel; import com.intellij.util.PlatformIcons; import com.intellij.util.containers.Convertor; import com.intellij.util.ui.tree.TreeUtil; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.swing.*; import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; import org.jetbrains.android.actions.CreateXmlResourceDialog; import org.jetbrains.android.facet.AndroidFacet; import org.jetbrains.android.facet.ResourceFolderManager; import org.jetbrains.android.util.AndroidBundle; import org.jetbrains.android.util.AndroidUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; class ExtractStyleDialog extends DialogWrapper { private JPanel myPanel; private JTextField myStyleNameField; private JPanel myAttributeListWrapper; private JBLabel myAttributesLabel; private JBLabel myModuleLabel; private ModulesComboBox myModuleCombo; private JBCheckBox mySearchForStyleApplicationsAfter; private final Module myModule; private final String myFileName; private final List<String> myDirNames; private final CheckboxTree myTree; private final CheckedTreeNode myRootNode; private static final String SEARCH_STYLE_APPLICATIONS_PROPERTY = "AndroidExtractStyleSearchStyleApplications"; public ExtractStyleDialog(@NotNull Module module, @NotNull String fileName, @Nullable String parentStyleName, @NotNull List<String> dirNames, @NotNull List<XmlAttribute> attributes) { super(module.getProject()); myFileName = fileName; myDirNames = dirNames; if (parentStyleName != null && !parentStyleName.isEmpty()) { myStyleNameField.setText(parentStyleName + "."); myStyleNameField.selectAll(); } else { String prefix = IdeResourcesUtil.prependResourcePrefix(module, null, ResourceFolderType.VALUES); if (prefix != null) { myStyleNameField.setText(prefix); } } final Set<Module> modulesSet = new HashSet<Module>(); modulesSet.add(module); for (AndroidFacet depFacet : AndroidUtils.getAllAndroidDependencies(module, true)) { modulesSet.add(depFacet.getModule()); } assert !modulesSet.isEmpty(); if (modulesSet.size() == 1) { myModule = module; myModuleLabel.setVisible(false); myModuleCombo.setVisible(false); } else { myModule = null; myModuleCombo.setModules(modulesSet); myModuleCombo.setSelectedModule(module); } myRootNode = new CheckedTreeNode(null); for (XmlAttribute attribute : attributes) { myRootNode.add(new CheckedTreeNode(attribute)); } CheckboxTree.CheckboxTreeCellRenderer renderer = new CheckboxTree.CheckboxTreeCellRenderer() { @Override public void customizeRenderer(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { if (value instanceof CheckedTreeNode) { XmlAttribute attribute = (XmlAttribute)((CheckedTreeNode)value).getUserObject(); if (attribute != null) { getTextRenderer().append(attribute.getLocalName()); getTextRenderer().append(" [" + attribute.getValue() + "]", SimpleTextAttributes.GRAY_ATTRIBUTES); } } } }; myTree = new CheckboxTree(renderer, myRootNode) { @Override protected void installSpeedSearch() { new TreeSpeedSearch(this, new Convertor<TreePath, String>() { @Override public String convert(TreePath path) { Object object = path.getLastPathComponent(); if (object instanceof CheckedTreeNode) { XmlAttribute attribute = (XmlAttribute)((CheckedTreeNode)object).getUserObject(); if (attribute != null) { return attribute.getLocalName(); } } return ""; } }); } }; myTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); myTree.setRootVisible(false); myTree.setShowsRootHandles(false); TreeUtil.expandAll(myTree); myAttributesLabel.setLabelFor(myTree); ToolbarDecorator decorator = ToolbarDecorator.createDecorator(myTree); decorator.setToolbarPosition(ActionToolbarPosition.RIGHT); decorator.setEditAction(null); decorator.disableUpDownActions(); AnActionButton selectAll = new AnActionButton(AndroidBundle.messagePointer("action.AnActionButton.extract.style.text.select.all"), PlatformIcons.SELECT_ALL_ICON) { @Override public void actionPerformed(@NotNull AnActionEvent e) { setChecked(true); } }; decorator.addExtraAction(selectAll); AnActionButton unselectAll = new AnActionButton(AndroidBundle.messagePointer("action.AnActionButton.extract.style.text.unselect.all"), PlatformIcons.UNSELECT_ALL_ICON) { @Override public void actionPerformed(@NotNull AnActionEvent e) { setChecked(false); } }; decorator.addExtraAction(unselectAll); myAttributeListWrapper.add(decorator.createPanel()); final String value = PropertiesComponent.getInstance().getValue(SEARCH_STYLE_APPLICATIONS_PROPERTY); mySearchForStyleApplicationsAfter.setSelected(Boolean.parseBoolean(value)); init(); } private void setChecked(boolean value) { int count = myRootNode.getChildCount(); for (int i = 0; i < count; i++) { ((CheckedTreeNode)myRootNode.getChildAt(i)).setChecked(value); } myTree.repaint(); } @Override protected JComponent createCenterPanel() { return myPanel; } @Override protected void doOKAction() { super.doOKAction(); PropertiesComponent.getInstance().setValue( SEARCH_STYLE_APPLICATIONS_PROPERTY, Boolean.toString(mySearchForStyleApplicationsAfter.isSelected())); } @Override public JComponent getPreferredFocusedComponent() { return myStyleNameField; } @Override protected ValidationInfo doValidate() { final String styleName = getStyleName(); if (styleName.isEmpty()) { return new ValidationInfo("specify style name", myStyleNameField); } if (!IdeResourcesUtil.isCorrectAndroidResourceName(styleName)) { return new ValidationInfo("incorrect style name", myStyleNameField); } final Module module = getChosenModule(); if (module == null) { return new ValidationInfo("specify module", myModuleCombo); } VirtualFile resourceDir = getResourceDirectory(); if (resourceDir == null) { return new ValidationInfo("specify a module with resources", myModuleCombo); } return CreateXmlResourceDialog.checkIfResourceAlreadyExists(module.getProject(), resourceDir, getStyleName(), null, ResourceType.STYLE, myDirNames, myFileName); } @NotNull public String getStyleName() { return myStyleNameField.getText().trim(); } @NotNull public List<XmlAttribute> getStyledAttributes() { List<XmlAttribute> attributes = new ArrayList<XmlAttribute>(); int count = myRootNode.getChildCount(); for (int i = 0; i < count; i++) { final CheckedTreeNode treeNode = (CheckedTreeNode)myRootNode.getChildAt(i); if (treeNode.isChecked()) { attributes.add((XmlAttribute)treeNode.getUserObject()); } } return attributes; } @Nullable private Module getChosenModule() { return myModule != null ? myModule : myModuleCombo.getSelectedModule(); } @Nullable public VirtualFile getResourceDirectory() { Module module = getChosenModule(); if (module == null) { return null; } AndroidFacet facet = AndroidFacet.getInstance(module); if (facet == null) { return null; } return ResourceFolderManager.getInstance(facet).getPrimaryFolder(); } public boolean isToSearchStyleApplications() { return mySearchForStyleApplicationsAfter.isSelected(); } }
3,481
339
from __future__ import division, print_function, unicode_literals import argparse import json import random import time from io import open import os import numpy as np import torch from torch.optim import Adam from convlab2.policy.mdrg.multiwoz.utils import util from convlab2.policy.mdrg.multiwoz.model import Model parser = argparse.ArgumentParser(description='S2S') parser.add_argument('--batch_size', type=int, default=64, metavar='N', help='input batch size for training (default: 128)') parser.add_argument('--vocab_size', type=int, default=400, metavar='V') parser.add_argument('--use_attn', type=util.str2bool, nargs='?', const=True, default=False) parser.add_argument('--attention_type', type=str, default='bahdanau') parser.add_argument('--use_emb', type=util.str2bool, nargs='?', const=True, default=False) parser.add_argument('--emb_size', type=int, default=50) parser.add_argument('--hid_size_enc', type=int, default=150) parser.add_argument('--hid_size_dec', type=int, default=150) parser.add_argument('--hid_size_pol', type=int, default=150) parser.add_argument('--db_size', type=int, default=30) parser.add_argument('--bs_size', type=int, default=94) parser.add_argument('--cell_type', type=str, default='lstm') parser.add_argument('--depth', type=int, default=1, help='depth of rnn') parser.add_argument('--max_len', type=int, default=50) parser.add_argument('--optim', type=str, default='adam') parser.add_argument('--lr_rate', type=float, default=0.005) parser.add_argument('--lr_decay', type=float, default=0.0) parser.add_argument('--l2_norm', type=float, default=0.00001) parser.add_argument('--clip', type=float, default=5.0, help='clip the gradient by norm') parser.add_argument('--teacher_ratio', type=float, default=1.0, help='probability of using targets for learning') parser.add_argument('--dropout', type=float, default=0.0) parser.add_argument('--no_cuda', type=util.str2bool, nargs='?', const=True, default=True) parser.add_argument('--seed', type=int, default=0, metavar='S', help='random seed (default: 1)') parser.add_argument('--train_output', type=str, default='data/train_dials/', help='Training output dir path') parser.add_argument('--max_epochs', type=int, default=15) parser.add_argument('--early_stop_count', type=int, default=2) parser.add_argument('--model_dir', type=str, default='model/model/') parser.add_argument('--model_name', type=str, default='translate.ckpt') parser.add_argument('--load_param', type=util.str2bool, nargs='?', const=True, default=False) parser.add_argument('--epoch_load', type=int, default=0) parser.add_argument('--mode', type=str, default='train', help='training or testing: test, train, RL') args = parser.parse_args() args.cuda = not args.no_cuda and torch.cuda.is_available() torch.manual_seed(args.seed) device = torch.device("cuda" if args.cuda else "cpu") def train(print_loss_total,print_act_total, print_grad_total, input_tensor, target_tensor, bs_tensor, db_tensor, name=None): # create an empty matrix with padding tokens input_tensor, input_lengths = util.padSequence(input_tensor) target_tensor, target_lengths = util.padSequence(target_tensor) bs_tensor = torch.tensor(bs_tensor, dtype=torch.float, device=device) db_tensor = torch.tensor(db_tensor, dtype=torch.float, device=device) loss, loss_acts, grad = model.train(input_tensor, input_lengths, target_tensor, target_lengths, db_tensor, bs_tensor, name) #print(loss, loss_acts) print_loss_total += loss print_act_total += loss_acts print_grad_total += grad model.global_step += 1 model.sup_loss = torch.zeros(1) return print_loss_total, print_act_total, print_grad_total def trainIters(model, n_epochs=10, args=args): prev_min_loss, early_stop_count = 1 << 30, args.early_stop_count start = time.time() for epoch in range(1, n_epochs + 1): print_loss_total = 0; print_grad_total = 0; print_act_total = 0 # Reset every print_every start_time = time.time() # watch out where do you put it model.optimizer = Adam(lr=args.lr_rate, params=filter(lambda x: x.requires_grad, model.parameters()), weight_decay=args.l2_norm) model.optimizer_policy = Adam(lr=args.lr_rate, params=filter(lambda x: x.requires_grad, model.policy.parameters()), weight_decay=args.l2_norm) dials = list(train_dials.keys()) random.shuffle(dials) input_tensor = [];target_tensor = [];bs_tensor = [];db_tensor = [] for name in dials: val_file = train_dials[name] model.optimizer.zero_grad() model.optimizer_policy.zero_grad() input_tensor, target_tensor, bs_tensor, db_tensor = util.loadDialogue(model, val_file, input_tensor, target_tensor, bs_tensor, db_tensor) if len(db_tensor) > args.batch_size: print_loss_total, print_act_total, print_grad_total = train(print_loss_total, print_act_total, print_grad_total, input_tensor, target_tensor, bs_tensor, db_tensor) input_tensor = [];target_tensor = [];bs_tensor = [];db_tensor = []; print_loss_avg = print_loss_total / len(train_dials) print_act_total_avg = print_act_total / len(train_dials) print_grad_avg = print_grad_total / len(train_dials) print('TIME:', time.time() - start_time) print('Time since %s (Epoch:%d %d%%) Loss: %.4f, Loss act: %.4f, Grad: %.4f' % (util.timeSince(start, epoch / n_epochs), epoch, epoch / n_epochs * 100, print_loss_avg, print_act_total_avg, print_grad_avg)) # VALIDATION valid_loss = 0 for name, val_file in val_dials.items(): input_tensor = []; target_tensor = []; bs_tensor = [];db_tensor = [] input_tensor, target_tensor, bs_tensor, db_tensor = util.loadDialogue(model, val_file, input_tensor, target_tensor, bs_tensor, db_tensor) # create an empty matrix with padding tokens input_tensor, input_lengths = util.padSequence(input_tensor) target_tensor, target_lengths = util.padSequence(target_tensor) bs_tensor = torch.tensor(bs_tensor, dtype=torch.float, device=device) db_tensor = torch.tensor(db_tensor, dtype=torch.float, device=device) proba, _, _ = model.forward(input_tensor, input_lengths, target_tensor, target_lengths, db_tensor, bs_tensor) proba = proba.view(-1, model.vocab_size) # flatten all predictions loss = model.gen_criterion(proba, target_tensor.view(-1)) valid_loss += loss.item() valid_loss /= len(val_dials) print('Current Valid LOSS:', valid_loss) model.saveModel(epoch) def loadDictionaries(): # load data and dictionaries with open(os.path.join(os.path.dirname(__file__), 'data/input_lang.index2word.json'), 'r') as f: input_lang_index2word = json.load(f) with open(os.path.join(os.path.dirname(__file__), 'data/input_lang.word2index.json'), 'r') as f: input_lang_word2index = json.load(f) with open(os.path.join(os.path.dirname(__file__), 'data/output_lang.index2word.json'), 'r') as f: output_lang_index2word = json.load(f) with open(os.path.join(os.path.dirname(__file__), 'data/output_lang.word2index.json'), 'r') as f: output_lang_word2index = json.load(f) return input_lang_index2word, output_lang_index2word, input_lang_word2index, output_lang_word2index if __name__ == '__main__': input_lang_index2word, output_lang_index2word, input_lang_word2index, output_lang_word2index = loadDictionaries() # Load training file list: with open(os.path.join(os.path.dirname(__file__),'data/train_dials.json'), 'r') as outfile: train_dials = json.load(outfile) # Load validation file list: with open(os.path.join(os.path.dirname(__file__), 'data/val_dials.json'), 'r') as outfile: val_dials = json.load(outfile) model = Model(args, input_lang_index2word, output_lang_index2word, input_lang_word2index, output_lang_word2index) if args.load_param: model.loadModel(args.epoch_load) trainIters(model, n_epochs=args.max_epochs, args=args)
3,516
467
<gh_stars>100-1000 from django.conf import settings DEVSERVER_MODULES = getattr(settings, 'DEVSERVER_MODULES', ( 'devserver.modules.sql.SQLRealTimeModule', # 'devserver.modules.sql.SQLSummaryModule', # 'devserver.modules.profile.ProfileSummaryModule', # 'devserver.modules.request.SessionInfoModule', # 'devserver.modules.profile.MemoryUseModule', # 'devserver.modules.profile.LeftOversModule', # 'devserver.modules.cache.CacheSummaryModule', )) DEVSERVER_FILTER_SQL = getattr(settings, 'DEVSERVER_FILTER_SQL', False) DEVSERVER_TRUNCATE_SQL = getattr(settings, 'DEVSERVER_TRUNCATE_SQL', True) DEVSERVER_TRUNCATE_AGGREGATES = getattr(settings, 'DEVSERVER_TRUNCATE_AGGREGATES', getattr(settings, 'DEVSERVER_TRUNCATE_AGGREGATES', False)) # This variable gets set to True when we're running the devserver DEVSERVER_ACTIVE = False DEVSERVER_AJAX_CONTENT_LENGTH = getattr(settings, 'DEVSERVER_AJAX_CONTENT_LENGTH', 300) DEVSERVER_AJAX_PRETTY_PRINT = getattr(settings, 'DEVSERVER_AJAX_PRETTY_PRINT', False) # Minimum time a query must execute to be shown, value is in MS DEVSERVER_SQL_MIN_DURATION = getattr(settings, 'DEVSERVER_SQL_MIN_DURATION', None) DEVSERVER_AUTO_PROFILE = getattr(settings, 'DEVSERVER_AUTO_PROFILE', False)
484
2,151
<filename>components/variations/variations_params_manager.h // Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_VARIATIONS_VARIATIONS_PARAMS_MANAGER_H_ #define COMPONENTS_VARIATIONS_VARIATIONS_PARAMS_MANAGER_H_ #include <map> #include <memory> #include <set> #include <string> #include "base/macros.h" #include "base/metrics/field_trial.h" namespace base { class CommandLine; class FieldTrialList; namespace test { class ScopedFeatureList; } // namespace test } // namespace base namespace variations { namespace testing { // Use this class as a member in your test class to set variation params for // your tests. You can directly set the parameters in the constructor (if they // are used by other members upon construction). You can change them later // arbitrarily many times using the SetVariationParams function. Internally, it // creates a FieldTrialList as a member. It works well for multiple tests of a // given test class, as it clears the parameters when this class is destructed. // Note that it clears all parameters (not just those registered here). class VariationParamsManager { public: // Does not associate any parameters. VariationParamsManager(); // Calls directly SetVariationParams with the provided arguments. VariationParamsManager( const std::string& trial_name, const std::map<std::string, std::string>& param_values); // Calls directly SetVariationParamsWithFeatures with the provided arguments. VariationParamsManager( const std::string& trial_name, const std::map<std::string, std::string>& param_values, const std::set<std::string>& associated_features); ~VariationParamsManager(); // Associates |param_values| with the given |trial_name|. |param_values| maps // parameter names to their values. The function creates a new trial group, // used only for testing. Between two calls of this function, // ClearAllVariationParams() has to be called. void SetVariationParams( const std::string& trial_name, const std::map<std::string, std::string>& param_values); // Like SetVariationParams(). |associated_features| lists names of features // to be associated to the newly created trial group. As a result, all // parameters from |param_values| can be accessed via any of the feature from // |associated_features|. void SetVariationParamsWithFeatureAssociations( const std::string& trial_name, const std::map<std::string, std::string>& param_values, const std::set<std::string>& associated_features); // Clears all of the mapped associations. void ClearAllVariationIDs(); // Clears all of the associated params. void ClearAllVariationParams(); // Appends command line switches to |command_line| in a way that mimics // SetVariationParams. // // This static method is useful in situations where using // VariationParamsManager directly would have resulted in initializing // FieldTrialList twice (once from ChromeBrowserMainParts::SetupFieldTrials // and once from VariationParamsManager). static void AppendVariationParams( const std::string& trial_name, const std::string& trial_group_name, const std::map<std::string, std::string>& param_values, base::CommandLine* command_line); private: std::unique_ptr<base::FieldTrialList> field_trial_list_; std::unique_ptr<base::test::ScopedFeatureList> scoped_feature_list_; DISALLOW_COPY_AND_ASSIGN(VariationParamsManager); }; } // namespace testing } // namespace variations #endif // COMPONENTS_VARIATIONS_VARIATIONS_PARAMS_MANAGER_H_
1,105