repo_name
stringlengths
4
116
path
stringlengths
3
942
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
ICT4H/dcs-enketo-core
test/karma.conf.js
3479
// Karma configuration // Generated on Mon Mar 16 2015 13:42:33 GMT-0600 (MDT) module.exports = function( config ) { config.set( { // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '..', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: [ 'jasmine', 'requirejs' ], // list of files / patterns to load in the browser files: [ 'require-config.js', 'test/test-main.js', 'test/mock/*.js', { pattern: 'test/spec/*.spec.js', included: false }, { pattern: 'src/js/*.js', included: false }, { pattern: 'src/widget/*/*.*', included: false }, { pattern: 'config.json', included: false }, { pattern: 'src/widget/date/bootstrap3-datepicker/js/bootstrap-datepicker.js', included: false }, { pattern: 'src/widget/time/bootstrap3-timepicker/js/bootstrap-timepicker.js', included: false }, { pattern: 'lib/jquery-touchswipe/jquery.touchSwipe.js', included: false }, { pattern: 'lib/jquery-xpath/jquery.xpath.js', included: false }, { pattern: 'lib/text/text.js', included: false }, { pattern: 'lib/leaflet/leaflet.js', included: false }, { pattern: 'lib/bootstrap-slider/js/bootstrap-slider.js', included: false }, { pattern: 'lib/Modernizr.js', included: false }, { pattern: 'lib/xpath/build/enketo-xpathjs.js', included: false }, { pattern: 'lib/bower-components/jquery/dist/jquery.js', included: false }, { pattern: 'lib/bower-components/q/q.js', included: false }, ], // list of files to exclude exclude: [], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: {}, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: [ 'progress' ], // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: false, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: [ 'Chrome', 'ChromeCanary', 'Firefox', 'Safari', 'PhantomJS', 'Opera' ], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: false } ); };
apache-2.0
openstack/python-neutronclient
neutronclient/v2_0/client.py
115185
# Copyright 2012 OpenStack Foundation. # Copyright 2015 Hewlett-Packard Development Company, L.P. # Copyright 2017 FUJITSU LIMITED # All Rights Reserved # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # import inspect import itertools import logging import re import time import urllib.parse as urlparse import debtcollector.renames from keystoneauth1 import exceptions as ksa_exc import requests from neutronclient._i18n import _ from neutronclient import client from neutronclient.common import exceptions from neutronclient.common import extension as client_extension from neutronclient.common import serializer from neutronclient.common import utils _logger = logging.getLogger(__name__) HEX_ELEM = '[0-9A-Fa-f]' UUID_PATTERN = '-'.join([HEX_ELEM + '{8}', HEX_ELEM + '{4}', HEX_ELEM + '{4}', HEX_ELEM + '{4}', HEX_ELEM + '{12}']) def exception_handler_v20(status_code, error_content): """Exception handler for API v2.0 client. This routine generates the appropriate Neutron exception according to the contents of the response body. :param status_code: HTTP error status code :param error_content: deserialized body of error response """ error_dict = None request_ids = error_content.request_ids if isinstance(error_content, dict): error_dict = error_content.get('NeutronError') # Find real error type client_exc = None if error_dict: # If Neutron key is found, it will definitely contain # a 'message' and 'type' keys? try: error_type = error_dict['type'] error_message = error_dict['message'] if error_dict['detail']: error_message += "\n" + error_dict['detail'] # If corresponding exception is defined, use it. client_exc = getattr(exceptions, '%sClient' % error_type, None) except Exception: error_message = "%s" % error_dict else: error_message = None if isinstance(error_content, dict): error_message = error_content.get('message') if not error_message: # If we end up here the exception was not a neutron error error_message = "%s-%s" % (status_code, error_content) # If an exception corresponding to the error type is not found, # look up per status-code client exception. if not client_exc: client_exc = exceptions.HTTP_EXCEPTION_MAP.get(status_code) # If there is no exception per status-code, # Use NeutronClientException as fallback. if not client_exc: client_exc = exceptions.NeutronClientException raise client_exc(message=error_message, status_code=status_code, request_ids=request_ids) class _RequestIdMixin(object): """Wrapper class to expose x-openstack-request-id to the caller.""" def _request_ids_setup(self): self._request_ids = [] @property def request_ids(self): return self._request_ids def _append_request_ids(self, resp): """Add request_ids as an attribute to the object :param resp: Response object or list of Response objects """ if isinstance(resp, list): # Add list of request_ids if response is of type list. for resp_obj in resp: self._append_request_id(resp_obj) elif resp is not None: # Add request_ids if response contains single object. self._append_request_id(resp) def _append_request_id(self, resp): if isinstance(resp, requests.Response): # Extract 'x-openstack-request-id' from headers if # response is a Response object. request_id = resp.headers.get('x-openstack-request-id') else: # If resp is of type string. request_id = resp if request_id: self._request_ids.append(request_id) class _DictWithMeta(dict, _RequestIdMixin): def __init__(self, values, resp): super(_DictWithMeta, self).__init__(values) self._request_ids_setup() self._append_request_ids(resp) class _TupleWithMeta(tuple, _RequestIdMixin): def __new__(cls, values, resp): return super(_TupleWithMeta, cls).__new__(cls, values) def __init__(self, values, resp): self._request_ids_setup() self._append_request_ids(resp) class _StrWithMeta(str, _RequestIdMixin): def __new__(cls, value, resp): return super(_StrWithMeta, cls).__new__(cls, value) def __init__(self, values, resp): self._request_ids_setup() self._append_request_ids(resp) class _GeneratorWithMeta(_RequestIdMixin): def __init__(self, paginate_func, collection, path, **params): self.paginate_func = paginate_func self.collection = collection self.path = path self.params = params self.generator = None self._request_ids_setup() def _paginate(self): for r in self.paginate_func( self.collection, self.path, **self.params): yield r, r.request_ids def __iter__(self): return self # Python 3 compatibility def __next__(self): return self.next() def next(self): if not self.generator: self.generator = self._paginate() try: obj, req_id = next(self.generator) self._append_request_ids(req_id) except StopIteration: raise StopIteration() return obj class ClientBase(object): """Client for the OpenStack Neutron v2.0 API. :param string username: Username for authentication. (optional) :param string user_id: User ID for authentication. (optional) :param string password: Password for authentication. (optional) :param string token: Token for authentication. (optional) :param string tenant_name: DEPRECATED! Use project_name instead. :param string project_name: Project name. (optional) :param string tenant_id: DEPRECATED! Use project_id instead. :param string project_id: Project id. (optional) :param string auth_strategy: 'keystone' by default, 'noauth' for no authentication against keystone. (optional) :param string auth_url: Keystone service endpoint for authorization. :param string service_type: Network service type to pull from the keystone catalog (e.g. 'network') (optional) :param string endpoint_type: Network service endpoint type to pull from the keystone catalog (e.g. 'publicURL', 'internalURL', or 'adminURL') (optional) :param string region_name: Name of a region to select when choosing an endpoint from the service catalog. :param string endpoint_url: A user-supplied endpoint URL for the neutron service. Lazy-authentication is possible for API service calls if endpoint is set at instantiation.(optional) :param integer timeout: Allows customization of the timeout for client http requests. (optional) :param bool insecure: SSL certificate validation. (optional) :param bool log_credentials: Allow for logging of passwords or not. Defaults to False. (optional) :param string ca_cert: SSL CA bundle file to use. (optional) :param cert: A client certificate to pass to requests. These are of the same form as requests expects. Either a single filename containing both the certificate and key or a tuple containing the path to the certificate then a path to the key. (optional) :param integer retries: How many times idempotent (GET, PUT, DELETE) requests to Neutron server should be retried if they fail (default: 0). :param bool raise_errors: If True then exceptions caused by connection failure are propagated to the caller. (default: True) :param session: Keystone client auth session to use. (optional) :param auth: Keystone auth plugin to use. (optional) Example:: from neutronclient.v2_0 import client neutron = client.Client(username=USER, password=PASS, project_name=PROJECT_NAME, auth_url=KEYSTONE_URL) nets = neutron.list_networks() ... """ # API has no way to report plurals, so we have to hard code them # This variable should be overridden by a child class. EXTED_PLURALS = {} @debtcollector.renames.renamed_kwarg( 'tenant_id', 'project_id', replace=True) def __init__(self, **kwargs): """Initialize a new client for the Neutron v2.0 API.""" super(ClientBase, self).__init__() self.retries = kwargs.pop('retries', 0) self.raise_errors = kwargs.pop('raise_errors', True) self.httpclient = client.construct_http_client(**kwargs) self.version = '2.0' self.action_prefix = "/v%s" % (self.version) self.retry_interval = 1 def _handle_fault_response(self, status_code, response_body, resp): # Create exception with HTTP status code and message _logger.debug("Error message: %s", response_body) # Add deserialized error message to exception arguments try: des_error_body = self.deserialize(response_body, status_code) except Exception: # If unable to deserialized body it is probably not a # Neutron error des_error_body = {'message': response_body} error_body = self._convert_into_with_meta(des_error_body, resp) # Raise the appropriate exception exception_handler_v20(status_code, error_body) def do_request(self, method, action, body=None, headers=None, params=None): # Add format and project_id action = self.action_prefix + action if isinstance(params, dict) and params: params = utils.safe_encode_dict(params) action += '?' + urlparse.urlencode(params, doseq=1) if body: body = self.serialize(body) resp, replybody = self.httpclient.do_request(action, method, body=body, headers=headers) status_code = resp.status_code if status_code in (requests.codes.ok, requests.codes.created, requests.codes.accepted, requests.codes.no_content): data = self.deserialize(replybody, status_code) return self._convert_into_with_meta(data, resp) else: if not replybody: replybody = resp.reason self._handle_fault_response(status_code, replybody, resp) def get_auth_info(self): return self.httpclient.get_auth_info() def serialize(self, data): """Serializes a dictionary into JSON. A dictionary with a single key can be passed and it can contain any structure. """ if data is None: return None elif isinstance(data, dict): return serializer.Serializer().serialize(data) else: raise Exception(_("Unable to serialize object of type = '%s'") % type(data)) def deserialize(self, data, status_code): """Deserializes a JSON string into a dictionary.""" if not data: return data return serializer.Serializer().deserialize( data)['body'] def retry_request(self, method, action, body=None, headers=None, params=None): """Call do_request with the default retry configuration. Only idempotent requests should retry failed connection attempts. :raises: ConnectionFailed if the maximum # of retries is exceeded """ max_attempts = self.retries + 1 for i in range(max_attempts): try: return self.do_request(method, action, body=body, headers=headers, params=params) except (exceptions.ConnectionFailed, ksa_exc.ConnectionError): # Exception has already been logged by do_request() if i < self.retries: _logger.debug('Retrying connection to Neutron service') time.sleep(self.retry_interval) elif self.raise_errors: raise if self.retries: msg = (_("Failed to connect to Neutron server after %d attempts") % max_attempts) else: msg = _("Failed to connect Neutron server") raise exceptions.ConnectionFailed(reason=msg) def delete(self, action, body=None, headers=None, params=None): return self.retry_request("DELETE", action, body=body, headers=headers, params=params) def get(self, action, body=None, headers=None, params=None): return self.retry_request("GET", action, body=body, headers=headers, params=params) def post(self, action, body=None, headers=None, params=None): # Do not retry POST requests to avoid the orphan objects problem. return self.do_request("POST", action, body=body, headers=headers, params=params) def put(self, action, body=None, headers=None, params=None): return self.retry_request("PUT", action, body=body, headers=headers, params=params) def list(self, collection, path, retrieve_all=True, **params): if retrieve_all: res = [] request_ids = [] for r in self._pagination(collection, path, **params): res.extend(r[collection]) request_ids.extend(r.request_ids) return _DictWithMeta({collection: res}, request_ids) else: return _GeneratorWithMeta(self._pagination, collection, path, **params) def _pagination(self, collection, path, **params): if params.get('page_reverse', False): linkrel = 'previous' else: linkrel = 'next' next = True while next: res = self.get(path, params=params) yield res next = False try: for link in res['%s_links' % collection]: if link['rel'] == linkrel: query_str = urlparse.urlparse(link['href']).query params = urlparse.parse_qs(query_str) next = True break except KeyError: break def _convert_into_with_meta(self, item, resp): if item: if isinstance(item, dict): return _DictWithMeta(item, resp) elif isinstance(item, str): return _StrWithMeta(item, resp) else: return _TupleWithMeta((), resp) def get_resource_plural(self, resource): for k in self.EXTED_PLURALS: if self.EXTED_PLURALS[k] == resource: return k return resource + 's' def find_resource_by_id(self, resource, resource_id, cmd_resource=None, parent_id=None, fields=None): if not cmd_resource: cmd_resource = resource cmd_resource_plural = self.get_resource_plural(cmd_resource) resource_plural = self.get_resource_plural(resource) # TODO(amotoki): Use show_%s instead of list_%s obj_lister = getattr(self, "list_%s" % cmd_resource_plural) # perform search by id only if we are passing a valid UUID match = re.match(UUID_PATTERN, resource_id) collection = resource_plural if match: params = {'id': resource_id} if fields: params['fields'] = fields if parent_id: data = obj_lister(parent_id, **params) else: data = obj_lister(**params) if data and data[collection]: return data[collection][0] not_found_message = (_("Unable to find %(resource)s with id " "'%(id)s'") % {'resource': resource, 'id': resource_id}) # 404 is raised by exceptions.NotFound to simulate serverside behavior raise exceptions.NotFound(message=not_found_message) def _find_resource_by_name(self, resource, name, project_id=None, cmd_resource=None, parent_id=None, fields=None): if not cmd_resource: cmd_resource = resource cmd_resource_plural = self.get_resource_plural(cmd_resource) resource_plural = self.get_resource_plural(resource) obj_lister = getattr(self, "list_%s" % cmd_resource_plural) params = {'name': name} if fields: params['fields'] = fields if project_id: params['tenant_id'] = project_id if parent_id: data = obj_lister(parent_id, **params) else: data = obj_lister(**params) collection = resource_plural info = data[collection] if len(info) > 1: raise exceptions.NeutronClientNoUniqueMatch(resource=resource, name=name) elif len(info) == 0: not_found_message = (_("Unable to find %(resource)s with name " "'%(name)s'") % {'resource': resource, 'name': name}) # 404 is raised by exceptions.NotFound # to simulate serverside behavior raise exceptions.NotFound(message=not_found_message) else: return info[0] def find_resource(self, resource, name_or_id, project_id=None, cmd_resource=None, parent_id=None, fields=None): try: return self.find_resource_by_id(resource, name_or_id, cmd_resource, parent_id, fields) except exceptions.NotFound: try: return self._find_resource_by_name( resource, name_or_id, project_id, cmd_resource, parent_id, fields) except exceptions.NotFound: not_found_message = (_("Unable to find %(resource)s with name " "or id '%(name_or_id)s'") % {'resource': resource, 'name_or_id': name_or_id}) raise exceptions.NotFound( message=not_found_message) class Client(ClientBase): networks_path = "/networks" network_path = "/networks/%s" ports_path = "/ports" port_path = "/ports/%s" port_bindings_path = "/ports/%s/bindings" port_binding_path = "/ports/%s/bindings/%s" port_binding_path_activate = "/ports/%s/bindings/%s/activate" subnets_path = "/subnets" subnet_path = "/subnets/%s" onboard_network_subnets_path = "/subnetpools/%s/onboard_network_subnets" subnetpools_path = "/subnetpools" subnetpool_path = "/subnetpools/%s" address_scopes_path = "/address-scopes" address_scope_path = "/address-scopes/%s" quotas_path = "/quotas" quota_path = "/quotas/%s" quota_default_path = "/quotas/%s/default" quota_details_path = "/quotas/%s/details.json" extensions_path = "/extensions" extension_path = "/extensions/%s" routers_path = "/routers" router_path = "/routers/%s" floatingips_path = "/floatingips" floatingip_path = "/floatingips/%s" security_groups_path = "/security-groups" security_group_path = "/security-groups/%s" security_group_rules_path = "/security-group-rules" security_group_rule_path = "/security-group-rules/%s" segments_path = "/segments" segment_path = "/segments/%s" sfc_flow_classifiers_path = "/sfc/flow_classifiers" sfc_flow_classifier_path = "/sfc/flow_classifiers/%s" sfc_port_pairs_path = "/sfc/port_pairs" sfc_port_pair_path = "/sfc/port_pairs/%s" sfc_port_pair_groups_path = "/sfc/port_pair_groups" sfc_port_pair_group_path = "/sfc/port_pair_groups/%s" sfc_port_chains_path = "/sfc/port_chains" sfc_port_chain_path = "/sfc/port_chains/%s" sfc_service_graphs_path = "/sfc/service_graphs" sfc_service_graph_path = "/sfc/service_graphs/%s" endpoint_groups_path = "/vpn/endpoint-groups" endpoint_group_path = "/vpn/endpoint-groups/%s" vpnservices_path = "/vpn/vpnservices" vpnservice_path = "/vpn/vpnservices/%s" ipsecpolicies_path = "/vpn/ipsecpolicies" ipsecpolicy_path = "/vpn/ipsecpolicies/%s" ikepolicies_path = "/vpn/ikepolicies" ikepolicy_path = "/vpn/ikepolicies/%s" ipsec_site_connections_path = "/vpn/ipsec-site-connections" ipsec_site_connection_path = "/vpn/ipsec-site-connections/%s" lbaas_loadbalancers_path = "/lbaas/loadbalancers" lbaas_loadbalancer_path = "/lbaas/loadbalancers/%s" lbaas_loadbalancer_path_stats = "/lbaas/loadbalancers/%s/stats" lbaas_loadbalancer_path_status = "/lbaas/loadbalancers/%s/statuses" lbaas_listeners_path = "/lbaas/listeners" lbaas_listener_path = "/lbaas/listeners/%s" lbaas_l7policies_path = "/lbaas/l7policies" lbaas_l7policy_path = lbaas_l7policies_path + "/%s" lbaas_l7rules_path = lbaas_l7policy_path + "/rules" lbaas_l7rule_path = lbaas_l7rules_path + "/%s" lbaas_pools_path = "/lbaas/pools" lbaas_pool_path = "/lbaas/pools/%s" lbaas_healthmonitors_path = "/lbaas/healthmonitors" lbaas_healthmonitor_path = "/lbaas/healthmonitors/%s" lbaas_members_path = lbaas_pool_path + "/members" lbaas_member_path = lbaas_pool_path + "/members/%s" vips_path = "/lb/vips" vip_path = "/lb/vips/%s" pools_path = "/lb/pools" pool_path = "/lb/pools/%s" pool_path_stats = "/lb/pools/%s/stats" members_path = "/lb/members" member_path = "/lb/members/%s" health_monitors_path = "/lb/health_monitors" health_monitor_path = "/lb/health_monitors/%s" associate_pool_health_monitors_path = "/lb/pools/%s/health_monitors" disassociate_pool_health_monitors_path = ( "/lb/pools/%(pool)s/health_monitors/%(health_monitor)s") qos_queues_path = "/qos-queues" qos_queue_path = "/qos-queues/%s" agents_path = "/agents" agent_path = "/agents/%s" network_gateways_path = "/network-gateways" network_gateway_path = "/network-gateways/%s" gateway_devices_path = "/gateway-devices" gateway_device_path = "/gateway-devices/%s" service_providers_path = "/service-providers" metering_labels_path = "/metering/metering-labels" metering_label_path = "/metering/metering-labels/%s" metering_label_rules_path = "/metering/metering-label-rules" metering_label_rule_path = "/metering/metering-label-rules/%s" DHCP_NETS = '/dhcp-networks' DHCP_AGENTS = '/dhcp-agents' L3_ROUTERS = '/l3-routers' L3_AGENTS = '/l3-agents' LOADBALANCER_POOLS = '/loadbalancer-pools' LOADBALANCER_AGENT = '/loadbalancer-agent' AGENT_LOADBALANCERS = '/agent-loadbalancers' LOADBALANCER_HOSTING_AGENT = '/loadbalancer-hosting-agent' firewall_rules_path = "/fw/firewall_rules" firewall_rule_path = "/fw/firewall_rules/%s" firewall_policies_path = "/fw/firewall_policies" firewall_policy_path = "/fw/firewall_policies/%s" firewall_policy_insert_path = "/fw/firewall_policies/%s/insert_rule" firewall_policy_remove_path = "/fw/firewall_policies/%s/remove_rule" firewalls_path = "/fw/firewalls" firewall_path = "/fw/firewalls/%s" fwaas_firewall_groups_path = "/fwaas/firewall_groups" fwaas_firewall_group_path = "/fwaas/firewall_groups/%s" fwaas_firewall_rules_path = "/fwaas/firewall_rules" fwaas_firewall_rule_path = "/fwaas/firewall_rules/%s" fwaas_firewall_policies_path = "/fwaas/firewall_policies" fwaas_firewall_policy_path = "/fwaas/firewall_policies/%s" fwaas_firewall_policy_insert_path = \ "/fwaas/firewall_policies/%s/insert_rule" fwaas_firewall_policy_remove_path = \ "/fwaas/firewall_policies/%s/remove_rule" rbac_policies_path = "/rbac-policies" rbac_policy_path = "/rbac-policies/%s" qos_policies_path = "/qos/policies" qos_policy_path = "/qos/policies/%s" qos_bandwidth_limit_rules_path = "/qos/policies/%s/bandwidth_limit_rules" qos_bandwidth_limit_rule_path = "/qos/policies/%s/bandwidth_limit_rules/%s" qos_packet_rate_limit_rules_path = \ "/qos/policies/%s/packet_rate_limit_rules" qos_packet_rate_limit_rule_path = \ "/qos/policies/%s/packet_rate_limit_rules/%s" qos_dscp_marking_rules_path = "/qos/policies/%s/dscp_marking_rules" qos_dscp_marking_rule_path = "/qos/policies/%s/dscp_marking_rules/%s" qos_minimum_bandwidth_rules_path = \ "/qos/policies/%s/minimum_bandwidth_rules" qos_minimum_bandwidth_rule_path = \ "/qos/policies/%s/minimum_bandwidth_rules/%s" qos_minimum_packet_rate_rules_path = \ "/qos/policies/%s/minimum_packet_rate_rules" qos_minimum_packet_rate_rule_path = \ "/qos/policies/%s/minimum_packet_rate_rules/%s" qos_rule_types_path = "/qos/rule-types" qos_rule_type_path = "/qos/rule-types/%s" flavors_path = "/flavors" flavor_path = "/flavors/%s" service_profiles_path = "/service_profiles" service_profile_path = "/service_profiles/%s" flavor_profile_bindings_path = flavor_path + service_profiles_path flavor_profile_binding_path = flavor_path + service_profile_path availability_zones_path = "/availability_zones" auto_allocated_topology_path = "/auto-allocated-topology/%s" BGP_DRINSTANCES = "/bgp-drinstances" BGP_DRINSTANCE = "/bgp-drinstance/%s" BGP_DRAGENTS = "/bgp-dragents" BGP_DRAGENT = "/bgp-dragents/%s" bgp_speakers_path = "/bgp-speakers" bgp_speaker_path = "/bgp-speakers/%s" bgp_peers_path = "/bgp-peers" bgp_peer_path = "/bgp-peers/%s" network_ip_availabilities_path = '/network-ip-availabilities' network_ip_availability_path = '/network-ip-availabilities/%s' tags_path = "/%s/%s/tags" tag_path = "/%s/%s/tags/%s" trunks_path = "/trunks" trunk_path = "/trunks/%s" subports_path = "/trunks/%s/get_subports" subports_add_path = "/trunks/%s/add_subports" subports_remove_path = "/trunks/%s/remove_subports" bgpvpns_path = "/bgpvpn/bgpvpns" bgpvpn_path = "/bgpvpn/bgpvpns/%s" bgpvpn_network_associations_path =\ "/bgpvpn/bgpvpns/%s/network_associations" bgpvpn_network_association_path =\ "/bgpvpn/bgpvpns/%s/network_associations/%s" bgpvpn_router_associations_path = "/bgpvpn/bgpvpns/%s/router_associations" bgpvpn_router_association_path =\ "/bgpvpn/bgpvpns/%s/router_associations/%s" bgpvpn_port_associations_path = "/bgpvpn/bgpvpns/%s/port_associations" bgpvpn_port_association_path = "/bgpvpn/bgpvpns/%s/port_associations/%s" network_logs_path = "/log/logs" network_log_path = "/log/logs/%s" network_loggables_path = "/log/loggable-resources" # API has no way to report plurals, so we have to hard code them EXTED_PLURALS = {'routers': 'router', 'floatingips': 'floatingip', 'service_types': 'service_type', 'service_definitions': 'service_definition', 'security_groups': 'security_group', 'security_group_rules': 'security_group_rule', 'segments': 'segment', 'ipsecpolicies': 'ipsecpolicy', 'ikepolicies': 'ikepolicy', 'ipsec_site_connections': 'ipsec_site_connection', 'vpnservices': 'vpnservice', 'endpoint_groups': 'endpoint_group', 'vips': 'vip', 'pools': 'pool', 'members': 'member', 'health_monitors': 'health_monitor', 'quotas': 'quota', 'service_providers': 'service_provider', 'firewall_rules': 'firewall_rule', 'firewall_policies': 'firewall_policy', 'firewalls': 'firewall', 'fwaas_firewall_rules': 'fwaas_firewall_rule', 'fwaas_firewall_policies': 'fwaas_firewall_policy', 'fwaas_firewall_groups': 'fwaas_firewall_group', 'metering_labels': 'metering_label', 'metering_label_rules': 'metering_label_rule', 'loadbalancers': 'loadbalancer', 'listeners': 'listener', 'l7rules': 'l7rule', 'l7policies': 'l7policy', 'lbaas_l7policies': 'lbaas_l7policy', 'lbaas_pools': 'lbaas_pool', 'lbaas_healthmonitors': 'lbaas_healthmonitor', 'lbaas_members': 'lbaas_member', 'healthmonitors': 'healthmonitor', 'rbac_policies': 'rbac_policy', 'address_scopes': 'address_scope', 'qos_policies': 'qos_policy', 'policies': 'policy', 'bandwidth_limit_rules': 'bandwidth_limit_rule', 'packet_rate_limit_rules': 'packet_rate_limit_rule', 'minimum_bandwidth_rules': 'minimum_bandwidth_rule', 'minimum_packet_rate_rules': 'minimum_packet_rate_rule', 'rules': 'rule', 'dscp_marking_rules': 'dscp_marking_rule', 'rule_types': 'rule_type', 'flavors': 'flavor', 'bgp_speakers': 'bgp_speaker', 'bgp_peers': 'bgp_peer', 'network_ip_availabilities': 'network_ip_availability', 'trunks': 'trunk', 'bgpvpns': 'bgpvpn', 'network_associations': 'network_association', 'router_associations': 'router_association', 'port_associations': 'port_association', 'flow_classifiers': 'flow_classifier', 'port_pairs': 'port_pair', 'port_pair_groups': 'port_pair_group', 'port_chains': 'port_chain', 'service_graphs': 'service_graph', 'logs': 'log', 'loggable_resources': 'loggable_resource', } def list_ext(self, collection, path, retrieve_all, **_params): """Client extension hook for list.""" return self.list(collection, path, retrieve_all, **_params) def show_ext(self, path, id, **_params): """Client extension hook for show.""" return self.get(path % id, params=_params) def create_ext(self, path, body=None): """Client extension hook for create.""" return self.post(path, body=body) def update_ext(self, path, id, body=None): """Client extension hook for update.""" return self.put(path % id, body=body) def delete_ext(self, path, id): """Client extension hook for delete.""" return self.delete(path % id) def get_quotas_tenant(self, **_params): """Fetch project info for following quota operation.""" return self.get(self.quota_path % 'tenant', params=_params) def list_quotas(self, **_params): """Fetch all projects' quotas.""" return self.get(self.quotas_path, params=_params) @debtcollector.renames.renamed_kwarg( 'tenant_id', 'project_id', replace=True) def show_quota(self, project_id, **_params): """Fetch information of a certain project's quotas.""" return self.get(self.quota_path % (project_id), params=_params) @debtcollector.renames.renamed_kwarg( 'tenant_id', 'project_id', replace=True) def show_quota_details(self, project_id, **_params): """Fetch information of a certain project's quota details.""" return self.get(self.quota_details_path % (project_id), params=_params) @debtcollector.renames.renamed_kwarg( 'tenant_id', 'project_id', replace=True) def show_quota_default(self, project_id, **_params): """Fetch information of a certain project's default quotas.""" return self.get(self.quota_default_path % (project_id), params=_params) @debtcollector.renames.renamed_kwarg( 'tenant_id', 'project_id', replace=True) def update_quota(self, project_id, body=None): """Update a project's quotas.""" return self.put(self.quota_path % (project_id), body=body) @debtcollector.renames.renamed_kwarg( 'tenant_id', 'project_id', replace=True) def delete_quota(self, project_id): """Delete the specified project's quota values.""" return self.delete(self.quota_path % (project_id)) def list_extensions(self, **_params): """Fetch a list of all extensions on server side.""" return self.get(self.extensions_path, params=_params) def show_extension(self, ext_alias, **_params): """Fetches information of a certain extension.""" return self.get(self.extension_path % ext_alias, params=_params) def list_ports(self, retrieve_all=True, **_params): """Fetches a list of all ports for a project.""" # Pass filters in "params" argument to do_request return self.list('ports', self.ports_path, retrieve_all, **_params) def show_port(self, port, **_params): """Fetches information of a certain port.""" return self.get(self.port_path % (port), params=_params) def create_port(self, body=None): """Creates a new port.""" return self.post(self.ports_path, body=body) def update_port(self, port, body=None, revision_number=None): """Updates a port.""" return self._update_resource(self.port_path % (port), body=body, revision_number=revision_number) def delete_port(self, port): """Deletes the specified port.""" return self.delete(self.port_path % (port)) def create_port_binding(self, port_id, body=None): """Creates a new port binding.""" return self.post(self.port_bindings_path % port_id, body=body) def delete_port_binding(self, port_id, host_id): """Deletes the specified port binding.""" return self.delete(self.port_binding_path % (port_id, host_id)) def show_port_binding(self, port_id, host_id, **_params): """Fetches information for a certain port binding.""" return self.get(self.port_binding_path % (port_id, host_id), params=_params) def list_port_bindings(self, port_id, retrieve_all=True, **_params): """Fetches a list of all bindings for a certain port.""" return self.list('port_bindings', self.port_bindings_path % port_id, retrieve_all, **_params) def activate_port_binding(self, port_id, host_id): """Activates a port binding.""" return self.put(self.port_binding_path_activate % (port_id, host_id)) def list_networks(self, retrieve_all=True, **_params): """Fetches a list of all networks for a project.""" # Pass filters in "params" argument to do_request return self.list('networks', self.networks_path, retrieve_all, **_params) def show_network(self, network, **_params): """Fetches information of a certain network.""" return self.get(self.network_path % (network), params=_params) def create_network(self, body=None): """Creates a new network.""" return self.post(self.networks_path, body=body) def update_network(self, network, body=None, revision_number=None): """Updates a network.""" return self._update_resource(self.network_path % (network), body=body, revision_number=revision_number) def delete_network(self, network): """Deletes the specified network.""" return self.delete(self.network_path % (network)) def list_subnets(self, retrieve_all=True, **_params): """Fetches a list of all subnets for a project.""" return self.list('subnets', self.subnets_path, retrieve_all, **_params) def show_subnet(self, subnet, **_params): """Fetches information of a certain subnet.""" return self.get(self.subnet_path % (subnet), params=_params) def create_subnet(self, body=None): """Creates a new subnet.""" return self.post(self.subnets_path, body=body) def update_subnet(self, subnet, body=None, revision_number=None): """Updates a subnet.""" return self._update_resource(self.subnet_path % (subnet), body=body, revision_number=revision_number) def delete_subnet(self, subnet): """Deletes the specified subnet.""" return self.delete(self.subnet_path % (subnet)) def list_subnetpools(self, retrieve_all=True, **_params): """Fetches a list of all subnetpools for a project.""" return self.list('subnetpools', self.subnetpools_path, retrieve_all, **_params) def show_subnetpool(self, subnetpool, **_params): """Fetches information of a certain subnetpool.""" return self.get(self.subnetpool_path % (subnetpool), params=_params) def create_subnetpool(self, body=None): """Creates a new subnetpool.""" return self.post(self.subnetpools_path, body=body) def update_subnetpool(self, subnetpool, body=None, revision_number=None): """Updates a subnetpool.""" return self._update_resource(self.subnetpool_path % (subnetpool), body=body, revision_number=revision_number) def delete_subnetpool(self, subnetpool): """Deletes the specified subnetpool.""" return self.delete(self.subnetpool_path % (subnetpool)) def list_routers(self, retrieve_all=True, **_params): """Fetches a list of all routers for a project.""" # Pass filters in "params" argument to do_request return self.list('routers', self.routers_path, retrieve_all, **_params) def show_router(self, router, **_params): """Fetches information of a certain router.""" return self.get(self.router_path % (router), params=_params) def create_router(self, body=None): """Creates a new router.""" return self.post(self.routers_path, body=body) def update_router(self, router, body=None, revision_number=None): """Updates a router.""" return self._update_resource(self.router_path % (router), body=body, revision_number=revision_number) def delete_router(self, router): """Deletes the specified router.""" return self.delete(self.router_path % (router)) def list_address_scopes(self, retrieve_all=True, **_params): """Fetches a list of all address scopes for a project.""" return self.list('address_scopes', self.address_scopes_path, retrieve_all, **_params) def show_address_scope(self, address_scope, **_params): """Fetches information of a certain address scope.""" return self.get(self.address_scope_path % (address_scope), params=_params) def create_address_scope(self, body=None): """Creates a new address scope.""" return self.post(self.address_scopes_path, body=body) def update_address_scope(self, address_scope, body=None): """Updates a address scope.""" return self.put(self.address_scope_path % (address_scope), body=body) def delete_address_scope(self, address_scope): """Deletes the specified address scope.""" return self.delete(self.address_scope_path % (address_scope)) def add_interface_router(self, router, body=None): """Adds an internal network interface to the specified router.""" return self.put((self.router_path % router) + "/add_router_interface", body=body) def remove_interface_router(self, router, body=None): """Removes an internal network interface from the specified router.""" return self.put((self.router_path % router) + "/remove_router_interface", body=body) def add_extra_routes_to_router(self, router, body=None): """Adds extra routes to the specified router.""" return self.put((self.router_path % router) + "/add_extraroutes", body=body) def remove_extra_routes_from_router(self, router, body=None): """Removes extra routes from the specified router.""" return self.put((self.router_path % router) + "/remove_extraroutes", body=body) def add_gateway_router(self, router, body=None): """Adds an external network gateway to the specified router.""" return self.put((self.router_path % router), body={'router': {'external_gateway_info': body}}) def remove_gateway_router(self, router): """Removes an external network gateway from the specified router.""" return self.put((self.router_path % router), body={'router': {'external_gateway_info': {}}}) def list_floatingips(self, retrieve_all=True, **_params): """Fetches a list of all floatingips for a project.""" # Pass filters in "params" argument to do_request return self.list('floatingips', self.floatingips_path, retrieve_all, **_params) def show_floatingip(self, floatingip, **_params): """Fetches information of a certain floatingip.""" return self.get(self.floatingip_path % (floatingip), params=_params) def create_floatingip(self, body=None): """Creates a new floatingip.""" return self.post(self.floatingips_path, body=body) def update_floatingip(self, floatingip, body=None, revision_number=None): """Updates a floatingip.""" return self._update_resource(self.floatingip_path % (floatingip), body=body, revision_number=revision_number) def delete_floatingip(self, floatingip): """Deletes the specified floatingip.""" return self.delete(self.floatingip_path % (floatingip)) def create_security_group(self, body=None): """Creates a new security group.""" return self.post(self.security_groups_path, body=body) def update_security_group(self, security_group, body=None, revision_number=None): """Updates a security group.""" return self._update_resource(self.security_group_path % security_group, body=body, revision_number=revision_number) def list_security_groups(self, retrieve_all=True, **_params): """Fetches a list of all security groups for a project.""" return self.list('security_groups', self.security_groups_path, retrieve_all, **_params) def show_security_group(self, security_group, **_params): """Fetches information of a certain security group.""" return self.get(self.security_group_path % (security_group), params=_params) def delete_security_group(self, security_group): """Deletes the specified security group.""" return self.delete(self.security_group_path % (security_group)) def create_security_group_rule(self, body=None): """Creates a new security group rule.""" return self.post(self.security_group_rules_path, body=body) def delete_security_group_rule(self, security_group_rule): """Deletes the specified security group rule.""" return self.delete(self.security_group_rule_path % (security_group_rule)) def list_security_group_rules(self, retrieve_all=True, **_params): """Fetches a list of all security group rules for a project.""" return self.list('security_group_rules', self.security_group_rules_path, retrieve_all, **_params) def show_security_group_rule(self, security_group_rule, **_params): """Fetches information of a certain security group rule.""" return self.get(self.security_group_rule_path % (security_group_rule), params=_params) def create_segment(self, body=None): """Creates a new segment.""" return self.post(self.segments_path, body=body) def update_segment(self, segment, body=None, revision_number=None): """Updates a segment.""" return self._update_resource(self.segment_path % segment, body=body, revision_number=revision_number) def list_segments(self, retrieve_all=True, **_params): """Fetches a list of all segments for a project.""" return self.list('segments', self.segments_path, retrieve_all, **_params) def show_segment(self, segment, **_params): """Fetches information of a certain segment.""" return self.get(self.segment_path % segment, params=_params) def delete_segment(self, segment): """Deletes the specified segment.""" return self.delete(self.segment_path % segment) def list_endpoint_groups(self, retrieve_all=True, **_params): """Fetches a list of all VPN endpoint groups for a project.""" return self.list('endpoint_groups', self.endpoint_groups_path, retrieve_all, **_params) def show_endpoint_group(self, endpointgroup, **_params): """Fetches information for a specific VPN endpoint group.""" return self.get(self.endpoint_group_path % endpointgroup, params=_params) def create_endpoint_group(self, body=None): """Creates a new VPN endpoint group.""" return self.post(self.endpoint_groups_path, body=body) def update_endpoint_group(self, endpoint_group, body=None): """Updates a VPN endpoint group.""" return self.put(self.endpoint_group_path % endpoint_group, body=body) def delete_endpoint_group(self, endpoint_group): """Deletes the specified VPN endpoint group.""" return self.delete(self.endpoint_group_path % endpoint_group) def list_vpnservices(self, retrieve_all=True, **_params): """Fetches a list of all configured VPN services for a project.""" return self.list('vpnservices', self.vpnservices_path, retrieve_all, **_params) def show_vpnservice(self, vpnservice, **_params): """Fetches information of a specific VPN service.""" return self.get(self.vpnservice_path % (vpnservice), params=_params) def create_vpnservice(self, body=None): """Creates a new VPN service.""" return self.post(self.vpnservices_path, body=body) def update_vpnservice(self, vpnservice, body=None): """Updates a VPN service.""" return self.put(self.vpnservice_path % (vpnservice), body=body) def delete_vpnservice(self, vpnservice): """Deletes the specified VPN service.""" return self.delete(self.vpnservice_path % (vpnservice)) def list_ipsec_site_connections(self, retrieve_all=True, **_params): """Fetches all configured IPsecSiteConnections for a project.""" return self.list('ipsec_site_connections', self.ipsec_site_connections_path, retrieve_all, **_params) def show_ipsec_site_connection(self, ipsecsite_conn, **_params): """Fetches information of a specific IPsecSiteConnection.""" return self.get( self.ipsec_site_connection_path % (ipsecsite_conn), params=_params ) def create_ipsec_site_connection(self, body=None): """Creates a new IPsecSiteConnection.""" return self.post(self.ipsec_site_connections_path, body=body) def update_ipsec_site_connection(self, ipsecsite_conn, body=None): """Updates an IPsecSiteConnection.""" return self.put( self.ipsec_site_connection_path % (ipsecsite_conn), body=body ) def delete_ipsec_site_connection(self, ipsecsite_conn): """Deletes the specified IPsecSiteConnection.""" return self.delete(self.ipsec_site_connection_path % (ipsecsite_conn)) def list_ikepolicies(self, retrieve_all=True, **_params): """Fetches a list of all configured IKEPolicies for a project.""" return self.list('ikepolicies', self.ikepolicies_path, retrieve_all, **_params) def show_ikepolicy(self, ikepolicy, **_params): """Fetches information of a specific IKEPolicy.""" return self.get(self.ikepolicy_path % (ikepolicy), params=_params) def create_ikepolicy(self, body=None): """Creates a new IKEPolicy.""" return self.post(self.ikepolicies_path, body=body) def update_ikepolicy(self, ikepolicy, body=None): """Updates an IKEPolicy.""" return self.put(self.ikepolicy_path % (ikepolicy), body=body) def delete_ikepolicy(self, ikepolicy): """Deletes the specified IKEPolicy.""" return self.delete(self.ikepolicy_path % (ikepolicy)) def list_ipsecpolicies(self, retrieve_all=True, **_params): """Fetches a list of all configured IPsecPolicies for a project.""" return self.list('ipsecpolicies', self.ipsecpolicies_path, retrieve_all, **_params) def show_ipsecpolicy(self, ipsecpolicy, **_params): """Fetches information of a specific IPsecPolicy.""" return self.get(self.ipsecpolicy_path % (ipsecpolicy), params=_params) def create_ipsecpolicy(self, body=None): """Creates a new IPsecPolicy.""" return self.post(self.ipsecpolicies_path, body=body) def update_ipsecpolicy(self, ipsecpolicy, body=None): """Updates an IPsecPolicy.""" return self.put(self.ipsecpolicy_path % (ipsecpolicy), body=body) def delete_ipsecpolicy(self, ipsecpolicy): """Deletes the specified IPsecPolicy.""" return self.delete(self.ipsecpolicy_path % (ipsecpolicy)) def list_loadbalancers(self, retrieve_all=True, **_params): """Fetches a list of all loadbalancers for a project.""" return self.list('loadbalancers', self.lbaas_loadbalancers_path, retrieve_all, **_params) def show_loadbalancer(self, lbaas_loadbalancer, **_params): """Fetches information for a load balancer.""" return self.get(self.lbaas_loadbalancer_path % (lbaas_loadbalancer), params=_params) def create_loadbalancer(self, body=None): """Creates a new load balancer.""" return self.post(self.lbaas_loadbalancers_path, body=body) def update_loadbalancer(self, lbaas_loadbalancer, body=None): """Updates a load balancer.""" return self.put(self.lbaas_loadbalancer_path % (lbaas_loadbalancer), body=body) def delete_loadbalancer(self, lbaas_loadbalancer): """Deletes the specified load balancer.""" return self.delete(self.lbaas_loadbalancer_path % (lbaas_loadbalancer)) def retrieve_loadbalancer_stats(self, loadbalancer, **_params): """Retrieves stats for a certain load balancer.""" return self.get(self.lbaas_loadbalancer_path_stats % (loadbalancer), params=_params) def retrieve_loadbalancer_status(self, loadbalancer, **_params): """Retrieves status for a certain load balancer.""" return self.get(self.lbaas_loadbalancer_path_status % (loadbalancer), params=_params) def list_listeners(self, retrieve_all=True, **_params): """Fetches a list of all lbaas_listeners for a project.""" return self.list('listeners', self.lbaas_listeners_path, retrieve_all, **_params) def show_listener(self, lbaas_listener, **_params): """Fetches information for a lbaas_listener.""" return self.get(self.lbaas_listener_path % (lbaas_listener), params=_params) def create_listener(self, body=None): """Creates a new lbaas_listener.""" return self.post(self.lbaas_listeners_path, body=body) def update_listener(self, lbaas_listener, body=None): """Updates a lbaas_listener.""" return self.put(self.lbaas_listener_path % (lbaas_listener), body=body) def delete_listener(self, lbaas_listener): """Deletes the specified lbaas_listener.""" return self.delete(self.lbaas_listener_path % (lbaas_listener)) def list_lbaas_l7policies(self, retrieve_all=True, **_params): """Fetches a list of all L7 policies for a listener.""" return self.list('l7policies', self.lbaas_l7policies_path, retrieve_all, **_params) def show_lbaas_l7policy(self, l7policy, **_params): """Fetches information of a certain listener's L7 policy.""" return self.get(self.lbaas_l7policy_path % l7policy, params=_params) def create_lbaas_l7policy(self, body=None): """Creates L7 policy for a certain listener.""" return self.post(self.lbaas_l7policies_path, body=body) def update_lbaas_l7policy(self, l7policy, body=None): """Updates L7 policy.""" return self.put(self.lbaas_l7policy_path % l7policy, body=body) def delete_lbaas_l7policy(self, l7policy): """Deletes the specified L7 policy.""" return self.delete(self.lbaas_l7policy_path % l7policy) def list_lbaas_l7rules(self, l7policy, retrieve_all=True, **_params): """Fetches a list of all rules for L7 policy.""" return self.list('rules', self.lbaas_l7rules_path % l7policy, retrieve_all, **_params) def show_lbaas_l7rule(self, l7rule, l7policy, **_params): """Fetches information of a certain L7 policy's rule.""" return self.get(self.lbaas_l7rule_path % (l7policy, l7rule), params=_params) def create_lbaas_l7rule(self, l7policy, body=None): """Creates rule for a certain L7 policy.""" return self.post(self.lbaas_l7rules_path % l7policy, body=body) def update_lbaas_l7rule(self, l7rule, l7policy, body=None): """Updates L7 rule.""" return self.put(self.lbaas_l7rule_path % (l7policy, l7rule), body=body) def delete_lbaas_l7rule(self, l7rule, l7policy): """Deletes the specified L7 rule.""" return self.delete(self.lbaas_l7rule_path % (l7policy, l7rule)) def list_lbaas_pools(self, retrieve_all=True, **_params): """Fetches a list of all lbaas_pools for a project.""" return self.list('pools', self.lbaas_pools_path, retrieve_all, **_params) def show_lbaas_pool(self, lbaas_pool, **_params): """Fetches information for a lbaas_pool.""" return self.get(self.lbaas_pool_path % (lbaas_pool), params=_params) def create_lbaas_pool(self, body=None): """Creates a new lbaas_pool.""" return self.post(self.lbaas_pools_path, body=body) def update_lbaas_pool(self, lbaas_pool, body=None): """Updates a lbaas_pool.""" return self.put(self.lbaas_pool_path % (lbaas_pool), body=body) def delete_lbaas_pool(self, lbaas_pool): """Deletes the specified lbaas_pool.""" return self.delete(self.lbaas_pool_path % (lbaas_pool)) def list_lbaas_healthmonitors(self, retrieve_all=True, **_params): """Fetches a list of all lbaas_healthmonitors for a project.""" return self.list('healthmonitors', self.lbaas_healthmonitors_path, retrieve_all, **_params) def show_lbaas_healthmonitor(self, lbaas_healthmonitor, **_params): """Fetches information for a lbaas_healthmonitor.""" return self.get(self.lbaas_healthmonitor_path % (lbaas_healthmonitor), params=_params) def create_lbaas_healthmonitor(self, body=None): """Creates a new lbaas_healthmonitor.""" return self.post(self.lbaas_healthmonitors_path, body=body) def update_lbaas_healthmonitor(self, lbaas_healthmonitor, body=None): """Updates a lbaas_healthmonitor.""" return self.put(self.lbaas_healthmonitor_path % (lbaas_healthmonitor), body=body) def delete_lbaas_healthmonitor(self, lbaas_healthmonitor): """Deletes the specified lbaas_healthmonitor.""" return self.delete(self.lbaas_healthmonitor_path % (lbaas_healthmonitor)) def list_lbaas_loadbalancers(self, retrieve_all=True, **_params): """Fetches a list of all lbaas_loadbalancers for a project.""" return self.list('loadbalancers', self.lbaas_loadbalancers_path, retrieve_all, **_params) def list_lbaas_members(self, lbaas_pool, retrieve_all=True, **_params): """Fetches a list of all lbaas_members for a project.""" return self.list('members', self.lbaas_members_path % lbaas_pool, retrieve_all, **_params) def show_lbaas_member(self, lbaas_member, lbaas_pool, **_params): """Fetches information of a certain lbaas_member.""" return self.get(self.lbaas_member_path % (lbaas_pool, lbaas_member), params=_params) def create_lbaas_member(self, lbaas_pool, body=None): """Creates a lbaas_member.""" return self.post(self.lbaas_members_path % lbaas_pool, body=body) def update_lbaas_member(self, lbaas_member, lbaas_pool, body=None): """Updates a lbaas_member.""" return self.put(self.lbaas_member_path % (lbaas_pool, lbaas_member), body=body) def delete_lbaas_member(self, lbaas_member, lbaas_pool): """Deletes the specified lbaas_member.""" return self.delete(self.lbaas_member_path % (lbaas_pool, lbaas_member)) def list_vips(self, retrieve_all=True, **_params): """Fetches a list of all load balancer vips for a project.""" # Pass filters in "params" argument to do_request return self.list('vips', self.vips_path, retrieve_all, **_params) def show_vip(self, vip, **_params): """Fetches information of a certain load balancer vip.""" return self.get(self.vip_path % (vip), params=_params) def create_vip(self, body=None): """Creates a new load balancer vip.""" return self.post(self.vips_path, body=body) def update_vip(self, vip, body=None): """Updates a load balancer vip.""" return self.put(self.vip_path % (vip), body=body) def delete_vip(self, vip): """Deletes the specified load balancer vip.""" return self.delete(self.vip_path % (vip)) def list_pools(self, retrieve_all=True, **_params): """Fetches a list of all load balancer pools for a project.""" # Pass filters in "params" argument to do_request return self.list('pools', self.pools_path, retrieve_all, **_params) def show_pool(self, pool, **_params): """Fetches information of a certain load balancer pool.""" return self.get(self.pool_path % (pool), params=_params) def create_pool(self, body=None): """Creates a new load balancer pool.""" return self.post(self.pools_path, body=body) def update_pool(self, pool, body=None): """Updates a load balancer pool.""" return self.put(self.pool_path % (pool), body=body) def delete_pool(self, pool): """Deletes the specified load balancer pool.""" return self.delete(self.pool_path % (pool)) def retrieve_pool_stats(self, pool, **_params): """Retrieves stats for a certain load balancer pool.""" return self.get(self.pool_path_stats % (pool), params=_params) def list_members(self, retrieve_all=True, **_params): """Fetches a list of all load balancer members for a project.""" # Pass filters in "params" argument to do_request return self.list('members', self.members_path, retrieve_all, **_params) def show_member(self, member, **_params): """Fetches information of a certain load balancer member.""" return self.get(self.member_path % (member), params=_params) def create_member(self, body=None): """Creates a new load balancer member.""" return self.post(self.members_path, body=body) def update_member(self, member, body=None): """Updates a load balancer member.""" return self.put(self.member_path % (member), body=body) def delete_member(self, member): """Deletes the specified load balancer member.""" return self.delete(self.member_path % (member)) def list_health_monitors(self, retrieve_all=True, **_params): """Fetches a list of all load balancer health monitors for a project. """ # Pass filters in "params" argument to do_request return self.list('health_monitors', self.health_monitors_path, retrieve_all, **_params) def show_health_monitor(self, health_monitor, **_params): """Fetches information of a certain load balancer health monitor.""" return self.get(self.health_monitor_path % (health_monitor), params=_params) def create_health_monitor(self, body=None): """Creates a new load balancer health monitor.""" return self.post(self.health_monitors_path, body=body) def update_health_monitor(self, health_monitor, body=None): """Updates a load balancer health monitor.""" return self.put(self.health_monitor_path % (health_monitor), body=body) def delete_health_monitor(self, health_monitor): """Deletes the specified load balancer health monitor.""" return self.delete(self.health_monitor_path % (health_monitor)) def associate_health_monitor(self, pool, body): """Associate specified load balancer health monitor and pool.""" return self.post(self.associate_pool_health_monitors_path % (pool), body=body) def disassociate_health_monitor(self, pool, health_monitor): """Disassociate specified load balancer health monitor and pool.""" path = (self.disassociate_pool_health_monitors_path % {'pool': pool, 'health_monitor': health_monitor}) return self.delete(path) def create_qos_queue(self, body=None): """Creates a new queue.""" return self.post(self.qos_queues_path, body=body) def list_qos_queues(self, **_params): """Fetches a list of all queues for a project.""" return self.get(self.qos_queues_path, params=_params) def show_qos_queue(self, queue, **_params): """Fetches information of a certain queue.""" return self.get(self.qos_queue_path % (queue), params=_params) def delete_qos_queue(self, queue): """Deletes the specified queue.""" return self.delete(self.qos_queue_path % (queue)) def list_agents(self, **_params): """Fetches agents.""" # Pass filters in "params" argument to do_request return self.get(self.agents_path, params=_params) def show_agent(self, agent, **_params): """Fetches information of a certain agent.""" return self.get(self.agent_path % (agent), params=_params) def update_agent(self, agent, body=None): """Updates an agent.""" return self.put(self.agent_path % (agent), body=body) def delete_agent(self, agent): """Deletes the specified agent.""" return self.delete(self.agent_path % (agent)) def list_network_gateways(self, **_params): """Retrieve network gateways.""" return self.get(self.network_gateways_path, params=_params) def show_network_gateway(self, gateway_id, **_params): """Fetch a network gateway.""" return self.get(self.network_gateway_path % gateway_id, params=_params) def create_network_gateway(self, body=None): """Create a new network gateway.""" return self.post(self.network_gateways_path, body=body) def update_network_gateway(self, gateway_id, body=None): """Update a network gateway.""" return self.put(self.network_gateway_path % gateway_id, body=body) def delete_network_gateway(self, gateway_id): """Delete the specified network gateway.""" return self.delete(self.network_gateway_path % gateway_id) def connect_network_gateway(self, gateway_id, body=None): """Connect a network gateway to the specified network.""" base_uri = self.network_gateway_path % gateway_id return self.put("%s/connect_network" % base_uri, body=body) def disconnect_network_gateway(self, gateway_id, body=None): """Disconnect a network from the specified gateway.""" base_uri = self.network_gateway_path % gateway_id return self.put("%s/disconnect_network" % base_uri, body=body) def list_gateway_devices(self, **_params): """Retrieve gateway devices.""" return self.get(self.gateway_devices_path, params=_params) def show_gateway_device(self, gateway_device_id, **_params): """Fetch a gateway device.""" return self.get(self.gateway_device_path % gateway_device_id, params=_params) def create_gateway_device(self, body=None): """Create a new gateway device.""" return self.post(self.gateway_devices_path, body=body) def update_gateway_device(self, gateway_device_id, body=None): """Updates a new gateway device.""" return self.put(self.gateway_device_path % gateway_device_id, body=body) def delete_gateway_device(self, gateway_device_id): """Delete the specified gateway device.""" return self.delete(self.gateway_device_path % gateway_device_id) def list_dhcp_agent_hosting_networks(self, network, **_params): """Fetches a list of dhcp agents hosting a network.""" return self.get((self.network_path + self.DHCP_AGENTS) % network, params=_params) def list_networks_on_dhcp_agent(self, dhcp_agent, **_params): """Fetches a list of networks hosted on a DHCP agent.""" return self.get((self.agent_path + self.DHCP_NETS) % dhcp_agent, params=_params) def add_network_to_dhcp_agent(self, dhcp_agent, body=None): """Adds a network to dhcp agent.""" return self.post((self.agent_path + self.DHCP_NETS) % dhcp_agent, body=body) def remove_network_from_dhcp_agent(self, dhcp_agent, network_id): """Remove a network from dhcp agent.""" return self.delete((self.agent_path + self.DHCP_NETS + "/%s") % ( dhcp_agent, network_id)) def list_l3_agent_hosting_routers(self, router, **_params): """Fetches a list of L3 agents hosting a router.""" return self.get((self.router_path + self.L3_AGENTS) % router, params=_params) def list_routers_on_l3_agent(self, l3_agent, **_params): """Fetches a list of routers hosted on an L3 agent.""" return self.get((self.agent_path + self.L3_ROUTERS) % l3_agent, params=_params) def add_router_to_l3_agent(self, l3_agent, body): """Adds a router to L3 agent.""" return self.post((self.agent_path + self.L3_ROUTERS) % l3_agent, body=body) def list_dragents_hosting_bgp_speaker(self, bgp_speaker, **_params): """Fetches a list of Dynamic Routing agents hosting a BGP speaker.""" return self.get((self.bgp_speaker_path + self.BGP_DRAGENTS) % bgp_speaker, params=_params) def add_bgp_speaker_to_dragent(self, bgp_dragent, body): """Adds a BGP speaker to Dynamic Routing agent.""" return self.post((self.agent_path + self.BGP_DRINSTANCES) % bgp_dragent, body=body) def remove_bgp_speaker_from_dragent(self, bgp_dragent, bgpspeaker_id): """Removes a BGP speaker from Dynamic Routing agent.""" return self.delete((self.agent_path + self.BGP_DRINSTANCES + "/%s") % (bgp_dragent, bgpspeaker_id)) def list_bgp_speaker_on_dragent(self, bgp_dragent, **_params): """Fetches a list of BGP speakers hosted by Dynamic Routing agent.""" return self.get((self.agent_path + self.BGP_DRINSTANCES) % bgp_dragent, params=_params) def list_firewall_rules(self, retrieve_all=True, **_params): """Fetches a list of all firewall rules for a project.""" # Pass filters in "params" argument to do_request return self.list('firewall_rules', self.firewall_rules_path, retrieve_all, **_params) def show_firewall_rule(self, firewall_rule, **_params): """Fetches information of a certain firewall rule.""" return self.get(self.firewall_rule_path % (firewall_rule), params=_params) def create_firewall_rule(self, body=None): """Creates a new firewall rule.""" return self.post(self.firewall_rules_path, body=body) def update_firewall_rule(self, firewall_rule, body=None): """Updates a firewall rule.""" return self.put(self.firewall_rule_path % (firewall_rule), body=body) def delete_firewall_rule(self, firewall_rule): """Deletes the specified firewall rule.""" return self.delete(self.firewall_rule_path % (firewall_rule)) def list_firewall_policies(self, retrieve_all=True, **_params): """Fetches a list of all firewall policies for a project.""" # Pass filters in "params" argument to do_request return self.list('firewall_policies', self.firewall_policies_path, retrieve_all, **_params) def show_firewall_policy(self, firewall_policy, **_params): """Fetches information of a certain firewall policy.""" return self.get(self.firewall_policy_path % (firewall_policy), params=_params) def create_firewall_policy(self, body=None): """Creates a new firewall policy.""" return self.post(self.firewall_policies_path, body=body) def update_firewall_policy(self, firewall_policy, body=None): """Updates a firewall policy.""" return self.put(self.firewall_policy_path % (firewall_policy), body=body) def delete_firewall_policy(self, firewall_policy): """Deletes the specified firewall policy.""" return self.delete(self.firewall_policy_path % (firewall_policy)) def firewall_policy_insert_rule(self, firewall_policy, body=None): """Inserts specified rule into firewall policy.""" return self.put(self.firewall_policy_insert_path % (firewall_policy), body=body) def firewall_policy_remove_rule(self, firewall_policy, body=None): """Removes specified rule from firewall policy.""" return self.put(self.firewall_policy_remove_path % (firewall_policy), body=body) def list_firewalls(self, retrieve_all=True, **_params): """Fetches a list of all firewalls for a project.""" # Pass filters in "params" argument to do_request return self.list('firewalls', self.firewalls_path, retrieve_all, **_params) def show_firewall(self, firewall, **_params): """Fetches information of a certain firewall.""" return self.get(self.firewall_path % (firewall), params=_params) def create_firewall(self, body=None): """Creates a new firewall.""" return self.post(self.firewalls_path, body=body) def update_firewall(self, firewall, body=None): """Updates a firewall.""" return self.put(self.firewall_path % (firewall), body=body) def delete_firewall(self, firewall): """Deletes the specified firewall.""" return self.delete(self.firewall_path % (firewall)) def list_fwaas_firewall_groups(self, retrieve_all=True, **_params): """Fetches a list of all firewall groups for a project""" return self.list('firewall_groups', self.fwaas_firewall_groups_path, retrieve_all, **_params) def show_fwaas_firewall_group(self, fwg, **_params): """Fetches information of a certain firewall group""" return self.get(self.fwaas_firewall_group_path % (fwg), params=_params) def create_fwaas_firewall_group(self, body=None): """Creates a new firewall group""" return self.post(self.fwaas_firewall_groups_path, body=body) def update_fwaas_firewall_group(self, fwg, body=None): """Updates a firewall group""" return self.put(self.fwaas_firewall_group_path % (fwg), body=body) def delete_fwaas_firewall_group(self, fwg): """Deletes the specified firewall group""" return self.delete(self.fwaas_firewall_group_path % (fwg)) def list_fwaas_firewall_rules(self, retrieve_all=True, **_params): """Fetches a list of all firewall rules for a project""" # Pass filters in "params" argument to do_request return self.list('firewall_rules', self.fwaas_firewall_rules_path, retrieve_all, **_params) def show_fwaas_firewall_rule(self, firewall_rule, **_params): """Fetches information of a certain firewall rule""" return self.get(self.fwaas_firewall_rule_path % (firewall_rule), params=_params) def create_fwaas_firewall_rule(self, body=None): """Creates a new firewall rule""" return self.post(self.fwaas_firewall_rules_path, body=body) def update_fwaas_firewall_rule(self, firewall_rule, body=None): """Updates a firewall rule""" return self.put(self.fwaas_firewall_rule_path % (firewall_rule), body=body) def delete_fwaas_firewall_rule(self, firewall_rule): """Deletes the specified firewall rule""" return self.delete(self.fwaas_firewall_rule_path % (firewall_rule)) def list_fwaas_firewall_policies(self, retrieve_all=True, **_params): """Fetches a list of all firewall policies for a project""" # Pass filters in "params" argument to do_request return self.list('firewall_policies', self.fwaas_firewall_policies_path, retrieve_all, **_params) def show_fwaas_firewall_policy(self, firewall_policy, **_params): """Fetches information of a certain firewall policy""" return self.get(self.fwaas_firewall_policy_path % (firewall_policy), params=_params) def create_fwaas_firewall_policy(self, body=None): """Creates a new firewall policy""" return self.post(self.fwaas_firewall_policies_path, body=body) def update_fwaas_firewall_policy(self, firewall_policy, body=None): """Updates a firewall policy""" return self.put(self.fwaas_firewall_policy_path % (firewall_policy), body=body) def delete_fwaas_firewall_policy(self, firewall_policy): """Deletes the specified firewall policy""" return self.delete(self.fwaas_firewall_policy_path % (firewall_policy)) def insert_rule_fwaas_firewall_policy(self, firewall_policy, body=None): """Inserts specified rule into firewall policy""" return self.put((self.fwaas_firewall_policy_insert_path % (firewall_policy)), body=body) def remove_rule_fwaas_firewall_policy(self, firewall_policy, body=None): """Removes specified rule from firewall policy""" return self.put((self.fwaas_firewall_policy_remove_path % (firewall_policy)), body=body) def remove_router_from_l3_agent(self, l3_agent, router_id): """Remove a router from l3 agent.""" return self.delete((self.agent_path + self.L3_ROUTERS + "/%s") % ( l3_agent, router_id)) def get_lbaas_agent_hosting_pool(self, pool, **_params): """Fetches a loadbalancer agent hosting a pool.""" return self.get((self.pool_path + self.LOADBALANCER_AGENT) % pool, params=_params) def list_pools_on_lbaas_agent(self, lbaas_agent, **_params): """Fetches a list of pools hosted by the loadbalancer agent.""" return self.get((self.agent_path + self.LOADBALANCER_POOLS) % lbaas_agent, params=_params) def get_lbaas_agent_hosting_loadbalancer(self, loadbalancer, **_params): """Fetches a loadbalancer agent hosting a loadbalancer.""" return self.get((self.lbaas_loadbalancer_path + self.LOADBALANCER_HOSTING_AGENT) % loadbalancer, params=_params) def list_loadbalancers_on_lbaas_agent(self, lbaas_agent, **_params): """Fetches a list of loadbalancers hosted by the loadbalancer agent.""" return self.get((self.agent_path + self.AGENT_LOADBALANCERS) % lbaas_agent, params=_params) def list_service_providers(self, retrieve_all=True, **_params): """Fetches service providers.""" # Pass filters in "params" argument to do_request return self.list('service_providers', self.service_providers_path, retrieve_all, **_params) def create_metering_label(self, body=None): """Creates a metering label.""" return self.post(self.metering_labels_path, body=body) def delete_metering_label(self, label): """Deletes the specified metering label.""" return self.delete(self.metering_label_path % (label)) def list_metering_labels(self, retrieve_all=True, **_params): """Fetches a list of all metering labels for a project.""" return self.list('metering_labels', self.metering_labels_path, retrieve_all, **_params) def show_metering_label(self, metering_label, **_params): """Fetches information of a certain metering label.""" return self.get(self.metering_label_path % (metering_label), params=_params) def create_metering_label_rule(self, body=None): """Creates a metering label rule.""" return self.post(self.metering_label_rules_path, body=body) def delete_metering_label_rule(self, rule): """Deletes the specified metering label rule.""" return self.delete(self.metering_label_rule_path % (rule)) def list_metering_label_rules(self, retrieve_all=True, **_params): """Fetches a list of all metering label rules for a label.""" return self.list('metering_label_rules', self.metering_label_rules_path, retrieve_all, **_params) def show_metering_label_rule(self, metering_label_rule, **_params): """Fetches information of a certain metering label rule.""" return self.get(self.metering_label_rule_path % (metering_label_rule), params=_params) def create_rbac_policy(self, body=None): """Create a new RBAC policy.""" return self.post(self.rbac_policies_path, body=body) def update_rbac_policy(self, rbac_policy_id, body=None): """Update a RBAC policy.""" return self.put(self.rbac_policy_path % rbac_policy_id, body=body) def list_rbac_policies(self, retrieve_all=True, **_params): """Fetch a list of all RBAC policies for a project.""" return self.list('rbac_policies', self.rbac_policies_path, retrieve_all, **_params) def show_rbac_policy(self, rbac_policy_id, **_params): """Fetch information of a certain RBAC policy.""" return self.get(self.rbac_policy_path % rbac_policy_id, params=_params) def delete_rbac_policy(self, rbac_policy_id): """Delete the specified RBAC policy.""" return self.delete(self.rbac_policy_path % rbac_policy_id) def list_qos_policies(self, retrieve_all=True, **_params): """Fetches a list of all qos policies for a project.""" # Pass filters in "params" argument to do_request return self.list('policies', self.qos_policies_path, retrieve_all, **_params) def show_qos_policy(self, qos_policy, **_params): """Fetches information of a certain qos policy.""" return self.get(self.qos_policy_path % qos_policy, params=_params) def create_qos_policy(self, body=None): """Creates a new qos policy.""" return self.post(self.qos_policies_path, body=body) def update_qos_policy(self, qos_policy, body=None, revision_number=None): """Updates a qos policy.""" return self._update_resource(self.qos_policy_path % qos_policy, body=body, revision_number=revision_number) def delete_qos_policy(self, qos_policy): """Deletes the specified qos policy.""" return self.delete(self.qos_policy_path % qos_policy) def list_qos_rule_types(self, retrieve_all=True, **_params): """List available qos rule types.""" return self.list('rule_types', self.qos_rule_types_path, retrieve_all, **_params) def list_bandwidth_limit_rules(self, policy_id, retrieve_all=True, **_params): """Fetches a list of all bandwidth limit rules for the given policy.""" return self.list('bandwidth_limit_rules', self.qos_bandwidth_limit_rules_path % policy_id, retrieve_all, **_params) def show_bandwidth_limit_rule(self, rule, policy, **_params): """Fetches information of a certain bandwidth limit rule.""" return self.get(self.qos_bandwidth_limit_rule_path % (policy, rule), params=_params) def create_bandwidth_limit_rule(self, policy, body=None): """Creates a new bandwidth limit rule.""" return self.post(self.qos_bandwidth_limit_rules_path % policy, body=body) def update_bandwidth_limit_rule(self, rule, policy, body=None): """Updates a bandwidth limit rule.""" return self.put(self.qos_bandwidth_limit_rule_path % (policy, rule), body=body) def delete_bandwidth_limit_rule(self, rule, policy): """Deletes a bandwidth limit rule.""" return self.delete(self.qos_bandwidth_limit_rule_path % (policy, rule)) def list_dscp_marking_rules(self, policy_id, retrieve_all=True, **_params): """Fetches a list of all DSCP marking rules for the given policy.""" return self.list('dscp_marking_rules', self.qos_dscp_marking_rules_path % policy_id, retrieve_all, **_params) def show_dscp_marking_rule(self, rule, policy, **_params): """Shows information of a certain DSCP marking rule.""" return self.get(self.qos_dscp_marking_rule_path % (policy, rule), params=_params) def create_dscp_marking_rule(self, policy, body=None): """Creates a new DSCP marking rule.""" return self.post(self.qos_dscp_marking_rules_path % policy, body=body) def update_dscp_marking_rule(self, rule, policy, body=None): """Updates a DSCP marking rule.""" return self.put(self.qos_dscp_marking_rule_path % (policy, rule), body=body) def delete_dscp_marking_rule(self, rule, policy): """Deletes a DSCP marking rule.""" return self.delete(self.qos_dscp_marking_rule_path % (policy, rule)) def list_minimum_bandwidth_rules(self, policy_id, retrieve_all=True, **_params): """Fetches a list of all minimum bandwidth rules for the given policy. """ return self.list('minimum_bandwidth_rules', self.qos_minimum_bandwidth_rules_path % policy_id, retrieve_all, **_params) def show_minimum_bandwidth_rule(self, rule, policy, body=None): """Fetches information of a certain minimum bandwidth rule.""" return self.get(self.qos_minimum_bandwidth_rule_path % (policy, rule), body=body) def create_minimum_bandwidth_rule(self, policy, body=None): """Creates a new minimum bandwidth rule.""" return self.post(self.qos_minimum_bandwidth_rules_path % policy, body=body) def list_packet_rate_limit_rules(self, policy_id, retrieve_all=True, **_params): """Fetches a list of all packet rate limit rules for the given policy """ return self.list('packet_rate_limit_rules', self.qos_packet_rate_limit_rules_path % policy_id, retrieve_all, **_params) def show_packet_rate_limit_rule(self, rule, policy, body=None): """Fetches information of a certain packet rate limit rule.""" return self.get(self.qos_packet_rate_limit_rule_path % (policy, rule), body=body) def create_packet_rate_limit_rule(self, policy, body=None): """Creates a new packet rate limit rule.""" return self.post(self.qos_packet_rate_limit_rules_path % policy, body=body) def update_packet_rate_limit_rule(self, rule, policy, body=None): """Updates a packet rate limit rule.""" return self.put(self.qos_packet_rate_limit_rule_path % (policy, rule), body=body) def delete_packet_rate_limit_rule(self, rule, policy): """Deletes a packet rate limit rule.""" return self.delete(self.qos_packet_rate_limit_rule_path % (policy, rule)) def update_minimum_bandwidth_rule(self, rule, policy, body=None): """Updates a minimum bandwidth rule.""" return self.put(self.qos_minimum_bandwidth_rule_path % (policy, rule), body=body) def delete_minimum_bandwidth_rule(self, rule, policy): """Deletes a minimum bandwidth rule.""" return self.delete(self.qos_minimum_bandwidth_rule_path % (policy, rule)) def list_minimum_packet_rate_rules(self, policy_id, retrieve_all=True, **_params): """Fetches a list of all minimum packet rate rules for the given policy """ return self.list('minimum_packet_rate_rules', self.qos_minimum_packet_rate_rules_path % policy_id, retrieve_all, **_params) def show_minimum_packet_rate_rule(self, rule, policy, body=None): """Fetches information of a certain minimum packet rate rule.""" return self.get(self.qos_minimum_packet_rate_rule_path % (policy, rule), body=body) def create_minimum_packet_rate_rule(self, policy, body=None): """Creates a new minimum packet rate rule.""" return self.post(self.qos_minimum_packet_rate_rules_path % policy, body=body) def update_minimum_packet_rate_rule(self, rule, policy, body=None): """Updates a minimum packet rate rule.""" return self.put(self.qos_minimum_packet_rate_rule_path % (policy, rule), body=body) def delete_minimum_packet_rate_rule(self, rule, policy): """Deletes a minimum packet rate rule.""" return self.delete(self.qos_minimum_packet_rate_rule_path % (policy, rule)) def create_flavor(self, body=None): """Creates a new Neutron service flavor.""" return self.post(self.flavors_path, body=body) def delete_flavor(self, flavor): """Deletes the specified Neutron service flavor.""" return self.delete(self.flavor_path % (flavor)) def list_flavors(self, retrieve_all=True, **_params): """Fetches a list of all Neutron service flavors for a project.""" return self.list('flavors', self.flavors_path, retrieve_all, **_params) def show_flavor(self, flavor, **_params): """Fetches information for a certain Neutron service flavor.""" return self.get(self.flavor_path % (flavor), params=_params) def update_flavor(self, flavor, body): """Update a Neutron service flavor.""" return self.put(self.flavor_path % (flavor), body=body) def associate_flavor(self, flavor, body): """Associate a Neutron service flavor with a profile.""" return self.post(self.flavor_profile_bindings_path % (flavor), body=body) def disassociate_flavor(self, flavor, flavor_profile): """Disassociate a Neutron service flavor with a profile.""" return self.delete(self.flavor_profile_binding_path % (flavor, flavor_profile)) def create_service_profile(self, body=None): """Creates a new Neutron service flavor profile.""" return self.post(self.service_profiles_path, body=body) def delete_service_profile(self, flavor_profile): """Deletes the specified Neutron service flavor profile.""" return self.delete(self.service_profile_path % (flavor_profile)) def list_service_profiles(self, retrieve_all=True, **_params): """Fetches a list of all Neutron service flavor profiles.""" return self.list('service_profiles', self.service_profiles_path, retrieve_all, **_params) def show_service_profile(self, flavor_profile, **_params): """Fetches information for a certain Neutron service flavor profile.""" return self.get(self.service_profile_path % (flavor_profile), params=_params) def update_service_profile(self, service_profile, body): """Update a Neutron service profile.""" return self.put(self.service_profile_path % (service_profile), body=body) def list_availability_zones(self, retrieve_all=True, **_params): """Fetches a list of all availability zones.""" return self.list('availability_zones', self.availability_zones_path, retrieve_all, **_params) @debtcollector.renames.renamed_kwarg( 'tenant_id', 'project_id', replace=True) def get_auto_allocated_topology(self, project_id, **_params): """Fetch information about a project's auto-allocated topology.""" return self.get( self.auto_allocated_topology_path % project_id, params=_params) @debtcollector.renames.renamed_kwarg( 'tenant_id', 'project_id', replace=True) def delete_auto_allocated_topology(self, project_id, **_params): """Delete a project's auto-allocated topology.""" return self.delete( self.auto_allocated_topology_path % project_id, params=_params) @debtcollector.renames.renamed_kwarg( 'tenant_id', 'project_id', replace=True) def validate_auto_allocated_topology_requirements(self, project_id): """Validate requirements for getting an auto-allocated topology.""" return self.get_auto_allocated_topology(project_id, fields=['dry-run']) def list_bgp_speakers(self, retrieve_all=True, **_params): """Fetches a list of all BGP speakers for a project.""" return self.list('bgp_speakers', self.bgp_speakers_path, retrieve_all, **_params) def show_bgp_speaker(self, bgp_speaker_id, **_params): """Fetches information of a certain BGP speaker.""" return self.get(self.bgp_speaker_path % (bgp_speaker_id), params=_params) def create_bgp_speaker(self, body=None): """Creates a new BGP speaker.""" return self.post(self.bgp_speakers_path, body=body) def update_bgp_speaker(self, bgp_speaker_id, body=None): """Update a BGP speaker.""" return self.put(self.bgp_speaker_path % bgp_speaker_id, body=body) def delete_bgp_speaker(self, speaker_id): """Deletes the specified BGP speaker.""" return self.delete(self.bgp_speaker_path % (speaker_id)) def add_peer_to_bgp_speaker(self, speaker_id, body=None): """Adds a peer to BGP speaker.""" return self.put((self.bgp_speaker_path % speaker_id) + "/add_bgp_peer", body=body) def remove_peer_from_bgp_speaker(self, speaker_id, body=None): """Removes a peer from BGP speaker.""" return self.put((self.bgp_speaker_path % speaker_id) + "/remove_bgp_peer", body=body) def add_network_to_bgp_speaker(self, speaker_id, body=None): """Adds a network to BGP speaker.""" return self.put((self.bgp_speaker_path % speaker_id) + "/add_gateway_network", body=body) def remove_network_from_bgp_speaker(self, speaker_id, body=None): """Removes a network from BGP speaker.""" return self.put((self.bgp_speaker_path % speaker_id) + "/remove_gateway_network", body=body) def list_route_advertised_from_bgp_speaker(self, speaker_id, **_params): """Fetches a list of all routes advertised by BGP speaker.""" return self.get((self.bgp_speaker_path % speaker_id) + "/get_advertised_routes", params=_params) def list_bgp_peers(self, **_params): """Fetches a list of all BGP peers.""" return self.get(self.bgp_peers_path, params=_params) def show_bgp_peer(self, peer_id, **_params): """Fetches information of a certain BGP peer.""" return self.get(self.bgp_peer_path % peer_id, params=_params) def create_bgp_peer(self, body=None): """Create a new BGP peer.""" return self.post(self.bgp_peers_path, body=body) def update_bgp_peer(self, bgp_peer_id, body=None): """Update a BGP peer.""" return self.put(self.bgp_peer_path % bgp_peer_id, body=body) def delete_bgp_peer(self, peer_id): """Deletes the specified BGP peer.""" return self.delete(self.bgp_peer_path % peer_id) def list_network_ip_availabilities(self, retrieve_all=True, **_params): """Fetches IP availability information for all networks""" return self.list('network_ip_availabilities', self.network_ip_availabilities_path, retrieve_all, **_params) def show_network_ip_availability(self, network, **_params): """Fetches IP availability information for a specified network""" return self.get(self.network_ip_availability_path % (network), params=_params) def add_tag(self, resource_type, resource_id, tag, **_params): """Add a tag on the resource.""" return self.put(self.tag_path % (resource_type, resource_id, tag)) def replace_tag(self, resource_type, resource_id, body, **_params): """Replace tags on the resource.""" return self.put(self.tags_path % (resource_type, resource_id), body) def remove_tag(self, resource_type, resource_id, tag, **_params): """Remove a tag on the resource.""" return self.delete(self.tag_path % (resource_type, resource_id, tag)) def remove_tag_all(self, resource_type, resource_id, **_params): """Remove all tags on the resource.""" return self.delete(self.tags_path % (resource_type, resource_id)) def create_trunk(self, body=None): """Create a trunk port.""" return self.post(self.trunks_path, body=body) def update_trunk(self, trunk, body=None, revision_number=None): """Update a trunk port.""" return self._update_resource(self.trunk_path % trunk, body=body, revision_number=revision_number) def delete_trunk(self, trunk): """Delete a trunk port.""" return self.delete(self.trunk_path % (trunk)) def list_trunks(self, retrieve_all=True, **_params): """Fetch a list of all trunk ports.""" return self.list('trunks', self.trunks_path, retrieve_all, **_params) def show_trunk(self, trunk, **_params): """Fetch information for a certain trunk port.""" return self.get(self.trunk_path % (trunk), params=_params) def trunk_add_subports(self, trunk, body=None): """Add specified subports to the trunk.""" return self.put(self.subports_add_path % (trunk), body=body) def trunk_remove_subports(self, trunk, body=None): """Removes specified subports from the trunk.""" return self.put(self.subports_remove_path % (trunk), body=body) def trunk_get_subports(self, trunk, **_params): """Fetch a list of all subports attached to given trunk.""" return self.get(self.subports_path % (trunk), params=_params) def list_bgpvpns(self, retrieve_all=True, **_params): """Fetches a list of all BGP VPNs for a project""" return self.list('bgpvpns', self.bgpvpns_path, retrieve_all, **_params) def show_bgpvpn(self, bgpvpn, **_params): """Fetches information of a certain BGP VPN""" return self.get(self.bgpvpn_path % bgpvpn, params=_params) def create_bgpvpn(self, body=None): """Creates a new BGP VPN""" return self.post(self.bgpvpns_path, body=body) def update_bgpvpn(self, bgpvpn, body=None): """Updates a BGP VPN""" return self.put(self.bgpvpn_path % bgpvpn, body=body) def delete_bgpvpn(self, bgpvpn): """Deletes the specified BGP VPN""" return self.delete(self.bgpvpn_path % bgpvpn) def list_bgpvpn_network_assocs(self, bgpvpn, retrieve_all=True, **_params): """Fetches a list of network associations for a given BGP VPN.""" return self.list('network_associations', self.bgpvpn_network_associations_path % bgpvpn, retrieve_all, **_params) def show_bgpvpn_network_assoc(self, bgpvpn, net_assoc, **_params): """Fetches information of a certain BGP VPN's network association""" return self.get( self.bgpvpn_network_association_path % (bgpvpn, net_assoc), params=_params) def create_bgpvpn_network_assoc(self, bgpvpn, body=None): """Creates a new BGP VPN network association""" return self.post(self.bgpvpn_network_associations_path % bgpvpn, body=body) def update_bgpvpn_network_assoc(self, bgpvpn, net_assoc, body=None): """Updates a BGP VPN network association""" return self.put( self.bgpvpn_network_association_path % (bgpvpn, net_assoc), body=body) def delete_bgpvpn_network_assoc(self, bgpvpn, net_assoc): """Deletes the specified BGP VPN network association""" return self.delete( self.bgpvpn_network_association_path % (bgpvpn, net_assoc)) def list_bgpvpn_router_assocs(self, bgpvpn, retrieve_all=True, **_params): """Fetches a list of router associations for a given BGP VPN.""" return self.list('router_associations', self.bgpvpn_router_associations_path % bgpvpn, retrieve_all, **_params) def show_bgpvpn_router_assoc(self, bgpvpn, router_assoc, **_params): """Fetches information of a certain BGP VPN's router association""" return self.get( self.bgpvpn_router_association_path % (bgpvpn, router_assoc), params=_params) def create_bgpvpn_router_assoc(self, bgpvpn, body=None): """Creates a new BGP VPN router association""" return self.post(self.bgpvpn_router_associations_path % bgpvpn, body=body) def update_bgpvpn_router_assoc(self, bgpvpn, router_assoc, body=None): """Updates a BGP VPN router association""" return self.put( self.bgpvpn_router_association_path % (bgpvpn, router_assoc), body=body) def delete_bgpvpn_router_assoc(self, bgpvpn, router_assoc): """Deletes the specified BGP VPN router association""" return self.delete( self.bgpvpn_router_association_path % (bgpvpn, router_assoc)) def list_bgpvpn_port_assocs(self, bgpvpn, retrieve_all=True, **_params): """Fetches a list of port associations for a given BGP VPN.""" return self.list('port_associations', self.bgpvpn_port_associations_path % bgpvpn, retrieve_all, **_params) def show_bgpvpn_port_assoc(self, bgpvpn, port_assoc, **_params): """Fetches information of a certain BGP VPN's port association""" return self.get( self.bgpvpn_port_association_path % (bgpvpn, port_assoc), params=_params) def create_bgpvpn_port_assoc(self, bgpvpn, body=None): """Creates a new BGP VPN port association""" return self.post(self.bgpvpn_port_associations_path % bgpvpn, body=body) def update_bgpvpn_port_assoc(self, bgpvpn, port_assoc, body=None): """Updates a BGP VPN port association""" return self.put( self.bgpvpn_port_association_path % (bgpvpn, port_assoc), body=body) def delete_bgpvpn_port_assoc(self, bgpvpn, port_assoc): """Deletes the specified BGP VPN port association""" return self.delete( self.bgpvpn_port_association_path % (bgpvpn, port_assoc)) def create_sfc_port_pair(self, body=None): """Creates a new Port Pair.""" return self.post(self.sfc_port_pairs_path, body=body) def update_sfc_port_pair(self, port_pair, body=None): """Update a Port Pair.""" return self.put(self.sfc_port_pair_path % port_pair, body=body) def delete_sfc_port_pair(self, port_pair): """Deletes the specified Port Pair.""" return self.delete(self.sfc_port_pair_path % (port_pair)) def list_sfc_port_pairs(self, retrieve_all=True, **_params): """Fetches a list of all Port Pairs.""" return self.list('port_pairs', self.sfc_port_pairs_path, retrieve_all, **_params) def show_sfc_port_pair(self, port_pair, **_params): """Fetches information of a certain Port Pair.""" return self.get(self.sfc_port_pair_path % (port_pair), params=_params) def create_sfc_port_pair_group(self, body=None): """Creates a new Port Pair Group.""" return self.post(self.sfc_port_pair_groups_path, body=body) def update_sfc_port_pair_group(self, port_pair_group, body=None): """Update a Port Pair Group.""" return self.put(self.sfc_port_pair_group_path % port_pair_group, body=body) def delete_sfc_port_pair_group(self, port_pair_group): """Deletes the specified Port Pair Group.""" return self.delete(self.sfc_port_pair_group_path % (port_pair_group)) def list_sfc_port_pair_groups(self, retrieve_all=True, **_params): """Fetches a list of all Port Pair Groups.""" return self.list('port_pair_groups', self.sfc_port_pair_groups_path, retrieve_all, **_params) def show_sfc_port_pair_group(self, port_pair_group, **_params): """Fetches information of a certain Port Pair Group.""" return self.get(self.sfc_port_pair_group_path % (port_pair_group), params=_params) def create_sfc_port_chain(self, body=None): """Creates a new Port Chain.""" return self.post(self.sfc_port_chains_path, body=body) def update_sfc_port_chain(self, port_chain, body=None): """Update a Port Chain.""" return self.put(self.sfc_port_chain_path % port_chain, body=body) def delete_sfc_port_chain(self, port_chain): """Deletes the specified Port Chain.""" return self.delete(self.sfc_port_chain_path % (port_chain)) def list_sfc_port_chains(self, retrieve_all=True, **_params): """Fetches a list of all Port Chains.""" return self.list('port_chains', self.sfc_port_chains_path, retrieve_all, **_params) def show_sfc_port_chain(self, port_chain, **_params): """Fetches information of a certain Port Chain.""" return self.get(self.sfc_port_chain_path % (port_chain), params=_params) def create_sfc_flow_classifier(self, body=None): """Creates a new Flow Classifier.""" return self.post(self.sfc_flow_classifiers_path, body=body) def update_sfc_flow_classifier(self, flow_classifier, body=None): """Update a Flow Classifier.""" return self.put(self.sfc_flow_classifier_path % flow_classifier, body=body) def delete_sfc_flow_classifier(self, flow_classifier): """Deletes the specified Flow Classifier.""" return self.delete(self.sfc_flow_classifier_path % (flow_classifier)) def list_sfc_flow_classifiers(self, retrieve_all=True, **_params): """Fetches a list of all Flow Classifiers.""" return self.list('flow_classifiers', self.sfc_flow_classifiers_path, retrieve_all, **_params) def show_sfc_flow_classifier(self, flow_classifier, **_params): """Fetches information of a certain Flow Classifier.""" return self.get(self.sfc_flow_classifier_path % (flow_classifier), params=_params) def create_sfc_service_graph(self, body=None): """Create the specified Service Graph.""" return self.post(self.sfc_service_graphs_path, body=body) def update_sfc_service_graph(self, service_graph, body=None): """Update a Service Graph.""" return self.put(self.sfc_service_graph_path % service_graph, body=body) def delete_sfc_service_graph(self, service_graph): """Deletes the specified Service Graph.""" return self.delete(self.sfc_service_graph_path % service_graph) def list_sfc_service_graphs(self, retrieve_all=True, **_params): """Fetches a list of all Service Graphs.""" return self.list('service_graphs', self.sfc_service_graphs_path, retrieve_all, **_params) def show_sfc_service_graph(self, service_graph, **_params): """Fetches information of a certain Service Graph.""" return self.get(self.sfc_service_graph_path % service_graph, params=_params) def create_network_log(self, body=None): """Create a network log.""" return self.post(self.network_logs_path, body=body) def delete_network_log(self, net_log): """Delete a network log.""" return self.delete(self.network_log_path % net_log) def list_network_logs(self, retrieve_all=True, **_params): """Fetch a list of all network logs.""" return self.list( 'logs', self.network_logs_path, retrieve_all, **_params) def show_network_log(self, net_log, **_params): """Fetch information for a certain network log.""" return self.get(self.network_log_path % net_log, params=_params) def update_network_log(self, net_log, body=None): """Update a network log.""" return self.put(self.network_log_path % net_log, body=body) def list_network_loggable_resources(self, retrieve_all=True, **_params): """Fetch a list of supported resource types for network log.""" return self.list('loggable_resources', self.network_loggables_path, retrieve_all, **_params) def onboard_network_subnets(self, subnetpool, body=None): """Onboard the specified network's subnets into a subnet pool.""" return self.put(self.onboard_network_subnets_path % (subnetpool), body=body) def __init__(self, **kwargs): """Initialize a new client for the Neutron v2.0 API.""" super(Client, self).__init__(**kwargs) self._register_extensions(self.version) def _update_resource(self, path, **kwargs): revision_number = kwargs.pop('revision_number', None) if revision_number: headers = kwargs.setdefault('headers', {}) headers['If-Match'] = 'revision_number=%s' % revision_number return self.put(path, **kwargs) def extend_show(self, resource_singular, path, parent_resource): def _fx(obj, **_params): return self.show_ext(path, obj, **_params) def _parent_fx(obj, parent_id, **_params): return self.show_ext(path % parent_id, obj, **_params) fn = _fx if not parent_resource else _parent_fx setattr(self, "show_%s" % resource_singular, fn) def extend_list(self, resource_plural, path, parent_resource): def _fx(retrieve_all=True, **_params): return self.list_ext(resource_plural, path, retrieve_all, **_params) def _parent_fx(parent_id, retrieve_all=True, **_params): return self.list_ext(resource_plural, path % parent_id, retrieve_all, **_params) fn = _fx if not parent_resource else _parent_fx setattr(self, "list_%s" % resource_plural, fn) def extend_create(self, resource_singular, path, parent_resource): def _fx(body=None): return self.create_ext(path, body) def _parent_fx(parent_id, body=None): return self.create_ext(path % parent_id, body) fn = _fx if not parent_resource else _parent_fx setattr(self, "create_%s" % resource_singular, fn) def extend_delete(self, resource_singular, path, parent_resource): def _fx(obj): return self.delete_ext(path, obj) def _parent_fx(obj, parent_id): return self.delete_ext(path % parent_id, obj) fn = _fx if not parent_resource else _parent_fx setattr(self, "delete_%s" % resource_singular, fn) def extend_update(self, resource_singular, path, parent_resource): def _fx(obj, body=None): return self.update_ext(path, obj, body) def _parent_fx(obj, parent_id, body=None): return self.update_ext(path % parent_id, obj, body) fn = _fx if not parent_resource else _parent_fx setattr(self, "update_%s" % resource_singular, fn) def _extend_client_with_module(self, module, version): classes = inspect.getmembers(module, inspect.isclass) for cls_name, cls in classes: if hasattr(cls, 'versions'): if version not in cls.versions: continue parent_resource = getattr(cls, 'parent_resource', None) if issubclass(cls, client_extension.ClientExtensionList): self.extend_list(cls.resource_plural, cls.object_path, parent_resource) elif issubclass(cls, client_extension.ClientExtensionCreate): self.extend_create(cls.resource, cls.object_path, parent_resource) elif issubclass(cls, client_extension.ClientExtensionUpdate): self.extend_update(cls.resource, cls.resource_path, parent_resource) elif issubclass(cls, client_extension.ClientExtensionDelete): self.extend_delete(cls.resource, cls.resource_path, parent_resource) elif issubclass(cls, client_extension.ClientExtensionShow): self.extend_show(cls.resource, cls.resource_path, parent_resource) elif issubclass(cls, client_extension.NeutronClientExtension): setattr(self, "%s_path" % cls.resource_plural, cls.object_path) setattr(self, "%s_path" % cls.resource, cls.resource_path) self.EXTED_PLURALS.update({cls.resource_plural: cls.resource}) def _register_extensions(self, version): for name, module in itertools.chain( client_extension._discover_via_entry_points()): self._extend_client_with_module(module, version)
apache-2.0
Webnology-/cookbook2013VeryLast
www/js/javascript.js
18944
 var currPageIndex = 0; app.initialize(); $(document).ready(function () { //$('.appV').html('v1.17'); //onDocumentReady(); setMenu(); toggleMenu(); }); function onDocumentReady() { SetPagesList(); setBackground(); runPinchzoom(); turnPages(currPageIndex); setPep(); //changeSize(); setZIndex(); setTimeout("setImgList();", 500); } function setImgList() { var imgList = [ 'images/smallTop.png', 'images/middle.png', 'images/smallBottom.png', 'images/largeTop.png', 'images/largeBottom.png', 'images/menu_cats.png', 'images/menu_recipes.png' ]; var imgListLength = imgList.length; for (var i = 0; i < recipesList.length; i++) { imgList[i + 8] = "images/RecipesImages/" + recipesList[i].image; } preload(imgList); } function preload(arrayOfImages) { for (var i = 0; i < arrayOfImages.length; i++) { setTimeout("$('<img />').attr('src', '"+arrayOfImages[i]+"').appendTo('body').css('display', 'none');", 200); } //$(arrayOfImages).each(function () { //}); } function setPep() { $('.ingredientsDiv, .directionsDiv, .text').pep({ useCSSTranslation: false, constrainTo: 'parent', place: false }); } function setBackground() { var picturesArray = new Array(); for (var i = 0; i < categoriesList.length; i++) { picturesArray[i] = categoriesList[i].background; } $('BODY').bgStretcher({ images: picturesArray, imageWidth: 2000, imageHeight: 1200, slideShowSpeed: 1500, anchoring: 'center top', anchoringImg: 'center top', slideShow: false, transitionEffect: 'simpleSlide', slideDirection: 'W', sequenceMode: 'normal', buttonNext: '.next', buttonPrev: '.back', }); } function chkIfIE9() { if (isIE9()) { $('.ingredientsDiv, .directionsDiv, .imgDiv').addClass('hide'); } else { setTimeout(" $('.ingredientsDiv, .directionsDiv, .imgDiv').removeClass('hide');", 1000); } } function isIE9() { var myNav = navigator.userAgent.toLowerCase(); //alert(myNav); return (myNav.indexOf('msie 9') != -1); } function setZIndex() { $('.ingredientsDiv, .directionsDiv, .imgDiv').click(function () { $('.ingredientsDiv, .directionsDiv, .imgDiv').removeClass('zIndex2'); $(this).addClass('zIndex2'); }); } var isChangingSize = false; function changeSize() { $('.ingredientsDiv, .directionsDiv').click(function () { if (!isChangingSize) { if ($(this).hasClass('bigSize')) { $(this).removeClass('bigSize'); isChangingSize = true; } else { $(this).addClass('bigSize'); isChangingSize = true; } setTimeout("isChangingSize = false;", 200); } }); } function runPinchzoom() { if (!Hammer.HAS_TOUCHEVENTS && !Hammer.HAS_POINTEREVENTS) { Hammer.plugins.fakeMultitouch(); } var pinchzoom = $('.pinchzoom').each(function () { var hammertime = Hammer($(this).get(0), { transform_always_block: true, transform_min_scale: 1, drag_block_horizontal: true, drag_block_vertical: true, drag_min_distance: 0 }); var rect = $(this).find('.rect').get(0); var posX = 0, posY = 0, scale = 1, last_scale, rotation = 1, last_rotation; hammertime.on('touch drag transform', function (ev) { switch (ev.type) { case 'touch': last_scale = scale; last_rotation = rotation; break; case 'drag': posX = ev.gesture.deltaX; posY = ev.gesture.deltaY; break; case 'transform': rotation = last_rotation + ev.gesture.rotation; scale = Math.max(1, Math.min(last_scale * ev.gesture.scale, 2)); break; } if (rotation == 1) rotation = 0; // transform! var transform = //"translate3d(" + posX + "px," + posY + "px, 0) " + "scale3d(" + scale + "," + scale + ", 1) " + "rotate(" + rotation + "deg) "; rect.style.transform = transform; rect.style.oTransform = transform; rect.style.msTransform = transform; rect.style.mozTransform = transform; rect.style.webkitTransform = transform; rect.style.msTransform = transform; }); }); } // Category class: function category(id, name, background, header_bg) { this.id = id; this.name = name; this.background = background; this.header_bg = header_bg; this.type = 'category'; } // Recipe class: function recipe(cat_id, name, header_bg, description1, description2, image, pdf) { this.cat_id = cat_id; this.name = name; this.header_bg = header_bg; this.description1 = description1; this.description2 = description2; this.image = image; this.pdf = pdf; this.type = 'recipe'; } var categoriesList = new Array(); categoriesList[0] = new category(0, "Main", 'images/bg_main.jpg', ''); categoriesList[1] = new category(1, "Intro", 'images/bg_intro.jpg', ''); categoriesList[2] = new category(10, "Alex & Cathy's Recipes", 'images/bg_owners.jpg', ''); categoriesList[3] = new category(2, "Appetizers", 'images/bg_appetizers.jpg', 'images/cat_appetizers.png'); categoriesList[4] = new category(3, "Main dishes", 'images/bg_main_dishes.jpg', 'images/cat_mainDishes.png'); categoriesList[5] = new category(4, "Desserts", 'images/bg_desserts.jpg', 'images/cat_desserts.png'); categoriesList[6] = new category(5, "Breakfast", 'images/bg_breakfast.jpg', 'images/cat_breakfast.png'); categoriesList[7] = new category(6, "Drinks", 'images/bg_drinks.jpg', 'images/cat_drinks.png'); categoriesList[8] = new category(7, "Sides", 'images/bg_sides.jpg', 'images/cat_sides.png'); categoriesList[9] = new category(8, "Thank You", 'images/bg_thank_you.jpg', ''); //categoriesList[8] = new category(8, "SoupAndBeans", 'images/bg_soup_and_beans.jpg', 'images/cat_soupsAndBeans.png'); var recipesList = new Array(); var pagesList = new Array(); function SetPagesList() { var catID; var index = 0; for (var i = 0; i < categoriesList.length; i++) { catID = categoriesList[i].id; if (catID != 10) { pagesList[index] = categoriesList[i]; index++; } for (var j = 0; j < recipesList.length; j++) { if (recipesList[j].cat_id == catID) { pagesList[index] = recipesList[j]; index++; } } } } var isPageInMove = false; function turnPages(moveToIndex) { if (!isPageInMove && moveToIndex < pagesList.length) { isPageInMove = true; $('.bigSize').removeClass('bigSize'); $('BODY').bgStretcher.pause(); moveToPage = pagesList[moveToIndex]; //alert(moveToPage.name); if (findCurrBackgroundIndex(pagesList[currPageIndex]) != findCurrBackgroundIndex(pagesList[moveToIndex])) { //if (moveToIndex != 0) { var slideNumber = findCurrBackgroundIndex(pagesList[moveToIndex]); $('BODY').bgStretcher.slideShow(null, slideNumber); //if (currPageIndex < moveToIndex) { // $('.next').click(); //} //else { // $('.back').click(); //} //} } if (moveToPage.type == 'category') { //hide the elements - FOR IE9: chkIfIE9(); //////////////////////////// hideElelnent(); if (pagesList[moveToIndex].header_bg == "") { $('.categoryHeaderDiv').hide(0) } else { //$('.headerDiv').hide(); $('.categoryHeaderDiv').fadeIn() $('.categoryHeaderDiv img').attr({ 'src': pagesList[moveToIndex].header_bg, 'alt': pagesList[moveToIndex].name }); $('.categoryHeaderDiv').removeClass('categoryHeaderDivOut'); } $('#container').show(1000); } else { //show the elements - FOR IE9: setTimeout(" $('.ingredientsDiv, .directionsDiv, .imgDiv').removeClass('hide');", 1000); //////////////////////////// hideElelnent(); $('#container').fadeOut(); setTimeout(function () { setCurrRecipe(pagesList[moveToIndex]); $('.ingredientsDiv, .directionsDiv').each(function () { //alert($(this).css('transition-property')); $(this).removeClass('textOut'); $(this).css('transition-duration', Math.random() / 2 + .5 + 's'); $('.imgDiv').hide(); $('.imgDiv img').load(function () { $('.imgDiv').show(); setTimeout("$('.imgDiv').removeClass('imgOut');", 10); }); $('.imgDiv').css('transition-duration', Math.random() / 2 + .5 + 's'); $('.headerDiv').removeClass('headerOut headerScale'); $('.headerDiv').show(); $('.headerDiv').css('transition-duration', Math.random() / 2 + .5 + 's'); }); }, 1000); } currPageIndex = moveToIndex; setTimeout("isPageInMove = false;", 1000); if (moveToIndex == 0) $('.arrowBack').fadeOut(1000); else if ($('.arrowBack').css('display') == 'none') $('.arrowBack').fadeIn(1000); if (moveToIndex == pagesList.length - 1) $('.arrowNext').fadeOut(1000); else if ($('.arrowNext').css('display') == 'none') $('.arrowNext').fadeIn(1000); } } function findCurrBackgroundIndex(currPage) { var backgroungIndex = 0; if (currPage.type == 'category') { for (var i = 0; i < categoriesList.length; i++) { if (categoriesList[i].id == currPage.id) { backgroungIndex = i; } } } else { for (var i = 0; i < categoriesList.length; i++) { if (categoriesList[i].id == currPage.cat_id) { backgroungIndex = i; } } } return backgroungIndex; } function hideElelnent() { $('.ingredientsDiv, .directionsDiv').each(function () { $(this).addClass('textOut'); $(this).css('transition-duration', Math.random() / 2 + .5 + 's'); }); $('.imgDiv').addClass('imgOut'); $('.imgDiv').css('transition-duration', Math.random() / 2 + .5 + 's'); $('.headerDiv').addClass('headerOut'); $('.categoryHeaderDiv').addClass('categoryHeaderDivOut'); setTimeout(function () { $('.headerDiv').addClass('headerScale'); }, 300); $('.headerDiv').css('transition-duration', Math.random() / 2 + .2 + 's'); } function setCurrRecipe(currRecipe) { $('.ingredientsDiv, .directionsDiv, .imgDiv').css('transition-property', 'none'); $('.headerDiv img').attr({ 'src': currRecipe.header_bg, 'alt': currRecipe.name }); $('.ingredientsDiv_middle p').html(currRecipe.description1); $('.directionsDiv_middle p').html(currRecipe.description2); // $('.printer').attr('href', '/pdf/' + currRecipe.pdf); //$('.printer').attr('href', '#'); $('.printer').unbind('click'); $('.printer').click(function () { //alert('aa'); //window.open(currRecipe.pdf, '_system', 'location=yes'); //window.open('http://docs.google.com/viewer?url=' + currRecipe.pdf, '_blank', 'location=no'); //alert('bb'); //alert(currRecipe.pdf); //window.plugins.childBrowser.showWebPage(currRecipe.pdf, { showLocationBar: false }); window.open(encodeURI(currRecipe.pdf), '_system', 'location=no'); }); if (currRecipe.image == null || currRecipe.image == "") { $('.imgDiv').hide(0); } else { $('.imgDiv img').attr({ 'src': 'images/RecipesImages/' + currRecipe.image, 'alt': currRecipe.name }); $('.imgDiv').show(0); } //$('.ingredientsDiv').css("height", ""); //$('.directionsDiv').css("height", ""); $('.ingredientsDiv, .directionsDiv, .imgDiv').each(function () { $(this).css("width", ""); $(this).css("height", ""); $(this).find('div').each(function () { $(this).css("width", "") $(this).css("height", "") }); //alert(fontSize * currScale); //$('.ingredientsDiv_middle p, .directionsDiv_middle p').css('font-size', fontSize * currScale + 'px'); }); //alert($('.ingredientsDiv').height()); setElementSize(1); $('.ingredientsDiv, .directionsDiv, .imgDiv').css('transition-property', 'all'); } function setElementSize(currScale) { var ingredientsDivTop = 220 * (1 - ((1 - currScale) / 2)); $('.ingredientsDiv').css({ 'top': ingredientsDivTop + 'px', 'left': '80px' }); //$('.ingredientsDiv_middle').height($('.ingredientsDiv_middle p').outerHeight(true)); //$('.directionsDiv_middle').height($('.directionsDiv_middle p').outerHeight(true)); $('.directionsDiv').css({ 'top': ((ingredientsDivTop + $('.ingredientsDiv').height()) + 50) * currScale + 'px', 'left': '80px' }); $('.imgDiv').css({ 'top': (ingredientsDivTop + 50) * currScale + 'px', 'left': '600px' }); //alert($('.ingredientsDiv_middle p').outerHeight(true)); //alert($('.ingredientsDiv_middle').height()); //setTimeout("setElementSizeInner(" + currScale + ");", 1200); setElementSizeInner(currScale); //alert($('directionsDiv').height()); } function setElementSizeInner(currScale) { var ingredientsDivTop = 220 * (1 - ((1 - currScale) / 2)); var fontSize = 15; var directionsDivButtom = ingredientsDivTop + ($('.ingredientsDiv').height() + 50 + $('.directionsDiv').height()) * currScale; //alert($(window).height() + " " + directionsDivButtom + " " + $('.directionsDiv').height()); var callAgain = false; if (($(window).height() * 0.90) < directionsDivButtom) { currScale *= 0.9; callAgain = true; setElementSizeInner(currScale); } //} else { //$('.ingredientsDiv_middle').height($('.ingredientsDiv_middle p').outerHeight(true)); //$('.directionsDiv_middle').height($('.directionsDiv_middle p').outerHeight(true)); //alert(ingredientsDivTop + " " + ($('.ingredientsDiv').height()) * currScale + " " + $('.directionsDiv').css('top')); //$('.ingredientsDiv, .directionsDiv').css('transition-property', 'transform'); $('.imgDiv').width(500 * currScale); $('.imgFrame').css('background-size', $('.imgDiv').width() + 'px ' + $('.imgDiv').height() + 'px'); $('.ingredientsDiv, .directionsDiv').each(function () { var halfTheScale = 1 - ((1 - currScale) / 2); $(this).width($(this).width() * halfTheScale); $(this).height($(this).height() * currScale); $(this).find('div').each(function () { $(this).width($(this).width() * halfTheScale); //$(this).height($(this).height() * currScale); //alert($(this).width() + " " + $(this).height()); $(this).css('background-size', $(this).width() + 'px ' + $(this).height() + 'px'); }); //$('.imgDiv img').width($(this).width()); $('.ingredientsDiv_middle p, .directionsDiv_middle p').css('font-size', fontSize * currScale + 'px'); }); var originalMarginLeft = 80; var totalMarginLeft; if (600 + $('.imgDiv').width() < $(window).width()) { totalMarginLeft = ($(window).width() - (600 + $('.imgDiv').width())) / 2 + 20; } else { totalMarginLeft = 20; } var imgLeftPosition = (-totalMarginLeft * 2 + $(window).width() - $('.imgDiv').width()); $('.ingredientsDiv').css({ 'top': ingredientsDivTop + 'px', 'left': totalMarginLeft + 'px' }); $('.directionsDiv').css({ 'top': ingredientsDivTop + $('.ingredientsDiv').height() + 70 + 'px', 'left': totalMarginLeft + 'px' }); $('.imgDiv').css({ 'left': totalMarginLeft + imgLeftPosition + 'px' }); //if (callAgain) // setElementSizeInner(currScale); } } function setMenu() { for (var i = 0; i < categoriesList.length; i++) { $('<li><a href="#"><span></span></a></li>').appendTo('.menu_cats'); for (var j = 0; j < recipesList.length; j++) { if (recipesList[j].cat_id == categoriesList[i].id) { $('<li><a href="#"><span></span></a></li>').appendTo('.menu_recipe'); } } } $('.menu_cats > li').each(function () { if (categoriesList[$(this).index()].id != 1) { $(this).find('span').text((categoriesList[$(this).index()].name).toUpperCase()); } if ($(this).find('span').html() == "") { $(this).hide(); } }); $('.menu_cats > li > a').click(function () { var catID; $('.menu_recipe li').remove(); for (var i = 0; i < categoriesList.length; i++) { //alert($(this).find('span').html() +' '+ categoriesList[i].name.toUpperCase()); if ($(this).find('span').html().replace("&amp;", "&") == categoriesList[i].name.toUpperCase()) { catID = categoriesList[i].id; if (catID == 0 || catID == 8) { $('.menu_recipe').slideUp(); } else { $('.menu_recipe').slideDown(); } } } if (catID == 0) { turnPages(0); hideMenu(); } else if (catID == 8) { turnPages(51); hideMenu(); } else { var currCatRecipesList = new Array; var index = 0; for (var j = 0; j < pagesList.length; j++) { if (pagesList[j].type == 'recipe' && pagesList[j].cat_id == catID) { $('<li onclick="turnPages(' + j + ');"><span onclick="hideMenu();">' + pagesList[j].name + '</span></li>').appendTo('.menu_recipe'); currCatRecipesList[index] = pagesList[j]; index++; } } } }); } function toggleMenu() { $('.btnMenu').click(function () { $('.menu_cats').slideToggle(); $('.menu_recipe').slideUp(); }); } function hideMenu() { $('.menu_cats, .menu_recipe').slideUp(); }
apache-2.0
citrix/terraform-provider-netscaler
vendor/github.com/citrix/adc-nitro-go/resource/config/vpn/vpnglobal_authenticationsamlpolicy_binding.go
2162
/* * Copyright (c) 2021 Citrix Systems, 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 vpn /** * Binding class showing the authenticationsamlpolicy that can be bound to vpnglobal. */ type Vpnglobalauthenticationsamlpolicybinding struct { /** * The name of the policy. */ Policyname string `json:"policyname,omitempty"` /** * Integer specifying the policy's priority. The lower the priority number, the higher the policy's priority. Maximum value for default syntax policies is 2147483647 and for classic policies is 64000. */ Priority int `json:"priority,omitempty"` /** * Bind the authentication policy as the secondary policy to use in a two-factor configuration. A user must then authenticate not only to a primary authentication server but also to a secondary authentication server. User groups are aggregated across both authentication servers. The user name must be exactly the same on both authentication servers, but the authentication servers can require different passwords. */ Secondary bool `json:"secondary,omitempty"` /** * Bind the Authentication policy to a tertiary chain which will be used only for group extraction. The user will not authenticate against this server, and this will only be called it primary and/or secondary authentication has succeeded. */ Groupextraction bool `json:"groupextraction,omitempty"` /** * Applicable only to advance vpn session policy. An expression or other value specifying the priority of the next policy which will get evaluated if the current policy rule evaluates to TRUE. */ Gotopriorityexpression string `json:"gotopriorityexpression,omitempty"` }
apache-2.0
i25ffz/spollo
src/com/spollo/player/menu/DeleteDialog.java
4090
/* * Copyright (C) 2012 Andrew Neal 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 com.spollo.player.menu; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.os.Bundle; import android.support.v4.app.DialogFragment; import com.spollo.player.R; import com.spollo.player.Config; import com.spollo.player.cache.ImageFetcher; import com.spollo.player.utils.ApolloUtils; import com.spollo.player.utils.MusicUtils; /** * Alert dialog used to delete tracks. * <p> * TODO: Remove albums from the recents list upon deletion. * * @author Andrew Neal ([email protected]) */ public class DeleteDialog extends DialogFragment { public interface DeleteDialogCallback { public void onDelete(long[] id); } /** * The item(s) to delete */ private long[] mItemList; /** * The image cache */ private ImageFetcher mFetcher; /** * Empty constructor as per the {@link Fragment} documentation */ public DeleteDialog() { } /** * @param title The title of the artist, album, or song to delete * @param items The item(s) to delete * @param key The key used to remove items from the cache. * @return A new instance of the dialog */ public static DeleteDialog newInstance(final String title, final long[] items, final String key) { final DeleteDialog frag = new DeleteDialog(); final Bundle args = new Bundle(); args.putString(Config.NAME, title); args.putLongArray("items", items); args.putString("cachekey", key); frag.setArguments(args); return frag; } /** * {@inheritDoc} */ @Override public Dialog onCreateDialog(final Bundle savedInstanceState) { final String delete = getString(R.string.context_menu_delete); final Bundle arguments = getArguments(); // Get the image cache key final String key = arguments.getString("cachekey"); // Get the track(s) to delete mItemList = arguments.getLongArray("items"); // Get the dialog title final String title = arguments.getString(Config.NAME); final String dialogTitle = getString(R.string.delete_dialog_title, title); // Initialize the image cache mFetcher = ApolloUtils.getImageFetcher(getActivity()); // Build the dialog return new AlertDialog.Builder(getActivity()).setTitle(dialogTitle) .setMessage(R.string.cannot_be_undone) .setPositiveButton(delete, new OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int which) { // Remove the items from the image cache mFetcher.removeFromCache(key); // Delete the selected item(s) MusicUtils.deleteTracks(getActivity(), mItemList); if (getActivity() instanceof DeleteDialogCallback) { ((DeleteDialogCallback)getActivity()).onDelete(mItemList); } dialog.dismiss(); } }).setNegativeButton(R.string.cancel, new OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int which) { dialog.dismiss(); } }).create(); } }
apache-2.0
evgeniy-khist/velocity-site
README.md
1778
velocity-site ============= **velocity-site** is simple static site generator in Java and [Velocity](http://velocity.apache.org/engine/releases/velocity-1.7/user-guide.html). To generate static site from Velocity templates and Properties files run: `java -DpagesDir=path/to/pages -DtemplatesDir=path/to/templates -DtargetDir=path/to/target -jar path/to/velocity-site.jar` * `pagesDir` - directory to look for Properties files of page definitions (default `pages`) * `templatesDir` - directory to look for Velocity templates like layouts and page templates (default `templates`) * `targetDir` - directory to output static html pages (default `target`) Each page has set of properties defined in Properties file. Common for multiple pages properties can be defined in `_default.properties`. All properties from `_default.properties` will be inherited by all pages, but can be overrided in page Properties file. There are implicit properties that will be added by default: * `_page` - page name (default *filename without extension* of page Properties file) * `_pageContentFile` - path to file with page content relative to *templates directory* (default `$page['_page'].vm`) * `_targetFile` - path to output file relative to *target directory* (default `$page['_page'].html`) * `_order` - order of page used in sorting (default 0) All these properties can be overrided in page Properties file. `_layout` - path to layout Velocity template relative to *target directory* (mandatory property) All properties added implicitly or explicitly are available in Velocity templates: `$page['propertyName']`. All pages sorted by `_order` property are also available in templates: `$allPages`. ``` <ul> #foreach($somePage in $allPages) <li>$somePage['_page']</li> #end </ul> ```
apache-2.0
jeffrey-io/world-bootstrap
src/test/java/io/jeffrey/world/things/points/TestEditEventedPoint2.java
1345
package io.jeffrey.world.things.points; import org.junit.Test; import io.jeffrey.world.WorldTestFramework; public class TestEditEventedPoint2 extends WorldTestFramework { @Test public void sanityCheckXEditing() { final SelectablePoint2 point = new SelectablePoint2(1, 2); final HasUpdateMock mock = new HasUpdateMock(); final EventedPoint2 evPoint = new EventedPoint2(point, mock); final EditEventedPoint2 edit = new EditEventedPoint2(-1, evPoint, true); assertEquals("-1", edit.name()); assertEquals("1.0", edit.getAsText()); assertFalse(edit.setByText("foo")); assertEquals("1.0", edit.getAsText()); assertTrue(edit.setByText("4")); assertEquals(4.0, point.x); assertEquals("4.0", edit.getAsText()); } @Test public void sanityCheckYEditing() { final SelectablePoint2 point = new SelectablePoint2(1, 2); final HasUpdateMock mock = new HasUpdateMock(); final EventedPoint2 evPoint = new EventedPoint2(point, mock); final EditEventedPoint2 edit = new EditEventedPoint2(-2, evPoint, false); assertEquals("-2", edit.name()); assertEquals("2.0", edit.getAsText()); assertFalse(edit.setByText("foo")); assertEquals("2.0", edit.getAsText()); assertTrue(edit.setByText("7")); assertEquals(7.0, point.y); assertEquals("7.0", edit.getAsText()); } }
apache-2.0
75py/EasyPrefs
easyprefs-processor/src/test/java/com/nagopy/android/easyprefs/processor/EasyPrefProcessorBoolTest.java
1259
package com.nagopy.android.easyprefs.processor; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import javax.tools.JavaFileObject; import static com.google.common.truth.Truth.assert_; import static com.google.testing.compile.JavaSourceSubjectFactory.javaSource; @RunWith(JUnit4.class) public class EasyPrefProcessorBoolTest { final TestHelper testHelper = new TestHelper("BoolPrefSample", "/bool/", "GenBoolPrefSample", "BoolPrefSample_CheckBoxPreference"); @Test public void よくある形() throws Throwable { testHelper.testProvider("リソース指定あり"); testHelper.testProvider("リソース指定なし"); testHelper.testPreference("リソース指定あり"); testHelper.testPreference("リソース指定なし"); } @Test public void コンパイル時チェック_タイトル未指定() throws Throwable { JavaFileObject src = testHelper.getJavaFileObject("タイトルなし.txt"); assert_().about(javaSource()) .that(src) .processedWith(new EasyPrefProcessor()) .failsToCompile() .withErrorContaining("title or titleStr is required."); } }
apache-2.0
nghiant2710/base-images
balena-base-images/node/genericx86-64-ext/ubuntu/disco/10.23.1/build/Dockerfile
2771
# AUTOGENERATED FILE FROM balenalib/genericx86-64-ext-ubuntu:disco-build ENV NODE_VERSION 10.23.1 ENV YARN_VERSION 1.22.4 RUN for key in \ 6A010C5166006599AA17F08146C2130DFD2497F5 \ ; do \ gpg --keyserver pgp.mit.edu --recv-keys "$key" || \ gpg --keyserver keyserver.pgp.com --recv-keys "$key" || \ gpg --keyserver ha.pool.sks-keyservers.net --recv-keys "$key" ; \ done \ && curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-x64.tar.gz" \ && echo "2a5f9d862468a4c677630923531e52339526cfd075cc6df30da4636782eb7bda node-v$NODE_VERSION-linux-x64.tar.gz" | sha256sum -c - \ && tar -xzf "node-v$NODE_VERSION-linux-x64.tar.gz" -C /usr/local --strip-components=1 \ && rm "node-v$NODE_VERSION-linux-x64.tar.gz" \ && curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \ && curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \ && gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \ && mkdir -p /opt/yarn \ && tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \ && ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \ && ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \ && rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \ && npm config set unsafe-perm true -g --unsafe-perm \ && rm -rf /tmp/* CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/[email protected]" \ && echo "Running test-stack@node" \ && chmod +x [email protected] \ && bash [email protected] \ && rm -rf [email protected] RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: Intel 64-bit (x86-64) \nOS: Ubuntu disco \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v10.23.1, Yarn v1.22.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
apache-2.0
nghiant2710/base-images
balena-base-images/node/orange-pi-lite/ubuntu/eoan/12.20.1/build/Dockerfile
2763
# AUTOGENERATED FILE FROM balenalib/orange-pi-lite-ubuntu:eoan-build ENV NODE_VERSION 12.20.1 ENV YARN_VERSION 1.22.4 RUN for key in \ 6A010C5166006599AA17F08146C2130DFD2497F5 \ ; do \ gpg --keyserver pgp.mit.edu --recv-keys "$key" || \ gpg --keyserver keyserver.pgp.com --recv-keys "$key" || \ gpg --keyserver ha.pool.sks-keyservers.net --recv-keys "$key" ; \ done \ && curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-armv7l.tar.gz" \ && echo "7283ced5d7c0cc036a35bc2e64b23e7d4b348848170567880edabcf5279f4f8a node-v$NODE_VERSION-linux-armv7l.tar.gz" | sha256sum -c - \ && tar -xzf "node-v$NODE_VERSION-linux-armv7l.tar.gz" -C /usr/local --strip-components=1 \ && rm "node-v$NODE_VERSION-linux-armv7l.tar.gz" \ && curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \ && curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \ && gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \ && mkdir -p /opt/yarn \ && tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \ && ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \ && ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \ && rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \ && npm config set unsafe-perm true -g --unsafe-perm \ && rm -rf /tmp/* CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/[email protected]" \ && echo "Running test-stack@node" \ && chmod +x [email protected] \ && bash [email protected] \ && rm -rf [email protected] RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Ubuntu eoan \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v12.20.1, Yarn v1.22.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
apache-2.0
arrowli/RsyncHadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-common/target/org/apache/hadoop/mapreduce/v2/jobhistory/package-summary.html
6238
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.6.0_27) on Mon Dec 16 23:54:41 EST 2013 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>org.apache.hadoop.mapreduce.v2.jobhistory (hadoop-mapreduce-client-common 2.2.0 API)</title> <meta name="date" content="2013-12-16"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="org.apache.hadoop.mapreduce.v2.jobhistory (hadoop-mapreduce-client-common 2.2.0 API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-use.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../org/apache/hadoop/mapreduce/v2/api/records/impl/pb/package-summary.html">PREV PACKAGE</a></li> <li><a href="../../../../../../org/apache/hadoop/mapreduce/v2/proto/package-summary.html">NEXT PACKAGE</a></li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/hadoop/mapreduce/v2/jobhistory/package-summary.html" target="_top">FRAMES</a></li> <li><a href="package-summary.html" target="_top">NO FRAMES</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <p>@InterfaceAudience.Private </p> <h1 title="Package" class="title">Package&nbsp;org.apache.hadoop.mapreduce.v2.jobhistory</h1> </div> <div class="contentContainer"> <ul class="blockList"> <li class="blockList"> <table class="packageSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation"> <caption><span>Class Summary</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Class</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="../../../../../../org/apache/hadoop/mapreduce/v2/jobhistory/FileNameIndexUtils.html" title="class in org.apache.hadoop.mapreduce.v2.jobhistory">FileNameIndexUtils</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../../org/apache/hadoop/mapreduce/v2/jobhistory/JHAdminConfig.html" title="class in org.apache.hadoop.mapreduce.v2.jobhistory">JHAdminConfig</a></td> <td class="colLast"> <div class="block">Stores Job History configuration keys that can be set by administrators of the Job History server.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../../../../org/apache/hadoop/mapreduce/v2/jobhistory/JobHistoryUtils.html" title="class in org.apache.hadoop.mapreduce.v2.jobhistory">JobHistoryUtils</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../../org/apache/hadoop/mapreduce/v2/jobhistory/JobIndexInfo.html" title="class in org.apache.hadoop.mapreduce.v2.jobhistory">JobIndexInfo</a></td> <td class="colLast"> <div class="block">Maintains information which may be used by the jobHistroy indexing system.</div> </td> </tr> </tbody> </table> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-use.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../org/apache/hadoop/mapreduce/v2/api/records/impl/pb/package-summary.html">PREV PACKAGE</a></li> <li><a href="../../../../../../org/apache/hadoop/mapreduce/v2/proto/package-summary.html">NEXT PACKAGE</a></li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/hadoop/mapreduce/v2/jobhistory/package-summary.html" target="_top">FRAMES</a></li> <li><a href="package-summary.html" target="_top">NO FRAMES</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2013 <a href="http://www.apache.org">Apache Software Foundation</a>. All Rights Reserved.</small></p> </body> </html>
apache-2.0
introproventures/graphql-jpa-query
graphql-jpa-query-schema/src/test/java/com/introproventures/graphql/jpa/query/converter/model/AbstractVariableEntity.java
4011
package com.introproventures.graphql.jpa.query.converter.model; import java.util.Date; import java.util.Objects; import javax.persistence.Column; import javax.persistence.Convert; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.MappedSuperclass; import org.springframework.format.annotation.DateTimeFormat; @MappedSuperclass public abstract class AbstractVariableEntity extends ActivitiEntityMetadata { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String type; private String name; @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) private Date createTime; @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) private Date lastUpdatedTime; private String executionId; @Convert(converter = VariableValueJsonConverter.class) @Column(columnDefinition="text") private VariableValue<?> value; private Boolean markedAsDeleted = false; private String processInstanceId; public AbstractVariableEntity() { } public AbstractVariableEntity(Long id, String type, String name, String processInstanceId, String serviceName, String serviceFullName, String serviceVersion, String appName, String appVersion, Date createTime, Date lastUpdatedTime, String executionId) { super(serviceName, serviceFullName, serviceVersion, appName, appVersion); this.id = id; this.type = type; this.name = name; this.processInstanceId = processInstanceId; this.createTime = createTime; this.lastUpdatedTime = lastUpdatedTime; this.executionId = executionId; } public Long getId() { return id; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getLastUpdatedTime() { return lastUpdatedTime; } public void setLastUpdatedTime(Date lastUpdatedTime) { this.lastUpdatedTime = lastUpdatedTime; } public String getExecutionId() { return executionId; } public void setExecutionId(String executionId) { this.executionId = executionId; } public <T> void setValue(T value) { this.value = new VariableValue<>(value); } public <T> T getValue() { return (T) value.getValue(); } public Boolean getMarkedAsDeleted() { return markedAsDeleted; } public void setMarkedAsDeleted(Boolean markedAsDeleted) { this.markedAsDeleted = markedAsDeleted; } public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + Objects.hash(id); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; AbstractVariableEntity other = (AbstractVariableEntity) obj; return Objects.equals(id, other.id); } }
apache-2.0
deepgram/kur
tests/examples/modkurfile.py
1380
""" Copyright 2017 Deepgram 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. """ def modify_kurfile(data): for k in ('train', 'validate', 'test', 'evaluate'): if k not in data: continue if 'weights' in data[k]: del data[k]['weights'] if 'provider' not in data[k]: data[k]['provider'] = {} data[k]['provider']['num_batches'] = 1 data[k]['provider']['batch_size'] = 2 if 'train' in data: if 'checkpoint' in data['train']: del data['train']['checkpoint'] if 'stop_when' not in data['train']: data['train']['stop_when'] = {} data['train']['stop_when']['epochs'] = 2 if 'epochs' in data['train']: del data['train']['epochs'] if 'log' in data['train']: del data['train']['log'] if 'evaluate' in data: if 'destination' in data['evaluate']: del data['evaluate']['destination'] ### EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF
apache-2.0
willmclaren/ensembl-variation
modules/Bio/EnsEMBL/Variation/Pipeline/FinishTranscriptEffect.pm
3049
=head1 LICENSE Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute Copyright [2016-2017] EMBL-European Bioinformatics Institute 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. =cut =head1 CONTACT Please email comments or questions to the public Ensembl developers list at <http://lists.ensembl.org/mailman/listinfo/dev>. Questions may also be sent to the Ensembl help desk at <http://www.ensembl.org/Help/Contact>. =cut package Bio::EnsEMBL::Variation::Pipeline::FinishTranscriptEffect; use strict; use warnings; use ImportUtils qw(load); use Sys::Hostname; use FileHandle; use File::Path qw(rmtree); use base qw(Bio::EnsEMBL::Variation::Pipeline::BaseVariationProcess); my $DEBUG = 0; sub run { my $self = shift; $self->rejoin_table_files(); my $dbc = $self->get_species_adaptor('variation')->dbc; my $dir = $self->required_param('pipeline_dir'); $ImportUtils::TMP_DIR = $dir; my $host = hostname; # do unique sort on command line, it's faster than relying on MySQL's unique index foreach my $file(grep {-e "$dir/$_"} qw(variation_hgvs.txt variation_genename.txt)) { system("gzip -c $dir/$file > $dir/$file\_bak.gz"); system( sprintf( 'cat %s/%s | sort -T %s -u > %s/%s.unique', $dir, $file, $dir, $dir, $file, ) ) and die("ERROR: Failed to unique sort $file"); unlink("$dir/$file\.gz") if -e "$dir/$file\.gz"; system("gzip $dir/$file");# unlink("$dir/$file"); } if(-e $dir.'/variation_hgvs.txt.unique') { $ImportUtils::TMP_FILE = 'variation_hgvs.txt.unique'; load($dbc, qw(variation_hgvs variation_id hgvs_name)); } if(-e $dir.'/variation_genename.txt.unique') { $ImportUtils::TMP_FILE = 'variation_genename.txt.unique'; load($dbc, qw(variation_genename variation_id gene_name)); } return; } sub rejoin_table_files { my $self = shift; my $dir = $self->required_param('pipeline_dir'); my $gene_fh = FileHandle->new(); $gene_fh->open(">".$dir."/variation_genename.txt") or die $!; my $hgvs_fh = FileHandle->new(); $hgvs_fh->open(">".$dir."/variation_hgvs.txt") or die $!; opendir DIR, $dir."/table_files"; foreach my $hex_stub(grep {!/^\./} readdir DIR) { opendir HEX, "$dir/table_files/$hex_stub"; foreach my $file(grep {!/^\./} readdir HEX) { my $fh = $file =~ /hgvs/ ? $hgvs_fh : $gene_fh; open IN, "$dir/table_files/$hex_stub/$file" or die $!; while(<IN>) { print $fh $_; } close IN; } } rmtree($dir."/table_files"); } 1;
apache-2.0
Kodestruct/Kodestruct.Dynamo
Kodestruct.Dynamo.UI/Nodes/Loads/ASCE7/Lateral/Wind/WindFace.cs
4968
#region Copyright /*Copyright (C) 2015 Konstantin Udilovich 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. */ #endregion using System; using System.Collections.Generic; using System.Windows.Controls; using Dynamo.Controls; using Dynamo.Models; using Dynamo.Wpf; using ProtoCore.AST.AssociativeAST; using Kodestruct.Common.CalculationLogger; using Kodestruct.Dynamo.Common; using Dynamo.Nodes; using Dynamo.Graph.Nodes; using System.Xml; using Dynamo.Graph; namespace Kodestruct.Loads.ASCE7.Lateral.Wind.PressureCoefficient { /// <summary> ///Selection of the type of face relative to wind direction (windward, leeward or side) /// </summary> [NodeName("Wind face")] [NodeCategory("Kodestruct.Loads.ASCE7.Lateral.Wind.PressureCoefficient")] [NodeDescription("Selection of the type of face relative to wind direction (windward, leeward or side) ")] [IsDesignScriptCompatible] public class WindFaceSelection : UiNodeBase { public WindFaceSelection() { //OutPortData.Add(new PortData("ReportEntry", "Calculation log entries (for reporting)")); OutPortData.Add(new PortData("WindFaceType", "Type of face relative to wind direction (windward, leeward or side) ")); RegisterAllPorts(); SetDefaultParameters(); //PropertyChanged += NodePropertyChanged; } private void SetDefaultParameters() { //ReportEntry=""; WindFaceType = "Windward"; } /// <summary> /// Gets the type of this class, to be used in base class for reflection /// </summary> protected override Type GetModelType() { return GetType(); } #region Properties #region InputProperties #endregion #region OutputProperties #region WindFaceTypeProperty /// <summary> /// WindFaceType property /// </summary> /// <value>Type of face relative to wind direction (windward, leeward or side) </value> public string _WindFaceType; public string WindFaceType { get { return _WindFaceType; } set { _WindFaceType = value; RaisePropertyChanged("WindFaceType"); OnNodeModified(); } } #endregion #region ReportEntryProperty ///// <summary> ///// log property ///// </summary> ///// <value>Calculation entries that can be converted into a report.</value> //public string reportEntry; //public string ReportEntry //{ // get { return reportEntry; } // set // { // reportEntry = value; // RaisePropertyChanged("ReportEntry"); // OnNodeModified(); // } //} #endregion #endregion #endregion #region Serialization /// <summary> ///Saves property values to be retained when opening the node /// </summary> protected override void SerializeCore(XmlElement nodeElement, SaveContext context) { base.SerializeCore(nodeElement, context); nodeElement.SetAttribute("WindFaceType", WindFaceType); } /// <summary> ///Retrieved property values when opening the node /// </summary> protected override void DeserializeCore(XmlElement nodeElement, SaveContext context) { base.DeserializeCore(nodeElement, context); var attrib = nodeElement.Attributes["WindFaceType"]; if (attrib == null) return; WindFaceType = attrib.Value; //SetComponentDescription(); } #endregion /// <summary> ///Customization of WPF view in Dynamo UI /// </summary> public class WindFaceViewCustomization : UiNodeBaseViewCustomization, INodeViewCustomization<WindFaceSelection> { public void CustomizeView(WindFaceSelection model, NodeView nodeView) { base.CustomizeView(model, nodeView); WindFaceView control = new WindFaceView(); control.DataContext = model; nodeView.inputGrid.Children.Add(control); base.CustomizeView(model, nodeView); } } } }
apache-2.0
jochenw/afw
afw-core/docs/apidocs/com/github/jochenw/afw/core/log/package-use.html
13084
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_192) on Wed Feb 06 20:26:47 CET 2019 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Package com.github.jochenw.afw.core.log (AFW (Core) 1.0 API)</title> <meta name="date" content="2019-02-06"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Package com.github.jochenw.afw.core.log (AFW (Core) 1.0 API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li class="navBarCell1Rev">Use</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?com/github/jochenw/afw/core/log/package-use.html" target="_top">Frames</a></li> <li><a href="package-use.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 title="Uses of Package com.github.jochenw.afw.core.log" class="title">Uses of Package<br>com.github.jochenw.afw.core.log</h1> </div> <div class="contentContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../com/github/jochenw/afw/core/log/package-summary.html">com.github.jochenw.afw.core.log</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#com.github.jochenw.afw.core.log">com.github.jochenw.afw.core.log</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#com.github.jochenw.afw.core.log.log4j">com.github.jochenw.afw.core.log.log4j</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><a href="#com.github.jochenw.afw.core.log.simple">com.github.jochenw.afw.core.log.simple</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#com.github.jochenw.afw.core.log.slf4j">com.github.jochenw.afw.core.log.slf4j</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"><a name="com.github.jochenw.afw.core.log"> <!-- --> </a> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../../../com/github/jochenw/afw/core/log/package-summary.html">com.github.jochenw.afw.core.log</a> used by <a href="../../../../../../com/github/jochenw/afw/core/log/package-summary.html">com.github.jochenw.afw.core.log</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colOne"><a href="../../../../../../com/github/jochenw/afw/core/log/class-use/AbstractLog.html#com.github.jochenw.afw.core.log">AbstractLog</a>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colOne"><a href="../../../../../../com/github/jochenw/afw/core/log/class-use/AbstractLogFactory.html#com.github.jochenw.afw.core.log">AbstractLogFactory</a>&nbsp;</td> </tr> <tr class="altColor"> <td class="colOne"><a href="../../../../../../com/github/jochenw/afw/core/log/class-use/DefaultLogFactory.html#com.github.jochenw.afw.core.log">DefaultLogFactory</a>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colOne"><a href="../../../../../../com/github/jochenw/afw/core/log/class-use/ILog.html#com.github.jochenw.afw.core.log">ILog</a>&nbsp;</td> </tr> <tr class="altColor"> <td class="colOne"><a href="../../../../../../com/github/jochenw/afw/core/log/class-use/ILog.Level.html#com.github.jochenw.afw.core.log">ILog.Level</a>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colOne"><a href="../../../../../../com/github/jochenw/afw/core/log/class-use/ILogFactory.html#com.github.jochenw.afw.core.log">ILogFactory</a>&nbsp;</td> </tr> <tr class="altColor"> <td class="colOne"><a href="../../../../../../com/github/jochenw/afw/core/log/class-use/IMLog.html#com.github.jochenw.afw.core.log">IMLog</a>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colOne"><a href="../../../../../../com/github/jochenw/afw/core/log/class-use/LogManager.html#com.github.jochenw.afw.core.log">LogManager</a>&nbsp;</td> </tr> <tr class="altColor"> <td class="colOne"><a href="../../../../../../com/github/jochenw/afw/core/log/class-use/LogManager.Listener.html#com.github.jochenw.afw.core.log">LogManager.Listener</a>&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"><a name="com.github.jochenw.afw.core.log.log4j"> <!-- --> </a> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../../../com/github/jochenw/afw/core/log/package-summary.html">com.github.jochenw.afw.core.log</a> used by <a href="../../../../../../com/github/jochenw/afw/core/log/log4j/package-summary.html">com.github.jochenw.afw.core.log.log4j</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colOne"><a href="../../../../../../com/github/jochenw/afw/core/log/class-use/AbstractLog.html#com.github.jochenw.afw.core.log.log4j">AbstractLog</a>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colOne"><a href="../../../../../../com/github/jochenw/afw/core/log/class-use/AbstractLogFactory.html#com.github.jochenw.afw.core.log.log4j">AbstractLogFactory</a>&nbsp;</td> </tr> <tr class="altColor"> <td class="colOne"><a href="../../../../../../com/github/jochenw/afw/core/log/class-use/ILog.html#com.github.jochenw.afw.core.log.log4j">ILog</a>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colOne"><a href="../../../../../../com/github/jochenw/afw/core/log/class-use/ILog.Level.html#com.github.jochenw.afw.core.log.log4j">ILog.Level</a>&nbsp;</td> </tr> <tr class="altColor"> <td class="colOne"><a href="../../../../../../com/github/jochenw/afw/core/log/class-use/ILogFactory.html#com.github.jochenw.afw.core.log.log4j">ILogFactory</a>&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"><a name="com.github.jochenw.afw.core.log.simple"> <!-- --> </a> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../../../com/github/jochenw/afw/core/log/package-summary.html">com.github.jochenw.afw.core.log</a> used by <a href="../../../../../../com/github/jochenw/afw/core/log/simple/package-summary.html">com.github.jochenw.afw.core.log.simple</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colOne"><a href="../../../../../../com/github/jochenw/afw/core/log/class-use/AbstractLog.html#com.github.jochenw.afw.core.log.simple">AbstractLog</a>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colOne"><a href="../../../../../../com/github/jochenw/afw/core/log/class-use/AbstractLogFactory.html#com.github.jochenw.afw.core.log.simple">AbstractLogFactory</a>&nbsp;</td> </tr> <tr class="altColor"> <td class="colOne"><a href="../../../../../../com/github/jochenw/afw/core/log/class-use/ILog.html#com.github.jochenw.afw.core.log.simple">ILog</a>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colOne"><a href="../../../../../../com/github/jochenw/afw/core/log/class-use/ILog.Level.html#com.github.jochenw.afw.core.log.simple">ILog.Level</a>&nbsp;</td> </tr> <tr class="altColor"> <td class="colOne"><a href="../../../../../../com/github/jochenw/afw/core/log/class-use/ILogFactory.html#com.github.jochenw.afw.core.log.simple">ILogFactory</a>&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"><a name="com.github.jochenw.afw.core.log.slf4j"> <!-- --> </a> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../../../com/github/jochenw/afw/core/log/package-summary.html">com.github.jochenw.afw.core.log</a> used by <a href="../../../../../../com/github/jochenw/afw/core/log/slf4j/package-summary.html">com.github.jochenw.afw.core.log.slf4j</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colOne"><a href="../../../../../../com/github/jochenw/afw/core/log/class-use/AbstractLog.html#com.github.jochenw.afw.core.log.slf4j">AbstractLog</a>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colOne"><a href="../../../../../../com/github/jochenw/afw/core/log/class-use/AbstractLogFactory.html#com.github.jochenw.afw.core.log.slf4j">AbstractLogFactory</a>&nbsp;</td> </tr> <tr class="altColor"> <td class="colOne"><a href="../../../../../../com/github/jochenw/afw/core/log/class-use/ILog.html#com.github.jochenw.afw.core.log.slf4j">ILog</a>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colOne"><a href="../../../../../../com/github/jochenw/afw/core/log/class-use/ILog.Level.html#com.github.jochenw.afw.core.log.slf4j">ILog.Level</a>&nbsp;</td> </tr> <tr class="altColor"> <td class="colOne"><a href="../../../../../../com/github/jochenw/afw/core/log/class-use/ILogFactory.html#com.github.jochenw.afw.core.log.slf4j">ILogFactory</a>&nbsp;</td> </tr> </tbody> </table> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li class="navBarCell1Rev">Use</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?com/github/jochenw/afw/core/log/package-use.html" target="_top">Frames</a></li> <li><a href="package-use.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2019. All rights reserved.</small></p> </body> </html>
apache-2.0
clairton/ember-table-filterable
app/components/table-filterable.js
77
export { default } from 'ember-table-filterable/components/table-filterable';
apache-2.0
Chuy288/simple-xml-signer
src/main/java/org/hitzoft/xml/SignatureMethodAlgorithm.java
945
package org.hitzoft.xml; /** * * @author jesus.espinoza */ public enum SignatureMethodAlgorithm { DSA_SHA1("http://www.w3.org/2000/09/xmldsig#dsa-sha1"), DSA_SHA256("http://www.w3.org/2009/xmldsig11#dsa-sha256"), RSA_SHA1("http://www.w3.org/2000/09/xmldsig#rsa-sha1"), RSA_SHA256("http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"), RSA_SHA512("http://www.w3.org/2001/04/xmldsig-more#rsa-sha512"); // // ECDSA_SHA1("http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha1"), // ECDSA_SHA256("http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256"), // ECDSA_SHA512("http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha512"), // // HMAC_SHA1("http://www.w3.org/2000/09/xmldsig#hmac-sha1"); private final String URI; private SignatureMethodAlgorithm(String URI) { this.URI = URI; } @Override public String toString() { return URI; } }
apache-2.0
gdbots/common-js
src/isValidSlug.js
767
import endsWith from 'lodash/endsWith'; import startsWith from 'lodash/startsWith'; import trim from 'lodash/trim'; const VALID_SLUG_PATTERN = /^([a-z0-9]-?)*[a-z0-9]$/; const VALID_DATED_SLUG_PATTERN = /^([a-z0-9-]|[a-z0-9-][a-z0-9-/]*[a-z0-9-])$/; /** * Returns true if the provided value is a slug. * * @param {string} slug * @param {boolean} [allowSlashes] * * @returns {boolean} */ export default function isValidSlug(slug, allowSlashes = false) { if (!trim(slug)) { return false; } if (startsWith(slug, '-') || startsWith(slug, '/')) { return false; } if (endsWith(slug, '-') || endsWith(slug, '/')) { return false; } const regex = allowSlashes ? VALID_DATED_SLUG_PATTERN : VALID_SLUG_PATTERN; return regex.test(slug); }
apache-2.0
JohnSnowLabs/spark-nlp
docs/_posts/maziyarpanahi/2021-06-04-translate_lv_ru_xx.md
2605
--- layout: model title: Translate Latvian to Russian Pipeline author: John Snow Labs name: translate_lv_ru date: 2021-06-04 tags: [open_source, pipeline, seq2seq, translation, lv, ru, xx, multilingual] task: Translation language: xx edition: Spark NLP 3.1.0 spark_version: 3.0 supported: true article_header: type: cover use_language_switcher: "Python-Scala-Java" --- ## Description Marian is an efficient, free Neural Machine Translation framework written in pure C++ with minimal dependencies. It is mainly being developed by the Microsoft Translator team. Many academic (most notably the University of Edinburgh and in the past the Adam Mickiewicz University in Poznań) and commercial contributors help with its development. It is currently the engine behind the Microsoft Translator Neural Machine Translation services and being deployed by many companies, organizations and research projects (see below for an incomplete list). source languages: lv target languages: ru {:.btn-box} [Live Demo](https://demo.johnsnowlabs.com/public/TRANSLATION_MARIAN/){:.button.button-orange} [Open in Colab](https://colab.research.google.com/github/JohnSnowLabs/spark-nlp-workshop/blob/master/tutorials/streamlit_notebooks/TRANSLATION_MARIAN.ipynb){:.button.button-orange.button-orange-trans.co.button-icon} [Download](https://s3.amazonaws.com/auxdata.johnsnowlabs.com/public/models/translate_lv_ru_xx_3.1.0_2.4_1622841229405.zip){:.button.button-orange.button-orange-trans.arr.button-icon} ## How to use <div class="tabs-box" markdown="1"> {% include programmingLanguageSelectScalaPythonNLU.html %} ```python from sparknlp.pretrained import PretrainedPipeline pipeline = PretrainedPipeline("translate_lv_ru", lang = "xx") pipeline.annotate("Your sentence to translate!") ``` ```scala import com.johnsnowlabs.nlp.pretrained.PretrainedPipeline val pipeline = new PretrainedPipeline("translate_lv_ru", lang = "xx") pipeline.annotate("Your sentence to translate!") ``` {:.nlu-block} ```python import nlu text = ["text to translate"] translate_df = nlu.load('xx.Latvian.translate_to.Russian').predict(text, output_level='sentence') translate_df ``` </div> {:.model-param} ## Model Information {:.table-model} |---|---| |Model Name:|translate_lv_ru| |Type:|pipeline| |Compatibility:|Spark NLP 3.1.0+| |License:|Open Source| |Edition:|Official| |Language:|xx| ## Data Source [https://huggingface.co/Helsinki-NLP/opus-mt-lv-ru](https://huggingface.co/Helsinki-NLP/opus-mt-lv-ru) ## Included Models - DocumentAssembler - SentenceDetectorDLModel - MarianTransformer
apache-2.0
areitz/pants
tests/python/pants_test/backend/python/tasks/checkstyle/test_noqa.py
3397
# coding=utf-8 # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import textwrap import pytest from pants.backend.python.tasks.checkstyle.checker import PythonCheckStyleTask, PythonFile from pants.backend.python.tasks.checkstyle.common import CheckstylePlugin from pants.subsystem.subsystem import Subsystem from pants_test.backend.python.tasks.python_task_test_base import PythonTaskTestBase class RageSubsystem(Subsystem): options_scope = 'pycheck-pep8' @classmethod def register_options(cls, register): super(PEP8Subsystem, cls).register_options(register) register('--skip', default=False, action='store_true', help='If enabled, skip this style checker.') class Rage(CheckstylePlugin): """Dummy Checkstyle plugin that hates everything""" subsystem = RageSubsystem def __init__(self, python_file): self.python_file = python_file def nits(self): """Return Nits for everything you see""" for line_no, _ in self.python_file.enumerate(): yield self.error('T999', 'I hate everything!', line_no) @pytest.fixture() def no_qa_line(request): """Py Test fixture to create a testing file for single line filters""" request.cls.no_qa_line = PythonFile.from_statement(textwrap.dedent(""" print('This is not fine') print('This is fine') # noqa """)) @pytest.fixture() def no_qa_file(request): """Py Test fixture to create a testing file for whole file filters""" request.cls.no_qa_file = PythonFile.from_statement(textwrap.dedent(""" # checkstyle: noqa print('This is not fine') print('This is fine') """)) @pytest.mark.usefixtures('no_qa_file', 'no_qa_line') class TestPyStyleTask(PythonTaskTestBase): @classmethod def task_type(cls): """Required method""" return PythonCheckStyleTask def _create_context(self, target_roots=None): return self.context( options={ 'py.check': { 'interpreter': 'python' # Interpreter required by PythonTaskTestBase } }, target_roots=target_roots) def setUp(self): """Setup PythonCheckStyleTask with Rage Checker""" super(TestPyStyleTask, self).setUp() PythonCheckStyleTask.options_scope = 'py.check' self.style_check = PythonCheckStyleTask(self._create_context(), ".") self.style_check._plugins = [{'name': 'Troll', 'checker': Rage}] self.style_check.options.suppress = None def test_noqa_line_filter_length(self): """Verify the number of lines filtered is what we expect""" nits = list(self.style_check.get_nits(self.no_qa_line)) assert len(nits) == 1, ('Actually got nits: {}'.format( ' '.join('{}:{}'.format(nit._line_number, nit) for nit in nits) )) def test_noqa_line_filter_code(self): """Verify that the line we see has the correct code""" nits = list(self.style_check.get_nits(self.no_qa_line)) assert nits[0].code == 'T999', 'Not handling the code correctly' def test_noqa_file_filter(self): """Verify Whole file filters are applied correctly""" nits = list(self.style_check.get_nits(self.no_qa_file)) assert len(nits) == 0, 'Expected zero nits since entire file should be ignored'
apache-2.0
TheTemportalist/MorphAdditions
src/main/scala/com/temportalist/morphadditions/common/network/PacketKeyPressed.scala
854
package com.temportalist.morphadditions.common.network import com.temportalist.morphadditions.api.AbilityAction import com.temportalist.morphadditions.common.MAOptions import com.temportalist.morphadditions.common.init.Abilities import com.temportalist.origin.foundation.common.network.IPacket import cpw.mods.fml.relauncher.Side import morph.api.Api import net.minecraft.entity.EntityLivingBase import net.minecraft.entity.player.EntityPlayer /** * * * @author TheTemportalist */ class PacketKeyPressed() extends IPacket { override def handle(player: EntityPlayer, side: Side): Unit = { Api.getMorphEntity(player.getCommandSenderName, side.isClient) match { case entity: EntityLivingBase => Abilities.getAbility(entity) match { case ability: AbilityAction => MAOptions.getMP(player).trigger(entity, ability) } } } }
apache-2.0
Anteoy/gtools
test/base/note/reflect/type/base-recombination/main.go
611
package main import ( "fmt" "reflect" ) var ( Int reflect.Type = reflect.TypeOf(0) String reflect.Type = reflect.TypeOf("") ) // 可从基本类型获取所对应复合类型。 func main() { var c reflect.Type c = reflect.ChanOf(reflect.SendDir, String) fmt.Println(c) m := reflect.MapOf(String, Int) fmt.Println(m) s := reflect.SliceOf(Int) fmt.Println(s) t := struct{ Name string }{} p := reflect.PtrTo(reflect.TypeOf(t)) fmt.Println(p) //与之对应,⽅法 Elem 可返回复合类型的基类型。 var t1 reflect.Type t1 = reflect.TypeOf(make(chan int)).Elem() fmt.Println(t1) }
apache-2.0
bytePassion/OpenQuoridorFramework
OpenQuoridorFramework/OQF.CommonUiElements/Info/Pages/PageViewModels/TournamentInfoPage/TournamentInfoPageViewModelSampleData.cs
366
using System.ComponentModel; #pragma warning disable 0067 namespace OQF.CommonUiElements.Info.Pages.PageViewModels.TournamentInfoPage { internal class TournamentInfoPageViewModelSampleData : ITournamentInfoPageViewModel { public event PropertyChangedEventHandler PropertyChanged; public void Dispose() { } public string DisplayName => "Turnier"; } }
apache-2.0
oharasteve/eagle
src/com/eagle/programmar/Java/Terminals/Java_Punctuation.java
495
// Copyright Eagle Legacy Modernization, 2010-date // Original author: Steven A. O'Hara, Dec 17, 2010 package com.eagle.programmar.Java.Terminals; import com.eagle.tokens.TerminalPunctuationToken; public class Java_Punctuation extends TerminalPunctuationToken { // Need default constructor for reading from the XML file public Java_Punctuation() { this('\0'); } public Java_Punctuation(char punct) { super(punct); } public Java_Punctuation(String punct) { super(punct); } }
apache-2.0
cmmdy/cmmdyweather
app/src/main/java/com/example/cmmdyweather/gson/Basic.java
402
package com.example.cmmdyweather.gson; import com.google.gson.annotations.SerializedName; /** * Created by 夏夜晚凤 on 2017/2/14. */ public class Basic { @SerializedName("city") public String cityName; @SerializedName("id") public String weatherId; public Update update; public class Update{ @SerializedName("loc") public String updateTime; } }
apache-2.0
wealdtech/wealdtech-android
wealdtech-tiles/src/main/java/com/wealdtech/android/providers/ProviderState.java
915
/* * Copyright 2012 - 2014 Weald Technology Trading Limited * * 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 com.wealdtech.android.providers; /** */ public enum ProviderState { /** * The provider is not providing data */ NOT_PROVIDING, /** * The provider wants to provide data but is not configured */ AWAITING_CONFIGURATION, /** * The provider is providing data */ PROVIDING }
apache-2.0
w9jds/azure-activedirectory-library-for-android
src/src/com/microsoft/aad/adal/AuthenticationCancelError.java
1266
// Copyright © Microsoft Open Technologies, Inc. // // All Rights Reserved // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION // ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A // PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache License, Version 2.0 for the specific language // governing permissions and limitations under the License. package com.microsoft.aad.adal; /** * Cancellation error. */ public class AuthenticationCancelError extends AuthenticationException { static final long serialVersionUID = 1; /** * Constructs a new AuthenticationCancelError. */ public AuthenticationCancelError() { super(); } /** * Constructs a new AuthenticationCancelError with message. * * @param msg Message for cancel request */ public AuthenticationCancelError(String msg) { super(ADALError.AUTH_FAILED_CANCELLED, msg); } }
apache-2.0
Sigma-One/DestinationSol
engine/src/main/java/org/destinationsol/game/input/BigObjAvoider.java
2268
/* * Copyright 2017 MovingBlocks * * 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.destinationsol.game.input; import com.badlogic.gdx.math.Vector2; import org.destinationsol.Const; import org.destinationsol.common.SolMath; import org.destinationsol.game.SolGame; import org.destinationsol.game.planet.Planet; public class BigObjAvoider { public static final float MAX_DIST_LEN = 2 * (Const.MAX_GROUND_HEIGHT + Const.ATM_HEIGHT); private Vector2 myProj; public BigObjAvoider() { myProj = new Vector2(); } public float avoid(SolGame game, Vector2 from, Vector2 dest, float toDestAngle) { float toDestLen = from.dst(dest); if (toDestLen > MAX_DIST_LEN) { toDestLen = MAX_DIST_LEN; } float res = toDestAngle; Planet p = game.getPlanetMan().getNearestPlanet(from); Vector2 pPos = p.getPos(); float pRad = p.getFullHeight(); if (dest.dst(pPos) < pRad) { pRad = p.getGroundHeight(); } myProj.set(pPos); myProj.sub(from); SolMath.rotate(myProj, -toDestAngle); if (0 < myProj.x && myProj.x < toDestLen) { if (SolMath.abs(myProj.y) < pRad) { toDestLen = myProj.x; res = toDestAngle + 45 * SolMath.toInt(myProj.y < 0); } } Vector2 sunPos = p.getSys().getPos(); float sunRad = Const.SUN_RADIUS; myProj.set(sunPos); myProj.sub(from); SolMath.rotate(myProj, -toDestAngle); if (0 < myProj.x && myProj.x < toDestLen) { if (SolMath.abs(myProj.y) < sunRad) { res = toDestAngle + 45 * SolMath.toInt(myProj.y < 0); } } return res; } }
apache-2.0
woshihuo12/evilbonefun
egameserver/src/main/java/com/hsj/egameserver/server/Crypt.java
931
package com.hsj.egameserver.server; public class Crypt { private static Crypt _instance = null; private synchronized static void createInstance() { if (_instance == null) { _instance = new Crypt(); } } public static Crypt getInstance() { if (_instance == null) { createInstance(); } return _instance; } public Crypt() { } public char[] C2Sdecrypt(byte encdata[]) { char decdata[] = new char[encdata.length]; for (int i = 0; i < encdata.length; i++) { decdata[i] = (char) ((char) (encdata[i] - 15) % 256); } return decdata; } public byte[] S2Cencrypt(char decdata[]) { byte encdata[] = new byte[decdata.length]; for (int i = 0; i < decdata.length; i++) { encdata[i] = (byte) ((decdata[i] ^ 0xc3) + 0x0f); } return encdata; } }
apache-2.0
izumin5210/Bletia
bletia-core/src/main/java/info/izumin/android/bletia/core/action/AbstractDisconnectAction.java
1026
package info.izumin.android.bletia.core.action; import info.izumin.android.bletia.core.BleState; import info.izumin.android.bletia.core.BletiaException; import info.izumin.android.bletia.core.ResolveStrategy; import info.izumin.android.bletia.core.StateContainer; import info.izumin.android.bletia.core.wrapper.BluetoothGattWrapper; /** * Created by izumin on 11/14/15. */ public abstract class AbstractDisconnectAction<R> extends AbstractAction<Void, BletiaException, Void, R> { public static final String TAG = AbstractDisconnectAction.class.getSimpleName(); private final StateContainer mContainer; public AbstractDisconnectAction(ResolveStrategy<Void, BletiaException, R> resolveStrategy, StateContainer container) { super(null, Type.DISCONNECT, resolveStrategy); mContainer = container; } @Override public boolean execute(BluetoothGattWrapper gattWrapper) { mContainer.setState(BleState.DISCONNECTING); gattWrapper.disconnect(); return true; } }
apache-2.0
weiwenqiang/GitHub
Dialog/PopupWindow/RelativePopupWindow-master/relativepopupwindow/src/main/java/com/labo/kaji/relativepopupwindow/RelativePopupWindow.java
6819
package com.labo.kaji.relativepopupwindow; import android.annotation.TargetApi; import android.content.Context; import android.os.Build; import android.support.annotation.IntDef; import android.support.annotation.NonNull; import android.support.v4.widget.PopupWindowCompat; import android.util.AttributeSet; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.PopupWindow; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * @author kakajika * @since 2016/07/01 */ public class RelativePopupWindow extends PopupWindow { @IntDef({ VerticalPosition.CENTER, VerticalPosition.ABOVE, VerticalPosition.BELOW, VerticalPosition.ALIGN_TOP, VerticalPosition.ALIGN_BOTTOM, }) @Retention(RetentionPolicy.SOURCE) public @interface VerticalPosition { int CENTER = 0; int ABOVE = 1; int BELOW = 2; int ALIGN_TOP = 3; int ALIGN_BOTTOM = 4; } @IntDef({ HorizontalPosition.CENTER, HorizontalPosition.LEFT, HorizontalPosition.RIGHT, HorizontalPosition.ALIGN_LEFT, HorizontalPosition.ALIGN_RIGHT, }) @Retention(RetentionPolicy.SOURCE) public @interface HorizontalPosition { int CENTER = 0; int LEFT = 1; int RIGHT = 2; int ALIGN_LEFT = 3; int ALIGN_RIGHT = 4; } public RelativePopupWindow(Context context) { super(context); } public RelativePopupWindow(Context context, AttributeSet attrs) { super(context, attrs); } public RelativePopupWindow(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @TargetApi(Build.VERSION_CODES.HONEYCOMB) public RelativePopupWindow(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } public RelativePopupWindow() { super(); } public RelativePopupWindow(View contentView) { super(contentView); } public RelativePopupWindow(int width, int height) { super(width, height); } public RelativePopupWindow(View contentView, int width, int height) { super(contentView, width, height); } public RelativePopupWindow(View contentView, int width, int height, boolean focusable) { super(contentView, width, height, focusable); } /** * Show at relative position to anchor View. * @param anchor Anchor View * @param vertPos Vertical Position Flag * @param horizPos Horizontal Position Flag */ public void showOnAnchor(@NonNull View anchor, @VerticalPosition int vertPos, @HorizontalPosition int horizPos) { showOnAnchor(anchor, vertPos, horizPos, 0, 0); } /** * Show at relative position to anchor View. * @param anchor Anchor View * @param vertPos Vertical Position Flag * @param horizPos Horizontal Position Flag * @param fitInScreen Automatically fit in screen or not */ public void showOnAnchor(@NonNull View anchor, @VerticalPosition int vertPos, @HorizontalPosition int horizPos, boolean fitInScreen) { showOnAnchor(anchor, vertPos, horizPos, 0, 0, fitInScreen); } /** * Show at relative position to anchor View with translation. * @param anchor Anchor View * @param vertPos Vertical Position Flag * @param horizPos Horizontal Position Flag * @param x Translation X * @param y Translation Y */ public void showOnAnchor(@NonNull View anchor, @VerticalPosition int vertPos, @HorizontalPosition int horizPos, int x, int y) { showOnAnchor(anchor, vertPos, horizPos, x, y, true); } /** * Show at relative position to anchor View with translation. * @param anchor Anchor View * @param vertPos Vertical Position Flag * @param horizPos Horizontal Position Flag * @param x Translation X * @param y Translation Y * @param fitInScreen Automatically fit in screen or not */ public void showOnAnchor(@NonNull View anchor, @VerticalPosition int vertPos, @HorizontalPosition int horizPos, int x, int y, boolean fitInScreen) { setClippingEnabled(fitInScreen); View contentView = getContentView(); contentView.measure(makeDropDownMeasureSpec(getWidth()), makeDropDownMeasureSpec(getHeight())); final int measuredW = contentView.getMeasuredWidth(); final int measuredH = contentView.getMeasuredHeight(); if (!fitInScreen) { final int[] anchorLocation = new int[2]; anchor.getLocationInWindow(anchorLocation); x += anchorLocation[0]; y += anchorLocation[1] + anchor.getHeight(); } switch (vertPos) { case VerticalPosition.ABOVE: y -= measuredH + anchor.getHeight(); break; case VerticalPosition.ALIGN_BOTTOM: y -= measuredH; break; case VerticalPosition.CENTER: y -= anchor.getHeight()/2 + measuredH/2; break; case VerticalPosition.ALIGN_TOP: y -= anchor.getHeight(); break; case VerticalPosition.BELOW: // Default position. break; } switch (horizPos) { case HorizontalPosition.LEFT: x -= measuredW; break; case HorizontalPosition.ALIGN_RIGHT: x -= measuredW - anchor.getWidth(); break; case HorizontalPosition.CENTER: x += anchor.getWidth()/2 - measuredW/2; break; case HorizontalPosition.ALIGN_LEFT: // Default position. break; case HorizontalPosition.RIGHT: x += anchor.getWidth(); break; } if (fitInScreen) { PopupWindowCompat.showAsDropDown(this, anchor, x, y, Gravity.NO_GRAVITY); } else { showAtLocation(anchor, Gravity.NO_GRAVITY, x, y); } } @SuppressWarnings("ResourceType") private static int makeDropDownMeasureSpec(int measureSpec) { return View.MeasureSpec.makeMeasureSpec(View.MeasureSpec.getSize(measureSpec), getDropDownMeasureSpecMode(measureSpec)); } private static int getDropDownMeasureSpecMode(int measureSpec) { switch (measureSpec) { case ViewGroup.LayoutParams.WRAP_CONTENT: return View.MeasureSpec.UNSPECIFIED; default: return View.MeasureSpec.EXACTLY; } } }
apache-2.0
firebase/firebase-android-sdk
firebase-perf/src/test/java/com/google/firebase/perf/transport/TransportManagerTest.java
60225
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.firebase.perf.transport; import static com.google.common.truth.Truth.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.clearInvocations; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import com.google.android.datatransport.TransportFactory; import com.google.android.gms.tasks.Tasks; import com.google.firebase.FirebaseApp; import com.google.firebase.inject.Provider; import com.google.firebase.installations.FirebaseInstallationsApi; import com.google.firebase.perf.FirebasePerformance; import com.google.firebase.perf.FirebasePerformanceTestBase; import com.google.firebase.perf.application.AppStateMonitor; import com.google.firebase.perf.config.ConfigResolver; import com.google.firebase.perf.session.SessionManager; import com.google.firebase.perf.shadows.ShadowPreconditions; import com.google.firebase.perf.util.Clock; import com.google.firebase.perf.util.Constants; import com.google.firebase.perf.util.Constants.CounterNames; import com.google.firebase.perf.v1.AndroidMemoryReading; import com.google.firebase.perf.v1.ApplicationProcessState; import com.google.firebase.perf.v1.CpuMetricReading; import com.google.firebase.perf.v1.GaugeMetadata; import com.google.firebase.perf.v1.GaugeMetric; import com.google.firebase.perf.v1.NetworkRequestMetric; import com.google.firebase.perf.v1.NetworkRequestMetric.HttpMethod; import com.google.firebase.perf.v1.PerfMetric; import com.google.firebase.perf.v1.PerfSession; import com.google.firebase.perf.v1.TraceMetric; import com.google.testing.timing.FakeScheduledExecutorService; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.ArgumentMatchers; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.verification.VerificationMode; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; /** Unit tests for {@link TransportManager}. */ @Config(shadows = ShadowPreconditions.class) @RunWith(RobolectricTestRunner.class) public class TransportManagerTest extends FirebasePerformanceTestBase { private static final String FAKE_FIREBASE_INSTALLATIONS_ID = "fakeFID"; private TransportManager testTransportManager; private FakeScheduledExecutorService fakeExecutorService; @Mock private FirebaseInstallationsApi mockFirebaseInstallationsApi; @Mock private Provider<TransportFactory> mockFlgTransportFactoryProvider; @Mock private ConfigResolver mockConfigResolver; @Mock private RateLimiter mockRateLimiter; @Mock private AppStateMonitor mockAppStateMonitor; @Mock private FlgTransport mockFlgTransport; @Captor private ArgumentCaptor<PerfMetric> perfMetricArgumentCaptor; @Before public void setUp() { initMocks(this); when(mockConfigResolver.isPerformanceMonitoringEnabled()).thenReturn(true); mockInstallationsGetId(FAKE_FIREBASE_INSTALLATIONS_ID); when(mockRateLimiter.isEventSampled(ArgumentMatchers.any())).thenReturn(true); when(mockRateLimiter.isEventRateLimited(ArgumentMatchers.any())).thenReturn(false); fakeExecutorService = new FakeScheduledExecutorService(); initializeTransport(true); fakeExecutorService.runAll(); } @After public void tearDown() { reset(mockFirebaseInstallationsApi); FirebaseApp.clearInstancesForTest(); } // region Transport Initialization @Test public void validTraceMetric_transportNotInitialized_getLoggedAfterInitialization() { initializeTransport(false); TraceMetric validTrace = createValidTraceMetric(); testTransportManager.log(validTrace, ApplicationProcessState.BACKGROUND); fakeExecutorService.runAll(); assertThat(getLastLoggedEvent(never())).isNull(); assertThat(testTransportManager.getPendingEventsQueue().size()).isEqualTo(1); initializeTransport(true); fakeExecutorService.runAll(); PerfMetric loggedPerfMetric = getLastLoggedEvent(times(1)); assertThat(loggedPerfMetric.getTraceMetric()).isEqualTo(validTrace); validateApplicationInfo(loggedPerfMetric, ApplicationProcessState.BACKGROUND); assertThat(testTransportManager.getPendingEventsQueue().isEmpty()).isTrue(); } @Test public void validNetworkMetric_transportNotInitialized_getLoggedAfterInitialization() { initializeTransport(false); NetworkRequestMetric validNetworkRequest = createValidNetworkRequestMetric(); testTransportManager.log(validNetworkRequest, ApplicationProcessState.BACKGROUND); fakeExecutorService.runAll(); assertThat(getLastLoggedEvent(never())).isNull(); assertThat(testTransportManager.getPendingEventsQueue().size()).isEqualTo(1); initializeTransport(true); fakeExecutorService.runAll(); PerfMetric loggedPerfMetric = getLastLoggedEvent(times(1)); assertThat(loggedPerfMetric.getNetworkRequestMetric()).isEqualTo(validNetworkRequest); validateApplicationInfo(loggedPerfMetric, ApplicationProcessState.BACKGROUND); assertThat(testTransportManager.getPendingEventsQueue().isEmpty()).isTrue(); } @Test public void validGaugeMetric_transportNotInitialized_getLoggedAfterInitialization() { initializeTransport(false); GaugeMetric validGauge = createValidGaugeMetric(); testTransportManager.log(validGauge, ApplicationProcessState.BACKGROUND); fakeExecutorService.runAll(); assertThat(getLastLoggedEvent(never())).isNull(); assertThat(testTransportManager.getPendingEventsQueue().size()).isEqualTo(1); initializeTransport(true); fakeExecutorService.runAll(); PerfMetric loggedPerfMetric = getLastLoggedEvent(times(1)); assertThat(loggedPerfMetric.getGaugeMetric()).isEqualTo(validGauge); validateApplicationInfo(loggedPerfMetric, ApplicationProcessState.BACKGROUND); assertThat(testTransportManager.getPendingEventsQueue().isEmpty()).isTrue(); } @Test public void invalidTraceMetric_transportNotInitialized_notLoggedAfterInitialization() { initializeTransport(false); testTransportManager.log(createInvalidTraceMetric(), ApplicationProcessState.BACKGROUND); fakeExecutorService.runAll(); assertThat(getLastLoggedEvent(never())).isNull(); assertThat(testTransportManager.getPendingEventsQueue().size()).isEqualTo(1); initializeTransport(true); fakeExecutorService.runAll(); assertThat(getLastLoggedEvent(never())).isNull(); assertThat(testTransportManager.getPendingEventsQueue().isEmpty()).isTrue(); } @Test public void invalidNetworkMetric_transportNotInitialized_notLoggedAfterInitialization() { initializeTransport(false); testTransportManager.log( createInvalidNetworkRequestMetric(), ApplicationProcessState.BACKGROUND); fakeExecutorService.runAll(); assertThat(getLastLoggedEvent(never())).isNull(); assertThat(testTransportManager.getPendingEventsQueue().size()).isEqualTo(1); initializeTransport(true); fakeExecutorService.runAll(); assertThat(getLastLoggedEvent(never())).isNull(); assertThat(testTransportManager.getPendingEventsQueue().isEmpty()).isTrue(); } @Test public void invalidGaugeMetric_transportNotInitialized_notLoggedAfterInitialization() { initializeTransport(false); testTransportManager.log(createInValidGaugeMetric(), ApplicationProcessState.BACKGROUND); fakeExecutorService.runAll(); assertThat(getLastLoggedEvent(never())).isNull(); assertThat(testTransportManager.getPendingEventsQueue().size()).isEqualTo(1); initializeTransport(true); fakeExecutorService.runAll(); assertThat(getLastLoggedEvent(never())).isNull(); assertThat(testTransportManager.getPendingEventsQueue().isEmpty()).isTrue(); } @Test public void logMultipleEvents_transportNotInitialized_validEventsGetLoggedInOrderAfterInitialization() { initializeTransport(false); TraceMetric validTrace = createValidTraceMetric(); testTransportManager.log(validTrace, ApplicationProcessState.BACKGROUND); fakeExecutorService.runAll(); assertThat(getLastLoggedEvent(never())).isNull(); TraceMetric invalidTrace = createInvalidTraceMetric(); testTransportManager.log(invalidTrace, ApplicationProcessState.BACKGROUND); fakeExecutorService.runAll(); assertThat(getLastLoggedEvent(never())).isNull(); NetworkRequestMetric validNetworkRequest = createValidNetworkRequestMetric(); testTransportManager.log(validNetworkRequest, ApplicationProcessState.FOREGROUND); fakeExecutorService.runAll(); assertThat(getLastLoggedEvent(never())).isNull(); NetworkRequestMetric invalidNetworkRequest = createInvalidNetworkRequestMetric(); testTransportManager.log(invalidNetworkRequest, ApplicationProcessState.FOREGROUND); fakeExecutorService.runAll(); assertThat(getLastLoggedEvent(never())).isNull(); GaugeMetric validGauge = createValidGaugeMetric(); testTransportManager.log(validGauge); fakeExecutorService.runAll(); assertThat(getLastLoggedEvent(never())).isNull(); GaugeMetric invalidGauge = createInValidGaugeMetric(); testTransportManager.log(invalidGauge); fakeExecutorService.runAll(); assertThat(getLastLoggedEvent(never())).isNull(); assertThat(testTransportManager.getPendingEventsQueue().size()).isEqualTo(6); initializeTransport(true); clearLastLoggedEvents(); fakeExecutorService.runNext(); PerfMetric loggedValidTrace = getLastLoggedEvent(times(1)); assertThat(loggedValidTrace.getTraceMetric()).isEqualTo(validTrace); validateApplicationInfo(loggedValidTrace, ApplicationProcessState.BACKGROUND); clearLastLoggedEvents(); fakeExecutorService.runNext(); PerfMetric loggedInvalidTrace = getLastLoggedEvent(never()); assertThat(loggedInvalidTrace).isNull(); clearLastLoggedEvents(); fakeExecutorService.runNext(); PerfMetric loggedValidNetworkRequest = getLastLoggedEvent(times(1)); assertThat(loggedValidNetworkRequest.getNetworkRequestMetric()).isEqualTo(validNetworkRequest); validateApplicationInfo(loggedValidNetworkRequest, ApplicationProcessState.FOREGROUND); clearLastLoggedEvents(); fakeExecutorService.runNext(); PerfMetric loggedInValidNetworkRequest = getLastLoggedEvent(never()); assertThat(loggedInValidNetworkRequest).isNull(); clearLastLoggedEvents(); fakeExecutorService.runNext(); PerfMetric loggedValidGauge = getLastLoggedEvent(times(1)); assertThat(loggedValidGauge.getGaugeMetric()).isEqualTo(validGauge); validateApplicationInfo( loggedValidGauge, ApplicationProcessState.APPLICATION_PROCESS_STATE_UNKNOWN); clearLastLoggedEvents(); fakeExecutorService.runNext(); PerfMetric loggedInValidGauge = getLastLoggedEvent(never()); assertThat(loggedInValidGauge).isNull(); assertThat(testTransportManager.getPendingEventsQueue().isEmpty()).isTrue(); } @Test public void logMultipleTraces_transportNotInitialized_tracesAfterMaxCapAreNotQueued() { // 1. Transport is not initialized in the beginning initializeTransport(false); // 2. Log multiple Traces such that they are capped int maxTracesCacheSize = 50; // only 50 TraceMetric events are allowed to cache int totalTraceEvents = maxTracesCacheSize + 10; TraceMetric[] validTraces = new TraceMetric[totalTraceEvents]; for (int i = 0; i < totalTraceEvents; i++) { validTraces[i] = createValidTraceMetric().toBuilder().setName("Trace - " + (i + 1)).build(); testTransportManager.log(validTraces[i], ApplicationProcessState.FOREGROUND); fakeExecutorService.runAll(); assertThat(getLastLoggedEvent(never())).isNull(); } // 3. Even though we recorded "totalTraceEvents", events up-to "maxTracesCacheSize" are only // queued assertThat(testTransportManager.getPendingEventsQueue().size()).isEqualTo(maxTracesCacheSize); // 4. Initialize Transport initializeTransport(true); // 5. Consume all queued Traces and validate them for (int i = 0; i < maxTracesCacheSize; i++) { clearLastLoggedEvents(); fakeExecutorService.runNext(); PerfMetric loggedValidTrace = getLastLoggedEvent(times(1)); assertThat(loggedValidTrace.getTraceMetric()).isEqualTo(validTraces[i]); validateApplicationInfo(loggedValidTrace, ApplicationProcessState.FOREGROUND); } // 6. Queue is all consumed after iterating "maxTracesCacheSize" events assertThat(testTransportManager.getPendingEventsQueue().isEmpty()).isTrue(); // 7. No pending events clearLastLoggedEvents(); fakeExecutorService.runAll(); assertThat(getLastLoggedEvent(never())).isNull(); } @Test public void logMultipleNetworkRequests_transportNotInitialized_networkRequestsAfterMaxCapAreNotQueued() { // 1. Transport is not initialized in the beginning initializeTransport(false); // 2. Log multiple Network Requests such that they are capped int maxNetworkRequestsCacheSize = 50; // only 50 NetworkRequestMetric events are allowed to cache int totalNetworkRequestEvents = maxNetworkRequestsCacheSize + 10; NetworkRequestMetric[] validNetworkRequests = new NetworkRequestMetric[totalNetworkRequestEvents]; for (int i = 0; i < totalNetworkRequestEvents; i++) { validNetworkRequests[i] = createValidNetworkRequestMetric().toBuilder().setClientStartTimeUs(i + 1).build(); testTransportManager.log(validNetworkRequests[i], ApplicationProcessState.FOREGROUND); fakeExecutorService.runAll(); assertThat(getLastLoggedEvent(never())).isNull(); } // 3. Even though we recorded "totalNetworkRequestEvents", events up-to // "maxNetworkRequestsCacheSize" are only queued assertThat(testTransportManager.getPendingEventsQueue().size()) .isEqualTo(maxNetworkRequestsCacheSize); // 4. Initialize Transport initializeTransport(true); // 5. Consume all queued Network Requests and validate them for (int i = 0; i < maxNetworkRequestsCacheSize; i++) { clearLastLoggedEvents(); fakeExecutorService.runNext(); PerfMetric loggedValidNetworkRequest = getLastLoggedEvent(times(1)); assertThat(loggedValidNetworkRequest.getNetworkRequestMetric()) .isEqualTo(validNetworkRequests[i]); validateApplicationInfo(loggedValidNetworkRequest, ApplicationProcessState.FOREGROUND); } // 6. Queue is all consumed after iterating "maxNetworkRequestsCacheSize" events assertThat(testTransportManager.getPendingEventsQueue().isEmpty()).isTrue(); // 7. No pending events clearLastLoggedEvents(); fakeExecutorService.runAll(); assertThat(getLastLoggedEvent(never())).isNull(); } @Test public void logMultipleGauges_transportNotInitialized_gaugesAfterMaxCapAreNotQueued() { // 1. Transport is not initialized in the beginning initializeTransport(false); // 2. Log multiple Gauges such that they are capped int maxGaugesCacheSize = 50; // only 50 GaugeMetric events are allowed to cache int totalGaugeEvents = maxGaugesCacheSize + 10; GaugeMetric[] validGauges = new GaugeMetric[totalGaugeEvents]; for (int i = 0; i < totalGaugeEvents; i++) { validGauges[i] = createValidGaugeMetric().toBuilder().setSessionId("Session - " + (i + 1)).build(); testTransportManager.log(validGauges[i], ApplicationProcessState.FOREGROUND); fakeExecutorService.runAll(); assertThat(getLastLoggedEvent(never())).isNull(); } // 3. Even though we recorded "totalGaugeEvents", events up-to "maxGaugesCacheSize" are only // queued assertThat(testTransportManager.getPendingEventsQueue().size()).isEqualTo(maxGaugesCacheSize); // 4. Initialize Transport initializeTransport(true); // 5. Consume all queued Gauges and validate them for (int i = 0; i < maxGaugesCacheSize; i++) { clearLastLoggedEvents(); fakeExecutorService.runNext(); PerfMetric loggedValidGauge = getLastLoggedEvent(times(1)); assertThat(loggedValidGauge.getGaugeMetric()).isEqualTo(validGauges[i]); validateApplicationInfo(loggedValidGauge, ApplicationProcessState.FOREGROUND); } // 6. Queue is all consumed after iterating "maxGaugesCacheSize" events assertThat(testTransportManager.getPendingEventsQueue().isEmpty()).isTrue(); // 7. No pending events clearLastLoggedEvents(); fakeExecutorService.runAll(); assertThat(getLastLoggedEvent(never())).isNull(); } @Test public void logTraces_fewTracesAfterOtherCappedEventsAndTransportNotInitialized_cappedEventsDoesNotCauseOtherEventsToCap() { // 1. Transport is not initialized in the beginning initializeTransport(false); // 2. Log multiple Network Requests (any one of PerfMetric event other than TraceMetric) such // that they are capped int maxNetworkRequestsCacheSize = 50; // only 50 NetworkRequestMetric events are allowed to cache int totalNetworkRequestEvents = maxNetworkRequestsCacheSize + 10; for (int i = 0; i < totalNetworkRequestEvents; i++) { testTransportManager.log( createValidNetworkRequestMetric().toBuilder().setClientStartTimeUs(i + 1).build()); fakeExecutorService.runAll(); assertThat(getLastLoggedEvent(never())).isNull(); } // 3. Even though we recorded "totalNetworkRequestEvents", events up-to // "maxNetworkRequestsCacheSize" are only // queued assertThat(testTransportManager.getPendingEventsQueue().size()) .isEqualTo(maxNetworkRequestsCacheSize); // 4. Log few Traces such that they are under the max cap int totalTraceEvents = 20; // less than max cache for TraceMetric events TraceMetric[] validTraces = new TraceMetric[totalTraceEvents]; for (int i = 0; i < totalTraceEvents; i++) { validTraces[i] = createValidTraceMetric().toBuilder().setName("Trace - " + (i + 1)).build(); testTransportManager.log(validTraces[i], ApplicationProcessState.FOREGROUND); fakeExecutorService.runAll(); assertThat(getLastLoggedEvent(never())).isNull(); } // 5. All Traces are queued even after Network Requests are capped assertThat(testTransportManager.getPendingEventsQueue().size()) .isEqualTo(maxNetworkRequestsCacheSize + totalTraceEvents); // 6. Initialize Transport initializeTransport(true); // 7. Consume all queued Network Requests for (int i = 0; i < maxNetworkRequestsCacheSize; i++) { clearLastLoggedEvents(); fakeExecutorService.runNext(); } // 8. Consume all queued Traces and validate them for (int i = 0; i < totalTraceEvents; i++) { clearLastLoggedEvents(); fakeExecutorService.runNext(); PerfMetric loggedValidTrace = getLastLoggedEvent(times(1)); assertThat(loggedValidTrace.getTraceMetric()).isEqualTo(validTraces[i]); validateApplicationInfo(loggedValidTrace, ApplicationProcessState.FOREGROUND); } // 9. Queue is all consumed assertThat(testTransportManager.getPendingEventsQueue().isEmpty()).isTrue(); // 10. No pending events clearLastLoggedEvents(); fakeExecutorService.runAll(); assertThat(getLastLoggedEvent(never())).isNull(); } @Test public void logNetworkRequests_fewNetworkRequestsAfterOtherCappedEventsAndTransportNotInitialized_cappedEventsDoesNotCauseOtherEventsToCap() { // 1. Transport is not initialized in the beginning initializeTransport(false); // 2. Log multiple Traces (any one of PerfMetric event other than NetworkRequestMetric) such // that they are capped int maxTracesCacheSize = 50; // only 50 TraceMetric events are allowed to cache int totalTraceEvents = maxTracesCacheSize + 10; for (int i = 0; i < totalTraceEvents; i++) { testTransportManager.log( createValidTraceMetric().toBuilder().setName("Trace - " + (i + 1)).build()); fakeExecutorService.runAll(); assertThat(getLastLoggedEvent(never())).isNull(); } // 3. Even though we recorded "totalTraceEvents", events up-to "maxTracesCacheSize" are only // queued assertThat(testTransportManager.getPendingEventsQueue().size()).isEqualTo(maxTracesCacheSize); // 4. Log few Network Requests such that they are under the max cap int totalNetworkRequestEvents = 20; // less than max cache for NetworkRequestMetric events NetworkRequestMetric[] validNetworkRequests = new NetworkRequestMetric[totalNetworkRequestEvents]; for (int i = 0; i < totalNetworkRequestEvents; i++) { validNetworkRequests[i] = createValidNetworkRequestMetric().toBuilder().setClientStartTimeUs(i + 1).build(); testTransportManager.log(validNetworkRequests[i], ApplicationProcessState.FOREGROUND); fakeExecutorService.runAll(); assertThat(getLastLoggedEvent(never())).isNull(); } // 5. All NetworkRequests are queued even after Traces are capped assertThat(testTransportManager.getPendingEventsQueue().size()) .isEqualTo(maxTracesCacheSize + totalNetworkRequestEvents); // 6. Initialize Transport initializeTransport(true); // 7. Consume all queued Traces for (int i = 0; i < maxTracesCacheSize; i++) { clearLastLoggedEvents(); fakeExecutorService.runNext(); } // 8. Consume all queued Network Requests and validate them for (int i = 0; i < totalNetworkRequestEvents; i++) { clearLastLoggedEvents(); fakeExecutorService.runNext(); PerfMetric loggedValidNetworkRequest = getLastLoggedEvent(times(1)); assertThat(loggedValidNetworkRequest.getNetworkRequestMetric()) .isEqualTo(validNetworkRequests[i]); validateApplicationInfo(loggedValidNetworkRequest, ApplicationProcessState.FOREGROUND); } // 9. Queue is all consumed assertThat(testTransportManager.getPendingEventsQueue().isEmpty()).isTrue(); // 10. No pending events clearLastLoggedEvents(); fakeExecutorService.runAll(); assertThat(getLastLoggedEvent(never())).isNull(); } @Test public void logGauges_fewGaugesAfterOtherCappedEventsAndTransportNotInitialized_cappedEventsDoesNotCauseOtherEventsToCap() { // 1. Transport is not initialized in the beginning initializeTransport(false); // 2. Log multiple Traces (any one of PerfMetric event other than GaugeMetric) such that they // are capped int maxTracesCacheSize = 50; // only 50 TraceMetric events are allowed to cache int totalTraceEvents = maxTracesCacheSize + 10; for (int i = 0; i < totalTraceEvents; i++) { testTransportManager.log( createValidTraceMetric().toBuilder().setName("Trace - " + (i + 1)).build()); fakeExecutorService.runAll(); assertThat(getLastLoggedEvent(never())).isNull(); } // 3. Even though we recorded "totalTraceEvents", events up-to "maxTracesCacheSize" are only // queued assertThat(testTransportManager.getPendingEventsQueue().size()).isEqualTo(maxTracesCacheSize); // 4. Log few Gauges such that they are under the max cap int totalGaugeEvents = 20; // less than max cache for GaugeMetric events GaugeMetric[] validGauges = new GaugeMetric[totalGaugeEvents]; for (int i = 0; i < totalGaugeEvents; i++) { validGauges[i] = createValidGaugeMetric().toBuilder().setSessionId("Session - " + (i + 1)).build(); testTransportManager.log(validGauges[i], ApplicationProcessState.FOREGROUND); fakeExecutorService.runAll(); assertThat(getLastLoggedEvent(never())).isNull(); } // 5. All Gauges are queued even after Traces are capped assertThat(testTransportManager.getPendingEventsQueue().size()) .isEqualTo(maxTracesCacheSize + totalGaugeEvents); // 6. Initialize Transport initializeTransport(true); // 7. Consume all queued Traces for (int i = 0; i < maxTracesCacheSize; i++) { clearLastLoggedEvents(); fakeExecutorService.runNext(); } // 8. Consume all queued Gauges and validate them for (int i = 0; i < totalGaugeEvents; i++) { clearLastLoggedEvents(); fakeExecutorService.runNext(); PerfMetric loggedValidGauge = getLastLoggedEvent(times(1)); assertThat(loggedValidGauge.getGaugeMetric()).isEqualTo(validGauges[i]); validateApplicationInfo(loggedValidGauge, ApplicationProcessState.FOREGROUND); } // 9. Queue is all consumed assertThat(testTransportManager.getPendingEventsQueue().isEmpty()).isTrue(); // 10. No pending events clearLastLoggedEvents(); fakeExecutorService.runAll(); assertThat(getLastLoggedEvent(never())).isNull(); } @Test public void logMultipleEvents_exhaustTheEntireCacheWhileTransportNotInitialized_eventsAfterMaxCapAreNotQueued() { // 1. Transport is not initialized in the beginning initializeTransport(false); // 2. Log multiple Traces such that they are capped int maxTracesCacheSize = 50; // only 50 TraceMetric events are allowed to cache int totalTraceEvents = maxTracesCacheSize + 10; for (int i = 0; i < totalTraceEvents; i++) { testTransportManager.log( createValidTraceMetric().toBuilder().setName("Trace - " + (i + 1)).build()); fakeExecutorService.runAll(); assertThat(getLastLoggedEvent(never())).isNull(); } // 3. Log multiple Network Requests such that they are capped int maxNetworkRequestsCacheSize = 50; // only 50 NetworkRequestMetric events are allowed to cache int totalNetworkRequestEvents = maxNetworkRequestsCacheSize + 10; for (int i = 0; i < totalNetworkRequestEvents; i++) { testTransportManager.log( createValidNetworkRequestMetric().toBuilder().setClientStartTimeUs(i + 1).build()); fakeExecutorService.runAll(); assertThat(getLastLoggedEvent(never())).isNull(); } // 4. Log multiple Gauges such that they are capped int maxGaugesCacheSize = 50; // only 50 GaugeMetric events are allowed to cache int totalGaugeEvents = maxGaugesCacheSize + 10; GaugeMetric[] validGauges = new GaugeMetric[totalGaugeEvents]; for (int i = 0; i < totalGaugeEvents; i++) { validGauges[i] = createValidGaugeMetric().toBuilder().setSessionId("Session - " + (i + 1)).build(); testTransportManager.log(validGauges[i], ApplicationProcessState.FOREGROUND); fakeExecutorService.runAll(); assertThat(getLastLoggedEvent(never())).isNull(); } // 5. Even though we recorded "totalTraceEvents" + "totalNetworkRequestEvents" + // "totalGaugeEvents" events up-to "maxTracesCacheSize" + "maxNetworkRequestsCacheSize" + // "maxGaugesCacheSize" are only // queued assertThat(testTransportManager.getPendingEventsQueue().size()) .isEqualTo(maxTracesCacheSize + maxNetworkRequestsCacheSize + maxGaugesCacheSize); // 6. Initialize Transport initializeTransport(true); // 7. Consume all queued Events for (int i = 1; i <= (maxTracesCacheSize + maxNetworkRequestsCacheSize + maxGaugesCacheSize); i++) { clearLastLoggedEvents(); fakeExecutorService.runNext(); } // 8. Queue is all consumed assertThat(testTransportManager.getPendingEventsQueue().isEmpty()).isTrue(); // 9. No pending events clearLastLoggedEvents(); fakeExecutorService.runAll(); assertThat(getLastLoggedEvent(never())).isNull(); } // endregion // region Flg Destination @Test public void logPerfMetric_dispatchedToFlgOnly() { TraceMetric validTrace = createValidTraceMetric(); testTransportManager.log(validTrace, ApplicationProcessState.FOREGROUND); fakeExecutorService.runAll(); verify(mockFlgTransport, times(1)).log(any()); assertThat(getLastLoggedEvent(times(1)).getTraceMetric()).isEqualTo(validTrace); } // endregion // region Performance Enable/Disable or Rate Limited @Test public void validTraceMetric_perfDisabled_notLogged() { when(mockConfigResolver.isPerformanceMonitoringEnabled()).thenReturn(false); testTransportManager.log(createValidTraceMetric()); fakeExecutorService.runAll(); assertThat(getLastLoggedEvent(never())).isNull(); } @Test public void validNetworkMetric_perfDisabled_notLogged() { when(mockConfigResolver.isPerformanceMonitoringEnabled()).thenReturn(false); testTransportManager.log(createValidNetworkRequestMetric()); fakeExecutorService.runAll(); assertThat(getLastLoggedEvent(never())).isNull(); } @Test public void validGaugeMetric_perfDisabled_notLogged() { when(mockConfigResolver.isPerformanceMonitoringEnabled()).thenReturn(false); testTransportManager.log(createValidGaugeMetric()); fakeExecutorService.runAll(); assertThat(getLastLoggedEvent(never())).isNull(); } @Test public void validTraceMetric_rateLimited_notLogged() { when(mockRateLimiter.isEventRateLimited(ArgumentMatchers.nullable(PerfMetric.class))) .thenReturn(true); testTransportManager.log(createValidTraceMetric()); fakeExecutorService.runAll(); assertThat(getLastLoggedEvent(never())).isNull(); verify(mockAppStateMonitor) .incrementCount(Constants.CounterNames.TRACE_EVENT_RATE_LIMITED.toString(), 1); } @Test public void validNetworkMetric_rateLimited_notLogged() { when(mockRateLimiter.isEventRateLimited(ArgumentMatchers.nullable(PerfMetric.class))) .thenReturn(true); testTransportManager.log(createValidNetworkRequestMetric()); fakeExecutorService.runAll(); assertThat(getLastLoggedEvent(never())).isNull(); verify(mockAppStateMonitor) .incrementCount(CounterNames.NETWORK_TRACE_EVENT_RATE_LIMITED.toString(), 1); } @Test public void validTraceMetric_notSampled_notLogged() { when(mockRateLimiter.isEventSampled(ArgumentMatchers.nullable(PerfMetric.class))) .thenReturn(false); testTransportManager.log(createValidTraceMetric()); fakeExecutorService.runAll(); assertThat(getLastLoggedEvent(never())).isNull(); verify(mockAppStateMonitor) .incrementCount(Constants.CounterNames.TRACE_EVENT_RATE_LIMITED.toString(), 1); } @Test public void validNetworkMetric_notSampled_notLogged() { when(mockRateLimiter.isEventSampled(ArgumentMatchers.nullable(PerfMetric.class))) .thenReturn(false); testTransportManager.log(createValidNetworkRequestMetric()); fakeExecutorService.runAll(); assertThat(getLastLoggedEvent(never())).isNull(); verify(mockAppStateMonitor) .incrementCount(CounterNames.NETWORK_TRACE_EVENT_RATE_LIMITED.toString(), 1); } // endregion // region ApplicationProcessState Behaviour @Test public void validTraceMetric_knownApplicationProcessState_getLogged() { TraceMetric validTrace = createValidTraceMetric(); testTransportManager.log(validTrace, ApplicationProcessState.BACKGROUND); fakeExecutorService.runAll(); PerfMetric loggedPerfMetric = getLastLoggedEvent(times(1)); assertThat(loggedPerfMetric.getTraceMetric()).isEqualTo(validTrace); validateApplicationInfo(loggedPerfMetric, ApplicationProcessState.BACKGROUND); } @Test public void validNetworkMetric_knownApplicationProcessState_getLogged() { NetworkRequestMetric validNetworkRequest = createValidNetworkRequestMetric(); testTransportManager.log(validNetworkRequest, ApplicationProcessState.FOREGROUND); fakeExecutorService.runAll(); PerfMetric loggedPerfMetric = getLastLoggedEvent(times(1)); assertThat(loggedPerfMetric.getNetworkRequestMetric()).isEqualTo(validNetworkRequest); validateApplicationInfo(loggedPerfMetric, ApplicationProcessState.FOREGROUND); } @Test public void validGaugeMetric_knownApplicationProcessState_getLogged() { GaugeMetric validGauge = createValidGaugeMetric(); testTransportManager.log(validGauge, ApplicationProcessState.BACKGROUND); fakeExecutorService.runAll(); PerfMetric loggedPerfMetric = getLastLoggedEvent(times(1)); assertThat(loggedPerfMetric.getGaugeMetric()).isEqualTo(validGauge); validateApplicationInfo(loggedPerfMetric, ApplicationProcessState.BACKGROUND); } @Test public void validTraceMetric_unknownApplicationProcessState_getLogged() { TraceMetric validTrace = createValidTraceMetric(); testTransportManager.log(validTrace); fakeExecutorService.runAll(); PerfMetric loggedPerfMetric = getLastLoggedEvent(times(1)); assertThat(loggedPerfMetric.getTraceMetric()).isEqualTo(validTrace); validateApplicationInfo( loggedPerfMetric, ApplicationProcessState.APPLICATION_PROCESS_STATE_UNKNOWN); } @Test public void validNetworkMetric_unknownApplicationProcessState_getLogged() { NetworkRequestMetric validNetworkRequest = createValidNetworkRequestMetric(); testTransportManager.log(validNetworkRequest); fakeExecutorService.runAll(); PerfMetric loggedPerfMetric = getLastLoggedEvent(times(1)); assertThat(loggedPerfMetric.getNetworkRequestMetric()).isEqualTo(validNetworkRequest); validateApplicationInfo( loggedPerfMetric, ApplicationProcessState.APPLICATION_PROCESS_STATE_UNKNOWN); } @Test public void validGaugeMetric_unknownApplicationProcessState_getLogged() { GaugeMetric validGauge = createValidGaugeMetric(); testTransportManager.log(validGauge); fakeExecutorService.runAll(); PerfMetric loggedPerfMetric = getLastLoggedEvent(times(1)); assertThat(loggedPerfMetric.getGaugeMetric()).isEqualTo(validGauge); validateApplicationInfo( loggedPerfMetric, ApplicationProcessState.APPLICATION_PROCESS_STATE_UNKNOWN); } @Test public void invalidTraceMetric_knownApplicationProcessState_notLogged() { testTransportManager.log(createInvalidTraceMetric()); fakeExecutorService.runAll(); assertThat(getLastLoggedEvent(never())).isNull(); } @Test public void invalidNetworkMetric_knownApplicationProcessState_notLogged() { testTransportManager.log( createInvalidNetworkRequestMetric(), ApplicationProcessState.FOREGROUND); fakeExecutorService.runAll(); assertThat(getLastLoggedEvent(never())).isNull(); } @Test public void invalidGaugeMetric_knownApplicationProcessState_notLogged() { testTransportManager.log(createInValidGaugeMetric()); fakeExecutorService.runAll(); assertThat(getLastLoggedEvent(never())).isNull(); } @Test public void invalidTraceMetric_unknownApplicationProcessState_notLogged() { testTransportManager.log(createInvalidTraceMetric()); fakeExecutorService.runAll(); assertThat(getLastLoggedEvent(never())).isNull(); } @Test public void invalidNetworkMetric_unknownApplicationProcessState_notLogged() { testTransportManager.log(createInvalidNetworkRequestMetric()); fakeExecutorService.runAll(); assertThat(getLastLoggedEvent(never())).isNull(); } @Test public void invalidGaugeMetric_unknownApplicationProcessState_notLogged() { testTransportManager.log(createInValidGaugeMetric()); fakeExecutorService.runAll(); assertThat(getLastLoggedEvent(never())).isNull(); } @Test public void invalidNetworkMetric_validURIButInvalidHostWithUnknownApplicationState_notLogged() { NetworkRequestMetric invalidNetworkRequest = createValidNetworkRequestMetric().toBuilder().setUrl("validUriButInvalidHost").build(); testTransportManager.log(invalidNetworkRequest); fakeExecutorService.runAll(); assertThat(getLastLoggedEvent(never())).isNull(); } @Test public void appStateChanges_capturedByUpdatingRate() { testTransportManager.onUpdateAppState(ApplicationProcessState.BACKGROUND); fakeExecutorService.runAll(); verify(mockRateLimiter).changeRate(/* isForeground= */ false); testTransportManager.onUpdateAppState(ApplicationProcessState.FOREGROUND); fakeExecutorService.runAll(); verify(mockRateLimiter).changeRate(/* isForeground= */ true); } // endregion // region Installations Interaction @Test public void validTraceMetric_nullInstallationsAndNoCache_notLogged() { clearInstallationsIdFromCache(); mockInstallationsGetId(null); clearLastLoggedEvents(); testTransportManager.log(createValidTraceMetric()); fakeExecutorService.runAll(); assertThat(getLastLoggedEvent(never())).isNull(); } @Test public void validNetworkMetric_nullInstallationsAndNoCache_notLogged() { clearInstallationsIdFromCache(); mockInstallationsGetId(null); clearLastLoggedEvents(); testTransportManager.log(createValidNetworkRequestMetric()); fakeExecutorService.runAll(); assertThat(getLastLoggedEvent(never())).isNull(); } @Test public void validTraceMetric_nullInstallationsDuringInitButValidValueLater_getLogged() { // Null Installations during initialization mockInstallationsGetId(null); initializeTransport(true); fakeExecutorService.runAll(); // Valid FID later mockInstallationsGetId(FAKE_FIREBASE_INSTALLATIONS_ID); TraceMetric validTrace = createValidTraceMetric(); testTransportManager.log(validTrace); fakeExecutorService.runAll(); PerfMetric loggedPerfMetric = getLastLoggedEvent(times(1)); assertThat(loggedPerfMetric.getTraceMetric()).isEqualTo(validTrace); validateApplicationInfo( loggedPerfMetric, ApplicationProcessState.APPLICATION_PROCESS_STATE_UNKNOWN); } @Test public void validNetworkMetric_nullInstallationsDuringInitButValidValueLater_getLogged() { // Null Installations during initialization mockInstallationsGetId(null); initializeTransport(true); fakeExecutorService.runAll(); // Valid FID later mockInstallationsGetId(FAKE_FIREBASE_INSTALLATIONS_ID); NetworkRequestMetric validNetworkRequest = createValidNetworkRequestMetric(); testTransportManager.log(validNetworkRequest); fakeExecutorService.runAll(); PerfMetric loggedPerfMetric = getLastLoggedEvent(times(1)); assertThat(loggedPerfMetric.getNetworkRequestMetric()).isEqualTo(validNetworkRequest); validateApplicationInfo( loggedPerfMetric, ApplicationProcessState.APPLICATION_PROCESS_STATE_UNKNOWN); } @Test public void syncLog_appInBackgroundWithoutCache_callsFirebaseInstallationsOnce() { clearInstallationsIdFromCache(); // Mimic the Background app state event testTransportManager.onUpdateAppState(ApplicationProcessState.BACKGROUND); fakeExecutorService.runAll(); // Attempts to send logs first time when the app is in the background clearLastLoggedEvents(); testTransportManager.log(createValidTraceMetric()); testTransportManager.log(createValidNetworkRequestMetric()); fakeExecutorService.runAll(); // getId() call happens only once in the background verify(mockFirebaseInstallationsApi, times(1)).getId(); } @Test public void syncLog_appInBackgroundWithCache_neverCallsFirebaseInstallations() { // Mimic the Foreground app state event testTransportManager.onUpdateAppState(ApplicationProcessState.FOREGROUND); testTransportManager.log(createValidTraceMetric()); fakeExecutorService.runAll(); // getId() is called since syncLog() is called during foreground (FID is cached after this call) verify(mockFirebaseInstallationsApi, times(1)).getId(); // Mimic the Background app state event testTransportManager.onUpdateAppState(ApplicationProcessState.BACKGROUND); fakeExecutorService.runAll(); // Attempt to send logs when the app is in background testTransportManager.log(createValidTraceMetric()); testTransportManager.log(createValidNetworkRequestMetric()); fakeExecutorService.runAll(); // getId() call count doesn't increment because cache already exists verify(mockFirebaseInstallationsApi, times(1)).getId(); } @Test public void syncLog_appInForeground_alwaysCallFirebaseInstallations() { // Mimic the Foreground app state event testTransportManager.onUpdateAppState(ApplicationProcessState.FOREGROUND); testTransportManager.log(createValidTraceMetric()); testTransportManager.log(createValidNetworkRequestMetric()); fakeExecutorService.runAll(); // getId() is called when syncLog() is called during foreground verify(mockFirebaseInstallationsApi, times(2)).getId(); } @Test public void syncLogForTraceMetric_performanceDisabled_noInteractionWithFirebaseInstallations() { when(mockConfigResolver.isPerformanceMonitoringEnabled()).thenReturn(false); testTransportManager.log(createValidTraceMetric()); fakeExecutorService.runAll(); assertThat(getLastLoggedEvent(never())).isNull(); verify(mockFirebaseInstallationsApi, never()).getId(); } @Test public void syncLogForNetworkMetric_performanceDisabled_noInteractionWithFirebaseInstallations() { when(mockConfigResolver.isPerformanceMonitoringEnabled()).thenReturn(false); testTransportManager.log(createValidNetworkRequestMetric()); fakeExecutorService.runAll(); assertThat(getLastLoggedEvent(never())).isNull(); verify(mockFirebaseInstallationsApi, never()).getId(); } @Test public void syncLogForGaugeMetric_performanceDisabled_noInteractionWithFirebaseInstallations() { when(mockConfigResolver.isPerformanceMonitoringEnabled()).thenReturn(false); testTransportManager.log(createValidGaugeMetric()); fakeExecutorService.runAll(); assertThat(getLastLoggedEvent(never())).isNull(); verify(mockFirebaseInstallationsApi, never()).getId(); } // endregion // region Global Custom Attributes Behaviour @Test public void logTraceMetric_globalCustomAttributesAreAdded() { FirebasePerformance.getInstance().putAttribute("test_key1", "test_value1"); FirebasePerformance.getInstance().putAttribute("test_key2", "test_value2"); TraceMetric validTrace = createValidTraceMetric(); testTransportManager.log(validTrace); fakeExecutorService.runAll(); PerfMetric loggedPerfMetric = getLastLoggedEvent(times(1)); assertThat(loggedPerfMetric.getTraceMetric()).isEqualTo(validTrace); validateApplicationInfo( loggedPerfMetric, ApplicationProcessState.APPLICATION_PROCESS_STATE_UNKNOWN); Map<String, String> globalCustomAttributes = loggedPerfMetric.getApplicationInfo().getCustomAttributesMap(); assertThat(globalCustomAttributes).hasSize(2); assertThat(globalCustomAttributes).containsEntry("test_key1", "test_value1"); assertThat(globalCustomAttributes).containsEntry("test_key2", "test_value2"); } @Test public void logNetworkMetric_globalCustomAttributesAreAdded() { FirebasePerformance.getInstance().putAttribute("test_key1", "test_value1"); FirebasePerformance.getInstance().putAttribute("test_key2", "test_value2"); NetworkRequestMetric validNetworkRequest = createValidNetworkRequestMetric(); testTransportManager.log(validNetworkRequest); fakeExecutorService.runAll(); PerfMetric loggedPerfMetric = getLastLoggedEvent(times(1)); assertThat(loggedPerfMetric.getNetworkRequestMetric()).isEqualTo(validNetworkRequest); validateApplicationInfo( loggedPerfMetric, ApplicationProcessState.APPLICATION_PROCESS_STATE_UNKNOWN); Map<String, String> globalCustomAttributes = loggedPerfMetric.getApplicationInfo().getCustomAttributesMap(); assertThat(globalCustomAttributes).hasSize(2); assertThat(globalCustomAttributes).containsEntry("test_key1", "test_value1"); assertThat(globalCustomAttributes).containsEntry("test_key2", "test_value2"); } @Test public void logGaugeMetric_globalCustomAttributesAreNotAdded() { FirebasePerformance.getInstance().putAttribute("test_key1", "test_value1"); FirebasePerformance.getInstance().putAttribute("test_key2", "test_value2"); GaugeMetric validGauge = createValidGaugeMetric(); testTransportManager.log(validGauge); fakeExecutorService.runAll(); PerfMetric loggedPerfMetric = getLastLoggedEvent(times(1)); assertThat(loggedPerfMetric.getGaugeMetric()).isEqualTo(validGauge); validateApplicationInfo( loggedPerfMetric, ApplicationProcessState.APPLICATION_PROCESS_STATE_UNKNOWN); assertThat(loggedPerfMetric.getApplicationInfo().getCustomAttributesCount()).isEqualTo(0); } // endregion // region Session's Behaviour @Test public void logTraceMetric_sessionEnabled_doesNotStripOffSessionId() { TraceMetric.Builder validTrace = createValidTraceMetric().toBuilder(); List<PerfSession> perfSessions = new ArrayList<>(); perfSessions.add( new com.google.firebase.perf.session.PerfSession("fakeSessionId", new Clock()).build()); validTrace.addAllPerfSessions(perfSessions); testTransportManager.log(validTrace.build()); fakeExecutorService.runAll(); PerfMetric loggedPerfMetric = getLastLoggedEvent(times(1)); assertThat(loggedPerfMetric.getTraceMetric().getPerfSessionsCount()).isEqualTo(1); assertThat(loggedPerfMetric.getTraceMetric().getPerfSessions(0).getSessionId()) .isEqualTo("fakeSessionId"); } @Test public void logNetworkMetric_sessionEnabled_doesNotStripOffSessionId() { NetworkRequestMetric.Builder validNetworkRequest = createValidNetworkRequestMetric().toBuilder(); List<PerfSession> perfSessions = new ArrayList<>(); perfSessions.add( new com.google.firebase.perf.session.PerfSession("fakeSessionId", new Clock()).build()); validNetworkRequest.clearPerfSessions().addAllPerfSessions(perfSessions); testTransportManager.log(validNetworkRequest.build()); fakeExecutorService.runAll(); PerfMetric loggedPerfMetric = getLastLoggedEvent(times(1)); assertThat(loggedPerfMetric.getNetworkRequestMetric().getPerfSessionsCount()).isEqualTo(1); assertThat(loggedPerfMetric.getNetworkRequestMetric().getPerfSessions(0).getSessionId()) .isEqualTo("fakeSessionId"); } @Test public void logTraceMetric_perfSessionExpired_updatesSessionId() { com.google.firebase.perf.session.PerfSession mockPerfSession = mock(com.google.firebase.perf.session.PerfSession.class); when(mockPerfSession.sessionId()).thenReturn("sessionId"); when(mockPerfSession.isExpired()).thenReturn(true); SessionManager.getInstance().setPerfSession(mockPerfSession); String oldSessionId = SessionManager.getInstance().perfSession().sessionId(); assertThat(oldSessionId).isEqualTo(SessionManager.getInstance().perfSession().sessionId()); testTransportManager.log(createValidTraceMetric(), ApplicationProcessState.BACKGROUND); fakeExecutorService.runAll(); assertThat(oldSessionId).isNotEqualTo(SessionManager.getInstance().perfSession().sessionId()); } @Test public void logNetworkMetric_perfSessionExpired_updatesSessionId() { com.google.firebase.perf.session.PerfSession mockPerfSession = mock(com.google.firebase.perf.session.PerfSession.class); when(mockPerfSession.sessionId()).thenReturn("sessionId"); when(mockPerfSession.isExpired()).thenReturn(true); SessionManager.getInstance().setPerfSession(mockPerfSession); String oldSessionId = SessionManager.getInstance().perfSession().sessionId(); assertThat(oldSessionId).isEqualTo(SessionManager.getInstance().perfSession().sessionId()); testTransportManager.log(createValidNetworkRequestMetric(), ApplicationProcessState.BACKGROUND); fakeExecutorService.runAll(); assertThat(oldSessionId).isNotEqualTo(SessionManager.getInstance().perfSession().sessionId()); } @Test public void logGaugeMetric_perfSessionExpired_updatesSessionId() { com.google.firebase.perf.session.PerfSession mockPerfSession = mock(com.google.firebase.perf.session.PerfSession.class); when(mockPerfSession.sessionId()).thenReturn("sessionId"); when(mockPerfSession.isExpired()).thenReturn(true); SessionManager.getInstance().setPerfSession(mockPerfSession); String oldSessionId = SessionManager.getInstance().perfSession().sessionId(); assertThat(oldSessionId).isEqualTo(SessionManager.getInstance().perfSession().sessionId()); testTransportManager.log(createValidGaugeMetric(), ApplicationProcessState.FOREGROUND); fakeExecutorService.runAll(); assertThat(oldSessionId).isNotEqualTo(SessionManager.getInstance().perfSession().sessionId()); } @Test public void logTraceMetric_perfSessionNotExpired_doesNotUpdateSessionId() { com.google.firebase.perf.session.PerfSession mockPerfSession = mock(com.google.firebase.perf.session.PerfSession.class); when(mockPerfSession.sessionId()).thenReturn("sessionId"); when(mockPerfSession.isExpired()).thenReturn(false); SessionManager.getInstance().setPerfSession(mockPerfSession); String oldSessionId = SessionManager.getInstance().perfSession().sessionId(); assertThat(oldSessionId).isEqualTo(SessionManager.getInstance().perfSession().sessionId()); testTransportManager.log(createValidTraceMetric(), ApplicationProcessState.BACKGROUND); fakeExecutorService.runAll(); assertThat(oldSessionId).isEqualTo(SessionManager.getInstance().perfSession().sessionId()); } @Test public void logNetworkMetric_perfSessionNotExpired_doesNotUpdateSessionId() { com.google.firebase.perf.session.PerfSession mockPerfSession = mock(com.google.firebase.perf.session.PerfSession.class); when(mockPerfSession.sessionId()).thenReturn("sessionId"); when(mockPerfSession.isExpired()).thenReturn(false); SessionManager.getInstance().setPerfSession(mockPerfSession); String oldSessionId = SessionManager.getInstance().perfSession().sessionId(); assertThat(oldSessionId).isEqualTo(SessionManager.getInstance().perfSession().sessionId()); testTransportManager.log(createValidNetworkRequestMetric(), ApplicationProcessState.BACKGROUND); fakeExecutorService.runAll(); assertThat(oldSessionId).isEqualTo(SessionManager.getInstance().perfSession().sessionId()); } @Test public void logGaugeMetric_perfSessionNotExpired_doesNotUpdateSessionId() { com.google.firebase.perf.session.PerfSession mockPerfSession = mock(com.google.firebase.perf.session.PerfSession.class); when(mockPerfSession.sessionId()).thenReturn("sessionId"); when(mockPerfSession.isExpired()).thenReturn(false); SessionManager.getInstance().setPerfSession(mockPerfSession); String oldSessionId = SessionManager.getInstance().perfSession().sessionId(); assertThat(oldSessionId).isEqualTo(SessionManager.getInstance().perfSession().sessionId()); testTransportManager.log(createValidGaugeMetric(), ApplicationProcessState.FOREGROUND); fakeExecutorService.runAll(); assertThat(oldSessionId).isEqualTo(SessionManager.getInstance().perfSession().sessionId()); } // endregion // region Gauge Specific @Test public void validGaugeMetric_withCpuReadings_isLogged() { ApplicationProcessState expectedAppState = ApplicationProcessState.FOREGROUND; // Construct a list of Cpu metric readings List<CpuMetricReading> expectedCpuMetricReadings = new ArrayList<>(); expectedCpuMetricReadings.add( createValidCpuMetricReading(/* userTimeUs= */ 10, /* systemTimeUs= */ 20)); expectedCpuMetricReadings.add( createValidCpuMetricReading(/* userTimeUs= */ 20, /* systemTimeUs= */ 30)); GaugeMetric validGauge = GaugeMetric.newBuilder() .setSessionId("sessionId") .addAllCpuMetricReadings(expectedCpuMetricReadings) .build(); testTransportManager.log(validGauge, expectedAppState); fakeExecutorService.runAll(); PerfMetric loggedPerfMetric = getLastLoggedEvent(times(1)); assertThat(loggedPerfMetric.getGaugeMetric().getCpuMetricReadingsList()) .containsExactlyElementsIn(expectedCpuMetricReadings); assertThat(loggedPerfMetric.getGaugeMetric().getSessionId()).isEqualTo("sessionId"); } @Test public void validGaugeMetric_withMemoryReadings_isLogged() { ApplicationProcessState expectedAppState = ApplicationProcessState.FOREGROUND; // Construct a list of Memory metric readings List<AndroidMemoryReading> expectedMemoryMetricReadings = new ArrayList<>(); expectedMemoryMetricReadings.add( createValidAndroidMetricReading(/* currentUsedAppJavaHeapMemoryKb= */ 1234)); expectedMemoryMetricReadings.add( createValidAndroidMetricReading(/* currentUsedAppJavaHeapMemoryKb= */ 23456)); GaugeMetric validGauge = GaugeMetric.newBuilder() .setSessionId("sessionId") .addAllAndroidMemoryReadings(expectedMemoryMetricReadings) .build(); testTransportManager.log(validGauge, expectedAppState); fakeExecutorService.runAll(); PerfMetric loggedPerfMetric = getLastLoggedEvent(times(1)); assertThat(loggedPerfMetric.getGaugeMetric().getAndroidMemoryReadingsList()) .containsExactlyElementsIn(expectedMemoryMetricReadings); assertThat(loggedPerfMetric.getGaugeMetric().getSessionId()).isEqualTo("sessionId"); } @Test public void validGaugeMetric_withMetadata_isLogged() { ApplicationProcessState expectedAppState = ApplicationProcessState.FOREGROUND; GaugeMetadata gaugeMetadata = GaugeMetadata.newBuilder() .setDeviceRamSizeKb(2000) .setMaxAppJavaHeapMemoryKb(1000) .setMaxEncouragedAppJavaHeapMemoryKb(800) .build(); GaugeMetric validGauge = GaugeMetric.newBuilder().setSessionId("sessionId").setGaugeMetadata(gaugeMetadata).build(); testTransportManager.log(validGauge, expectedAppState); fakeExecutorService.runAll(); PerfMetric loggedPerfMetric = getLastLoggedEvent(times(1)); assertThat(loggedPerfMetric.getGaugeMetric().getSessionId()).isEqualTo("sessionId"); assertThat(loggedPerfMetric.getGaugeMetric().getGaugeMetadata().getDeviceRamSizeKb()) .isEqualTo(2000); assertThat(loggedPerfMetric.getGaugeMetric().getGaugeMetadata().getMaxAppJavaHeapMemoryKb()) .isEqualTo(1000); assertThat( loggedPerfMetric .getGaugeMetric() .getGaugeMetadata() .getMaxEncouragedAppJavaHeapMemoryKb()) .isEqualTo(800); } // endregion // region Helper Methods private void initializeTransport(boolean shouldInitialize) { // # Before Initializing // Clear any logged events clearLastLoggedEvents(); if (shouldInitialize) { testTransportManager = TransportManager.getInstance(); testTransportManager.initializeForTest( FirebaseApp.getInstance(), FirebasePerformance.getInstance(), mockFirebaseInstallationsApi, mockFlgTransportFactoryProvider, mockConfigResolver, mockRateLimiter, mockAppStateMonitor, mockFlgTransport, fakeExecutorService); } else { testTransportManager.setInitialized(false); } } private void clearInstallationsIdFromCache() { testTransportManager.clearAppInstanceId(); } private void mockInstallationsGetId(final String installationsId) { when(mockFirebaseInstallationsApi.getId()).thenReturn(Tasks.forResult(installationsId)); } private List<PerfMetric> getLastLoggedEvents(VerificationMode expectedVerificationMode) { verifyDispatch(expectedVerificationMode); if (!expectedVerificationMode.toString().equals(never().toString())) { return perfMetricArgumentCaptor.getAllValues(); } return new ArrayList<>(); } private PerfMetric getLastLoggedEvent(VerificationMode expectedVerificationMode) { verifyDispatch(expectedVerificationMode); if (!expectedVerificationMode.toString().equals(never().toString())) { return perfMetricArgumentCaptor.getValue(); } return null; } private void verifyDispatch(VerificationMode expectedVerificationMode) { verify(mockFlgTransport, expectedVerificationMode).log(perfMetricArgumentCaptor.capture()); } private void clearLastLoggedEvents() { clearInvocations(mockFlgTransport); } private static void validateApplicationInfo( PerfMetric loggedPerfMetric, ApplicationProcessState applicationProcessState) { assertThat(loggedPerfMetric.getApplicationInfo().getAppInstanceId()) .isEqualTo(FAKE_FIREBASE_INSTALLATIONS_ID); assertThat(loggedPerfMetric.getApplicationInfo().getGoogleAppId()) .isEqualTo(FAKE_FIREBASE_APPLICATION_ID); assertThat(loggedPerfMetric.getApplicationInfo().getApplicationProcessState()) .isEqualTo(applicationProcessState); assertThat(loggedPerfMetric.getApplicationInfo().hasAndroidAppInfo()).isTrue(); } private static TraceMetric createInvalidTraceMetric() { return createValidTraceMetric().toBuilder().setName("").build(); } private static TraceMetric createValidTraceMetric() { return TraceMetric.newBuilder() .setName("test_trace") .setClientStartTimeUs(100L) .setDurationUs(100L) .build(); } private static NetworkRequestMetric createInvalidNetworkRequestMetric() { return createValidNetworkRequestMetric().toBuilder().setUrl("//: invalidUrl").build(); } private static NetworkRequestMetric createValidNetworkRequestMetric() { return NetworkRequestMetric.newBuilder() .setUrl("https://www.google.com") .setHttpMethod(HttpMethod.GET) .setHttpResponseCode(200) .setClientStartTimeUs(100L) .setTimeToResponseCompletedUs(100L) .build(); } private static GaugeMetric createInValidGaugeMetric() { return createValidGaugeMetric().toBuilder().clearSessionId().build(); } private static GaugeMetric createValidGaugeMetric() { // Construct a list of Cpu metric readings List<CpuMetricReading> cpuMetricReadings = new ArrayList<>(); cpuMetricReadings.add( createValidCpuMetricReading(/* userTimeUs= */ 10, /* systemTimeUs= */ 20)); cpuMetricReadings.add( createValidCpuMetricReading(/* userTimeUs= */ 20, /* systemTimeUs= */ 30)); // Construct a list of Memory metric readings List<AndroidMemoryReading> memoryMetricReadings = new ArrayList<>(); memoryMetricReadings.add( createValidAndroidMetricReading(/* currentUsedAppJavaHeapMemoryKb= */ 1234)); memoryMetricReadings.add( createValidAndroidMetricReading(/* currentUsedAppJavaHeapMemoryKb= */ 23456)); return GaugeMetric.newBuilder() .setSessionId("sessionId") .addAllCpuMetricReadings(cpuMetricReadings) .addAllAndroidMemoryReadings(memoryMetricReadings) .build(); } private static CpuMetricReading createValidCpuMetricReading(long userTimeUs, long systemTimeUs) { return CpuMetricReading.newBuilder() .setClientTimeUs(System.currentTimeMillis()) .setUserTimeUs(userTimeUs) .setSystemTimeUs(systemTimeUs) .build(); } private static AndroidMemoryReading createValidAndroidMetricReading( int currentUsedAppJavaHeapMemoryKb) { return AndroidMemoryReading.newBuilder() .setClientTimeUs(System.currentTimeMillis()) .setUsedAppJavaHeapMemoryKb(currentUsedAppJavaHeapMemoryKb) .build(); } // endregion }
apache-2.0
y-higuchi/odenos
src/main/java/org/o3project/odenos/core/component/network/topology/Port.java
7900
/* * Copyright 2015 NEC Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.o3project.odenos.core.component.network.topology; import static org.msgpack.template.Templates.tMap; import static org.msgpack.template.Templates.TString; import org.apache.commons.lang.builder.ToStringBuilder; import org.msgpack.packer.Packer; import org.msgpack.type.ValueType; import org.msgpack.unpacker.Unpacker; import org.o3project.odenos.remoteobject.message.BaseObject; import java.io.IOException; import java.util.HashMap; import java.util.Map; /** * Switch Port data class. * */ public class Port extends BaseObject implements Cloneable { private static final int MSG_NUM_MIN = 1; private static final int MSG_NUM_MAX = 7; private String type = "Port"; private String portId; private String nodeId; private String outLink; private String inLink; /** * Constructor. */ public Port() { } /** * Constructor. * @param portId port id that is unique in the Node. */ public Port(String portId) { this.portId = portId; } /** * Constructor. * @param portId port id that is unique in the Node. * @param nodeId Port belongs to this node id. */ public Port(String portId, String nodeId) { this(portId); this.nodeId = nodeId; } /** * Constructor. * @param version number of version. * @param portId port id that is unique in the Node. * @param nodeId Port belongs to this node id. */ public Port(String version, String portId, String nodeId) { this(portId, nodeId); this.setVersion(version); } /** * Constructor. * @param version string of version. * @param portId port id that is unique in the Node. * @param nodeId Port belongs to this node id. * @param outLink output link id. * @param inLink input link id. * @param attributes map of attributes. */ public Port(String version, String portId, String nodeId, String outLink, String inLink, Map<String, String> attributes) { this(version, portId, nodeId); this.outLink = outLink; this.inLink = inLink; this.putAttributes(attributes); } /** * Constructor. * @param msg port message. */ public Port(Port msg) { this(msg.getVersion(), msg.getId(), msg.getNode(), msg.getOutLink(), msg.getInLink(), new HashMap<String, String>( msg.getAttributes())); } /** * Confirm the parameter. * @return true if parameter is valid. */ public boolean validate() { if (this.nodeId == null || this.portId == null || this.type == null) { return false; } return true; } /** * Returns a type of port. * @return type of port. */ public String getType() { return type; } /** * Returns a port ID. * @return port ID. */ public String getId() { return portId; } /** * Sets a port ID. * @param portId port ID. */ public void setId(String portId) { this.portId = portId; } /** * Returns a node ID. * @return node ID. */ public String getNode() { return nodeId; } /** * Sets a node ID. * @param nodeId node ID. */ public void setNode(String nodeId) { this.nodeId = nodeId; } /** * Returns a output link ID. * @return output link ID. */ public String getOutLink() { return outLink; } /** * Sets a output link ID. * @param linkId output link ID. */ public void setOutLink(String linkId) { outLink = linkId; } /** * Returns a input link ID. * @return input link ID. */ public String getInLink() { return inLink; } /** * Sets a input link ID. * @param linkId input link ID. */ public void setInLink(String linkId) { inLink = linkId; } @Override public void readFrom(Unpacker upk) throws IOException { int size = upk.readMapBegin(); if (size < MSG_NUM_MIN || MSG_NUM_MAX < size) { throw new IOException(); } while (size-- > 0) { switch (upk.readString()) { case "type": type = upk.readString(); break; case "version": if (upk.getNextType() == ValueType.NIL) { upk.readNil(); setVersion("0"); } else { setVersion(upk.readString()); } break; case "port_id": if (upk.getNextType() == ValueType.NIL) { upk.readNil(); portId = null; } else { portId = upk.readString(); } break; case "node_id": if (upk.getNextType() == ValueType.NIL) { upk.readNil(); nodeId = null; } else { nodeId = upk.readString(); } break; case "out_link": if (upk.getNextType() == ValueType.NIL) { upk.readNil(); outLink = null; } else { outLink = upk.readString(); } break; case "in_link": if (upk.getNextType() == ValueType.NIL) { upk.readNil(); inLink = null; } else { inLink = upk.readString(); } break; case "attributes": putAttributes(upk.read(tMap(TString, TString))); break; default: break; } } upk.readMapEnd(); } @Override public void writeTo(Packer pk) throws IOException { pk.writeMapBegin(MSG_NUM_MAX); pk.write("type"); pk.write(type); pk.write("version"); pk.write(getVersion()); pk.write("port_id"); pk.write(portId); pk.write("node_id"); pk.write(nodeId); pk.write("out_link"); if (outLink != null) { pk.write(outLink); } else { pk.writeNil(); } pk.write("in_link"); if (inLink != null) { pk.write(inLink); } else { pk.writeNil(); } pk.write("attributes"); pk.write(getAttributes()); pk.writeMapEnd(); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (obj == this) { return true; } if (!(obj instanceof Port)) { return false; } Port portMessage = (Port) obj; try { if (portMessage.getType().equals(this.type) && portMessage.getVersion().equals(this.getVersion()) && portMessage.getId().equals(this.portId) && portMessage.getNode().equals(this.nodeId) && String.format("%s", portMessage.getOutLink()).equals( String.format("%s", this.outLink)) && String.format("%s", portMessage.getInLink()).equals( String.format("%s", this.inLink)) && portMessage.getAttributes().equals(this.getAttributes())) { return true; } } catch (NullPointerException e) { //e.printStackTrace(); } return false; } @Override public Port clone() { return new Port(this); } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { ToStringBuilder sb = new ToStringBuilder(this); sb.append("version", getVersion()); sb.append("portId", portId); sb.append("nodeId", nodeId); sb.append("outLink", outLink); sb.append("inLink", inLink); sb.append("attributes", getAttributes()); return sb.toString(); } }
apache-2.0
googleads/googleads-dotnet-lib
examples/AdManager/CSharp/v202111/CreativeService/CreateCustomCreative.cs
5069
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Google.Api.Ads.Common.Util; using Google.Api.Ads.AdManager.Lib; using Google.Api.Ads.AdManager.v202111; using System; namespace Google.Api.Ads.AdManager.Examples.CSharp.v202111 { /// <summary> /// This code example creates a custom creative for a given advertiser. To /// determine which companies are advertisers, run GetCompaniesByStatement.cs. /// To determine which creatives already exist, run GetAllCreatives.cs. /// </summary> public class CreateCustomCreative : SampleBase { /// <summary> /// Returns a description about the code example. /// </summary> public override string Description { get { return "This code example creates a custom creative for a given advertiser. " + "To determine which companies are advertisers, " + "run GetCompaniesByStatement.cs. To determine which creatives already exist, " + "run GetAllCreatives.cs."; } } /// <summary> /// Main method, to run this code example as a standalone application. /// </summary> public static void Main() { CreateCustomCreative codeExample = new CreateCustomCreative(); Console.WriteLine(codeExample.Description); codeExample.Run(new AdManagerUser()); } /// <summary> /// Run the code example. /// </summary> public void Run(AdManagerUser user) { using (CreativeService creativeService = user.GetService<CreativeService>()) { // Set the ID of the advertiser (company) that all creatives will be // assigned to. long advertiserId = long.Parse(_T("INSERT_ADVERTISER_ID_HERE")); // Create the local custom creative object. CustomCreative customCreative = new CustomCreative(); customCreative.name = "Custom creative " + GetTimeStamp(); customCreative.advertiserId = advertiserId; customCreative.destinationUrl = "http://google.com"; // Set the custom creative image asset. CustomCreativeAsset customCreativeAsset = new CustomCreativeAsset(); customCreativeAsset.macroName = "IMAGE_ASSET"; CreativeAsset asset = new CreativeAsset(); asset.fileName = string.Format("inline{0}.jpg", GetTimeStamp()); asset.assetByteArray = MediaUtilities.GetAssetDataFromUrl("https://goo.gl/3b9Wfh", user.Config); customCreativeAsset.asset = asset; customCreative.customCreativeAssets = new CustomCreativeAsset[] { customCreativeAsset }; // Set the HTML snippet using the custom creative asset macro. customCreative.htmlSnippet = "<a href='%%CLICK_URL_UNESC%%%%DEST_URL%%'>" + "<img src='%%FILE:" + customCreativeAsset.macroName + "%%'/>" + "</a><br>Click above for great deals!"; // Set the creative size. Size size = new Size(); size.width = 300; size.height = 250; size.isAspectRatio = false; customCreative.size = size; try { // Create the custom creative on the server. Creative[] createdCreatives = creativeService.createCreatives(new Creative[] { customCreative }); foreach (Creative createdCreative in createdCreatives) { Console.WriteLine( "A custom creative with ID \"{0}\", name \"{1}\", and size ({2}, " + "{3}) was created and can be previewed at {4}", createdCreative.id, createdCreative.name, createdCreative.size.width, createdCreative.size.height, createdCreative.previewUrl); } } catch (Exception e) { Console.WriteLine("Failed to create custom creatives. Exception says \"{0}\"", e.Message); } } } } }
apache-2.0
atompulse/atompulse
src/Atompulse/Bundle/FusionBundle/Assets/Refiner/SimpleRefiner.php
1051
<?php namespace Atompulse\Bundle\FusionBundle\Assets\Refiner; /** * Class SimpleRefiner * @package Atompulse\Bundle\FusionBundle\Compiler\Refiner * * @author Petru Cojocar <[email protected]> */ class SimpleRefiner implements RefinerInterface { /** * Very basic content optimizer * @param string $content * @return mixed|string */ public static function refine($content) { // remove comments $content = preg_replace('$\/\*[\s\S]*?\*\/$', '', $content); //$content = preg_replace('/[ \t]*(?:\/\*(?:.(?!(?<=\*)\/))*\*\/|\/\/[^\n\r]*\n?\r?)/', '', $content); $content = preg_replace('$(?<=\s|\w)[\/]{2,}.*$', '', $content); // remove tabs, spaces, newlines, etc. $content = str_replace(["\r\n", "\r", "\n", "\t", ' ', ' ', ' '], '', $content); // remove special language constructs $content = str_replace([" : ",": ",', ',' (', ' = ',' || ',' ? ',') {'], [':', ':',',','(','=','||','?','){'], $content); return $content; } }
apache-2.0
shapesecurity/shift-parser-js
src/tokenizer.js
46755
/** * Copyright 2014 Shape Security, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { getHexValue, isLineTerminator, isWhiteSpace, isIdentifierStart, isIdentifierPart, isDecimalDigit } from './utils'; import { ErrorMessages } from './errors'; export const TokenClass = { Eof: { name: '<End>' }, Ident: { name: 'Identifier', isIdentifierName: true }, Keyword: { name: 'Keyword', isIdentifierName: true }, NumericLiteral: { name: 'Numeric' }, TemplateElement: { name: 'Template' }, Punctuator: { name: 'Punctuator' }, StringLiteral: { name: 'String' }, RegularExpression: { name: 'RegularExpression' }, Illegal: { name: 'Illegal' }, }; export const TokenType = { EOS: { klass: TokenClass.Eof, name: 'EOS' }, LPAREN: { klass: TokenClass.Punctuator, name: '(' }, RPAREN: { klass: TokenClass.Punctuator, name: ')' }, LBRACK: { klass: TokenClass.Punctuator, name: '[' }, RBRACK: { klass: TokenClass.Punctuator, name: ']' }, LBRACE: { klass: TokenClass.Punctuator, name: '{' }, RBRACE: { klass: TokenClass.Punctuator, name: '}' }, COLON: { klass: TokenClass.Punctuator, name: ':' }, SEMICOLON: { klass: TokenClass.Punctuator, name: ';' }, PERIOD: { klass: TokenClass.Punctuator, name: '.' }, ELLIPSIS: { klass: TokenClass.Punctuator, name: '...' }, ARROW: { klass: TokenClass.Punctuator, name: '=>' }, CONDITIONAL: { klass: TokenClass.Punctuator, name: '?' }, INC: { klass: TokenClass.Punctuator, name: '++' }, DEC: { klass: TokenClass.Punctuator, name: '--' }, ASSIGN: { klass: TokenClass.Punctuator, name: '=' }, ASSIGN_BIT_OR: { klass: TokenClass.Punctuator, name: '|=' }, ASSIGN_BIT_XOR: { klass: TokenClass.Punctuator, name: '^=' }, ASSIGN_BIT_AND: { klass: TokenClass.Punctuator, name: '&=' }, ASSIGN_SHL: { klass: TokenClass.Punctuator, name: '<<=' }, ASSIGN_SHR: { klass: TokenClass.Punctuator, name: '>>=' }, ASSIGN_SHR_UNSIGNED: { klass: TokenClass.Punctuator, name: '>>>=' }, ASSIGN_ADD: { klass: TokenClass.Punctuator, name: '+=' }, ASSIGN_SUB: { klass: TokenClass.Punctuator, name: '-=' }, ASSIGN_MUL: { klass: TokenClass.Punctuator, name: '*=' }, ASSIGN_DIV: { klass: TokenClass.Punctuator, name: '/=' }, ASSIGN_MOD: { klass: TokenClass.Punctuator, name: '%=' }, ASSIGN_EXP: { klass: TokenClass.Punctuator, name: '**=' }, COMMA: { klass: TokenClass.Punctuator, name: ',' }, OR: { klass: TokenClass.Punctuator, name: '||' }, AND: { klass: TokenClass.Punctuator, name: '&&' }, BIT_OR: { klass: TokenClass.Punctuator, name: '|' }, BIT_XOR: { klass: TokenClass.Punctuator, name: '^' }, BIT_AND: { klass: TokenClass.Punctuator, name: '&' }, SHL: { klass: TokenClass.Punctuator, name: '<<' }, SHR: { klass: TokenClass.Punctuator, name: '>>' }, SHR_UNSIGNED: { klass: TokenClass.Punctuator, name: '>>>' }, ADD: { klass: TokenClass.Punctuator, name: '+' }, SUB: { klass: TokenClass.Punctuator, name: '-' }, MUL: { klass: TokenClass.Punctuator, name: '*' }, DIV: { klass: TokenClass.Punctuator, name: '/' }, MOD: { klass: TokenClass.Punctuator, name: '%' }, EXP: { klass: TokenClass.Punctuator, name: '**' }, EQ: { klass: TokenClass.Punctuator, name: '==' }, NE: { klass: TokenClass.Punctuator, name: '!=' }, EQ_STRICT: { klass: TokenClass.Punctuator, name: '===' }, NE_STRICT: { klass: TokenClass.Punctuator, name: '!==' }, LT: { klass: TokenClass.Punctuator, name: '<' }, GT: { klass: TokenClass.Punctuator, name: '>' }, LTE: { klass: TokenClass.Punctuator, name: '<=' }, GTE: { klass: TokenClass.Punctuator, name: '>=' }, INSTANCEOF: { klass: TokenClass.Keyword, name: 'instanceof' }, IN: { klass: TokenClass.Keyword, name: 'in' }, NOT: { klass: TokenClass.Punctuator, name: '!' }, BIT_NOT: { klass: TokenClass.Punctuator, name: '~' }, ASYNC: { klass: TokenClass.Keyword, name: 'async' }, AWAIT: { klass: TokenClass.Keyword, name: 'await' }, ENUM: { klass: TokenClass.Keyword, name: 'enum' }, DELETE: { klass: TokenClass.Keyword, name: 'delete' }, TYPEOF: { klass: TokenClass.Keyword, name: 'typeof' }, VOID: { klass: TokenClass.Keyword, name: 'void' }, BREAK: { klass: TokenClass.Keyword, name: 'break' }, CASE: { klass: TokenClass.Keyword, name: 'case' }, CATCH: { klass: TokenClass.Keyword, name: 'catch' }, CLASS: { klass: TokenClass.Keyword, name: 'class' }, CONTINUE: { klass: TokenClass.Keyword, name: 'continue' }, DEBUGGER: { klass: TokenClass.Keyword, name: 'debugger' }, DEFAULT: { klass: TokenClass.Keyword, name: 'default' }, DO: { klass: TokenClass.Keyword, name: 'do' }, ELSE: { klass: TokenClass.Keyword, name: 'else' }, EXPORT: { klass: TokenClass.Keyword, name: 'export' }, EXTENDS: { klass: TokenClass.Keyword, name: 'extends' }, FINALLY: { klass: TokenClass.Keyword, name: 'finally' }, FOR: { klass: TokenClass.Keyword, name: 'for' }, FUNCTION: { klass: TokenClass.Keyword, name: 'function' }, IF: { klass: TokenClass.Keyword, name: 'if' }, IMPORT: { klass: TokenClass.Keyword, name: 'import' }, LET: { klass: TokenClass.Keyword, name: 'let' }, NEW: { klass: TokenClass.Keyword, name: 'new' }, RETURN: { klass: TokenClass.Keyword, name: 'return' }, SUPER: { klass: TokenClass.Keyword, name: 'super' }, SWITCH: { klass: TokenClass.Keyword, name: 'switch' }, THIS: { klass: TokenClass.Keyword, name: 'this' }, THROW: { klass: TokenClass.Keyword, name: 'throw' }, TRY: { klass: TokenClass.Keyword, name: 'try' }, VAR: { klass: TokenClass.Keyword, name: 'var' }, WHILE: { klass: TokenClass.Keyword, name: 'while' }, WITH: { klass: TokenClass.Keyword, name: 'with' }, NULL: { klass: TokenClass.Keyword, name: 'null' }, TRUE: { klass: TokenClass.Keyword, name: 'true' }, FALSE: { klass: TokenClass.Keyword, name: 'false' }, YIELD: { klass: TokenClass.Keyword, name: 'yield' }, NUMBER: { klass: TokenClass.NumericLiteral, name: '' }, STRING: { klass: TokenClass.StringLiteral, name: '' }, REGEXP: { klass: TokenClass.RegularExpression, name: '' }, IDENTIFIER: { klass: TokenClass.Ident, name: '' }, CONST: { klass: TokenClass.Keyword, name: 'const' }, TEMPLATE: { klass: TokenClass.TemplateElement, name: '' }, ESCAPED_KEYWORD: { klass: TokenClass.Keyword, name: '' }, ILLEGAL: { klass: TokenClass.Illegal, name: '' }, }; const TT = TokenType; const I = TT.ILLEGAL; const F = false; const T = true; const ONE_CHAR_PUNCTUATOR = [ I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, TT.NOT, I, I, I, TT.MOD, TT.BIT_AND, I, TT.LPAREN, TT.RPAREN, TT.MUL, TT.ADD, TT.COMMA, TT.SUB, TT.PERIOD, TT.DIV, I, I, I, I, I, I, I, I, I, I, TT.COLON, TT.SEMICOLON, TT.LT, TT.ASSIGN, TT.GT, TT.CONDITIONAL, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, TT.LBRACK, I, TT.RBRACK, TT.BIT_XOR, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, TT.LBRACE, TT.BIT_OR, TT.RBRACE, TT.BIT_NOT, ]; const PUNCTUATOR_START = [ F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, T, F, F, F, T, T, F, T, T, T, T, T, T, F, T, F, F, F, F, F, F, F, F, F, F, T, T, T, T, T, T, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, T, F, T, T, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, T, T, T, T, F, ]; export class JsError extends Error { constructor(index, line, column, msg) { super(msg); this.index = index; // Safari defines these properties as non-writable and non-configurable on Error objects try { this.line = line; this.column = column; } catch (e) {} // define these as well so Safari still has access to this info this.parseErrorLine = line; this.parseErrorColumn = column; this.description = msg; this.message = `[${line}:${column}]: ${msg}`; } } function fromCodePoint(cp) { if (cp <= 0xFFFF) return String.fromCharCode(cp); let cu1 = String.fromCharCode(Math.floor((cp - 0x10000) / 0x400) + 0xD800); let cu2 = String.fromCharCode((cp - 0x10000) % 0x400 + 0xDC00); return cu1 + cu2; } function decodeUtf16(lead, trail) { return (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000; } export default class Tokenizer { constructor(source) { this.source = source; this.index = 0; this.line = 0; this.lineStart = 0; this.startIndex = 0; this.startLine = 0; this.startLineStart = 0; this.lastIndex = 0; this.lastLine = 0; this.lastLineStart = 0; this.hasLineTerminatorBeforeNext = false; this.tokenIndex = 0; } saveLexerState() { return { source: this.source, index: this.index, line: this.line, lineStart: this.lineStart, startIndex: this.startIndex, startLine: this.startLine, startLineStart: this.startLineStart, lastIndex: this.lastIndex, lastLine: this.lastLine, lastLineStart: this.lastLineStart, lookahead: this.lookahead, hasLineTerminatorBeforeNext: this.hasLineTerminatorBeforeNext, tokenIndex: this.tokenIndex, }; } restoreLexerState(state) { this.source = state.source; this.index = state.index; this.line = state.line; this.lineStart = state.lineStart; this.startIndex = state.startIndex; this.startLine = state.startLine; this.startLineStart = state.startLineStart; this.lastIndex = state.lastIndex; this.lastLine = state.lastLine; this.lastLineStart = state.lastLineStart; this.lookahead = state.lookahead; this.hasLineTerminatorBeforeNext = state.hasLineTerminatorBeforeNext; this.tokenIndex = state.tokenIndex; } createILLEGAL() { this.startIndex = this.index; this.startLine = this.line; this.startLineStart = this.lineStart; return this.index < this.source.length ? this.createError(ErrorMessages.UNEXPECTED_ILLEGAL_TOKEN, this.source.charAt(this.index)) : this.createError(ErrorMessages.UNEXPECTED_EOS); } createUnexpected(token) { switch (token.type.klass) { case TokenClass.Eof: return this.createError(ErrorMessages.UNEXPECTED_EOS); case TokenClass.Ident: return this.createError(ErrorMessages.UNEXPECTED_IDENTIFIER); case TokenClass.Keyword: if (token.type === TokenType.ESCAPED_KEYWORD) { return this.createError(ErrorMessages.UNEXPECTED_ESCAPED_KEYWORD); } return this.createError(ErrorMessages.UNEXPECTED_TOKEN, token.slice.text); case TokenClass.NumericLiteral: return this.createError(ErrorMessages.UNEXPECTED_NUMBER); case TokenClass.TemplateElement: return this.createError(ErrorMessages.UNEXPECTED_TEMPLATE); case TokenClass.Punctuator: return this.createError(ErrorMessages.UNEXPECTED_TOKEN, token.type.name); case TokenClass.StringLiteral: return this.createError(ErrorMessages.UNEXPECTED_STRING); // the other token classes are RegularExpression and Illegal, but they cannot reach here } // istanbul ignore next throw new Error('Unreachable: unexpected token of class ' + token.type.klass); } createError(message, ...params) { let msg; if (typeof message === 'function') { msg = message(...params); } else { msg = message; } return new JsError(this.startIndex, this.startLine + 1, this.startIndex - this.startLineStart + 1, msg); } createErrorWithLocation(location, message) { /* istanbul ignore next */ let msg = message.replace(/\{(\d+)\}/g, (_, n) => JSON.stringify(arguments[+n + 2])); if (location.slice && location.slice.startLocation) { location = location.slice.startLocation; } return new JsError(location.offset, location.line, location.column + 1, msg); } static cse2(id, ch1, ch2) { return id.charAt(1) === ch1 && id.charAt(2) === ch2; } static cse3(id, ch1, ch2, ch3) { return id.charAt(1) === ch1 && id.charAt(2) === ch2 && id.charAt(3) === ch3; } static cse4(id, ch1, ch2, ch3, ch4) { return id.charAt(1) === ch1 && id.charAt(2) === ch2 && id.charAt(3) === ch3 && id.charAt(4) === ch4; } static cse5(id, ch1, ch2, ch3, ch4, ch5) { return id.charAt(1) === ch1 && id.charAt(2) === ch2 && id.charAt(3) === ch3 && id.charAt(4) === ch4 && id.charAt(5) === ch5; } static cse6(id, ch1, ch2, ch3, ch4, ch5, ch6) { return id.charAt(1) === ch1 && id.charAt(2) === ch2 && id.charAt(3) === ch3 && id.charAt(4) === ch4 && id.charAt(5) === ch5 && id.charAt(6) === ch6; } static cse7(id, ch1, ch2, ch3, ch4, ch5, ch6, ch7) { return id.charAt(1) === ch1 && id.charAt(2) === ch2 && id.charAt(3) === ch3 && id.charAt(4) === ch4 && id.charAt(5) === ch5 && id.charAt(6) === ch6 && id.charAt(7) === ch7; } getKeyword(id) { if (id.length === 1 || id.length > 10) { return TokenType.IDENTIFIER; } /* istanbul ignore next */ switch (id.length) { case 2: switch (id.charAt(0)) { case 'i': switch (id.charAt(1)) { case 'f': return TokenType.IF; case 'n': return TokenType.IN; default: break; } break; case 'd': if (id.charAt(1) === 'o') { return TokenType.DO; } break; } break; case 3: switch (id.charAt(0)) { case 'v': if (Tokenizer.cse2(id, 'a', 'r')) { return TokenType.VAR; } break; case 'f': if (Tokenizer.cse2(id, 'o', 'r')) { return TokenType.FOR; } break; case 'n': if (Tokenizer.cse2(id, 'e', 'w')) { return TokenType.NEW; } break; case 't': if (Tokenizer.cse2(id, 'r', 'y')) { return TokenType.TRY; } break; case 'l': if (Tokenizer.cse2(id, 'e', 't')) { return TokenType.LET; } break; } break; case 4: switch (id.charAt(0)) { case 't': if (Tokenizer.cse3(id, 'h', 'i', 's')) { return TokenType.THIS; } else if (Tokenizer.cse3(id, 'r', 'u', 'e')) { return TokenType.TRUE; } break; case 'n': if (Tokenizer.cse3(id, 'u', 'l', 'l')) { return TokenType.NULL; } break; case 'e': if (Tokenizer.cse3(id, 'l', 's', 'e')) { return TokenType.ELSE; } else if (Tokenizer.cse3(id, 'n', 'u', 'm')) { return TokenType.ENUM; } break; case 'c': if (Tokenizer.cse3(id, 'a', 's', 'e')) { return TokenType.CASE; } break; case 'v': if (Tokenizer.cse3(id, 'o', 'i', 'd')) { return TokenType.VOID; } break; case 'w': if (Tokenizer.cse3(id, 'i', 't', 'h')) { return TokenType.WITH; } break; } break; case 5: switch (id.charAt(0)) { case 'a': if (Tokenizer.cse4(id, 's', 'y', 'n', 'c')) { return TokenType.ASYNC; } if (Tokenizer.cse4(id, 'w', 'a', 'i', 't')) { return TokenType.AWAIT; } break; case 'w': if (Tokenizer.cse4(id, 'h', 'i', 'l', 'e')) { return TokenType.WHILE; } break; case 'b': if (Tokenizer.cse4(id, 'r', 'e', 'a', 'k')) { return TokenType.BREAK; } break; case 'f': if (Tokenizer.cse4(id, 'a', 'l', 's', 'e')) { return TokenType.FALSE; } break; case 'c': if (Tokenizer.cse4(id, 'a', 't', 'c', 'h')) { return TokenType.CATCH; } else if (Tokenizer.cse4(id, 'o', 'n', 's', 't')) { return TokenType.CONST; } else if (Tokenizer.cse4(id, 'l', 'a', 's', 's')) { return TokenType.CLASS; } break; case 't': if (Tokenizer.cse4(id, 'h', 'r', 'o', 'w')) { return TokenType.THROW; } break; case 'y': if (Tokenizer.cse4(id, 'i', 'e', 'l', 'd')) { return TokenType.YIELD; } break; case 's': if (Tokenizer.cse4(id, 'u', 'p', 'e', 'r')) { return TokenType.SUPER; } break; } break; case 6: switch (id.charAt(0)) { case 'r': if (Tokenizer.cse5(id, 'e', 't', 'u', 'r', 'n')) { return TokenType.RETURN; } break; case 't': if (Tokenizer.cse5(id, 'y', 'p', 'e', 'o', 'f')) { return TokenType.TYPEOF; } break; case 'd': if (Tokenizer.cse5(id, 'e', 'l', 'e', 't', 'e')) { return TokenType.DELETE; } break; case 's': if (Tokenizer.cse5(id, 'w', 'i', 't', 'c', 'h')) { return TokenType.SWITCH; } break; case 'e': if (Tokenizer.cse5(id, 'x', 'p', 'o', 'r', 't')) { return TokenType.EXPORT; } break; case 'i': if (Tokenizer.cse5(id, 'm', 'p', 'o', 'r', 't')) { return TokenType.IMPORT; } break; } break; case 7: switch (id.charAt(0)) { case 'd': if (Tokenizer.cse6(id, 'e', 'f', 'a', 'u', 'l', 't')) { return TokenType.DEFAULT; } break; case 'f': if (Tokenizer.cse6(id, 'i', 'n', 'a', 'l', 'l', 'y')) { return TokenType.FINALLY; } break; case 'e': if (Tokenizer.cse6(id, 'x', 't', 'e', 'n', 'd', 's')) { return TokenType.EXTENDS; } break; } break; case 8: switch (id.charAt(0)) { case 'f': if (Tokenizer.cse7(id, 'u', 'n', 'c', 't', 'i', 'o', 'n')) { return TokenType.FUNCTION; } break; case 'c': if (Tokenizer.cse7(id, 'o', 'n', 't', 'i', 'n', 'u', 'e')) { return TokenType.CONTINUE; } break; case 'd': if (Tokenizer.cse7(id, 'e', 'b', 'u', 'g', 'g', 'e', 'r')) { return TokenType.DEBUGGER; } break; } break; case 10: if (id === 'instanceof') { return TokenType.INSTANCEOF; } break; } return TokenType.IDENTIFIER; } skipSingleLineComment(offset) { this.index += offset; while (this.index < this.source.length) { /** * @type {Number} */ let chCode = this.source.charCodeAt(this.index); this.index++; if (isLineTerminator(chCode)) { this.hasLineTerminatorBeforeNext = true; if (chCode === 0xD /* "\r" */ && this.source.charCodeAt(this.index) === 0xA /* "\n" */) { this.index++; } this.lineStart = this.index; this.line++; return; } } } skipMultiLineComment() { this.index += 2; const length = this.source.length; let isLineStart = false; while (this.index < length) { let chCode = this.source.charCodeAt(this.index); if (chCode < 0x80) { switch (chCode) { case 42: // "*" // Block comment ends with "*/". if (this.source.charAt(this.index + 1) === '/') { this.index = this.index + 2; return isLineStart; } this.index++; break; case 10: // "\n" isLineStart = true; this.hasLineTerminatorBeforeNext = true; this.index++; this.lineStart = this.index; this.line++; break; case 13: // "\r": isLineStart = true; this.hasLineTerminatorBeforeNext = true; if (this.source.charAt(this.index + 1) === '\n') { this.index++; } this.index++; this.lineStart = this.index; this.line++; break; default: this.index++; } } else if (chCode === 0x2028 || chCode === 0x2029) { isLineStart = true; this.hasLineTerminatorBeforeNext = true; this.index++; this.lineStart = this.index; this.line++; } else { this.index++; } } throw this.createILLEGAL(); } skipComment() { this.hasLineTerminatorBeforeNext = false; let isLineStart = this.index === 0; const length = this.source.length; while (this.index < length) { let chCode = this.source.charCodeAt(this.index); if (isWhiteSpace(chCode)) { this.index++; } else if (isLineTerminator(chCode)) { this.hasLineTerminatorBeforeNext = true; this.index++; if (chCode === 13 /* "\r" */ && this.source.charAt(this.index) === '\n') { this.index++; } this.lineStart = this.index; this.line++; isLineStart = true; } else if (chCode === 47 /* "/" */) { if (this.index + 1 >= length) { break; } chCode = this.source.charCodeAt(this.index + 1); if (chCode === 47 /* "/" */) { this.skipSingleLineComment(2); isLineStart = true; } else if (chCode === 42 /* "*" */) { isLineStart = this.skipMultiLineComment() || isLineStart; } else { break; } } else if (!this.moduleIsTheGoalSymbol && isLineStart && chCode === 45 /* "-" */) { if (this.index + 2 >= length) { break; } // U+003E is ">" if (this.source.charAt(this.index + 1) === '-' && this.source.charAt(this.index + 2) === '>') { // "-->" is a single-line comment this.skipSingleLineComment(3); } else { break; } } else if (!this.moduleIsTheGoalSymbol && chCode === 60 /* "<" */) { if (this.source.slice(this.index + 1, this.index + 4) === '!--') { this.skipSingleLineComment(4); isLineStart = true; } else { break; } } else { break; } } } scanHexEscape2() { if (this.index + 2 > this.source.length) { return -1; } let r1 = getHexValue(this.source.charAt(this.index)); if (r1 === -1) { return -1; } let r2 = getHexValue(this.source.charAt(this.index + 1)); if (r2 === -1) { return -1; } this.index += 2; return r1 << 4 | r2; } scanUnicode() { if (this.source.charAt(this.index) === '{') { // \u{HexDigits} let i = this.index + 1; let hexDigits = 0, ch; while (i < this.source.length) { ch = this.source.charAt(i); let hex = getHexValue(ch); if (hex === -1) { break; } hexDigits = hexDigits << 4 | hex; if (hexDigits > 0x10FFFF) { throw this.createILLEGAL(); } i++; } if (ch !== '}') { throw this.createILLEGAL(); } if (i === this.index + 1) { ++this.index; // This is so that the error is 'Unexpected "}"' instead of 'Unexpected "{"'. throw this.createILLEGAL(); } this.index = i + 1; return hexDigits; } // \uHex4Digits if (this.index + 4 > this.source.length) { return -1; } let r1 = getHexValue(this.source.charAt(this.index)); if (r1 === -1) { return -1; } let r2 = getHexValue(this.source.charAt(this.index + 1)); if (r2 === -1) { return -1; } let r3 = getHexValue(this.source.charAt(this.index + 2)); if (r3 === -1) { return -1; } let r4 = getHexValue(this.source.charAt(this.index + 3)); if (r4 === -1) { return -1; } this.index += 4; return r1 << 12 | r2 << 8 | r3 << 4 | r4; } getEscapedIdentifier() { let id = ''; let check = isIdentifierStart; while (this.index < this.source.length) { let ch = this.source.charAt(this.index); let code = ch.charCodeAt(0); let start = this.index; ++this.index; if (ch === '\\') { if (this.index >= this.source.length) { throw this.createILLEGAL(); } if (this.source.charAt(this.index) !== 'u') { throw this.createILLEGAL(); } ++this.index; code = this.scanUnicode(); if (code < 0) { throw this.createILLEGAL(); } ch = fromCodePoint(code); } else if (code >= 0xD800 && code <= 0xDBFF) { if (this.index >= this.source.length) { throw this.createILLEGAL(); } let lowSurrogateCode = this.source.charCodeAt(this.index); ++this.index; if (!(lowSurrogateCode >= 0xDC00 && lowSurrogateCode <= 0xDFFF)) { throw this.createILLEGAL(); } code = decodeUtf16(code, lowSurrogateCode); ch = fromCodePoint(code); } if (!check(code)) { if (id.length < 1) { throw this.createILLEGAL(); } this.index = start; return id; } check = isIdentifierPart; id += ch; } return id; } getIdentifier() { let start = this.index; let l = this.source.length; let i = this.index; let check = isIdentifierStart; while (i < l) { let ch = this.source.charAt(i); let code = ch.charCodeAt(0); if (ch === '\\' || code >= 0xD800 && code <= 0xDBFF) { // Go back and try the hard one. this.index = start; return this.getEscapedIdentifier(); } if (!check(code)) { this.index = i; return this.source.slice(start, i); } ++i; check = isIdentifierPart; } this.index = i; return this.source.slice(start, i); } scanIdentifier() { let startLocation = this.getLocation(); let start = this.index; // Backslash (U+005C) starts an escaped character. let id = this.source.charAt(this.index) === '\\' ? this.getEscapedIdentifier() : this.getIdentifier(); let slice = this.getSlice(start, startLocation); slice.text = id; let hasEscape = this.index - start !== id.length; let type = this.getKeyword(id); if (hasEscape && type !== TokenType.IDENTIFIER) { type = TokenType.ESCAPED_KEYWORD; } return { type, value: id, slice, escaped: hasEscape }; } getLocation() { return { line: this.startLine + 1, column: this.startIndex - this.startLineStart, offset: this.startIndex, }; } getLastTokenEndLocation() { return { line: this.lastLine + 1, column: this.lastIndex - this.lastLineStart, offset: this.lastIndex, }; } getSlice(start, startLocation) { return { text: this.source.slice(start, this.index), start, startLocation, end: this.index }; } scanPunctuatorHelper() { let ch1 = this.source.charAt(this.index); switch (ch1) { // Check for most common single-character punctuators. case '.': { let ch2 = this.source.charAt(this.index + 1); if (ch2 !== '.') return TokenType.PERIOD; let ch3 = this.source.charAt(this.index + 2); if (ch3 !== '.') return TokenType.PERIOD; return TokenType.ELLIPSIS; } case '(': return TokenType.LPAREN; case ')': case ';': case ',': return ONE_CHAR_PUNCTUATOR[ch1.charCodeAt(0)]; case '{': return TokenType.LBRACE; case '}': case '[': case ']': case ':': case '?': case '~': return ONE_CHAR_PUNCTUATOR[ch1.charCodeAt(0)]; default: // "=" (U+003D) marks an assignment or comparison operator. if (this.index + 1 < this.source.length && this.source.charAt(this.index + 1) === '=') { switch (ch1) { case '=': if (this.index + 2 < this.source.length && this.source.charAt(this.index + 2) === '=') { return TokenType.EQ_STRICT; } return TokenType.EQ; case '!': if (this.index + 2 < this.source.length && this.source.charAt(this.index + 2) === '=') { return TokenType.NE_STRICT; } return TokenType.NE; case '|': return TokenType.ASSIGN_BIT_OR; case '+': return TokenType.ASSIGN_ADD; case '-': return TokenType.ASSIGN_SUB; case '*': return TokenType.ASSIGN_MUL; case '<': return TokenType.LTE; case '>': return TokenType.GTE; case '/': return TokenType.ASSIGN_DIV; case '%': return TokenType.ASSIGN_MOD; case '^': return TokenType.ASSIGN_BIT_XOR; case '&': return TokenType.ASSIGN_BIT_AND; // istanbul ignore next default: break; // failed } } } if (this.index + 1 < this.source.length) { let ch2 = this.source.charAt(this.index + 1); if (ch1 === ch2) { if (this.index + 2 < this.source.length) { let ch3 = this.source.charAt(this.index + 2); if (ch1 === '>' && ch3 === '>') { // 4-character punctuator: >>>= if (this.index + 3 < this.source.length && this.source.charAt(this.index + 3) === '=') { return TokenType.ASSIGN_SHR_UNSIGNED; } return TokenType.SHR_UNSIGNED; } if (ch1 === '<' && ch3 === '=') { return TokenType.ASSIGN_SHL; } if (ch1 === '>' && ch3 === '=') { return TokenType.ASSIGN_SHR; } if (ch1 === '*' && ch3 === '=') { return TokenType.ASSIGN_EXP; } } // Other 2-character punctuators: ++ -- << >> && || switch (ch1) { case '*': return TokenType.EXP; case '+': return TokenType.INC; case '-': return TokenType.DEC; case '<': return TokenType.SHL; case '>': return TokenType.SHR; case '&': return TokenType.AND; case '|': return TokenType.OR; // istanbul ignore next default: break; // failed } } else if (ch1 === '=' && ch2 === '>') { return TokenType.ARROW; } } return ONE_CHAR_PUNCTUATOR[ch1.charCodeAt(0)]; } // 7.7 Punctuators scanPunctuator() { let startLocation = this.getLocation(); let start = this.index; let subType = this.scanPunctuatorHelper(); this.index += subType.name.length; return { type: subType, value: subType.name, slice: this.getSlice(start, startLocation) }; } scanHexLiteral(start, startLocation) { let i = this.index; while (i < this.source.length) { let ch = this.source.charAt(i); let hex = getHexValue(ch); if (hex === -1) { break; } i++; } if (this.index === i) { throw this.createILLEGAL(); } if (i < this.source.length && isIdentifierStart(this.source.charCodeAt(i))) { throw this.createILLEGAL(); } this.index = i; let slice = this.getSlice(start, startLocation); return { type: TokenType.NUMBER, value: parseInt(slice.text.substr(2), 16), slice }; } scanBinaryLiteral(start, startLocation) { let offset = this.index - start; while (this.index < this.source.length) { let ch = this.source.charAt(this.index); if (ch !== '0' && ch !== '1') { break; } this.index++; } if (this.index - start <= offset) { throw this.createILLEGAL(); } if (this.index < this.source.length && (isIdentifierStart(this.source.charCodeAt(this.index)) || isDecimalDigit(this.source.charCodeAt(this.index)))) { throw this.createILLEGAL(); } return { type: TokenType.NUMBER, value: parseInt(this.getSlice(start, startLocation).text.substr(offset), 2), slice: this.getSlice(start, startLocation), octal: false, noctal: false, }; } scanOctalLiteral(start, startLocation) { while (this.index < this.source.length) { let ch = this.source.charAt(this.index); if (ch >= '0' && ch <= '7') { this.index++; } else if (isIdentifierPart(ch.charCodeAt(0))) { throw this.createILLEGAL(); } else { break; } } if (this.index - start === 2) { throw this.createILLEGAL(); } return { type: TokenType.NUMBER, value: parseInt(this.getSlice(start, startLocation).text.substr(2), 8), slice: this.getSlice(start, startLocation), octal: false, noctal: false, }; } scanLegacyOctalLiteral(start, startLocation) { let isOctal = true; while (this.index < this.source.length) { let ch = this.source.charAt(this.index); if (ch >= '0' && ch <= '7') { this.index++; } else if (ch === '8' || ch === '9') { isOctal = false; this.index++; } else if (isIdentifierPart(ch.charCodeAt(0))) { throw this.createILLEGAL(); } else { break; } } let slice = this.getSlice(start, startLocation); if (!isOctal) { this.eatDecimalLiteralSuffix(); return { type: TokenType.NUMBER, slice, value: +slice.text, octal: true, noctal: !isOctal, }; } return { type: TokenType.NUMBER, slice, value: parseInt(slice.text.substr(1), 8), octal: true, noctal: !isOctal, }; } scanNumericLiteral() { let ch = this.source.charAt(this.index); // assert(ch === "." || "0" <= ch && ch <= "9") let startLocation = this.getLocation(); let start = this.index; if (ch === '0') { this.index++; if (this.index < this.source.length) { ch = this.source.charAt(this.index); if (ch === 'x' || ch === 'X') { this.index++; return this.scanHexLiteral(start, startLocation); } else if (ch === 'b' || ch === 'B') { this.index++; return this.scanBinaryLiteral(start, startLocation); } else if (ch === 'o' || ch === 'O') { this.index++; return this.scanOctalLiteral(start, startLocation); } else if (ch >= '0' && ch <= '9') { return this.scanLegacyOctalLiteral(start, startLocation); } } else { let slice = this.getSlice(start, startLocation); return { type: TokenType.NUMBER, value: +slice.text, slice, octal: false, noctal: false, }; } } else if (ch !== '.') { // Must be "1".."9" ch = this.source.charAt(this.index); while (ch >= '0' && ch <= '9') { this.index++; if (this.index === this.source.length) { let slice = this.getSlice(start, startLocation); return { type: TokenType.NUMBER, value: +slice.text, slice, octal: false, noctal: false, }; } ch = this.source.charAt(this.index); } } this.eatDecimalLiteralSuffix(); if (this.index !== this.source.length && isIdentifierStart(this.source.charCodeAt(this.index))) { throw this.createILLEGAL(); } let slice = this.getSlice(start, startLocation); return { type: TokenType.NUMBER, value: +slice.text, slice, octal: false, noctal: false, }; } eatDecimalLiteralSuffix() { let ch = this.source.charAt(this.index); if (ch === '.') { this.index++; if (this.index === this.source.length) { return; } ch = this.source.charAt(this.index); while (ch >= '0' && ch <= '9') { this.index++; if (this.index === this.source.length) { return; } ch = this.source.charAt(this.index); } } // EOF not reached here if (ch === 'e' || ch === 'E') { this.index++; if (this.index === this.source.length) { throw this.createILLEGAL(); } ch = this.source.charAt(this.index); if (ch === '+' || ch === '-') { this.index++; if (this.index === this.source.length) { throw this.createILLEGAL(); } ch = this.source.charAt(this.index); } if (ch >= '0' && ch <= '9') { while (ch >= '0' && ch <= '9') { this.index++; if (this.index === this.source.length) { break; } ch = this.source.charAt(this.index); } } else { throw this.createILLEGAL(); } } } scanStringEscape(str, octal) { this.index++; if (this.index === this.source.length) { throw this.createILLEGAL(); } let ch = this.source.charAt(this.index); if (isLineTerminator(ch.charCodeAt(0))) { this.index++; if (ch === '\r' && this.source.charAt(this.index) === '\n') { this.index++; } this.lineStart = this.index; this.line++; } else { switch (ch) { case 'n': str += '\n'; this.index++; break; case 'r': str += '\r'; this.index++; break; case 't': str += '\t'; this.index++; break; case 'u': case 'x': { let unescaped; this.index++; if (this.index >= this.source.length) { throw this.createILLEGAL(); } unescaped = ch === 'u' ? this.scanUnicode() : this.scanHexEscape2(); if (unescaped < 0) { throw this.createILLEGAL(); } str += fromCodePoint(unescaped); break; } case 'b': str += '\b'; this.index++; break; case 'f': str += '\f'; this.index++; break; case 'v': str += '\u000B'; this.index++; break; default: if (ch >= '0' && ch <= '7') { let octalStart = this.index; let octLen = 1; // 3 digits are only allowed when string starts // with 0, 1, 2, 3 if (ch >= '0' && ch <= '3') { octLen = 0; } let code = 0; while (octLen < 3 && ch >= '0' && ch <= '7') { this.index++; if (octLen > 0 || ch !== '0') { octal = this.source.slice(octalStart, this.index); } code *= 8; code += ch - '0'; octLen++; if (this.index === this.source.length) { throw this.createILLEGAL(); } ch = this.source.charAt(this.index); } if (code === 0 && octLen === 1 && (ch === '8' || ch === '9')) { octal = this.source.slice(octalStart, this.index + 1); } str += String.fromCharCode(code); } else if (ch === '8' || ch === '9') { throw this.createILLEGAL(); } else { str += ch; this.index++; } } } return [str, octal]; } // 7.8.4 String Literals scanStringLiteral() { let str = ''; let quote = this.source.charAt(this.index); // assert((quote === "\"" || quote === """), "String literal must starts with a quote") let startLocation = this.getLocation(); let start = this.index; this.index++; let octal = null; while (this.index < this.source.length) { let ch = this.source.charAt(this.index); if (ch === quote) { this.index++; return { type: TokenType.STRING, slice: this.getSlice(start, startLocation), str, octal }; } else if (ch === '\\') { [str, octal] = this.scanStringEscape(str, octal); } else if (isLineTerminator(ch.charCodeAt(0))) { throw this.createILLEGAL(); } else { str += ch; this.index++; } } throw this.createILLEGAL(); } scanTemplateElement() { let startLocation = this.getLocation(); let start = this.index; this.index++; while (this.index < this.source.length) { let ch = this.source.charCodeAt(this.index); switch (ch) { case 0x60: { // ` this.index++; return { type: TokenType.TEMPLATE, tail: true, slice: this.getSlice(start, startLocation) }; } case 0x24: { // $ if (this.source.charCodeAt(this.index + 1) === 0x7B) { // { this.index += 2; return { type: TokenType.TEMPLATE, tail: false, slice: this.getSlice(start, startLocation) }; } this.index++; break; } case 0x5C: { // \\ let octal = this.scanStringEscape('', null)[1]; if (octal != null) { throw this.createError(ErrorMessages.NO_OCTALS_IN_TEMPLATES); } break; } case 0x0D: { // \r this.line++; this.index++; if (this.index < this.source.length && this.source.charAt(this.index) === '\n') { this.index++; } this.lineStart = this.index; break; } case 0x0A: // \r case 0x2028: case 0x2029: { this.line++; this.index++; this.lineStart = this.index; break; } default: this.index++; } } throw this.createILLEGAL(); } scanRegExp(str) { let startLocation = this.getLocation(); let start = this.index; let terminated = false; let classMarker = false; while (this.index < this.source.length) { let ch = this.source.charAt(this.index); if (ch === '\\') { str += ch; this.index++; ch = this.source.charAt(this.index); // ECMA-262 7.8.5 if (isLineTerminator(ch.charCodeAt(0))) { throw this.createError(ErrorMessages.UNTERMINATED_REGEXP); } str += ch; this.index++; } else if (isLineTerminator(ch.charCodeAt(0))) { throw this.createError(ErrorMessages.UNTERMINATED_REGEXP); } else { if (classMarker) { if (ch === ']') { classMarker = false; } } else if (ch === '/') { terminated = true; str += ch; this.index++; break; } else if (ch === '[') { classMarker = true; } str += ch; this.index++; } } if (!terminated) { throw this.createError(ErrorMessages.UNTERMINATED_REGEXP); } while (this.index < this.source.length) { let ch = this.source.charAt(this.index); if (ch === '\\') { throw this.createError(ErrorMessages.INVALID_REGEXP_FLAGS); } if (!isIdentifierPart(ch.charCodeAt(0))) { break; } this.index++; str += ch; } return { type: TokenType.REGEXP, value: str, slice: this.getSlice(start, startLocation) }; } advance() { let startLocation = this.getLocation(); this.lastIndex = this.index; this.lastLine = this.line; this.lastLineStart = this.lineStart; this.skipComment(); this.startIndex = this.index; this.startLine = this.line; this.startLineStart = this.lineStart; if (this.lastIndex === 0) { this.lastIndex = this.index; this.lastLine = this.line; this.lastLineStart = this.lineStart; } if (this.index >= this.source.length) { return { type: TokenType.EOS, slice: this.getSlice(this.index, startLocation) }; } let charCode = this.source.charCodeAt(this.index); if (charCode < 0x80) { if (PUNCTUATOR_START[charCode]) { return this.scanPunctuator(); } if (isIdentifierStart(charCode) || charCode === 0x5C /* backslash (\) */) { return this.scanIdentifier(); } // Dot (.) U+002E can also start a floating-point number, hence the need // to check the next character. if (charCode === 0x2E) { if (this.index + 1 < this.source.length && isDecimalDigit(this.source.charCodeAt(this.index + 1))) { return this.scanNumericLiteral(); } return this.scanPunctuator(); } // String literal starts with single quote (U+0027) or double quote (U+0022). if (charCode === 0x27 || charCode === 0x22) { return this.scanStringLiteral(); } // Template literal starts with back quote (U+0060) if (charCode === 0x60) { return this.scanTemplateElement(); } if (charCode /* "0" */ >= 0x30 && charCode <= 0x39 /* "9" */) { return this.scanNumericLiteral(); } // Slash (/) U+002F can also start a regex. throw this.createILLEGAL(); } else { if (isIdentifierStart(charCode) || charCode >= 0xD800 && charCode <= 0xDBFF) { return this.scanIdentifier(); } throw this.createILLEGAL(); } } eof() { return this.lookahead.type === TokenType.EOS; } lex() { let prevToken = this.lookahead; this.lookahead = this.advance(); this.tokenIndex++; return prevToken; } }
apache-2.0
deleidos/digitaledge-platform
commons-core/src/main/script/boot/apt_mirror_update.sh
12672
#!/bin/bash # # Apache License # Version 2.0, January 2004 # http://www.apache.org/licenses/ # # TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION # # 1. Definitions. # # "License" shall mean the terms and conditions for use, reproduction, # and distribution as defined by Sections 1 through 9 of this document. # # "Licensor" shall mean the copyright owner or entity authorized by # the copyright owner that is granting the License. # # "Legal Entity" shall mean the union of the acting entity and all # other entities that control, are controlled by, or are under common # control with that entity. For the purposes of this definition, # "control" means (i) the power, direct or indirect, to cause the # direction or management of such entity, whether by contract or # otherwise, or (ii) ownership of fifty percent (50%) or more of the # outstanding shares, or (iii) beneficial ownership of such entity. # # "You" (or "Your") shall mean an individual or Legal Entity # exercising permissions granted by this License. # # "Source" form shall mean the preferred form for making modifications, # including but not limited to software source code, documentation # source, and configuration files. # # "Object" form shall mean any form resulting from mechanical # transformation or translation of a Source form, including but # not limited to compiled object code, generated documentation, # and conversions to other media types. # # "Work" shall mean the work of authorship, whether in Source or # Object form, made available under the License, as indicated by a # copyright notice that is included in or attached to the work # (an example is provided in the Appendix below). # # "Derivative Works" shall mean any work, whether in Source or Object # form, that is based on (or derived from) the Work and for which the # editorial revisions, annotations, elaborations, or other modifications # represent, as a whole, an original work of authorship. For the purposes # of this License, Derivative Works shall not include works that remain # separable from, or merely link (or bind by name) to the interfaces of, # the Work and Derivative Works thereof. # # "Contribution" shall mean any work of authorship, including # the original version of the Work and any modifications or additions # to that Work or Derivative Works thereof, that is intentionally # submitted to Licensor for inclusion in the Work by the copyright owner # or by an individual or Legal Entity authorized to submit on behalf of # the copyright owner. For the purposes of this definition, "submitted" # means any form of electronic, verbal, or written communication sent # to the Licensor or its representatives, including but not limited to # communication on electronic mailing lists, source code control systems, # and issue tracking systems that are managed by, or on behalf of, the # Licensor for the purpose of discussing and improving the Work, but # excluding communication that is conspicuously marked or otherwise # designated in writing by the copyright owner as "Not a Contribution." # # "Contributor" shall mean Licensor and any individual or Legal Entity # on behalf of whom a Contribution has been received by Licensor and # subsequently incorporated within the Work. # # 2. Grant of Copyright License. Subject to the terms and conditions of # this License, each Contributor hereby grants to You a perpetual, # worldwide, non-exclusive, no-charge, royalty-free, irrevocable # copyright license to reproduce, prepare Derivative Works of, # publicly display, publicly perform, sublicense, and distribute the # Work and such Derivative Works in Source or Object form. # # 3. Grant of Patent License. Subject to the terms and conditions of # this License, each Contributor hereby grants to You a perpetual, # worldwide, non-exclusive, no-charge, royalty-free, irrevocable # (except as stated in this section) patent license to make, have made, # use, offer to sell, sell, import, and otherwise transfer the Work, # where such license applies only to those patent claims licensable # by such Contributor that are necessarily infringed by their # Contribution(s) alone or by combination of their Contribution(s) # with the Work to which such Contribution(s) was submitted. If You # institute patent litigation against any entity (including a # cross-claim or counterclaim in a lawsuit) alleging that the Work # or a Contribution incorporated within the Work constitutes direct # or contributory patent infringement, then any patent licenses # granted to You under this License for that Work shall terminate # as of the date such litigation is filed. # # 4. Redistribution. You may reproduce and distribute copies of the # Work or Derivative Works thereof in any medium, with or without # modifications, and in Source or Object form, provided that You # meet the following conditions: # # (a) You must give any other recipients of the Work or # Derivative Works a copy of this License; and # # (b) You must cause any modified files to carry prominent notices # stating that You changed the files; and # # (c) You must retain, in the Source form of any Derivative Works # that You distribute, all copyright, patent, trademark, and # attribution notices from the Source form of the Work, # excluding those notices that do not pertain to any part of # the Derivative Works; and # # (d) If the Work includes a "NOTICE" text file as part of its # distribution, then any Derivative Works that You distribute must # include a readable copy of the attribution notices contained # within such NOTICE file, excluding those notices that do not # pertain to any part of the Derivative Works, in at least one # of the following places: within a NOTICE text file distributed # as part of the Derivative Works; within the Source form or # documentation, if provided along with the Derivative Works; or, # within a display generated by the Derivative Works, if and # wherever such third-party notices normally appear. The contents # of the NOTICE file are for informational purposes only and # do not modify the License. You may add Your own attribution # notices within Derivative Works that You distribute, alongside # or as an addendum to the NOTICE text from the Work, provided # that such additional attribution notices cannot be construed # as modifying the License. # # You may add Your own copyright statement to Your modifications and # may provide additional or different license terms and conditions # for use, reproduction, or distribution of Your modifications, or # for any such Derivative Works as a whole, provided Your use, # reproduction, and distribution of the Work otherwise complies with # the conditions stated in this License. # # 5. Submission of Contributions. Unless You explicitly state otherwise, # any Contribution intentionally submitted for inclusion in the Work # by You to the Licensor shall be under the terms and conditions of # this License, without any additional terms or conditions. # Notwithstanding the above, nothing herein shall supersede or modify # the terms of any separate license agreement you may have executed # with Licensor regarding such Contributions. # # 6. Trademarks. This License does not grant permission to use the trade # names, trademarks, service marks, or product names of the Licensor, # except as required for reasonable and customary use in describing the # origin of the Work and reproducing the content of the NOTICE file. # # 7. Disclaimer of Warranty. Unless required by applicable law or # agreed to in writing, Licensor provides the Work (and each # Contributor provides its Contributions) on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied, including, without limitation, any warranties or conditions # of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A # PARTICULAR PURPOSE. You are solely responsible for determining the # appropriateness of using or redistributing the Work and assume any # risks associated with Your exercise of permissions under this License. # # 8. Limitation of Liability. In no event and under no legal theory, # whether in tort (including negligence), contract, or otherwise, # unless required by applicable law (such as deliberate and grossly # negligent acts) or agreed to in writing, shall any Contributor be # liable to You for damages, including any direct, indirect, special, # incidental, or consequential damages of any character arising as a # result of this License or out of the use or inability to use the # Work (including but not limited to damages for loss of goodwill, # work stoppage, computer failure or malfunction, or any and all # other commercial damages or losses), even if such Contributor # has been advised of the possibility of such damages. # # 9. Accepting Warranty or Additional Liability. While redistributing # the Work or Derivative Works thereof, You may choose to offer, # and charge a fee for, acceptance of support, warranty, indemnity, # or other liability obligations and/or rights consistent with this # License. However, in accepting such obligations, You may act only # on Your own behalf and on Your sole responsibility, not on behalf # of any other Contributor, and only if You agree to indemnify, # defend, and hold each Contributor harmless for any liability # incurred by, or claims asserted against, such Contributor by reason # of your accepting any such warranty or additional liability. # # END OF TERMS AND CONDITIONS # # APPENDIX: How to apply the Apache License to your work. # # To apply the Apache License to your work, attach the following # boilerplate notice, with the fields enclosed by brackets "{}" # replaced with your own identifying information. (Don't include # the brackets!) The text should be enclosed in the appropriate # comment syntax for the file format. We also recommend that a # file or class name and description of purpose be included on the # same "printed page" as the copyright notice for easier # identification within third-party archives. # # Copyright {yyyy} {name of copyright owner} # # 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. # set -x # Updates the internal mirror from contents in s3 source /etc/rtwsrc if [ -z "$RTWS_APT_MIRROR_ROOT_LOCATION" ]; then RTWS_APT_MIRROR_ROOT_LOCATION="/mnt/rdafs/" echo "Defaulting RTWS_APT_MIRROR_ROOT_LOCATION to $RTWS_APT_MIRROR_ROOT_LOCATION" fi if [ ! -d $RTWS_APT_MIRROR_ROOT_LOCATION ]; then mkdir -pv $RTWS_APT_MIRROR_ROOT_LOCATION fi if [[ "$(whoami)" != "root" ]]; then echo "ERROR: You must be root to proceed..." exit 1 fi if [ -z "$RTWS_MOUNT_DEVICE" ]; then echo "ERROR: RTWS_MOUNT_DEVICE not defined..." exit 1 fi s3cmd -c /home/rtws/.s3cfg -rf get s3://$RTWS_MOUNT_DEVICE/mirror $RTWS_APT_MIRROR_ROOT_LOCATION # Link mirrored domain content excluding their domain prefix cd $RTWS_APT_MIRROR_ROOT_LOCATION/mirror/ for domain in $(/bin/ls -d *) do cd $domain for dir in $(/bin/ls -d *) do ln -sf $RTWS_APT_MIRROR_ROOT_LOCATION/mirror/$domain/$dir /var/www/. done cd - done
apache-2.0
worldline/TrainingJEEAngular
trainingapp/src/components/slides/preamble/fwksCompare2/fwksCompare2.ts
696
import {Component, Inject, ElementRef} from '@angular/core'; import {SlideCommon} from '../../slideCommon/slideCommon'; import {Editor} from '../../../editor/editor'; import {EditorTab} from '../../../editorTab/editorTab'; import {HOST_SLIDE_CONTAINER_CLASS} from '../../../../services/constants'; @Component({ selector:'fwksCompare2', templateUrl:'src/components/slides/preamble/fwksCompare2/fwksCompare2.html', styleUrls: ['src/components/slides/preamble/fwksCompare2/fwksCompare2.css'], directives: [Editor, EditorTab] }) export class FwksCompare2 extends SlideCommon{ constructor(elt: ElementRef, @Inject(HOST_SLIDE_CONTAINER_CLASS) hostClass: string) { super(elt, hostClass); } }
apache-2.0
polyaxon/polyaxon
site/docs/intro/builds/introduction.md
932
--- title: "Introduction" sub_link: "builds/introduction" meta_title: "Introduction - Polyaxon quick start tutorial - Core Concepts" meta_description: "Introduction - Become familiar with the ecosystem of Polyaxon tools with a top-level overview and useful links to get you started." visibility: public status: published tags: - tutorials - concepts - quick-start sidebar: "intro" --- ## Deploying with a registry connection In order to build containers in-cluster with Polyaxon, you need to update your deployment with a [registry connection](/docs/setup/connections/registry/). Polyaxon provides several options to connecting and configuring a docker registry. Similar to the options provided in the [integrations docs](/integrations/registries/), you can set any registry of your choice if not mentioned. After configuring a valid registry connection, you can upgrade your deployment or sync your agent's connections:
apache-2.0
carbolymer/blockchain
blockchain-ui-fe/src/app/nodes/nodes.component.html
661
<h2 class="header teal-text text-darken-4">List of nodes in the network</h2> <table class="bordered highlight"> <thead> <tr> <th>Node name</th> <th>Valid chain length</th> </tr> </thead> <tbody> <tr *ngFor="let node of nodes"> <td>{{node.id}}</td> <td>{{node.validChainLength}}</td> <td> <button id="mine-{{node.id}}" (click)="mine(node, $event)" [disabled]="currentlyMiningNodesIds.has(node.id)" class="btn waves-effect waves-light">mine new block</button> </td> </tr> <tr *ngIf="nodes.length === 0"> <td colspan="3">There are no active nodes</td> </tr> </tbody> </table>
apache-2.0
firebase/firebase-admin-java
src/main/java/com/google/firebase/messaging/internal/package-info.java
661
/* * Copyright 2019 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @hide */ package com.google.firebase.messaging.internal;
apache-2.0
lkleen/bitcoin-app
core/src/main/java/org/larsworks/bitcoin/app/core/notifications/NotificationEngine.java
405
package org.larsworks.bitcoin.app.core.notifications; import org.larsworks.bitcoin.app.core.notifications.conditions.Condition; /** * @author Lars Kleen * @since 0.0.1 * Date: 01.02.14 * Time: 13:32 */ public interface NotificationEngine<T> { void addCondition(Condition<T> condition); void removeCondition(Condition<T> condition); void process(T t); }
apache-2.0
wastedge/wastedge-querier
WastedgeQuerier/JavaScript/NewProjectForm.cs
2391
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using SystemEx.Windows.Forms; using WastedgeQuerier.Util; namespace WastedgeQuerier.JavaScript { public partial class NewProjectForm : SystemEx.Windows.Forms.Form { public string ProjectName => _name.Text; public string ProjectLocation => _location.Text; public NewProjectForm() { InitializeComponent(); using (var key = Program.BaseKey) { _location.Text = key.GetValue("Last Project Location") as string ?? Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); } } private void _browse_Click(object sender, EventArgs e) { var form = new FolderBrowser { Title = "Project Location" }; if (form.ShowDialog(this) == DialogResult.OK) _location.Text = form.SelectedPath; } private void _acceptButton_Click(object sender, EventArgs e) { if (_name.Text.Length == 0) { TaskDialogEx.Show(this, "Please enter a name", Text, TaskDialogCommonButtons.OK, TaskDialogIcon.Warning); } else if (!Directory.Exists(_location.Text)) { TaskDialogEx.Show(this, "Please select a valid location", Text, TaskDialogCommonButtons.OK, TaskDialogIcon.Warning); } else { var fullPath = Path.Combine(_location.Text, _name.Text); if (Directory.Exists(fullPath)) { TaskDialogEx.Show(this, $"The directory {fullPath} already exists", Text, TaskDialogCommonButtons.OK, TaskDialogIcon.Warning); } else { using (var key = Program.BaseKey) { key.SetValue("Last Project Location", _location.Text); } DialogResult = DialogResult.OK; } } } } }
apache-2.0
julianche/ixalumninew
config/routes.rb
1895
Rails.application.routes.draw do devise_for :users, :controllers => { registrations: 'registrations' } get "/profiles/search" => "profiles#search" resources :profiles resources :forums do resources :posts end resources :posts, only: [] do resources :comments end # The priority is based upon order of creation: first created -> highest priority. # See how all your routes lay out with "rake routes". # You can have the root of your site routed with "root" root "welcome#welcome" get "/home", to: "welcome#home" # Example of regular route: # get 'products/:id' => 'catalog#view' # Example of named route that can be invoked with purchase_url(id: product.id) # get 'products/:id/purchase' => 'catalog#purchase', as: :purchase # Example resource route (maps HTTP verbs to controller actions automatically): # resources :products # Example resource route with options: # resources :products do # member do # get 'short' # post 'toggle' # end # # collection do # get 'sold' # end # end # Example resource route with sub-resources: # resources :products do # resources :comments, :sales # resource :seller # end # Example resource route with more complex sub-resources: # resources :products do # resources :comments # resources :sales do # get 'recent', on: :collection # end # end # Example resource route with concerns: # concern :toggleable do # post 'toggle' # end # resources :posts, concerns: :toggleable # resources :photos, concerns: :toggleable # Example resource route within a namespace: # namespace :admin do # # Directs /admin/products/* to Admin::ProductsController # # (app/controllers/admin/products_controller.rb) # resources :products # end end
apache-2.0
googleads/googleads-java-lib
modules/dfp_appengine/src/main/java/com/google/api/ads/admanager/jaxws/v202105/RequiredCollectionErrorReason.java
2070
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.api.ads.admanager.jaxws.v202105; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for RequiredCollectionError.Reason. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="RequiredCollectionError.Reason"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="REQUIRED"/> * &lt;enumeration value="TOO_LARGE"/> * &lt;enumeration value="TOO_SMALL"/> * &lt;enumeration value="UNKNOWN"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "RequiredCollectionError.Reason") @XmlEnum public enum RequiredCollectionErrorReason { /** * * A required collection is missing. * * */ REQUIRED, /** * * Collection size is too large. * * */ TOO_LARGE, /** * * Collection size is too small. * * */ TOO_SMALL, /** * * The value returned if the actual value is not exposed by the requested API version. * * */ UNKNOWN; public String value() { return name(); } public static RequiredCollectionErrorReason fromValue(String v) { return valueOf(v); } }
apache-2.0
drausin/libri
libri/author/io/publish/acquirer.go
4183
package publish import ( "bytes" "sync" "github.com/drausin/libri/libri/common/ecid" "github.com/drausin/libri/libri/common/id" "github.com/drausin/libri/libri/common/storage" "github.com/drausin/libri/libri/librarian/api" "github.com/drausin/libri/libri/librarian/client" lclient "github.com/drausin/libri/libri/librarian/client" ) // Acquirer Gets documents from the libri network. type Acquirer interface { // Acquire Gets a document from the libri network using a librarian client. Acquire(docKey id.ID, authorPub []byte, lc api.Getter) (*api.Document, error) } type acquirer struct { clientID ecid.ID orgID ecid.ID clientSigner client.Signer orgSigner client.Signer params *Parameters } // NewAcquirer creates a new Acquirer with the given clientID clientSigner, and params. func NewAcquirer( clientID, orgID ecid.ID, clientSigner, orgSigner client.Signer, params *Parameters, ) Acquirer { return &acquirer{ clientID: clientID, orgID: orgID, clientSigner: clientSigner, orgSigner: orgSigner, params: params, } } func (a *acquirer) Acquire(docKey id.ID, authorPub []byte, lc api.Getter) (*api.Document, error) { rq := client.NewGetRequest(a.clientID, a.orgID, docKey) ctx, cancel, err := client.NewSignedTimeoutContext(a.clientSigner, a.orgSigner, rq, a.params.GetTimeout) if err != nil { return nil, err } rp, err := lc.Get(ctx, rq) cancel() if err != nil { return nil, err } if !bytes.Equal(rq.Metadata.RequestId, rp.Metadata.RequestId) { return nil, client.ErrUnexpectedRequestID } if err := api.ValidateDocument(rp.Value); err != nil { return nil, err } return rp.Value, nil } // SingleStoreAcquirer Gets a document and saves it to internal storage. type SingleStoreAcquirer interface { // Acquire Gets the document with the given key from the libri network and saves it to // internal storage. Acquire(docKey id.ID, authorPub []byte, lc api.Getter) error } type singleStoreAcquirer struct { inner Acquirer docS storage.DocumentStorer } // NewSingleStoreAcquirer creates a new SingleStoreAcquirer from the inner Acquirer and the docS // document storer. func NewSingleStoreAcquirer(inner Acquirer, docS storage.DocumentStorer) SingleStoreAcquirer { return &singleStoreAcquirer{ inner: inner, docS: docS, } } func (a *singleStoreAcquirer) Acquire(docKey id.ID, authorPub []byte, lc api.Getter) error { doc, err := a.inner.Acquire(docKey, authorPub, lc) if err != nil { return err } if err := a.docS.Store(docKey, doc); err != nil { return err } return nil } // MultiStoreAcquirer Gets and stores multiple documents. type MultiStoreAcquirer interface { // Acquire in parallel Gets and stores the documents with the given keys. It balances // between librarian clients for its Put requests. Acquire(docKeys []id.ID, authorPub []byte, cb client.GetterBalancer) error // GetRetryGetter returns a new retrying api.Getter. GetRetryGetter(cb client.GetterBalancer) api.Getter } type multiStoreAcquirer struct { inner SingleStoreAcquirer params *Parameters } // NewMultiStoreAcquirer creates a new MultiStoreAcquirer from the inner SingleStoreAcquirer and // params. func NewMultiStoreAcquirer(inner SingleStoreAcquirer, params *Parameters) MultiStoreAcquirer { return &multiStoreAcquirer{ inner: inner, params: params, } } func (a *multiStoreAcquirer) Acquire( docKeys []id.ID, authorPub []byte, cb client.GetterBalancer, ) error { rlc := a.GetRetryGetter(cb) docKeysChan := make(chan id.ID, a.params.PutParallelism) go loadChan(docKeys, docKeysChan) wg := new(sync.WaitGroup) getErrs := make(chan error, a.params.GetParallelism) for c := uint32(0); c < a.params.GetParallelism; c++ { wg.Add(1) go func() { for docKey := range docKeysChan { if err := a.inner.Acquire(docKey, authorPub, rlc); err != nil { getErrs <- err break } } wg.Done() }() } wg.Wait() close(getErrs) select { case err := <-getErrs: return err default: return nil } } func (a *multiStoreAcquirer) GetRetryGetter(cb client.GetterBalancer) api.Getter { return lclient.NewRetryGetter(cb, true, a.params.GetTimeout) }
apache-2.0
oprochazka/hTBG
public/indexGame.html
3674
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href="./css/style.css"> <link rel="shortcut icon" href="./css/image/king.ico" type="image/x-icon"> <title>Turn based game</title> </head> <body> <div id="playerUI" class="playerUI"> <div id="yourTurn" class="your-turn"> That is your turn!!!!! </div> <div id="nickName" class="nick-name"> Nick: </div> <div class="army-stats"> <div class="header"> Army stats: </div> <div id="armyStats" class="army-body"> </div> <img id="armyStatsImg" class="army-stats-img"> </img> <div id="buyItems" class="buy-items"> </div> </div> <div class="playerStats"> Count army: <span id="countArmy"></span> </br> Count building: <span id="countBuilding"></span> </br> Turn: <span id="playerTurn"> </span> </br> Gold: <span id="playerGold"> </span> </br> </div> <div id="endTurn" class="end-turn"> End Turn </div> <div id="players" class="online-players"> test </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script> <script src="./configure.js"></script> <script src="./client/gameEngine.js"></script> <script src="./shared/tilesDesc.js"></script> <script src="./shared/buildingDesc.js"></script> <script src="./shared/armyDesc.js"></script> <script src="./shared/builderDesc.js"></script> <script src="./shared/objectDesc.js"></script> <script src="./client/toolTip.js"></script> <script src="./client/client.js"></script> <script src="./client/uiDynamic.js"></script> <script src="./client/uiPlayer.js"></script> <script src="./client/utils.js"></script> <script src="./client/contextOption.js"></script> <script src="./client/canvasUi.js"></script> <script src="./client/draw.js"></script> <script src="./shared/playerEntityShared.js"></script> <script src="./client/playerEntity.js"></script> <script src="./shared/builderShared.js"></script> <script src="./client/builder.js"></script> <script src="./client/slideWindow.js"></script> <script src="./shared/fieldShared.js"></script> <script src="./client/field.js"></script> <script src="./shared/tileShared.js"></script> <script src="./client/tile.js"></script> <script src="./shared/buildingShared.js"></script> <script src="./client/building.js"></script> <script src="./shared/armyShared.js"></script> <script src="./client/army.js"></script> <script src="./shared/playerShared.js"></script> <script src="./client/player.js"></script> <script src="./shared/gameManagerShared.js"></script> <script src="./client/gameManager.js"></script> <div class="canvasWrapper"> <canvas class="gameCanvas" id="canvasLayer1" width="1536" height="960" ></canvas> </div> <script src="./client/canvasEngine.js"></script> </body> </html>
apache-2.0
destil/GPS-Averaging
app/src/main/java/org/destil/gpsaveraging/ui/AdManager.java
1678
/* * Copyright 2015 David Vávra * * 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.destil.gpsaveraging.ui; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdView; /** * Manages loading ads. * * @author David Vávra ([email protected]) */ public class AdManager { private final AdView mAdView; public AdManager(AdView adView) { mAdView = adView; } public void load() { AdRequest.Builder builder = new AdRequest.Builder(); builder.addKeyword("geocaching"); builder.addKeyword("gps"); builder.addKeyword("location"); builder.addKeyword("measurements"); builder.addKeyword("places"); builder.addKeyword("check in"); builder.addTestDevice("6E70B945F7D166EA14779C899463B8BC"); // My N7 builder.addTestDevice("197CB241DBFB335DD54A6D050DE58792"); // My N5 builder.addTestDevice("996EE7E77D7181208AF916072F5FFE4C"); // My N5#2 builder.addTestDevice("622AFF2BE01381DB65A2ACAE09D77ABD"); // Genymotion mAdView.loadAd(builder.build()); } public void destroy() { mAdView.destroy(); } }
apache-2.0
AndriyZabavskyy/eiffel-intelligence
src/main/java/com/ericsson/ei/subscriptionhandler/RunSubscription.java
3706
/* Copyright 2017 Ericsson AB. For a full list of individual contributors, please see the commit history. 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 com.ericsson.ei.subscriptionhandler; import java.util.Iterator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.ericsson.ei.jmespath.JmesPathInterface; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; /** * This class represents the mechanism to fetch the rule conditions from the * Subscription Object and match it with the aggregatedObject to check if it is * true. * * @author xjibbal * */ @Component public class RunSubscription { @Autowired private JmesPathInterface jmespath; static Logger log = (Logger) LoggerFactory.getLogger(RunSubscription.class); /** * This method matches every condition specified in the subscription Object * and if all conditions are matched then only the aggregatedObject is * eligible for notification via e-mail or REST POST. * * (AND between conditions in requirements, "OR" between requirements with conditions) * * @param aggregatedObject * @param requirement * @param subscriptionJson * @return boolean */ public boolean runSubscriptionOnObject(String aggregatedObject, Iterator<JsonNode> requirementIterator, JsonNode subscriptionJson) { boolean conditionFulfilled = false; int count_condition_fulfillment = 0; int count_conditions = 0; while (requirementIterator.hasNext()) { JsonNode requirement = requirementIterator.next(); log.info("The fulfilled requirement which will condition checked is : " + requirement.toString()); ArrayNode conditions = (ArrayNode) requirement.get("conditions"); count_condition_fulfillment = 0; count_conditions = conditions.size(); log.info("Conditions of the subscription : " + conditions.toString()); Iterator<JsonNode> conditionIterator = conditions.elements(); while (conditionIterator.hasNext()) { String rule = conditionIterator.next().get("jmespath").toString().replaceAll("^\"|\"$", ""); String new_Rule = rule.replace("'", "\""); log.info("Rule : " + rule); log.info("New Rule after replacing single quote : " + new_Rule); JsonNode result = jmespath.runRuleOnEvent(rule, aggregatedObject); log.info("Result : " + result.toString()); if (result.toString() != null && result.toString() != "false" && !result.toString().equals("[]")){ count_condition_fulfillment++; } } if(count_conditions != 0 && count_condition_fulfillment == count_conditions){ conditionFulfilled = true; } } log.info("The final value of conditionFulfilled is : " + conditionFulfilled); return conditionFulfilled; } }
apache-2.0
nikolai-m/nmatveev
chapter_002/src/main/java/ru/job4j/professions/doctor/package-info.java
152
/** * Package for job4j chapter 2 projects. * * @author Nikolai Matveev * @version 0.1 * @since 14.10.2017 */ package ru.job4j.professions.doctor;
apache-2.0
aragozin/stackviewer
src/main/java/com/vldocking/swing/docking/HeavyWeightDragControler.java
12546
/* VLDocking Framework 3.0 Copyright Lilian Chamontin, 2004-2013 www.vldocking.com [email protected] ------------------------------------------------------------------------ This software is distributed under the LGPL license The fact that you are presently reading this and using this class means that you have had knowledge of the LGPL license and that you accept its terms. You can read the complete license here : http://www.gnu.org/licenses/lgpl.html */ package com.vldocking.swing.docking; import java.awt.Canvas; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Cursor; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Point; import java.awt.Rectangle; import java.awt.Shape; import java.awt.Window; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import java.lang.reflect.Method; import javax.swing.Icon; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLayeredPane; import javax.swing.SwingUtilities; import javax.swing.UIManager; /** A Heavyweight implementation of the drag controler, and its associated classes * * @since 3.0 * @author Lilian Chamontin, vlsolutions. */ class HeavyWeightDragControler extends AbstractDragControler { private boolean paintBackgroundUnderDragRect = UIManager.getBoolean("DragControler.paintBackgroundUnderDragRect"); /** instantiates a controler for a given docking panel*/ HeavyWeightDragControler(DockingDesktop desktop) { super(desktop); } /** find the top most component of this container */ protected Component findComponentAt(Container container, int x, int y) { Rectangle bounds = new Rectangle(); int count = container.getComponentCount(); //ShapePainterStrategy shapePainterStrategy = getShapePainter(container, null); for(int i = 0; i < count; i++) { Component child = container.getComponent(i); if(child.isVisible()) { child.getBounds(bounds); if(bounds.contains(x, y)) { if(child instanceof Container) { // recursive Component found = findComponentAt((Container) child, x - bounds.x, y - bounds.y); if(found != null) { return found; } else { return child; } } else if(! (child instanceof HeavyShape || child instanceof HeavyLabel)) { // skip our dedicated components for heavyweight support return child; // } else if (child != shapePainterStrategy.heavyShape && // child != shapePainterStrategy.heavyShape.label){ // // skip our dedicated components for heavyweight support // return child; } } } } return null; } @Override protected ShapePainterStrategy createShapePainterStrategy(Window w) { return new HWShapePainterStrategy(w); } public Dockable getDockable() { if(dockableDragSource != null) { return dockableDragSource.getDockable(); } else { return null; } } // ----------------------------------------------------------------------------------------------------------- // --------------------------------- you don't want to look at the code underneath this line... -------------- // ----------------------------------------------------------------------------------------------------------- // I'll rewrite it entirely someday as i'm not pleased with it (much too complex) /** This class holds implementation strategies of shapes painting. *<p> * As painting is different when pure Swing is used (glasspane) and * heavyweight components are mixed in (glasspane + canvas). */ private class HWShapePainterStrategy implements ShapePainterStrategy { private DragControlerGlassPane dragGlassPane = new DragControlerGlassPane(HeavyWeightDragControler.this); private Component oldGlassPane = null; private boolean oldGlassPaneVisible = false; private Window window = null; private boolean isDragStarted = false; // heavyweight support private HeavyShape heavyShape; // instanciated only when heavyweight suport is enabled /*public ShapePainterStrategy(){ if (! isLightWeight){ dragGlassPane.setPaintShapes(false); heavyShape = new HeavyShape(); } }*/ public HWShapePainterStrategy(Window window) { this.window = window; dragGlassPane.setPaintShapes(false); heavyShape = new HeavyShape(); } /** show the drag cursor */ public void showDragCursor() { dragGlassPane.showDragCursor(); heavyShape.setCursor(dragGlassPane.getCursor()); } /** show the stop-drag cursor (drag not enabled)*/ public void showStopDragCursor() { dragGlassPane.showStopDragCursor(); heavyShape.setCursor(dragGlassPane.getCursor()); } /** show the stop-drag cursor (drag not enabled)*/ public void showSwapDragCursor() { dragGlassPane.showSwapDragCursor(); heavyShape.setCursor(dragGlassPane.getCursor()); } /** show the float (detached) cursor */ public void showFloatCursor() { dragGlassPane.showFloatCursor(); heavyShape.setCursor(dragGlassPane.getCursor()); } public void repaint() { /* this is a hack that will be refactored : we post a repaint when there is * a need to show a drag shape */ if(dropShape != null) { heavyShape.moveToShape(dropShape); // adjust to the shape before repainting } else if(heavyShape.isVisible()) { heavyShape.setVisible(false); } } public void startDrag(DockableDragSource source) { if(isDragStarted || source == null) { // safety checks return; } Window aboveWindow = this.window; isDragStarted = true; if(heavyShape.getParent() == null) { // first use of the heavyshapes components if(aboveWindow instanceof JFrame) { JFrame fr = (JFrame) aboveWindow; fr.getLayeredPane().add(heavyShape, JLayeredPane.DRAG_LAYER); heavyShape.validate(); fr.getLayeredPane().add(heavyShape.label, JLayeredPane.DRAG_LAYER); } else if(aboveWindow instanceof JDialog) { JDialog dlg = (JDialog) aboveWindow; dlg.getLayeredPane().add(heavyShape, JLayeredPane.DRAG_LAYER); heavyShape.validate(); dlg.getLayeredPane().add(heavyShape.label, JLayeredPane.DRAG_LAYER); } heavyShape.setZOrder(); } heavyShape.label.setName(source.getDockable().getDockKey().getName()); // take a snapshot of the frame... ugly trick, but couldn't find anything better ! heavyShape.startDrag(); if(aboveWindow instanceof JFrame) { oldGlassPane = ((JFrame) aboveWindow).getGlassPane(); oldGlassPaneVisible = oldGlassPane.isVisible(); ((JFrame) aboveWindow).setGlassPane(dragGlassPane); dragGlassPane.setVisible(true); } else if(aboveWindow instanceof JDialog) { oldGlassPane = ((JDialog) aboveWindow).getGlassPane(); oldGlassPaneVisible = oldGlassPane.isVisible(); ((JDialog) aboveWindow).setGlassPane(dragGlassPane); dragGlassPane.setVisible(true); } } public void endDrag() { heavyShape.setVisible(false); Window aboveWindow = this.window;//SwingUtilities.getWindowAncestor(desktop); if(aboveWindow instanceof JFrame) { ((JFrame) aboveWindow).setGlassPane(oldGlassPane); } else if(aboveWindow instanceof JDialog) { ((JDialog) aboveWindow).setGlassPane(oldGlassPane); } oldGlassPane.setVisible(oldGlassPaneVisible); isDragStarted = false; } } /** heavyweight component used to paint shapes on top of heavyweight components */ private class HeavyShape extends Canvas { private static final long serialVersionUID = 1L; private Rectangle cachedShapeBounds; private BufferedImage desktopImage; // used for heavyweight painting private Image subImage; private Rectangle subImageBounds; private ShapeOutlinePainter outlinePainter = new ShapeOutlinePainter(); private HeavyLabel label = new HeavyLabel(); public HeavyShape() { setEnabled(false); // don't override the glaspane cursor } public void setZOrder() { // jdk1.5 only try { //desktop.setComponentZOrder(this, -1); // on top Method m = Container.class.getMethod("setComponentZOrder", new Class[] {Component.class, int.class}); m.invoke(getParent(), new Object[] {this, new Integer(0)}); } catch(Exception ignore) { } label.setZOrder(); } private void startDrag() { Container parent = getParent(); if(paintBackgroundUnderDragRect) { // 2007/02/27 if(desktopImage == null || (desktopImage.getWidth() != parent.getWidth()) || (desktopImage.getHeight() != parent.getHeight())) { desktopImage = (BufferedImage) parent.createImage(parent.getWidth(), parent.getHeight()); subImage = null; } Graphics g = desktopImage.getGraphics(); parent.paint(g); g.dispose(); } } public void paint(Graphics g) { if(dropShape != null) { Point p = SwingUtilities.convertPoint((Component) dropReceiver, 0, 0, getParent()); Rectangle r = dropShape.getBounds(); int shapeX = r.x, shapeY = r.y; if(paintBackgroundUnderDragRect) { r.x += p.x; r.y += p.y; r.width += 2; // stroked shape (+3 pixels, centered) r.height += 2; if(r.x + r.width > desktopImage.getWidth()) { r.width = desktopImage.getWidth() - r.x; } if(r.y + r.height > desktopImage.getHeight()) { r.height = desktopImage.getHeight() - r.y; } if(subImage == null || ! r.equals(subImageBounds)) { subImageBounds = r; subImage = desktopImage.getSubimage(r.x, r.y, r.width, r.height); } g.drawImage(subImage, 0, 0, null); } Shape s = AffineTransform.getTranslateInstance(- shapeX, - shapeY).createTransformedShape(dropShape); Graphics2D g2 = (Graphics2D) g; outlinePainter.paintShape(g2, s); } } public void setVisible(boolean visible) { super.setVisible(visible); label.setVisible(visible); } public void setCursor(Cursor cursor) { super.setCursor(cursor); label.setCursor(cursor); } /** moves and resizes the canvas to the position of the drop shape */ public void moveToShape(Shape newShape) { setVisible(true); @SuppressWarnings("unused") Shape s = dropShape; Container container = getParent(); Point p = SwingUtilities.convertPoint((Component) dropReceiver, 0, 0, container); Rectangle r = dropShape.getBounds(); r.x += p.x; r.y += p.y; r.width += 2; // shape has stroke(3), so we must extend it a little bit r.height += 2; if(r.x + r.width > container.getWidth()) { // check extend not out of bounds r.width = container.getWidth() - r.x; } if(r.y + r.height > container.getHeight()) { r.height = container.getHeight() - r.y; } if(! r.equals(cachedShapeBounds)) { setBounds(r); cachedShapeBounds = r; label.moveToCenter(r); } } } private class HeavyLabel extends Canvas { private static final long serialVersionUID = 1L; private Color textColor = Color.WHITE; private Color textFillColor = new Color(128, 128, 128); private Color textBorderColor = new Color(64, 64, 64); private String name; @SuppressWarnings("unused") private Icon icon; public HeavyLabel() { setEnabled(false); // don't override the glaspane cursor } public void setZOrder() { // jdk1.5 only (but we compile with source=1.4) try { //desktop.setComponentZOrder(this, -2); // on top of heavy panel Method m = Container.class.getMethod("setComponentZOrder", new Class[] {Component.class, int.class}); m.invoke(getParent(), new Object[] {this, new Integer(0)}); } catch(Exception ignore) { ignore.printStackTrace(); } } public void setName(String name) { this.name = name; } @SuppressWarnings("unused") public void setIcon(Icon icon) { this.icon = icon; } public void moveToCenter(Rectangle shapeBounds) { Font f = getFont(); if(f != null) { FontMetrics fm = getFontMetrics(f); int w = fm.stringWidth(name) + 10; int h = fm.getHeight() + 5; setBounds(shapeBounds.x + shapeBounds.width / 2 - w / 2, shapeBounds.y + shapeBounds.height / 2 - h / 2, w, h); } } public void paint(Graphics g) { FontMetrics fm = g.getFontMetrics(); int w = fm.stringWidth(name); int h = fm.getHeight(); g.setColor(textFillColor); g.fillRect(0, 0, getWidth(), getHeight()); g.setColor(textBorderColor); g.drawRect(0, 0, getWidth() - 1, getHeight() - 1); g.setColor(textColor); g.drawString(name, getWidth() / 2 - w / 2, getHeight() / 2 + h / 2); } } }
apache-2.0
maraf/Money
src/Neptuo/Bootstrap/Dependencies/ImportAttribute.cs
503
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Neptuo.Bootstrap.Dependencies { [AttributeUsage(AttributeTargets.Property)] public class ImportAttribute : Attribute { public string Name { get; private set; } public ImportAttribute() { } public ImportAttribute(string name) { Ensure.NotNullOrEmpty(name, "name"); Name = name; } } }
apache-2.0
mattspaulding/AngularjsPhonegap
www/home.html
1830
<ons-page class="center"> <div class="container" ng-controller="HomeCtrl"> <div class="jumbotron"> <ons-navigator page="page3.html" title="login"> </ons-navigator> <h1>ASP.NET</h1> <p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS, and JavaScript.</p> <p><a href="http://asp.net" class="btn btn-primary btn-large">Learn more &raquo;</a></p> </div> <div class="row"> <div class="col-md-4"> <h2>Getting started</h2> <p> ASP.NET Single Page Application (SPA) helps you build applications that include significant client-side interactions using HTML, CSS, and JavaScript. It's now easier than ever before to getting started writing highly interactive web applications. </p> <p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=273732">Learn more &raquo;</a></p> </div> <div class="col-md-4"> <h2>Get more libraries</h2> <p>NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.</p> <p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301866">Learn more &raquo;</a></p> </div> <div class="col-md-4"> <h2>Web Hosting</h2> <p>You can easily find a web hosting company that offers the right mix of features and price for your applications.</p> <p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301867">Learn more &raquo;</a></p> </div> </div> </div> </ons-page>
apache-2.0
matedo1/pnc
bpm/src/test/java/org/jboss/pnc/bpm/test/RepositoryManagerResultSerializationTest.java
6189
/** * JBoss, Home of Professional Open Source. * Copyright 2014-2020 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * 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.jboss.pnc.bpm.test; import org.jboss.pnc.bpm.model.mapper.RepositoryManagerResultMapper; import org.jboss.pnc.bpm.model.RepositoryManagerResultRest; import org.jboss.pnc.common.Configuration; import org.jboss.pnc.common.json.moduleconfig.IndyRepoDriverModuleConfig; import org.jboss.pnc.common.json.moduleprovider.PncConfigProvider; import org.jboss.pnc.mapper.AbstractArtifactMapper; import org.jboss.pnc.mapper.AbstractArtifactMapperImpl; import org.jboss.pnc.mapper.api.TargetRepositoryMapper; import org.jboss.pnc.mapper.api.UserMapper; import org.jboss.pnc.mock.repositorymanager.RepositoryManagerResultMock; import org.jboss.pnc.common.json.JsonOutputConverterMapper; import org.jboss.pnc.spi.repositorymanager.RepositoryManagerResult; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.lang.reflect.Field; import org.jboss.pnc.mapper.api.BuildMapper; import static org.mockito.Mockito.when; /** * Test serialization of Repository manager rest */ @RunWith(MockitoJUnitRunner.class) public class RepositoryManagerResultSerializationTest { private final Logger log = LoggerFactory.getLogger(RepositoryManagerResultSerializationTest.class); @Mock private Configuration configuration; @Spy private TargetRepositoryMapper targetRepositoryMapper; @Spy private BuildMapper buildMapper; @Spy private UserMapper userMapper; @Spy private AbstractArtifactMapperImpl artifactMapper; @Spy @InjectMocks private RepositoryManagerResultMapper repositoryManagerResultMapper; @Before public void before() throws Exception { IndyRepoDriverModuleConfig indyRepoDriverModuleConfig = new IndyRepoDriverModuleConfig("http://url.com"); indyRepoDriverModuleConfig.setExternalRepositoryMvnPath("http://url.com"); indyRepoDriverModuleConfig.setExternalRepositoryNpmPath("http://url.com"); indyRepoDriverModuleConfig.setInternalRepositoryMvnPath("http://url.com"); indyRepoDriverModuleConfig.setInternalRepositoryNpmPath("http://url.com"); when(configuration.getModuleConfig(new PncConfigProvider<>(IndyRepoDriverModuleConfig.class))) .thenReturn(indyRepoDriverModuleConfig); injectMethod("config", artifactMapper, configuration, AbstractArtifactMapper.class); injectMethod( "targetRepositoryMapper", artifactMapper, targetRepositoryMapper, AbstractArtifactMapperImpl.class); injectMethod("buildMapper", artifactMapper, buildMapper, AbstractArtifactMapperImpl.class); injectMethod("userMapper", artifactMapper, userMapper, AbstractArtifactMapperImpl.class); } private void injectMethod(String fieldName, Object to, Object what, Class clazz) throws NoSuchFieldException, IllegalAccessException { Field f = clazz.getDeclaredField(fieldName); f.setAccessible(true); f.set(to, what); } @Test public void serializeAndDeserializeRepositoryManagerResult() throws IOException { RepositoryManagerResult repoMngrResult = RepositoryManagerResultMock.mockResult(); RepositoryManagerResultRest repoMngrResultRest = repositoryManagerResultMapper.toDTO(repoMngrResult); String repoMngrResultJson = JsonOutputConverterMapper.apply(repoMngrResultRest); log.debug("RepoManagerResultJson : {}", repoMngrResultJson); RepositoryManagerResultRest deserializedRepoManResultRest = JsonOutputConverterMapper .readValue(repoMngrResultJson, RepositoryManagerResultRest.class); RepositoryManagerResult deserializedRepoMngrResult = repositoryManagerResultMapper .toEntity(deserializedRepoManResultRest); String message = "Deserialized object does not match the original."; Assert.assertEquals( message, repoMngrResult.getBuildContentId(), deserializedRepoMngrResult.getBuildContentId()); Assert.assertEquals( message, repoMngrResult.getBuiltArtifacts().get(0), deserializedRepoMngrResult.getBuiltArtifacts().get(0)); Assert.assertEquals( message, repoMngrResult.getBuiltArtifacts().get(0).getSha256(), deserializedRepoMngrResult.getBuiltArtifacts().get(0).getSha256()); Assert.assertEquals( message, repoMngrResult.getBuiltArtifacts().get(0).isBuilt(), deserializedRepoMngrResult.getBuiltArtifacts().get(0).isBuilt()); Assert.assertEquals( message, repoMngrResult.getDependencies().get(0), deserializedRepoMngrResult.getDependencies().get(0)); Assert.assertEquals( message, repoMngrResult.getDependencies().get(0).getDeployPath(), deserializedRepoMngrResult.getDependencies().get(0).getDeployPath()); Assert.assertEquals( message, repoMngrResult.getDependencies().get(0).isImported(), deserializedRepoMngrResult.getDependencies().get(0).isImported()); } }
apache-2.0
huihoo/olat
OLAT-LMS/src/main/java/org/olat/presentation/course/assessment/_content/assessment_index.html
341
<div class="b_float_right"> $r.contextHelp("org.olat.presentation.course.assessment","course-assess-tool.html","help.hover.assess") </div> <h5>$r.translate("index.title")</h5> #if($hasAssessableNodes) <p> $r.translate("index.intro") </p> <p> $r.translate("index.slow") </p> #else <p> $r.translate("index.noAssessableNodes") </p> #end
apache-2.0
dealfonso/lxc-pm
networkmanager.py
8801
''' "network": [ { "index": 0, "ipv4_gateway": "", "name": "", "veth_pair": "", "mtu": "", "ipv6_gateway": "", "flags": "up", "ipv4": "", "ipv6": "", "hwaddr": "00:16:3e:1e:89:6b", "link": "lxcbr0", "script_up": "", "script_down": "", "type": "veth" } ''' import jsonlib import json import cpyutils.iputils import random class NetworkDefinition(jsonlib.Serializable): _JSON_FIELDS_required = [ 'name', 'link', 'type' ] _JSON_FIELDS_other = [ 'gateway' ] @classmethod def from_json(cls, json_str): o = jsonlib.Serializable.from_json(cls(None, None, None), json_str) if o is None: raise Exception("could not create object from json '%s'" % json_str) return o def __init__(self, name, link, _type): self._name = name self.link = link self.type = _type self.gateway = None self._last_lease = None self._leases = [] def _get_lease(self, lease): if self._check_hwaddr_in_leases(lease.hwaddr): return False if self._check_ipv4_in_leases(lease.ipv4): return False self._leases.append(lease) return True def _check_hwaddr_in_leases(self, hwaddr): for lease in self._leases: if lease.hwaddr == hwaddr: return True return False def _check_ipv4_in_leases(self, ipv4): for lease in self._leases: if lease.ipv4 == ipv4: return True return False def get_lease(self): return None def release_lease(self, lease): for e_lease in self._leases: if (lease.ipv4 == e_lease.ipv4) and (lease.hwaddr == e_lease.hwaddr): self._leases.remove(e_lease) return True return False class NetworkDefinition_MAC_Prefix(NetworkDefinition): _JSON_FIELDS_default = { 'hwaddrprefix': '40:00:00' } @staticmethod def gen_hex_mac_prefix(original_mac): mac = (original_mac.upper()).strip() parts = mac.split(':') if len(parts) > 6: return None if len(parts) > 1: # let's think that it is a : separated mac for p in parts: if len(p) != 2: return None mac = ''.join(parts) for c in mac: if c not in '0123456789ABCDEF': return None return mac @classmethod def from_json(cls, json_str, obj = None): if obj is None: obj = cls(None, None, None) o = jsonlib.Serializable.from_json(obj, json_str) mac_prefix = cls.gen_hex_mac_prefix(o.hwaddrprefix) if mac_prefix is None: raise Exception("Bad MAC mask format %s" % o.hwaddrprefix) o._mac_prefix = int(mac_prefix, 16) o._mac_tail = 0 o._mac_tail_bits = (12 - len(mac_prefix)) * 4 for i in range(0, 12 - len(mac_prefix)): o._mac_prefix = (o._mac_prefix << 4) o._mac_tail = (o._mac_tail << 4) | 0xf return o def _gen_mac(self): new_mac = ("%x" % (self._mac_prefix | (random.getrandbits(self._mac_tail_bits) & self._mac_tail))).lower() mac_str = ':'.join([new_mac[i:i+2] for i in range(0, len(new_mac), 2)]) return mac_str def _gen_hw(self): max_attempts = 10 mac = self._gen_mac() while max_attempts > 0 and self._check_hwaddr_in_leases(mac): mac = self._gen_mac() max_attempts = max_attempts - 1 if max_attempts == 0: return None return mac def get_lease(self): mac = self._gen_hw() if mac is None: return None lease = NetworkConfiguration(self, hwaddr = mac) if not self._get_lease(lease): return None return lease def _iphex_to_str(iphex): ip = [] while iphex > 0: v = iphex & 0xff ip.append(str(v)) iphex = iphex >> 8 return '.'.join(ip[::-1]) class NetworkDefinition_IP_Range(NetworkDefinition_MAC_Prefix): _JSON_FIELDS_default = { 'hwaddrprefix': '40:00:00', 'ipv4mask': '192.168.1.1/24' } @classmethod def from_json(cls, json_str): b = NetworkDefinition_MAC_Prefix.from_json(json_str, NetworkDefinition_IP_Range(None, None, None)) if b is None: return None o = jsonlib.Serializable.from_json(b, json_str) o._ipv4, o._mask = cpyutils.iputils.str_to_ipmask(o.ipv4mask) return o def get_lease(self): mac = self._gen_hw() if mac is None: return None v = 1 ipv4 = self._ipv4 & self._mask max_range = 0xffffffff - self._mask newip = _iphex_to_str(ipv4 | (v & max_range)) while (v < max_range) and self._check_ipv4_in_leases(newip): newip = _iphex_to_str(ipv4 + (v & max_range)) v = v + 1 lease = NetworkConfiguration(self) lease.ipv4 = newip lease.hwaddr = mac if not self._get_lease(lease): return None return lease class NetworkDefinition_Pair(NetworkDefinition): _JSON_FIELDS_required = [ 'name', 'link', 'type' ] _JSON_FIELDS_default = { 'iphw': [ { 'ipv4': '192.168.1.1', 'hwaddr': '40:00:00:00:00:01' } ] } @classmethod def from_json(cls, json_str): o = jsonlib.Serializable.from_json(cls(None, None, None), json_str) if o is not None: for lease in o.iphw: if not cpyutils.iputils.check_ip(lease['ipv4']): raise Exception("bad ip format: %s" % lease['ipv4']) if not cpyutils.iputils.check_mac(lease['hwaddr']): raise Exception("bad hw address format: %s" % lease['hwaddr']) else: raise Exception("could not create object from json '%s'" % json_str) return o def get_lease(self): lease = NetworkConfiguration(self) for lease_info in self.iphw: lease.ipv4, lease.hwaddr = (lease_info['ipv4'], lease_info['hwaddr']) if self._get_lease(lease): return lease return None class NetworkConfiguration(jsonlib.Serializable): _JSON_FIELDS_required = [ 'link', 'hwaddr', 'type' ] _JSON_FIELDS_default = { 'ipv4': None } @classmethod def from_json(cls, json_str): o = jsonlib.Serializable.from_json(cls(None), json_str) if o is not None: if not cpyutils.iputils.check_mac(o.hwaddr): raise Exception("mac format is not valid") return o def __init__(self, network_definition, ipv4 = None, hwaddr = None): self._network_definition = network_definition self.link = network_definition.link self.hwaddr = hwaddr self.type = network_definition.type self.ipv4 = ipv4 self.gateway = network_definition.gateway def lxc_config(self): config = [] config.append("lxc.network.type = %s" % self.type) config.append("lxc.network.link = %s" % self.link) if self.hwaddr is not None: config.append("lxc.network.hwaddr = %s" % self.hwaddr) if self.ipv4 is not None: config.append("lxc.network.ipv4 = %s" % self.ipv4) if self.gateway is not None: config.append("lxc.network.ipv4.gateway = %s" % self.gateway) config.append("lxc.network.flags = up") return "\n".join(config) if __name__ == "__main__": n = json.dumps( { 'name': 'public_dhcp', 'link': 'br0', 'type': 'veth', 'gateway': '10.0.0.1', 'iphw': [ { 'ipv4': '10.0.0.1', 'hwaddr': '60:00:00:00:00:01' }, { 'ipv4': '10.0.0.2', 'hwaddr': '60:00:00:00:00:02' } ] } , indent = 4) m = NetworkDefinition_MAC_Prefix.from_json(n) #print m.get_lease() #print m.get_lease() #print m.get_lease() #print m.get_lease() #print m.get_lease() p = NetworkDefinition_Pair.from_json(n) l1 = p.get_lease() l2 = p.get_lease() l3 = p.get_lease() print l1, l2, l3 i = NetworkDefinition_IP_Range.from_json(n) print i.get_lease().lxc_config() print i.get_lease().lxc_config() print i.get_lease().lxc_config() print i.get_lease().lxc_config() ''' d = NetworkDefinition.from_json( '{\ "name": "basic", \ "link": "br0", \ "type": "veth", \ "hwaddr": "40:00:00:00:00:01"\ }') print d ''' # print o # print json.dumps(o.serialize(), indent=4)
apache-2.0
friedhardware/druid
indexing-service/src/test/java/io/druid/indexing/overlord/TaskLifecycleTest.java
37250
/* * Druid - a distributed column store. * Copyright 2012 - 2015 Metamarkets Group 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.druid.indexing.overlord; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.jsontype.NamedType; import com.google.common.base.Function; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Ordering; import com.metamx.common.Granularity; import com.metamx.common.ISE; import com.metamx.common.guava.Comparators; import com.metamx.emitter.EmittingLogger; import com.metamx.emitter.core.Event; import com.metamx.emitter.service.ServiceEmitter; import com.metamx.emitter.service.ServiceEventBuilder; import com.metamx.metrics.Monitor; import com.metamx.metrics.MonitorScheduler; import io.druid.client.FilteredServerView; import io.druid.client.ServerView; import io.druid.client.cache.MapCache; import io.druid.data.input.Firehose; import io.druid.data.input.FirehoseFactory; import io.druid.data.input.InputRow; import io.druid.data.input.MapBasedInputRow; import io.druid.data.input.impl.InputRowParser; import io.druid.granularity.QueryGranularity; import io.druid.indexing.common.SegmentLoaderFactory; import io.druid.indexing.common.TaskLock; import io.druid.indexing.common.TaskStatus; import io.druid.indexing.common.TaskToolbox; import io.druid.indexing.common.TaskToolboxFactory; import io.druid.indexing.common.TestUtils; import io.druid.indexing.common.actions.LocalTaskActionClientFactory; import io.druid.indexing.common.actions.LockListAction; import io.druid.indexing.common.actions.SegmentInsertAction; import io.druid.indexing.common.actions.TaskActionClientFactory; import io.druid.indexing.common.actions.TaskActionToolbox; import io.druid.indexing.common.config.TaskConfig; import io.druid.indexing.common.config.TaskStorageConfig; import io.druid.indexing.common.task.AbstractFixedIntervalTask; import io.druid.indexing.common.task.IndexTask; import io.druid.indexing.common.task.KillTask; import io.druid.indexing.common.task.RealtimeIndexTask; import io.druid.indexing.common.task.RealtimeIndexTaskTest; import io.druid.indexing.common.task.Task; import io.druid.indexing.common.task.TaskResource; import io.druid.indexing.overlord.config.TaskQueueConfig; import io.druid.indexing.test.TestIndexerMetadataStorageCoordinator; import io.druid.jackson.DefaultObjectMapper; import io.druid.metadata.SQLMetadataStorageActionHandlerFactory; import io.druid.metadata.TestDerbyConnector; import io.druid.query.QueryRunnerFactoryConglomerate; import io.druid.query.aggregation.AggregatorFactory; import io.druid.query.aggregation.DoubleSumAggregatorFactory; import io.druid.query.aggregation.LongSumAggregatorFactory; import io.druid.segment.IndexIO; import io.druid.segment.IndexMerger; import io.druid.segment.IndexSpec; import io.druid.segment.indexing.DataSchema; import io.druid.segment.indexing.RealtimeIOConfig; import io.druid.segment.indexing.RealtimeTuningConfig; import io.druid.segment.indexing.granularity.UniformGranularitySpec; import io.druid.segment.loading.DataSegmentArchiver; import io.druid.segment.loading.DataSegmentMover; import io.druid.segment.loading.DataSegmentPusher; import io.druid.segment.loading.LocalDataSegmentKiller; import io.druid.segment.loading.SegmentLoaderConfig; import io.druid.segment.loading.SegmentLoaderLocalCacheManager; import io.druid.segment.loading.SegmentLoadingException; import io.druid.segment.loading.StorageLocationConfig; import io.druid.segment.realtime.FireDepartment; import io.druid.segment.realtime.FireDepartmentTest; import io.druid.server.coordination.DataSegmentAnnouncer; import io.druid.server.coordination.DruidServerMetadata; import io.druid.timeline.DataSegment; import io.druid.timeline.partition.NoneShardSpec; import org.easymock.EasyMock; import org.joda.time.DateTime; import org.joda.time.Hours; import org.joda.time.Interval; import org.joda.time.Period; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; @RunWith(Parameterized.class) public class TaskLifecycleTest { private static final ObjectMapper MAPPER; private static final IndexMerger INDEX_MERGER; private static final IndexIO INDEX_IO; static { TestUtils testUtils = new TestUtils(); MAPPER = testUtils.getTestObjectMapper(); INDEX_MERGER = testUtils.getTestIndexMerger(); INDEX_IO = testUtils.getTestIndexIO(); } @Parameterized.Parameters(name = "taskStorageType={0}") public static Collection<String[]> constructFeed() { return Arrays.asList(new String[][]{{"HeapMemoryTaskStorage"}, {"MetadataTaskStorage"}}); } public TaskLifecycleTest(String taskStorageType) { this.taskStorageType = taskStorageType; } public final @Rule TemporaryFolder temporaryFolder = new TemporaryFolder(); private static final Ordering<DataSegment> byIntervalOrdering = new Ordering<DataSegment>() { @Override public int compare(DataSegment dataSegment, DataSegment dataSegment2) { return Comparators.intervalsByStartThenEnd().compare(dataSegment.getInterval(), dataSegment2.getInterval()); } }; private static DateTime now = new DateTime(); private static final Iterable<InputRow> realtimeIdxTaskInputRows = ImmutableList.of( IR(now.toString("YYYY-MM-dd'T'HH:mm:ss"), "test_dim1", "test_dim2", 1.0f), IR(now.plus(new Period(Hours.ONE)).toString("YYYY-MM-dd'T'HH:mm:ss"), "test_dim1", "test_dim2", 2.0f), IR(now.plus(new Period(Hours.TWO)).toString("YYYY-MM-dd'T'HH:mm:ss"), "test_dim1", "test_dim2", 3.0f) ); private static final Iterable<InputRow> IdxTaskInputRows = ImmutableList.of( IR("2010-01-01T01", "x", "y", 1), IR("2010-01-01T01", "x", "z", 1), IR("2010-01-02T01", "a", "b", 2), IR("2010-01-02T01", "a", "c", 1) ); @Rule public final TestDerbyConnector.DerbyConnectorRule derbyConnectorRule = new TestDerbyConnector.DerbyConnectorRule(); private final String taskStorageType; private ObjectMapper mapper; private TaskStorageQueryAdapter tsqa = null; private File tmpDir = null; private TaskStorage ts = null; private TaskLockbox tl = null; private TaskQueue tq = null; private TaskRunner tr = null; private TestIndexerMetadataStorageCoordinator mdc = null; private TaskActionClientFactory tac = null; private TaskToolboxFactory tb = null; private IndexSpec indexSpec; private QueryRunnerFactoryConglomerate queryRunnerFactoryConglomerate; private FilteredServerView serverView; private MonitorScheduler monitorScheduler; private ServiceEmitter emitter; private TaskQueueConfig tqc; private int pushedSegments; private int announcedSinks; private static CountDownLatch publishCountDown; private TestDerbyConnector testDerbyConnector; private List<ServerView.SegmentCallback> segmentCallbacks = new ArrayList<>(); private static TestIndexerMetadataStorageCoordinator newMockMDC() { return new TestIndexerMetadataStorageCoordinator() { @Override public Set<DataSegment> announceHistoricalSegments(Set<DataSegment> segments) { Set<DataSegment> retVal = super.announceHistoricalSegments(segments); publishCountDown.countDown(); return retVal; } }; } private static ServiceEmitter newMockEmitter() { return new ServiceEmitter(null, null, null) { @Override public void emit(Event event) { } @Override public void emit(ServiceEventBuilder builder) { } }; } private static InputRow IR(String dt, String dim1, String dim2, float met) { return new MapBasedInputRow( new DateTime(dt).getMillis(), ImmutableList.of("dim1", "dim2"), ImmutableMap.<String, Object>of( "dim1", dim1, "dim2", dim2, "met", met ) ); } private static class MockExceptionalFirehoseFactory implements FirehoseFactory { @Override public Firehose connect(InputRowParser parser) throws IOException { return new Firehose() { @Override public boolean hasMore() { return true; } @Override public InputRow nextRow() { throw new RuntimeException("HA HA HA"); } @Override public Runnable commit() { return new Runnable() { @Override public void run() { } }; } @Override public void close() throws IOException { } }; } } private static class MockFirehoseFactory implements FirehoseFactory { @JsonProperty private boolean usedByRealtimeIdxTask; @JsonCreator public MockFirehoseFactory(@JsonProperty("usedByRealtimeIdxTask") boolean usedByRealtimeIdxTask) { this.usedByRealtimeIdxTask = usedByRealtimeIdxTask; } @Override public Firehose connect(InputRowParser parser) throws IOException { final Iterator<InputRow> inputRowIterator = usedByRealtimeIdxTask ? realtimeIdxTaskInputRows.iterator() : IdxTaskInputRows.iterator(); return new Firehose() { @Override public boolean hasMore() { return inputRowIterator.hasNext(); } @Override public InputRow nextRow() { return inputRowIterator.next(); } @Override public Runnable commit() { return new Runnable() { @Override public void run() { } }; } @Override public void close() throws IOException { } }; } } @Before public void setUp() throws Exception { emitter = EasyMock.createMock(ServiceEmitter.class); EmittingLogger.registerEmitter(emitter); queryRunnerFactoryConglomerate = EasyMock.createStrictMock(QueryRunnerFactoryConglomerate.class); monitorScheduler = EasyMock.createStrictMock(MonitorScheduler.class); publishCountDown = new CountDownLatch(1); announcedSinks = 0; pushedSegments = 0; tmpDir = temporaryFolder.newFolder(); TestUtils testUtils = new TestUtils(); mapper = testUtils.getTestObjectMapper(); tqc = mapper.readValue( "{\"startDelay\":\"PT0S\", \"restartDelay\":\"PT1S\", \"storageSyncRate\":\"PT0.5S\"}", TaskQueueConfig.class ); indexSpec = new IndexSpec(); if (taskStorageType.equals("HeapMemoryTaskStorage")) { ts = new HeapMemoryTaskStorage( new TaskStorageConfig(null) { } ); } else if (taskStorageType.equals("MetadataTaskStorage")) { testDerbyConnector = derbyConnectorRule.getConnector(); mapper.registerSubtypes( new NamedType(MockExceptionalFirehoseFactory.class, "mockExcepFirehoseFactory"), new NamedType(MockFirehoseFactory.class, "mockFirehoseFactory") ); testDerbyConnector.createTaskTables(); testDerbyConnector.createSegmentTable(); ts = new MetadataTaskStorage( testDerbyConnector, new TaskStorageConfig(null), new SQLMetadataStorageActionHandlerFactory( testDerbyConnector, derbyConnectorRule.metadataTablesConfigSupplier().get(), mapper ) ); } else { throw new RuntimeException(String.format("Unknown task storage type [%s]", taskStorageType)); } serverView = new FilteredServerView() { @Override public void registerSegmentCallback( Executor exec, ServerView.SegmentCallback callback, Predicate<DataSegment> filter ) { segmentCallbacks.add(callback); } }; setUpAndStartTaskQueue( new DataSegmentPusher() { @Override public String getPathForHadoop(String dataSource) { throw new UnsupportedOperationException(); } @Override public DataSegment push(File file, DataSegment segment) throws IOException { pushedSegments++; return segment; } } ); } private void setUpAndStartTaskQueue(DataSegmentPusher dataSegmentPusher) { final TaskConfig taskConfig = new TaskConfig(tmpDir.toString(), null, null, 50000, null, null, null); tsqa = new TaskStorageQueryAdapter(ts); tl = new TaskLockbox(ts); mdc = newMockMDC(); tac = new LocalTaskActionClientFactory(ts, new TaskActionToolbox(tl, mdc, newMockEmitter())); tb = new TaskToolboxFactory( taskConfig, tac, newMockEmitter(), dataSegmentPusher, new LocalDataSegmentKiller(), new DataSegmentMover() { @Override public DataSegment move(DataSegment dataSegment, Map<String, Object> targetLoadSpec) throws SegmentLoadingException { return dataSegment; } }, new DataSegmentArchiver() { @Override public DataSegment archive(DataSegment segment) throws SegmentLoadingException { return segment; } @Override public DataSegment restore(DataSegment segment) throws SegmentLoadingException { return segment; } }, new DataSegmentAnnouncer() { @Override public void announceSegment(DataSegment segment) throws IOException { announcedSinks++; } @Override public void unannounceSegment(DataSegment segment) throws IOException { } @Override public void announceSegments(Iterable<DataSegment> segments) throws IOException { } @Override public void unannounceSegments(Iterable<DataSegment> segments) throws IOException { } }, // segment announcer serverView, // new segment server view queryRunnerFactoryConglomerate, // query runner factory conglomerate corporation unionized collective null, // query executor service monitorScheduler, // monitor scheduler new SegmentLoaderFactory( new SegmentLoaderLocalCacheManager( null, new SegmentLoaderConfig() { @Override public List<StorageLocationConfig> getLocations() { return Lists.newArrayList(); } }, new DefaultObjectMapper() ) ), MAPPER, INDEX_MERGER, INDEX_IO, MapCache.create(0), FireDepartmentTest.NO_CACHE_CONFIG ); tr = new ThreadPoolTaskRunner(tb, taskConfig, emitter); tq = new TaskQueue(tqc, ts, tr, tac, tl, emitter); tq.start(); } @After public void tearDown() { tq.stop(); } @Test public void testIndexTask() throws Exception { final Task indexTask = new IndexTask( null, null, new IndexTask.IndexIngestionSpec( new DataSchema( "foo", null, new AggregatorFactory[]{new DoubleSumAggregatorFactory("met", "met")}, new UniformGranularitySpec( Granularity.DAY, null, ImmutableList.of(new Interval("2010-01-01/P2D")) ), mapper ), new IndexTask.IndexIOConfig(new MockFirehoseFactory(false)), new IndexTask.IndexTuningConfig(10000, 10, -1, indexSpec) ), mapper, null ); final Optional<TaskStatus> preRunTaskStatus = tsqa.getStatus(indexTask.getId()); Assert.assertTrue("pre run task status not present", !preRunTaskStatus.isPresent()); final TaskStatus mergedStatus = runTask(indexTask); final TaskStatus status = ts.getStatus(indexTask.getId()).get(); final List<DataSegment> publishedSegments = byIntervalOrdering.sortedCopy(mdc.getPublished()); final List<DataSegment> loggedSegments = byIntervalOrdering.sortedCopy(tsqa.getInsertedSegments(indexTask.getId())); Assert.assertEquals("statusCode", TaskStatus.Status.SUCCESS, status.getStatusCode()); Assert.assertEquals("merged statusCode", TaskStatus.Status.SUCCESS, mergedStatus.getStatusCode()); Assert.assertEquals("segments logged vs published", loggedSegments, publishedSegments); Assert.assertEquals("num segments published", 2, mdc.getPublished().size()); Assert.assertEquals("num segments nuked", 0, mdc.getNuked().size()); Assert.assertEquals("segment1 datasource", "foo", publishedSegments.get(0).getDataSource()); Assert.assertEquals("segment1 interval", new Interval("2010-01-01/P1D"), publishedSegments.get(0).getInterval()); Assert.assertEquals( "segment1 dimensions", ImmutableList.of("dim1", "dim2"), publishedSegments.get(0).getDimensions() ); Assert.assertEquals("segment1 metrics", ImmutableList.of("met"), publishedSegments.get(0).getMetrics()); Assert.assertEquals("segment2 datasource", "foo", publishedSegments.get(1).getDataSource()); Assert.assertEquals("segment2 interval", new Interval("2010-01-02/P1D"), publishedSegments.get(1).getInterval()); Assert.assertEquals( "segment2 dimensions", ImmutableList.of("dim1", "dim2"), publishedSegments.get(1).getDimensions() ); Assert.assertEquals("segment2 metrics", ImmutableList.of("met"), publishedSegments.get(1).getMetrics()); } @Test public void testIndexTaskFailure() throws Exception { final Task indexTask = new IndexTask( null, null, new IndexTask.IndexIngestionSpec( new DataSchema( "foo", null, new AggregatorFactory[]{new DoubleSumAggregatorFactory("met", "met")}, new UniformGranularitySpec( Granularity.DAY, null, ImmutableList.of(new Interval("2010-01-01/P1D")) ), mapper ), new IndexTask.IndexIOConfig(new MockExceptionalFirehoseFactory()), new IndexTask.IndexTuningConfig(10000, 10, -1, indexSpec) ), mapper, null ); final TaskStatus status = runTask(indexTask); Assert.assertEquals("statusCode", TaskStatus.Status.FAILED, status.getStatusCode()); Assert.assertEquals("num segments published", 0, mdc.getPublished().size()); Assert.assertEquals("num segments nuked", 0, mdc.getNuked().size()); } @Test public void testKillTask() throws Exception { final File tmpSegmentDir = temporaryFolder.newFolder(); List<DataSegment> expectedUnusedSegments = Lists.transform( ImmutableList.<String>of( "2011-04-01/2011-04-02", "2011-04-02/2011-04-03", "2011-04-04/2011-04-05" ), new Function<String, DataSegment>() { @Override public DataSegment apply(String input) { final Interval interval = new Interval(input); try { return DataSegment.builder() .dataSource("test_kill_task") .interval(interval) .loadSpec( ImmutableMap.<String, Object>of( "type", "local", "path", tmpSegmentDir.getCanonicalPath() + "/druid/localStorage/wikipedia/" + interval.getStart() + "-" + interval.getEnd() + "/" + "2011-04-6T16:52:46.119-05:00" + "/0/index.zip" ) ) .version("2011-04-6T16:52:46.119-05:00") .dimensions(ImmutableList.<String>of()) .metrics(ImmutableList.<String>of()) .shardSpec(new NoneShardSpec()) .binaryVersion(9) .size(0) .build(); } catch (IOException e) { throw new ISE(e, "Error creating segments"); } } } ); mdc.setUnusedSegments(expectedUnusedSegments); // manually create local segments files List<File> segmentFiles = Lists.newArrayList(); for (DataSegment segment : mdc.getUnusedSegmentsForInterval("test_kill_task", new Interval("2011-04-01/P4D"))) { File file = new File((String) segment.getLoadSpec().get("path")); file.mkdirs(); segmentFiles.add(file); } final Task killTask = new KillTask(null, "test_kill_task", new Interval("2011-04-01/P4D"), null); final TaskStatus status = runTask(killTask); Assert.assertEquals("merged statusCode", TaskStatus.Status.SUCCESS, status.getStatusCode()); Assert.assertEquals("num segments published", 0, mdc.getPublished().size()); Assert.assertEquals("num segments nuked", 3, mdc.getNuked().size()); Assert.assertTrue( "expected unused segments get killed", expectedUnusedSegments.containsAll(mdc.getNuked()) && mdc.getNuked().containsAll( expectedUnusedSegments ) ); for (File file : segmentFiles) { Assert.assertFalse("unused segments files get deleted", file.exists()); } } @Test public void testRealtimeishTask() throws Exception { final Task rtishTask = new RealtimeishTask(); final TaskStatus status = runTask(rtishTask); Assert.assertEquals("statusCode", TaskStatus.Status.SUCCESS, status.getStatusCode()); Assert.assertEquals("num segments published", 2, mdc.getPublished().size()); Assert.assertEquals("num segments nuked", 0, mdc.getNuked().size()); } @Test public void testNoopTask() throws Exception { final Task noopTask = new DefaultObjectMapper().readValue( "{\"type\":\"noop\", \"runTime\":\"100\"}\"", Task.class ); final TaskStatus status = runTask(noopTask); Assert.assertEquals("statusCode", TaskStatus.Status.SUCCESS, status.getStatusCode()); Assert.assertEquals("num segments published", 0, mdc.getPublished().size()); Assert.assertEquals("num segments nuked", 0, mdc.getNuked().size()); } @Test public void testNeverReadyTask() throws Exception { final Task neverReadyTask = new DefaultObjectMapper().readValue( "{\"type\":\"noop\", \"isReadyResult\":\"exception\"}\"", Task.class ); final TaskStatus status = runTask(neverReadyTask); Assert.assertEquals("statusCode", TaskStatus.Status.FAILED, status.getStatusCode()); Assert.assertEquals("num segments published", 0, mdc.getPublished().size()); Assert.assertEquals("num segments nuked", 0, mdc.getNuked().size()); } @Test public void testSimple() throws Exception { final Task task = new AbstractFixedIntervalTask( "id1", "id1", new TaskResource("id1", 1), "ds", new Interval("2012-01-01/P1D"), null ) { @Override public String getType() { return "test"; } @Override public TaskStatus run(TaskToolbox toolbox) throws Exception { final TaskLock myLock = Iterables.getOnlyElement( toolbox.getTaskActionClient() .submit(new LockListAction()) ); final DataSegment segment = DataSegment.builder() .dataSource("ds") .interval(new Interval("2012-01-01/P1D")) .version(myLock.getVersion()) .build(); toolbox.getTaskActionClient().submit(new SegmentInsertAction(ImmutableSet.of(segment))); return TaskStatus.success(getId()); } }; final TaskStatus status = runTask(task); Assert.assertEquals("statusCode", TaskStatus.Status.SUCCESS, status.getStatusCode()); Assert.assertEquals("segments published", 1, mdc.getPublished().size()); Assert.assertEquals("segments nuked", 0, mdc.getNuked().size()); } @Test public void testBadInterval() throws Exception { final Task task = new AbstractFixedIntervalTask("id1", "id1", "ds", new Interval("2012-01-01/P1D"), null) { @Override public String getType() { return "test"; } @Override public TaskStatus run(TaskToolbox toolbox) throws Exception { final TaskLock myLock = Iterables.getOnlyElement(toolbox.getTaskActionClient().submit(new LockListAction())); final DataSegment segment = DataSegment.builder() .dataSource("ds") .interval(new Interval("2012-01-01/P2D")) .version(myLock.getVersion()) .build(); toolbox.getTaskActionClient().submit(new SegmentInsertAction(ImmutableSet.of(segment))); return TaskStatus.success(getId()); } }; final TaskStatus status = runTask(task); Assert.assertEquals("statusCode", TaskStatus.Status.FAILED, status.getStatusCode()); Assert.assertEquals("segments published", 0, mdc.getPublished().size()); Assert.assertEquals("segments nuked", 0, mdc.getNuked().size()); } @Test public void testBadVersion() throws Exception { final Task task = new AbstractFixedIntervalTask("id1", "id1", "ds", new Interval("2012-01-01/P1D"), null) { @Override public String getType() { return "test"; } @Override public TaskStatus run(TaskToolbox toolbox) throws Exception { final TaskLock myLock = Iterables.getOnlyElement(toolbox.getTaskActionClient().submit(new LockListAction())); final DataSegment segment = DataSegment.builder() .dataSource("ds") .interval(new Interval("2012-01-01/P1D")) .version(myLock.getVersion() + "1!!!1!!") .build(); toolbox.getTaskActionClient().submit(new SegmentInsertAction(ImmutableSet.of(segment))); return TaskStatus.success(getId()); } }; final TaskStatus status = runTask(task); Assert.assertEquals("statusCode", TaskStatus.Status.FAILED, status.getStatusCode()); Assert.assertEquals("segments published", 0, mdc.getPublished().size()); Assert.assertEquals("segments nuked", 0, mdc.getNuked().size()); } @Test(timeout = 4000L) public void testRealtimeIndexTask() throws Exception { monitorScheduler.addMonitor(EasyMock.anyObject(Monitor.class)); EasyMock.expectLastCall().atLeastOnce(); monitorScheduler.removeMonitor(EasyMock.anyObject(Monitor.class)); EasyMock.expectLastCall().anyTimes(); EasyMock.replay(monitorScheduler, queryRunnerFactoryConglomerate); RealtimeIndexTask realtimeIndexTask = giveMeARealtimeIndexTask(); final String taskId = realtimeIndexTask.getId(); tq.add(realtimeIndexTask); //wait for task to process events and publish segment Assert.assertTrue(publishCountDown.await(1000, TimeUnit.MILLISECONDS)); // Realtime Task has published the segment, simulate loading of segment to a historical node so that task finishes with SUCCESS status segmentCallbacks.get(0).segmentAdded( new DruidServerMetadata( "dummy", "dummy_host", 0, "historical", "dummy_tier", 0 ), mdc.getPublished().iterator().next() ); // Wait for realtime index task to handle callback in plumber and succeed while (tsqa.getStatus(taskId).get().isRunnable()) { Thread.sleep(10); } Assert.assertTrue("Task should be in Success state", tsqa.getStatus(taskId).get().isSuccess()); Assert.assertEquals(1, announcedSinks); Assert.assertEquals(1, pushedSegments); Assert.assertEquals(1, mdc.getPublished().size()); DataSegment segment = mdc.getPublished().iterator().next(); Assert.assertEquals("test_ds", segment.getDataSource()); Assert.assertEquals(ImmutableList.of("dim1", "dim2"), segment.getDimensions()); Assert.assertEquals( new Interval(now.toString("YYYY-MM-dd") + "/" + now.plusDays(1).toString("YYYY-MM-dd")), segment.getInterval() ); Assert.assertEquals(ImmutableList.of("count"), segment.getMetrics()); EasyMock.verify(monitorScheduler, queryRunnerFactoryConglomerate); } @Test(timeout = 4000L) public void testRealtimeIndexTaskFailure() throws Exception { setUpAndStartTaskQueue( new DataSegmentPusher() { @Override public String getPathForHadoop(String s) { throw new UnsupportedOperationException(); } @Override public DataSegment push(File file, DataSegment dataSegment) throws IOException { throw new RuntimeException("FAILURE"); } } ); monitorScheduler.addMonitor(EasyMock.anyObject(Monitor.class)); EasyMock.expectLastCall().atLeastOnce(); monitorScheduler.removeMonitor(EasyMock.anyObject(Monitor.class)); EasyMock.expectLastCall().anyTimes(); EasyMock.replay(monitorScheduler, queryRunnerFactoryConglomerate); RealtimeIndexTask realtimeIndexTask = giveMeARealtimeIndexTask(); final String taskId = realtimeIndexTask.getId(); tq.add(realtimeIndexTask); // Wait for realtime index task to fail while (tsqa.getStatus(taskId).get().isRunnable()) { Thread.sleep(10); } Assert.assertTrue("Task should be in Failure state", tsqa.getStatus(taskId).get().isFailure()); EasyMock.verify(monitorScheduler, queryRunnerFactoryConglomerate); } @Test public void testResumeTasks() throws Exception { final Task indexTask = new IndexTask( null, null, new IndexTask.IndexIngestionSpec( new DataSchema( "foo", null, new AggregatorFactory[]{new DoubleSumAggregatorFactory("met", "met")}, new UniformGranularitySpec( Granularity.DAY, null, ImmutableList.of(new Interval("2010-01-01/P2D")) ), mapper ), new IndexTask.IndexIOConfig(new MockFirehoseFactory(false)), new IndexTask.IndexTuningConfig(10000, 10, -1, indexSpec) ), mapper, null ); final long startTime = System.currentTimeMillis(); // manually insert the task into TaskStorage, waiting for TaskQueue to sync from storage ts.insert(indexTask, TaskStatus.running(indexTask.getId())); while (tsqa.getStatus(indexTask.getId()).get().isRunnable()) { if (System.currentTimeMillis() > startTime + 10 * 1000) { throw new ISE("Where did the task go?!: %s", indexTask.getId()); } Thread.sleep(100); } final TaskStatus status = ts.getStatus(indexTask.getId()).get(); final List<DataSegment> publishedSegments = byIntervalOrdering.sortedCopy(mdc.getPublished()); final List<DataSegment> loggedSegments = byIntervalOrdering.sortedCopy(tsqa.getInsertedSegments(indexTask.getId())); Assert.assertEquals("statusCode", TaskStatus.Status.SUCCESS, status.getStatusCode()); Assert.assertEquals("segments logged vs published", loggedSegments, publishedSegments); Assert.assertEquals("num segments published", 2, mdc.getPublished().size()); Assert.assertEquals("num segments nuked", 0, mdc.getNuked().size()); Assert.assertEquals("segment1 datasource", "foo", publishedSegments.get(0).getDataSource()); Assert.assertEquals("segment1 interval", new Interval("2010-01-01/P1D"), publishedSegments.get(0).getInterval()); Assert.assertEquals( "segment1 dimensions", ImmutableList.of("dim1", "dim2"), publishedSegments.get(0).getDimensions() ); Assert.assertEquals("segment1 metrics", ImmutableList.of("met"), publishedSegments.get(0).getMetrics()); Assert.assertEquals("segment2 datasource", "foo", publishedSegments.get(1).getDataSource()); Assert.assertEquals("segment2 interval", new Interval("2010-01-02/P1D"), publishedSegments.get(1).getInterval()); Assert.assertEquals( "segment2 dimensions", ImmutableList.of("dim1", "dim2"), publishedSegments.get(1).getDimensions() ); Assert.assertEquals("segment2 metrics", ImmutableList.of("met"), publishedSegments.get(1).getMetrics()); } private TaskStatus runTask(final Task task) throws Exception { final Task dummyTask = new DefaultObjectMapper().readValue( "{\"type\":\"noop\", \"isReadyResult\":\"exception\"}\"", Task.class ); final long startTime = System.currentTimeMillis(); Preconditions.checkArgument(!task.getId().equals(dummyTask.getId())); tq.add(dummyTask); tq.add(task); TaskStatus retVal = null; for (final String taskId : ImmutableList.of(dummyTask.getId(), task.getId())) { try { TaskStatus status; while ((status = tsqa.getStatus(taskId).get()).isRunnable()) { if (System.currentTimeMillis() > startTime + 10 * 1000) { throw new ISE("Where did the task go?!: %s", task.getId()); } Thread.sleep(100); } if (taskId.equals(task.getId())) { retVal = status; } } catch (Exception e) { throw Throwables.propagate(e); } } return retVal; } private RealtimeIndexTask giveMeARealtimeIndexTask() { String taskId = String.format("rt_task_%s", System.currentTimeMillis()); DataSchema dataSchema = new DataSchema( "test_ds", null, new AggregatorFactory[]{new LongSumAggregatorFactory("count", "rows")}, new UniformGranularitySpec(Granularity.DAY, QueryGranularity.NONE, null), mapper ); RealtimeIOConfig realtimeIOConfig = new RealtimeIOConfig( new MockFirehoseFactory(true), null, // PlumberSchool - Realtime Index Task always uses RealtimePlumber which is hardcoded in RealtimeIndexTask class null ); RealtimeTuningConfig realtimeTuningConfig = new RealtimeTuningConfig( 1000, new Period("P1Y"), null, //default window period of 10 minutes null, // base persist dir ignored by Realtime Index task null, null, null, null, null ); FireDepartment fireDepartment = new FireDepartment(dataSchema, realtimeIOConfig, realtimeTuningConfig); return new RealtimeIndexTask( taskId, new TaskResource(taskId, 1), fireDepartment, null ); } }
apache-2.0
GeoscienceAustralia/PyRate
tests/test_mpi_vs_multiprocess_vs_single_process.py
18387
# This Python module is part of the PyRate software package. # # Copyright 2022 Geoscience Australia # # 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. """ This Python module contains regression tests for comparing output from serial, parallel and MPI PyRate runs. """ import shutil import pytest from pathlib import Path from subprocess import check_call, CalledProcessError, run import numpy as np import pyrate.constants as C from pyrate.configuration import Configuration, write_config_file from tests.common import ( assert_same_files_produced, assert_two_dirs_equal, manipulate_test_conf, MEXICO_CROPA_CONF, TEST_CONF_GAMMA, PY37GDAL304, PY37GDAL302, PYTHON3P8, PYTHON3P7, WORKING_DIR ) @pytest.fixture(params=[0, 1]) def parallel(request): return request.param @pytest.fixture(params=[1, 4]) def local_crop(request): return request.param @pytest.fixture() def modified_config(tempdir, get_lks, get_crop, orbfit_lks, orbfit_method, orbfit_degrees, ref_est_method): def modify_params(conf_file, parallel_vs_serial, output_conf_file): tdir = Path(tempdir()) params = manipulate_test_conf(conf_file, tdir) if params[C.PROCESSOR] == 1: # turn on coherence for gamma params[C.COH_MASK] = 1 params[C.PARALLEL] = parallel_vs_serial params[C.PROCESSES] = 4 params[C.APSEST] = 1 params[C.IFG_LKSX], params[C.IFG_LKSY] = get_lks, get_lks params[C.REFNX], params[C.REFNY] = 2, 2 params[C.IFG_CROP_OPT] = get_crop params[C.ORBITAL_FIT_LOOKS_X], params[C.ORBITAL_FIT_LOOKS_Y] = orbfit_lks, orbfit_lks params[C.ORBITAL_FIT] = 1 params[C.ORBITAL_FIT_METHOD] = orbfit_method params[C.ORBITAL_FIT_DEGREE] = orbfit_degrees params[C.REF_EST_METHOD] = ref_est_method params[C.MAX_LOOP_LENGTH] = 3 params[C.LR_MAXSIG] = 0 # turn off pixel masking for these tests params["rows"], params["cols"] = 3, 2 params["savenpy"] = 1 params["notiles"] = params["rows"] * params["cols"] # number of tiles print(params) # write new temp config output_conf = tdir.joinpath(output_conf_file) write_config_file(params=params, output_conf_file=output_conf) return output_conf, params return modify_params @pytest.mark.mpi @pytest.mark.slow @pytest.mark.skipif(not PYTHON3P8, reason="Only run in one CI env") def test_pipeline_parallel_vs_mpi(modified_config, gamma_or_mexicoa_conf=TEST_CONF_GAMMA): """ Tests proving single/multiprocess/mpi produce same output """ gamma_conf = gamma_or_mexicoa_conf if np.random.rand() > 0.1: # skip 90% of tests randomly pytest.skip("Randomly skipping as part of 85 percent") if gamma_conf == MEXICO_CROPA_CONF: # skip cropA conf 95% time if np.random.rand() > 0.5: pytest.skip('skipped in mexicoA') print("\n\n") print("===x==="*10) mpi_conf, params = modified_config(gamma_conf, 0, 'mpi_conf.conf') run(f"mpirun -n 3 pyrate conv2tif -f {mpi_conf}", shell=True, check=True) run(f"mpirun -n 3 pyrate prepifg -f {mpi_conf}", shell=True, check=True) try: run(f"mpirun -n 3 pyrate correct -f {mpi_conf}", shell=True, check=True) run(f"mpirun -n 3 pyrate timeseries -f {mpi_conf}", shell=True, check=True) run(f"mpirun -n 3 pyrate stack -f {mpi_conf}", shell=True, check=True) run(f"mpirun -n 3 pyrate merge -f {mpi_conf}", shell=True, check=True) except CalledProcessError as e: print(e) pytest.skip("Skipping as part of correction error") mr_conf, params_m = modified_config(gamma_conf, 1, 'multiprocess_conf.conf') run(f"pyrate workflow -f {mr_conf}", shell=True, check=True) sr_conf, params_s = modified_config(gamma_conf, 0, 'singleprocess_conf.conf') run(f"pyrate workflow -f {sr_conf}", shell=True, check=True) # convert2tif tests, 17 interferograms if not gamma_conf == MEXICO_CROPA_CONF: assert_same_files_produced(params[C.INTERFEROGRAM_DIR], params_m[C.INTERFEROGRAM_DIR], params_s[C.INTERFEROGRAM_DIR], "*_unw.tif", 17) # dem assert_same_files_produced(params[C.GEOMETRY_DIR], params_m[C.GEOMETRY_DIR], params_s[C.GEOMETRY_DIR], "*_dem.tif", 1) # if coherence masking, comprare coh files were converted if params[C.COH_FILE_LIST] is not None: assert_same_files_produced(params[C.COHERENCE_DIR], params_m[C.COHERENCE_DIR], params_s[C.COHERENCE_DIR], "*_cc.tif", 17) print("coherence files compared") # prepifg checks num_of_ifgs = 30 if gamma_conf == MEXICO_CROPA_CONF else 17 num_of_coh = 30 if gamma_conf == MEXICO_CROPA_CONF else 17 # check geom files if params[C.DEMERROR]: # check files required by dem error correction are produced assert_same_files_produced( params[C.GEOMETRY_DIR], params_m[C.GEOMETRY_DIR], params_s[C.GEOMETRY_DIR], [ft + '.tif' for ft in C.GEOMETRY_OUTPUT_TYPES] + ['*dem.tif'], 7 if gamma_conf == MEXICO_CROPA_CONF else 8 ) # ifgs assert_same_files_produced(params[C.INTERFEROGRAM_DIR], params_m[C.INTERFEROGRAM_DIR], params_s[C.INTERFEROGRAM_DIR], ["*_ifg.tif"], num_of_ifgs) # coherence assert_same_files_produced(params[C.COHERENCE_DIR], params_m[C.COHERENCE_DIR], params_s[C.COHERENCE_DIR], ["*_coh.tif"], num_of_coh) # coherence stats assert_same_files_produced(params[C.COHERENCE_DIR], params_m[C.COHERENCE_DIR], params_s[C.COHERENCE_DIR], ["coh_*.tif"], 3) num_files = 30 if gamma_conf == MEXICO_CROPA_CONF else 17 # cf.TEMP_MLOOKED_DIR will contain the temp files that can be potentially deleted later assert_same_files_produced(params[C.TEMP_MLOOKED_DIR], params_m[C.TEMP_MLOOKED_DIR], params_s[C.TEMP_MLOOKED_DIR], "*_ifg.tif", num_files) # prepifg + correct steps that overwrite tifs test # ifg phase checking in the previous step checks the correct pipeline upto APS correction # 2 x because of aps files assert_same_files_produced(params[C.TMPDIR], params_m[C.TMPDIR], params_s[ C.TMPDIR], "tsincr_*.npy", params['notiles'] * 2) assert_same_files_produced(params[C.TMPDIR], params_m[C.TMPDIR], params_s[ C.TMPDIR], "tscuml_*.npy", params['notiles']) assert_same_files_produced(params[C.TMPDIR], params_m[C.TMPDIR], params_s[ C.TMPDIR], "linear_rate_*.npy", params['notiles']) assert_same_files_produced(params[C.TMPDIR], params_m[C.TMPDIR], params_s[ C.TMPDIR], "linear_error_*.npy", params['notiles']) assert_same_files_produced(params[C.TMPDIR], params_m[C.TMPDIR], params_s[ C.TMPDIR], "linear_intercept_*.npy", params['notiles']) assert_same_files_produced(params[C.TMPDIR], params_m[C.TMPDIR], params_s[ C.TMPDIR], "linear_rsquared_*.npy", params['notiles']) assert_same_files_produced(params[C.TMPDIR], params_m[C.TMPDIR], params_s[ C.TMPDIR], "linear_samples_*.npy", params['notiles']) assert_same_files_produced(params[C.TMPDIR], params_m[C.TMPDIR], params_s[ C.TMPDIR], "stack_rate_*.npy", params['notiles']) assert_same_files_produced(params[C.TMPDIR], params_m[C.TMPDIR], params_s[ C.TMPDIR], "stack_error_*.npy", params['notiles']) assert_same_files_produced(params[C.TMPDIR], params_m[C.TMPDIR], params_s[ C.TMPDIR], "stack_samples_*.npy", params['notiles']) # compare merge step assert_same_files_produced(params[C.VELOCITY_DIR], params_m[C.VELOCITY_DIR], params_s[ C.VELOCITY_DIR], "stack*.tif", 3) assert_same_files_produced(params[C.VELOCITY_DIR], params_m[C.VELOCITY_DIR], params_s[ C.VELOCITY_DIR], "stack*.kml", 2) assert_same_files_produced(params[C.VELOCITY_DIR], params_m[C.VELOCITY_DIR], params_s[ C.VELOCITY_DIR], "stack*.png", 2) assert_same_files_produced(params[C.VELOCITY_DIR], params_m[C.VELOCITY_DIR], params_s[ C.VELOCITY_DIR], "stack*.npy", 3) assert_same_files_produced(params[C.VELOCITY_DIR], params_m[C.VELOCITY_DIR], params_s[ C.VELOCITY_DIR], "linear_*.tif", 5) assert_same_files_produced(params[C.VELOCITY_DIR], params_m[C.VELOCITY_DIR], params_s[ C.VELOCITY_DIR], "linear_*.kml", 3) assert_same_files_produced(params[C.VELOCITY_DIR], params_m[C.VELOCITY_DIR], params_s[ C.VELOCITY_DIR], "linear_*.png", 3) assert_same_files_produced(params[C.VELOCITY_DIR], params_m[C.VELOCITY_DIR], params_s[ C.VELOCITY_DIR], "linear_*.npy", 5) if params[C.PHASE_CLOSURE]: # only in cropA __check_equality_of_phase_closure_outputs(mpi_conf, sr_conf) __check_equality_of_phase_closure_outputs(mpi_conf, mr_conf) assert_same_files_produced(params[C.TIMESERIES_DIR], params_m[C.TIMESERIES_DIR], params_s[ C.TIMESERIES_DIR], "tscuml*.tif", 11) # phase closure removes one tif assert_same_files_produced(params[C.TIMESERIES_DIR], params_m[C.TIMESERIES_DIR], params_s[ C.TIMESERIES_DIR], "tsincr*.tif", 11) else: assert_same_files_produced(params[C.TIMESERIES_DIR], params_m[C.TIMESERIES_DIR], params_s[ C.TIMESERIES_DIR], "tscuml*.tif", 12) assert_same_files_produced(params[C.TIMESERIES_DIR], params_m[C.TIMESERIES_DIR], params_s[ C.TIMESERIES_DIR], "tsincr*.tif", 12) print("==========================xxx===========================") shutil.rmtree(params[WORKING_DIR]) shutil.rmtree(params_m[WORKING_DIR]) shutil.rmtree(params_s[WORKING_DIR]) def __check_equality_of_phase_closure_outputs(mpi_conf, sr_conf): m_config = Configuration(mpi_conf) s_config = Configuration(sr_conf) m_close = m_config.closure() s_close = s_config.closure() m_closure = np.load(m_close.closure) s_closure = np.load(s_close.closure) # loops m_loops = np.load(m_close.loops, allow_pickle=True) s_loops = np.load(s_close.loops, allow_pickle=True) m_weights = [m.weight for m in m_loops] s_weights = [m.weight for m in s_loops] np.testing.assert_array_equal(m_weights, s_weights) for i, (m, s) in enumerate(zip(m_loops, s_loops)): assert all(m_e == s_e for m_e, s_e in zip(m.edges, s.edges)) # closure np.testing.assert_array_almost_equal(np.abs(m_closure), np.abs(s_closure), decimal=4) # num_occurrences_each_ifg m_num_occurences_each_ifg = np.load(m_close.num_occurences_each_ifg, allow_pickle=True) s_num_occurences_each_ifg = np.load(s_close.num_occurences_each_ifg, allow_pickle=True) np.testing.assert_array_equal(m_num_occurences_each_ifg, s_num_occurences_each_ifg) # check ps m_ifgs_breach_count = np.load(m_close.ifgs_breach_count) s_ifgs_breach_count = np.load(s_close.ifgs_breach_count) np.testing.assert_array_equal(m_ifgs_breach_count, s_ifgs_breach_count) @pytest.fixture(params=[0, 1]) def coh_mask(request): return request.param @pytest.fixture() def modified_config_short(tempdir, local_crop, get_lks, coh_mask): orbfit_lks = 1 orbfit_method = 1 orbfit_degrees = 1 ref_est_method = 1 ref_pixel = (150.941666654, -34.218333314) def modify_params(conf_file, parallel, output_conf_file, largetifs): tdir = Path(tempdir()) params = manipulate_test_conf(conf_file, tdir) params[C.COH_MASK] = coh_mask params[C.PARALLEL] = parallel params[C.PROCESSES] = 4 params[C.APSEST] = 1 params[C.LARGE_TIFS] = largetifs params[C.IFG_LKSX], params[C.IFG_LKSY] = get_lks, get_lks params[C.REFX], params[C.REFY] = ref_pixel params[C.REFNX], params[C.REFNY] = 4, 4 params[C.IFG_CROP_OPT] = local_crop params[C.ORBITAL_FIT_LOOKS_X], params[ C.ORBITAL_FIT_LOOKS_Y] = orbfit_lks, orbfit_lks params[C.ORBITAL_FIT] = 1 params[C.ORBITAL_FIT_METHOD] = orbfit_method params[C.ORBITAL_FIT_DEGREE] = orbfit_degrees params[C.REF_EST_METHOD] = ref_est_method params["rows"], params["cols"] = 3, 2 params["savenpy"] = 1 params["notiles"] = params["rows"] * params["cols"] # number of tiles # print(params) # write new temp config output_conf = tdir.joinpath(output_conf_file) write_config_file(params=params, output_conf_file=output_conf) return output_conf, params return modify_params @pytest.fixture def create_mpi_files(): def _create(modified_config_short, gamma_conf): mpi_conf, params = modified_config_short(gamma_conf, 0, 'mpi_conf.conf', 1) check_call(f"mpirun -n 3 pyrate conv2tif -f {mpi_conf}", shell=True) check_call(f"mpirun -n 3 pyrate prepifg -f {mpi_conf}", shell=True) try: check_call(f"mpirun -n 3 pyrate correct -f {mpi_conf}", shell=True) check_call(f"mpirun -n 3 pyrate timeseries -f {mpi_conf}", shell=True) check_call(f"mpirun -n 3 pyrate stack -f {mpi_conf}", shell=True) except CalledProcessError as c: print(c) pytest.skip("Skipping as we encountered a process error during CI") check_call(f"mpirun -n 3 pyrate merge -f {mpi_conf}", shell=True) return params return _create @pytest.mark.mpi @pytest.mark.slow @pytest.mark.skipif(not PY37GDAL304, reason="Only run in one CI env") def test_stack_and_ts_mpi_vs_parallel_vs_serial(modified_config_short, gamma_conf, create_mpi_files, parallel): """ Checks performed: 1. mpi vs single process pipeline 2. mpi vs parallel (python multiprocess) pipeline. 3. Doing 1 and 2 means we have checked single vs parallel python multiprocess pipelines 4. This also checks the entire pipeline using largetifs (new prepifg) vs old perpifg (python based) """ if np.random.randint(0, 1000) > 300: # skip 90% of tests randomly pytest.skip("Randomly skipping as part of 60 percent") print("\n\n") print("===x==="*10) params = create_mpi_files(modified_config_short, gamma_conf) sr_conf, params_p = modified_config_short(gamma_conf, parallel, 'parallel_conf.conf', 0) check_call(f"pyrate workflow -f {sr_conf}", shell=True) # convert2tif tests, 17 interferograms assert_two_dirs_equal(params[C.INTERFEROGRAM_DIR], params_p[C.INTERFEROGRAM_DIR], "*_unw.tif", 17) # if coherence masking, compare coh files were converted if params[C.COH_FILE_LIST] is not None: assert_two_dirs_equal(params[C.COHERENCE_DIR], params_p[C.COHERENCE_DIR], "*_cc.tif", 17) print("coherence files compared") assert_two_dirs_equal(params[C.INTERFEROGRAM_DIR], params_p[C.INTERFEROGRAM_DIR], ["*_ifg.tif"], 17) # one original dem, another multilooked dem assert_two_dirs_equal(params[C.GEOMETRY_DIR], params_p[C.GEOMETRY_DIR], ['*dem.tif'], 2) assert_two_dirs_equal(params[C.GEOMETRY_DIR], params_p[C.GEOMETRY_DIR], [t + "*.tif" for t in C.GEOMETRY_OUTPUT_TYPES], 6) # 2 dems, 6 geom assert_two_dirs_equal(params[C.TEMP_MLOOKED_DIR], params_p[C.TEMP_MLOOKED_DIR], "*_ifg.tif", 17) # ifg phase checking in the previous step checks the correct pipeline upto APS correction assert_two_dirs_equal(params[C.TMPDIR], params_p[C.TMPDIR], "tsincr_*.npy", params['notiles'] * 2) assert_two_dirs_equal(params[C.TMPDIR], params_p[C.TMPDIR], "tscuml_*.npy", params['notiles']) assert_two_dirs_equal(params[C.TMPDIR], params_p[C.TMPDIR], "linear_rate_*.npy", params['notiles']) assert_two_dirs_equal(params[C.TMPDIR], params_p[C.TMPDIR], "linear_error_*.npy", params['notiles']) assert_two_dirs_equal(params[C.TMPDIR], params_p[C.TMPDIR], "linear_samples_*.npy", params['notiles']) assert_two_dirs_equal(params[C.TMPDIR], params_p[C.TMPDIR], "linear_intercept_*.npy", params['notiles']) assert_two_dirs_equal(params[C.TMPDIR], params_p[C.TMPDIR], "linear_rsquared_*.npy", params['notiles']) assert_two_dirs_equal(params[C.TMPDIR], params_p[C.TMPDIR], "stack_rate_*.npy", params['notiles']) assert_two_dirs_equal(params[C.TMPDIR], params_p[C.TMPDIR], "stack_error_*.npy", params['notiles']) assert_two_dirs_equal(params[C.TMPDIR], params_p[C.TMPDIR], "stack_samples_*.npy", params['notiles']) # compare merge step assert_two_dirs_equal(params[C.VELOCITY_DIR], params_p[C.VELOCITY_DIR], "stack*.tif", 3) assert_two_dirs_equal(params[C.VELOCITY_DIR], params_p[C.VELOCITY_DIR], "stack*.kml", 2) assert_two_dirs_equal(params[C.VELOCITY_DIR], params_p[C.VELOCITY_DIR], "stack*.png", 2) assert_two_dirs_equal(params[C.VELOCITY_DIR], params_p[C.VELOCITY_DIR], "stack*.npy", 3) assert_two_dirs_equal(params[C.VELOCITY_DIR], params_p[C.VELOCITY_DIR], "linear*.tif", 5) assert_two_dirs_equal(params[C.VELOCITY_DIR], params_p[C.VELOCITY_DIR], "linear*.kml", 3) assert_two_dirs_equal(params[C.VELOCITY_DIR], params_p[C.VELOCITY_DIR], "linear*.png", 3) assert_two_dirs_equal(params[C.VELOCITY_DIR], params_p[C.VELOCITY_DIR], "linear*.npy", 5) assert_two_dirs_equal(params[C.TIMESERIES_DIR], params_p[C.TIMESERIES_DIR], "tscuml*.tif") assert_two_dirs_equal(params[C.TIMESERIES_DIR], params_p[C.TIMESERIES_DIR], "tsincr*.tif") assert_two_dirs_equal(params[C.TIMESERIES_DIR], params_p[C.TIMESERIES_DIR], "tscuml*.npy") assert_two_dirs_equal(params[C.TIMESERIES_DIR], params_p[C.TIMESERIES_DIR], "tsincr*.npy") print("==========================xxx===========================") shutil.rmtree(params[WORKING_DIR]) shutil.rmtree(params_p[WORKING_DIR])
apache-2.0
naver/ngrinder
ngrinder-controller/src/main/java/org/ngrinder/perftest/service/samplinglistener/PluginRunListener.java
2865
/* * 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.ngrinder.perftest.service.samplinglistener; import net.grinder.SingleConsole; import net.grinder.SingleConsole.SamplingLifeCycleListener; import net.grinder.statistics.StatisticsSet; import org.ngrinder.extension.OnTestSamplingRunnable; import org.ngrinder.model.PerfTest; import org.ngrinder.perftest.service.PerfTestService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.List; /** * Sampling LifeCycle listener to run the pluings implementing {@link OnTestSamplingRunnable}. * * @since 3.1 */ public class PluginRunListener implements SamplingLifeCycleListener { private static final Logger LOGGER = LoggerFactory.getLogger(MonitorCollectorPlugin.class); private final List<OnTestSamplingRunnable> plugins; private final SingleConsole singleConsole; private final PerfTest perfTest; private final PerfTestService perfTestService; public PluginRunListener(List<OnTestSamplingRunnable> plugins, SingleConsole singleConsole, PerfTest perfTest, PerfTestService perfTestService) { this.plugins = plugins; this.singleConsole = singleConsole; this.perfTest = perfTest; this.perfTestService = perfTestService; } @Override public void onSamplingStarted() { for (OnTestSamplingRunnable each : plugins) { try { each.startSampling(singleConsole, perfTest, perfTestService); } catch (Exception e) { LOGGER.error("While running plugins, the error occurred : {}", e.getMessage()); LOGGER.debug("Details : ", e); } } } @Override public void onSampling(File file, StatisticsSet intervalStatistics, StatisticsSet cumulativeStatistics) { for (OnTestSamplingRunnable each : plugins) { try { each.sampling(singleConsole, perfTest, perfTestService, intervalStatistics, cumulativeStatistics); } catch (Exception e) { LOGGER.error("While running plugin the following error occurred : {}", e.getMessage()); LOGGER.debug("Details : ", e); } } } @Override public void onSamplingEnded() { for (OnTestSamplingRunnable each : plugins) { try { each.endSampling(singleConsole, perfTest, perfTestService); } catch (Exception e) { LOGGER.error("While running plugin the following error occurs : {}", e.getMessage()); LOGGER.debug("Details : ", e); } } } }
apache-2.0
aaronpmishkin/CUCSC-ValueCharts
client/modules/ValueChart/renderers/ScoreFunction.renderer.ts
21399
/* * @Author: aaronpmishkin * @Date: 2016-06-07 15:34:15 * @Last Modified by: aaronpmishkin * @Last Modified time: 2017-06-01 14:05:32 */ // Import Angular Classes: import { Injectable } from '@angular/core'; // Import Libraries: import * as d3 from 'd3'; import { Subject } from 'rxjs/Subject'; // Import Application Classes: import { ChartUndoRedoService } from '../services/ChartUndoRedo.service'; // Import Model Classes: import { Objective } from '../../../model/Objective'; import { PrimitiveObjective } from '../../../model/PrimitiveObjective'; import { ScoreFunction } from '../../../model/ScoreFunction'; import { ContinuousScoreFunction } from '../../../model/ContinuousScoreFunction'; import { DiscreteScoreFunction } from '../../../model/DiscreteScoreFunction'; import { ContinuousDomain } from '../../../model/ContinuousDomain'; import { ExpandScoreFunctionInteraction } from '../interactions/ExpandScoreFunction.interaction'; import { AdjustScoreFunctionInteraction } from '../interactions/AdjustScoreFunction.interaction'; import { DomainElement, ScoreFunctionData } from '../../../types/RendererData.types'; import { RendererUpdate } from '../../../types/RendererData.types'; import { InteractionConfig, ViewConfig } from '../../../types/Config.types' import { ScoreFunctionUpdate, ScoreFunctionConfig } from '../../../types/RendererData.types'; import { ChartOrientation } from '../../../types/Config.types'; // This class is the base class for DiscreteScoreFuntionRenderer, and ContinuousScoreFunctionRenderer. It contains the logic for creating and rendering the // axis, labels, and base containers of a ScoreFunction. It is an abstract class and should NOT be instantiated or used for any reason. This class has // uses outside of rendering a ValueChart, and as such is decoupled as much as possible from the services associated with the ValueChartDirective. @Injectable() export abstract class ScoreFunctionRenderer { // ======================================================================================== // Fields // ======================================================================================== protected domainSize: number; // The number of domain elements the score function needs to plot. protected objective: PrimitiveObjective; // The primitive objective this renderer is creating a plot for. protected scoreFunctionData: ScoreFunctionData[]; // The data that this class is rendering. protected enableInteraction: boolean; // Whether or not the score functions may be adjusted // d3 Selections: public rootContainer: d3.Selection<any, any, any, any>; // The 'g' element that is the root container of the score function plot. public outlineContainer: d3.Selection<any, any, any, any>; public plotOutline: d3.Selection<any, any, any, any>; // The 'rect' element that is used to outline the score function plot public plotContainer: d3.Selection<any, any, any, any>; // The 'g' element that contains the plot itself. public domainLabelContainer: d3.Selection<any, any, any, any>; // The 'g' element that contains the labels for each domain element. public domainLabels: d3.Selection<any, any, any, any>; // The selection of 'text' elements s.t. each element is a label for one domain element. public plotElementsContainer: d3.Selection<any, any, any, any>; // The 'g' element that holds the elements making up the plot, like points and fit lines, or bars. public userContainers: d3.Selection<any, any, any, any>; // The selection of 'g' elements s.t. each element is a container for the plot elements of one user. public axisContainer: d3.Selection<any, any, any, any>; // The 'g' element that conntains the y and x axis. public domainAxis: d3.Selection<any, any, any, any>; public unitsLabel: d3.Selection<any, any, any, any>; public utilityAxisContainer: d3.Selection<any, any, any, any>; public lastRendererUpdate: ScoreFunctionUpdate; protected numUsers: number; protected viewOrientation: ChartOrientation; public adjustScoreFunctionInteraction: AdjustScoreFunctionInteraction; public expandScoreFunctionInteraction: ExpandScoreFunctionInteraction; // class name definitions for SVG elements that are created by this renderer. public static defs = { OUTLINE_CONTAINER: 'scorefunction-outline-container', PLOT_OUTLINE: 'scorefunction-plot-outline', PLOT_CONTAINER: 'scorefunction-plot-container', USER_CONTAINER: 'scorefunction-user-container', DOMAIN_LABELS_CONTAINER: 'scorefunction-plot-domain-labels-container', DOMAIN_LABEL: 'scorefunction-domain-labels', PLOT_ELEMENTS_CONTAINER: 'scorefunction-plot-elements-container', AXES_CONTAINER: 'scorefunction-axes-container', UTILITY_AXIS_CONTAINER: 'scorefunction-utility-axis', DOMAIN_AXIS: 'scorefunction-domain-axis', UNITS_LABEL: 'scorefunction-units-label' }; // ======================================================================================== // Constructor // ======================================================================================== /* @returns {void} @description Used for Angular's dependency injection. However, this class is frequently constructed manually unlike the other renderer classes. This constructor should not be used to do any initialization of the class. Note that the dependencies of the class are intentionally being kept to a minimum. */ constructor( public chartUndoRedoService: ChartUndoRedoService) { this.adjustScoreFunctionInteraction = new AdjustScoreFunctionInteraction(this.chartUndoRedoService); this.expandScoreFunctionInteraction = new ExpandScoreFunctionInteraction(this.chartUndoRedoService); } // ======================================================================================== // Methods // ======================================================================================== public scoreFunctionChanged = (update: ScoreFunctionUpdate) => { this.lastRendererUpdate = update; if (this.rootContainer == undefined) { this.createScoreFunction(update); this.renderScoreFunction(update, (this.numUsers != update.scoreFunctions.length || this.viewOrientation != update.viewOrientation)); this.applyStyles(update); this.numUsers = update.scoreFunctions.length; return; } if (this.numUsers != update.scoreFunctions.length) { this.createPlot(update, this.plotElementsContainer, this.domainLabelContainer); } this.updateInteractions(update); this.renderScoreFunction(update, (this.numUsers != update.scoreFunctions.length || this.viewOrientation != update.viewOrientation)); if (update.styleUpdate) { this.applyStyles(update); } this.numUsers = update.scoreFunctions.length; this.viewOrientation = update.viewOrientation; } public viewConfigChanged = (displayScoreFunctionValueLabels: boolean) => { this.toggleValueLabels(displayScoreFunctionValueLabels); } public interactionConfigChanged = (interactionConfig: any) => { this.expandScoreFunctionInteraction.toggleExpandScoreFunction(interactionConfig.expandScoreFunctions, this.rootContainer.node().querySelectorAll('.' + ScoreFunctionRenderer.defs.PLOT_OUTLINE), this.lastRendererUpdate); } public updateInteractions = (u: ScoreFunctionUpdate) => { this.expandScoreFunctionInteraction.lastRendererUpdate = u; this.adjustScoreFunctionInteraction.lastRendererUpdate = u; } /* @param el - The element that to be used as the parent of the objective chart. @param objective - The objective for which the score function plot is going to be created. @returns {void} @description Creates the base containers and elements for a score function plot. It should be called as the first step of creating a score function plot. sub classes of this class should call createScoreFunction before creating any of their specific elements. */ protected createScoreFunction(u: ScoreFunctionUpdate): void { var objectiveId: string = u.objective.getId(); this.objective = u.objective; // The root container is passed in. this.rootContainer = u.el; // Create the a container for the plot outlines, and the plot outlines itself. this.outlineContainer = u.el.append('g') .classed(ScoreFunctionRenderer.defs.OUTLINE_CONTAINER, true) .attr('id', 'scorefunction-' + objectiveId + '-outline-container'); this.plotOutline = this.outlineContainer .append('rect') .classed(ScoreFunctionRenderer.defs.PLOT_OUTLINE, true) .attr('id', 'scorefunction-' + objectiveId + '-outline') .classed('valuechart-outline', true); // Create a container to hold all the elements of the plot. this.plotContainer = u.el.append('g') .classed(ScoreFunctionRenderer.defs.PLOT_CONTAINER, true) .attr('id', 'scorefunction-' + objectiveId + '-plot-container'); this.createScoreFunctionAxis(this.plotContainer, objectiveId); this.domainLabelContainer = this.plotContainer.append('g') // Create a container to hold the domain axis labels. .classed(ScoreFunctionRenderer.defs.DOMAIN_LABELS_CONTAINER, true) .attr('id', 'scorefunction-' + objectiveId + '-domain-labels-container'); this.plotElementsContainer = this.plotContainer.append('g') // create a container to hold all the elements of the plot, like points, lines, bars, etc. .classed(ScoreFunctionRenderer.defs.PLOT_ELEMENTS_CONTAINER, true) .classed('scorefunction-' + objectiveId + '-plot-elements-container', true); this.createPlot(u, this.plotElementsContainer, this.domainLabelContainer); } /* @param plotContainer - The 'g' element that is intended to contain the score function plot. @param objectiveId - The id of the objective for which this score function plot is being created. This is for use in setting element IDs. @returns {void} @description Creates the axes of a score function plot, both x and y, and creates the utility axis labels. Note that the domain labels are created in createPlot because they are data dependent. */ protected createScoreFunctionAxis(plotContainer: d3.Selection<any, any, any, any>, objectiveId: string): void { this.axisContainer = plotContainer.append('g') .classed(ScoreFunctionRenderer.defs.AXES_CONTAINER, true) .attr('id', 'scorefunction-' + objectiveId + '-axes-container'); this.domainAxis = this.axisContainer.append('line') .classed(ScoreFunctionRenderer.defs.DOMAIN_AXIS, true) .attr('id', 'scorefunction-' + objectiveId + '-domain-axis'); let unitsText = ""; let dom = this.objective.getDomain(); if (dom.type === 'continuous' && (<ContinuousDomain>dom).unit !== undefined ) { unitsText = (<ContinuousDomain>dom).unit; } this.unitsLabel = this.axisContainer.append('text') .classed(ScoreFunctionRenderer.defs.UNITS_LABEL, true) .attr('id', 'scorefunction-' + objectiveId + '-units-label') .text(unitsText); this.utilityAxisContainer = this.axisContainer.append('g') .classed(ScoreFunctionRenderer.defs.UTILITY_AXIS_CONTAINER, true) .attr('id', 'scorefunction-' + objectiveId + '-utility-axis-container'); } /* @param plotElementsContainer - The 'g' element that is intended to contain the user containers. These are 'g' elements that will contain the parts of each users plot (bars/points). @param domainLabelContainer - The 'g' element that is intended to contain the labels for the domain (x) axis. @param objective - The objective for which the score function plot is going to be created. @param scoreFunctionData - The correctly formatted data for underlying the points/bars of the score function plot. This format allows the plot to show multiple users' score functions. @returns {void} @description Creates the user containers, which will contain each user's plot elements, and the domain labels for the domain element axis. DiscreteScoreFunction and ContinuousScoreFunction extend this method in order to create the additional SVG elements they need. This method is also used to update a score function plot when the Users change. */ protected createPlot(u: ScoreFunctionUpdate, plotElementsContainer: d3.Selection<any, any, any, any>, domainLabelContainer: d3.Selection<any, any, any, any>): void { var objectiveId = u.objective.getId(); // Create the user containers. Each user should have one 'g' element that will hold the elements of its plot. Elements refers to bars, points, fit lines, etc. var updateUserContainers = plotElementsContainer.selectAll('.' + ScoreFunctionRenderer.defs.USER_CONTAINER) .data(u.scoreFunctionData); updateUserContainers.exit().remove(); updateUserContainers.enter().append('g') .classed(ScoreFunctionRenderer.defs.USER_CONTAINER, true) .attr('id', (d: ScoreFunctionData) => { return 'scorefunction-' + d.color.replace(/\s+/g, '') + '-container'; }); this.userContainers = plotElementsContainer.selectAll('.' + ScoreFunctionRenderer.defs.USER_CONTAINER) var updateDomainLabels = domainLabelContainer.selectAll('.' + ScoreFunctionRenderer.defs.DOMAIN_LABEL) .data(u.scoreFunctionData.length > 0 ? u.scoreFunctionData[0].elements : []); updateDomainLabels.exit().remove(); // Create one label for each element of the PrimitiveObjective's domain. updateDomainLabels .enter().append('text') .classed(ScoreFunctionRenderer.defs.DOMAIN_LABEL, true) .attr('id', (d: DomainElement) => { return 'scorefunction-' + objectiveId + '-' + d.element + '-label'; }); this.domainLabels = domainLabelContainer.selectAll('.' + ScoreFunctionRenderer.defs.DOMAIN_LABEL); } /* @param objective - The objective for which the score function plot is going to be created. @param width - The width of the area in which to render the score function plot. @param height - The height of the area in which to render the score function plot. @param viewOrientation - The orientation of the score function plot. Must be either 'vertical', or 'horizontal'. @returns {void} @description Initializes the view configuration for the score function plot, and then positions + styles its elements. This method should be used whenever the score function plot needs to be rendered for the first time, or when updated in response to changes to users' ScoreFunctions. View configuration must be done here because this class intentionally avoids using the renderConfigService class. It uses calls to the render plot method (which is overwritten by subclasses), and the renderAxesDimensionTwo to render the different parts of the score function plot. */ protected renderScoreFunction(u: ScoreFunctionUpdate, updateDimensionOne: boolean): void { this.domainSize = u.scoreFunctionData.length > 0 ? u.scoreFunctionData[0].elements.length : 0; // Give the plot outline the correct dimensions. this.plotOutline .attr(u.rendererConfig.dimensionOne, u.rendererConfig.dimensionOneSize - 1) .attr(u.rendererConfig.dimensionTwo, u.rendererConfig.dimensionTwoSize); this.renderAxesDimensionTwo(u); if (updateDimensionOne) this.renderAxesDimensionOne(u); this.renderPlot(u, updateDimensionOne); } protected renderAxesDimensionOne(u: ScoreFunctionUpdate): void { // Position the domain axis. this.domainAxis .attr(u.rendererConfig.coordinateOne + '1', u.rendererConfig.utilityAxisCoordinateOne) .attr(u.rendererConfig.coordinateOne + '2', u.rendererConfig.domainAxisMaxCoordinateOne); this.unitsLabel .attr(u.rendererConfig.coordinateOne, u.rendererConfig.domainAxisMaxCoordinateOne / 2); var labelCoordinateOneOffset: number; if (u.viewOrientation === ChartOrientation.Vertical) { labelCoordinateOneOffset = u.rendererConfig.labelOffset; } else { labelCoordinateOneOffset = (1.5 * u.rendererConfig.labelOffset); } // Position the domain labels along the domain (x) axis. this.domainLabels .attr(u.rendererConfig.coordinateOne, (d: DomainElement, i: number) => { return (((u.rendererConfig.domainAxisMaxCoordinateOne - u.rendererConfig.utilityAxisCoordinateOne) / this.domainSize) * i) + labelCoordinateOneOffset; }) // Position the domain labels at even intervals along the axis. .text((d: DomainElement) => { return d.element; }); } /* @param axisContainer - The 'g' element that the axes elements are in. @param viewOrientation - The orientation of the score function plot. Must be either 'vertical', or 'horizontal'. @returns {void} @description Positions and styles the elements of both the domain (y) and utility axes (x). This method should NOT be called manually. Rendering the axes elements should be done as part of a call to renderScoreFunction instead. */ protected renderAxesDimensionTwo(u: ScoreFunctionUpdate): void { this.domainAxis .attr(u.rendererConfig.coordinateTwo + '1', u.rendererConfig.domainAxisCoordinateTwo) .attr(u.rendererConfig.coordinateTwo + '2', u.rendererConfig.domainAxisCoordinateTwo); this.unitsLabel .attr(u.rendererConfig.coordinateTwo, u.rendererConfig.domainAxisCoordinateTwo + u.rendererConfig.labelOffset - 2); var labelCoordinateTwo: number; if (u.viewOrientation === ChartOrientation.Vertical) { labelCoordinateTwo = u.rendererConfig.domainAxisCoordinateTwo + u.rendererConfig.labelOffset - 12; } else { labelCoordinateTwo = u.rendererConfig.domainAxisCoordinateTwo - (u.rendererConfig.labelOffset); } this.domainLabels .attr(u.rendererConfig.coordinateTwo, labelCoordinateTwo) // Delete the elements of the previous utility axis. var elements: any = this.utilityAxisContainer.node().children; for (var i = 0; i < elements.length; i++) { elements[i].remove(); } // Create the new Scale for use creating the utility axis. var uilityScale: d3.ScaleLinear<number, number> = d3.scaleLinear() .domain([0, 1]) // Calculate the correct height of the utility axis. var utilityScaleHeight: number = (u.viewOrientation === ChartOrientation.Vertical) ? (u.rendererConfig.domainAxisCoordinateTwo - u.rendererConfig.utilityAxisMaxCoordinateTwo) : (u.rendererConfig.utilityAxisMaxCoordinateTwo - u.rendererConfig.domainAxisCoordinateTwo); var utilityAxis: any; // The range of the scale must be inverted for the vertical axis because pixels coordinates set y to increase downwards, rather than upwards as normal. if (u.viewOrientation === ChartOrientation.Vertical) { uilityScale.range([utilityScaleHeight, 0]); utilityAxis = d3.axisLeft(uilityScale); } else { uilityScale.range([0, utilityScaleHeight]); utilityAxis = d3.axisTop(uilityScale); } // The utility axis should have two ticks. For some reason 1 is the way to do this... utilityAxis.ticks(1); // Position the axis by positioning the axis container and then create it. this.utilityAxisContainer .attr('transform', () => { return 'translate(' + ((u.viewOrientation === ChartOrientation.Vertical) ? ((u.rendererConfig.utilityAxisCoordinateOne + 4) + ',' + (u.rendererConfig.utilityAxisMaxCoordinateTwo - .5) + ')') : ((u.rendererConfig.domainAxisCoordinateTwo - .5) + ', ' + (u.rendererConfig.utilityAxisCoordinateOne + 4) + ')')); }) .call(utilityAxis); } /* @param domainLabels - The selection 'text' elements used to label the domain axis. @param plotElementsContainer - The 'g' element that contains the userContainers elements. @param objective - The objective for which the score function plot is being rendered. @param scoreFunctionData - The correctly formatted data for underlying the points/bars of the score function plot. This format allows the plot to show multiple users' score functions. @param viewOrientation - The orientation of the score function plot. Must be either 'vertical', or 'horizontal'. @returns {void} @description Positions and styles the elements created by createPlot. Like createPlot, it is extended by DiscreteScoreFunction and ContinuousScoreFunction in order to render their specific elements. This method should NOT be called manually. Instead it should be called as a part of calling renderScoreFunction to re-render the entire score function plot. Note that parameters not actively used in this method are used in the extended methods of the subclasses. */ protected abstract renderPlot(u: ScoreFunctionUpdate, updateDimensionOne: boolean): void; protected abstract toggleValueLabels(displayScoreFunctionValueLabels: boolean): void; protected applyStyles(u: ScoreFunctionUpdate): void { this.domainAxis .style('stroke-width', 1) .style('stroke', 'black'); this.unitsLabel.style('font-size', '10px'); this.utilityAxisContainer.style('font-size', 8); this.domainLabels.style('font-size', '9px'); } // ======================================================================================== // Anonymous functions that are used often enough to be made class fields // ======================================================================================== calculatePlotElementCoordinateOne = (d: DomainElement, i: number) => { return (((this.lastRendererUpdate.rendererConfig.domainAxisMaxCoordinateOne - this.lastRendererUpdate.rendererConfig.utilityAxisCoordinateOne) / this.domainSize) * i) + this.lastRendererUpdate.rendererConfig.labelOffset * 1.5; } }
apache-2.0
aoehmichen/eae-docker
workerSparkExample/Dockerfile
1847
FROM aoehmich/cdh5.9:release-candidate MAINTAINER Axel Oehmichen <[email protected]> ADD Cloudera_Management.py /root ADD start_eae.sh /root ## We install all the dependencies RUN apt-get update -q \ && apt-get install -y vim git wget curl zip python-numpy python-scipy python-matplotlib python-pip python-scikits-learn libcurl4-openssl-dev libncurses-dev libxml2-dev \ && apt-get install -y libcurl4-gnutls-dev tcl-dev psmisc openssh-server \ && pip install scimath \ && pip install cm-api \ && pip install pymongo ## We install openlava RUN curl -L https://github.com/aoehmichen/eae-files/raw/master/op.tar.gz -o /root/op.tar.gz \ && tar zxvf /root/op.tar.gz openlava-3.3 \ && cd openlava-3.* \ && ./configure \ && make \ && make install \ && cd config \ && cp lsb.hosts lsb.params lsb.queues lsb.users lsf.cluster.openlava lsf.conf lsf.shared lsf.task openlava.* /opt/openlava-3.3/etc/ \ && useradd -r openlava \ && chown -R openlava:openlava /opt/openlava-3.*/ \ && cp /opt/openlava-3.*/etc/openlava /etc/init.d \ && update-rc.d openlava defaults \ && cp /opt/openlava-3.3/etc/openlava.* /etc/profile.d \ && chown openlava:openlava /etc/profile.d/openlava.* \ && chmod 755 /etc/profile.d/openlava.sh \ && chown openlava:openlava /opt/openlava-3.3/etc/* # We set up the ssh keys for user eae RUN mkdir -p /home/eae/.ssh && chmod 700 /home/eae/.ssh \ && echo "Host *" > /home/eae/.ssh/config \ && echo " StrictHostKeyChecking no" >> /home/eae/.ssh/config \ && chown -R eae:eae /home/eae/.ssh/ WORKDIR /usr/lib/jvm # We need to locate the proper java for Hadoop RUN ln -s java-7-oracle-cloudera/ default-java EXPOSE 22 16322 16323 16324 16325 EXPOSE 16322/udp ENTRYPOINT ["bash", "/root/start_eae.sh"] CMD ["-bash"]
apache-2.0
abhishekdepro/libman
LibraryManager/LibraryManager/Account/Login.aspx.cs
2903
using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.AspNet.Identity.Owin; using Microsoft.Owin.Security; using System; using System.Linq; using System.Web; using System.Web.UI; using LibraryManager.Models; using Library; using System.Data; namespace LibraryManager.Account { public partial class Login : Page { protected void Page_Load(object sender, EventArgs e) { RegisterHyperLink.NavigateUrl = "Register"; //Session["user"] = null; var returnUrl = HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]); if (!String.IsNullOrEmpty(returnUrl)) { RegisterHyperLink.NavigateUrl += "?ReturnUrl=" + returnUrl; } if (Session["user"] == null) { } else { UserName.Text = Session["user"].ToString(); error.Text = "Already logged in!"; } } protected void LogIn(object sender, EventArgs e) { Session["user"] = null; Users u = new Users(); if(u.SignIn(UserName.Text,Password.Text)==true) { //Context.User.Identity.Name = UserName.Text; Session["user"] = UserName.Text; if (UserName.Text == "admin") { Response.Redirect("/newbook.aspx"); } else { Response.Redirect("/Profile.aspx"); } } else { error.Text = "Wrong credentials!"; } } protected void logout_Click(object sender, EventArgs e) { Session["user"] = null; UserName.Text = ""; Password.Text = ""; error.Text = "Successfully logged out!"; } protected void forget_password_CheckedChanged(object sender, EventArgs e) { string pass = "", to=""; if (forget_password.Checked == true) { if (UserName.Text != "") { mail m = new mail(); Users u = new Users(); DataTable dt = u.getuser(UserName.Text); foreach (DataRow row in dt.Rows) { pass = row["pass"].ToString(); to = row["email"].ToString(); } m.recoverpassword(to, pass); error.Text = "Please check your email id for password!"; } else { error.Text = "Enter username first!"; } } } } }
apache-2.0
bayvictor/distributed-polling-system
bin/aptget_touch_support.sh
1838
echo "apt-cache search touch | sed 's/^/sudo apt-get install -y -y /g;s/ - / #- /g' " sudo apt-get install -y -y gimp #- The GNU Image Manipulation Program sudo apt-get install -y -y coreutils #- GNU core utilities sudo apt-get install -y -y libpam0g #- Pluggable Authentication Modules library sudo apt-get install -y -y libgrip0 #- Shared library providing multitouch gestures to GTK+ apps. sudo apt-get install -y -y libusbmuxd1 #- USB multiplexor daemon for iPhone and iPod Touch devices #- library sudo apt-get install -y -y libutouch-evemu1 #- Kernel Device Emulation Library sudo apt-get install -y -y libts-0.0-0 #- touch screen library sudo apt-get install -y -y libimobiledevice2 #- Library for communicating with the iPhone and iPod Touch sudo apt-get install -y -y libutouch-frame1 #- Touch Frame Library sudo apt-get install -y -y xserver-xorg-input-synaptics #- Synaptics TouchPad driver for X.Org server sudo apt-get install -y -y gimp-plugin-registry #- repository of optional extensions for GIMP sudo apt-get install -y -y lockfile-progs #- Programs for locking and unlocking files and mailboxes sudo apt-get install -y -y libutouch-geis1 #- Gesture engine interface support sudo apt-get install -y -y ginn #- Gesture Injector: No-GEIS, No-Toolkits sudo apt-get install -y -y tsconf #- touch screen library common files sudo apt-get install -y -y libmtdev1 #- Multitouch Protocol Translation Library #- shared library sudo apt-get install -y -y libutouch-grail1 #- Gesture Recognition And Instantiation Library sudo apt-get install -y -y ptouch-driver #- CUPS/Foomatic driver for Brother P-touch label printers sudo apt-get install -y -y inputattach #- utility to connect serial-attached peripherals to the input subsystem sudo apt-get install -y -y usbmuxd #- USB multiplexor daemon for iPhone and iPod Touch devices
apache-2.0
aws/aws-sdk-java
aws-java-sdk-config/src/main/java/com/amazonaws/services/config/model/transform/EvaluationResultIdentifierMarshaller.java
2519
/* * Copyright 2017-2022 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.config.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.config.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * EvaluationResultIdentifierMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class EvaluationResultIdentifierMarshaller { private static final MarshallingInfo<StructuredPojo> EVALUATIONRESULTQUALIFIER_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("EvaluationResultQualifier").build(); private static final MarshallingInfo<java.util.Date> ORDERINGTIMESTAMP_BINDING = MarshallingInfo.builder(MarshallingType.DATE) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("OrderingTimestamp").timestampFormat("unixTimestamp").build(); private static final EvaluationResultIdentifierMarshaller instance = new EvaluationResultIdentifierMarshaller(); public static EvaluationResultIdentifierMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(EvaluationResultIdentifier evaluationResultIdentifier, ProtocolMarshaller protocolMarshaller) { if (evaluationResultIdentifier == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(evaluationResultIdentifier.getEvaluationResultQualifier(), EVALUATIONRESULTQUALIFIER_BINDING); protocolMarshaller.marshall(evaluationResultIdentifier.getOrderingTimestamp(), ORDERINGTIMESTAMP_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
apache-2.0
mitchellrj/touchdown
touchdown/ssh/connection.py
3610
# Copyright 2015 Isotoma Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import time from touchdown.core import adapters, argument, errors, plan, serializers, workspace try: from . import client from paramiko import ssh_exception except ImportError: client = None from touchdown.provisioner import Target class Instance(adapters.Adapter): pass class Connection(Target): resource_name = "ssh_connection" username = argument.String(default="root", field="username") password = argument.String(field="password") private_key = argument.String(field="pkey", serializer=serializers.Identity()) hostname = argument.String(field="hostname") instance = argument.Resource(Instance, field="hostname", serializer=serializers.Resource()) port = argument.Integer(field="port", default=22) proxy = argument.Resource("touchdown.ssh.connection.Connection") root = argument.Resource(workspace.Workspace) def clean_private_key(self, private_key): if private_key and client: return client.private_key_from_string(private_key) raise errors.InvalidParameter("Invalid SSH private key") class ConnectionPlan(plan.Plan): name = "describe" resource = Connection _client = None def get_client(self): if self._client: return self._client cli = client.Client(self) kwargs = serializers.Resource().render(self.runner, self.resource) if self.resource.proxy: self.echo("Setting up connection proxy via {}".format(self.resource.proxy)) proxy = self.runner.get_plan(self.resource.proxy) transport = proxy.get_client().get_transport() self.echo("Setting up proxy channel to {}".format(kwargs['hostname'])) for i in range(20): try: kwargs['sock'] = transport.open_channel( 'direct-tcpip', (kwargs['hostname'], kwargs['port']), ('', 0) ) break except ssh_exception.ChannelException: time.sleep(i) continue if 'sock' not in kwargs: raise errors.Error("Error setting up proxy channel to {} after 20 tries".format(kwargs['hostname'])) self.echo("Proxy setup") if not self.resource.password and not self.resource.private_key: kwargs['look_for_keys'] = True kwargs['allow_agent'] = True args = ["hostname={}".format(kwargs['hostname']), "username={}".format(kwargs['username'])] if self.resource.port != 22: args.append("port={}".format(kwargs['port'])) self.echo("Establishing ssh connection ({})".format(", ".join(args))) cli.connect(**kwargs) self.echo("Got connection") self._client = cli return cli def get_actions(self): if not client: raise errors.Error("Paramiko library is required to perform operations involving ssh") return []
apache-2.0
amygithub/vavr
vavr/src/test/java/io/vavr/collection/HashSetTest.java
15210
/* __ __ __ __ __ ___ * \ \ / / \ \ / / __/ * \ \/ / /\ \ \/ / / * \____/__/ \__\____/__/ * * Copyright 2014-2017 Vavr, http://vavr.io * * 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.vavr.collection; import io.vavr.Tuple; import io.vavr.Value; import io.vavr.Tuple2; import org.assertj.core.api.*; import org.junit.Test; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Spliterator; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collector; import static org.junit.Assert.assertTrue; public class HashSetTest extends AbstractSetTest { @Override protected <T> IterableAssert<T> assertThat(Iterable<T> actual) { return new IterableAssert<T>(actual) { @Override public IterableAssert<T> isEqualTo(Object obj) { @SuppressWarnings("unchecked") final Iterable<T> expected = (Iterable<T>) obj; final java.util.Map<T, Integer> actualMap = countMap(actual); final java.util.Map<T, Integer> expectedMap = countMap(expected); assertThat(actualMap.size()).isEqualTo(expectedMap.size()); actualMap.keySet().forEach(k -> assertThat(actualMap.get(k)).isEqualTo(expectedMap.get(k))); return this; } private java.util.Map<T, Integer> countMap(Iterable<? extends T> it) { final java.util.HashMap<T, Integer> cnt = new java.util.HashMap<>(); it.forEach(i -> cnt.merge(i, 1, (v1, v2) -> v1 + v2)); return cnt; } }; } @Override protected <T> ObjectAssert<T> assertThat(T actual) { return new ObjectAssert<T>(actual) { }; } @Override protected BooleanAssert assertThat(Boolean actual) { return new BooleanAssert(actual) { }; } @Override protected DoubleAssert assertThat(Double actual) { return new DoubleAssert(actual) { }; } @Override protected IntegerAssert assertThat(Integer actual) { return new IntegerAssert(actual) { }; } @Override protected LongAssert assertThat(Long actual) { return new LongAssert(actual) { }; } @Override protected StringAssert assertThat(String actual) { return new StringAssert(actual) { }; } // -- construction @Override protected <T> Collector<T, ArrayList<T>, HashSet<T>> collector() { return HashSet.collector(); } @Override protected <T> HashSet<T> empty() { return HashSet.empty(); } @Override protected <T> HashSet<T> emptyWithNull() { return empty(); } @Override protected <T> HashSet<T> of(T element) { return HashSet.of(element); } @SuppressWarnings("varargs") @SafeVarargs @Override protected final <T> HashSet<T> of(T... elements) { return HashSet.of(elements); } @Override protected <T> HashSet<T> ofAll(Iterable<? extends T> elements) { return HashSet.ofAll(elements); } @Override protected <T extends Comparable<? super T>> HashSet<T> ofJavaStream(java.util.stream.Stream<? extends T> javaStream) { return HashSet.ofAll(javaStream); } @Override protected HashSet<Boolean> ofAll(boolean... elements) { return HashSet.ofAll(elements); } @Override protected HashSet<Byte> ofAll(byte... elements) { return HashSet.ofAll(elements); } @Override protected HashSet<Character> ofAll(char... elements) { return HashSet.ofAll(elements); } @Override protected HashSet<Double> ofAll(double... elements) { return HashSet.ofAll(elements); } @Override protected HashSet<Float> ofAll(float... elements) { return HashSet.ofAll(elements); } @Override protected HashSet<Integer> ofAll(int... elements) { return HashSet.ofAll(elements); } @Override protected HashSet<Long> ofAll(long... elements) { return HashSet.ofAll(elements); } @Override protected HashSet<Short> ofAll(short... elements) { return HashSet.ofAll(elements); } @Override protected <T> HashSet<T> tabulate(int n, Function<? super Integer, ? extends T> f) { return HashSet.tabulate(n, f); } @Override protected <T> HashSet<T> fill(int n, Supplier<? extends T> s) { return HashSet.fill(n, s); } @Override protected int getPeekNonNilPerformingAnAction() { return 1; } // -- static narrow @Test public void shouldNarrowHashSet() { final HashSet<Double> doubles = of(1.0d); final HashSet<Number> numbers = HashSet.narrow(doubles); final int actual = numbers.add(new BigDecimal("2.0")).sum().intValue(); assertThat(actual).isEqualTo(3); } // -- slideBy is not expected to work for larger subsequences, due to unspecified iteration order @Test public void shouldSlideNonNilBySomeClassifier() { // ignore } // TODO move to traversable // -- zip @Test public void shouldZipNils() { final HashSet<Tuple2<Object, Object>> actual = empty().zip(empty()); assertThat(actual).isEqualTo(empty()); } @Test public void shouldZipEmptyAndNonNil() { final HashSet<Tuple2<Object, Integer>> actual = empty().zip(of(1)); assertThat(actual).isEqualTo(empty()); } @Test public void shouldZipNonEmptyAndNil() { final HashSet<Tuple2<Integer, Integer>> actual = of(1).zip(empty()); assertThat(actual).isEqualTo(empty()); } @Test public void shouldZipNonNilsIfThisIsSmaller() { final HashSet<Tuple2<Integer, String>> actual = of(1, 2).zip(of("a", "b", "c")); final HashSet<Tuple2<Integer, String>> expected = of(Tuple.of(1, "a"), Tuple.of(2, "b")); assertThat(actual).isEqualTo(expected); } @Test public void shouldZipNonNilsIfThatIsSmaller() { final HashSet<Tuple2<Integer, String>> actual = of(1, 2, 3).zip(of("a", "b")); final HashSet<Tuple2<Integer, String>> expected = of(Tuple.of(1, "a"), Tuple.of(2, "b")); assertThat(actual).isEqualTo(expected); } @Test public void shouldZipNonNilsOfSameSize() { final HashSet<Tuple2<Integer, String>> actual = of(1, 2, 3).zip(of("a", "b", "c")); final HashSet<Tuple2<Integer, String>> expected = of(Tuple.of(1, "a"), Tuple.of(2, "b"), Tuple.of(3, "c")); assertThat(actual).isEqualTo(expected); } @Test(expected = NullPointerException.class) public void shouldThrowIfZipWithThatIsNull() { empty().zip(null); } // TODO move to traversable // -- zipAll @Test public void shouldZipAllNils() { // ignore } @Test public void shouldZipAllEmptyAndNonNil() { // ignore } @Test public void shouldZipAllNonEmptyAndNil() { final HashSet<?> actual = of(1).zipAll(empty(), null, null); final HashSet<Tuple2<Integer, Object>> expected = of(Tuple.of(1, null)); assertThat(actual).isEqualTo(expected); } @Test public void shouldZipAllNonNilsIfThisIsSmaller() { final HashSet<Tuple2<Integer, String>> actual = of(1, 2).zipAll(of("a", "b", "c"), 9, "z"); final HashSet<Tuple2<Integer, String>> expected = of(Tuple.of(1, "a"), Tuple.of(2, "b"), Tuple.of(9, "c")); assertThat(actual).isEqualTo(expected); } @Test public void shouldZipAllNonNilsIfThatIsSmaller() { final HashSet<Tuple2<Integer, String>> actual = of(1, 2, 3).zipAll(of("a", "b"), 9, "z"); final HashSet<Tuple2<Integer, String>> expected = of(Tuple.of(1, "a"), Tuple.of(2, "b"), Tuple.of(3, "z")); assertThat(actual).isEqualTo(expected); } @Test public void shouldZipAllNonNilsOfSameSize() { final HashSet<Tuple2<Integer, String>> actual = of(1, 2, 3).zipAll(of("a", "b", "c"), 9, "z"); final HashSet<Tuple2<Integer, String>> expected = of(Tuple.of(1, "a"), Tuple.of(2, "b"), Tuple.of(3, "c")); assertThat(actual).isEqualTo(expected); } @Test(expected = NullPointerException.class) public void shouldThrowIfZipAllWithThatIsNull() { empty().zipAll(null, null, null); } // TODO move to traversable // -- zipWithIndex @Test public void shouldZipNilWithIndex() { assertThat(this.<String> empty().zipWithIndex()).isEqualTo(this.<Tuple2<String, Integer>> empty()); } @Test public void shouldZipNonNilWithIndex() { final HashSet<Tuple2<String, Integer>> actual = of("a", "b", "c").zipWithIndex(); final HashSet<Tuple2<String, Integer>> expected = of(Tuple.of("a", 0), Tuple.of("b", 1), Tuple.of("c", 2)); assertThat(actual).isEqualTo(expected); } // -- transform() @Test public void shouldTransform() { final String transformed = of(42).transform(v -> String.valueOf(v.get())); assertThat(transformed).isEqualTo("42"); } // HashSet special cases @Override public void shouldDropRightAsExpectedIfCountIsLessThanSize() { assertThat(of(1, 2, 3).dropRight(2)).isEqualTo(of(3)); } @Override public void shouldTakeRightAsExpectedIfCountIsLessThanSize() { assertThat(of(1, 2, 3).takeRight(2)).isEqualTo(of(1, 2)); } @Override public void shouldGetInitOfNonNil() { assertThat(of(1, 2, 3).init()).isEqualTo(of(2, 3)); } @Override public void shouldFoldRightNonNil() { final String actual = of('a', 'b', 'c').foldRight("", (x, xs) -> x + xs); final List<String> expected = List.of('a', 'b', 'c').permutations().map(List::mkString); assertThat(actual).isIn(expected); } @Override public void shouldReduceRightNonNil() { final String actual = of("a", "b", "c").reduceRight((x, xs) -> x + xs); final List<String> expected = List.of("a", "b", "c").permutations().map(List::mkString); assertThat(actual).isIn(expected); } @Override public void shouldMkStringWithDelimiterNonNil() { final String actual = of('a', 'b', 'c').mkString(","); final List<String> expected = List.of('a', 'b', 'c').permutations().map(l -> l.mkString(",")); assertThat(actual).isIn(expected); } @Override public void shouldMkStringWithDelimiterAndPrefixAndSuffixNonNil() { final String actual = of('a', 'b', 'c').mkString("[", ",", "]"); final List<String> expected = List.of('a', 'b', 'c').permutations().map(l -> l.mkString("[", ",", "]")); assertThat(actual).isIn(expected); } @Override public void shouldComputeDistinctByOfNonEmptyTraversableUsingComparator() { // TODO } @Override public void shouldComputeDistinctByOfNonEmptyTraversableUsingKeyExtractor() { // TODO } @Override public void shouldFindLastOfNonNil() { final int actual = of(1, 2, 3, 4).findLast(i -> i % 2 == 0).get(); assertThat(actual).isIn(List.of(1, 2, 3, 4)); } @Override public void shouldThrowWhenFoldRightNullOperator() { throw new NullPointerException(); // TODO } @Override public void shouldReturnSomeInitWhenCallingInitOptionOnNonNil() { // TODO } @Test public void shouldBeEqual() { assertTrue(HashSet.of(1).equals(HashSet.of(1))); } //fixme: delete, when useIsEqualToInsteadOfIsSameAs() will be eliminated from AbstractValueTest class @Override protected boolean useIsEqualToInsteadOfIsSameAs() { return false; } @Override protected HashSet<Character> range(char from, char toExclusive) { return HashSet.range(from, toExclusive); } @Override protected HashSet<Character> rangeBy(char from, char toExclusive, int step) { return HashSet.rangeBy(from, toExclusive, step); } @Override protected HashSet<Double> rangeBy(double from, double toExclusive, double step) { return HashSet.rangeBy(from, toExclusive, step); } @Override protected HashSet<Integer> range(int from, int toExclusive) { return HashSet.range(from, toExclusive); } @Override protected HashSet<Integer> rangeBy(int from, int toExclusive, int step) { return HashSet.rangeBy(from, toExclusive, step); } @Override protected HashSet<Long> range(long from, long toExclusive) { return HashSet.range(from, toExclusive); } @Override protected HashSet<Long> rangeBy(long from, long toExclusive, long step) { return HashSet.rangeBy(from, toExclusive, step); } @Override protected HashSet<Character> rangeClosed(char from, char toInclusive) { return HashSet.rangeClosed(from, toInclusive); } @Override protected HashSet<Character> rangeClosedBy(char from, char toInclusive, int step) { return HashSet.rangeClosedBy(from, toInclusive, step); } @Override protected HashSet<Double> rangeClosedBy(double from, double toInclusive, double step) { return HashSet.rangeClosedBy(from, toInclusive, step); } @Override protected HashSet<Integer> rangeClosed(int from, int toInclusive) { return HashSet.rangeClosed(from, toInclusive); } @Override protected HashSet<Integer> rangeClosedBy(int from, int toInclusive, int step) { return HashSet.rangeClosedBy(from, toInclusive, step); } @Override protected HashSet<Long> rangeClosed(long from, long toInclusive) { return HashSet.rangeClosed(from, toInclusive); } @Override protected HashSet<Long> rangeClosedBy(long from, long toInclusive, long step) { return HashSet.rangeClosedBy(from, toInclusive, step); } // -- toSet @Test public void shouldReturnSelfOnConvertToSet() { final Value<Integer> value = of(1, 2, 3); assertThat(value.toSet()).isSameAs(value); } // -- spliterator @Test public void shouldNotHaveSortedSpliterator() { assertThat(of(1, 2, 3).spliterator().hasCharacteristics(Spliterator.SORTED)).isFalse(); } @Test public void shouldNotHaveOrderedSpliterator() { assertThat(of(1, 2, 3).spliterator().hasCharacteristics(Spliterator.ORDERED)).isFalse(); } // -- isSequential() @Test public void shouldReturnFalseWhenIsSequentialCalled() { assertThat(of(1, 2, 3).isSequential()).isFalse(); } }
apache-2.0
Nodstuff/hapi-fhir
hapi-fhir-structures-hl7org-dstu2/src/main/java/org/hl7/fhir/instance/model/MessageHeader.java
77040
package org.hl7.fhir.instance.model; /* Copyright (c) 2011+, HL7, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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. */ // Generated on Sat, Aug 22, 2015 23:00-0400 for FHIR v0.5.0 import java.util.*; import org.hl7.fhir.utilities.Utilities; import org.hl7.fhir.instance.model.Enumerations.*; import org.hl7.fhir.instance.model.annotations.ResourceDef; import org.hl7.fhir.instance.model.annotations.SearchParamDefinition; import org.hl7.fhir.instance.model.annotations.Child; import org.hl7.fhir.instance.model.annotations.Description; import org.hl7.fhir.instance.model.annotations.Block; import org.hl7.fhir.instance.model.api.*; /** * The header for a message exchange that is either requesting or responding to an action. The Reference(s) that are the subject of the action as well as other Information related to the action are typically transmitted in a bundle in which the MessageHeader resource instance is the first resource in the bundle. */ @ResourceDef(name="MessageHeader", profile="http://hl7.org/fhir/Profile/MessageHeader") public class MessageHeader extends DomainResource { public enum ResponseType { /** * The message was accepted and processed without error */ OK, /** * Some internal unexpected error occurred - wait and try again. Note - this is usually used for things like database unavailable, which may be expected to resolve, though human intervention may be required */ TRANSIENTERROR, /** * The message was rejected because of some content in it. There is no point in re-sending without change. The response narrative SHALL describe what the issue is. */ FATALERROR, /** * added to help the parsers */ NULL; public static ResponseType fromCode(String codeString) throws Exception { if (codeString == null || "".equals(codeString)) return null; if ("ok".equals(codeString)) return OK; if ("transient-error".equals(codeString)) return TRANSIENTERROR; if ("fatal-error".equals(codeString)) return FATALERROR; throw new Exception("Unknown ResponseType code '"+codeString+"'"); } public String toCode() { switch (this) { case OK: return "ok"; case TRANSIENTERROR: return "transient-error"; case FATALERROR: return "fatal-error"; default: return "?"; } } public String getSystem() { switch (this) { case OK: return "http://hl7.org/fhir/response-code"; case TRANSIENTERROR: return "http://hl7.org/fhir/response-code"; case FATALERROR: return "http://hl7.org/fhir/response-code"; default: return "?"; } } public String getDefinition() { switch (this) { case OK: return "The message was accepted and processed without error"; case TRANSIENTERROR: return "Some internal unexpected error occurred - wait and try again. Note - this is usually used for things like database unavailable, which may be expected to resolve, though human intervention may be required"; case FATALERROR: return "The message was rejected because of some content in it. There is no point in re-sending without change. The response narrative SHALL describe what the issue is."; default: return "?"; } } public String getDisplay() { switch (this) { case OK: return "OK"; case TRANSIENTERROR: return "Transient Error"; case FATALERROR: return "Fatal Error"; default: return "?"; } } } public static class ResponseTypeEnumFactory implements EnumFactory<ResponseType> { public ResponseType fromCode(String codeString) throws IllegalArgumentException { if (codeString == null || "".equals(codeString)) if (codeString == null || "".equals(codeString)) return null; if ("ok".equals(codeString)) return ResponseType.OK; if ("transient-error".equals(codeString)) return ResponseType.TRANSIENTERROR; if ("fatal-error".equals(codeString)) return ResponseType.FATALERROR; throw new IllegalArgumentException("Unknown ResponseType code '"+codeString+"'"); } public String toCode(ResponseType code) { if (code == ResponseType.OK) return "ok"; if (code == ResponseType.TRANSIENTERROR) return "transient-error"; if (code == ResponseType.FATALERROR) return "fatal-error"; return "?"; } } @Block() public static class MessageHeaderResponseComponent extends BackboneElement implements IBaseBackboneElement { /** * The id of the message that this message is a response to. */ @Child(name = "identifier", type = {IdType.class}, order=1, min=1, max=1, modifier=false, summary=true) @Description(shortDefinition="Id of original message", formalDefinition="The id of the message that this message is a response to." ) protected IdType identifier; /** * Code that identifies the type of response to the message - whether it was successful or not, and whether it should be resent or not. */ @Child(name = "code", type = {CodeType.class}, order=2, min=1, max=1, modifier=true, summary=true) @Description(shortDefinition="ok | transient-error | fatal-error", formalDefinition="Code that identifies the type of response to the message - whether it was successful or not, and whether it should be resent or not." ) protected Enumeration<ResponseType> code; /** * Full details of any issues found in the message. */ @Child(name = "details", type = {OperationOutcome.class}, order=3, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="Specific list of hints/warnings/errors", formalDefinition="Full details of any issues found in the message." ) protected Reference details; /** * The actual object that is the target of the reference (Full details of any issues found in the message.) */ protected OperationOutcome detailsTarget; private static final long serialVersionUID = -1008716838L; /* * Constructor */ public MessageHeaderResponseComponent() { super(); } /* * Constructor */ public MessageHeaderResponseComponent(IdType identifier, Enumeration<ResponseType> code) { super(); this.identifier = identifier; this.code = code; } /** * @return {@link #identifier} (The id of the message that this message is a response to.). This is the underlying object with id, value and extensions. The accessor "getIdentifier" gives direct access to the value */ public IdType getIdentifierElement() { if (this.identifier == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create MessageHeaderResponseComponent.identifier"); else if (Configuration.doAutoCreate()) this.identifier = new IdType(); // bb return this.identifier; } public boolean hasIdentifierElement() { return this.identifier != null && !this.identifier.isEmpty(); } public boolean hasIdentifier() { return this.identifier != null && !this.identifier.isEmpty(); } /** * @param value {@link #identifier} (The id of the message that this message is a response to.). This is the underlying object with id, value and extensions. The accessor "getIdentifier" gives direct access to the value */ public MessageHeaderResponseComponent setIdentifierElement(IdType value) { this.identifier = value; return this; } /** * @return The id of the message that this message is a response to. */ public String getIdentifier() { return this.identifier == null ? null : this.identifier.getValue(); } /** * @param value The id of the message that this message is a response to. */ public MessageHeaderResponseComponent setIdentifier(String value) { if (this.identifier == null) this.identifier = new IdType(); this.identifier.setValue(value); return this; } /** * @return {@link #code} (Code that identifies the type of response to the message - whether it was successful or not, and whether it should be resent or not.). This is the underlying object with id, value and extensions. The accessor "getCode" gives direct access to the value */ public Enumeration<ResponseType> getCodeElement() { if (this.code == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create MessageHeaderResponseComponent.code"); else if (Configuration.doAutoCreate()) this.code = new Enumeration<ResponseType>(new ResponseTypeEnumFactory()); // bb return this.code; } public boolean hasCodeElement() { return this.code != null && !this.code.isEmpty(); } public boolean hasCode() { return this.code != null && !this.code.isEmpty(); } /** * @param value {@link #code} (Code that identifies the type of response to the message - whether it was successful or not, and whether it should be resent or not.). This is the underlying object with id, value and extensions. The accessor "getCode" gives direct access to the value */ public MessageHeaderResponseComponent setCodeElement(Enumeration<ResponseType> value) { this.code = value; return this; } /** * @return Code that identifies the type of response to the message - whether it was successful or not, and whether it should be resent or not. */ public ResponseType getCode() { return this.code == null ? null : this.code.getValue(); } /** * @param value Code that identifies the type of response to the message - whether it was successful or not, and whether it should be resent or not. */ public MessageHeaderResponseComponent setCode(ResponseType value) { if (this.code == null) this.code = new Enumeration<ResponseType>(new ResponseTypeEnumFactory()); this.code.setValue(value); return this; } /** * @return {@link #details} (Full details of any issues found in the message.) */ public Reference getDetails() { if (this.details == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create MessageHeaderResponseComponent.details"); else if (Configuration.doAutoCreate()) this.details = new Reference(); // cc return this.details; } public boolean hasDetails() { return this.details != null && !this.details.isEmpty(); } /** * @param value {@link #details} (Full details of any issues found in the message.) */ public MessageHeaderResponseComponent setDetails(Reference value) { this.details = value; return this; } /** * @return {@link #details} The actual object that is the target of the reference. The reference library doesn't populate this, but you can use it to hold the resource if you resolve it. (Full details of any issues found in the message.) */ public OperationOutcome getDetailsTarget() { if (this.detailsTarget == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create MessageHeaderResponseComponent.details"); else if (Configuration.doAutoCreate()) this.detailsTarget = new OperationOutcome(); // aa return this.detailsTarget; } /** * @param value {@link #details} The actual object that is the target of the reference. The reference library doesn't use these, but you can use it to hold the resource if you resolve it. (Full details of any issues found in the message.) */ public MessageHeaderResponseComponent setDetailsTarget(OperationOutcome value) { this.detailsTarget = value; return this; } protected void listChildren(List<Property> childrenList) { super.listChildren(childrenList); childrenList.add(new Property("identifier", "id", "The id of the message that this message is a response to.", 0, java.lang.Integer.MAX_VALUE, identifier)); childrenList.add(new Property("code", "code", "Code that identifies the type of response to the message - whether it was successful or not, and whether it should be resent or not.", 0, java.lang.Integer.MAX_VALUE, code)); childrenList.add(new Property("details", "Reference(OperationOutcome)", "Full details of any issues found in the message.", 0, java.lang.Integer.MAX_VALUE, details)); } public MessageHeaderResponseComponent copy() { MessageHeaderResponseComponent dst = new MessageHeaderResponseComponent(); copyValues(dst); dst.identifier = identifier == null ? null : identifier.copy(); dst.code = code == null ? null : code.copy(); dst.details = details == null ? null : details.copy(); return dst; } @Override public boolean equalsDeep(Base other) { if (!super.equalsDeep(other)) return false; if (!(other instanceof MessageHeaderResponseComponent)) return false; MessageHeaderResponseComponent o = (MessageHeaderResponseComponent) other; return compareDeep(identifier, o.identifier, true) && compareDeep(code, o.code, true) && compareDeep(details, o.details, true) ; } @Override public boolean equalsShallow(Base other) { if (!super.equalsShallow(other)) return false; if (!(other instanceof MessageHeaderResponseComponent)) return false; MessageHeaderResponseComponent o = (MessageHeaderResponseComponent) other; return compareValues(identifier, o.identifier, true) && compareValues(code, o.code, true); } public boolean isEmpty() { return super.isEmpty() && (identifier == null || identifier.isEmpty()) && (code == null || code.isEmpty()) && (details == null || details.isEmpty()); } } @Block() public static class MessageSourceComponent extends BackboneElement implements IBaseBackboneElement { /** * Human-readable name for the source system. */ @Child(name = "name", type = {StringType.class}, order=1, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="Name of system", formalDefinition="Human-readable name for the source system." ) protected StringType name; /** * May include configuration or other information useful in debugging. */ @Child(name = "software", type = {StringType.class}, order=2, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="Name of software running the system", formalDefinition="May include configuration or other information useful in debugging." ) protected StringType software; /** * Can convey versions of multiple systems in situations where a message passes through multiple hands. */ @Child(name = "version", type = {StringType.class}, order=3, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="Version of software running", formalDefinition="Can convey versions of multiple systems in situations where a message passes through multiple hands." ) protected StringType version; /** * An e-mail, phone, website or other contact point to use to resolve issues with message communications. */ @Child(name = "contact", type = {ContactPoint.class}, order=4, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="Human contact for problems", formalDefinition="An e-mail, phone, website or other contact point to use to resolve issues with message communications." ) protected ContactPoint contact; /** * Identifies the routing target to send acknowledgements to. */ @Child(name = "endpoint", type = {UriType.class}, order=5, min=1, max=1, modifier=false, summary=true) @Description(shortDefinition="Actual message source address or id", formalDefinition="Identifies the routing target to send acknowledgements to." ) protected UriType endpoint; private static final long serialVersionUID = -115878196L; /* * Constructor */ public MessageSourceComponent() { super(); } /* * Constructor */ public MessageSourceComponent(UriType endpoint) { super(); this.endpoint = endpoint; } /** * @return {@link #name} (Human-readable name for the source system.). This is the underlying object with id, value and extensions. The accessor "getName" gives direct access to the value */ public StringType getNameElement() { if (this.name == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create MessageSourceComponent.name"); else if (Configuration.doAutoCreate()) this.name = new StringType(); // bb return this.name; } public boolean hasNameElement() { return this.name != null && !this.name.isEmpty(); } public boolean hasName() { return this.name != null && !this.name.isEmpty(); } /** * @param value {@link #name} (Human-readable name for the source system.). This is the underlying object with id, value and extensions. The accessor "getName" gives direct access to the value */ public MessageSourceComponent setNameElement(StringType value) { this.name = value; return this; } /** * @return Human-readable name for the source system. */ public String getName() { return this.name == null ? null : this.name.getValue(); } /** * @param value Human-readable name for the source system. */ public MessageSourceComponent setName(String value) { if (Utilities.noString(value)) this.name = null; else { if (this.name == null) this.name = new StringType(); this.name.setValue(value); } return this; } /** * @return {@link #software} (May include configuration or other information useful in debugging.). This is the underlying object with id, value and extensions. The accessor "getSoftware" gives direct access to the value */ public StringType getSoftwareElement() { if (this.software == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create MessageSourceComponent.software"); else if (Configuration.doAutoCreate()) this.software = new StringType(); // bb return this.software; } public boolean hasSoftwareElement() { return this.software != null && !this.software.isEmpty(); } public boolean hasSoftware() { return this.software != null && !this.software.isEmpty(); } /** * @param value {@link #software} (May include configuration or other information useful in debugging.). This is the underlying object with id, value and extensions. The accessor "getSoftware" gives direct access to the value */ public MessageSourceComponent setSoftwareElement(StringType value) { this.software = value; return this; } /** * @return May include configuration or other information useful in debugging. */ public String getSoftware() { return this.software == null ? null : this.software.getValue(); } /** * @param value May include configuration or other information useful in debugging. */ public MessageSourceComponent setSoftware(String value) { if (Utilities.noString(value)) this.software = null; else { if (this.software == null) this.software = new StringType(); this.software.setValue(value); } return this; } /** * @return {@link #version} (Can convey versions of multiple systems in situations where a message passes through multiple hands.). This is the underlying object with id, value and extensions. The accessor "getVersion" gives direct access to the value */ public StringType getVersionElement() { if (this.version == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create MessageSourceComponent.version"); else if (Configuration.doAutoCreate()) this.version = new StringType(); // bb return this.version; } public boolean hasVersionElement() { return this.version != null && !this.version.isEmpty(); } public boolean hasVersion() { return this.version != null && !this.version.isEmpty(); } /** * @param value {@link #version} (Can convey versions of multiple systems in situations where a message passes through multiple hands.). This is the underlying object with id, value and extensions. The accessor "getVersion" gives direct access to the value */ public MessageSourceComponent setVersionElement(StringType value) { this.version = value; return this; } /** * @return Can convey versions of multiple systems in situations where a message passes through multiple hands. */ public String getVersion() { return this.version == null ? null : this.version.getValue(); } /** * @param value Can convey versions of multiple systems in situations where a message passes through multiple hands. */ public MessageSourceComponent setVersion(String value) { if (Utilities.noString(value)) this.version = null; else { if (this.version == null) this.version = new StringType(); this.version.setValue(value); } return this; } /** * @return {@link #contact} (An e-mail, phone, website or other contact point to use to resolve issues with message communications.) */ public ContactPoint getContact() { if (this.contact == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create MessageSourceComponent.contact"); else if (Configuration.doAutoCreate()) this.contact = new ContactPoint(); // cc return this.contact; } public boolean hasContact() { return this.contact != null && !this.contact.isEmpty(); } /** * @param value {@link #contact} (An e-mail, phone, website or other contact point to use to resolve issues with message communications.) */ public MessageSourceComponent setContact(ContactPoint value) { this.contact = value; return this; } /** * @return {@link #endpoint} (Identifies the routing target to send acknowledgements to.). This is the underlying object with id, value and extensions. The accessor "getEndpoint" gives direct access to the value */ public UriType getEndpointElement() { if (this.endpoint == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create MessageSourceComponent.endpoint"); else if (Configuration.doAutoCreate()) this.endpoint = new UriType(); // bb return this.endpoint; } public boolean hasEndpointElement() { return this.endpoint != null && !this.endpoint.isEmpty(); } public boolean hasEndpoint() { return this.endpoint != null && !this.endpoint.isEmpty(); } /** * @param value {@link #endpoint} (Identifies the routing target to send acknowledgements to.). This is the underlying object with id, value and extensions. The accessor "getEndpoint" gives direct access to the value */ public MessageSourceComponent setEndpointElement(UriType value) { this.endpoint = value; return this; } /** * @return Identifies the routing target to send acknowledgements to. */ public String getEndpoint() { return this.endpoint == null ? null : this.endpoint.getValue(); } /** * @param value Identifies the routing target to send acknowledgements to. */ public MessageSourceComponent setEndpoint(String value) { if (this.endpoint == null) this.endpoint = new UriType(); this.endpoint.setValue(value); return this; } protected void listChildren(List<Property> childrenList) { super.listChildren(childrenList); childrenList.add(new Property("name", "string", "Human-readable name for the source system.", 0, java.lang.Integer.MAX_VALUE, name)); childrenList.add(new Property("software", "string", "May include configuration or other information useful in debugging.", 0, java.lang.Integer.MAX_VALUE, software)); childrenList.add(new Property("version", "string", "Can convey versions of multiple systems in situations where a message passes through multiple hands.", 0, java.lang.Integer.MAX_VALUE, version)); childrenList.add(new Property("contact", "ContactPoint", "An e-mail, phone, website or other contact point to use to resolve issues with message communications.", 0, java.lang.Integer.MAX_VALUE, contact)); childrenList.add(new Property("endpoint", "uri", "Identifies the routing target to send acknowledgements to.", 0, java.lang.Integer.MAX_VALUE, endpoint)); } public MessageSourceComponent copy() { MessageSourceComponent dst = new MessageSourceComponent(); copyValues(dst); dst.name = name == null ? null : name.copy(); dst.software = software == null ? null : software.copy(); dst.version = version == null ? null : version.copy(); dst.contact = contact == null ? null : contact.copy(); dst.endpoint = endpoint == null ? null : endpoint.copy(); return dst; } @Override public boolean equalsDeep(Base other) { if (!super.equalsDeep(other)) return false; if (!(other instanceof MessageSourceComponent)) return false; MessageSourceComponent o = (MessageSourceComponent) other; return compareDeep(name, o.name, true) && compareDeep(software, o.software, true) && compareDeep(version, o.version, true) && compareDeep(contact, o.contact, true) && compareDeep(endpoint, o.endpoint, true); } @Override public boolean equalsShallow(Base other) { if (!super.equalsShallow(other)) return false; if (!(other instanceof MessageSourceComponent)) return false; MessageSourceComponent o = (MessageSourceComponent) other; return compareValues(name, o.name, true) && compareValues(software, o.software, true) && compareValues(version, o.version, true) && compareValues(endpoint, o.endpoint, true); } public boolean isEmpty() { return super.isEmpty() && (name == null || name.isEmpty()) && (software == null || software.isEmpty()) && (version == null || version.isEmpty()) && (contact == null || contact.isEmpty()) && (endpoint == null || endpoint.isEmpty()) ; } } @Block() public static class MessageDestinationComponent extends BackboneElement implements IBaseBackboneElement { /** * Human-readable name for the target system. */ @Child(name = "name", type = {StringType.class}, order=1, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="Name of system", formalDefinition="Human-readable name for the target system." ) protected StringType name; /** * Identifies the target end system in situations where the initial message transmission is to an intermediary system. */ @Child(name = "target", type = {Device.class}, order=2, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="Particular delivery destination within the destination", formalDefinition="Identifies the target end system in situations where the initial message transmission is to an intermediary system." ) protected Reference target; /** * The actual object that is the target of the reference (Identifies the target end system in situations where the initial message transmission is to an intermediary system.) */ protected Device targetTarget; /** * Indicates where the message should be routed to. */ @Child(name = "endpoint", type = {UriType.class}, order=3, min=1, max=1, modifier=false, summary=true) @Description(shortDefinition="Actual destination address or id", formalDefinition="Indicates where the message should be routed to." ) protected UriType endpoint; private static final long serialVersionUID = -2097633309L; /* * Constructor */ public MessageDestinationComponent() { super(); } /* * Constructor */ public MessageDestinationComponent(UriType endpoint) { super(); this.endpoint = endpoint; } /** * @return {@link #name} (Human-readable name for the target system.). This is the underlying object with id, value and extensions. The accessor "getName" gives direct access to the value */ public StringType getNameElement() { if (this.name == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create MessageDestinationComponent.name"); else if (Configuration.doAutoCreate()) this.name = new StringType(); // bb return this.name; } public boolean hasNameElement() { return this.name != null && !this.name.isEmpty(); } public boolean hasName() { return this.name != null && !this.name.isEmpty(); } /** * @param value {@link #name} (Human-readable name for the target system.). This is the underlying object with id, value and extensions. The accessor "getName" gives direct access to the value */ public MessageDestinationComponent setNameElement(StringType value) { this.name = value; return this; } /** * @return Human-readable name for the target system. */ public String getName() { return this.name == null ? null : this.name.getValue(); } /** * @param value Human-readable name for the target system. */ public MessageDestinationComponent setName(String value) { if (Utilities.noString(value)) this.name = null; else { if (this.name == null) this.name = new StringType(); this.name.setValue(value); } return this; } /** * @return {@link #target} (Identifies the target end system in situations where the initial message transmission is to an intermediary system.) */ public Reference getTarget() { if (this.target == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create MessageDestinationComponent.target"); else if (Configuration.doAutoCreate()) this.target = new Reference(); // cc return this.target; } public boolean hasTarget() { return this.target != null && !this.target.isEmpty(); } /** * @param value {@link #target} (Identifies the target end system in situations where the initial message transmission is to an intermediary system.) */ public MessageDestinationComponent setTarget(Reference value) { this.target = value; return this; } /** * @return {@link #target} The actual object that is the target of the reference. The reference library doesn't populate this, but you can use it to hold the resource if you resolve it. (Identifies the target end system in situations where the initial message transmission is to an intermediary system.) */ public Device getTargetTarget() { if (this.targetTarget == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create MessageDestinationComponent.target"); else if (Configuration.doAutoCreate()) this.targetTarget = new Device(); // aa return this.targetTarget; } /** * @param value {@link #target} The actual object that is the target of the reference. The reference library doesn't use these, but you can use it to hold the resource if you resolve it. (Identifies the target end system in situations where the initial message transmission is to an intermediary system.) */ public MessageDestinationComponent setTargetTarget(Device value) { this.targetTarget = value; return this; } /** * @return {@link #endpoint} (Indicates where the message should be routed to.). This is the underlying object with id, value and extensions. The accessor "getEndpoint" gives direct access to the value */ public UriType getEndpointElement() { if (this.endpoint == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create MessageDestinationComponent.endpoint"); else if (Configuration.doAutoCreate()) this.endpoint = new UriType(); // bb return this.endpoint; } public boolean hasEndpointElement() { return this.endpoint != null && !this.endpoint.isEmpty(); } public boolean hasEndpoint() { return this.endpoint != null && !this.endpoint.isEmpty(); } /** * @param value {@link #endpoint} (Indicates where the message should be routed to.). This is the underlying object with id, value and extensions. The accessor "getEndpoint" gives direct access to the value */ public MessageDestinationComponent setEndpointElement(UriType value) { this.endpoint = value; return this; } /** * @return Indicates where the message should be routed to. */ public String getEndpoint() { return this.endpoint == null ? null : this.endpoint.getValue(); } /** * @param value Indicates where the message should be routed to. */ public MessageDestinationComponent setEndpoint(String value) { if (this.endpoint == null) this.endpoint = new UriType(); this.endpoint.setValue(value); return this; } protected void listChildren(List<Property> childrenList) { super.listChildren(childrenList); childrenList.add(new Property("name", "string", "Human-readable name for the target system.", 0, java.lang.Integer.MAX_VALUE, name)); childrenList.add(new Property("target", "Reference(Device)", "Identifies the target end system in situations where the initial message transmission is to an intermediary system.", 0, java.lang.Integer.MAX_VALUE, target)); childrenList.add(new Property("endpoint", "uri", "Indicates where the message should be routed to.", 0, java.lang.Integer.MAX_VALUE, endpoint)); } public MessageDestinationComponent copy() { MessageDestinationComponent dst = new MessageDestinationComponent(); copyValues(dst); dst.name = name == null ? null : name.copy(); dst.target = target == null ? null : target.copy(); dst.endpoint = endpoint == null ? null : endpoint.copy(); return dst; } @Override public boolean equalsDeep(Base other) { if (!super.equalsDeep(other)) return false; if (!(other instanceof MessageDestinationComponent)) return false; MessageDestinationComponent o = (MessageDestinationComponent) other; return compareDeep(name, o.name, true) && compareDeep(target, o.target, true) && compareDeep(endpoint, o.endpoint, true) ; } @Override public boolean equalsShallow(Base other) { if (!super.equalsShallow(other)) return false; if (!(other instanceof MessageDestinationComponent)) return false; MessageDestinationComponent o = (MessageDestinationComponent) other; return compareValues(name, o.name, true) && compareValues(endpoint, o.endpoint, true); } public boolean isEmpty() { return super.isEmpty() && (name == null || name.isEmpty()) && (target == null || target.isEmpty()) && (endpoint == null || endpoint.isEmpty()); } } /** * The identifier of this message. */ @Child(name = "identifier", type = {IdType.class}, order=0, min=1, max=1, modifier=false, summary=true) @Description(shortDefinition="Id of this message", formalDefinition="The identifier of this message." ) protected IdType identifier; /** * The time that the message was sent. */ @Child(name = "timestamp", type = {InstantType.class}, order=1, min=1, max=1, modifier=false, summary=true) @Description(shortDefinition="Time that the message was sent", formalDefinition="The time that the message was sent." ) protected InstantType timestamp; /** * Code that identifies the event this message represents and connects it with its definition. Events defined as part of the FHIR specification have the system value "http://hl7.org/fhir/message-events". */ @Child(name = "event", type = {Coding.class}, order=2, min=1, max=1, modifier=true, summary=true) @Description(shortDefinition="Code for the event this message represents", formalDefinition="Code that identifies the event this message represents and connects it with its definition. Events defined as part of the FHIR specification have the system value \"http://hl7.org/fhir/message-events\"." ) protected Coding event; /** * Information about the message that this message is a response to. Only present if this message is a response. */ @Child(name = "response", type = {}, order=3, min=0, max=1, modifier=true, summary=true) @Description(shortDefinition="If this is a reply to prior message", formalDefinition="Information about the message that this message is a response to. Only present if this message is a response." ) protected MessageHeaderResponseComponent response; /** * The source application from which this message originated. */ @Child(name = "source", type = {}, order=4, min=1, max=1, modifier=false, summary=true) @Description(shortDefinition="Message Source Application", formalDefinition="The source application from which this message originated." ) protected MessageSourceComponent source; /** * The destination application which the message is intended for. */ @Child(name = "destination", type = {}, order=5, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true) @Description(shortDefinition="Message Destination Application(s)", formalDefinition="The destination application which the message is intended for." ) protected List<MessageDestinationComponent> destination; /** * The person or device that performed the data entry leading to this message. Where there is more than one candidate, pick the most proximal to the message. Can provide other enterers in extensions. */ @Child(name = "enterer", type = {Practitioner.class}, order=6, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="The source of the data entry", formalDefinition="The person or device that performed the data entry leading to this message. Where there is more than one candidate, pick the most proximal to the message. Can provide other enterers in extensions." ) protected Reference enterer; /** * The actual object that is the target of the reference (The person or device that performed the data entry leading to this message. Where there is more than one candidate, pick the most proximal to the message. Can provide other enterers in extensions.) */ protected Practitioner entererTarget; /** * The logical author of the message - the person or device that decided the described event should happen. Where there is more than one candidate, pick the most proximal to the MessageHeader. Can provide other authors in extensions. */ @Child(name = "author", type = {Practitioner.class}, order=7, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="The source of the decision", formalDefinition="The logical author of the message - the person or device that decided the described event should happen. Where there is more than one candidate, pick the most proximal to the MessageHeader. Can provide other authors in extensions." ) protected Reference author; /** * The actual object that is the target of the reference (The logical author of the message - the person or device that decided the described event should happen. Where there is more than one candidate, pick the most proximal to the MessageHeader. Can provide other authors in extensions.) */ protected Practitioner authorTarget; /** * Allows data conveyed by a message to be addressed to a particular person or department when routing to a specific application isn't sufficient. */ @Child(name = "receiver", type = {Practitioner.class, Organization.class}, order=8, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="Intended \"real-world\" recipient for the data", formalDefinition="Allows data conveyed by a message to be addressed to a particular person or department when routing to a specific application isn't sufficient." ) protected Reference receiver; /** * The actual object that is the target of the reference (Allows data conveyed by a message to be addressed to a particular person or department when routing to a specific application isn't sufficient.) */ protected Resource receiverTarget; /** * The person or organization that accepts overall responsibility for the contents of the message. The implication is that the message event happened under the policies of the responsible party. */ @Child(name = "responsible", type = {Practitioner.class, Organization.class}, order=9, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="Final responsibility for event", formalDefinition="The person or organization that accepts overall responsibility for the contents of the message. The implication is that the message event happened under the policies of the responsible party." ) protected Reference responsible; /** * The actual object that is the target of the reference (The person or organization that accepts overall responsibility for the contents of the message. The implication is that the message event happened under the policies of the responsible party.) */ protected Resource responsibleTarget; /** * Coded indication of the cause for the event - indicates a reason for the occurance of the event that is a focus of this message. */ @Child(name = "reason", type = {CodeableConcept.class}, order=10, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="Cause of event", formalDefinition="Coded indication of the cause for the event - indicates a reason for the occurance of the event that is a focus of this message." ) protected CodeableConcept reason; /** * The actual data of the message - a reference to the root/focus class of the event. */ @Child(name = "data", type = {}, order=11, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true) @Description(shortDefinition="The actual content of the message", formalDefinition="The actual data of the message - a reference to the root/focus class of the event." ) protected List<Reference> data; /** * The actual objects that are the target of the reference (The actual data of the message - a reference to the root/focus class of the event.) */ protected List<Resource> dataTarget; private static final long serialVersionUID = 1866986127L; /* * Constructor */ public MessageHeader() { super(); } /* * Constructor */ public MessageHeader(IdType identifier, InstantType timestamp, Coding event, MessageSourceComponent source) { super(); this.identifier = identifier; this.timestamp = timestamp; this.event = event; this.source = source; } /** * @return {@link #identifier} (The identifier of this message.). This is the underlying object with id, value and extensions. The accessor "getIdentifier" gives direct access to the value */ public IdType getIdentifierElement() { if (this.identifier == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create MessageHeader.identifier"); else if (Configuration.doAutoCreate()) this.identifier = new IdType(); // bb return this.identifier; } public boolean hasIdentifierElement() { return this.identifier != null && !this.identifier.isEmpty(); } public boolean hasIdentifier() { return this.identifier != null && !this.identifier.isEmpty(); } /** * @param value {@link #identifier} (The identifier of this message.). This is the underlying object with id, value and extensions. The accessor "getIdentifier" gives direct access to the value */ public MessageHeader setIdentifierElement(IdType value) { this.identifier = value; return this; } /** * @return The identifier of this message. */ public String getIdentifier() { return this.identifier == null ? null : this.identifier.getValue(); } /** * @param value The identifier of this message. */ public MessageHeader setIdentifier(String value) { if (this.identifier == null) this.identifier = new IdType(); this.identifier.setValue(value); return this; } /** * @return {@link #timestamp} (The time that the message was sent.). This is the underlying object with id, value and extensions. The accessor "getTimestamp" gives direct access to the value */ public InstantType getTimestampElement() { if (this.timestamp == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create MessageHeader.timestamp"); else if (Configuration.doAutoCreate()) this.timestamp = new InstantType(); // bb return this.timestamp; } public boolean hasTimestampElement() { return this.timestamp != null && !this.timestamp.isEmpty(); } public boolean hasTimestamp() { return this.timestamp != null && !this.timestamp.isEmpty(); } /** * @param value {@link #timestamp} (The time that the message was sent.). This is the underlying object with id, value and extensions. The accessor "getTimestamp" gives direct access to the value */ public MessageHeader setTimestampElement(InstantType value) { this.timestamp = value; return this; } /** * @return The time that the message was sent. */ public Date getTimestamp() { return this.timestamp == null ? null : this.timestamp.getValue(); } /** * @param value The time that the message was sent. */ public MessageHeader setTimestamp(Date value) { if (this.timestamp == null) this.timestamp = new InstantType(); this.timestamp.setValue(value); return this; } /** * @return {@link #event} (Code that identifies the event this message represents and connects it with its definition. Events defined as part of the FHIR specification have the system value "http://hl7.org/fhir/message-events".) */ public Coding getEvent() { if (this.event == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create MessageHeader.event"); else if (Configuration.doAutoCreate()) this.event = new Coding(); // cc return this.event; } public boolean hasEvent() { return this.event != null && !this.event.isEmpty(); } /** * @param value {@link #event} (Code that identifies the event this message represents and connects it with its definition. Events defined as part of the FHIR specification have the system value "http://hl7.org/fhir/message-events".) */ public MessageHeader setEvent(Coding value) { this.event = value; return this; } /** * @return {@link #response} (Information about the message that this message is a response to. Only present if this message is a response.) */ public MessageHeaderResponseComponent getResponse() { if (this.response == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create MessageHeader.response"); else if (Configuration.doAutoCreate()) this.response = new MessageHeaderResponseComponent(); // cc return this.response; } public boolean hasResponse() { return this.response != null && !this.response.isEmpty(); } /** * @param value {@link #response} (Information about the message that this message is a response to. Only present if this message is a response.) */ public MessageHeader setResponse(MessageHeaderResponseComponent value) { this.response = value; return this; } /** * @return {@link #source} (The source application from which this message originated.) */ public MessageSourceComponent getSource() { if (this.source == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create MessageHeader.source"); else if (Configuration.doAutoCreate()) this.source = new MessageSourceComponent(); // cc return this.source; } public boolean hasSource() { return this.source != null && !this.source.isEmpty(); } /** * @param value {@link #source} (The source application from which this message originated.) */ public MessageHeader setSource(MessageSourceComponent value) { this.source = value; return this; } /** * @return {@link #destination} (The destination application which the message is intended for.) */ public List<MessageDestinationComponent> getDestination() { if (this.destination == null) this.destination = new ArrayList<MessageDestinationComponent>(); return this.destination; } public boolean hasDestination() { if (this.destination == null) return false; for (MessageDestinationComponent item : this.destination) if (!item.isEmpty()) return true; return false; } /** * @return {@link #destination} (The destination application which the message is intended for.) */ // syntactic sugar public MessageDestinationComponent addDestination() { //3 MessageDestinationComponent t = new MessageDestinationComponent(); if (this.destination == null) this.destination = new ArrayList<MessageDestinationComponent>(); this.destination.add(t); return t; } // syntactic sugar public MessageHeader addDestination(MessageDestinationComponent t) { //3 if (t == null) return this; if (this.destination == null) this.destination = new ArrayList<MessageDestinationComponent>(); this.destination.add(t); return this; } /** * @return {@link #enterer} (The person or device that performed the data entry leading to this message. Where there is more than one candidate, pick the most proximal to the message. Can provide other enterers in extensions.) */ public Reference getEnterer() { if (this.enterer == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create MessageHeader.enterer"); else if (Configuration.doAutoCreate()) this.enterer = new Reference(); // cc return this.enterer; } public boolean hasEnterer() { return this.enterer != null && !this.enterer.isEmpty(); } /** * @param value {@link #enterer} (The person or device that performed the data entry leading to this message. Where there is more than one candidate, pick the most proximal to the message. Can provide other enterers in extensions.) */ public MessageHeader setEnterer(Reference value) { this.enterer = value; return this; } /** * @return {@link #enterer} The actual object that is the target of the reference. The reference library doesn't populate this, but you can use it to hold the resource if you resolve it. (The person or device that performed the data entry leading to this message. Where there is more than one candidate, pick the most proximal to the message. Can provide other enterers in extensions.) */ public Practitioner getEntererTarget() { if (this.entererTarget == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create MessageHeader.enterer"); else if (Configuration.doAutoCreate()) this.entererTarget = new Practitioner(); // aa return this.entererTarget; } /** * @param value {@link #enterer} The actual object that is the target of the reference. The reference library doesn't use these, but you can use it to hold the resource if you resolve it. (The person or device that performed the data entry leading to this message. Where there is more than one candidate, pick the most proximal to the message. Can provide other enterers in extensions.) */ public MessageHeader setEntererTarget(Practitioner value) { this.entererTarget = value; return this; } /** * @return {@link #author} (The logical author of the message - the person or device that decided the described event should happen. Where there is more than one candidate, pick the most proximal to the MessageHeader. Can provide other authors in extensions.) */ public Reference getAuthor() { if (this.author == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create MessageHeader.author"); else if (Configuration.doAutoCreate()) this.author = new Reference(); // cc return this.author; } public boolean hasAuthor() { return this.author != null && !this.author.isEmpty(); } /** * @param value {@link #author} (The logical author of the message - the person or device that decided the described event should happen. Where there is more than one candidate, pick the most proximal to the MessageHeader. Can provide other authors in extensions.) */ public MessageHeader setAuthor(Reference value) { this.author = value; return this; } /** * @return {@link #author} The actual object that is the target of the reference. The reference library doesn't populate this, but you can use it to hold the resource if you resolve it. (The logical author of the message - the person or device that decided the described event should happen. Where there is more than one candidate, pick the most proximal to the MessageHeader. Can provide other authors in extensions.) */ public Practitioner getAuthorTarget() { if (this.authorTarget == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create MessageHeader.author"); else if (Configuration.doAutoCreate()) this.authorTarget = new Practitioner(); // aa return this.authorTarget; } /** * @param value {@link #author} The actual object that is the target of the reference. The reference library doesn't use these, but you can use it to hold the resource if you resolve it. (The logical author of the message - the person or device that decided the described event should happen. Where there is more than one candidate, pick the most proximal to the MessageHeader. Can provide other authors in extensions.) */ public MessageHeader setAuthorTarget(Practitioner value) { this.authorTarget = value; return this; } /** * @return {@link #receiver} (Allows data conveyed by a message to be addressed to a particular person or department when routing to a specific application isn't sufficient.) */ public Reference getReceiver() { if (this.receiver == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create MessageHeader.receiver"); else if (Configuration.doAutoCreate()) this.receiver = new Reference(); // cc return this.receiver; } public boolean hasReceiver() { return this.receiver != null && !this.receiver.isEmpty(); } /** * @param value {@link #receiver} (Allows data conveyed by a message to be addressed to a particular person or department when routing to a specific application isn't sufficient.) */ public MessageHeader setReceiver(Reference value) { this.receiver = value; return this; } /** * @return {@link #receiver} The actual object that is the target of the reference. The reference library doesn't populate this, but you can use it to hold the resource if you resolve it. (Allows data conveyed by a message to be addressed to a particular person or department when routing to a specific application isn't sufficient.) */ public Resource getReceiverTarget() { return this.receiverTarget; } /** * @param value {@link #receiver} The actual object that is the target of the reference. The reference library doesn't use these, but you can use it to hold the resource if you resolve it. (Allows data conveyed by a message to be addressed to a particular person or department when routing to a specific application isn't sufficient.) */ public MessageHeader setReceiverTarget(Resource value) { this.receiverTarget = value; return this; } /** * @return {@link #responsible} (The person or organization that accepts overall responsibility for the contents of the message. The implication is that the message event happened under the policies of the responsible party.) */ public Reference getResponsible() { if (this.responsible == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create MessageHeader.responsible"); else if (Configuration.doAutoCreate()) this.responsible = new Reference(); // cc return this.responsible; } public boolean hasResponsible() { return this.responsible != null && !this.responsible.isEmpty(); } /** * @param value {@link #responsible} (The person or organization that accepts overall responsibility for the contents of the message. The implication is that the message event happened under the policies of the responsible party.) */ public MessageHeader setResponsible(Reference value) { this.responsible = value; return this; } /** * @return {@link #responsible} The actual object that is the target of the reference. The reference library doesn't populate this, but you can use it to hold the resource if you resolve it. (The person or organization that accepts overall responsibility for the contents of the message. The implication is that the message event happened under the policies of the responsible party.) */ public Resource getResponsibleTarget() { return this.responsibleTarget; } /** * @param value {@link #responsible} The actual object that is the target of the reference. The reference library doesn't use these, but you can use it to hold the resource if you resolve it. (The person or organization that accepts overall responsibility for the contents of the message. The implication is that the message event happened under the policies of the responsible party.) */ public MessageHeader setResponsibleTarget(Resource value) { this.responsibleTarget = value; return this; } /** * @return {@link #reason} (Coded indication of the cause for the event - indicates a reason for the occurance of the event that is a focus of this message.) */ public CodeableConcept getReason() { if (this.reason == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create MessageHeader.reason"); else if (Configuration.doAutoCreate()) this.reason = new CodeableConcept(); // cc return this.reason; } public boolean hasReason() { return this.reason != null && !this.reason.isEmpty(); } /** * @param value {@link #reason} (Coded indication of the cause for the event - indicates a reason for the occurance of the event that is a focus of this message.) */ public MessageHeader setReason(CodeableConcept value) { this.reason = value; return this; } /** * @return {@link #data} (The actual data of the message - a reference to the root/focus class of the event.) */ public List<Reference> getData() { if (this.data == null) this.data = new ArrayList<Reference>(); return this.data; } public boolean hasData() { if (this.data == null) return false; for (Reference item : this.data) if (!item.isEmpty()) return true; return false; } /** * @return {@link #data} (The actual data of the message - a reference to the root/focus class of the event.) */ // syntactic sugar public Reference addData() { //3 Reference t = new Reference(); if (this.data == null) this.data = new ArrayList<Reference>(); this.data.add(t); return t; } // syntactic sugar public MessageHeader addData(Reference t) { //3 if (t == null) return this; if (this.data == null) this.data = new ArrayList<Reference>(); this.data.add(t); return this; } /** * @return {@link #data} (The actual objects that are the target of the reference. The reference library doesn't populate this, but you can use this to hold the resources if you resolvethemt. The actual data of the message - a reference to the root/focus class of the event.) */ public List<Resource> getDataTarget() { if (this.dataTarget == null) this.dataTarget = new ArrayList<Resource>(); return this.dataTarget; } protected void listChildren(List<Property> childrenList) { super.listChildren(childrenList); childrenList.add(new Property("identifier", "id", "The identifier of this message.", 0, java.lang.Integer.MAX_VALUE, identifier)); childrenList.add(new Property("timestamp", "instant", "The time that the message was sent.", 0, java.lang.Integer.MAX_VALUE, timestamp)); childrenList.add(new Property("event", "Coding", "Code that identifies the event this message represents and connects it with its definition. Events defined as part of the FHIR specification have the system value \"http://hl7.org/fhir/message-events\".", 0, java.lang.Integer.MAX_VALUE, event)); childrenList.add(new Property("response", "", "Information about the message that this message is a response to. Only present if this message is a response.", 0, java.lang.Integer.MAX_VALUE, response)); childrenList.add(new Property("source", "", "The source application from which this message originated.", 0, java.lang.Integer.MAX_VALUE, source)); childrenList.add(new Property("destination", "", "The destination application which the message is intended for.", 0, java.lang.Integer.MAX_VALUE, destination)); childrenList.add(new Property("enterer", "Reference(Practitioner)", "The person or device that performed the data entry leading to this message. Where there is more than one candidate, pick the most proximal to the message. Can provide other enterers in extensions.", 0, java.lang.Integer.MAX_VALUE, enterer)); childrenList.add(new Property("author", "Reference(Practitioner)", "The logical author of the message - the person or device that decided the described event should happen. Where there is more than one candidate, pick the most proximal to the MessageHeader. Can provide other authors in extensions.", 0, java.lang.Integer.MAX_VALUE, author)); childrenList.add(new Property("receiver", "Reference(Practitioner|Organization)", "Allows data conveyed by a message to be addressed to a particular person or department when routing to a specific application isn't sufficient.", 0, java.lang.Integer.MAX_VALUE, receiver)); childrenList.add(new Property("responsible", "Reference(Practitioner|Organization)", "The person or organization that accepts overall responsibility for the contents of the message. The implication is that the message event happened under the policies of the responsible party.", 0, java.lang.Integer.MAX_VALUE, responsible)); childrenList.add(new Property("reason", "CodeableConcept", "Coded indication of the cause for the event - indicates a reason for the occurance of the event that is a focus of this message.", 0, java.lang.Integer.MAX_VALUE, reason)); childrenList.add(new Property("data", "Reference(Any)", "The actual data of the message - a reference to the root/focus class of the event.", 0, java.lang.Integer.MAX_VALUE, data)); } public MessageHeader copy() { MessageHeader dst = new MessageHeader(); copyValues(dst); dst.identifier = identifier == null ? null : identifier.copy(); dst.timestamp = timestamp == null ? null : timestamp.copy(); dst.event = event == null ? null : event.copy(); dst.response = response == null ? null : response.copy(); dst.source = source == null ? null : source.copy(); if (destination != null) { dst.destination = new ArrayList<MessageDestinationComponent>(); for (MessageDestinationComponent i : destination) dst.destination.add(i.copy()); }; dst.enterer = enterer == null ? null : enterer.copy(); dst.author = author == null ? null : author.copy(); dst.receiver = receiver == null ? null : receiver.copy(); dst.responsible = responsible == null ? null : responsible.copy(); dst.reason = reason == null ? null : reason.copy(); if (data != null) { dst.data = new ArrayList<Reference>(); for (Reference i : data) dst.data.add(i.copy()); }; return dst; } protected MessageHeader typedCopy() { return copy(); } @Override public boolean equalsDeep(Base other) { if (!super.equalsDeep(other)) return false; if (!(other instanceof MessageHeader)) return false; MessageHeader o = (MessageHeader) other; return compareDeep(identifier, o.identifier, true) && compareDeep(timestamp, o.timestamp, true) && compareDeep(event, o.event, true) && compareDeep(response, o.response, true) && compareDeep(source, o.source, true) && compareDeep(destination, o.destination, true) && compareDeep(enterer, o.enterer, true) && compareDeep(author, o.author, true) && compareDeep(receiver, o.receiver, true) && compareDeep(responsible, o.responsible, true) && compareDeep(reason, o.reason, true) && compareDeep(data, o.data, true); } @Override public boolean equalsShallow(Base other) { if (!super.equalsShallow(other)) return false; if (!(other instanceof MessageHeader)) return false; MessageHeader o = (MessageHeader) other; return compareValues(identifier, o.identifier, true) && compareValues(timestamp, o.timestamp, true) ; } public boolean isEmpty() { return super.isEmpty() && (identifier == null || identifier.isEmpty()) && (timestamp == null || timestamp.isEmpty()) && (event == null || event.isEmpty()) && (response == null || response.isEmpty()) && (source == null || source.isEmpty()) && (destination == null || destination.isEmpty()) && (enterer == null || enterer.isEmpty()) && (author == null || author.isEmpty()) && (receiver == null || receiver.isEmpty()) && (responsible == null || responsible.isEmpty()) && (reason == null || reason.isEmpty()) && (data == null || data.isEmpty()); } @Override public ResourceType getResourceType() { return ResourceType.MessageHeader; } @SearchParamDefinition(name="code", path="MessageHeader.response.code", description="ok | transient-error | fatal-error", type="token" ) public static final String SP_CODE = "code"; @SearchParamDefinition(name="data", path="MessageHeader.data", description="The actual content of the message", type="reference" ) public static final String SP_DATA = "data"; @SearchParamDefinition(name="receiver", path="MessageHeader.receiver", description="Intended \"real-world\" recipient for the data", type="reference" ) public static final String SP_RECEIVER = "receiver"; @SearchParamDefinition(name="author", path="MessageHeader.author", description="The source of the decision", type="reference" ) public static final String SP_AUTHOR = "author"; @SearchParamDefinition(name="destination", path="MessageHeader.destination.name", description="Name of system", type="string" ) public static final String SP_DESTINATION = "destination"; @SearchParamDefinition(name="source", path="MessageHeader.source.name", description="Name of system", type="string" ) public static final String SP_SOURCE = "source"; @SearchParamDefinition(name="target", path="MessageHeader.destination.target", description="Particular delivery destination within the destination", type="reference" ) public static final String SP_TARGET = "target"; @SearchParamDefinition(name="destination-uri", path="MessageHeader.destination.endpoint", description="Actual destination address or id", type="uri" ) public static final String SP_DESTINATIONURI = "destination-uri"; @SearchParamDefinition(name="src-id", path="MessageHeader.identifier", description="Id of this message", type="token" ) public static final String SP_SRCID = "src-id"; @SearchParamDefinition(name="source-uri", path="MessageHeader.source.endpoint", description="Actual message source address or id", type="uri" ) public static final String SP_SOURCEURI = "source-uri"; @SearchParamDefinition(name="responsible", path="MessageHeader.responsible", description="Final responsibility for event", type="reference" ) public static final String SP_RESPONSIBLE = "responsible"; @SearchParamDefinition(name="response-id", path="MessageHeader.response.identifier", description="Id of original message", type="token" ) public static final String SP_RESPONSEID = "response-id"; @SearchParamDefinition(name="enterer", path="MessageHeader.enterer", description="The source of the data entry", type="reference" ) public static final String SP_ENTERER = "enterer"; @SearchParamDefinition(name="event", path="MessageHeader.event", description="Code for the event this message represents", type="token" ) public static final String SP_EVENT = "event"; @SearchParamDefinition(name="timestamp", path="MessageHeader.timestamp", description="Time that the message was sent", type="date" ) public static final String SP_TIMESTAMP = "timestamp"; }
apache-2.0
cppforlife/turbulence-release
src/github.com/cloudfoundry/bosh-cli/templatescompiler/rendered_job_list_archive_test.go
3889
package templatescompiler_test import ( . "github.com/cloudfoundry/bosh-cli/templatescompiler" "bytes" "os" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" mock_template "github.com/cloudfoundry/bosh-cli/templatescompiler/mocks" "github.com/golang/mock/gomock" bosherr "github.com/cloudfoundry/bosh-utils/errors" boshlog "github.com/cloudfoundry/bosh-utils/logger" fakeboshsys "github.com/cloudfoundry/bosh-utils/system/fakes" ) var _ = Describe("RenderedJobListArchive", func() { var mockCtrl *gomock.Controller BeforeEach(func() { mockCtrl = gomock.NewController(GinkgoT()) }) AfterEach(func() { mockCtrl.Finish() }) var ( outBuffer *bytes.Buffer errBuffer *bytes.Buffer logger boshlog.Logger fs *fakeboshsys.FakeFileSystem mockRenderedJobList *mock_template.MockRenderedJobList renderedJobListArchivePath string renderedJobListFingerprint string renderedJobListArchiveSHA1 string renderedJobListArchive RenderedJobListArchive ) BeforeEach(func() { outBuffer = bytes.NewBufferString("") errBuffer = bytes.NewBufferString("") logger = boshlog.NewWriterLogger(boshlog.LevelDebug, outBuffer, errBuffer) fs = fakeboshsys.NewFakeFileSystem() mockRenderedJobList = mock_template.NewMockRenderedJobList(mockCtrl) renderedJobListArchivePath = "fake-archive-path" renderedJobListFingerprint = "fake-fingerprint" renderedJobListArchiveSHA1 = "fake-sha1" renderedJobListArchive = NewRenderedJobListArchive( mockRenderedJobList, renderedJobListArchivePath, renderedJobListFingerprint, renderedJobListArchiveSHA1, fs, logger) }) Describe("List", func() { It("returns the rendered job list", func() { Expect(renderedJobListArchive.List()).To(Equal(mockRenderedJobList)) }) }) Describe("Path", func() { It("returns the rendered job list archive path", func() { Expect(renderedJobListArchive.Path()).To(Equal(renderedJobListArchivePath)) }) }) Describe("Fingerprint", func() { It("returns the rendered job list fingerprint", func() { Expect(renderedJobListArchive.Fingerprint()).To(Equal(renderedJobListFingerprint)) }) }) Describe("SHA1", func() { It("returns the rendered job list archive sha1", func() { Expect(renderedJobListArchive.SHA1()).To(Equal(renderedJobListArchiveSHA1)) }) }) Describe("Delete", func() { It("deletes the rendered job list archive from the file system", func() { err := fs.MkdirAll(renderedJobListArchivePath, os.ModePerm) Expect(err).ToNot(HaveOccurred()) err = renderedJobListArchive.Delete() Expect(err).ToNot(HaveOccurred()) Expect(fs.FileExists(renderedJobListArchivePath)).To(BeFalse()) }) Context("when deleting from the file system fails", func() { JustBeforeEach(func() { fs.RemoveAllStub = func(_ string) error { return bosherr.Error("fake-delete-error") } }) It("returns an error", func() { err := renderedJobListArchive.Delete() Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("fake-delete-error")) }) }) }) Describe("DeleteSilently", func() { It("deletes the rendered job path from the file system", func() { err := fs.MkdirAll(renderedJobListArchivePath, os.ModePerm) Expect(err).ToNot(HaveOccurred()) renderedJobListArchive.DeleteSilently() Expect(fs.FileExists(renderedJobListArchivePath)).To(BeFalse()) }) Context("when deleting from the file system fails", func() { JustBeforeEach(func() { fs.RemoveAllStub = func(_ string) error { return bosherr.Error("fake-delete-error") } }) It("logs the error", func() { renderedJobListArchive.DeleteSilently() errorLogString := errBuffer.String() Expect(errorLogString).To(ContainSubstring("Failed to delete rendered job list archive")) Expect(errorLogString).To(ContainSubstring("fake-delete-error")) }) }) }) })
apache-2.0
hfutxqd/keding_website
tmp/5f4fb68bba309d0d863177f9178e0d985db412a7.file.project.html.php
5303
<?php /* Smarty version Smarty-3.0.8, created on 2015-08-20 04:03:50 compiled from "F:\public_html\keding\new/tpl\project.html" */ ?> <?php /*%%SmartyHeaderCode:163455d535862a48c8-73480281%%*/if(!defined('SMARTY_DIR')) exit('no direct access allowed'); $_smarty_tpl->decodeProperties(array ( 'file_dependency' => array ( '5f4fb68bba309d0d863177f9178e0d985db412a7' => array ( 0 => 'F:\\public_html\\keding\\new/tpl\\project.html', 1 => 1440036215, 2 => 'file', ), ), 'nocache_hash' => '163455d535862a48c8-73480281', 'function' => array ( ), 'has_nocache_code' => false, )); /*/%%SmartyHeaderCode%%*/?> <?php if (!is_callable('smarty_modifier_truncate')) include 'F:\public_html\keding\new\SpeedPHP\Drivers\Smarty\plugins\modifier.truncate.php'; ?><!DOCTYPE html> <head> <link rel="shortcut icon" href="favicon.ico"> <meta http-equiv="Content-Type" content="text/html; charset="utf-8" /> <meta name="description" content="合肥科鼎电气有限公司批量生产各种类型的避雷器以及避雷器在线监测仪。" /> <meta name="Keywords" content="智能数字式避雷器在线监测仪,合肥避雷器,避雷器,合肥科鼎电气有限公司,避雷器在线监测仪,科鼎,合肥科鼎,氧化锌避雷器" /> <title>合肥科鼎电气有限公司</title> <script src="js/jquery-1.4.4.min.js"></script> <script src="js/slides.min.jquery.js"></script> <link rel="stylesheet" href="css/project.css"/> <link rel="stylesheet" href="css/news.css"/> </head> <body> <div id="project_main"> <div id="project_title"> </div> <div id="news_content"> <lu> <?php $_smarty_tpl->tpl_vars['one'] = new Smarty_Variable; $_from = $_smarty_tpl->getVariable('results')->value; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array');} if ($_smarty_tpl->_count($_from) > 0){ foreach ($_from as $_smarty_tpl->tpl_vars['one']->key => $_smarty_tpl->tpl_vars['one']->value){ ?> <li><a href="<?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['spUrl'][0][0]->__template_spUrl(array('c'=>'main','a'=>'article','type'=>'projects','id'=>$_smarty_tpl->tpl_vars['one']->value['id']),$_smarty_tpl);?> "><?php echo smarty_modifier_truncate($_smarty_tpl->tpl_vars['one']->value['title'],32,'...');?> </a><span><?php echo smarty_modifier_truncate($_smarty_tpl->tpl_vars['one']->value['time'],10,'');?> </span></li> <?php }} ?> </lu> <div id="news_footer"> <?php if ($_smarty_tpl->getVariable('pager')->value){?> 共有<?php echo $_smarty_tpl->getVariable('pager')->value['total_count'];?> 条,共有<?php echo $_smarty_tpl->getVariable('pager')->value['total_page'];?> 页 <!--在当前页不是第一页的时候,显示前页和上一页--> <?php if ($_smarty_tpl->getVariable('pager')->value['current_page']!=$_smarty_tpl->getVariable('pager')->value['first_page']){?> <a href="<?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['spUrl'][0][0]->__template_spUrl(array('c'=>'main','a'=>'project','page'=>$_smarty_tpl->getVariable('pager')->value['first_page']),$_smarty_tpl);?> ">首页</a> | <a href="<?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['spUrl'][0][0]->__template_spUrl(array('c'=>'main','a'=>'project','page'=>$_smarty_tpl->getVariable('pager')->value['prev_page']),$_smarty_tpl);?> ">上一页</a> | <?php }?> <!--开始循环页码,同时如果循环到当前页则不显示链接--> <?php $_smarty_tpl->tpl_vars['thepage'] = new Smarty_Variable; $_from = $_smarty_tpl->getVariable('pager')->value['all_pages']; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array');} if ($_smarty_tpl->_count($_from) > 0){ foreach ($_from as $_smarty_tpl->tpl_vars['thepage']->key => $_smarty_tpl->tpl_vars['thepage']->value){ ?> <?php if ($_smarty_tpl->tpl_vars['thepage']->value!=$_smarty_tpl->getVariable('pager')->value['current_page']){?> <a href="<?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['spUrl'][0][0]->__template_spUrl(array('c'=>'main','a'=>'project','page'=>$_smarty_tpl->tpl_vars['thepage']->value),$_smarty_tpl);?> "><?php echo $_smarty_tpl->tpl_vars['thepage']->value;?> </a> <?php }else{ ?> <b><?php echo $_smarty_tpl->tpl_vars['thepage']->value;?> </b> <?php }?> <?php }} ?> <!--在当前页不是最后一页的时候,显示下一页和后页--> <?php if ($_smarty_tpl->getVariable('pager')->value['current_page']!=$_smarty_tpl->getVariable('pager')->value['last_page']){?> | <a href="<?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['spUrl'][0][0]->__template_spUrl(array('c'=>'main','a'=>'project','page'=>$_smarty_tpl->getVariable('pager')->value['next_page']),$_smarty_tpl);?> ">下一页</a> | <a href="<?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['spUrl'][0][0]->__template_spUrl(array('c'=>'main','a'=>'project','page'=>$_smarty_tpl->getVariable('pager')->value['last_page']),$_smarty_tpl);?> ">末页</a> <?php }?> <?php }?> </div> </div> </div> </div> <script> parent.document.getElementById('win').style.height = 650 + 'px'; </script> </body> </html>
apache-2.0
morganzhh/sysrepo
src/executables/sysrepod.c
4424
/** * @file sysrepod.c * @author Rastislav Szabo <[email protected]>, Lukas Macko <[email protected]> * @brief Sysrepo daemon source file. * * @copyright * Copyright 2016 Cisco Systems, 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. */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <limits.h> #include <signal.h> #include "sr_common.h" #include "connection_manager.h" /** * @brief Callback to be called when a signal requesting daemon termination has been received. */ static void srd_sigterm_cb(cm_ctx_t *cm_ctx, int signum) { if (NULL != cm_ctx) { SR_LOG_INF("Sysrepo daemon termination requested by %s signal.", (SIGTERM == signum ? "SIGTERM" : "SIGINT")); /* stop the event loop in the Connection Manager */ cm_stop(cm_ctx); } } /** * @brief Prints daemon version. */ static void srd_print_version() { printf("sysrepod - sysrepo daemon, version %s\n\n", SR_VERSION); } /** * @brief Prints daemon usage help. */ static void srd_print_help() { srd_print_version(); printf("Usage:\n"); printf(" sysrepod [-h] [-v] [-d] [-l <level>]\n\n"); printf("Options:\n"); printf(" -h\t\tPrints usage help.\n"); printf(" -v\t\tPrints version.\n"); printf(" -d\t\tDebug mode - daemon will run in the foreground and print logs to stderr instead of syslog.\n"); printf(" -l <level>\tSets verbosity level of logging:\n"); printf("\t\t\t0 = all logging turned off\n"); printf("\t\t\t1 = log only error messages\n"); printf("\t\t\t2 = (default) log error and warning messages\n"); printf("\t\t\t3 = log error, warning and informational messages\n"); printf("\t\t\t4 = log everything, including development debug messages\n"); } /** * @brief Main routine of the sysrepo daemon. */ int main(int argc, char* argv[]) { pid_t parent_pid = 0; int pidfile_fd = -1; cm_ctx_t *sr_cm_ctx = NULL; int c = 0; bool debug_mode = false; int log_level = -1; int rc = SR_ERR_OK; while ((c = getopt (argc, argv, "hvdl:")) != -1) { switch (c) { case 'v': srd_print_version(); return 0; break; case 'd': debug_mode = true; break; case 'l': log_level = atoi(optarg); break; default: srd_print_help(); return 0; } } /* init logger */ sr_logger_init("sysrepod"); /* daemonize the process */ parent_pid = sr_daemonize(debug_mode, log_level, SR_DAEMON_PID_FILE, &pidfile_fd); /* initialize local Connection Manager */ rc = cm_init(CM_MODE_DAEMON, SR_DAEMON_SOCKET, &sr_cm_ctx); CHECK_RC_LOG_GOTO(rc, cleanup, "Unable to initialize Connection Manager: %s.", sr_strerror(rc)); /* install SIGTERM & SIGINT signal watchers */ rc = cm_watch_signal(sr_cm_ctx, SIGTERM, srd_sigterm_cb); if (SR_ERR_OK == rc) { rc = cm_watch_signal(sr_cm_ctx, SIGINT, srd_sigterm_cb); } CHECK_RC_LOG_GOTO(rc, cleanup, "Unable to initialize signal watcher: %s.", sr_strerror(rc)); /* tell the parent process that we are okay */ if (!debug_mode) { sr_daemonize_signal_success(parent_pid); } SR_LOG_INF_MSG("Sysrepo daemon initialized successfully."); /* execute the server (the call is blocking in the event loop) */ rc = cm_start(sr_cm_ctx); if (SR_ERR_OK != rc) { SR_LOG_ERR("Connection Manager execution returned an error: %s.", sr_strerror(rc)); } cleanup: cm_cleanup(sr_cm_ctx); SR_LOG_INF_MSG("Sysrepo daemon terminated."); sr_logger_cleanup(); unlink(SR_DAEMON_PID_FILE); if (-1 != pidfile_fd) { close(pidfile_fd); } exit((SR_ERR_OK == rc) ? EXIT_SUCCESS : EXIT_FAILURE); }
apache-2.0
Lidchanin/Shopping_List
app/src/main/java/com/lidchanin/shoppinglist/customview/DesignedEditText.java
821
package com.lidchanin.shoppinglist.customview; import android.content.Context; import android.graphics.Typeface; import android.util.AttributeSet; /** * Created by Alexander Destroyed on 19.08.2017. */ public class DesignedEditText extends android.support.v7.widget.AppCompatEditText { public DesignedEditText(Context context) { super(context); init(); } public DesignedEditText(Context context, AttributeSet attrs) { super(context, attrs); init(); } public DesignedEditText(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } public void init() { Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "MyriadPro-Regular.otf"); setTypeface(tf ,1); } }
apache-2.0
rwl/muntjac
muntjac/terminal/gwt/client/ui/v_option_group.py
110
# @MUNTJAC_COPYRIGHT@ # @MUNTJAC_LICENSE@ class VOptionGroup(object): HTML_CONTENT_ALLOWED = "usehtml"
apache-2.0
gsx-lab/caras-framework
spec/models/hostname_spec.rb
1898
# Copyright 2017 Global Security Experts 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. # require_relative '../app_helper' RSpec.describe Hostname do let(:site) { create(:site) } let(:host) { create(:host, site: site) } let(:other_host) { create(:host, :other, site: site) } let(:hostname) { create(:hostname, host: host) } let(:other_hostname) { create(:hostname, :other, host: host) } describe 'validation' do subject { hostname } it { is_expected.to be_valid } it { expect(other_hostname).to be_valid } describe 'host_id' do it 'should not be nil' do hostname.host_id = nil is_expected.not_to be_valid end it 'should exist' do hostname.host_id = Host.maximum(:id) + 1 is_expected.not_to be_valid end end describe 'name' do it 'should not be blank' do hostname.name = nil is_expected.not_to be_valid hostname.name = '' is_expected.not_to be_valid hostname.name = 'test.name' is_expected.to be_valid end it 'should be unique in host' do hostname.name = other_hostname.name is_expected.not_to be_valid end it 'is allowed to give same name to different hosts' do hostname.name = other_hostname.name hostname.host = other_host is_expected.to be_valid end end end end
apache-2.0
Talend/ui
packages/faceted-search/src/components/FacetedSearchIcon/FacetedSearchIcon.component.test.js
1710
import React from 'react'; // eslint-disable-next-line import/no-extraneous-dependencies import { mount } from 'enzyme'; // eslint-disable-next-line import/no-extraneous-dependencies import { FacetedSearchIcon } from './FacetedSearchIcon.component'; import getDefaultT from '../../translate'; const t = getDefaultT(); describe('FacetedSearchIcon', () => { it('should render by default', () => { // given const props = { onClick: jest.fn(), t, }; // when const wrapper = mount(<FacetedSearchIcon {...props} />); // then expect(wrapper.html()).toMatchSnapshot(); }); it('should render with button active when active props true', () => { // given const props = { active: true, onClick: jest.fn(), t, }; // when const wrapper = mount(<FacetedSearchIcon {...props} />); // then expect(wrapper.find('button[aria-label="Show faceted search"]').prop('className')).toEqual( 'faceted-search-icon theme-faceted-search-icon tc-icon-toggle theme-tc-icon-toggle theme-active active btn btn-link', ); }); it('should call onClick when trigger click', () => { // given const onClick = jest.fn(); const props = { active: true, onClick, t, }; // when const wrapper = mount(<FacetedSearchIcon {...props} />); wrapper.find('button[aria-label="Show faceted search"]').simulate('click'); // then expect(onClick).toHaveBeenCalled(); expect(onClick.mock.calls.length).toBe(1); }); it('should render the button in loading mode', () => { // given const props = { loading: true, onClick: jest.fn(), t, }; // when const wrapper = mount(<FacetedSearchIcon {...props} />); // then expect(wrapper.html()).toMatchSnapshot(); }); });
apache-2.0
campusappcn/Pan
docs/cn/campusapp/pan/lifecycle/OnPostCreate.html
9022
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="zh"> <head> <!-- Generated by javadoc (1.8.0_152-release) on Sat Oct 20 11:45:58 CST 2018 --> <title>OnPostCreate (library API)</title> <meta name="date" content="2018-10-20"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="OnPostCreate (library API)"; } } catch(err) { } //--> var methods = {"i0":6}; var tabs = {65535:["t0","所有方法"],2:["t2","实例方法"],4:["t3","抽象方法"]}; var altColor = "altColor"; var rowColor = "rowColor"; var tableTab = "tableTab"; var activeTableTab = "activeTableTab"; </script> <noscript> <div>您的浏览器已禁用 JavaScript。</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="跳过导航链接">跳过导航链接</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="导航"> <li><a href="../../../../overview-summary.html">概览</a></li> <li><a href="package-summary.html">程序包</a></li> <li class="navBarCell1Rev">类</li> <li><a href="package-tree.html">树</a></li> <li><a href="../../../../deprecated-list.html">已过时</a></li> <li><a href="../../../../index-all.html">索引</a></li> <li><a href="../../../../help-doc.html">帮助</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../cn/campusapp/pan/lifecycle/OnPause.html" title="cn.campusapp.pan.lifecycle中的接口"><span class="typeNameLink">上一个类</span></a></li> <li><a href="../../../../cn/campusapp/pan/lifecycle/OnRestart.html" title="cn.campusapp.pan.lifecycle中的接口"><span class="typeNameLink">下一个类</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?cn/campusapp/pan/lifecycle/OnPostCreate.html" target="_top">框架</a></li> <li><a href="OnPostCreate.html" target="_top">无框架</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">所有类</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>概要:&nbsp;</li> <li>嵌套&nbsp;|&nbsp;</li> <li>字段&nbsp;|&nbsp;</li> <li>构造器&nbsp;|&nbsp;</li> <li><a href="#method.summary">方法</a></li> </ul> <ul class="subNavList"> <li>详细资料:&nbsp;</li> <li>字段&nbsp;|&nbsp;</li> <li>构造器&nbsp;|&nbsp;</li> <li><a href="#method.detail">方法</a></li> </ul> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">cn.campusapp.pan.lifecycle</div> <h2 title="接口 OnPostCreate" class="title">接口 OnPostCreate</h2> </div> <div class="contentContainer"> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>所有超级接口:</dt> <dd><a href="../../../../cn/campusapp/pan/lifecycle/LifecycleObserver.html" title="cn.campusapp.pan.lifecycle中的接口">LifecycleObserver</a>, <a href="../../../../cn/campusapp/pan/lifecycle/LifecycleObserver.ForActivity.html" title="cn.campusapp.pan.lifecycle中的接口">LifecycleObserver.ForActivity</a></dd> </dl> <hr> <br> <pre>public interface <span class="typeNameLabel">OnPostCreate</span> extends <a href="../../../../cn/campusapp/pan/lifecycle/LifecycleObserver.html" title="cn.campusapp.pan.lifecycle中的接口">LifecycleObserver</a>, <a href="../../../../cn/campusapp/pan/lifecycle/LifecycleObserver.ForActivity.html" title="cn.campusapp.pan.lifecycle中的接口">LifecycleObserver.ForActivity</a></pre> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== NESTED CLASS SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="nested.class.summary"> <!-- --> </a> <h3>嵌套类概要</h3> <ul class="blockList"> <li class="blockList"><a name="nested.classes.inherited.from.class.cn.campusapp.pan.lifecycle.LifecycleObserver"> <!-- --> </a> <h3>从接口继承的嵌套类/接口&nbsp;cn.campusapp.pan.lifecycle.<a href="../../../../cn/campusapp/pan/lifecycle/LifecycleObserver.html" title="cn.campusapp.pan.lifecycle中的接口">LifecycleObserver</a></h3> <code><a href="../../../../cn/campusapp/pan/lifecycle/LifecycleObserver.ForActivity.html" title="cn.campusapp.pan.lifecycle中的接口">LifecycleObserver.ForActivity</a>, <a href="../../../../cn/campusapp/pan/lifecycle/LifecycleObserver.ForFragment.html" title="cn.campusapp.pan.lifecycle中的接口">LifecycleObserver.ForFragment</a></code></li> </ul> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method.summary"> <!-- --> </a> <h3>方法概要</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="方法概要表, 列表方法和解释"> <caption><span id="t0" class="activeTableTab"><span>所有方法</span><span class="tabEnd">&nbsp;</span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">实例方法</a></span><span class="tabEnd">&nbsp;</span></span><span id="t3" class="tableTab"><span><a href="javascript:show(4);">抽象方法</a></span><span class="tabEnd">&nbsp;</span></span></caption> <tr> <th class="colFirst" scope="col">限定符和类型</th> <th class="colLast" scope="col">方法和说明</th> </tr> <tr id="i0" class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../cn/campusapp/pan/lifecycle/OnPostCreate.html#onPostCreate-android.os.Bundle-">onPostCreate</a></span>(android.os.Bundle&nbsp;savedInstanceState)</code>&nbsp;</td> </tr> </table> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method.detail"> <!-- --> </a> <h3>方法详细资料</h3> <a name="onPostCreate-android.os.Bundle-"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>onPostCreate</h4> <pre>void&nbsp;onPostCreate(android.os.Bundle&nbsp;savedInstanceState)</pre> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="跳过导航链接">跳过导航链接</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="导航"> <li><a href="../../../../overview-summary.html">概览</a></li> <li><a href="package-summary.html">程序包</a></li> <li class="navBarCell1Rev">类</li> <li><a href="package-tree.html">树</a></li> <li><a href="../../../../deprecated-list.html">已过时</a></li> <li><a href="../../../../index-all.html">索引</a></li> <li><a href="../../../../help-doc.html">帮助</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../cn/campusapp/pan/lifecycle/OnPause.html" title="cn.campusapp.pan.lifecycle中的接口"><span class="typeNameLink">上一个类</span></a></li> <li><a href="../../../../cn/campusapp/pan/lifecycle/OnRestart.html" title="cn.campusapp.pan.lifecycle中的接口"><span class="typeNameLink">下一个类</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?cn/campusapp/pan/lifecycle/OnPostCreate.html" target="_top">框架</a></li> <li><a href="OnPostCreate.html" target="_top">无框架</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">所有类</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>概要:&nbsp;</li> <li>嵌套&nbsp;|&nbsp;</li> <li>字段&nbsp;|&nbsp;</li> <li>构造器&nbsp;|&nbsp;</li> <li><a href="#method.summary">方法</a></li> </ul> <ul class="subNavList"> <li>详细资料:&nbsp;</li> <li>字段&nbsp;|&nbsp;</li> <li>构造器&nbsp;|&nbsp;</li> <li><a href="#method.detail">方法</a></li> </ul> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
apache-2.0
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Rosales/Rosaceae/Potentilla/Potentilla crantzii/ Syn. Potentilla sabauda/README.md
203
# Potentilla sabauda Vill. ex DC., nom. illegit. SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
apache-2.0
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Rubiaceae/Simira/Simira mollis/README.md
190
# Simira mollis (Standl.) Steyerm. SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
apache-2.0
mdoering/backbone
life/Chromista/Ochrophyta/Phaeophyceae/Sphacelariales/Sphacelariaceae/Cladostephus/Cladostephus ceratophyllum/README.md
201
# Cladostephus ceratophyllum (Roth) C. Agardh SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
apache-2.0
mdoering/backbone
life/Fungi/Ascomycota/Sordariomycetes/Hypocreales/Myrothecium/Myrothecium dimorphum/README.md
252
# Myrothecium dimorphum Ts. Watan. SPECIES #### Status ACCEPTED #### According to Index Fungorum #### Published in in Watanabe, Watanabe & Nakamura, Mycoscience 44(4): 284 (2003) #### Original name Myrothecium dimorphum Ts. Watan. ### Remarks null
apache-2.0
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Plumbaginaceae/Armeria/Armeria villosa/Armeria villosa longiaristata/README.md
217
# Armeria villosa subsp. longiaristata (Boiss. & Reut.) Nieto Fel. SUBSPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
apache-2.0
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Myrtales/Melastomataceae/Mecranium/Mecranium axillare/Mecranium axillare urbanianum/README.md
211
# Mecranium axillare subsp. urbanianum (Cogn.) Skean SUBSPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
apache-2.0
mdoering/backbone
life/Fungi/Basidiomycota/Agaricomycetes/Hymenochaetales/Hymenochaetaceae/Inonotus/Inonotus obliquus/ Syn. Poria obliqua/README.md
266
# Poria obliqua (Ach. ex Pers.) P. Karst., 1881 SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in Revue mycol. , Toulouse 3: 19 (1881) #### Original name Boletus obliquus Ach. ex Pers., 1801 ### Remarks null
apache-2.0
dmcgowan/docker
daemon/oci_linux.go
25547
package daemon // import "github.com/docker/docker/daemon" import ( "fmt" "io" "os" "os/exec" "path/filepath" "sort" "strconv" "strings" containertypes "github.com/docker/docker/api/types/container" "github.com/docker/docker/container" daemonconfig "github.com/docker/docker/daemon/config" "github.com/docker/docker/oci" "github.com/docker/docker/pkg/idtools" "github.com/docker/docker/pkg/mount" volumemounts "github.com/docker/docker/volume/mounts" "github.com/opencontainers/runc/libcontainer/apparmor" "github.com/opencontainers/runc/libcontainer/cgroups" "github.com/opencontainers/runc/libcontainer/devices" "github.com/opencontainers/runc/libcontainer/user" "github.com/opencontainers/runtime-spec/specs-go" "github.com/pkg/errors" "github.com/sirupsen/logrus" "golang.org/x/sys/unix" ) const ( inContainerInitPath = "/sbin/" + daemonconfig.DefaultInitBinary ) func setResources(s *specs.Spec, r containertypes.Resources) error { weightDevices, err := getBlkioWeightDevices(r) if err != nil { return err } readBpsDevice, err := getBlkioThrottleDevices(r.BlkioDeviceReadBps) if err != nil { return err } writeBpsDevice, err := getBlkioThrottleDevices(r.BlkioDeviceWriteBps) if err != nil { return err } readIOpsDevice, err := getBlkioThrottleDevices(r.BlkioDeviceReadIOps) if err != nil { return err } writeIOpsDevice, err := getBlkioThrottleDevices(r.BlkioDeviceWriteIOps) if err != nil { return err } memoryRes := getMemoryResources(r) cpuRes, err := getCPUResources(r) if err != nil { return err } blkioWeight := r.BlkioWeight specResources := &specs.LinuxResources{ Memory: memoryRes, CPU: cpuRes, BlockIO: &specs.LinuxBlockIO{ Weight: &blkioWeight, WeightDevice: weightDevices, ThrottleReadBpsDevice: readBpsDevice, ThrottleWriteBpsDevice: writeBpsDevice, ThrottleReadIOPSDevice: readIOpsDevice, ThrottleWriteIOPSDevice: writeIOpsDevice, }, Pids: &specs.LinuxPids{ Limit: r.PidsLimit, }, } if s.Linux.Resources != nil && len(s.Linux.Resources.Devices) > 0 { specResources.Devices = s.Linux.Resources.Devices } s.Linux.Resources = specResources return nil } func setDevices(s *specs.Spec, c *container.Container) error { // Build lists of devices allowed and created within the container. var devs []specs.LinuxDevice devPermissions := s.Linux.Resources.Devices if c.HostConfig.Privileged { hostDevices, err := devices.HostDevices() if err != nil { return err } for _, d := range hostDevices { devs = append(devs, oci.Device(d)) } devPermissions = []specs.LinuxDeviceCgroup{ { Allow: true, Access: "rwm", }, } } else { for _, deviceMapping := range c.HostConfig.Devices { d, dPermissions, err := oci.DevicesFromPath(deviceMapping.PathOnHost, deviceMapping.PathInContainer, deviceMapping.CgroupPermissions) if err != nil { return err } devs = append(devs, d...) devPermissions = append(devPermissions, dPermissions...) } var err error devPermissions, err = appendDevicePermissionsFromCgroupRules(devPermissions, c.HostConfig.DeviceCgroupRules) if err != nil { return err } } s.Linux.Devices = append(s.Linux.Devices, devs...) s.Linux.Resources.Devices = devPermissions return nil } func (daemon *Daemon) setRlimits(s *specs.Spec, c *container.Container) error { var rlimits []specs.POSIXRlimit // We want to leave the original HostConfig alone so make a copy here hostConfig := *c.HostConfig // Merge with the daemon defaults daemon.mergeUlimits(&hostConfig) for _, ul := range hostConfig.Ulimits { rlimits = append(rlimits, specs.POSIXRlimit{ Type: "RLIMIT_" + strings.ToUpper(ul.Name), Soft: uint64(ul.Soft), Hard: uint64(ul.Hard), }) } s.Process.Rlimits = rlimits return nil } func setUser(s *specs.Spec, c *container.Container) error { uid, gid, additionalGids, err := getUser(c, c.Config.User) if err != nil { return err } s.Process.User.UID = uid s.Process.User.GID = gid s.Process.User.AdditionalGids = additionalGids return nil } func readUserFile(c *container.Container, p string) (io.ReadCloser, error) { fp, err := c.GetResourcePath(p) if err != nil { return nil, err } return os.Open(fp) } func getUser(c *container.Container, username string) (uint32, uint32, []uint32, error) { passwdPath, err := user.GetPasswdPath() if err != nil { return 0, 0, nil, err } groupPath, err := user.GetGroupPath() if err != nil { return 0, 0, nil, err } passwdFile, err := readUserFile(c, passwdPath) if err == nil { defer passwdFile.Close() } groupFile, err := readUserFile(c, groupPath) if err == nil { defer groupFile.Close() } execUser, err := user.GetExecUser(username, nil, passwdFile, groupFile) if err != nil { return 0, 0, nil, err } // todo: fix this double read by a change to libcontainer/user pkg groupFile, err = readUserFile(c, groupPath) if err == nil { defer groupFile.Close() } var addGroups []int if len(c.HostConfig.GroupAdd) > 0 { addGroups, err = user.GetAdditionalGroups(c.HostConfig.GroupAdd, groupFile) if err != nil { return 0, 0, nil, err } } uid := uint32(execUser.Uid) gid := uint32(execUser.Gid) sgids := append(execUser.Sgids, addGroups...) var additionalGids []uint32 for _, g := range sgids { additionalGids = append(additionalGids, uint32(g)) } return uid, gid, additionalGids, nil } func setNamespace(s *specs.Spec, ns specs.LinuxNamespace) { for i, n := range s.Linux.Namespaces { if n.Type == ns.Type { s.Linux.Namespaces[i] = ns return } } s.Linux.Namespaces = append(s.Linux.Namespaces, ns) } func setNamespaces(daemon *Daemon, s *specs.Spec, c *container.Container) error { userNS := false // user if c.HostConfig.UsernsMode.IsPrivate() { uidMap := daemon.idMapping.UIDs() if uidMap != nil { userNS = true ns := specs.LinuxNamespace{Type: "user"} setNamespace(s, ns) s.Linux.UIDMappings = specMapping(uidMap) s.Linux.GIDMappings = specMapping(daemon.idMapping.GIDs()) } } // network if !c.Config.NetworkDisabled { ns := specs.LinuxNamespace{Type: "network"} parts := strings.SplitN(string(c.HostConfig.NetworkMode), ":", 2) if parts[0] == "container" { nc, err := daemon.getNetworkedContainer(c.ID, c.HostConfig.NetworkMode.ConnectedContainer()) if err != nil { return err } ns.Path = fmt.Sprintf("/proc/%d/ns/net", nc.State.GetPID()) if userNS { // to share a net namespace, they must also share a user namespace nsUser := specs.LinuxNamespace{Type: "user"} nsUser.Path = fmt.Sprintf("/proc/%d/ns/user", nc.State.GetPID()) setNamespace(s, nsUser) } } else if c.HostConfig.NetworkMode.IsHost() { ns.Path = c.NetworkSettings.SandboxKey } setNamespace(s, ns) } // ipc ipcMode := c.HostConfig.IpcMode switch { case ipcMode.IsContainer(): ns := specs.LinuxNamespace{Type: "ipc"} ic, err := daemon.getIpcContainer(ipcMode.Container()) if err != nil { return err } ns.Path = fmt.Sprintf("/proc/%d/ns/ipc", ic.State.GetPID()) setNamespace(s, ns) if userNS { // to share an IPC namespace, they must also share a user namespace nsUser := specs.LinuxNamespace{Type: "user"} nsUser.Path = fmt.Sprintf("/proc/%d/ns/user", ic.State.GetPID()) setNamespace(s, nsUser) } case ipcMode.IsHost(): oci.RemoveNamespace(s, specs.LinuxNamespaceType("ipc")) case ipcMode.IsEmpty(): // A container was created by an older version of the daemon. // The default behavior used to be what is now called "shareable". fallthrough case ipcMode.IsPrivate(), ipcMode.IsShareable(), ipcMode.IsNone(): ns := specs.LinuxNamespace{Type: "ipc"} setNamespace(s, ns) default: return fmt.Errorf("Invalid IPC mode: %v", ipcMode) } // pid if c.HostConfig.PidMode.IsContainer() { ns := specs.LinuxNamespace{Type: "pid"} pc, err := daemon.getPidContainer(c) if err != nil { return err } ns.Path = fmt.Sprintf("/proc/%d/ns/pid", pc.State.GetPID()) setNamespace(s, ns) if userNS { // to share a PID namespace, they must also share a user namespace nsUser := specs.LinuxNamespace{Type: "user"} nsUser.Path = fmt.Sprintf("/proc/%d/ns/user", pc.State.GetPID()) setNamespace(s, nsUser) } } else if c.HostConfig.PidMode.IsHost() { oci.RemoveNamespace(s, specs.LinuxNamespaceType("pid")) } else { ns := specs.LinuxNamespace{Type: "pid"} setNamespace(s, ns) } // uts if c.HostConfig.UTSMode.IsHost() { oci.RemoveNamespace(s, specs.LinuxNamespaceType("uts")) s.Hostname = "" } return nil } func specMapping(s []idtools.IDMap) []specs.LinuxIDMapping { var ids []specs.LinuxIDMapping for _, item := range s { ids = append(ids, specs.LinuxIDMapping{ HostID: uint32(item.HostID), ContainerID: uint32(item.ContainerID), Size: uint32(item.Size), }) } return ids } // Get the source mount point of directory passed in as argument. Also return // optional fields. func getSourceMount(source string) (string, string, error) { // Ensure any symlinks are resolved. sourcePath, err := filepath.EvalSymlinks(source) if err != nil { return "", "", err } mi, err := mount.GetMounts(mount.ParentsFilter(sourcePath)) if err != nil { return "", "", err } if len(mi) < 1 { return "", "", fmt.Errorf("Can't find mount point of %s", source) } // find the longest mount point var idx, maxlen int for i := range mi { if len(mi[i].Mountpoint) > maxlen { maxlen = len(mi[i].Mountpoint) idx = i } } return mi[idx].Mountpoint, mi[idx].Optional, nil } const ( sharedPropagationOption = "shared:" slavePropagationOption = "master:" ) // hasMountinfoOption checks if any of the passed any of the given option values // are set in the passed in option string. func hasMountinfoOption(opts string, vals ...string) bool { for _, opt := range strings.Split(opts, " ") { for _, val := range vals { if strings.HasPrefix(opt, val) { return true } } } return false } // Ensure mount point on which path is mounted, is shared. func ensureShared(path string) error { sourceMount, optionalOpts, err := getSourceMount(path) if err != nil { return err } // Make sure source mount point is shared. if !hasMountinfoOption(optionalOpts, sharedPropagationOption) { return errors.Errorf("path %s is mounted on %s but it is not a shared mount", path, sourceMount) } return nil } // Ensure mount point on which path is mounted, is either shared or slave. func ensureSharedOrSlave(path string) error { sourceMount, optionalOpts, err := getSourceMount(path) if err != nil { return err } if !hasMountinfoOption(optionalOpts, sharedPropagationOption, slavePropagationOption) { return errors.Errorf("path %s is mounted on %s but it is not a shared or slave mount", path, sourceMount) } return nil } // Get the set of mount flags that are set on the mount that contains the given // path and are locked by CL_UNPRIVILEGED. This is necessary to ensure that // bind-mounting "with options" will not fail with user namespaces, due to // kernel restrictions that require user namespace mounts to preserve // CL_UNPRIVILEGED locked flags. func getUnprivilegedMountFlags(path string) ([]string, error) { var statfs unix.Statfs_t if err := unix.Statfs(path, &statfs); err != nil { return nil, err } // The set of keys come from https://github.com/torvalds/linux/blob/v4.13/fs/namespace.c#L1034-L1048. unprivilegedFlags := map[uint64]string{ unix.MS_RDONLY: "ro", unix.MS_NODEV: "nodev", unix.MS_NOEXEC: "noexec", unix.MS_NOSUID: "nosuid", unix.MS_NOATIME: "noatime", unix.MS_RELATIME: "relatime", unix.MS_NODIRATIME: "nodiratime", } var flags []string for mask, flag := range unprivilegedFlags { if uint64(statfs.Flags)&mask == mask { flags = append(flags, flag) } } return flags, nil } var ( mountPropagationMap = map[string]int{ "private": mount.PRIVATE, "rprivate": mount.RPRIVATE, "shared": mount.SHARED, "rshared": mount.RSHARED, "slave": mount.SLAVE, "rslave": mount.RSLAVE, } mountPropagationReverseMap = map[int]string{ mount.PRIVATE: "private", mount.RPRIVATE: "rprivate", mount.SHARED: "shared", mount.RSHARED: "rshared", mount.SLAVE: "slave", mount.RSLAVE: "rslave", } ) // inSlice tests whether a string is contained in a slice of strings or not. // Comparison is case sensitive func inSlice(slice []string, s string) bool { for _, ss := range slice { if s == ss { return true } } return false } func setMounts(daemon *Daemon, s *specs.Spec, c *container.Container, mounts []container.Mount) error { userMounts := make(map[string]struct{}) for _, m := range mounts { userMounts[m.Destination] = struct{}{} } // Copy all mounts from spec to defaultMounts, except for // - mounts overridden by a user supplied mount; // - all mounts under /dev if a user supplied /dev is present; // - /dev/shm, in case IpcMode is none. // While at it, also // - set size for /dev/shm from shmsize. defaultMounts := s.Mounts[:0] _, mountDev := userMounts["/dev"] for _, m := range s.Mounts { if _, ok := userMounts[m.Destination]; ok { // filter out mount overridden by a user supplied mount continue } if mountDev && strings.HasPrefix(m.Destination, "/dev/") { // filter out everything under /dev if /dev is user-mounted continue } if m.Destination == "/dev/shm" { if c.HostConfig.IpcMode.IsNone() { // filter out /dev/shm for "none" IpcMode continue } // set size for /dev/shm mount from spec sizeOpt := "size=" + strconv.FormatInt(c.HostConfig.ShmSize, 10) m.Options = append(m.Options, sizeOpt) } defaultMounts = append(defaultMounts, m) } s.Mounts = defaultMounts for _, m := range mounts { if m.Source == "tmpfs" { data := m.Data parser := volumemounts.NewParser("linux") options := []string{"noexec", "nosuid", "nodev", string(parser.DefaultPropagationMode())} if data != "" { options = append(options, strings.Split(data, ",")...) } merged, err := mount.MergeTmpfsOptions(options) if err != nil { return err } s.Mounts = append(s.Mounts, specs.Mount{Destination: m.Destination, Source: m.Source, Type: "tmpfs", Options: merged}) continue } mt := specs.Mount{Destination: m.Destination, Source: m.Source, Type: "bind"} // Determine property of RootPropagation based on volume // properties. If a volume is shared, then keep root propagation // shared. This should work for slave and private volumes too. // // For slave volumes, it can be either [r]shared/[r]slave. // // For private volumes any root propagation value should work. pFlag := mountPropagationMap[m.Propagation] switch pFlag { case mount.SHARED, mount.RSHARED: if err := ensureShared(m.Source); err != nil { return err } rootpg := mountPropagationMap[s.Linux.RootfsPropagation] if rootpg != mount.SHARED && rootpg != mount.RSHARED { s.Linux.RootfsPropagation = mountPropagationReverseMap[mount.SHARED] } case mount.SLAVE, mount.RSLAVE: var fallback bool if err := ensureSharedOrSlave(m.Source); err != nil { // For backwards compatibility purposes, treat mounts from the daemon root // as special since we automatically add rslave propagation to these mounts // when the user did not set anything, so we should fallback to the old // behavior which is to use private propagation which is normally the // default. if !strings.HasPrefix(m.Source, daemon.root) && !strings.HasPrefix(daemon.root, m.Source) { return err } cm, ok := c.MountPoints[m.Destination] if !ok { return err } if cm.Spec.BindOptions != nil && cm.Spec.BindOptions.Propagation != "" { // This means the user explicitly set a propagation, do not fallback in that case. return err } fallback = true logrus.WithField("container", c.ID).WithField("source", m.Source).Warn("Falling back to default propagation for bind source in daemon root") } if !fallback { rootpg := mountPropagationMap[s.Linux.RootfsPropagation] if rootpg != mount.SHARED && rootpg != mount.RSHARED && rootpg != mount.SLAVE && rootpg != mount.RSLAVE { s.Linux.RootfsPropagation = mountPropagationReverseMap[mount.RSLAVE] } } } bindMode := "rbind" if m.NonRecursive { bindMode = "bind" } opts := []string{bindMode} if !m.Writable { opts = append(opts, "ro") } if pFlag != 0 { opts = append(opts, mountPropagationReverseMap[pFlag]) } // If we are using user namespaces, then we must make sure that we // don't drop any of the CL_UNPRIVILEGED "locked" flags of the source // "mount" when we bind-mount. The reason for this is that at the point // when runc sets up the root filesystem, it is already inside a user // namespace, and thus cannot change any flags that are locked. if daemon.configStore.RemappedRoot != "" { unprivOpts, err := getUnprivilegedMountFlags(m.Source) if err != nil { return err } opts = append(opts, unprivOpts...) } mt.Options = opts s.Mounts = append(s.Mounts, mt) } if s.Root.Readonly { for i, m := range s.Mounts { switch m.Destination { case "/proc", "/dev/pts", "/dev/shm", "/dev/mqueue", "/dev": continue } if _, ok := userMounts[m.Destination]; !ok { if !inSlice(m.Options, "ro") { s.Mounts[i].Options = append(s.Mounts[i].Options, "ro") } } } } if c.HostConfig.Privileged { // clear readonly for /sys for i := range s.Mounts { if s.Mounts[i].Destination == "/sys" { clearReadOnly(&s.Mounts[i]) } } s.Linux.ReadonlyPaths = nil s.Linux.MaskedPaths = nil } // TODO: until a kernel/mount solution exists for handling remount in a user namespace, // we must clear the readonly flag for the cgroups mount (@mrunalp concurs) if uidMap := daemon.idMapping.UIDs(); uidMap != nil || c.HostConfig.Privileged { for i, m := range s.Mounts { if m.Type == "cgroup" { clearReadOnly(&s.Mounts[i]) } } } return nil } func (daemon *Daemon) populateCommonSpec(s *specs.Spec, c *container.Container) error { if c.BaseFS == nil { return errors.New("populateCommonSpec: BaseFS of container " + c.ID + " is unexpectedly nil") } linkedEnv, err := daemon.setupLinkedContainers(c) if err != nil { return err } s.Root = &specs.Root{ Path: c.BaseFS.Path(), Readonly: c.HostConfig.ReadonlyRootfs, } if err := c.SetupWorkingDirectory(daemon.idMapping.RootPair()); err != nil { return err } cwd := c.Config.WorkingDir if len(cwd) == 0 { cwd = "/" } s.Process.Args = append([]string{c.Path}, c.Args...) // only add the custom init if it is specified and the container is running in its // own private pid namespace. It does not make sense to add if it is running in the // host namespace or another container's pid namespace where we already have an init if c.HostConfig.PidMode.IsPrivate() { if (c.HostConfig.Init != nil && *c.HostConfig.Init) || (c.HostConfig.Init == nil && daemon.configStore.Init) { s.Process.Args = append([]string{inContainerInitPath, "--", c.Path}, c.Args...) path := daemon.configStore.InitPath if path == "" { path, err = exec.LookPath(daemonconfig.DefaultInitBinary) if err != nil { return err } } s.Mounts = append(s.Mounts, specs.Mount{ Destination: inContainerInitPath, Type: "bind", Source: path, Options: []string{"bind", "ro"}, }) } } s.Process.Cwd = cwd s.Process.Env = c.CreateDaemonEnvironment(c.Config.Tty, linkedEnv) s.Process.Terminal = c.Config.Tty s.Hostname = c.Config.Hostname // There isn't a field in the OCI for the NIS domainname, but luckily there // is a sysctl which has an identical effect to setdomainname(2) so there's // no explicit need for runtime support. s.Linux.Sysctl = make(map[string]string) if c.Config.Domainname != "" { s.Linux.Sysctl["kernel.domainname"] = c.Config.Domainname } return nil } func (daemon *Daemon) createSpec(c *container.Container) (retSpec *specs.Spec, err error) { s := oci.DefaultSpec() if err := daemon.populateCommonSpec(&s, c); err != nil { return nil, err } var cgroupsPath string scopePrefix := "docker" parent := "/docker" useSystemd := UsingSystemd(daemon.configStore) if useSystemd { parent = "system.slice" } if c.HostConfig.CgroupParent != "" { parent = c.HostConfig.CgroupParent } else if daemon.configStore.CgroupParent != "" { parent = daemon.configStore.CgroupParent } if useSystemd { cgroupsPath = parent + ":" + scopePrefix + ":" + c.ID logrus.Debugf("createSpec: cgroupsPath: %s", cgroupsPath) } else { cgroupsPath = filepath.Join(parent, c.ID) } s.Linux.CgroupsPath = cgroupsPath if err := setResources(&s, c.HostConfig.Resources); err != nil { return nil, fmt.Errorf("linux runtime spec resources: %v", err) } // We merge the sysctls injected above with the HostConfig (latter takes // precedence for backwards-compatibility reasons). for k, v := range c.HostConfig.Sysctls { s.Linux.Sysctl[k] = v } p := s.Linux.CgroupsPath if useSystemd { initPath, err := cgroups.GetInitCgroup("cpu") if err != nil { return nil, err } _, err = cgroups.GetOwnCgroup("cpu") if err != nil { return nil, err } p = filepath.Join(initPath, s.Linux.CgroupsPath) } // Clean path to guard against things like ../../../BAD parentPath := filepath.Dir(p) if !filepath.IsAbs(parentPath) { parentPath = filepath.Clean("/" + parentPath) } if err := daemon.initCgroupsPath(parentPath); err != nil { return nil, fmt.Errorf("linux init cgroups path: %v", err) } if err := setDevices(&s, c); err != nil { return nil, fmt.Errorf("linux runtime spec devices: %v", err) } if err := daemon.setRlimits(&s, c); err != nil { return nil, fmt.Errorf("linux runtime spec rlimits: %v", err) } if err := setUser(&s, c); err != nil { return nil, fmt.Errorf("linux spec user: %v", err) } if err := setNamespaces(daemon, &s, c); err != nil { return nil, fmt.Errorf("linux spec namespaces: %v", err) } if err := setCapabilities(&s, c); err != nil { return nil, fmt.Errorf("linux spec capabilities: %v", err) } if err := setSeccomp(daemon, &s, c); err != nil { return nil, fmt.Errorf("linux seccomp: %v", err) } if err := daemon.setupContainerMountsRoot(c); err != nil { return nil, err } if err := daemon.setupIpcDirs(c); err != nil { return nil, err } defer func() { if err != nil { daemon.cleanupSecretDir(c) } }() if err := daemon.setupSecretDir(c); err != nil { return nil, err } ms, err := daemon.setupMounts(c) if err != nil { return nil, err } if !c.HostConfig.IpcMode.IsPrivate() && !c.HostConfig.IpcMode.IsEmpty() { ms = append(ms, c.IpcMounts()...) } tmpfsMounts, err := c.TmpfsMounts() if err != nil { return nil, err } ms = append(ms, tmpfsMounts...) secretMounts, err := c.SecretMounts() if err != nil { return nil, err } ms = append(ms, secretMounts...) sort.Sort(mounts(ms)) if err := setMounts(daemon, &s, c, ms); err != nil { return nil, fmt.Errorf("linux mounts: %v", err) } for _, ns := range s.Linux.Namespaces { if ns.Type == "network" && ns.Path == "" && !c.Config.NetworkDisabled { target := filepath.Join("/proc", strconv.Itoa(os.Getpid()), "exe") s.Hooks = &specs.Hooks{ Prestart: []specs.Hook{{ Path: target, Args: []string{"libnetwork-setkey", "-exec-root=" + daemon.configStore.GetExecRoot(), c.ID, daemon.netController.ID()}, }}, } } } if apparmor.IsEnabled() { var appArmorProfile string if c.AppArmorProfile != "" { appArmorProfile = c.AppArmorProfile } else if c.HostConfig.Privileged { appArmorProfile = "unconfined" } else { appArmorProfile = "docker-default" } if appArmorProfile == "docker-default" { // Unattended upgrades and other fun services can unload AppArmor // profiles inadvertently. Since we cannot store our profile in // /etc/apparmor.d, nor can we practically add other ways of // telling the system to keep our profile loaded, in order to make // sure that we keep the default profile enabled we dynamically // reload it if necessary. if err := ensureDefaultAppArmorProfile(); err != nil { return nil, err } } s.Process.ApparmorProfile = appArmorProfile } s.Process.SelinuxLabel = c.GetProcessLabel() s.Process.NoNewPrivileges = c.NoNewPrivileges s.Process.OOMScoreAdj = &c.HostConfig.OomScoreAdj s.Linux.MountLabel = c.MountLabel // Set the masked and readonly paths with regard to the host config options if they are set. if c.HostConfig.MaskedPaths != nil { s.Linux.MaskedPaths = c.HostConfig.MaskedPaths } if c.HostConfig.ReadonlyPaths != nil { s.Linux.ReadonlyPaths = c.HostConfig.ReadonlyPaths } return &s, nil } func clearReadOnly(m *specs.Mount) { var opt []string for _, o := range m.Options { if o != "ro" { opt = append(opt, o) } } m.Options = opt } // mergeUlimits merge the Ulimits from HostConfig with daemon defaults, and update HostConfig func (daemon *Daemon) mergeUlimits(c *containertypes.HostConfig) { ulimits := c.Ulimits // Merge ulimits with daemon defaults ulIdx := make(map[string]struct{}) for _, ul := range ulimits { ulIdx[ul.Name] = struct{}{} } for name, ul := range daemon.configStore.Ulimits { if _, exists := ulIdx[name]; !exists { ulimits = append(ulimits, ul) } } c.Ulimits = ulimits }
apache-2.0
hbeatty/incubator-trafficcontrol
traffic_portal/test/integration/PageObjects/PhysLocationsPage.po.ts
5036
/* * 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. */ import { by, element } from 'protractor' import { BasePage } from './BasePage.po'; import { SideNavigationPage } from './SideNavigationPage.po'; import { ParametersPage } from './ParametersPage.po'; export class PhysLocationsPage extends BasePage { private btnCreateNewPhysLocation = element(by.name('createPhysLocationButton')); private txtName = element(by.name('name')); private txtShortName = element(by.name('shortName')); private txtAddress = element(by.name('address')); private txtCity = element(by.name('city')); private txtState = element(by.name('state')); private txtZip = element(by.name('zip')); private txtPoc = element(by.name('poc')); private txtPhone = element(by.name('phone')); private txtEmail = element(by.name('email')); private txtRegion = element(by.name('region')); private txtComments = element(by.name('comments')); private txtSearch = element(by.id('physLocationsTable_filter')).element(by.css('label input')); private mnuPhysLocationsTable = element(by.id('physLocationsTable')); private btnDelete = element(by.buttonText('Delete')); private txtConfirmName = element(by.name('confirmWithNameInput')); private config = require('../config'); private randomize = this.config.randomize; async OpenPhysLocationPage() { let snp = new SideNavigationPage(); await snp.NavigateToPhysLocation(); } async OpenConfigureMenu() { let snp = new SideNavigationPage(); await snp.ClickTopologyMenu(); } async CreatePhysLocation(physlocation) { let result = false; let basePage = new BasePage(); let snp = new SideNavigationPage(); await snp.NavigateToPhysLocation(); await this.btnCreateNewPhysLocation.click(); await this.txtName.sendKeys(physlocation.Name + this.randomize); await this.txtShortName.sendKeys(physlocation.ShortName); await this.txtAddress.sendKeys(physlocation.Address); await this.txtCity.sendKeys(physlocation.City); await this.txtState.sendKeys(physlocation.State); await this.txtZip.sendKeys(physlocation.Zip); await this.txtPoc.sendKeys(physlocation.Poc); await this.txtPhone.sendKeys(physlocation.Phone); await this.txtEmail.sendKeys(physlocation.Email); await this.txtRegion.sendKeys(physlocation.Region + this.randomize); await this.txtComments.sendKeys(physlocation.Comments); await basePage.ClickCreate(); result = await basePage.GetOutputMessage().then(function (value) { if (physlocation.validationMessage == value) { return true; } else { return false; } }) return result; } async SearchPhysLocation(physlocationName) { let result = false; let snp = new SideNavigationPage(); let name = physlocationName + this.randomize; await snp.NavigateToPhysLocation(); await this.txtSearch.clear(); await this.txtSearch.sendKeys(name); await element.all(by.repeater('pl in ::physLocations')).filter(function (row) { return row.element(by.name('name')).getText().then(function (val) { return val === name; }); }).first().click(); } async UpdatePhysLocation(physlocation) { let result = false; let basePage = new BasePage(); switch (physlocation.description) { case "update physlocation region": await this.txtRegion.sendKeys(physlocation.Region + this.randomize); await basePage.ClickUpdate(); break; default: result = undefined; } if (result = !undefined) { result = await basePage.GetOutputMessage().then(function (value) { if (physlocation.validationMessage == value) { return true; } else { return false; } }) } return result; } async DeletePhysLocation(physlocation) { let result = false; let basePage = new BasePage(); await this.btnDelete.click(); await this.txtConfirmName.sendKeys(physlocation.Name + this.randomize); await basePage.ClickDeletePermanently(); result = await basePage.GetOutputMessage().then(function (value) { if (physlocation.validationMessage == value) { return true; } else { return false; } }) return result; } }
apache-2.0
qintengfei/ionic-site
_site/docs/1.0.0-rc.2/api/directive/onDragDown/index.html
28571
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="Ionic makes it incredibly easy to build beautiful and interactive mobile apps using HTML5 and AngularJS."> <meta name="keywords" content="html5,javascript,mobile,drifty,ionic,hybrid,phonegap,cordova,native,ios,android,angularjs"> <meta name="author" content="Drifty"> <meta property="og:image" content="http://ionicframework.com/img/ionic-logo-blog.png"/> <title>on-drag-down - Directive in module ionic - Ionic Framework</title> <link href="/css/site.css?12" rel="stylesheet"> <!--<script src="//cdn.optimizely.com/js/595530035.js"></script>--> <script type="text/javascript">var _sf_startpt=(new Date()).getTime()</script> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-44023830-1', 'ionicframework.com'); ga('send', 'pageview'); </script> <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> </head> <body class="docs docs-page docs-api"> <nav class="navbar navbar-default horizontal-gradient" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle button ionic" data-toggle="collapse" data-target=".navbar-ex1-collapse"> <i class="icon ion-navicon"></i> </button> <a class="navbar-brand" href="/"> <img src="/img/ionic-logo-white.svg" width="123" height="43" alt="Ionic Framework"> </a> <a href="http://blog.ionic.io/announcing-ionic-1-0/" target="_blank"> <img src="/img/ionic1-tag.png" alt="Ionic 1.0 is out!" width="28" height="32" style="margin-left: 140px; margin-top:22px; display:block"> </a> </div> <div class="collapse navbar-collapse navbar-ex1-collapse"> <ul class="nav navbar-nav navbar-right"> <li><a class="getting-started-nav nav-link" href="/getting-started/">Getting Started</a></li> <li><a class="docs-nav nav-link" href="/docs/">Docs</a></li> <li><a class="nav-link" href="http://ionic.io/support">Support</a></li> <li><a class="blog-nav nav-link" href="http://blog.ionic.io/">Blog <span id="blog-badge">1</span></a></li> <li><a class="nav-link" href="http://forum.ionicframework.com/">Forum</a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle nav-link " data-toggle="dropdown" role="button" aria-expanded="false">More <span class="caret"></span></a> <ul class="dropdown-menu" role="menu"> <div class="arrow-up"></div> <li><a class="products-nav nav-link" href="http://ionic.io/">Ionic.io</a></li> <li><a class="examples-nav nav-link" href="http://showcase.ionicframework.com/">Showcase</a></li> <li><a class="nav-link" href="http://jobs.ionic.io/">Job Board</a></li> <li><a class="nav-link" href="http://market.ionic.io/">Market</a></li> <li><a class="nav-link" href="http://ionicworldwide.herokuapp.com/">Ionic Worldwide</a></li> <li><a class="nav-link" href="http://play.ionic.io/">Playground</a></li> <li><a class="nav-link" href="http://creator.ionic.io/">Creator</a></li> <li><a class="nav-link" href="http://shop.ionic.io/">Shop</a></li> <!--<li><a class="nav-link" href="http://ngcordova.com/">ngCordova</a></li>--> </ul> </li> </ul> </div> </div> </nav> <div class="header horizontal-gradient"> <div class="container"> <h3>on-drag-down</h3> <h4>Directive in module ionic</h4> </div> <div class="news"> <div class="container"> <div class="row"> <div class="col-sm-8 news-col"> <div class="picker"> <select onchange="window.location.href=this.options[this.selectedIndex].value"> <option value="/docs/nightly/api/directive/onDragDown/" > nightly </option> <option value="/docs/api/directive/onDragDown/" > 1.1.0 (latest) </option> <option value="/docs/1.0.1/api/directive/onDragDown/" > 1.0.1 </option> <option value="/docs/1.0.0/api/directive/onDragDown/" > 1.0.0 </option> <option value="/docs/1.0.0-rc.5/api/directive/onDragDown/" > 1.0.0-rc.5 </option> <option value="/docs/1.0.0-rc.4/api/directive/onDragDown/" > 1.0.0-rc.4 </option> <option value="/docs/1.0.0-rc.3/api/directive/onDragDown/" > 1.0.0-rc.3 </option> <option value="/docs/1.0.0-rc.2/api/directive/onDragDown/" selected> 1.0.0-rc.2 </option> <option value="/docs/1.0.0-rc.1/api/directive/onDragDown/" > 1.0.0-rc.1 </option> <option value="/docs/1.0.0-rc.0/api/directive/onDragDown/" > 1.0.0-rc.0 </option> <option value="/docs/1.0.0-beta.14/api/directive/onDragDown/" > 1.0.0-beta.14 </option> <option value="/docs/1.0.0-beta.13/api/directive/onDragDown/" > 1.0.0-beta.13 </option> <option value="/docs/1.0.0-beta.12/api/directive/onDragDown/" > 1.0.0-beta.12 </option> <option value="/docs/1.0.0-beta.11/api/directive/onDragDown/" > 1.0.0-beta.11 </option> <option value="/docs/1.0.0-beta.10/api/directive/onDragDown/" > 1.0.0-beta.10 </option> </select> </div> </div> <div class="col-sm-4 search-col"> <div class="search-bar"> <span class="search-icon ionic"><i class="ion-ios7-search-strong"></i></span> <input type="search" id="search-input" value="Search"> </div> </div> </div> </div> </div> </div> <div id="search-results" class="search-results" style="display:none"> <div class="container"> <div class="search-section search-api"> <h4>JavaScript</h4> <ul id="results-api"></ul> </div> <div class="search-section search-css"> <h4>CSS</h4> <ul id="results-css"></ul> </div> <div class="search-section search-content"> <h4>Resources</h4> <ul id="results-content"></ul> </div> </div> </div> <div class="container content-container"> <div class="row"> <div class="col-md-2 col-sm-3 aside-menu"> <div> <ul class="nav left-menu"> <li class="menu-title"> <a href="/docs/overview/">Overview</a> </li> </ul> <ul class="nav left-menu"> <li class="menu-title"> <a href="/docs/components/">CSS</a> </li> </ul> <ul class="nav left-menu"> <li class="menu-title"> <a href="/docs/platform-customization/">Platform Customization</a> </li> </ul> <!-- Docs: JavaScript --> <ul class="nav left-menu active-menu"> <li class="menu-title"> <a href="/docs/api/"> JavaScript </a> </li> <!-- Action Sheet --> <li class="menu-section"> <a href="/docs/api/service/$ionicActionSheet/" class="api-section"> Action Sheet </a> <ul> <li> <a href="/docs/api/service/$ionicActionSheet/"> $ionicActionSheet </a> </li> </ul> </li> <!-- Backdrop --> <li class="menu-section"> <a href="/docs/api/service/$ionicBackdrop/" class="api-section"> Backdrop </a> <ul> <li> <a href="/docs/api/service/$ionicBackdrop/"> $ionicBackdrop </a> </li> </ul> </li> <!-- Content --> <li class="menu-section"> <a href="/docs/api/directive/ionContent/" class="api-section"> Content </a> <ul> <li> <a href="/docs/api/directive/ionContent/"> ion-content </a> </li> <li> <a href="/docs/api/directive/ionRefresher/"> ion-refresher </a> </li> <li> <a href="/docs/api/directive/ionPane/"> ion-pane </a> </li> </ul> </li> <!-- Form Inputs --> <li class="menu-section"> <a href="/docs/api/directive/ionCheckbox/" class="api-section"> Form Inputs </a> <ul> <li> <a href="/docs/api/directive/ionCheckbox/"> ion-checkbox </a> </li> <li> <a href="/docs/api/directive/ionRadio/"> ion-radio </a> </li> <li> <a href="/docs/api/directive/ionToggle/"> ion-toggle </a> </li> </ul> </li> <!-- Gesture and Events --> <li class="menu-section"> <a href="/docs/api/directive/onHold/" class="api-section"> Gestures and Events </a> <ul> <li> <a href="/docs/api/directive/onHold/"> on-hold </a> </li> <li> <a href="/docs/api/directive/onTap/"> on-tap </a> </li> <li> <a href="/docs/api/directive/onDoubleTap/"> on-double-tap </a> </li> <li> <a href="/docs/api/directive/onTouch/"> on-touch </a> </li> <li> <a href="/docs/api/directive/onRelease/"> on-release </a> </li> <li> <a href="/docs/api/directive/onDrag/"> on-drag </a> </li> <li> <a href="/docs/api/directive/onDragUp/"> on-drag-up </a> </li> <li> <a href="/docs/api/directive/onDragRight/"> on-drag-right </a> </li> <li> <a href="/docs/api/directive/onDragDown/"> on-drag-down </a> </li> <li> <a href="/docs/api/directive/onDragLeft/"> on-drag-left </a> </li> <li> <a href="/docs/api/directive/onSwipe/"> on-swipe </a> </li> <li> <a href="/docs/api/directive/onSwipeUp/"> on-swipe-up </a> </li> <li> <a href="/docs/api/directive/onSwipeRight/"> on-swipe-right </a> </li> <li> <a href="/docs/api/directive/onSwipeDown/"> on-swipe-down </a> </li> <li> <a href="/docs/api/directive/onSwipeLeft/"> on-swipe-left </a> </li> <li> <a href="/docs/api/service/$ionicGesture/"> $ionicGesture </a> </li> </ul> </li> <!-- Headers/Footers --> <li class="menu-section"> <a href="/docs/api/directive/ionHeaderBar/" class="api-section"> Headers/Footers </a> <ul> <li> <a href="/docs/api/directive/ionHeaderBar/"> ion-header-bar </a> </li> <li> <a href="/docs/api/directive/ionFooterBar/"> ion-footer-bar </a> </li> </ul> </li> <!-- Keyboard --> <li class="menu-section"> <a href="/docs/api/page/keyboard/" class="api-section"> Keyboard </a> <ul> <li> <a href="/docs/api/page/keyboard/"> Keyboard </a> </li> <li> <a href="/docs/api/directive/keyboardAttach/"> keyboard-attach </a> </li> </ul> </li> <!-- Lists --> <li class="menu-section"> <a href="/docs/api/directive/ionList/" class="api-section"> Lists </a> <ul> <li> <a href="/docs/api/directive/ionList/"> ion-list </a> </li> <li> <a href="/docs/api/directive/ionItem/"> ion-item </a> </li> <li> <a href="/docs/api/directive/ionDeleteButton/"> ion-delete-button </a> </li> <li> <a href="/docs/api/directive/ionReorderButton/"> ion-reorder-button </a> </li> <li> <a href="/docs/api/directive/ionOptionButton/"> ion-option-button </a> </li> <li> <a href="/docs/api/directive/collectionRepeat/"> collection-repeat </a> </li> <li> <a href="/docs/api/service/$ionicListDelegate/"> $ionicListDelegate </a> </li> </ul> </li> <!-- Loading --> <li class="menu-section"> <a href="/docs/api/service/$ionicLoading/" class="api-section"> Loading </a> <ul> <li> <a href="/docs/api/service/$ionicLoading/"> $ionicLoading </a> </li> </ul> <ul> <li> <a href="/docs/api/object/$ionicLoadingConfig/"> $ionicLoadingConfig </a> </li> </ul> </li> <!-- Modal --> <li class="menu-section"> <a href="/docs/api/service/$ionicModal/" class="api-section"> Modal </a> <ul> <li> <a href="/docs/api/service/$ionicModal/"> $ionicModal </a> </li> <li> <a href="/docs/api/controller/ionicModal/"> ionicModal </a> </li> </ul> </li> <!-- Navigation --> <li class="menu-section"> <a href="/docs/api/directive/ionNavView/" class="api-section"> Navigation </a> <ul> <li> <a href="/docs/api/directive/ionNavView/"> ion-nav-view </a> </li> <li> <a href="/docs/api/directive/ionView/"> ion-view </a> </li> <li> <a href="/docs/api/directive/ionNavBar/"> ion-nav-bar </a> </li> <li> <a href="/docs/api/directive/ionNavBackButton/"> ion-nav-back-button </a> </li> <li> <a href="/docs/api/directive/ionNavButtons/"> ion-nav-buttons </a> </li> <li> <a href="/docs/api/directive/ionNavTitle/"> ion-nav-title </a> </li> <li> <a href="/docs/api/directive/navTransition/"> nav-transition </a> </li> <li> <a href="/docs/api/directive/navDirection/"> nav-direction </a> </li> <li> <a href="/docs/api/service/$ionicNavBarDelegate/"> $ionicNavBarDelegate </a> </li> <li> <a href="/docs/api/service/$ionicHistory/"> $ionicHistory </a> </li> </ul> </li> <!-- Platform --> <li class="menu-section"> <a href="/docs/api/service/$ionicPlatform/" class="api-section"> Platform </a> <ul> <li> <a href="/docs/api/service/$ionicPlatform/"> $ionicPlatform </a> </li> </ul> </li> <!-- Popover --> <li class="menu-section"> <a href="/docs/api/service/$ionicPopover/" class="api-section"> Popover </a> <ul> <li> <a href="/docs/api/service/$ionicPopover/"> $ionicPopover </a> </li> <li> <a href="/docs/api/controller/ionicPopover/"> ionicPopover </a> </li> </ul> </li> <!-- Popup --> <li class="menu-section"> <a href="/docs/api/service/$ionicPopup/" class="api-section"> Popup </a> <ul> <li> <a href="/docs/api/service/$ionicPopup/"> $ionicPopup </a> </li> </ul> </li> <!-- Scroll --> <li class="menu-section"> <a href="/docs/api/directive/ionScroll/" class="api-section"> Scroll </a> <ul> <li> <a href="/docs/api/directive/ionScroll/"> ion-scroll </a> </li> <li> <a href="/docs/api/directive/ionInfiniteScroll/"> ion-infinite-scroll </a> </li> <li> <a href="/docs/api/service/$ionicScrollDelegate/"> $ionicScrollDelegate </a> </li> </ul> </li> <!-- Side Menus --> <li class="menu-section"> <a href="/docs/api/directive/ionSideMenus/" class="api-section"> Side Menus </a> <ul> <li> <a href="/docs/api/directive/ionSideMenus/"> ion-side-menus </a> </li> <li> <a href="/docs/api/directive/ionSideMenuContent/"> ion-side-menu-content </a> </li> <li> <a href="/docs/api/directive/ionSideMenu/"> ion-side-menu </a> </li> <li> <a href="/docs/api/directive/exposeAsideWhen/"> expose-aside-when </a> </li> <li> <a href="/docs/api/directive/menuToggle/"> menu-toggle </a> </li> <li> <a href="/docs/api/directive/menuClose/"> menu-close </a> </li> <li> <a href="/docs/api/service/$ionicSideMenuDelegate/"> $ionicSideMenuDelegate </a> </li> </ul> </li> <!-- Slide Box --> <li class="menu-section"> <a href="/docs/api/directive/ionSlideBox/" class="api-section"> Slide Box </a> <ul> <li> <a href="/docs/api/directive/ionSlideBox/"> ion-slide-box </a> </li> <li> <a href="/docs/api/directive/ionSlidePager/"> ion-slide-pager </a> </li> <li> <a href="/docs/api/directive/ionSlide/"> ion-slide </a> </li> <li> <a href="/docs/api/service/$ionicSlideBoxDelegate/"> $ionicSlideBoxDelegate </a> </li> </ul> </li> <!-- Spinner --> <li class="menu-section"> <a href="/docs/api/directive/ionSpinner/" class="api-section"> Spinner </a> <ul> <li> <a href="/docs/api/directive/ionSpinner/"> ion-spinner </a> </li> </ul> </li> <!-- Tabs --> <li class="menu-section"> <a href="/docs/api/directive/ionTabs/" class="api-section"> Tabs </a> <ul> <li> <a href="/docs/api/directive/ionTabs/"> ion-tabs </a> </li> <li> <a href="/docs/api/directive/ionTab/"> ion-tab </a> </li> <li> <a href="/docs/api/service/$ionicTabsDelegate/"> $ionicTabsDelegate </a> </li> </ul> </li> <!-- Tap --> <li class="menu-section"> <a href="/docs/api/page/tap/" class="api-section"> Tap &amp; Click </a> </li> <!-- Utility --> <li class="menu-section"> <a href="#" class="api-section"> Utility </a> <ul> <li> <a href="/docs/api/provider/$ionicConfigProvider/"> $ionicConfigProvider </a> </li> <li> <a href="/docs/api/utility/ionic.Platform/"> ionic.Platform </a> </li> <li> <a href="/docs/api/utility/ionic.DomUtil/"> ionic.DomUtil </a> </li> <li> <a href="/docs/api/utility/ionic.EventController/"> ionic.EventController </a> </li> <li> <a href="/docs/api/service/$ionicPosition/"> $ionicPosition </a> </li> </ul> </li> </ul> <ul class="nav left-menu"> <li class="menu-title"> <a href="/docs/cli/">CLI</a> </li> </ul> <ul class="nav left-menu"> <li class="menu-title"> <a href="http://learn.ionicframework.com/">Learn Ionic</a> </li> </ul> <ul class="nav left-menu"> <li class="menu-title"> <a href="/docs/guide/">Guide</a> </li> </ul> <ul class="nav left-menu"> <li class="menu-title"> <a href="/docs/ionic-cli-faq/">FAQ</a> </li> </ul> <ul class="nav left-menu"> <li class="menu-title"> <a href="/docs/getting-help/">Getting Help</a> </li> </ul> <ul class="nav left-menu"> <li class="menu-title"> <a href="/docs/concepts/">Ionic Concepts</a> </li> </ul> </div> </div> <div class="col-md-10 col-sm-9 main-content"> <div class="improve-docs"> <a href='http://github.com/driftyco/ionic/tree/master/js/angular/directive/gesture.js#L140'> View Source </a> &nbsp; <a href='http://github.com/driftyco/ionic/edit/master/js/angular/directive/gesture.js#L140'> Improve this doc </a> </div> <h1 class="api-title"> on-drag-down </h1> <p>Called when the element is dragged down.</p> <h2 id="usage">Usage</h2> <div class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt">&lt;button</span> <span class="na">on-drag-down=</span><span class="s">&quot;onDragDown()&quot;</span> <span class="na">class=</span><span class="s">&quot;button&quot;</span><span class="nt">&gt;</span>Test<span class="nt">&lt;/button&gt;</span> </code></pre></div> </div> </div> </div> <div class="pre-footer"> <div class="row ionic"> <div class="col-sm-6 col-a"> <h4> <a href="/getting-started/">Getting started <span class="icon ion-arrow-right-c"></span></a> </h4> <p> Learn more about how Ionic was built, why you should use it, and what's included. We'll cover the basics and help you get started from the ground up. </p> </div> <div class="col-sm-6 col-b"> <h4> <a href="/docs/">Documentation <span class="icon ion-arrow-right-c"></span></a> </h4> <p> What are you waiting for? Take a look and get coding! Our documentation covers all you need to know to get an app up and running in minutes. </p> </div> </div> </div> <footer class="footer"> <nav class="base-links"> <dl> <dt>Docs</dt> <dd><a href="http://ionicframework.com/docs/">Documentation</a></dd> <dd><a href="http://ionicframework.com/getting-started/">Getting Started</a></dd> <dd><a href="http://ionicframework.com/docs/overview/">Overview</a></dd> <dd><a href="http://ionicframework.com/docs/components/">Components</a></dd> <dd><a href="http://ionicframework.com/docs/api/">JavaScript</a></dd> <dd><a href="http://ionicframework.com/submit-issue/">Submit Issue</a></dd> </dl> <dl> <dt>Resources</dt> <dd><a href="http://learn.ionicframework.com/">Learn Ionic</a></dd> <dd><a href="http://ngcordova.com/">ngCordova</a></dd> <dd><a href="http://ionicons.com/">Ionicons</a></dd> <dd><a href="http://creator.ionic.io/">Creator</a></dd> <dd><a href="http://showcase.ionicframework.com/">Showcase</a></dd> <dd><a href="http://manning.com/wilken/?a_aid=ionicinactionben&a_bid=1f0a0e1d">The Ionic Book</a></dd> </dl> <dl> <dt>Contribute</dt> <dd><a href="http://forum.ionicframework.com/">Community Forum</a></dd> <dd><a href="http://webchat.freenode.net/?randomnick=1&amp;channels=%23ionic&amp;uio=d4">Ionic IRC</a></dd> <dd><a href="http://ionicframework.com/present-ionic/">Present Ionic</a></dd> <dd><a href="http://ionicframework.com/contribute/">Contribute</a></dd> <dd><a href="https://github.com/driftyco/ionic-learn/issues/new">Write for us</a></dd> <dd><a href="http://shop.ionic.io/">Ionic Shop</a></dd> </dl> <dl class="small-break"> <dt>About</dt> <dd><a href="http://blog.ionic.io/">Blog</a></dd> <dd><a href="http://ionic.io">Services</a></dd> <dd><a href="http://drifty.com">Company</a></dd> <dd><a href="https://s3.amazonaws.com/ionicframework.com/logo-pack.zip">Logo Pack</a></dd> <dd><a href="mailto:[email protected]">Contact</a></dd> <dd><a href="http://ionicframework.com/jobs/">Jobs</a></dd> </dl> <dl> <dt>Connect</dt> <dd><a href="https://twitter.com/IonicFramework">Twitter</a></dd> <dd><a href="https://github.com/driftyco/ionic">GitHub</a></dd> <dd><a href="https://www.facebook.com/ionicframework">Facebook</a></dd> <dd><a href="https://plus.google.com/b/112280728135675018538/+Ionicframework/posts">Google+</a></dd> <dd><a href="https://www.youtube.com/channel/UChYheBnVeCfhCmqZfCUdJQw">YouTube</a></dd> <dd><a href="https://twitter.com/ionitron">Ionitron</a></dd> </dl> </nav> <div class="newsletter row"> <div class="newsletter-container"> <div class="col-sm-7"> <div class="newsletter-text">Stay in the loop</div> <div class="sign-up">Sign up to receive emails for the latest updates, features, and news on the framework.</div> </div> <form action="http://codiqa.createsend.com/t/t/s/jytylh/" method="post" class="input-group col-sm-5"> <input id="fieldEmail" name="cm-jytylh-jytylh" class="form-control" type="email" placeholder="Email" required /> <span class="input-group-btn"> <button class="btn btn-default" type="submit">Subscribe</button> </span> </form> </div> </div> <div class="copy"> <div class="copy-container"> <p class="authors"> Code licensed under <a href="/docs/#license">MIT</a>. Docs under <a href="https://tldrlegal.com/license/apache-license-2.0-(apache-2.0)">Apache 2</a> <span>|</span> &copy; 2013-2015 <a href="http://drifty.com/">Drifty Co</a> </p> </div> </div> </footer> <script type="text/javascript"> var _sf_async_config = { uid: 54141, domain: 'ionicframework.com', useCanonical: true }; (function() { function loadChartbeat() { window._sf_endpt = (new Date()).getTime(); var e = document.createElement('script'); e.setAttribute('language', 'javascript'); e.setAttribute('type', 'text/javascript'); e.setAttribute('src','//static.chartbeat.com/js/chartbeat.js'); document.body.appendChild(e); }; var oldonload = window.onload; window.onload = (typeof window.onload != 'function') ? loadChartbeat : function() { oldonload(); loadChartbeat(); }; })(); </script> <script src="//netdna.bootstrapcdn.com/bootstrap/3.0.2/js/bootstrap.min.js"></script> <script src="/js/site.js?1"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/Cookies.js/0.4.0/cookies.min.js"></script> <script> $('.navbar .dropdown').on('show.bs.dropdown', function(e){ //$(this).find('.dropdown-menu').addClass('animated fadeInDown'); }); // ADD SLIDEUP ANIMATION TO DROPDOWN // $('.navbar .dropdown').on('hide.bs.dropdown', function(e){ //$(this).find('.dropdown-menu').first().stop(true, true).slideUp(200); //$(this).find('.dropdown-menu').removeClass('animated fadeInDown'); }); try { var d = new Date('2015-03-20 05:00:00 -0500'); var ts = d.getTime(); var cd = Cookies.get('_iondj'); if(cd) { cd = JSON.parse(atob(cd)); if(parseInt(cd.lp) < ts) { var bt = document.getElementById('blog-badge'); bt.style.display = 'block'; } cd.lp = ts; } else { var bt = document.getElementById('blog-badge'); bt.style.display = 'block'; cd = { lp: ts } } Cookies.set('_iondj', btoa(JSON.stringify(cd))); } catch(e) { } </script> <div id="fb-root"></div> <script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/all.js#xfbml=1"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));</script> </body> </html>
apache-2.0
thymol/thymol.js
src/main/java/org/thymoljs/thymol/test/json/JDEREGJsonCodec.java
533
package org.thymoljs.thymol.test.json; import com.cedarsoftware.util.io.JsonReader; import com.cedarsoftware.util.io.JsonWriter; public class JDEREGJsonCodec implements JSONCodec { // Using the most cool https://github.com/jdereg/json-io public JDEREGJsonCodec() { } @Override public String encode( Object source ) { String target = JsonWriter.objectToJson( source ); return target; } @Override public Object decode( String source ) { Object target = JsonReader.jsonToJava( source ); return target; } }
apache-2.0
GramozKrasniqi/HRMS
HRM/HR-Managment/Employee/List.aspx.cs
503
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Entities; namespace HRM.HR_Managment.Employee { public partial class List : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { GUIHelper.BindEnum2DropDownList(EmployeeStatusDropDownList, typeof(StatusEnum), true); } } } }
apache-2.0
loresoft/MongoDB.Messaging
Samples/QueueBrowser/App_Start/BundleConfig.cs
2337
using System.Web; using System.Web.Optimization; namespace QueueBrowser { public class BundleConfig { public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new StyleBundle("~/content/css") .Include( "~/Content/bootstrap.css", "~/Content/bootstrap-theme.css", "~/Content/angular-toastr.css", "~/Content/bootstrap-dialog.css", "~/Content/alert.css", "~/Content/badge.css", "~/Content/metric.css", "~/Content/site.css" ) ); bundles.Add(new ScriptBundle("~/bundles/modernizr") .Include( "~/Scripts/modernizr-{version}.js" ) ); bundles.Add(new ScriptBundle("~/bundles/scripts") .Include( "~/Scripts/jquery-{version}.js", /* angular */ "~/Scripts/angular.js", "~/Scripts/angular-animate.js", "~/Scripts/angular-messages.js", "~/Scripts/angular-route.js", "~/Scripts/angular-sanitize.js", /* bootstrap */ "~/Scripts/bootstrap.js", /* other */ "~/Scripts/lodash.js", "~/Scripts/jquery.signalR-{version}.js", "~/Scripts/angular-signalr-hub.js", "~/Scripts/moment.js", "~/Scripts/angular-moment.js", "~/Scripts/bootstrap-dialog.js", "~/Scripts/angular-toastr.tpls.js", "~/Scripts/angular-ui/ui-bootstrap-tpls.js" ) ); bundles.Add(new ScriptBundle("~/bundles/app") .Include("~/app/app.js") .IncludeDirectory("~/app/models/", "*.js") .IncludeDirectory("~/app/services/", "*.js") .IncludeDirectory("~/app/queue/", "*.js") .IncludeDirectory("~/app/logging/", "*.js") ); #if !DEBUG BundleTable.EnableOptimizations = true; #endif } } }
apache-2.0
rhoadster91/android-siesta
library/src/main/java/com/rhoadster91/android/siesta/api/capability/Puttable.java
837
/* * Copyright 2016 Girish Kamath * * 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 com.rhoadster91.android.siesta.api.capability; import com.rhoadster91.android.siesta.request.PutRequest; public interface Puttable<T> { PutRequest<T> newPutRequest(); boolean isPutSuccess(int responseCode, T response); }
apache-2.0
nimkar/jenkins-server
Dockerfile
197
FROM jenkins COPY executors.groovy /usr/share/jenkins/ref/init.groovy.d/executors.groovy COPY plugins.txt /usr/share/jenkins/plugins.txt RUN /usr/local/bin/plugins.sh /usr/share/jenkins/plugins.txt
apache-2.0
CenturyLinkCloud/clc-node-sdk
test/compute-services/servers/create-server-test.js
2709
var _ = require('underscore'); var vcr = require('nock-vcr-recorder-mocha'); var Sdk = require('./../../../lib/clc-sdk.js'); var compute = new Sdk('cloud_user', 'cloud_user_password').computeServices(); var assert = require('assert'); var ServerBuilder = require('./../server-builder.js'); vcr.describe('Create server operation [UNIT]', function () { var DataCenter = compute.DataCenter; var Server = compute.Server; var Group = compute.Group; var builder = new ServerBuilder(compute); it('Should create new server', function (done) { this.timeout(10000); builder.createCentOsVm({ customFields: [ { name: "Type", value: 0 } ] }) .then(builder.deleteServer(done)); }); it('Should create new hyperscale server with anti-affinity policy', function (done) { this.timeout(10000); builder.createCentOsVm({ description: "My hyperscale server", group: { dataCenter: DataCenter.CA_TORONTO_2, name: Group.DEFAULT }, template: { dataCenter: DataCenter.CA_TORONTO_2, operatingSystem: { family: compute.OsFamily.CENTOS, version: "6", architecture: compute.Machine.Architecture.X86_64 } }, machine: { cpu: 1, memoryGB: 1, disks: [ { size: 2 }, { path: "/data", size: 4 } ], antiAffinity: { nameContains: 'policy' } }, type: Server.HYPERSCALE }) .then(compute.servers().findSingle) .then(assertThatServerIsHyperscale) .then(assertThatAntiAffinityPolicyIsSpecified) .then(builder.deleteServer(done)); }); function assertThatServerIsHyperscale(server) { assert.equal(server.type, Server.HYPERSCALE); assert.equal(server.storageType, Server.StorageType.HYPERSCALE); return server; } function assertThatAntiAffinityPolicyIsSpecified(server) { return compute.policies().antiAffinity() .findSingle({ dataCenterId: server.locationId.toLowerCase(), nameContains: 'policy' }) .then(function(policy) { var serverLink = _.findWhere(policy.links, {rel: 'server', id: server.id}); assert(!_.isUndefined(serverLink)); return server; }); } });
apache-2.0
BeyondMinecraft/AbacusCommonsLib
src/main/java/net/minecraft/src/NetServerHandler.java
178
package net.minecraft.src; import net.minecraft.entity.player.EntityPlayer; /** * * @author Gregory */ public class NetServerHandler { public EntityPlayer playerEntity; }
apache-2.0
les69/calvin-base
calvin/runtime/south/plugins/io/sensors/rotary_encoder/platform/ky040_rotary_impl/rotary_encoder.py
3011
# -*- coding: utf-8 -*- # Copyright (c) 2016 Ericsson AB # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from calvin.runtime.south.plugins.io.sensors.rotary_encoder import base_rotary_encoder from calvin.runtime.south.plugins.async import async from calvin.runtime.south.plugins.io.gpio import gpiopin from calvin.utilities.calvinlogger import get_logger _log = get_logger(__name__) class RotaryEncoder(base_rotary_encoder.RotaryEncoderBase): """ KY040 Rotary Encoder """ def __init__(self, node, turn_callback, switch_callback): super(RotaryEncoder, self).__init__(node, turn_callback, switch_callback) self._running = False self._node = node self._turn_callback = turn_callback self._switch_callback = switch_callback config = self._node.attributes.get_private("/hardware/ky040_rotary_encoder") clk_pin = config.get('clk_pin', None) dt_pin = config.get('dt_pin', None) sw_pin = config.get('sw_pin', None) self._clk_pin = gpiopin.GPIOPin(self._knob, clk_pin, "i", "u") self._dt_pin = gpiopin.GPIOPin(None, dt_pin, "i", None) self._sw_pin = gpiopin.GPIOPin(self._switch, sw_pin, "i", "u") def start(self, frequency=0.5): try : self._clk_pin.detect_edge("f") self._sw_pin.detect_edge("f") self._running = True # gpio.add_event_detect(self.echo_pin, # gpio.FALLING, # callback=self._echo_callback) except Exception as e: _log.error("Could not setup event detect: %r" % (e, )) def cb_error(self, *args, **kwargs): _log.error("%r: %r" % (args, kwargs)) def _knob(self): if self._clk_pin.get_state(): if self._dt_pin.get_state() : async.call_from_thread(self._turn_callback, -1) else : async.call_from_thread(self._turn_callback, 1) def _switch(self): async.call_from_thread(self._switch_callback) def stop(self): if self._running : if self.retry and self.retry.iactive() : self.retry.cancel() try: self._sw_pin.stop_detect() self._dt_pin.stop_detect() self._clk_pin.stop_detect() except Exception as e: _log.warning("Could not remove event detect: %r" % (e,)) self._running = False
apache-2.0
willscott/zmap
scripts/check_manfile.py
493
#!/usr/env python import sys #let's parse strings in python! options = [] with open("src/zopt.ggo.in") as fd: for l in fd: if l.startswith("option "): option = l.split()[1].lstrip('"').rstrip('"') options.append(option) man = open('src/zmap.1.ronn').read() failures = False for option in options: if option not in man: failures = True sys.stderr.write("ZMap option missing from man file: %s\n" % option) if failures: sys.exit(1)
apache-2.0
Eeemil/scale.cloudpool
commons/src/test/java/com/elastisys/scale/cloudpool/commons/basepool/IsSetServiceStateAlert.java
1505
package com.elastisys.scale.cloudpool.commons.basepool; import static com.google.common.base.Objects.equal; import static java.lang.String.format; import org.hamcrest.Description; import org.hamcrest.Factory; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; import com.elastisys.scale.cloudpool.api.types.ServiceState; import com.elastisys.scale.cloudpool.commons.basepool.alerts.AlertTopics; import com.elastisys.scale.commons.net.alerter.Alert; public class IsSetServiceStateAlert extends TypeSafeMatcher<Alert> { private final String machineId; private final ServiceState serviceState; public IsSetServiceStateAlert(String machineId, ServiceState serviceState) { this.machineId = machineId; this.serviceState = serviceState; } @Override public boolean matchesSafely(Alert someAlert) { String messagePattern = format("Service state set to %s for machine %s", this.serviceState, this.machineId); return equal(AlertTopics.SERVICE_STATE.name(), someAlert.getTopic()) && someAlert.getMessage().contains(messagePattern); } @Override public void describeTo(Description description) { description.appendText(String.format("service state alert (%s, %s)", this.machineId, this.serviceState)); } @Factory public static <T> Matcher<Alert> isSetServiceStateAlert(String machineId, ServiceState serviceState) { return new IsSetServiceStateAlert(machineId, serviceState); } }
apache-2.0
mageddo/bookmark-notes
src/test/java/com/mageddo/config/DatabaseConfiguratorExtension.java
974
package com.mageddo.config; import org.junit.jupiter.api.extension.BeforeTestExecutionCallback; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.TestInstancePostProcessor; import org.junit.platform.commons.support.AnnotationSupport; import io.micronaut.test.annotation.MicronautTest; import static com.mageddo.config.ApplicationContextUtils.context; public class DatabaseConfiguratorExtension implements TestInstancePostProcessor, BeforeTestExecutionCallback { @Override public void postProcessTestInstance(Object o, ExtensionContext extensionContext) throws Exception { AnnotationSupport.findAnnotation(extensionContext.getRequiredTestClass(), MicronautTest.class); } @Override public void beforeTestExecution(ExtensionContext extensionContext) throws Exception { final DatabaseConfigurator databaseConfigurator = context().getBean(DatabaseConfigurator.class); databaseConfigurator.migrate(); } }
apache-2.0
ptphp/PyLib
src/webpy1/src/jjrspider/ganji.py
40700
#coding=UTF-8 ''' Created on 2011-7-6 @author: Administrator ''' from urlparse import urlparse import cookielib from pyquery.pyquery import PyQuery #@UnresolvedImport import re import datetime #@UnusedImport import urllib2 from lxml import etree #@UnresolvedImport from lxml.cssselect import CSSSelector #@UnresolvedImport import simplejson as js #@UnusedImport @UnresolvedImport from config import housetype, checkPath, makePath,fitment,toward,deposit import threading from BeautifulSoup import BeautifulSoup #@UnresolvedImport import time import gc from jjrlog import msglogger, LinkLog from common import postHost homepath="e:\\home\\spider\\" gc.enable() class LinkCrawl(object): def __init__(self,citycode="",kind="",upc="5",st="3"): cj = cookielib.MozillaCookieJar() self.br=urllib2.build_opener(urllib2.HTTPHandler(),urllib2.HTTPCookieProcessor(cj),urllib2.HTTPRedirectHandler()) self.header={ "User-Agent":'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; GTB6.6; .NET CLR 3.5.30729)', } self.upc=upc self.endtime=str(datetime.date.today() -datetime.timedelta(days=7)) self.clinks=[] self.pn=[] self.citycode=citycode self.baseUrl="http://%s.ganji.com"%self.citycode self.kind=kind if kind=="1":#出售 self.urlpath="/fang5/a1u2%s/" self.folder="sell\\" elif kind=="2":#出租 self.urlpath="/fang1/u2%s/" self.folder="rent\\" elif kind=="3":#求购 self.urlpath="/fang4/u2f0/a1%s/" self.folder="buy\\" elif kind=="4":#求租 self.urlpath="/fang2/u2f0/a1%s/" self.folder="req\\" def __getAllNeedLinks(self): cond=True idx=0 checkit="0" while cond: url=self.baseUrl+self.urlpath%("f"+str(idx*32)) #url="http://gz.ganji.com/fang2/u2f0/a1f768/" # print url try: req=urllib2.Request(url, None, self.header) p=self.br.open(req).read() except: continue else: check=PyQuery(p)("ul.pageLink li a.c").text() if check==None or check==checkit: cond=False break else: checkit=check links=PyQuery(p)("div.list dl") p=None # print len(links) for link in links: lk=self.baseUrl+PyQuery(link)(" a.list_title").attr("href") # print lk if self.kind=="3" or self.kind=="4": tm=PyQuery(link)("dd span.time").text() if re.match('''\d{2}-\d{2}''', tm): Y=int(time.strftime('%Y', time.localtime())) tm="%s-%s"%(Y,tm.strip()) if tm<self.endtime: cond=False break elif "分钟" in tm: pass elif "小时" in tm: pass else: cond=False break if not checkPath(homepath,self.folder,lk): LinkLog.info("%s|%s"%(self.kind,lk)) try: getContent(lk,self.citycode,self.kind,self.upc) except Exception,e:print "ganji getContent Exception %s"%e # fetch_quere.put({"mod":"ganji","link":lk,"citycode":self.citycode,"kind":self.kind}) # if lk not in self.clinks: # self.clinks.append(lk) idx=idx+1 # print len(self.clinks) def runme(self): #self.__initPageNum() self.__getAllNeedLinks() class ContentCrawl(object): def __init__(self,links,citycode,kind,upc): cj = cookielib.MozillaCookieJar() self.br=urllib2.build_opener(urllib2.HTTPHandler(),urllib2.HTTPCookieProcessor(cj),urllib2.HTTPRedirectHandler()) self.pdb={} self.header={ "User-Agent":'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; GTB6.6; .NET CLR 3.5.30729)', } self.urls=links self.kind=kind self.fd={} self.citycode=citycode self.upc=upc if kind=="1": self.folder="sell\\" elif kind=="2": self.folder="rent\\" elif kind=="3": self.folder="buy\\" else: self.folder="req\\" #js resgx self.xiaoqu_regex="xiaoqu : '(.*?)'," self.address_regex="address : '(.*?)'," self.house_room_regex="(\d+)室" self.house_hall_regex="(\d+)厅" self.house_toilet_regex="(\d+)卫" self.house_desc_regex="房屋概况</p>(.*?)</p>" self.house_floor_regex="<li>楼层: 第(\d+)层/总(\d+)层</li>" self.house_totalarea_regex="<li>面积: (\d+) ㎡</li>" self.house_totalarea_regex_qiu="(\d+)㎡" self.house_type_regex3="<li>户型: (.*)</li>" self.house_toward_regex="<li>朝向: (.*)</li>" self.house_type_regex="<li>类型: (.*)</li>" self.cityarea_regex="<li>区域:([\s\S]*?)</li>" self.house_age_regex="<li>房龄: (\d+) 年</li>" self.house_fitment_regex="<li>装修: (.*)</li>" self.house_support_regex="<li>配置: (.*) </li>" self.house_price_regex="<li>售价: <span>(.*)</span>.*</li>" self.house_price_regex_2="<li>租金: <span>(.*)</span>.*</li>" self.borough_name_regex="<li>小区:(.*)</li>" self.house_deposit_regex="<li>租金: (.*)</li>" self.house_price_regex_zu = "<li>期望租金: (.*)</li>" self.borough_name_regex_reg = "<li>期望小区: (.*)</li>" self.house_addr_regex_reg = "<li>小区地址:(.*)</li>" self.house_price_regex_gou = "<li>期望售价: (.*)</li>" def __addText(self,tag, no_tail=False): text = [] if tag.text: text.append(tag.text) for child in tag.getchildren(): text.append(self.__addText(child)) if not no_tail and tag.tail: text.append(tag.tail) return "".join(text) def getText(self,html): text=[] for tag in html: text.append(self.__addText(tag, no_tail=True)) return ' '.join([t.strip() for t in text if t.strip()]) def mayGetIt(self,page): try: href=PyQuery(page)("a.userHistory").attr("href") if href==None: return False href="http://%s.ganji.com%s"%(self.citycode,href) resp = urllib2.urlopen(urllib2.Request(href, None, self.header)).read() trs=PyQuery(resp)("table.tel_list tr") except: return True # print "user list-------->%s| %s"%((len(trs)-1),self.urls) if len(trs)-1>int(self.upc): return True else: return False def sell(self,url): request = urllib2.Request(url, None, self.header) response = urllib2.urlopen(request).read() if self.mayGetIt(response): self.fd={} return tree = etree.HTML(response) soup =BeautifulSoup(response) self.fd['house_flag'] = 1 self.fd['belong']=0 detail_mer = soup.find('div',{'class':'detail_mer'}) #非个人房源 return if u"个人房源" not in str(detail_mer):return Dname = detail_mer.find('span',{'class':'Dname'}) if Dname: self.fd['owner_name'] = Dname.string else: self.fd['owner_name'] = None ganji_phone_call_class = detail_mer.find('span',{'class':'ganji_phone_call_class'}) if ganji_phone_call_class: self.fd['owner_phone'] = ganji_phone_call_class.contents[0] if str(ganji_phone_call_class).find('src='): self.fd['owner_phone'] = 'http://'+urlparse(url)[1]+ganji_phone_call_class.img['src'] else: self.fd['owner_phone'] = None else: self.fd['owner_phone'] = None #没有联系方式 return if not self.fd['owner_phone']:return if re.search("<span class=\"city\"><a .*?>(.*?)</a>", response): cityname=re.search("<span class=\"city\"><a .*?>(.*?)</a>", response).group(1) self.fd['cityname'] = cityname else: return if re.search(self.house_floor_regex, response): house_floor=re.search(self.house_floor_regex, response).group(1) house_topfloor=re.search(self.house_floor_regex, response).group(2) self.fd['house_floor'] = house_floor self.fd['house_topfloor'] = house_topfloor else: self.fd['house_floor'] = None self.fd['house_topfloor'] = None if re.search(self.house_totalarea_regex, response): house_totalarea=re.search(self.house_totalarea_regex, response).group(1) self.fd['house_totalarea'] = house_totalarea else: self.fd['house_totalarea'] = None #类型 if re.search(self.house_type_regex, response): house_type=re.search(self.house_type_regex, response).group(1) self.fd['house_type'] = housetype(house_type) else: self.fd['house_type'] = None if re.search(self.house_price_regex, response): house_price=re.search(self.house_price_regex, response).group(1) if house_price=="面议": house_price="0" self.fd['house_price'] = house_price else: self.fd['house_price'] = None posttime=CSSSelector('span.pub_time')(tree)!=None and CSSSelector('span.pub_time')(tree)[0].text.strip() or None if posttime: Y=int(time.strftime('%Y', time.localtime())) M=int(posttime.split(' ')[0].split('-')[0]) D=int(posttime.split(' ')[0].split('-')[1]) s = datetime.datetime(Y,M,D,0,0) posttime=int(time.mktime(s.timetuple())) self.fd['posttime'] =posttime else: self.fd['posttime'] =None if re.search(self.house_room_regex, response): house_room=re.search(self.house_room_regex, response).group(1) self.fd['house_room'] = house_room else: self.fd['house_room'] = '0' if re.search(self.house_hall_regex, response): house_hall=re.search(self.house_hall_regex, response).group(1) self.fd['house_hall'] = house_hall else: self.fd['house_hall'] = '0' if re.search(self.house_toilet_regex, response): house_toilet=re.search(self.house_toilet_regex, response).group(1) self.fd['house_toilet'] = house_toilet else: self.fd['house_toilet'] = '0' house_title=CSSSelector("div.detail_title h1")(tree)[0] !=None and CSSSelector("div.detail_title h1")(tree)[0].text.strip() or None self.fd['house_title'] = house_title.replace("(求购)","").replace("(求租)","").replace("(出售)","") #描述 detail_box = soup.find('div',{'class':'detail_box'}) if detail_box: house_desc = str(detail_box('p')[1]) self.fd['house_desc'] = re.sub("<.*?>|\n|\r|\t|联系我时请说明是从赶集网上看到的","",house_desc) else: self.fd['house_desc'] = None d_i = soup.find('ul',{'class':'d_i'}) #小区名 #先处理JS if re.search(self.xiaoqu_regex, response): borough_name=re.search(self.xiaoqu_regex, response).group(1) self.fd['borough_name'] = borough_name if re.search(self.address_regex, response): house_addr=re.search(self.address_regex, response).group(1) self.fd['house_addr'] = house_addr else: if d_i.find(text="小区: "): borough_box = d_i.find(text="小区: ").parent borough_name = borough_box.find("a") if borough_name: self.fd['borough_name'] = borough_name.string else: self.fd['borough_name'] = None #地址 if borough_name and borough_name.nextSibling: house_addr = borough_name.nextSibling.string self.fd['house_addr'] = re.sub("\(|\)| ","",house_addr) else: self.fd['house_addr'] = None else: if re.search(self.borough_name_regex, response): borough_name=re.search(self.borough_name_regex, response).group(1) self.fd['borough_name'] = re.sub("\(.*\)| ","",borough_name) #区域 area_box = d_i.find(text="区域: ").parent area_a = area_box('a') if area_a and len(area_a)>1: self.fd['cityarea'] = area_a[0].string self.fd['section'] = area_a[1].string elif area_a and len(area_a)==1: self.fd['cityarea'] = area_a[0].string self.fd['section'] = None else: self.fd['cityarea'] = None self.fd['section'] = None if re.search(self.house_age_regex, response): house_age=re.search(self.house_age_regex, response).group(1) self.fd['house_age'] = house_age else: self.fd['house_age'] = None #朝向 if re.search(self.house_toward_regex, response): house_toward=re.search(self.house_toward_regex, response).group(1) self.fd['house_toward'] = toward(house_toward) else: self.fd['house_toward'] = None if re.search(self.house_fitment_regex, response): house_fitment=re.search(self.house_fitment_regex, response).group(1) self.fd['house_fitment'] = fitment(house_fitment) else: self.fd['house_fitment'] = 2 request = None response = None soup=None tree=None del tree del request del response del soup def buy(self,url): self.fd['city'] = self.citycode self.fd['house_flag'] = 3 # self.fd['belong']="1" request = urllib2.Request(url, None, self.header) response = urllib2.urlopen(request).read() if self.mayGetIt(response): self.fd={} return tree = etree.HTML(response) soup =BeautifulSoup(response) detail_mer = soup.find('div',{'class':'detail_mer'}) #非个人房源 return if u"个人房源" not in str(detail_mer):return Dname = detail_mer.find('span',{'class':'Dname'}) if Dname: self.fd['owner_name'] = Dname.string else: self.fd['owner_name'] = None ganji_phone_call_class = detail_mer.find('span',{'class':'ganji_phone_call_class'}) if ganji_phone_call_class: self.fd['owner_phone'] = ganji_phone_call_class.contents[0] if str(ganji_phone_call_class).find('src='): self.fd['owner_phone'] = 'http://'+urlparse(url)[1]+ganji_phone_call_class.img['src'] else: self.fd['owner_phone'] = None else: self.fd['owner_phone'] = None #没有联系方式 return if not self.fd['owner_phone']:return if re.search("<span class=\"city\"><a .*?>(.*?)</a>", response): cityname=re.search("<span class=\"city\"><a .*?>(.*?)</a>", response).group(1) self.fd['cityname'] = cityname else: return self.fd['house_floor'] = 0 self.fd['house_topfloor'] = 0 self.fd['house_type'] = 0 self.fd['house_age'] = 0 self.fd['house_toward'] = 0 self.fd['house_fitment'] = 0 if re.search(self.house_totalarea_regex_qiu, response): house_totalarea=re.search(self.house_totalarea_regex_qiu, response).group(1) self.fd['house_totalarea'] = house_totalarea self.fd['house_totalarea_max'] = house_totalarea self.fd['house_totalarea_min'] = house_totalarea else: self.fd['house_totalarea'] = 0 self.fd['house_totalarea_max'] = 0 self.fd['house_totalarea_min'] = 0 if re.search(self.house_price_regex_gou, response): house_price_zu = re.search(self.house_price_regex_gou, response).group(1) house_price_zu = house_price_zu.replace('万','') if house_price_zu.find("以上") != -1: self.fd['house_price_max'] = 0 self.fd['house_price_min'] = house_price_zu.replace('以上','') self.fd['house_price'] = self.fd['house_price_min'] elif house_price_zu.find("以下") != -1: self.fd['house_price_max'] = house_price_zu.replace('以下','') self.fd['house_price_min'] = 0 self.fd['house_price'] = self.fd['house_price_max'] elif house_price_zu.find("-") != -1: self.fd['house_price_max'] = house_price_zu.split('-')[1] self.fd['house_price_min'] = house_price_zu.split('-')[0] self.fd['house_price'] = house_price_zu.split('-')[1] else: self.fd['house_price_max'] = 0 self.fd['house_price_min'] = 0 self.fd['house_price'] = 0 else: self.fd['house_price_max'] = 0 self.fd['house_price_min'] = 0 self.fd['house_price'] = 0 posttime=CSSSelector('span.pub_time')(tree)!=None and CSSSelector('span.pub_time')(tree)[0].text.strip() or None if posttime: Y=int(time.strftime('%Y', time.localtime())) M=int(posttime.split(' ')[0].split('-')[0]) D=int(posttime.split(' ')[0].split('-')[1]) s = datetime.datetime(Y,M,D,0,0) posttime=int(time.mktime(s.timetuple())) self.fd['posttime'] =posttime else: self.fd['posttime'] =None if re.search(self.house_room_regex, response): house_room=re.search(self.house_room_regex, response).group(1) self.fd['house_room'] = house_room else: self.fd['house_room'] = '0' if re.search(self.house_hall_regex, response): house_hall=re.search(self.house_hall_regex, response).group(1) self.fd['house_hall'] = house_hall else: self.fd['house_hall'] = '0' if re.search(self.house_toilet_regex, response): house_toilet=re.search(self.house_toilet_regex, response).group(1) self.fd['house_toilet'] = house_toilet else: self.fd['house_toilet'] = '0' house_title=CSSSelector("div.detail_title h1")(tree)[0] !=None and CSSSelector("div.detail_title h1")(tree)[0].text.strip() or None self.fd['house_title'] = house_title #描述 detail_box = soup.find('div',{'class':'detail_box'}) if detail_box: house_desc = str(detail_box('p')[1]) self.fd['house_desc'] = re.sub("<.*?>|\n|\r|\t|联系我时请说明是从赶集网上看到的","",house_desc) else: self.fd['house_desc'] = None d_i = soup.find('ul',{'class':'d_i'}) #小区名 #先处理JS if re.search(self.xiaoqu_regex, response): borough_name=re.search(self.xiaoqu_regex, response).group(1) self.fd['borough_name'] = borough_name if re.search(self.address_regex, response): house_addr=re.search(self.address_regex, response).group(1) self.fd['house_addr'] = house_addr else: if d_i.find(text="小区: "): borough_box = d_i.find(text="小区: ").parent borough_name = borough_box.find("a") if borough_name: self.fd['borough_name'] = borough_name.string else: self.fd['borough_name'] = None else: if re.search(self.borough_name_regex_reg, response): borough_name=re.search(self.borough_name_regex_reg, response).group(1) self.fd['borough_name'] = borough_name if re.search(self.house_addr_regex_reg, response): house_addr=re.search(self.house_addr_regex_reg, response).group(1) self.fd['house_addr'] = house_addr else: self.fd['house_addr'] = '' #区域 area_box = d_i.find(text="区域: ").parent area_a = area_box('a') if area_a and len(area_a)>1: self.fd['cityarea'] = area_a[0].string self.fd['section'] = area_a[1].string elif area_a and len(area_a)==1: self.fd['cityarea'] = area_a[0].string self.fd['section'] = None else: self.fd['cityarea'] = None self.fd['section'] = None request = None response = None soup=None tree=None del tree del request del response del soup def rent(self,url): self.fd['city'] = urlparse(url)[1].replace('.ganji.com',"") request = urllib2.Request(url, None, self.header) response = urllib2.urlopen(request).read() if self.mayGetIt(response): self.fd={} return tree = etree.HTML(response) if re.search("<span class=\"city\"><a .*?>(.*?)</a>", response): cityname=re.search("<span class=\"city\"><a .*?>(.*?)</a>", response).group(1) self.fd['cityname'] = cityname else: return self.fd['house_flag'] = 2 self.fd['house_type'] = 0 self.fd['house_floor'] = "" self.fd['house_topfloor'] = "" soup =BeautifulSoup(response) detail_mer = soup.find('div',{'class':'detail_mer'}) #非个人房源 return if u"个人房源" not in str(detail_mer):return Dname = detail_mer.find('span',{'class':'Dname'}) if Dname: self.fd['owner_name'] = Dname.string else: self.fd['owner_name'] = None ganji_phone_call_class = detail_mer.find('span',{'class':'ganji_phone_call_class'}) if ganji_phone_call_class: self.fd['owner_phone'] = ganji_phone_call_class.contents[0] if str(ganji_phone_call_class).find('src='): self.fd['owner_phone'] = 'http://'+urlparse(url)[1]+ganji_phone_call_class.img['src'] else: self.fd['owner_phone'] = None else: self.fd['owner_phone'] = None #没有联系方式 return if not self.fd['owner_phone']:return if re.search(self.house_totalarea_regex, response): house_totalarea=re.search(self.house_totalarea_regex, response).group(1) self.fd['house_totalarea'] = house_totalarea else: self.fd['house_totalarea'] = None if re.search(self.house_price_regex_2, response): house_price=re.search(self.house_price_regex_2, response).group(1) if house_price=="面议": house_price="0" self.fd['house_price'] = house_price else: self.fd['house_price'] = None # house_price=tree.xpath("/html/body/div[2]/div/div/ul/li/span") and tree.xpath("/html/body/div[2]/div/div/ul/li/span")[0].text.strip() or None # v['house_price'] = house_price posttime=CSSSelector('span.pub_time')(tree)!=None and CSSSelector('span.pub_time')(tree)[0].text.strip() or None if posttime: Y=int(time.strftime('%Y', time.localtime())) M=int(posttime.split(' ')[0].split('-')[0]) D=int(posttime.split(' ')[0].split('-')[1]) s = datetime.datetime(Y,M,D,0,0) posttime=int(time.mktime(s.timetuple())) self.fd['posttime'] =posttime else: self.fd['posttime'] =None house_title=CSSSelector("div.detail_title h1")(tree)[0] !=None and CSSSelector("div.detail_title h1")(tree)[0].text.strip() or None self.fd['house_title'] = house_title.replace("(求购)","").replace("(求租)","").replace("(出售)","") if re.search(self.house_room_regex, response): house_room=re.search(self.house_room_regex, response).group(1) self.fd['house_room'] = house_room else: self.fd['house_room'] = '0' if re.search(self.house_hall_regex, response): house_hall=re.search(self.house_hall_regex, response).group(1) self.fd['house_hall'] = house_hall else: self.fd['house_hall'] = '0' if re.search(self.house_toilet_regex, response): house_toilet=re.search(self.house_toilet_regex, response).group(1) self.fd['house_toilet'] = house_toilet else: self.fd['house_toilet'] = '0' house_title=CSSSelector("div.detail_title h1")(tree)[0] !=None and CSSSelector("div.detail_title h1")(tree)[0].text.strip() or None self.fd['house_title'] = house_title.replace("(求购)","").replace("(求租)","").replace("(出售)","") #描述 detail_box = soup.find('div',{'class':'detail_box'}) if detail_box: house_desc = str(detail_box('p')[1]) self.fd['house_desc'] = re.sub("<.*?>|\n|\r|\t|联系我时请说明是从赶集网上看到的","",house_desc) else: self.fd['house_desc'] = None d_i = soup.find('ul',{'class':'d_i'}) #小区名 #先处理JS if re.search(self.xiaoqu_regex, response): borough_name=re.search(self.xiaoqu_regex, response).group(1) self.fd['borough_name'] = borough_name if re.search(self.address_regex, response): house_addr=re.search(self.address_regex, response).group(1) self.fd['house_addr'] = house_addr else: if d_i.find(text="小区: "): borough_box = d_i.find(text="小区: ").parent borough_name = borough_box.find("a") if borough_name: self.fd['borough_name'] = borough_name.string else: self.fd['borough_name'] = None #地址 if borough_name and borough_name.nextSibling: house_addr = borough_name.nextSibling.string self.fd['house_addr'] = re.sub("\(|\)| ","",house_addr) else: self.fd['house_addr'] = None else: if re.search(self.borough_name_regex, response): borough_name=re.search(self.borough_name_regex, response).group(1) self.fd['borough_name'] = re.sub("\(.*\)| ","",borough_name) #区域 area_box = d_i.find(text="区域: ").parent area_a = area_box('a') if area_a and len(area_a)>1: self.fd['cityarea'] = area_a[0].string self.fd['section'] = area_a[1].string elif area_a and len(area_a)==1: self.fd['cityarea'] = area_a[0].string self.fd['section'] = None else: self.fd['cityarea'] = None self.fd['section'] = None if re.search(self.house_age_regex, response): house_age=re.search(self.house_age_regex, response).group(1) self.fd['house_age'] = house_age else: self.fd['house_age'] = None #朝向 if re.search(self.house_toward_regex, response): house_toward=re.search(self.house_toward_regex, response).group(1) self.fd['house_toward'] = toward(house_toward) else: self.fd['house_toward'] = None if re.search(self.house_fitment_regex, response): house_fitment=re.search(self.house_fitment_regex, response).group(1) self.fd['house_fitment'] = fitment(house_fitment) else: self.fd['house_fitment'] = 2 if re.search(self.house_deposit_regex, response): house_deposit=re.search(self.house_deposit_regex, response).group(1) self.fd['house_deposit'] = deposit(house_deposit) else: self.fd['house_deposit'] = None request = None response = None soup=None tree=None del tree del request del response del soup def require(self,url): self.fd['city'] = urlparse(url)[1].replace('.ganji.com',"") request = urllib2.Request(url, None, self.header) response = urllib2.urlopen(request).read() if self.mayGetIt(response): self.fd={} return tree = etree.HTML(response) if re.search("<span class=\"city\"><a .*?>(.*?)</a>", response): cityname=re.search("<span class=\"city\"><a .*?>(.*?)</a>", response).group(1) self.fd['cityname'] = cityname else: return self.fd['house_flag'] = 4 self.fd['house_type'] = 0 self.fd['house_floor'] = "" self.fd['house_topfloor'] = "" self.fd['house_totalarea']=0 self.fd['house_age'] = 0 self.fd['house_toward'] = 0 self.fd['house_fitment'] = 0 self.fd['house_deposit'] = 0 self.fd['house_totalarea_max'] = 0 self.fd['house_totalarea_min'] = 0 self.fd['house_totalarea'] = 0 soup =BeautifulSoup(response) detail_mer = soup.find('div',{'class':'detail_mer'}) #非个人房源 return if u"个人房源" not in str(detail_mer):return Dname = detail_mer.find('span',{'class':'Dname'}) if Dname: self.fd['owner_name'] = Dname.string else: self.fd['owner_name'] = None ganji_phone_call_class = detail_mer.find('span',{'class':'ganji_phone_call_class'}) if ganji_phone_call_class: self.fd['owner_phone'] = ganji_phone_call_class.contents[0] if str(ganji_phone_call_class).find('src='): self.fd['owner_phone'] = 'http://'+urlparse(url)[1]+ganji_phone_call_class.img['src'] else: self.fd['owner_phone'] = None else: self.fd['owner_phone'] = None #没有联系方式 return if not self.fd['owner_phone']:return if re.search(self.house_price_regex_zu, response): house_price_zu = re.search(self.house_price_regex_zu, response).group(1) house_price_zu = house_price_zu.replace('元/月','') if house_price_zu.find("以上") != -1: self.fd['house_price_max'] = 0 self.fd['house_price_min'] = house_price_zu.replace('以上','') self.fd['house_price'] = house_price_zu.replace('以上','') elif house_price_zu.find("以下") != -1: self.fd['house_price_max'] = house_price_zu.replace('以下','') self.fd['house_price_min'] = 0 self.fd['house_price'] = house_price_zu.replace('以下','') elif house_price_zu.find("-") != -1: self.fd['house_price_max'] = house_price_zu.split('-')[1] self.fd['house_price_min'] = house_price_zu.split('-')[0] self.fd['house_price'] = house_price_zu.split('-')[1] else: self.fd['house_price_max'] = 0 self.fd['house_price_min'] = 0 self.fd['house_price'] = 0 else: self.fd['house_price_max'] = 0 self.fd['house_price_min'] = 0 self.fd['house_price'] = 0 posttime=CSSSelector('span.pub_time')(tree)!=None and CSSSelector('span.pub_time')(tree)[0].text.strip() or None if posttime: Y=int(time.strftime('%Y', time.localtime())) M=int(posttime.split(' ')[0].split('-')[0]) D=int(posttime.split(' ')[0].split('-')[1]) s = datetime.datetime(Y,M,D,0,0) posttime=int(time.mktime(s.timetuple())) self.fd['posttime'] =posttime else: self.fd['posttime'] =None house_title=CSSSelector("div.detail_title h1")(tree)[0] !=None and CSSSelector("div.detail_title h1")(tree)[0].text.strip() or None self.fd['house_title'] = house_title.replace("(求购)","").replace("(求租)","").replace("(出售)","") if re.search(self.house_room_regex, response): house_room=re.search(self.house_room_regex, response).group(1) self.fd['house_room'] = house_room else: self.fd['house_room'] = '0' if re.search(self.house_hall_regex, response): house_hall=re.search(self.house_hall_regex, response).group(1) self.fd['house_hall'] = house_hall else: self.fd['house_hall'] = '0' if re.search(self.house_toilet_regex, response): house_toilet=re.search(self.house_toilet_regex, response).group(1) self.fd['house_toilet'] = house_toilet else: self.fd['house_toilet'] = '0' house_title=CSSSelector("div.detail_title h1")(tree)[0] !=None and CSSSelector("div.detail_title h1")(tree)[0].text.strip() or None self.fd['house_title'] = house_title.replace("(求购)","").replace("(求租)","").replace("(出售)","") #描述 detail_box = soup.find('div',{'class':'detail_box'}) if detail_box: house_desc = str(detail_box('p')[1]) self.fd['house_desc'] = re.sub("<.*?>|\n|\r|\t|联系我时请说明是从赶集网上看到的","",house_desc) else: self.fd['house_desc'] = None d_i = soup.find('ul',{'class':'d_i'}) #小区名 #先处理JS if re.search(self.xiaoqu_regex, response): borough_name=re.search(self.xiaoqu_regex, response).group(1) self.fd['borough_name'] = borough_name if re.search(self.address_regex, response): house_addr=re.search(self.address_regex, response).group(1) self.fd['house_addr'] = house_addr else: if re.search(self.borough_name_regex_reg, response): borough_name=re.search(self.borough_name_regex_reg, response).group(1) self.fd['borough_name'] = borough_name if re.search(self.house_addr_regex_reg, response): house_addr=re.search(self.house_addr_regex_reg, response).group(1) self.fd['house_addr'] = house_addr else: self.fd['house_addr'] = '' #区域 area_box = d_i.find(text="区域: ").parent area_a = area_box('a') if area_a and len(area_a)>1: self.fd['cityarea'] = area_a[0].string self.fd['section'] = area_a[1].string elif area_a and len(area_a)==1: self.fd['cityarea'] = area_a[0].string self.fd['section'] = None else: self.fd['cityarea'] = None self.fd['section'] = None request = None response = None soup=None tree=None del tree del request del response del soup def extractDict(self): if checkPath(homepath,self.folder,self.urls): pass else: try: if self.kind=="1": self.sell(self.urls) elif self.kind=="2": self.rent(self.urls) elif self.kind=="3": self.buy(self.urls) else: self.require(self.urls) makePath(homepath,self.folder,self.urls) #超过七天 # if (time.time() -self.fd["posttime"]) > 7*24*36000:return except Exception,e: msglogger.info("%s 链接采集异常"%self.urls) # print "%s||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||"%self.urls self.fd["c"]="houseapi" self.fd["a"]="savehouse" self.fd["is_checked"] = 1 self.fd["web_flag"] = "gj" print "%s %s %s %s %s"%(("%s.soufun.com"% self.citycode),self.citycode, self.kind ,time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time())), self.urls) return self.fd if not self.fd["is_checked"]: for i in self.fd.items(): print i[0],i[1] print "*"*80 # if len(self.fd)==7 or len(self.fd)==17: # print "#####################################" # continue # req=urllib2.Request("http://site.jjr360.com/app.php", urllib.urlencode(self.fd)) # p=self.br.open(req).read().strip() # print p.decode('gbk') # print "*"*80 class fetchData(threading.Thread): def __init__(self,d): threading.Thread.__init__(self) self.d=d def run(self): lc=LinkCrawl(self.d["citycode"],self.d["kind"]) clinks=lc.runme() cc=ContentCrawl(clinks,self.d["citycode"],self.d["kind"]) cc.extractDict() class getLinksThread(threading.Thread): def __init__(self,d): threading.Thread.__init__(self) self.d=d def run(self): gc.enable() lc=LinkCrawl(self.d["citycode"],self.d["kind"]) lc.runme() del gc.garbage[:] def getLinks(d): lc=LinkCrawl(d["citycode"],d["kind"],d["st1"]) while True: lc.runme() del gc.garbage[:] time.sleep(int(d["st2"])) def getContent(clinks,citycode,kind,upc): # return cc=ContentCrawl(clinks,citycode,kind,upc) fd=cc.extractDict() res="" try: res=postHost(fd) except Exception,e: res=e print res msglogger.info("%s|%s|%s"%(clinks,res,fd)) del gc.garbage[:] if __name__=="__main__": # lc=LinkCrawl(citycode="su",kind="1") # lc.runme()# #url1 = "http://su.ganji.com/fang5/11071015_233901.htm" #url2 = "http://su.ganji.com/fang1/11071017_418972.htm" #url3 = "http://su.ganji.com/fang4/11062413_4152.htm" #url4 = "http://su.ganji.com/fang2/11070900_21214.htm" cc=ContentCrawl("http://su.ganji.com/fang2/11071417_21820.htm",citycode="su",kind="4") cc.extractDict() # while 1: # for i in range(1,5): # k = "%s" % str(i) # try: # lc=LinkCrawl(citycode="su",kind=k) # clinks=lc.runme() # cc=ContentCrawl(clinks,citycode="su",kind=k) # cc.extractDict() # except: # pass
apache-2.0
sdsxer/mmdiary
client/source/mmdiary/app/src/main/java/com/example/android/architecture/blueprints/todoapp/tasks/domain/model/Task.java
4578
/* * Copyright 2016, The Android Open Source Project * * 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 com.example.android.architecture.blueprints.todoapp.tasks.domain.model; import android.arch.persistence.room.ColumnInfo; import android.arch.persistence.room.Entity; import android.arch.persistence.room.Ignore; import android.arch.persistence.room.PrimaryKey; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.google.common.base.Objects; import com.google.common.base.Strings; import java.util.UUID; /** * Immutable model class for a Task. */ @Entity(tableName = "tasks") public final class Task { @PrimaryKey @NonNull @ColumnInfo(name = "entryid") private final String mId; @Nullable @ColumnInfo(name = "title") private final String mTitle; @Nullable @ColumnInfo(name = "description") private final String mDescription; @ColumnInfo(name = "completed") private final boolean mCompleted; /** * Use this constructor to create a new active Task. * * @param title title of the task * @param description description of the task */ @Ignore public Task(@Nullable String title, @Nullable String description) { this(title, description, UUID.randomUUID().toString(), false); } /** * Use this constructor to create an active Task if the Task already has an id (copy of another * Task). * * @param title title of the task * @param description description of the task * @param id id of the task */ @Ignore public Task(@Nullable String title, @Nullable String description, @NonNull String id) { this(title, description, id, false); } /** * Use this constructor to create a new completed Task. * * @param title title of the task * @param description description of the task * @param completed true if the task is completed, false if it's active */ @Ignore public Task(@Nullable String title, @Nullable String description, boolean completed) { this(title, description, UUID.randomUUID().toString(), completed); } /** * Use this constructor to specify a completed Task if the Task already has an id (copy of * another Task). * * @param title title of the task * @param description description of the task * @param id id of the task * @param completed true if the task is completed, false if it's active */ public Task(@Nullable String title, @Nullable String description, @NonNull String id, boolean completed) { mId = id; mTitle = title; mDescription = description; mCompleted = completed; } @NonNull public String getId() { return mId; } @Nullable public String getTitle() { return mTitle; } @Nullable public String getTitleForList() { if (!Strings.isNullOrEmpty(mTitle)) { return mTitle; } else { return mDescription; } } @Nullable public String getDescription() { return mDescription; } public boolean isCompleted() { return mCompleted; } public boolean isActive() { return !mCompleted; } public boolean isEmpty() { return Strings.isNullOrEmpty(mTitle) && Strings.isNullOrEmpty(mDescription); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Task task = (Task) o; return Objects.equal(mId, task.mId) && Objects.equal(mTitle, task.mTitle) && Objects.equal(mDescription, task.mDescription); } @Override public int hashCode() { return Objects.hashCode(mId, mTitle, mDescription); } @Override public String toString() { return "Task with title " + mTitle; } }
apache-2.0
JoelMarcey/buck
src/com/facebook/buck/core/artifact/DeclaredArtifact.java
1622
/* * Copyright (c) Facebook, Inc. and its affiliates. * * 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 com.facebook.buck.core.artifact; import com.facebook.buck.core.rules.analysis.action.ActionAnalysisDataKey; /** * Represents an {@link Artifact} that is just declared by a rule implemention, with no {@link * com.facebook.buck.core.rules.actions.Action}s attached to build it. * * <p>This is not intended to be used by users, but only by the build engine. */ public interface DeclaredArtifact extends Artifact { /** * Binds an corresponding {@link com.facebook.buck.core.rules.actions.Action} as represented by * the {@link ActionAnalysisDataKey} to this {@link Artifact}. * * @param key the {@link ActionAnalysisDataKey} to attach to this {@link Artifact} * @return the {@link BuildArtifact} of this instance after attaching the {@link * ActionAnalysisDataKey}. */ BuildArtifact materialize(ActionAnalysisDataKey key); /** Intended for framework use only, comparing order for {@link DeclaredArtifact} */ int compareDeclared(DeclaredArtifact artifact); }
apache-2.0